diff --git a/assets/dist_transformers/1.21.0-dev.20241109/transformers.js.map b/assets/dist_transformers/1.21.0-dev.20241109/transformers.js.map deleted file mode 100644 index 6c3e31a..0000000 --- a/assets/dist_transformers/1.21.0-dev.20241109/transformers.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transformers.js","mappings":";;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD;AACA;AACA;AACA,aAAa,QAAQ;AACrB,aAAa,WAAW;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,MAAM;AACN,MAAM;AACN,MAAM;AACN;AACA;AACA;AACA,KAAK;AACL,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C;AAC1C;AACA;AACA;AACA,gCAAgC,MAAM,OAAO,GAAG;AAChD;AACA,0CAA0C;AAC1C;AACA;AACA,uCAAuC;AACvC;AACA,4BAA4B,GAAG,oBAAoB,UAAU,gBAAgB,QAAQ,gBAAgB,UAAU,iBAAiB,QAAQ;AACxI;AACA,sCAAsC;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iEAAiE,QAAQ;AACzE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC,uEAAuE;AAC3G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yDAAyD,KAAK;AAC9D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,KAAK,EAAE,IAAI;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA,qDAAqD,KAAK;AAC1D;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uCAAuC,MAAM,IAAI,WAAW,MAAM,KAAK;AACvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wDAAwD,qBAAqB;AAC7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qDAAqD;AACrD;AACA,wDAAwD;AACxD;AACA;AACA;AACA;AACA,qDAAqD;AACrD;AACA,wDAAwD;AACxD;AACA;AACA;AACA;AACA,qDAAqD;AACrD;AACA,wDAAwD;AACxD;AACA;AACA,yDAAyD,qBAAqB;AAC9E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oFAAoF,mBAAmB;AACvG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qEAAqE,sBAAsB;AAC3F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,WAAW;AAC9D;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,UAAU;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA,sBAAsB,kCAAkC;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,cAAc;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB;AACxB,wBAAwB;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8DAA8D,SAAS;AACvE;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8DAA8D,aAAa;AAC3E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+DAA+D,aAAa;AAC5E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0DAA0D,KAAK;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa,QAAQ;AACrB,eAAe,aAAa;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC,KAAK;AAC9C;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+CAA+C,oBAAoB,YAAY,WAAW,MAAM,WAAW;AAC3G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qEAAqE,QAAQ,MAAM,OAAO;AAC1F;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4DAA4D,OAAO;AACnE;AACA,eAAe;AACf;AACA;AACA,0DAA0D,aAAa;AACvE;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2DAA2D,aAAa;AACxE;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA,4DAA4D,aAAa;AACzE;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2DAA2D,aAAa;AACxE;AACA;AACA,8CAA8C,aAAa,aAAa,aAAa;AACrF,MAAM;AACN;AACA;AACA,2CAA2C,mBAAmB;AAC9D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD,eAAe;AAChE;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe;AACf;AACA,cAAc;AACd;AACA;AACA;AACA;AACA,sDAAsD,WAAW;AACjE,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,WAAW;AAClE,QAAQ;AACR,gDAAgD,WAAW,aAAa,aAAa;AACrF;AACA;AACA,uCAAuC,iBAAiB;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uCAAuC,gBAAgB;AACvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,oBAAoB;AACvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2EAA2E,QAAQ;AACnF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,uEAAuE,cAAc;AACrF;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA,QAAQ;AACR,kFAAkF,cAAc;AAChG;AACA,MAAM;AACN;AACA,uEAAuE,cAAc;AACrF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN,mEAAmE,8BAA8B;AACjG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,iEAAiE,cAAc;AAC/E;AACA;AACA;AACA,oBAAoB,2BAA2B;AAC/C;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA,8DAA8D,aAAa;AAC3E;AACA;AACA;AACA,iCAAiC,wDAAwD;AACzF;AACA;AACA,0BAA0B,0BAA0B;AACpD;AACA,oEAAoE,sBAAsB;AAC1F;AACA;AACA;AACA;AACA,QAAQ;AACR,qDAAqD,kBAAkB;AACvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,kBAAkB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA;AACA;AACA;AACA;AACA,8DAA8D,iBAAiB;AAC/E;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ,sDAAsD,aAAa;AACnE;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gEAAgE,kBAAkB;AAClF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA,0DAA0D,MAAM;AAChE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,gBAAgB,EAAE,cAAc,gBAAgB,GAAG,EAAE,YAAY,SAAS,gBAAgB;AACtH,QAAQ;AACR;AACA,wBAAwB,IAAI,KAAK,wCAAwC;AACzE,6BAA6B,gBAAgB,EAAE,EAAE;AACjD,SAAS;AACT,0BAA0B,EAAE,eAAe,EAAE,aAAa,MAAM,EAAE,iBAAiB;AACnF;AACA;AACA;AACA,iDAAiD,WAAW;AAC5D;AACA;;AAEA;AACA;AACA;AACA;AACA,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAOE;;;;;;;;;;;;;;;;AChxDF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,iCAAiC,mBAAmB;AACpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4DAA4D,KAAK,mBAAmB,SAAS;AAC7F;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,qCAAqC;AACjE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uCAAuC,EAAE;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,uCAAuC;AACjE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4DAA4D,oBAAoB,OAAO,IAAI,MAAM,cAAc;AAC/G;AACA;AACA,iBAAiB,YAAY;AAC7B;AACA;AACA,mEAAmE,KAAK,sDAAsD,IAAI;AAClI;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;;;;;;;;;;;;;;;AC5IA;AACA;AACoD;AACpD;;;;;;;;;;;;;;;ACHA;AACA;AACuC;AACvC;AACO;AACP,YAAY;AACZ,aAAa;AACb,cAAc;AACd,gBAAgB,QAAQ,gDAAO,EAAE;AACjC;AACA;AACA;AACA;AACA;AACA,0DAA0D,MAAM;AAChE;AACA;AACA,KAAK;AACL;AACA;AACA,KAAK;AACL;AACA;AACA,yCAAyC,kBAAkB;AAC3D;;;;;;;;;;;;;;;ACxBA;AACA;AAC+C;AAC/C;AACA;AACA;AACO,YAAY,6CAAO;AAC1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC6B;AACJ;AACc;AACX;AACW;AACH;AACT;AACK;AACA;AACM;AACtC;;;;;;;;;;;;;;;;;AC3BA;AACA;AACwE;AACnC;AACyB;AACvD;AACP;AACA;AACA;AACA;AACA,QAAQ,2DAAgB;AACxB;AACA;AACA;AACA,4EAA4E,8CAAM;AAClF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,8CAAM;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wFAAwF,KAAK;AAC7F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,8CAAM;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,KAAK;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sCAAsC,8CAAM;AAC5C;AACA;AACA;AACA,2CAA2C,8CAAM;AACjD;AACA;AACA;AACA,QAAQ,yDAAc;AACtB;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,2DAAgB;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6EAA6E,kBAAkB;AAC/F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iFAAiF,+BAA+B;AAChH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yDAAyD,qFAAmC;AAC5F;AACA,QAAQ,yDAAc;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;ACrMA;AACA;AACuF;AACvF;AACO,yBAAyB,wEAAoB;AACpD;;;;;;;;;;;ACLA;AACA;AACU;AACV;;;;;;;;;;;ACHA;AACA;AACU;AACV;;;;;;;;;;;;;;;ACHA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe;AACf;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,YAAY;AACpC,4BAA4B,WAAW;AACvC,uFAAuF;AACvF,uFAAuF;AACvF,uFAAuF;AACvF;AACA;AACA,iFAAiF;AACjF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe;AACf;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,oBAAoB;AAC5C,qGAAqG;AACrG,qGAAqG;AACrG,qGAAqG;AACrG;AACA;AACA,6EAA6E;AAC7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;ACpMA;AACA;AACU;AACV;;;;;;;;;;;;;;;;;;;ACHA;AACA;AAC0C;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,gBAAgB;AAC5B,mCAAmC;AACnC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,YAAY;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,mDAAM;AAC7D,YAAY,mDAAM;AAClB;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,YAAY,mCAAmC;AAC/C;AACA;AACA,eAAe,mDAAM,GAAG,wEAAwE;AAChG;AACA;AACA;AACA;AACO;AACP,YAAY,oCAAoC;AAChD,eAAe,mDAAM,GAAG,yFAAyF;AACjH;AACA;AACA;AACA;AACO,2DAA2D,mDAAM,GAAG,2EAA2E;AACtJ;;;;;;;;;;;AChQA;AACA;AACU;AACV;;;;;;;;;;;;;;;;ACHA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;ACrDA;AACA;AACiF;AAC0C;AACmB;AACxE;AACtE;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA,QAAQ,6EAAe;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0DAA0D,+FAAqC;AAC/F;AACA,iEAAiE,KAAK;AACtE;AACA;AACA,wEAAwE,mCAAmC;AAC3G;AACA;AACA;AACA;AACA;AACA;AACA,iEAAiE,KAAK;AACtE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iEAAiE,KAAK;AACtE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iFAAiF,kBAAkB;AACnG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oFAAoF;AACpF;AACA;AACA;AACA;AACA;AACA,kDAAkD,+FAAqC;AACvF;AACA,wEAAwE,KAAK;AAC7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD,MAAM,gCAAgC,sBAAsB;AAC7G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mFAAmF,iBAAiB;AACpG;AACA;AACA;AACA;AACA,uCAAuC,+FAAqC;AAC5E;AACA,iFAAiF,iBAAiB;AAClG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,oEAAa;AAClC;AACA;AACA,6CAA6C,KAAK,+BAA+B,oBAAoB;AACrG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,wEAAe;AAC9B;AACA;AACA,eAAe,0EAAiB;AAChC;AACA;AACA,eAAe,4EAAmB;AAClC;AACA;AACA,eAAe,+EAAsB;AACrC;AACA;AACA;AACA;AACA,eAAe,2EAAe;AAC9B;AACA;AACA,eAAe,6EAAiB;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kEAAkE,kBAAkB;AACpF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,oEAAa;AAC5B;AACA;AACA;;;;;;;;;;;;;;;;AC1SA;AACA;AAC0C;AAC1C;AACA;AACA;AACA;AACA;AACO;AACP;AACA,oBAAoB,iBAAiB;AACrC;AACA;AACA,wCAAwC,EAAE,6BAA6B,IAAI;AAC3E;AACA;AACA,yCAAyC,EAAE,yCAAyC,IAAI;AACxF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,uBAAuB,mDAAM;AAC7B;AACA,uBAAuB,mDAAM;AAC7B;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,uBAAuB,mDAAM;AAC7B;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,uBAAuB,mDAAM;AAC7B;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,8DAA8D,iBAAiB;AAC/E;AACA;AACA;;;;;;;;;;;;;;;ACtDA;AACA;AACwD;AACxD;AACO,eAAe,mDAAU;AAChC;;;;;;;;;;;;;;;;;ACLA;AACA;AACoC;AACpC;AACA;AACA;AACO;AACP,eAAe,6CAAG,0BAA0B,6CAAG,eAAe,6CAAG;AACjE;AACA;AACA;AACA,yBAAyB,WAAW,SAAS,MAAM;AACnD;AACA;AACA;AACA;AACA,oBAAoB,kBAAkB;AACtC;AACA,gCAAgC,IAAI,IAAI,8BAA8B;AACtE;AACA,8BAA8B,SAAS;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,eAAe,6CAAG,0BAA0B,6CAAG,eAAe,6CAAG;AACjE;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,eAAe,6CAAG,0BAA0B,6CAAG,eAAe,6CAAG;AACjE;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;AChDA;AACA;AACwE;AACnC;AACrC;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yDAAyD,qFAAmC;AAC5F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4EAA4E,8CAAM;AAClF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,8CAAM;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wFAAwF,KAAK;AAC7F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,8CAAM;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,KAAK;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sCAAsC,8CAAM;AAC5C;AACA;AACA;AACA,2CAA2C,8CAAM;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6DAA6D;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;ACpNA;AACA;AACoF;AACpF;AACO,wBAAwB,sEAAmB;AAClD;;;;;;;;;;;;;;ACLA;AACA;AACA;AACA;AACO;AACP;;;;;;;;;;;;;;;;;;;;;;ACLA;AACA;AACA;AACA;AACA;AACA,6BAA6B,uCA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ACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;ACp0FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,MAAM;AAClB;AACA;AACA;AACA;AACA;;AAEsC;;AAEtC;AACA;AAC8C;;AAE9C;AACA;AACA;AACA;AACgD;;AAEJ;;AAE5C;AACA,aAAa,uEAAuE;AACpF;;AAEA,WAAW,0EAA0E;AACrF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,aAAa,kCAAkC;AAC/C,mBAAmB,kCAAkC;AACrD,mBAAmB,kCAAkC;AACrD,mBAAmB,kCAAkC;AACrD,CAAC;;AAED;AACA;AACA,UAAU;AACV;AACA;;AAEA,WAAW,0BAA0B;AACrC;AACA;AACA;;AAEA;AACA;AACA;;AAEA,EAAE,SAAS,yCAAI;AACf,WAAW,6CAAiB,IAAI,0NAAS;;AAEzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,EAAE;AACF,WAAW,gDAAQ;;AAEnB,QAAQ,yCAAI;AACZ;AACA;AACA;;AAEA,QAAQ,yCAAI;AACZ;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,WAAW,sDAAsD;AACjE,aAAa,0BAA0B;AACvC;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,4CAA4C,OAAO,uBAAuB,4BAA4B;AACtG;;;AAGA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;;AAEA;AACA;AACA,WAAW,YAAY;AACvB,WAAW,8DAA8D;AACzE,WAAW,QAAQ;AACnB,aAAa,0DAA0D,eAAe,GAAG;AACzF;AACO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,KAAK;AAChB,aAAa,SAAS;AACtB;AACO;AACP;AACA;;AAEA,WAAW,kCAAkC;AAC7C;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,wFAAwF,wCAAG,SAAS;;AAEpG;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,aAAa,SAAS;AACtB;AACO;AACP;AACA;AACA;;AAEA;AACA,wCAAG;;;;;;;;;;;;;;;;;;;;ACtNH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,aAAa;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEuC;AAGf;;AAExB;AACA,aAAa,4CAA4C;AACzD;;;AAGA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,mBAAmB;AAC9B,aAAa,iBAAiB;AAC9B;AACA;AACA,iBAAiB,2DAAY;AAC7B;;AAEA;AACA;AACA,WAAW,kBAAkB;AAC7B,aAAa,QAAQ;AACrB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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O;AACP;;AAEA,eAAe,aAAa;AAC5B;;AAEA,eAAe,SAAS;AACxB;;AAEA,eAAe,QAAQ;AACvB;;AAEA,eAAe,sBAAsB;AACrC;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,mBAAmB;AAClC,gBAAgB,OAAO;AACvB;AACA,iBAAiB,2BAA2B;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;AACV;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,eAAe,yCAAyC;AACxD;AACA;AACA;AACA;;AAEA;AACA;AACA,aAAa,QAAQ;AACrB,cAAc,yHAAyH;AACvI,cAAc,wBAAwB;AACtC;AACA;AACA,cAAc,yCAAyC;AACvD,cAAc,sCAAsC;AACpD,cAAc,iCAAiC;AAC/C;;;;;;;;;;;;;;;;;;;ACtXA;AACA;AACA;AACA;AACA;AACA,YAAY,MAAM;AAClB;AACA;AACA;AACA;AACA;AACA,YAAY,MAAM;AAClB;AACA;AACA;AACA;AACA;AACA,YAAY,MAAM;AAClB;AACA;AACA;AACA;AACA;;AAEoB;AACI;AACF;;AAEtB;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iCAAiC,+BAAE;AACnC,mCAAmC,iCAAI;;AAEvC;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,CAAC;;AAED;AACA;AACA,MAAM,yCAAY,CAAC,yCAAY,CAAC,8CAAiB;AACjD;;AAEA;AACA;AACA,MAAM,sCAAS;AACf;;AAEA;AACA;AACA;AACA,MAAM,sCAAS;AACf;;AAEA;AACA;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,eAAe,kDAAkD;AACjE;AACA,cAAc,SAAS;AACvB;AACA,cAAc,QAAQ;AACtB,cAAc,QAAQ;AACtB,cAAc,SAAS;AACvB;AACA,cAAc,QAAQ;AACtB,cAAc,SAAS;AACvB,cAAc,SAAS;AACvB,cAAc,SAAS;AACvB,cAAc,QAAQ;AACtB,cAAc,SAAS;AACvB,cAAc,QAAQ;AACtB;AACA;;AAEA,WAAW,yBAAyB;AAC7B;AACP;;AAEA;AACA;AACA;AACA;AACA,gBAAgB;AAChB,KAAK;;AAEL;AACA;AACA;AACA,0BAA0B,MAAM,UAAU,SAAS;;AAEnD;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;;AAGA;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;ACrJA;AACA;AACA;;AAEwC;;AAExC;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,uCAAuC;AACvC,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,+BAA+B,mDAAmD;AAClF,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,eAAe,2DAA2D;AAC1E;AACA;AACA,4BAA4B,oDAAI;AAChC;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC1XA;AACA;AACA;;AAE+C;AACH;;AAES;;AAErD;AACA;AACA;AACO,8BAA8B,uDAAQ;AAC7C;AACA;AACA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACO,2BAA2B,uDAAQ;AAC1C;AACA;AACA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACO,kCAAkC,uDAAQ;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,iBAAiB;AAChC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,mBAAmB;AAClC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,oBAAoB;AACtC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,kBAAkB,YAAY;AAC9B,kBAAkB,QAAQ;AAC1B,oBAAoB,QAAQ;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA,qDAAqD,cAAc;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,iBAAiB;AAChC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA,qDAAqD,cAAc;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,UAAU;AACzB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA,qDAAqD,cAAc;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,2EAA2E;AAC1F,eAAe,UAAU;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA,wBAAwB,sBAAsB;AAC9C,iDAAiD,cAAc;;AAE/D;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,qFAAqF;AACrF;AACA;AACA;;AAEA;AACA,iDAAiD;AACjD;AACA,kBAAkB,OAAO;AACzB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,6BAA6B,4DAAW;AACxC;AACA,2CAA2C,oDAAG;;AAE9C;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,uBAAuB;AACxC;AACA;AACA;;AAEA,kBAAkB,YAAY;AAC9B;AACA,wBAAwB,4CAA4C;AACpE;AACA,4BAA4B,+BAA+B;AAC3D;AACA;AACA;AACA;;AAEA,mBAAmB,uBAAuB;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,uBAAuB;AACtC,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA;;AAEA,UAAU;AACV;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA,wBAAwB,sBAAsB;AAC9C,iDAAiD,cAAc;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;;AAEA,wBAAwB,sBAAsB;AAC9C,iDAAiD,cAAc;AAC/D;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,iBAAiB;AAChC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA,qDAAqD,cAAc;;AAEnE;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,iBAAiB;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA;AACA,qDAAqD,cAAc;;AAEnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,iBAAiB;AAChC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA,wBAAwB,sBAAsB;AAC9C,iDAAiD,cAAc;AAC/D;AACA;AACA;AACA;;AAEA;AACA;AACA,gCAAgC,kEAAkE;;AAElG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+GAA+G,eAAe;AAC9H;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,gBAAgB,qBAAqB,kBAAkB;AACrF;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,wBAAwB,+BAA+B;AACvD;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,qCAAqC,YAAY;;AAEjD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA,6CAA6C,cAAc;AAC3D,wBAAwB,8BAA8B;AACtD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA,MAAM,IAAI;AACV;AACA;AACA,6EAA6E,MAAM;AACnF;AACA;AACA,yFAAyF,mBAAmB;AAC5G;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA,MAAM,IAAI;AACV;AACA;AACA,4EAA4E,MAAM;AAClF;;AAEA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;AC7sBA;AACA;AACA;;AAE+C;AACG;;AAKvB;AAC6C;;AAExE;AACA;AACA;AACO,4BAA4B,uDAAQ;AAC3C;AACA;AACA,eAAe,kBAAkB;AACjC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,gBAAgB,OAAO;AACvB,iBAAiB;AACjB;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB;AACjB;AACA;AACA;;AAEA,8BAA8B,cAAc;;AAE5C;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,wCAAwC;AACvD,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA,wBAAwB,0BAA0B;AAClD;AACA;;AAEA;AACA,wBAAwB,0BAA0B;AAClD;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;;AAEA;AACA;AACA,eAAe,kBAAkB;AACjC,iBAAiB,eAAe;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,UAAU;AACV;;AAEA,UAAU;AACV;AACA,iGAAiG,uCAAuC;AACxI;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,6BAA6B;AAC9C;AACA;AACA;AACA,uBAAuB,oDAAG;;AAE1B;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB;AACjB;AACA;AACA,oCAAoC;AACpC;AACA;AACA;;AAEA;AACA,6BAA6B,sDAAI;;AAEjC;AACA,8BAA8B,wDAAO,YAAY,cAAc;;AAE/D,4BAA4B,0CAA0C;AACtE;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;;AAGA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB;AACjB;AACA;AACA,oCAAoC;AACpC;AACA;AACA;;AAEA;AACA,6BAA6B,sDAAI;;AAEjC;AACA,8BAA8B,wDAAO,YAAY,cAAc;;AAE/D,4BAA4B,0CAA0C;AACtE;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;;;;;;;;;;;;;;;;;;;;AC1MA;AACA;AACA;;AAE+C;;AAE/C;AACA;;AAEA;AACA;AACA;AACO,+BAA+B,uDAAQ;AAC9C;AACA;AACA,eAAe,YAAY;AAC3B;AACA,eAAe,YAAY;AAC3B;AACA;AACA,iBAAiB,WAAW;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACO,mCAAmC,uDAAQ;AAClD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,kBAAkB;AACjC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,0DAA0D;AACzE;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,4BAA4B,oBAAoB;AAChD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA,eAAe,iBAAiB;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,YAAY;AAC3B,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;AC1JA;AACA;AACA;;AAE+C;AACI;AAClB;;AAE1B;AACP;AACA;AACA,eAAe,YAAY;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,qBAAqB,yCAAI;AACzB;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,gDAAgD;AAC/D;AACA;AACA;AACA;AACA;AACA,0BAA0B;AAC1B;AACA,MAAM,IAAI;AACV;AACA;AACA;AACA;AACA;AACA,+BAA+B;;AAE/B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,2BAA2B,2DAAW;AACtC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU,4BAA4B,+DAAe;AACrD;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB;AACA;AACA;AACA;AACA;AACA,qEAAqE,yCAAI;AACzE;AACA;AACA;A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;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;;AAEA,0BAA0B,2DAAY;;AAEtC;AACA;AACA,eAAe,SAAS,+BAA+B,KAAK;AAC5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,0CAAI;AAChB;AACA;AACA,wBAAwB,SAAS,EAAE,OAAO;AAC1C,4BAA4B,wBAAwB,GAAG,KAAK;AAC5D;AACA,+BAA+B,2DAAY;AAC3C,sBAAsB,YAAY;AAClC,SAAS;;AAET,MAAM;AACN;AACA;AACA;AACA,yCAAyC,2DAAY;AACrD,yBAAyB;AACzB;AACA;AACA,SAAS;AACT;;AAEA;AACA;AACA;;AAEA;AACA,uBAAuB,8DAAiB;AACxC;AACA,SAAS;AACT,+CAA+C,8DAAW;AAC1D;AACA,uBAAuB,kEAAkE;AACzF;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA,aAAa;AACb;;AAEA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,wBAAwB;AACnC,WAAW,iDAAiD;AAC5D,aAAa,8BAA8B;AAC3C;AACA;AACA;AACA;AACA;AACA,oBAAoB,0CAA0C;AAC9D,kCAAkC,yEAAsB;AACxD;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,wBAAwB;AACnC,WAAW,iDAAiD;AAC5D,aAAa,8BAA8B;AAC3C;AACA;AACA;AACA;AACA;AACA,iCAAiC,2DAAY;AAC7C;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,wBAAwB;AACrC,YAAY,OAAO;AACnB;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,oDAAM;AACtC;AACA;AACA;AACA;AACA;AACA;AACA,mCAAmC,8DAAW;AAC9C;AACA;AACA;AACA,wFAAwF,yBAAyB;AACjH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,gEAAgE,mBAAmB,IAAI,gBAAgB,4CAA4C,mBAAmB;AACtK;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,iBAAiB;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,yBAAyB;AAC9C;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA,6CAA6C,QAAQ;AACrD;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,oEAAoE,EAAE;AACtE;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA,YAAY,+DAAY;AACxB,4BAA4B,oDAAM;AAClC,UAAU;AACV;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA,WAAW,cAAc;AACzB,aAAa,QAAQ;AACrB,YAAY,OAAO;AACnB;AACA;AACA;AACA,yBAAyB,oDAAM;AAC/B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,mBAAmB,oDAAM;AACzB;AACA;AACA;AACA,MAAM;AACN;AACA,mBAAmB,oDAAM;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,SAAS;AACpB,aAAa,QAAQ;AACrB;AACA;AACA;AACA,eAAe,oDAAM;AACrB;;AAEA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,0BAA0B;AACvC;AACA;AACA;AACA,UAAU,yEAAyE;AACnF;AACA;AACA,+BAA+B,oDAAI;AACnC;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;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AACA;AACA;AACA;;AAEA,2BAA2B,oDAAM;AACjC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,gBAAgB,4BAA4B;;AAE5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,8CAA8C,sDAAI;AAClD;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACO,8BAA8B,uDAAQ;AAC7C;AACA;AACA;AACA;AACA,eAAe,yCAAyC;AACxD,eAAe,qBAAqB;AACpC,eAAe,wBAAwB;AACvC;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,mBAAmB,6CAA6C;AAChE;AACA;;AAEA;AACA;AACA,gBAAgB,oBAAoB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA,eAAe,iDAAiD;AAChE;AACA,iBAAiB,0BAA0B;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B;AAC5B,MAAM,IAAI;;AAEV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA,wCAAwC,mDAAU;;AAElD;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA,iBAAiB;AACjB;;AAEA,UAAU;AACV;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA,iBAAiB;AACjB;;AAEA,UAAU;AACV;AACA;AACA;AACA;AACA,iBAAiB;AACjB;;AAEA,UAAU;AACV;AACA;AACA;AACA;AACA,iBAAiB;AACjB;;AAEA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;;AAEA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA,iBAAiB;AACjB;;AAEA,UAAU,OAAO;AACjB;AACA,gDAAgD,gCAAgC,yEAAyE,iEAAgB,CAAC;AAC1K;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,iBAAiB;AAClC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,iBAAiB;AAClC,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,uBAAuB;AACxC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,kBAAkB;AACjC,iBAAiB,qBAAqB;AACtC;AACA;;AAEA;AACA,4BAA4B,8EAAmB;;AAE/C;AACA,6BAA6B,kFAAuB;AACpD;AACA;AACA;AACA,6BAA6B,2EAAgB;AAC7C;AACA;AACA;AACA,6BAA6B,2EAAgB;AAC7C;;AAEA;AACA;;AAEA;AACA,eAAe,kBAAkB;AACjC,eAAe,QAAQ;AACvB,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,8EAAmB;;AAElD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,gCAAgC,2FAAgC;AAChE;;AAEA;AACA,gCAAgC,uFAA4B;AAC5D;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;;AAEA;AACA,gCAAgC,oFAAyB;AACzD;;AAEA;AACA,gCAAgC,mFAAwB;AACxD;;AAEA;AACA,gCAAgC,4FAAiC;AACjE;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA,gCAAgC,wFAA6B;AAC7D;;AAEA;AACA,gCAAgC,wFAA6B;AAC7D;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,gCAAgC,+FAAoC;AACpE;;AAEA;AACA;AACA;AACA;;;AAGA;AACA;AACA,gCAAgC,gGAAqC;AACrE;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,eAAe,uBAAuB;AACtC,eAAe,QAAQ;AACvB,iBAAiB,kBAAkB;AACnC;AACA,gEAAgE,gFAAgB;AAChF;AACA;AACA,yBAAyB;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA,8DAA8D;;AAE9D;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,sCAAsC,oDAAI;AAC1C;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,kBAAkB;AACjC,eAAe,sBAAsB;AACrC;AACA;AACA,6BAA6B,mFAAoB;;AAEjD;AACA,8BAA8B,gFAAiB;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,+EAAgB;AAC9C;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,2DAA2D,UAAU;AACrE;AACA,4EAA4E,4CAA4C;AACxH;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,eAAe,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ACjI;AACA;AACA;AACA,cAAc;AACd;AACA;AACA,iBAAiB;AACjB;AACA,UAAU;AACV;AACA;AACA;AACA,aAAa;AACb;;AAEA;AACA,iDAAiD,2DAAS;;AAE1D,iBAAiB;AACjB;;AAEA;AACA;AACA,eAAe,mEAAmE;AAClF,iBAAiB,6BAA6B;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,KAAK;AACL;;AAEA;AACA;;AAEA;AACA,cAAc,gDAAgD;AAC9D;AACA;AACA,SAAS;;AAET;;AAEA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,eAAe,0BAA0B;AACzC;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,UAAU;AACV;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,sBAAsB,UAAU;AAChC;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA,wBAAwB,yEAAa;;AAErC;AACA;AACA,mBAAmB,YAAY;AAC/B;AACA;AACA;AACA;AACA,wDAAwD,mBAAmB;;AAE3E;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA,uBAAuB,YAAY;AACnC;AACA,uCAAuC;AACvC;AACA,oCAAoC,2CAA2C;AAC/E;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,aAAa;AACb;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,8BAA8B,oDAAM;;AAEpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,OAAO;AACzB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,kBAAkB,8BAA8B;AAChD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;;AAEA,2BAA2B,8DAAiB;;AAE5C;AACA,yCAAyC,oDAAM;AAC/C;AACA;AACA;;AAEA,yBAAyB,cAAc;AACvC,8BAA8B;AAC9B,8EAA8E,cAAc;AAC5F;AACA;AACA;AACA,wFAAwF,iBAAiB;AACzG;AACA;AACA;AACA;AACA;;AAEA,wBAAwB,WAAW;AACnC,6BAA6B;AAC7B,kEAAkE,WAAW;AAC7E;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,kBAAkB,4DAA4D;AAC9E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACA;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;AACA;AACP;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;AACA;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;AACA;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;AACA;AACA;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;AACA;AACA;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;;AAEP;AACA;AACA;AACO;AACP;;;AAGA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;;;AAGA;AACA;AACO;;AAEA;;AAEP;AACA;AACA;AACO;AACP;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;;AAGO;AACP;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;;;AAGA;AACA;AACO;AACA;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;AACA;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACO;AACP;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;;;AAGP;AACA;AACA;AACO;;AAEP;AACA,0BAA0B,yBAAyB,gEAAgE,2FAAuB;AAC1I;;AAEA;AACA;AACA,eAAe,yBAAyB;AACxC;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,kCAAkC,4FAAwB;AAC1D,wCAAwC,cAAc;AACtD;;AAEA;AACA;AACA;;AAEA,UAAU;AACV;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,eAAe,sFAAsF;AACrG,iBAAiB,6BAA6B;AAC9C;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,KAAK;AACL;;AAEA;;AAEA;AACA,qCAAqC,8EAAmB;AACxD;AACA,oBAAoB,0FAA+B;AACnD;AACA;;AAEA;AACA,qCAAqC,8EAAmB;AACxD;AACA,oBAAoB,+FAAoC;AACxD;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,8CAA8C,oCAAoC;AAClF;AACA,sBAAsB,qDAAG;AACzB;;AAEA,wBAAwB,uDAAK;AAC7B;AACA,+CAA+C,GAAG,gDAAgD,wBAAwB;AAC1H;AACA;AACA;AACA;AACA,SAAS;;AAET,sCAAsC,0DAAQ;;AAE9C;AACA,iDAAiD;;AAEjD,wBAAwB,6BAA6B;AACrD,gDAAgD;;AAEhD,4BAA4B,qBAAqB;AACjD,4CAA4C;;AAE5C,yDAAyD;AACzD,qEAAqE;;AAErE,gCAAgC,qBAAqB;;AAErD,uDAAuD;AACvD,oCAAoC,wBAAwB;AAC5D;AACA;;AAEA;AACA,oCAAoC,8DAAY;AAChD;AACA;AACA;;AAEA;AACA,iCAAiC,sDAAI;;AAErC;;AAEA,+BAA+B,oDAAM;AACrC;AACA;AACA;AACA;;AAEA;AACA,gCAAgC,gCAAgC;AAChE;AACA;AACA;AACA,iDAAiD,sEAAoB;;AAErE,uCAAuC,iCAAiC;AACxE,0BAA0B,2DAAW,4BAA4B;;AAEjE;AACA,4BAA4B,kBAAkB;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,wBAAwB,yBAAyB;AACjD;;AAEA;AACA;AACA;AACA;AACA,gBAAgB,qDAAG;AACnB;AACA;AACA;AACA;AACA;;AAEA;AACA,gBAAgB,qDAAG;AACnB;AACA,oBAAoB,sDAAI;AACxB;AACA;AACA;AACA;;AAEA;AACA,2BAA2B,uDAAK;AAChC,4BAA4B,uDAAK;AACjC;AACA;AACA;AACA;;AAEO,mFAAmF;;AAEnF;AACP;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;;AAEP;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA,2BAA2B,qDAAG;AAC9B;AACA;AACA;AACA,4BAA4B,qDAAG;AAC/B,gBAAgB,sDAAI;AACpB;AACA;AACA;AACA;;AAEA,mCAAmC,wDAAwD;AAC3F;AACA;AACA;;AAEA;AACA;AACA;AACA,qDAAqD,WAAW;AAChE;AACA;AACA,uDAAuD,cAAc;AACrE;;AAEA;AACA;AACA,eAAe,gCAAgC;AAC/C;AACA;AACA;AACA;AACA,aAAa;AACb,UAAU;AACV;AACA;;AAEA,iBAAiB;AACjB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA,eAAe,gCAAgC,sCAAsC,wDAAwD;AAC7I;;AAEA;AACA;AACA,kBAAkB,oBAAoB,+BAA+B,+BAA+B;AACpG;AACA;;AAEA;AACA;AACA;AACA;AACA,6DAA6D,8BAA8B;AAC3F;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,oDAAoD;AAChE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,iCAAiC;AACzE;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,iCAAiC;AAC/D;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP,eAAe,iCAAiC;AAChD,4EAA4E;AAC5E;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,6CAA6C;AACzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,iCAAiC;AACzE;AACA;AACA,WAAW,cAAc;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,eAAe,iCAAiC;AAChD,4EAA4E;AAC5E;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP,eAAe,iCAAiC;AAChD,4EAA4E;AAC5E;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,wDAAwD;AACpE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,eAAe;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,eAAe,iCAAiC;AAChD,4EAA4E;AAC5E;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,sDAAsD;AAClE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,yCAAyC;AACnF;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,iCAAiC;AACjE;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,iCAAiC;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,yCAAyC;AACnF;AACA;AACA,WAAW,gBAAgB;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP,eAAe,iCAAiC;AAChD,4EAA4E;AAC5E;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,4CAA4C;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,gBAAgB;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,eAAe,iCAAiC;AAChD,4EAA4E;AAC5E;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEA;AACP;;;AAGA;AACA;AACO;;AAEA;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,sEAAsE;AAClF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,iCAAiC;AAC3E;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,SAAS,gBAAgB,iCAAiC;AACrE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,mBAAmB;AACtC;AACA,4BAA4B,EAAE;AAC9B;AACA;AACA;AACO;AACP;;;AAGA;AACA;AACO;;AAEA;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;;;AAGA;AACA;AACO;AACA;;AAEA;AACP;;AAEA;AACA;AACO;AACA;;AAEA;AACP;;;AAGA;AACA;AACO;;AAEA;;AAEA;AACP;;;AAGA;AACA;AACO;;AAEA;;AAEA;AACP;;AAEA;AACA;AACO;AACP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;;;AAGA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACO;;AAEA;AACP;;;AAGA;AACA;AACO;AACA;AACA;AACP;;;AAGA;AACA;;AAEA;AACA;AACA;AACO;AACA;;AAEA;AACP;;AAEA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACO;;AAEA;AACP;;AAEA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACO;;AAEA;AACP;;AAEA;AACO;AACA;;AAEA;;;AAGP;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACO;;AAEA;AACP;;;AAGA;AACA;AACO;AACP;AACA;AACA;AACO;;AAEA;AACP;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEA;AACP;;;AAGA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;;AAEA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;AACA;AACP;;;AAGA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;AACA;AACP;;;AAGA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA,YAAY,mDAAmD;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,SAAS;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,cAAc;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACO;AACA;AACA;AACP;;AAEA;AACO;AACA;AACA;AACP;;AAEA;AACA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,iCAAiC;AAClD;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA,kBAAkB,oBAAoB;AACtC;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,kBAAkB,gCAAgC;AAClD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA,kBAAkB,oBAAoB;AACtC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;;AAEP;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACO;AACP;;;AAGA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,0DAA0D;AACtE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;;AAEA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA,YAAY,mEAAmE;AAC/E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,kBAAkB;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;;AAEA;AACO;;AAEP;AACA;AACA;AACO;AACP;;;AAGA;AACO;AACA;AACA;AACA;AACP;;AAEA;AACO;AACA;AACP;;AAEA;AACO;AACA;AACA;AACP;;AAEA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA,YAAY,oEAAoE;AAChF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,kBAAkB;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;;AAEA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,iEAAiE;AAC7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,iEAAiE;AAC7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gDAAgD,SAAS;AACzD;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACO;AACP;;;AAGA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA,kBAAkB,oBAAoB;AACtC;AACA;AACA;AACA;AACA;AACA;;;;;AAKA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,oCAAoC;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+CAA+C,cAAc;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU,+DAA+D,GAAG;AAC7F;AACA,iCAAiC,cAAc;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C,cAAc;AAC1D;;AAEA;AACA,iBAAiB,QAAQ;AACzB,kBAAkB,QAAQ;AAC1B;AACA,kBAAkB,QAAQ;AAC1B;AACA,kBAAkB,QAAQ;AAC1B;AACA;AACA;AACA;AACA;AACA,kBAAkB,QAAQ;AAC1B,kBAAkB,QAAQ;AAC1B,kBAAkB,QAAQ;AAC1B;;AAEA;AACA,eAAe,gBAAgB;AAC/B,iBAAiB,iBAAiB;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,4CAA4C,oDAAM;AAClD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,qCAAqC;AACtD;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,kBAAkB,wBAAwB;AAC1C;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;;AAEA;;AAEA;AACP;;AAEA;AACA;AACO;;AAEA;;AAEA;AACP;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,uCAAuC;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEA;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,kEAAkE;AAC9E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,SAAS;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,0EAA0E;AACtF,YAAY,2FAA2F;AACvG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;AACA;AACP;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,uCAAuC;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,uCAAuC;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,YAAY,uCAAuC;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,wBAAwB;AACzC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,YAAY,kEAAkE;AAC9E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,SAAS;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA,YAAY,iFAAiF;AAC7F;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wFAAwF,eAAe;AACvG,sFAAsF,eAAe;AACrG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,YAAY;AACvB;AACA;AACA,WAAW,WAAW,+DAA+D,SAAS;AAC9F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA,iBAAiB,QAAQ;AACzB,kBAAkB,QAAQ;AAC1B;AACA,kBAAkB,QAAQ;AAC1B,kBAAkB,QAAQ;AAC1B;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,iBAAiB,uBAAuB;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;;AAEV;AACA;AACA;;AAEA,gBAAgB,0CAA0C;;AAE1D;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd,sCAAsC,oDAAM;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,oBAAoB,iBAAiB;AACrC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,4BAA4B,qDAAG;AAC/B,gBAAgB,WAAW,gDAAgD,aAAa;;AAExF;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;;;AAGA;AACA;AACA;AACA;AACA;AACO;;AAEA;;AAEA;AACP;;;AAGA;AACA;AACA;AACA;AACA;AACO;;AAEA;;AAEA;AACP;;;AAGA;AACA;AACA;AACA;AACA;AACO;;AAEA;;AAEA;AACP;;;AAGA;AACA;AACO;;AAEA;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,6CAA6C;AACzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,iCAAiC;AAC3E;AACA;AACA,WAAW,cAAc;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP,eAAe,iCAAiC;AAChD,4EAA4E;AAC5E;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,0DAA0D;AACtE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,eAAe;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,eAAe,iCAAiC;AAChD,4EAA4E;AAC5E;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA,YAAY,2BAA2B;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,WAAW;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,0BAA0B;AAC3C;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;;;AAGA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,kDAAkD;AAC9D;AACA;AACA;AACA;AACA,gCAAgC;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,iEAAiE;AACxE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA,wBAAwB,kBAAkB;AAC1C;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,mBAAmB,oDAAM;AACzB;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA,wBAAwB,2BAA2B;AACnD,4BAA4B,8BAA8B;AAC1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,eAAe,mEAAmE;AAClF,iBAAiB,6BAA6B;AAC9C;AACA;;AAEA;;AAEA;AACA;AACA;AACA,uBAAuB,QAAQ;AAC/B,yBAAyB;;AAEzB,gBAAgB,eAAe,sDAAsD,aAAa;;AAElG;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACO;;AAEP;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA;AACA;;;AAGA,eAAe,wCAAwC;AACvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B;AAC5B,MAAM,IAAI;;AAEV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,mDAAU;;AAEzC;AACA;AACA;;AAEA;AACA;AACA;AACA,0BAA0B;AAC1B;AACA;AACA;;AAEA;AACA,iDAAiD,0BAA0B;AAC3E;AACA,UAAU;AACV,mDAAmD,0BAA0B;AAC7E;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,eAAe,uBAAuB;AACtC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEO;AACP;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEO;AACP;AACA;;AAEO;AACP;AACA;;AAEO;AACP;AACA;;AAEO;AACP;AACA;;AAEO;AACP;AACA;;AAEO;AACP;AACA;;AAEO;AACP;AACA;;AAEO;AACP;AACA;;AAEO;AACP;AACA;;AAEO;AACP;AACA;;AAEA;;AAEA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,kBAAkB,8FAA8F;AAChH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,kBAAkB,QAAQ;AAC1B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,kBAAkB,oBAAoB;AACtC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,kBAAkB,QAAQ;AAC1B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,kBAAkB,QAAQ;AAC1B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,kBAAkB,0BAA0B;AAC5C;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,kBAAkB,QAAQ;AAC1B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA,kBAAkB,yBAAyB;AAC3C;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,kBAAkB,QAAQ;AAC1B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA,kBAAkB,uBAAuB;AACzC;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;ACxuNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;AACP;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA,UAAU;AACV;AACA;AACA;;AAEA,yCAAyC,SAAS,sCAAsC,sBAAsB;AAC9G;AACA;AACA;AACA;;;;;;;;;;;;;;;;ACtJ2E;;AAEpE,sCAAsC,gFAAgB;;AAE7D;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA,aAAa,yEAAyE,4CAA4C,2BAA2B;AAC7J;;;;;;;;;;;;;;;;;ACxF6D;AACjB;;AAE5C;AACA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,8DAA8D;AACzE,cAAc,8BAA8B;AAC5C,WAAW,GAAG;AACd;AACA,aAAa,qGAAqG,yBAAyB;AAC3I;AACA;AACA;AACA,0BAA0B,yEAAsB;AAChD;AACA;AACA,sBAAsB,KAAK,qBAAqB,wBAAwB;AACxE;AACA;;AAEA;AACA,wCAAwC,oDAAM;AAC9C,UAAU;AACV,uBAAuB,oDAAM,oBAAoB,QAAQ;AACzD;AACA,KAAK;AACL;;AAEA;AACO;AACP;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACtGA;AACA;AACA;AACA;AACA;AACA,YAAY,WAAW;AACvB;AACA;AACA;AACA,QAAQ,0CAA0C;AAClD;AACA;AACA;AACA;;AAKyB;AA0BJ;AAII;;AAIG;;AAMH;AAKC;AAGA;AAOC;AACiB;;;AAG5C;AACA,aAAa,yBAAyB;AACtC,aAAa,yBAAyB;AACtC;;AAEA;AACA;AACA,WAAW,qBAAqB;AAChC,aAAa,qBAAqB;AAClC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,6CAA6C,qDAAQ;AACrD;;AAEA;AACA,aAAa,4CAA4C;AACzD,aAAa,yBAAyB;AACtC;;AAEA;AACA;AACA,WAAW,qBAAqB;AAChC,WAAW,QAAQ;AACnB,aAAa,yBAAyB;AACtC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,mBAAmB,2DAAU;AAC7B,UAAU;AACV;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,cAAc,QAAQ;AACtB,cAAc,QAAQ;AACtB,cAAc,QAAQ;AACtB;;AAEA;AACA,0EAA0E;AAC1E,WAAW,UAAU;AACrB,WAAW,SAAS;AACpB,aAAa,aAAa;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,aAAa;AACb;;;AAGA;AACA;AACA,aAAa,eAAe;AAC5B;AACA,aAAa,QAAQ;AACrB,cAAc,aAAa;AAC3B;;AAEA;AACA;AAC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V;;AAEA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;;AAEA;AACA;;AAEA;AACA,wBAAwB,oBAAoB;AAC5C;AACA;;AAEA;AACA;AACA,4BAA4B,mBAAmB;AAC/C;AACA,sCAAsC,oDAAG;;AAEzC,6EAA6E,cAAc;AAC3F;AACA;AACA;AACA;;AAEA;AACA,sEAAsE,2BAA2B;AACjG;AACA;AACA;AACA;;AAEA,+BAA+B,wDAAO;;AAEtC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,cAAc,QAAQ;AACtB,cAAc,QAAQ;AACtB,cAAc,QAAQ;AACtB;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB;AACA;AACA,WAAW,iBAAiB;AAC5B,WAAW,iBAAiB;AAC5B,WAAW,kCAAkC;AAC7C,aAAa,4DAA4D;AACzE;AACA,aAAa,8EAA8E;AAC3F;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,oDAAoD,6EAA6E;;AAExI;AACA;AACA,eAAe,6BAA6B;AAC5C;AACA;AACA;AACA;;AAEA,eAAe,mCAAmC;AAClD;AACA;AACA,MAAM,IAAI;;AAEV;AACA;AACA;AACA;AACA;AACA,SAAS;;AAET,gBAAgB,2BAA2B;AAC3C;AACA;;AAEA;AACA;;AAEA,mBAAmB,2BAA2B;AAC9C;AACA,wBAAwB,0BAA0B;AAClD;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,4BAA4B,kBAAkB;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,iCAAiC,wDAAO;AACxC,+BAA+B,wDAAO;;AAEtC;AACA;AACA;;AAEA;AACA,4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A4D;AACrE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ,SAAS,sDAAsD;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ,SAAS,2FAA2F;AACpG;AACA;AACO,8CAA8C,uEAAuE,eAAe,KAAK;AAChJ,eAAe,oBAAoB;AACnC;;AAEA;AACA;AACA,eAAe,6BAA6B;AAC5C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,aAAa,qCAAqC;AAClD;AACA,aAAa,QAAQ;AACrB,cAAc,aAAa;AAC3B,aAAa,wBAAwB;AACrC;AACA,aAAa,QAAQ;AACrB,cAAc,SAAS;AACvB,cAAc,SAAS;AACvB,aAAa,+FAA+F;AAC5G;AACA;AACA,WAAW,6BAA6B;AACxC,WAAW,+BAA+B;AAC1C,aAAa,sDAAsD;AACnE;AACA,aAAa,2EAA2E;AACxF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,6FAA6F;AACtG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA,OAAO;AACP;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACO,iDAAiD,0EAA0E;;AAElI;AACA;AACA,eAAe,6BAA6B;AAC5C;AACA;AACA;AACA;;AAEA,eAAe,gCAAgC;AAC/C,2CAA2C;AAC3C;AACA;;AAEA;AACA,mBAAmB,UAAU;AAC7B;AACA;AACA;AACA,UAAU;AACV;AACA,gCAAgC,UAAU;AAC1C,UAAU;AACV;AACA,oCAAoC,MAAM;AAC1C,cAAc;AACd;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA,gCAAgC,UAAU,cAAc,QAAQ;AAChE;AACA;AACA;AACA,iBAAiB;AACjB;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,SAAS;;AAET,0CAA0C,QAAQ;AAClD;AACA;AACA,SAAS;;AAET;AACA;AACA,SAAS;;AAET;AACA;AACA;AACA;AACA,aAAa;AACb;;AAEA,mBAAmB,wBAAwB;AAC3C,sCAAsC,sBAAsB;AAC5D,wBAAwB,oBAAoB;AAC5C;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,QAAQ;AAChD,0BAA0B,wCAAwC;AAClE;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;;AAEA;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,cAAc,UAAU;AACxB,cAAc,UAAU;AACxB;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ,wCAAwC;AAC9D,yFAAyF;AACzF,cAAc,SAAS;AACvB;AACA;AACA;AACA;AACA;AACA,WAAW,iBAAiB;AAC5B,WAAW,iBAAiB;AAC5B;AACA,WAAW,uCAAuC;AAClD,aAAa,sEAAsE;AACnF;AACA,aAAa,mFAAmF;AAChG;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,mBAAmB;AACtE;AACA;AACA;AACA;AACA;AACA;AACA;AACO,yDAAyD,kFAAkF;AAClJ;AACA;AACA,eAAe,6BAA6B;AAC5C;AACA;AACA;;AAEA;AACA;AACA,uCAAuC,KAAK;AAC5C;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA,eAAe,wCAAwC;AACvD;AACA,iDAAiD;AACjD;AACA,MAAM,IAAI;;AAEV;AACA;AACA,gCAAgC,QAAQ;AACxC;AACA;AACA;AACA;;AAEA;AACA;AACA,gDAAgD;AAChD;;AAEA;AACA;AACA;AACA;;AAEA,mBAAmB,gCAAgC;AACnD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;;AAEA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;;AAEA,uBAAuB,UAAU;AACjC;AACA,0CAA0C,wDAAO;AACjD,kBAAkB,wDAAO;;AAEzB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;;AAEA;AACA,aAAa,QAAQ;AACrB,cAAc,qBAAqB;AACnC,cAAc,SAAS;AACvB,cAAc,SAAS;AACvB,cAAc,oBAAoB;AAClC;AACA;AACA,WAAW,iBAAiB;AAC5B,WAAW,kCAAkC;AAC7C,aAAa,iBAAiB;AAC9B;AACA,aAAa,8EAA8E;AAC3F;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,wFAAwF,qBAAqB;AAC7G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wFAAwF,qBAAqB;AAC7G,8DAA8D,kCAAkC;AAChG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8DAA8D,kCAAkC;AAChG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8DAA8D,sDAAsD;AACpH;AACA;AACA;AACA;AACA;AACA;AACA;AACO,oDAAoD,6EAA6E;AACxI;AACA;AACA,eAAe,6BAA6B;AAC5C;AACA;AACA;AACA;;AAEA,eAAe,mCAAmC;AAClD;AACA,6BAA6B,QAAQ;AACrC;AACA;AACA,+BAA+B,UAAU;AACzC,MAAM,IAAI;;AAEV;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;;AAEA;AACA;AACA;AACA;;AAEA,mBAAmB,QAAQ;AAC3B;AACA;AACA;AACA,UAAU;AACV,qBAAqB,8DAAY;AACjC,UAAU;AACV;AACA,UAAU;AACV,2CAA2C,QAAQ;AACnD;;AAEA;AACA;AACA;;AAEA;AACA,qBAAqB,qEAAmB;AACxC;;AAEA;AACA;AACA;;;AAGA;AACA,aAAa,QAAQ;AACrB,cAAc,SAAS;AACvB;AACA;AACA,WAAW,qBAAqB;AAChC,WAAW,uCAAuC;AAClD,aAAa,iBAAiB;AAC9B;AACA,aAAa,oFAAoF;AACjG;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,yDAAyD,mFAAmF;AACnJ;AACA;AACA,eAAe,8BAA8B;AAC7C;AACA;AACA;AACA;;AAEA,eAAe,wCAAwC;AACvD;AACA;AACA,MAAM,IAAI;;AAEV;AACA,gBAAgB,eAAe;AAC/B,2CAA2C,cAAc;;AAEzD,mBAAmB,QAAQ;AAC3B;AACA;AACA;AACA;AACA;AACA;;AAEA,UAAU;AACV;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,cAAc,QAAQ;AACtB,aAAa,6BAA6B;AAC1C;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB;AACA;AACA;AACA;AACA,WAAW,qBAAqB;AAChC;AACA;AACA;AACA;AACA,WAAW,oCAAoC;AAC/C,aAAa,gEAAgE;AAC7E;AACA,aAAa,iFAAiF;AAC9F;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU,0CAA0C;AACpD,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,UAAU;AACpD;AACA,UAAU,0CAA0C;AACpD,UAAU,0CAA0C;AACpD,UAAU,4DAA4D;AACtE,UAAU,6CAA6C;AACvD;AACA;AACA;AACO,sDAAsD,gFAAgF;;AAE7I;AACA;AACA,eAAe,8BAA8B;AAC7C;AACA;AACA;AACA;;AAEA,eAAe,qCAAqC;AACpD;AACA;AACA,MAAM,IAAI;;AAEV;AACA;;AAEA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;AACtB,cAAc,QAAQ;AACtB,aAAa,2GAA2G;AACxH;AACA;AACA,WAAW,qBAAqB;AAChC;AACA;AACA;AACA;AACA,WAAW,2CAA2C;AACtD,aAAa,8EAA8E;AAC3F;AACA,aAAa,4FAA4F;AACzG;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,yBAAyB;AACpE;AACA;AACA;AACA,YAAY;AACZ,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,2BAA2B;AACtE;AACA;AACA;AACA,YAAY,wCAAwC;AACpD,YAAY,0CAA0C;AACtD,YAAY,0CAA0C;AACtD;AACA,YAAY,2CAA2C;AACvD,YAAY,6CAA6C;AACzD,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,wCAAwC;AACnF,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,uCAAuC;AAClF,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,wCAAwC;AACnF,QAAQ;AACR;AACA;AACO,6DAA6D,2FAA2F;;AAE/J;AACA;AACA,eAAe,kCAAkC;AACjD;AACA;AACA;AACA;;AAEA,eAAe,4CAA4C;AAC3D,kCAAkC;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mGAAmG,6BAA6B;AAChI;AACA;;AAEA;AACA,cAAc;AACd;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,gCAAgC,YAAY;AAC5C;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,mCAAmC,oDAAG;AACtC;AACA;AACA,4BAA4B,2BAA2B;AACvD;AACA;AACA;;AAEA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,oCAAoC;;AAEpC;AACA;AACA,4DAA4D;AAC5D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A+E;AAC5F;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU,6DAA6D,OAAO;AAC9E,UAAU,0DAA0D;AACpE;AACA;AACA;AACO,oDAAoD,8EAA8E;AACzI;AACA;AACA,eAAe,8BAA8B;AAC7C;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,eAAe,mCAAmC;AAClD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;AACV;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA,gBAAgB,2BAA2B;AAC3C,0CAA0C,0BAA0B;;AAEpE;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA,mBAAmB,mCAAmC;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,gCAAgC,8BAA8B;AAC9D;AACA;AACA;AACA;;AAEA,iCAAiC,qDAAQ;;AAEzC;AACA;AACA;AACA;AACA,iBAAiB;AACjB;;AAEA,UAAU;AACV,oBAAoB,uBAAuB;;AAE3C;AACA;AACA,gCAAgC,8BAA8B;AAC9D;AACA;AACA;AACA;;AAEA,iCAAiC,qDAAQ;;AAEzC;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA,UAAU;AACV,mCAAmC,SAAS;AAC5C;;AAEA;AACA;AACA;;AAEA;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,cAAc,QAAQ;AACtB;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ,2CAA2C;AACjE;AACA;AACA;AACA;AACA,WAAW,qBAAqB;AAChC,WAAW,UAAU;AACrB,WAAW,4CAA4C;AACvD,aAAa,oFAAoF;AACjG;AACA,aAAa,6FAA6F;AAC1G;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU,2CAA2C;AACrD,UAAU,8CAA8C;AACxD,UAAU;AACV;AACA;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AC3B;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,cAAc,QAAQ;AACtB;AACA;AACA,cAAc,SAAS;AACvB;AACA;AACA,WAAW,qBAAqB;AAChC,WAAW,UAAU;AACrB,WAAW,wCAAwC;AACnD,aAAa,4EAA4E;AACzF;AACA,aAAa,yFAAyF;AACtG;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB,SAAS;AACT;AACA;AACA;AACA,iBAAiB;AACjB,SAAS;AACT;AACA;AACA;AACA,iBAAiB;AACjB,SAAS;AACT;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0DAA0D,2BAA2B;AACrF;AACA;AACA;AACA;AACA,iBAAiB;AACjB,SAAS;AACT;AACA;AACA;AACA,iBAAiB;AACjB,SAAS;AACT;AACA;AACA;AACA,iBAAiB;AACjB,SAAS;AACT;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACO,0DAA0D,wFAAwF;;AAEzJ;AACA;AACA,eAAe,kCAAkC;AACjD;AACA;AACA;AACA;;AAEA,eAAe,yCAAyC;AACxD;AACA;AACA;AACA;AACA,MAAM,IAAI;;AAEV;AACA;;AAEA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;;AAEA;AACA;AACA;AACA;AACA,wBAAwB,2BAA2B;AACnD;AACA;AACA;;AAEA;AACA,8CAA8C,8BAA8B;;AAE5E;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,aAAa,mCAAmC;AAChD;AACA;AACA,WAAW,YAAY;AACvB,WAAW,QAAQ;AACnB,WAAW,yEAAyE;AACpF,aAAa,4EAA4E;AACzF;AACA,aAAa,2FAA2F;AACxG;;AAEA;AACA;AACA,mFAAmF;AACnF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,kBAAkB;AAC3B;AACA;AACO,4DAA4D,0FAA0F;;AAE7J;AACA;AACA,eAAe,kCAAkC;AACjD;AACA;AACA;AACA;;AAEA,eAAe,2CAA2C;AAC1D,qDAAqD;AACrD,sFAAsF;;AAEtF;;AAEA;AACA;AACA,gBAAgB,eAAe;;AAE/B;AACA,qDAAqD,SAAS;AAC9D;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA,+DAA+D,QAAQ;;AAEvE;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,QAAQ;AAC1B;AACA;;;AAGA;AACA,aAAa,QAAQ;AACrB,cAAc,iBAAiB;AAC/B,aAAa,mDAAmD;AAChE;;AAEA;AACA,aAAa,QAAQ;AACrB,cAAc,cAAc;AAC5B,cAAc,QAAQ;AACtB;AACA,aAAa,QAAQ;AACrB,cAAc,gCAAgC;AAC9C;AACA;AACA,WAAW,iBAAiB;AAC5B,WAAW,4BAA4B;AACvC,aAAa,4BAA4B;AACzC;AACA,aAAa,+EAA+E;AAC5F;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,iFAAiF,kBAAkB;AACnG;AACA,4DAA4D,oBAAoB;AAChF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,8CAA8C,8EAA8E;AACnI;;AAEA;AACA;AACA,eAAe,oCAAoC;AACnD;AACA;AACA;;AAEA;AACA;AACA;;;AAGA,eAAe,6BAA6B;AAC5C;AACA;AACA,MAAM,IAAI;;AAEV;AACA;AACA,iEAAiE,oBAAoB;AACrF,UAAU;AACV;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA,gBAAgB,WAAW;;AAE3B;AACA;AACA;AACA;AACA;AACA;;AAEA,mDAAmD,oBAAoB;;AAEvE;AACA;AACA;AACA,iCAAiC,iDAAS,4CAA4C,eAAe;AACrG;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,qCAAqC,oDAAM;AAC3C;AACA;AACA;AACA;AACA,UAAU,yCAAyC,oDAAM;AACzD;AACA;;AAEA;AACA,gBAAgB,YAAY;AAC5B;AACA;AACA,SAAS;;AAET;AACA;AACA,gBAAgB,WAAW,oEAAoE,uBAAuB;;AAEtH;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,qBAAqB;AAChC,aAAa,8BAA8B;AAC3C;AACA,aAAa,0EAA0E;AACvF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,+CAA+C,yEAAyE;AAC/H;AACA;AACA,eAAe,8BAA8B;AAC7C;AACA;AACA;AACA;;AAEA,eAAe,8BAA8B;AAC7C;;AAEA;AACA;AACA;;AAEA,mBAAmB,YAAY;AAC/B;AACA;AACA;AACA,0BAA0B,qDAAQ;AAClC;;AAEA;AACA;AACA;;AAEA;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,cAAc,UAAU;AACxB;AACA;AACA,WAAW,qBAAqB;AAChC,aAAa,wEAAwE;AACrF;AACA,aAAa,6EAA6E;AAC1F;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,kDAAkD,4EAA4E;AACrI;AACA;AACA,eAAe,8BAA8B;AAC7C;AACA;AACA;AACA;;AAEA,eAAe,iCAAiC;AAChD;;AAEA;;AAEA;AACA,gBAAgB,kBAAkB;;AAElC;AACA,wBAAwB,2BAA2B;AACnD,+BAA+B,6DAAW;AAC1C,oDAAoD,oDAAG;AACvD;AACA;AACA,uBAAuB,qDAAQ;AAC/B,aAAa;AACb;;AAEA;AACA;AACA;;AAEA;AACA;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,0EAAkC;AACnD;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,uEAA+B;AAChD;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,qEAA6B;AAC9C;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;;AAEL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,4DAAoB;AACrC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,6DAAqB;AACtC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,6DAAqB;AACtC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,6DAAqB;AACtC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,4DAAoB;AACrC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,0EAAkC;AACnD;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA;AACA,iBAAiB,uEAA+B;AAChD,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,iDAAS;AAC1B,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,kBAAkB,iEAAyB,EAAE,uDAAe;AAC5D,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,kBAAkB,kEAA0B,EAAE,qEAA6B;AAC3E,sBAAsB,yDAAa;AACnC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,8DAAsB;AACvC,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;;AAEL;AACA;AACA;AACA,iBAAiB,uEAA+B;AAChD,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;;AAEL;AACA;AACA;AACA,kBAAkB,qEAA6B,EAAE,wEAAgC,EAAE,yEAAiC;AACpH,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;;AAEL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,iDAAS;AAC1B,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;;AAEL;AACA;AACA;AACA,iBAAiB,mEAA2B;AAC5C,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,2EAAmC;AACpD,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,6EAAqC;AACtD,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA;AACA;AACA,iBAAiB,gEAAwB;AACzC,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA;AACA;AACA,iBAAiB,mEAA2B;AAC5C,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;;AAEL;AACA;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,iDAAS;AAC1B;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,kBAAkB,0EAAkC,EAAE,iDAAS;AAC/D;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL,CAAC;;;AAGD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,CAAC;;AAED;AACA,aAAa,8BAA8B;AAC3C,aAAa,2BAA2B;AACxC,aAAa,sBAAsB;AACnC,cAAc,uEAAuE;AACrF,cAAc,sFAAsF;AACpG,aAAa,6BAA6B;AAC1C;;AAEA;AACA;AACA;AACA,cAAc,cAAc;AAC5B,WAAW,GAAG;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,iDAAiD;AAC5D,aAAa,sBAAsB;AACnC,YAAY,OAAO;AACnB;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B;AAC5B,MAAM;AACN;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,6CAA6C,KAAK,oBAAoB,6BAA6B;AACnG;;AAEA;AACA;AACA;AACA,iEAAiE,MAAM;AACvE;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,IAAI,gEAAgB;AACpB;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;;;AAGA;AACA;AACA,WAAW,kBAAkB;AAC7B,WAAW,QAAQ;AACnB,WAAW,4CAA4C;AACvD;AACA;AACA;;AAEA;;AAEA,cAAc,WAAW;AACzB;AACA;AACA;;AAEA,kBAAkB,SAAS;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA;AACA;AACA;AACA,0BAA0B;AAC1B;AACA,0BAA0B;AAC1B;AACA;AACA;;AAEA;AACA;AACA;AACA,aAAa;AACb,UAAU;AACV;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC5wGA;AACA;AACA;AACA;AACA;AACA,YAAY,4BAA4B;AACxC;AACA;AACA;AACA,SAAS,iBAAiB;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAG4B;;AAKH;;AAID;;AAOE;;;AAGgE;;AAE9C;AAKlB;;;AAG1B;;AAEA;AACA;AACA;AACA,WAAW,UAAU;AACrB,aAAa,UAAU;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,oBAAoB;AAC/B,WAAW,SAAS;AACpB,YAAY,UAAU;AACtB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,oBAAoB,gBAAgB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,wBAAwB,eAAe;AACvC;;AAEA;AACA;AACA;AACA;AACA;AACA,gCAAgC,kBAAkB;AAClD;AACA;AACA;AACA;;AAEA,cAAc;AACd;AACA,+BAA+B,oDAAG;;AAElC;AACA;AACA;AACA;AACA;AACA,wBAAwB,wDAAO;;AAE/B;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA,2BAA2B,UAAU;AACrC;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA,WAAW,GAAG;AACd,WAAW,o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7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,6BAA6B,oDAAM;AACnC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,wBAAwB,uBAAuB;AAC/C,4BAA4B,6DAAW;AACvC;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA,oBAAoB,uBAAuB;AAC3C;;AAEA;;AAEA,wBAAwB,8BAA8B;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,oBAAoB,wBAAwB;AAC5C;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;;;AAGA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;AACA;AACA;AACA;;AAEA;AACA;;;AAGA;AACA;AACA,WAAW,GAAG;AACd,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,aAAa;AACxB,WAAW,oBAAoB;AAC/B,aAAa,QAAQ,4CAA4C,4CAA4C,EAAE;AAC/G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,iFAAiF;AACjF,qFAAqF;;AAErF;;AAEA;AACA,qBAAqB;;AAErB;AACA;AACA;;AAEA;AACA,oBAAoB,gBAAgB;AACpC;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA,mCAAmC,oDAAM;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,SAAS;AACT;;AAEA;AACA;;;AAGA;AACA;AACA,WAAW,GAAG;AACd,WAAW,QAAQ;AACnB,WAAW,oBAAoB;AAC/B;AACA,aAAa,QAAQ,4CAA4C,4CAA4C,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;AACA;AACA;AACA,eAAe,UAAU;AACzB,eAAe,KAAK;AACpB,iBAAiB,kBAAkB;AACnC;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA,oBAAoB,gBAAgB;AACpC;AACA;AACA;AACA;AACA;AACA;;AAEA,UAAU;AACV;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,UAAU;AACV;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA,UAAU;AACV;AACA,UAAU;AACV,yGAAyG,qBAAqB;AAC9H;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,mBAAmB;AACpC;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;;AAEA;AACA,iBAAiB,QAAQ;AACzB,kBAAkB,aAAa;AAC/B,kBAAkB,aAAa;AAC/B,kBAAkB,QAAQ;AAC1B;;AAEA;AACA;AACA;AACA,eAAe,UAAU;AACzB,eAAe,QAAQ;AACvB,iBAAiB,4BAA4B;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;AACV;AACA;AACA;AACA;AACA;;AAEA,kDAAkD;;AAElD;AACA;AACA;AACA,UAAU;AACV;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;;AAEA,mBAAmB,aAAa;AAChC;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,qFAAqF,kBAAkB,uBAAuB,iBAAiB,oDAAoD,eAAe;AAClN;;AAEA,4BAA4B,sBAAsB;AAClD,gCAAgC,oBAAoB;AACpD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,+CAA+C;AAC/C,cAAc;AACd;AACA,4EAA4E,0CAA0C;AACtH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,4BAA4B,sBAAsB;AAClD;AACA;AACA;AACA;AACA;;AAEA,iCAAiC,oDAAM;AACvC,+BAA+B;;AAE/B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,sCAAsC;AACvD;AACA;AACA;AACA;AACA;AACA,mBAAmB,qBAAqB;AACxC;;AAEA;AACA,6BAA6B,uDAAK;;AAElC;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEO;AACP,eAAe,2CAA2C;AAC1D;AACA;AACA;AACA;AACO;AACP,eAAe,2CAA2C;AAC1D;AACA;AACA;AACA;AACO;AACA;AACA,wDAAwD;AACxD;AACA;AACA;AACA,0DAA0D;AAC1D;AACA;AACA;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,aAAa;;AAEb;AACA;AACA,aAAa;;AAEb;AACA;AACA,UAAU;AACV;AACA;AACA;AACA,aAAa;AACb;;AAEA;AACA;AACA;AACO,mEAAmE;AACnE;AACA;;AAEA;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;AACA;AACA;AACA;;AAEA;AACA,oEAAoE;AACpE;AACP,eAAe,sCAAsC;AACrD;AACA;AACA;AACA;AACO,6DAA6D;;AAE7D;AACP,eAAe,sCAAsC;AACrD;AACA;AACA;AACA;;AAEO;AACA;AACA;AACP,uDAAuD;AACvD;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACO,6D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;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;AAEO;AACP;AACA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,YAAY;AAC3B,iBAAiB,sCAAsC;AACvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,SAAS;;;AAGT;AACA,6BAA6B,uDAAK;AAClC;AACA,sBAAsB,qDAAG;AACzB;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEO;;AAEP;AACA;;AAEA;AACA,oCAAoC,gEAAe;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,sBAAsB,gEAAe;AACrC;;AAEA;AACA;AACA,eAAe,2BAA2B;AAC1C,iBAAiB,iBAAiB;AAClC;AACA;AACA,+BAA+B,4DAAW;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,yBAAyB,oDAAG;;AAE5B,wBAAwB,iBAAiB;AACzC;AACA;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,2BAA2B;AAC1C,iBAAiB,UAAU,wBAAwB,GAAG;AACtD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEO;;AAEP;AACA,eAAe,cAAc;AAC7B,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,2BAA2B;AAC1C,iBAAiB,UAAU,sBAAsB,wBAAwB,GAAG;AAC5E;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,8BAA8B,oDAAM;AACpC,gCAAgC,oDAAM;AACtC;AACA;AACA;;AAEO;;AAEP;AACA;;AAEA;AACA,4BAA4B,gEAAe;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,wBAAwB,wBAAwB;AAChD;AACA;AACA;;AAEA,sBAAsB,gEAAe;AACrC;AACA,SAAS;AACT;;AAEA;AACA;AACA,eAAe,2BAA2B;AAC1C,eAAe,QAAQ;AACvB,iBAAiB,iBAAiB;AAClC;AACA;AACA;;AAEA;AACA;AACA,4CAA4C,QAAQ;;AAEpD,eAAe,4DAAW;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,2BAA2B;AAC1C,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,iBAAiB,UAAU,iDAAiD,GAAG;AAC/E;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;AACV;;AAEA;;AAEA;AACA;AACA;AACA,4BAA4B,kBAAkB;AAC9C;AACA,gCAAgC,kBAAkB;AAClD;AACA;;AAEA;;AAEA;AACA,gCAAgC,kBAAkB;AAClD;AACA;AACA,8CAA8C;;AAE9C;AACA,gCAAgC,kBAAkB;AAClD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,oCAAoC,cAAc;;AAElD;AACA;AACA;AACA;AACA;;AAEA;AACA,+BAA+B,oDAAM;AACrC;AACA;AACA;AACA;;AAEA;AACA,gDAAgD,oDAAM;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,qDAAqD,WAAW,sCAAsC,OAAO;AAC7G;;AAEA;AACA;AACA;AACA;AACA;;AAEA,yBAAyB;;AAEzB;AACA;;AAEA;;AAEA;AACA;AACA,uCAAuC,gBAAgB;AACvD;AACA;AACA,cAAc;AACd;AACA;AACA,wCAAwC,oDAAM;AAC9C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEO;;;AAGP;AACA;;AAEA;AACA,4BAA4B,gEAAe;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,wBAAwB,wBAAwB;AAChD;AACA;AACA;;AAEA,sBAAsB,gEAAe;AACrC;AACA,SAAS;;AAET;AACA;AACA;;AAEA;AACA;AACA,eAAe,2BAA2B;AAC1C,eAAe,QAAQ;AACvB,iBAAiB,iBAAiB;AAClC;AACA;AACA;AACA,eAAe,4DAAW;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA,eAAe,2BAA2B;AAC1C,iBAAiB,UAAU,sBAAsB,GAAG;AACpD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,4BAA4B,0BAA0B;AACtD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEO;;AAEP;AACA;;AAEA,2BAA2B,gEAAe;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,kCAAkC,gEAAe;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,sBAAsB,gEAAe;;AAErC;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,2BAA2B;AAC1C,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,iBAAiB;AAClC;AACA;AACA;;AAEA,mBAAmB,QAAQ;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,cAAc;AACd;AACA,wDAAwD,WAAW;AACnE;AACA,UAAU;AACV;AACA,2DAA2D;AAC3D;;AAEA;AACA,kDAAkD,gBAAgB;AAClE;AACA;AACA,kBAAkB;AAClB,kDAAkD,WAAW;AAC7D;AACA;AACA;AACA;AACA;;AAEA;AACA,wDAAwD,WAAW;AACnE;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,2BAA2B;AAC1C,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,iBAAiB;AAClC;AACA;AACA;AACA,eAAe,4DAAW;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA,eAAe,2BAA2B;AAC1C,iBAAiB,UAAU,wBAAwB,GAAG;AACtD;AACA;AACA;AACA,MAAM,IAAI;AACV;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;;AAGO;AACP;AACA;AACA,eAAe,2BAA2B;AAC1C,iBAAiB,UAAU,uBAAuB,GAAG;AACrD;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,oDAAM;AACpC;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,cAAc,4DAA4D,IAAI;AAC/F;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,4BAA4B,mBAAmB;AAC/C,sCAAsC,wDAAO;AAC7C,oCAAoC,oDAAG;AACvC;;AAEA;AACA;AACA;AACA,gDAAgD,uBAAuB;AACvE,kBAAkB;AAClB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,mBAAmB,uBAAuB;AAC1C;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;;AAEA;;AAEO;;AAEP;AACA;;AAEA;AACA,4BAA4B,gEAAe;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,wBAAwB,wBAAwB;AAChD;AACA;AACA;;AAEA,sBAAsB,gEAAe;AACrC;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA,eAAe,2BAA2B;AAC1C,iBAAiB,iBAAiB;AAClC;AACA;AACA;AACA;AACA,4CAA4C,QAAQ;;AAEpD,eAAe,4DAAW;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA,eAAe,2BAA2B;AAC1C,iBAAiB,UAAU,wBAAwB,GAAG;AACtD;AACA;AACA;;AAEA;;AAEA;AACA;AACA,wCAAwC,cAAc;AACtD,4CAA4C,cAAc;AAC1D;;AAEA,4BAA4B,gBAAgB;AAC5C;AACA;AACA,gCAAgC,gBAAgB;AAChD;AACA,oCAAoC,kBAAkB;AACtD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEO;;AAEP;AACA;AACA;AACA;AACO,wBAAwB,uDAAQ;AACvC;AACA;AACA,eAAe,kBAAkB;AACjC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,KAAK;AACpB,eAAe,QAAQ;AACvB,iBAAiB,cAAc;AAC/B;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,KAAK;AACpB,iBAAiB,cAAc;AAC/B;AACA;AACA;AACA;AACA;;;AAGO;AACP;AACA;AACA,eAAe,KAAK;AACpB,iBAAiB,cAAc;AAC/B;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA,eAAe,KAAK;AACpB,iBAAiB,cAAc;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEO;AACP;AACA;AACA,eAAe,KAAK;AACpB,iBAAiB,cAAc;AAC/B;AACA;AACA;AACA;AACA;;AAEO;;AAEA;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA,UAAU;;AAEV,mBAAmB,qBAAqB;AACxC,+GAA+G;;AAE/G,mBAAmB,qBAAqB;AACxC,mGAAmG;;AAEnG,mBAAmB,qBAAqB;AACxC,2FAA2F;;AAE3F;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,iBAAiB;AAChC,iBAAiB;AACjB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yDAAyD,MAAM;AAC/D;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,kBAAkB;AACjC;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC;AACjC;;AAEA;AACA,yCAAyC,KAAK,cAAc,iCAAiC;AAC7F;;AAEA,iBAAiB;AACjB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA,eAAe,4CAA4C;AAC3D;AACA,iBAAiB,oBAAoB;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;;AAEV,iDAAiD,2DAAY;AAC7D;AACA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,wDAAwD,IAAI;AAC5D;AACA,cAAc;AACd,mEAAmE,IAAI;AACvE;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC1lFA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,gBAAgB;AAC5B;AACA;AACA,WAAW,YAAY;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAG4B;;AAQH;;AAID;;AAE2B;AACR;;AAMP;;AAEU;;AAKF;AACY;;AAExD;AACA,aAAa,QAAQ;AACrB,cAAc,SAAS;AACvB,aAAa,kEAAkE;AAC/E;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,4BAA4B;AACvC,aAAa,gBAAgB;AAC7B;AACA;;AAEA;AACA,QAAQ,2DAAY;AACpB,QAAQ,2DAAY;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,UAAU;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,SAAS;AACpB,aAAa,aAAa;AAC1B;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,+DAA+D;;AAE/D;AACA;AACA;AACA;;AAEA;;AAEA,MAAM;AACN,wBAAwB,4DAAY;AACpC;AACA,iDAAiD,QAAQ;;AAEzD,MAAM;AACN;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,kBAAkB;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,UAAU;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2EAA2E,YAAY;AACvF;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACA;AACA,4BAA4B,EAAE;AAC9B;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,eAAe;AAC1B,aAAa,SAAS;AACtB;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,kBAAkB;AAC7B,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,UAAU;AACvB;AACA;AACA;AACA;;AAEA,+BAA+B,EAAE;AACjC,+CAA+C,kBAAkB;AACjE;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,kBAAkB,kBAAkB,iBAAiB,kBAAkB;AACvE;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACO,6BAA6B,uDAAQ;AAC5C;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;;AAEA,mBAAmB,UAAU;AAC7B;;AAEA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA;;AAEA,mBAAmB,SAAS;AAC5B;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,MAAM;AACrB,iBAAiB,gBAAgB;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA;AACA;AACA;AACA,gEAAgE,YAAY;AAC5E;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,mBAAmB;AAClC,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,QAAQ;AACvB;AACA;AACA;;AAEA;AACA;AACA;AACA,wBAAwB,eAAe;AACvC;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,8BAA8B;;AAE9B,oEAAoE;AACpE;;AAEA;AACA;;AAEA,wBAAwB,oDAAG;;AAE3B;AACA;;AAEA,wBAAwB,+DAAQ;AAChC;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,cAAc;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,mDAAG;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA,4BAA4B,mEAAY;AACxC;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;;AAEA;AACA,wBAAwB,mDAAmD;AAC3E,wBAAwB,mDAAmD;AAC3E,wBAAwB,mDAAmD;AAC3E;AACA;AACA;AACA,oBAAoB,SAAS;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;;AAED,yBAAyB,iEAAiB;;;AAG1C;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,cAAc,QAAQ;AACtB,cAAc,QAAQ;AACtB,cAAc,SAAS;AACvB,cAAc,SAAS;AACvB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,6BAA6B;AAC5C,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB;AACA;AACA;;AAEA,mBAAmB,qBAAqB;AACxC;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,mBAAmB,oBAAoB;AACvC;AACA,yBAAyB,oBAAoB;AAC7C,0BAA0B,UAAU,uCAAuC,kBAAkB;AAC7F;;AAEA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA,mBAAmB,uBAAuB;AAC1C;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,8BAA8B,oEAAa;;AAE3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,4BAA4B,iBAAiB;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,8CAA8C;;AAE9C;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,sBAAsB;AACtB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,iDAAiD,sBAAsB;AACvE;AACA;AACA,UAAU;AACV;AACA;;AAEA;AACA;AACA;AACA,4BAA4B,uBAAuB;AACnD;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;;AAGA;AACA;AACA,eAAe,eAAe;AAC9B,eAAe,SAAS;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,kBAAkB;AAClB;AACA,wCAAwC,8CAA8C;AACtF;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;;AAEA,kBAAkB,qBAAqB;AACvC;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA,yBAAyB,uDAAQ;AACjC;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,YAAY;AAC7B,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4DAA4D,YAAY;AACxE;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;;AAEA;AACA,kBAAkB,2BAA2B;AAC7C,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa,QAAQ;AACrB,aAAa,UAAU;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc,QAAQ;AACtB,gBAAgB,QAAQ;AACxB;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA,wBAAwB,iBAAiB;AACzC;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA,iDAAiD,GAAG;AACpD;;;AAGA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,SAAS;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,GAAG;AACpD;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qCAAqC;AACrC;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,UAAU;AACV;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,2BAA2B,uDAAQ;AACnC;AACA;AACA;AACA;AACA,aAAa,QAAQ;AACrB,eAAe,cAAc;AAC7B,cAAc,OAAO;AACrB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8DAA8D,YAAY;AAC1E;AACA;;AAEA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,iBAAiB;AAChC,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,kBAAkB,gCAAgC;AAClD,eAAe,iBAAiB;AAChC,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA,mFAAmF,GAAG;AACtF,0CAA0C,kBAAkB,MAAM,kBAAkB;AACpF;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;;AAEA;AACA,kBAAkB,SAAS;AAC3B;AACA;AACA;;AAEA;AACA,kBAAkB,SAAS;AAC3B;AACA;AACA;AACA;;AAEA;AACA,kBAAkB,SAAS;AAC3B;AACA;AACA;AACA,qDAAqD,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,EAAE;;AAElF;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,aAAa,yEAAyE;AACtF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,kBAAkB;AACjC,eAAe,kBAAkB;AACjC,eAAe,wBAAwB;AACvC,eAAe,SAAS;AACxB;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,wBAAwB;AACvC;AACA;AACA;AACA;AACA,uCAAuC,kBAAkB,MAAM,kBAAkB;AACjF;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB;AACA;AACA;AACA;;AAEA;AACA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e,OAAO;AACtB,eAAe,OAAO;AACtB;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,eAAe,UAAU;AACzB,iBAAiB,qBAAqB;AACtC;AACA;AACA;AACA,MAAM,IAAI;AACV;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA,sCAAsC,2DAAW;AACjD,4BAA4B,2DAAW;;AAEvC,kBAAkB;AAClB,sCAAsC,2DAAW;AACjD,4BAA4B,2DAAW;AACvC;AACA;AACA;AACA,iBAAiB;AACjB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,UAAU;AACzB,eAAe,UAAU;AACzB,iBAAiB,qBAAqB;AACtC;AACA;AACA;AACA,qBAAqB,2DAAW;AAChC;AACA,iBAAiB;AACjB;AACA;;;AAGA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,UAAU;AACzB;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,eAAe,UAAU;AACzB,iBAAiB,qBAAqB;AACtC;AACA,yDAAyD;AACzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,uDAAQ;;AAE9B;AACA;AACA;AACA,cAAc,QAAQ;AACtB;AACA;AACA;AACA;;AAEA,mBAAmB,cAAc;AACjC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,aAAa,QAAQ;AACrB,eAAe,SAAS;AACxB,cAAc,OAAO;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,yDAAyD,YAAY;AACrE;AACA;;AAEA;AACA;AACA;AACA,cAAc,UAAU;AACxB,gBAAgB,QAAQ;AACxB;AACA;AACA;AACA;;AAEA;AACA;AACA,cAAc,UAAU;AACxB,gBAAgB,QAAQ;AACxB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA,eAAe,yBAAyB;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;;AAEA;AACA;;AAEA,eAAe,yBAAyB;AACxC;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA,eAAe,yBAAyB;AACxC;AACA;AACA;AACA;;;AAGA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,eAAe,yBAAyB;AACxC;AACA;AACA;AACA,4BAA4B,gBAAgB;AAC5C;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;;AAEA;AACA,4BAA4B,eAAe;AAC3C;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;;AAEA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB;AACA;AACA;AACA;AACA;;AAEA,eAAe,yBAAyB;AACxC;AACA;AACA;AACA;AACA,qDAAqD;AACrD;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,eAAe,yBAAyB;AACxC;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,QAAQ;AACzB;AACA;AACA;;AAEA;AACA;AACA,wBAAwB,mBAAmB;AAC3C;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA,eAAe,yBAAyB;AACxC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,UAAU;AACzB;AACA;AACA;AACA;AACA;;AAEA,eAAe,yBAAyB;AACxC;AACA;AACA;AACA;AACA,SAAS;AACT;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,eAAe,yBAAyB;AACxC;AACA;AACA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA,eAAe,yBAAyB;AACxC;AACA;AACA,wBAAwB,mBAAmB;AAC3C;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,0BAA0B;AACzC;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA,MAAM,IAAI;;AAEV;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,QAAQ;AACvB;AACA;AACA;;AAEA;AACA;AACA;;AAEA,eAAe,yBAAyB;AACxC;AACA;AACA,wBAAwB,mBAAmB;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,2FAA2F;AAC3F,gJAAgJ;;AAEhJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,UAAU;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,uBAAuB;AAClC,WAAW,QAAQ;AACnB,WAAW,sBAAsB;AACjC,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,cAAc,2DAAW;AACzB,cAAc,2DAAW;AACzB;AACA;;AAEA;AACA;AACA;AACA,WAAW,uBAAuB;AAClC,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,cAAc,QAAQ;AACtB;;AAEO,kCAAkC,uDAAQ;AACjD;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,mBAAmB,cAAc;AACjC;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iEAAiE;;AAEjE;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,6BAA6B,uBAAuB,GAAG,4DAAY,YAAY,GAAG,uBAAuB;AACzG;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;;AAEA,mBAAmB,SAAS;AAC5B;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,yBAAyB,iBAAiB;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,WAAW;AAC1B,iBAAiB,aAAa;AAC9B,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,kBAAkB;AAClB,kDAAkD,KAAK;AACvD;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,4BAA4B;AAC3C;AACA,gBAAgB,OAAO;AACvB,iBAAiB,8BAA8B;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;;AAEV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;AACA;;AAEA;AACA,iBAAiB,4BAA4B;AAC7C;AACA,iBAAiB,QAAQ;AACzB,kBAAkB,mBAAmB;AACrC,kBAAkB,mBAAmB;AACrC,kBAAkB,mBAAmB;AACrC;;AAEA;AACA;AACA,eAAe,iBAAiB;AAChC,eAAe,QAAQ;AACvB,eAAe,iBAAiB;AAChC,eAAe,sBAAsB;AACrC,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,iBAAiB,eAAe;AAChC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU,IAAI;AACd;;AAEA;;AAEA,mBAAmB,kBAAkB;AACrC;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,kBAAkB;AAClB;AACA;;AAEA;AACA,qDAAqD,oEAAoE;AACzH;;AAEA,cAAc;AACd,qEAAqE,2CAA2C;AAChH;;AAEA,UAAU;AACV;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,uDAAuD,sDAAsD;AAC7G;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA,6BAA6B,oDAAG;AAChC;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA,4BAA4B,0BAA0B;AACtD;AACA;;AAEA,kBAAkB;AAClB;AACA;AACA;AACA;;AAEA,kBAAkB,OAAO;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,kCAAkC,oDAAM;AACxC;AACA;AACA;AACA;;AAEA,UAAU;AACV;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,0BAA0B,eAAe;AACzC;;AAEA;AACA;AACA;AACA,eAAe,aAAa;AAC5B,iBAAiB,eAAe;AAChC;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB;;AAEjB;;AAEA;AACA;AACA,SAAS;;AAET;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,iBAAiB,gBAAgB;AACjC;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;;AAEV,gBAAgB,yBAAyB,gCAAgC,qCAAqC;;AAE9G;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,kBAAkB,8CAA8C;AAChE;AACA;AACA;AACA;AACA,MAAM,IAAI;AACV;AACA;;AAEA;AACA,qDAAqD,oBAAoB;AACzE,gBAAgB,QAAQ,2DAAW;AACnC;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA,MAAM,IAAI;AACV,6CAA6C,0BAA0B;AACvE;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;AACV;AACA;AACA;AACA;AACA,SAAS;AACT;;AAEA;AACA;AACA,eAAe,mBAAmB;AAClC,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA,wCAAwC;AACxC,6BAA6B,oDAAM;AACnC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,0BAA0B;AACzC,eAAe,QAAQ,eAAe;AACtC,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB;AACA,iBAAiB,QAAQ;AACzB,gBAAgB,OAAO;AACvB;AACA;AACA;AACA,wBAAwB;AACxB;AACA,iCAAiC,oDAAM;AACvC;AACA;;AAEA,oEAAoE,gEAAgB;AACpF;AACA;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,mBAAmB;AAClC,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB;AACA,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,mBAAmB,QAAQ;AAC3B;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA,eAAe,UAAU;AACzB;AACA;AACA;AACA;AACA;AACA,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA,MAAM,IAAI;;AAEV;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA,kBAAkB;AAClB;AACA,kBAAkB;AAClB;AACA;AACA;AACA,8CAA8C,kCAAkC;AAChF;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,gBAAgB;AAChC;AACA;AACA;AACA;AACA,WAAW,kDAAkD;AAC7D,WAAW,8EAA8E;AACzF,WAAW,8EAA8E;AACzF;AACA;AACA,0DAA0D,iBAAiB;AAC3E;AACA;AACA,+DAA+D,sCAAsC;AACrG;AACA;AACA;AACA,eAAe,WAAW;AAC1B;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,eAAe,UAAU;AACzB;AACA;AACA;AACA;AACA;AACA,eAAe,0BAA0B;AACzC;AACA;AACA;AACA;AACA;AACA,eAAe,SAAS;AACxB;AACA;AACA;AACA,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,eAAe,QAAQ;AACvB;AACA,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,eAAe,QAAQ,4BAA4B;AACnD,iBAAiB,sDAAsD;AACvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA,MAAM,IAAI;;AAEV,iDAAiD,sBAAsB;;AAEvE;AACA,mEAAmE,qBAAqB;AACxF;;AAEA;AACA;AACA;AACA,mCAAmC,wDAAQ;AAC3C;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACO;AACP;AACA;AACO;AACP;AACA;AACO;AACP;AACA;AACO;AACP;AACA;AACO;AACP;AACA;AACO;AACP;AACA;AACO;AACP;AACA;AACO;AACA;AACA;AACP;;AAEA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEO;AACA;AACA;AACA;AACP;AACA;;AAEA,qCAAqC,EAAE,OAAO,EAAE;AAChD;AACA,qCAAqC;AACrC;;AAEA;AACA;AACA,eAAe,iBAAiB;AAChC,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACO,kDAAkD;;AAElD;;AAEA;;AAEP;;AAEO;;AAEP;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEA;AACA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEP;AACA;AACA,WAAW,qBAAqB;AAChC,WAAW,iBAAiB;AAC5B,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iDAAiD,eAAe,iCAAiC,EAAE,gCAAgC;AACnI;;AAEA;AACA;AACA;AACA;AACA,qDAAqD,eAAe,iCAAiC,EAAE,gCAAgC;AACvI;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACO;;AAEP;AACA;;AAEA,qCAAqC,EAAE,YAAY,EAAE;AACrD;AACA,qCAAqC;AACrC;;AAEA;AACA;AACA,eAAe,iBAAiB;AAChC,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACO;AACP;AACA;;AAEA,uCAAuC,IAAI;AAC3C;AACA;AACA;AACA,uCAAuC,EAAE;AACzC;;AAEA;AACA;AACA,eAAe,iBAAiB;AAChC,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;;AAEA;AACA;AACA,eAAe,OAAO,gEAAgE,GAAG;AACzF,eAAe,QAAQ;AACvB,iBAAiB,cAAc,0BAA0B,mEAAmE,EAAE,GAAG;AACjI;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;AACV;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA,qBAAqB;AACrB;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;;AAGA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,uDAAuD,QAAQ;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,4BAA4B,sBAAsB;AAClD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,qCAAqC,uFAAwB;;AAE7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,sBAAsB;AACtB;AACA;AACA,kBAAkB;AAClB;AACA;AACA,yCAAyC,sDAAK;;AAE9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,sBAAsB;AACtB;AACA,sBAAsB;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B;AAC1B;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,kBAAkB;AAClB;AACA;AACA;AACA;;AAEA;AACA,yCAAyC,sDAAK;;AAE9C;AACA;AACA,uCAAuC,sDAAK;;AAE5C;AACA;AACA;AACA;AACA;AACA,2CAA2C,sDAAK;AAChD;AACA,0BAA0B;AAC1B;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,4BAA4B,mBAAmB;AAC/C;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B,cAAc;AACd,6BAA6B;AAC7B;AACA;AACA;;AAEA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,iBAAiB,YAAY;AAC7B,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;;AAEA;AACA;;AAEA;;AAEA;AACA;;AAEA;;AAEA;AACA;;AAEA;;AAEA;AACA,4BAA4B,8BAA8B;AAC1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA,wBAAwB,kBAAkB;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,UAAU;AACzB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA,gFAAgF,4CAA4C;AAC5H;;AAEA;;AAEA;AACA;AACA;AACA,UAAU;AACV;AACA;;AAEA;AACA;;AAEA,eAAe,+BAA+B;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qCAAqC,oDAAM;AAC3C;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,eAAe,mBAAmB;AAClC,eAAe,QAAQ;AACvB;AACA;AACA;AACA;;AAEA;AACA,kBAAkB,OAAO;AACzB;AACA;AACA;AACA;AACA;AACA,kCAAkC,UAAU;AAC5C;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA,gCAAgC,2BAA2B;AAC3D;;AAEA;AACA;;AAEA;AACA;AACA;AACA,aAAa;;AAEb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA,iDAAiD,kBAAkB;;AAEnE,wBAAwB,qBAAqB;;AAE7C;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,eAAe,YAAY;AAC3B,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;AACA;;AAEA;AACA;AACA;AACA,+BAA+B,2DAAW;AAC1C,gCAAgC,2DAAW;AAC3C;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,2DAAW;AAC1C,gCAAgC,2DAAW;AAC3C;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACA;AACA;;AAEP;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,eAAe,aAAa;AAC5B,iBAAiB,OAAO;AACxB;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA,UAAU;AACV;AACA;;AAEA;AACA,2DAA2D,SAAS,uEAAuE,8CAA8C;AACzL;AACA,mBAAmB,2DAAW;AAC9B;AACA;;AAEA;;AAEO;;AAEA;AACA;;AAEA;;AAEA;;AAEA;;AAEP;AACA;;AAEA;AACA,yCAAyC;AACzC;AACA;;AAEO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA,eAAe,4BAA4B;AAC3C;AACA,iBAAiB,8BAA8B;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;;AAEV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;;AAEA;AACA;AACA,qDAAqD,cAAc;AACnE;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;ACvwIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAIkB;AACoB;AAGnB;AAC0B;;;AAG7C;AACA;AACA,WAAW,YAAY;AACvB,WAAW,QAAQ;AACnB,aAAa,uBAAuB;AACpC;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,kCAAkC,gDAAO;AACzC,wCAAwC,2BAA2B;AACnE;AACA,oEAAoE,oBAAoB;AACxF;AACA;;AAEA,eAAe,cAAc;AAC7B;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,wBAAwB,oBAAoB;AAC5C;AACA;;AAEA,MAAM;AACN;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,cAAc;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,oBAAoB,OAAO;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,cAAc;AAC3B;AACO;AACP;AACA;;;AAGA;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,cAAc;AAC3B;AACO;AACP;AACA;;;AAGA;AACA,uBAAuB,QAAQ;AAC/B,yBAAyB,QAAQ;AACjC,0BAA0B,QAAQ;AAClC;AACA;AACA;AACA;;AAEA;AACA,cAAc,kCAAkC;AAChD,WAAW,GAAG;AACd,WAAW,QAAQ;AACnB,aAAa;AACb;AACA;AAC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AS;AACpB;AACA,WAAW,QAAQ;AACnB,WAAW,YAAY;AACvB;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB;AACA;AACA,WAAW,QAAQ;AACnB;AACA,WAAW,QAAQ;AACnB;AACA;AACA,WAAW,QAAQ;AACnB;AACA,WAAW,SAAS;AACpB;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,SAAS;AACpB,WAAW,SAAS;AACpB,aAAa,iBAAiB;AAC9B;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,qCAAqC,aAAa,uCAAuC,WAAW;AACpG;;AAEA;AACA,iDAAiD,cAAc,6BAA6B,aAAa;AACzG;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,yCAAyC,SAAS;AAClD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,2CAA2C;AAC3C;AACA;AACA;AACA,UAAU,OAAO;AACjB;AACA;AACA;;AAEA;AACA,oBAAoB,0CAAG;AACvB;AACA;AACA;;AAEA,oBAAoB,QAAQ;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,wBAAwB,iBAAiB;AACzC;AACA;;AAEA;AACA;AACA,4BAA4B,iBAAiB;AAC7C;AACA;AACA;AACA,4BAA4B,iBAAiB;AAC7C;AACA;AACA;;AAEA;AACA;AACA,0CAA0C,QAAQ;AAClD;AACA;AACA;AACA;;AAEA;AACA,wBAAwB,mBAAmB;AAC3C;AACA;;AAEA;;AAEA;AACA,wBAAwB,wBAAwB;AAChD;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,+BAA+B;AAC/B,wBAAwB,oCAAoC;AAC5D;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,yBAAyB,kDAAM;AAC/B;AACA,YAAY,8CAAM;AAClB,YAAY,8CAAM;AAClB;AACA;AACA;AACA;;AAEA,qCAAqC,cAAc;AACnD,oBAAoB,0BAA0B;AAC9C;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,gCAAgC,OAAO;AACvC;AACA;AACA;AACA;AACA,gCAAgC,OAAO;AACvC;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA,kBAAkB;AAClB,kEAAkE,QAAQ,eAAe,MAAM;AAC/F;AACA;AACA;AACA,6FAA6F,QAAQ;AACrG;AACA;;AAEA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,SAAS;AACpB,WAAW,QAAQ;AACnB;AACA,WAAW,SAAS;AACpB,aAAa,cAAc;AAC3B;AACO;AACP;AACA;AACA;AACA,EAAE,IAAI;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,KAAK;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD,cAAc,yCAAyC,aAAa;AACrH;;AAEA;AACA;;;;;;;;;;;;;;;;AC9rBO;;;;;;;;;;;;;;;;;;;;;;;;;;ACAP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,KAAK;AAChB,aAAa;AACb;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACA;AACO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP,oCAAoC,sBAAsB;AAC1D;;AAEA;AACA;AACA,WAAW,GAAG;AACd,aAAa,SAAS;AACtB;AACA;AACA;AACO;AACP;AACA;;;AAGA;AACA;AACA,WAAW,GAAG;AACd,aAAa,SAAS;AACtB;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,UAAU;AACvB;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,GAAG;AACd,aAAa,GAAG;AAChB,YAAY,OAAO;AACnB;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,KAAK;AAChC;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY,SAAS;AACrB,aAAa,OAAO;AACpB;AACO;AACP;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,aAAa,OAAO;AACpB;AACA;AACO;AACP;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,UAAU;AACrB,aAAa;AACb;AACO;AACP;AACA,UAAU;AACV;AACA;AACA,yBAAyB;AACzB;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;AC/JA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA,eAAe,6BAA6B;AAC5C;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,SAAS;AAC1B;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,KAAK;AACtB;AACA;AACA;AACA;;AAEA;AACA;AACA,gBAAgB,QAAQ;AACxB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,OAAO;AACtB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,KAAK;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,GAAG;AAClB,iBAAiB,GAAG;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,SAAS;AAC1B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,gBAAgB,QAAQ;AACxB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAAS;AACxB,eAAe,2BAA2B;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,cAAc;AAC/B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uCAAuC,sBAAsB;AAC7D,qCAAqC,sBAAsB;;AAE3D;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB,oBAAoB;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,eAAe,kBAAkB;AACjC,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;;AAEA;AACA,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,kBAAkB;AACnC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;AC7bA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,CAAC;;AAED;AACA,aAAa,2BAA2B;AACxC;;;;;;;;;;;;;;;;;;;;ACrBiC;;AAEW;;AAE5C;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP,eAAe,SAAS;AACxB;;AAEA;AACA;AACA,iBAAiB,yCAAI;AACrB;AACA,cAAc;AACd;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;;AAEM;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,cAAc,yBAAyB;;AAEhC;AACP;AACA,KAAK,qDAAY;AACjB,CAAC;;AAED,WAAW,0BAA0B;AAC9B;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;;;;;;;;;;;;;;;;AC1DD;AACA;AACA;AACA;AACA,UAAU,WAAW;AACrB;AACO,4BAA4B,KAAK;AACxC;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB,mBAAmB,QAAQ;AAC3B,qBAAqB,GAAG;AACxB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,eAAe,OAAO;AACtB,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA,CAAC;;;;;;;;;;;;;;;;;;;;;;ACjCD;AACA;AACA;AACA;AACA;;AAEoB;AACI;;AAEQ;AACa;;AAE7C;AACA,aAAa,QAAQ;AACrB,cAAc,UAAU;AACxB,cAAc,0CAA0C;AACxD;AACA;AACA,cAAc,QAAQ;AACtB,cAAc,SAAS;AACvB,cAAc,QAAQ;AACtB;AACA;AACA;;AAEA;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB;AACA,cAAc,QAAQ;AACtB,cAAc,qFAAqF;AACnG,cAAc,+EAA+E;AAC7F,cAAc,iCAAiC;AAC/C,cAAc,8DAA8D;AAC5E;;AAEA;AACA,aAAa,oDAAoD;AACjE;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B;AACA;AACA;AACA;;AAEA,sBAAsB,0CAAa;AACnC;AACA;AACA;;AAEA,wBAAwB,wCAAW;AACnC;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA,aAAa;AACb,UAAU;AACV;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,cAAc;AAC/B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB,sBAAsB;AACvC,gBAAgB,OAAO;AACvB;AACA;AACA,2BAA2B,wCAAW;AACtC;AACA;;AAEA;AACA;AACA;AACA,iBAAiB,eAAe;AAChC,gBAAgB,OAAO;AACvB;AACA;AACA,2BAA2B,wCAAW;AACtC,kCAAkC,wCAAwC;AAC1E;;AAEA;AACA;AACA;AACA,iBAAiB,iBAAiB;AAClC,gBAAgB,OAAO;AACvB;AACA;AACA,2BAA2B,wCAAW;AACtC;AACA;;AAEA;AACA;AACA;AACA;AACA,iBAAiB,iBAAiB;AAClC,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,YAAY;AACvB,WAAW,UAAU;AACrB,WAAW,UAAU;AACrB,aAAa,SAAS;AACtB;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,YAAY;AACvB,aAAa,gCAAgC;AAC7C;AACO;;AAEP,QAAQ,wCAAG;AACX;;AAEA,MAAM;AACN;AACA,wBAAwB,wCAAG;;AAE3B;AACA,qDAAqD,UAAU,QAAQ,OAAO;;AAE9E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,MAAM;AAC7D;AACA;AACA,kCAAkC,SAAS;AAC3C,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,SAAS;AACpB,aAAa,MAAM;AACnB,YAAY,OAAO;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,uDAAuD,OAAO;AAC9D,mBAAmB,QAAQ,KAAK,UAAU;AAC1C;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB;AACjB;AACA;;AAEA,uBAAuB,sCAAS;AAChC;;AAEA;AACA;AACA,UAAU;AACV;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,uBAAuB;AACtC,iBAAiB;AACjB;AACA;AACA;;AAEA,yBAAyB,sCAAS;;AAElC;AACA,kBAAkB,wCAAW,OAAO,yCAAY,gBAAgB,iBAAiB;AACjF,kBAAkB,wCAAW;;AAE7B,UAAU;AACV;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,iBAAiB;AAC5B,WAAW,UAAU;AACrB,aAAa,0CAA0C;AACvD;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,SAAS;AACpB,WAAW,mBAAmB;AAC9B;AACA;AACA,aAAa,qBAAqB;AAClC;AACO,iFAAiF;;AAExF,SAAS,wCAAG;AACZ;;AAEA;AACA;AACA,UAAU,UAAU,wCAAG;AACvB;AACA;AACA;;AAEA;AACA,IAAI,0DAAgB;AACpB;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA,kBAAkB,wCAAG;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;;AAEA,kBAAkB,wCAAG;AACrB;;AAEA;AACA,mDAAmD,wCAAG;AACtD;;AAEA,kBAAkB,wCAAG;AACrB;AACA,aAAa,wCAAG;AAChB;AACA;;AAEA;AACA,aAAa,wCAAG,uBAAuB,wCAAG;AAC1C;AACA;AACA;AACA;AACA;AACA,gBAAgB,wCAAG;AACnB;;AAEA;;AAEA;AACA,6BAA6B,wCAAG;;AAEhC;AACA,QAAQ,wCAAG;AACX,QAAQ,wCAAG;AACX,0BAA0B,MAAM;AAChC,0BAA0B,SAAS;AACnC;AACA;;AAEA;AACA;AACA;AACA;;AAEA,eAAe,QAAQ;AACvB;AACA;;AAEA;AACA;;AAEA,eAAe,iCAAiC;AAChD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA,YAAY,wCAAG;AACf;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C;AAC1C,kBAAkB;AAClB;AACA;AACA,oEAAoE,UAAU,MAAM,EAAE;AACtF;AACA,cAAc;AACd,wGAAwG,WAAW;AACnH,cAAc,UAAU,wCAAG;AAC3B,8GAA8G,WAAW;AACzH;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,6CAA6C,wCAAG;AAChD;AACA;AACA,mIAAmI,UAAU;AAC7I,kBAAkB;AAClB;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,IAAI,0DAAgB;AACpB;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA;AACA;;AAEA,eAAe,YAAY;AAC3B;;AAEA;AACA;AACA;AACA;;AAEA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,QAAQ,0DAAgB;AACxB;AACA;AACA;AACA;AACA,SAAS;AACT,MAAM;AACN;AACA,YAAY,0DAAgB;AAC5B;AACA;AACA,aAAa;AACb,SAAS;AACT;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,yEAAyE,IAAI;AAC7E,aAAa;;AAEb;;AAEA,IAAI,0DAAgB;AACpB;AACA;AACA;AACA,KAAK;;AAEL;AACA;;AAEA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,SAAS;AACpB,WAAW,mBAAmB;AAC9B,aAAa,iBAAiB;AAC9B;AACA;AACO,2EAA2E;AAClF;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,KAAK;AAChB,WAAW,UAAU;AACrB,aAAa,qBAAqB;AAClC;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,gBAAgB,cAAc;AAC9B;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,WAAW;AACtB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;;;;;;;;;;;;;;;;;;;AC9pBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEmC;AACH;AACK;;AAErC;AAC0B;;AAE1B;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,uCAAuC,QAAQ,qBAAqB,QAAQ;AAC5E;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,EAAE,SAAS,kCAAK;AAChB;;AAEA,yCAAyC,YAAY;AACrD;AACA;;AAEA,gBAAgB,aAAa,sCAAsC,yBAAyB;;AAE5F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,EAAE;AACF;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;;AAEP;AACA;AACA,eAAe,8BAA8B;AAC7C,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,kBAAkB;AACnC;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,qBAAqB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,UAAU;AACV,uDAAuD,aAAa;AACpE;AACA;;AAEA;AACA;AACA,eAAe,mCAAmC;AAClD,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,iBAAiB,mBAAmB;AACpC;AACA;AACA,+BAA+B,gDAAO;AACtC;AACA,0DAA0D,IAAI,KAAK,iBAAiB,EAAE,oBAAoB;AAC1G;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,MAAM;AACrB,iBAAiB,mBAAmB;AACpC;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;;AAEA,UAAU;AACV;AACA,wBAAwB,kCAAK;;AAE7B;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA,wEAAwE,oBAAoB;AAC5F;;AAEA;AACA;AACA,UAAU;AACV;AACA,UAAU;AACV,2DAA2D,eAAe;AAC1E;AACA;AACA,wDAAwD,YAAY;AACpE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mEAAmE,eAAe;AAClF;AACA;;AAEA;AACA;AACA,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,4CAA4C,sBAAsB;AAClE;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,4FAA4F,cAAc;AAC1G;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,4CAA4C,sBAAsB;AAClE;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C,sBAAsB;AAClE;AACA;AACA;AACA;AACA;AACA;AACA,4FAA4F,cAAc;AAC1G;AACA;;AAEA;;AAEA;AACA;AACA,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,4CAA4C,sBAAsB;AAClE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C,sBAAsB;AAClE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4FAA4F,cAAc;AAC1G;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,oBAAoB;AACnC,iBAAiB,mBAAmB;AACpC;AACA;AACA;AACA,MAAM,IAAI;;AAEV;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA,UAAU;AACV;AACA;;AAEA;AACA;AACA;AACA;AACA,0DAA0D,gBAAgB;AAC1E;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB;AACrB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB;AACrB;;AAEA;AACA,yDAAyD,gBAAgB;AACzE;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA,UAAU;AACV,gDAAgD,0BAA0B;AAC1E;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;;AAEb;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA,UAAU;AACV;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB;AACjB,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA,iBAAiB;AACjB;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,4CAA4C,eAAe;AAC3D;;AAEA;AACA,yBAAyB,8CAAM;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA,UAAU,qCAAqC;AAC/C;AACA,UAAU;AACV,2DAA2D,eAAe;AAC1E;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,mBAAmB;AAClC,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,cAAc;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA,wDAAwD;;AAExD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4FAA4F,cAAc;AAC1G;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA,UAAU,UAAU,wCAAG;AACvB;;AAEA,UAAU;AACV;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,eAAe,kCAAK;AACpB;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACvuBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,aAAa,gIAAgI;AAC7I,aAAa,gCAAgC;AAC7C,aAAa,4BAA4B;AACzC;;AAEA;AACA,WAAW,YAAY;AACvB;AACO;AACP;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,oBAAoB,gBAAgB;AACpC,wBAAwB,eAAe;AACvC;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;;AAGA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,4BAA4B,iBAAiB;AAC7C;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;;AAGA;AACA;AACA,cAAc,eAAe;AAC7B,WAAW,GAAG;AACd,WAAW,UAAU;AACrB,WAAW,UAAU;AACrB,aAAa,eAAe;AAC5B;AACO;AACP;AACA;AACA;AACA;;AAEA,yCAAyC,QAAQ;AACjD;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,oBAAoB,kBAAkB;AACtC;AACA,6CAA6C,QAAQ;AACrD;AACA;AACA;AACA;AACA;;AAEA;AACA;;;AAGA;AACA;AACA,cAAc,qBAAqB;AACnC,WAAW,GAAG;AACd,aAAa,GAAG;AAChB;AACO;AACP;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA,sBAAsB,GAAG;AACzB;;AAEA;AACA;AACA,cAAc,qBAAqB;AACnC,WAAW,GAAG;AACd,aAAa,GAAG;AAChB;AACO;AACP;AACA;;AAEA;AACA;AACA,mBAAmB,gBAAgB;AACnC;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA,sBAAsB,GAAG;AACzB;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,UAAU;AACrB,aAAa,QAAQ;AACrB;AACO;AACP;AACA,oBAAoB,iBAAiB;AACrC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,UAAU;AACrB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;;;AAGA;AACA;AACA,WAAW,qBAAqB;AAChC,aAAa,kBAAkB;AAC/B,YAAY,OAAO;AACnB;AACO;AACP;AACA;AACA;AACA,oBAAoB,gBAAgB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA,WAAW,wBAAwB;AACnC,aAAa,kBAAkB;AAC/B,YAAY,OAAO;AACnB;AACO;AACP;AACA;AACA;AACA,oBAAoB,gBAAgB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,gBAAgB,OAAO;AACvB;AACA;AACA,8BAA8B;AAC9B;AACA;;AAEA;;AAEA;AACA,wBAAwB,uBAAuB;AAC/C;AACA;AACA;AACA;;AAEA;AACA;AACA,wBAAwB,eAAe;AACvC;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,wBAAwB,yBAAyB;AACjD;AACA,gCAAgC,qBAAqB;AACrD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB,cAAc;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA,wBAAwB,oBAAoB;AAC5C;AACA;AACA;;AAEA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B,iBAAiB,cAAc;AAC/B;AACA;AACA;AACA,wBAAwB,gBAAgB;AACxC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B;AACA,gBAAgB,OAAO;AACvB;AACA,iBAAiB;AACjB;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B;AACA,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B,gBAAgB,OAAO;AACvB,iBAAiB;AACjB;AACA;AACA;AACA;;AAEA;AACA,wBAAwB,gBAAgB;AACxC;AACA;;AAEA;AACA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B,eAAe,QAAQ;AACvB,iBAAiB;AACjB;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,oCAAoC,eAAe;AACnD;AACA;AACA;AACA,UAAU;AACV;AACA,oCAAoC,eAAe;AACnD;AACA;AACA;AACA;;AAEA;AACA;AACA,yBAAyB,WAAW;AACpC;AACA;;AAEA;AACA,6BAA6B,eAAe;AAC5C;AACA;AACA,4CAA4C,WAAW;AACvD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB;AACjB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B,eAAe,QAAQ;AACvB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,oCAAoC,eAAe;AACnD;AACA;AACA;AACA,UAAU;AACV;AACA,oCAAoC,eAAe;AACnD;AACA;AACA;AACA;;AAEA;AACA;AACA,yBAAyB,WAAW;AACpC;AACA;AACA;AACA;;AAEA;AACA,6BAA6B,eAAe;AAC5C,uCAAuC,kBAAkB;AACzD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,wBAAwB,UAAU;AAClC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,iBAAiB;AACjB;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,wBAAwB,YAAY;AACpC;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,4BAA4B,eAAe;AAC3C;AACA;;AAEA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,4BAA4B,eAAe;AAC3C;AACA;AACA;AACA;AACA;AACA;;AAEA,wBAAwB,eAAe;AACvC;;AAEA;AACA;AACA;AACA;;AAEA,wBAAwB,gBAAgB;AACxC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;AAGA;AACA;AACA,WAAW,eAAe;AAC1B,WAAW,QAAQ;AACnB;AACO;;AAEP;AACA;AACA;;AAEA;AACA;;AAEA;AACA,qDAAqD;;AAErD;;AAEA,oBAAoB,iBAAiB;AACrC;;AAEA,sCAAsC,qBAAqB;AAC3D;AACA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA,WAAW,YAAY;AACvB,aAAa;AACb;AACO;AACP;AACA;;AAEA;;AAEA;AACA,UAAU,wBAAwB;AAClC;AACA;AACA;;AAEA;AACA,UAAU,wBAAwB;AAClC;AACA;;AAEA,oBAAoB,oBAAoB;AACxC,wBAAwB,oBAAoB;AAC5C;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,oBAAoB,oBAAoB,OAAO;AAC/C;AACA;AACA,oBAAoB,oBAAoB,OAAO;AAC/C;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gFAAgF,EAAE,IAAI,EAAE;AACxF;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACliCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAKoB;;AAIS;;AAEyB;;AAEtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;;AAED;AACA,aAAa,0BAA0B;AACvC,aAAa,4CAA4C;AACzD;;;AAGO;AACP,eAAe,UAAU;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,eAAe,UAAU;AACzB;AACA;AACA;;AAEA,eAAe,WAAW;AAC1B;AACA;AACA;;AAEA,eAAe,QAAQ;AACvB;AACA;AACA;;AAEA,eAAe,QAAQ;AACvB;AACA;AACA;;AAEA;;AAEA;AACA;AACA,eAAe,8CAA8C;AAC7D;AACA;AACA,YAAY,+DAAY;AACxB,yCAAyC,YAAY;AACrD,UAAU;AACV;AACA,kCAAkC,qDAAU;AAC5C,2BAA2B,UAAU;AACrC,2BAA2B,gEAAgE;AAC3F;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;;AAEA;AACA;AACA;AACA,SAAS;AACT;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB,UAAU;AAC3B;AACA;AACA;;AAEA;AACA;AACA,4BAA4B,gBAAgB;AAC5C;AACA;AACA,UAAU;AACV;AACA;;AAEA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;;AAEA;AACA,eAAe,eAAe;AAC9B,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA,4BAA4B,0BAA0B;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,KAAK;AACpB,iBAAiB;AACjB;AACA;AACA;AACA;;AAEA;AACA;AACA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EAA8E,QAAQ;AACtF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,iCAAiC;AACjC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,iCAAiC;AACjC;AACA;AACA;AACA;AACA;;AAEA;AACA,iCAAiC;AACjC;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;;AAEA;AACA;AACA,gBAAgB,WAAW;AAC3B,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA,wBAAwB,iBAAiB;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,aAAa;;AAEb;AACA;AACA,uDAAuD;AACvD;;AAEA;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,iCAAiC;AACjC;AACA;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;;AAEA;AACA,iCAAiC;AACjC;AACA;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA;AACA;A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/C;AACA;;AAEA,oBAAoB,eAAe;AACnC;AACA,wBAAwB,gBAAgB;AACxC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,sBAAsB;AACjC,aAAa,UAAU;AACvB;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,SAAS;AACT;AACA;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,QAAQ;AACnB,aAAa,UAAU;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACA,YAAY,OAAO;AACnB;AACA;AACA;AACA;AACA,6CAA6C,OAAO,gCAAgC,2CAA2C,YAAY,KAAK;AAChJ;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA,MAAM;;AAEN;;AAEA,wBAAwB,oBAAoB;AAC5C,oBAAoB,aAAa;;AAEjC;AACA,4BAA4B,iBAAiB;AAC7C;AACA;;AAEA,6EAA6E,QAAQ;AACrF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;AACA;AACA;;;AAGA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,aAAa;AACxB,WAAW,QAAQ;AACnB,WAAW,SAAS;AACpB,aAAa,UAAU;AACvB;AACO;AACP,iCAAiC,cAAc;AAC/C;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA,0CAA0C;AAC1C,yBAAyB;;AAEzB;AACA;AACA;;AAEA;AACA,oBAAoB,sBAAsB;;AAE1C;AACA;;AAEA,0EAA0E,QAAQ;AAClF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,oBAAoB,mBAAmB;AACvC;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;;;AAGA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,aAAa;AACxB,WAAW,SAAS;AACpB,aAAa,QAAQ;AACrB;AACO;AACP,iCAAiC,cAAc;;AAE/C;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,0CAA0C;AAC1C,yBAAyB;;AAEzB;AACA;AACA;;AAEA;AACA,oBAAoB,sBAAsB;;AAE1C;AACA;;AAEA,0EAA0E,QAAQ;AAClF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,wBAAwB,mBAAmB;AAC3C;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;;AAGA;AACA;AACA,0CAA0C,QAAQ;AAClD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,eAAe;AAC1B,aAAa,QAAQ;AACrB;AACO;AACP;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,MAAM;AACN;AACA,kDAAkD,kBAAkB;AACpE;AACA;AACA;;AAEO;AACP;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,aAAa,QAAQ;AACrB;AACO;AACP;AAC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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAE+B;AACA;AACH;AACI;AACA;AACH;;AAEI;AACA;AACC;AACD;;AAES;AACQ","sources":["webpack://@huggingface/transformers/ignored|/home/belem/github/transformers.js/src/backends|onnxruntime-node","webpack://@huggingface/transformers/ignored|/home/belem/github/transformers.js/src/utils|fs","webpack://@huggingface/transformers/ignored|/home/belem/github/transformers.js/src/utils|path","webpack://@huggingface/transformers/ignored|/home/belem/github/transformers.js/src/utils|sharp","webpack://@huggingface/transformers/ignored|/home/belem/github/transformers.js/src|fs","webpack://@huggingface/transformers/ignored|/home/belem/github/transformers.js/src|path","webpack://@huggingface/transformers/ignored|/home/belem/github/transformers.js/src|url","webpack://@huggingface/transformers/./node_modules/@huggingface/jinja/dist/index.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/backend-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/backend.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/env-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/env.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/index.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/inference-session.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/onnx-model.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/onnx-value.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-factory.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/trace.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/training-session-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/training-session.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/version.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs","webpack://@huggingface/transformers/./src/backends/onnx.js","webpack://@huggingface/transformers/./src/configs.js","webpack://@huggingface/transformers/./src/env.js","webpack://@huggingface/transformers/./src/generation/configuration_utils.js","webpack://@huggingface/transformers/./src/generation/logits_process.js","webpack://@huggingface/transformers/./src/generation/logits_sampler.js","webpack://@huggingface/transformers/./src/generation/stopping_criteria.js","webpack://@huggingface/transformers/./src/generation/streamers.js","webpack://@huggingface/transformers/./src/models.js","webpack://@huggingface/transformers/./src/models/whisper/common_whisper.js","webpack://@huggingface/transformers/./src/models/whisper/generation_whisper.js","webpack://@huggingface/transformers/./src/ops/registry.js","webpack://@huggingface/transformers/./src/pipelines.js","webpack://@huggingface/transformers/./src/processors.js","webpack://@huggingface/transformers/./src/tokenizers.js","webpack://@huggingface/transformers/./src/utils/audio.js","webpack://@huggingface/transformers/./src/utils/constants.js","webpack://@huggingface/transformers/./src/utils/core.js","webpack://@huggingface/transformers/./src/utils/data-structures.js","webpack://@huggingface/transformers/./src/utils/devices.js","webpack://@huggingface/transformers/./src/utils/dtypes.js","webpack://@huggingface/transformers/./src/utils/generic.js","webpack://@huggingface/transformers/./src/utils/hub.js","webpack://@huggingface/transformers/./src/utils/image.js","webpack://@huggingface/transformers/./src/utils/maths.js","webpack://@huggingface/transformers/./src/utils/tensor.js","webpack://@huggingface/transformers/webpack/bootstrap","webpack://@huggingface/transformers/webpack/runtime/create fake namespace object","webpack://@huggingface/transformers/webpack/runtime/define property getters","webpack://@huggingface/transformers/webpack/runtime/hasOwnProperty shorthand","webpack://@huggingface/transformers/webpack/runtime/make namespace object","webpack://@huggingface/transformers/webpack/runtime/publicPath","webpack://@huggingface/transformers/webpack/runtime/import chunk loading","webpack://@huggingface/transformers/./src/transformers.js"],"sourcesContent":["/* (ignored) */","/* (ignored) */","/* (ignored) */","/* (ignored) */","/* (ignored) */","/* (ignored) */","/* (ignored) */","// src/lexer.ts\nvar TOKEN_TYPES = Object.freeze({\n Text: \"Text\",\n // The text between Jinja statements or expressions\n NumericLiteral: \"NumericLiteral\",\n // e.g., 123\n BooleanLiteral: \"BooleanLiteral\",\n // true or false\n StringLiteral: \"StringLiteral\",\n // 'string'\n Identifier: \"Identifier\",\n // Variables, functions, etc.\n Equals: \"Equals\",\n // =\n OpenParen: \"OpenParen\",\n // (\n CloseParen: \"CloseParen\",\n // )\n OpenStatement: \"OpenStatement\",\n // {%\n CloseStatement: \"CloseStatement\",\n // %}\n OpenExpression: \"OpenExpression\",\n // {{\n CloseExpression: \"CloseExpression\",\n // }}\n OpenSquareBracket: \"OpenSquareBracket\",\n // [\n CloseSquareBracket: \"CloseSquareBracket\",\n // ]\n OpenCurlyBracket: \"OpenCurlyBracket\",\n // {\n CloseCurlyBracket: \"CloseCurlyBracket\",\n // }\n Comma: \"Comma\",\n // ,\n Dot: \"Dot\",\n // .\n Colon: \"Colon\",\n // :\n Pipe: \"Pipe\",\n // |\n CallOperator: \"CallOperator\",\n // ()\n AdditiveBinaryOperator: \"AdditiveBinaryOperator\",\n // + -\n MultiplicativeBinaryOperator: \"MultiplicativeBinaryOperator\",\n // * / %\n ComparisonBinaryOperator: \"ComparisonBinaryOperator\",\n // < > <= >= == !=\n UnaryOperator: \"UnaryOperator\",\n // ! - +\n // Keywords\n Set: \"Set\",\n If: \"If\",\n For: \"For\",\n In: \"In\",\n Is: \"Is\",\n NotIn: \"NotIn\",\n Else: \"Else\",\n EndIf: \"EndIf\",\n ElseIf: \"ElseIf\",\n EndFor: \"EndFor\",\n And: \"And\",\n Or: \"Or\",\n Not: \"UnaryOperator\",\n Macro: \"Macro\",\n EndMacro: \"EndMacro\"\n});\nvar KEYWORDS = Object.freeze({\n set: TOKEN_TYPES.Set,\n for: TOKEN_TYPES.For,\n in: TOKEN_TYPES.In,\n is: TOKEN_TYPES.Is,\n if: TOKEN_TYPES.If,\n else: TOKEN_TYPES.Else,\n endif: TOKEN_TYPES.EndIf,\n elif: TOKEN_TYPES.ElseIf,\n endfor: TOKEN_TYPES.EndFor,\n and: TOKEN_TYPES.And,\n or: TOKEN_TYPES.Or,\n not: TOKEN_TYPES.Not,\n \"not in\": TOKEN_TYPES.NotIn,\n macro: TOKEN_TYPES.Macro,\n endmacro: TOKEN_TYPES.EndMacro,\n // Literals\n true: TOKEN_TYPES.BooleanLiteral,\n false: TOKEN_TYPES.BooleanLiteral,\n // NOTE: According to the Jinja docs: The special constants true, false, and none are indeed lowercase.\n // Because that caused confusion in the past, (True used to expand to an undefined variable that was considered false),\n // all three can now also be written in title case (True, False, and None). However, for consistency, (all Jinja identifiers are lowercase)\n // you should use the lowercase versions.\n True: TOKEN_TYPES.BooleanLiteral,\n False: TOKEN_TYPES.BooleanLiteral\n});\nvar Token = class {\n /**\n * Constructs a new Token.\n * @param {string} value The raw value as seen inside the source code.\n * @param {TokenType} type The type of token.\n */\n constructor(value, type) {\n this.value = value;\n this.type = type;\n }\n};\nfunction isWord(char) {\n return /\\w/.test(char);\n}\nfunction isInteger(char) {\n return /[0-9]/.test(char);\n}\nvar ORDERED_MAPPING_TABLE = [\n // Control sequences\n [\"{%\", TOKEN_TYPES.OpenStatement],\n [\"%}\", TOKEN_TYPES.CloseStatement],\n [\"{{\", TOKEN_TYPES.OpenExpression],\n [\"}}\", TOKEN_TYPES.CloseExpression],\n // Single character tokens\n [\"(\", TOKEN_TYPES.OpenParen],\n [\")\", TOKEN_TYPES.CloseParen],\n [\"{\", TOKEN_TYPES.OpenCurlyBracket],\n [\"}\", TOKEN_TYPES.CloseCurlyBracket],\n [\"[\", TOKEN_TYPES.OpenSquareBracket],\n [\"]\", TOKEN_TYPES.CloseSquareBracket],\n [\",\", TOKEN_TYPES.Comma],\n [\".\", TOKEN_TYPES.Dot],\n [\":\", TOKEN_TYPES.Colon],\n [\"|\", TOKEN_TYPES.Pipe],\n // Comparison operators\n [\"<=\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\">=\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\"==\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\"!=\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\"<\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\">\", TOKEN_TYPES.ComparisonBinaryOperator],\n // Arithmetic operators\n [\"+\", TOKEN_TYPES.AdditiveBinaryOperator],\n [\"-\", TOKEN_TYPES.AdditiveBinaryOperator],\n [\"*\", TOKEN_TYPES.MultiplicativeBinaryOperator],\n [\"/\", TOKEN_TYPES.MultiplicativeBinaryOperator],\n [\"%\", TOKEN_TYPES.MultiplicativeBinaryOperator],\n // Assignment operator\n [\"=\", TOKEN_TYPES.Equals]\n];\nvar ESCAPE_CHARACTERS = /* @__PURE__ */ new Map([\n [\"n\", \"\\n\"],\n // New line\n [\"t\", \"\t\"],\n // Horizontal tab\n [\"r\", \"\\r\"],\n // Carriage return\n [\"b\", \"\\b\"],\n // Backspace\n [\"f\", \"\\f\"],\n // Form feed\n [\"v\", \"\\v\"],\n // Vertical tab\n [\"'\", \"'\"],\n // Single quote\n ['\"', '\"'],\n // Double quote\n [\"\\\\\", \"\\\\\"]\n // Backslash\n]);\nfunction preprocess(template, options = {}) {\n if (template.endsWith(\"\\n\")) {\n template = template.slice(0, -1);\n }\n template = template.replace(/{#.*?#}/gs, \"{##}\");\n if (options.lstrip_blocks) {\n template = template.replace(/^[ \\t]*({[#%])/gm, \"$1\");\n }\n if (options.trim_blocks) {\n template = template.replace(/([#%]})\\n/g, \"$1\");\n }\n return template.replace(/{##}/g, \"\").replace(/-%}\\s*/g, \"%}\").replace(/\\s*{%-/g, \"{%\").replace(/-}}\\s*/g, \"}}\").replace(/\\s*{{-/g, \"{{\");\n}\nfunction tokenize(source, options = {}) {\n const tokens = [];\n const src = preprocess(source, options);\n let cursorPosition = 0;\n const consumeWhile = (predicate) => {\n let str = \"\";\n while (predicate(src[cursorPosition])) {\n if (src[cursorPosition] === \"\\\\\") {\n ++cursorPosition;\n if (cursorPosition >= src.length)\n throw new SyntaxError(\"Unexpected end of input\");\n const escaped = src[cursorPosition++];\n const unescaped = ESCAPE_CHARACTERS.get(escaped);\n if (unescaped === void 0) {\n throw new SyntaxError(`Unexpected escaped character: ${escaped}`);\n }\n str += unescaped;\n continue;\n }\n str += src[cursorPosition++];\n if (cursorPosition >= src.length)\n throw new SyntaxError(\"Unexpected end of input\");\n }\n return str;\n };\n main:\n while (cursorPosition < src.length) {\n const lastTokenType = tokens.at(-1)?.type;\n if (lastTokenType === void 0 || lastTokenType === TOKEN_TYPES.CloseStatement || lastTokenType === TOKEN_TYPES.CloseExpression) {\n let text = \"\";\n while (cursorPosition < src.length && // Keep going until we hit the next Jinja statement or expression\n !(src[cursorPosition] === \"{\" && (src[cursorPosition + 1] === \"%\" || src[cursorPosition + 1] === \"{\"))) {\n text += src[cursorPosition++];\n }\n if (text.length > 0) {\n tokens.push(new Token(text, TOKEN_TYPES.Text));\n continue;\n }\n }\n consumeWhile((char2) => /\\s/.test(char2));\n const char = src[cursorPosition];\n if (char === \"-\" || char === \"+\") {\n const lastTokenType2 = tokens.at(-1)?.type;\n if (lastTokenType2 === TOKEN_TYPES.Text || lastTokenType2 === void 0) {\n throw new SyntaxError(`Unexpected character: ${char}`);\n }\n switch (lastTokenType2) {\n case TOKEN_TYPES.Identifier:\n case TOKEN_TYPES.NumericLiteral:\n case TOKEN_TYPES.BooleanLiteral:\n case TOKEN_TYPES.StringLiteral:\n case TOKEN_TYPES.CloseParen:\n case TOKEN_TYPES.CloseSquareBracket:\n break;\n default: {\n ++cursorPosition;\n const num = consumeWhile(isInteger);\n tokens.push(\n new Token(`${char}${num}`, num.length > 0 ? TOKEN_TYPES.NumericLiteral : TOKEN_TYPES.UnaryOperator)\n );\n continue;\n }\n }\n }\n for (const [char2, token] of ORDERED_MAPPING_TABLE) {\n const slice2 = src.slice(cursorPosition, cursorPosition + char2.length);\n if (slice2 === char2) {\n tokens.push(new Token(char2, token));\n cursorPosition += char2.length;\n continue main;\n }\n }\n if (char === \"'\" || char === '\"') {\n ++cursorPosition;\n const str = consumeWhile((c) => c !== char);\n tokens.push(new Token(str, TOKEN_TYPES.StringLiteral));\n ++cursorPosition;\n continue;\n }\n if (isInteger(char)) {\n const num = consumeWhile(isInteger);\n tokens.push(new Token(num, TOKEN_TYPES.NumericLiteral));\n continue;\n }\n if (isWord(char)) {\n const word = consumeWhile(isWord);\n const type = Object.hasOwn(KEYWORDS, word) ? KEYWORDS[word] : TOKEN_TYPES.Identifier;\n if (type === TOKEN_TYPES.In && tokens.at(-1)?.type === TOKEN_TYPES.Not) {\n tokens.pop();\n tokens.push(new Token(\"not in\", TOKEN_TYPES.NotIn));\n } else {\n tokens.push(new Token(word, type));\n }\n continue;\n }\n throw new SyntaxError(`Unexpected character: ${char}`);\n }\n return tokens;\n}\n\n// src/ast.ts\nvar Statement = class {\n type = \"Statement\";\n};\nvar Program = class extends Statement {\n constructor(body) {\n super();\n this.body = body;\n }\n type = \"Program\";\n};\nvar If = class extends Statement {\n constructor(test, body, alternate) {\n super();\n this.test = test;\n this.body = body;\n this.alternate = alternate;\n }\n type = \"If\";\n};\nvar For = class extends Statement {\n constructor(loopvar, iterable, body, defaultBlock) {\n super();\n this.loopvar = loopvar;\n this.iterable = iterable;\n this.body = body;\n this.defaultBlock = defaultBlock;\n }\n type = \"For\";\n};\nvar SetStatement = class extends Statement {\n constructor(assignee, value) {\n super();\n this.assignee = assignee;\n this.value = value;\n }\n type = \"Set\";\n};\nvar Macro = class extends Statement {\n constructor(name, args, body) {\n super();\n this.name = name;\n this.args = args;\n this.body = body;\n }\n type = \"Macro\";\n};\nvar Expression = class extends Statement {\n type = \"Expression\";\n};\nvar MemberExpression = class extends Expression {\n constructor(object, property, computed) {\n super();\n this.object = object;\n this.property = property;\n this.computed = computed;\n }\n type = \"MemberExpression\";\n};\nvar CallExpression = class extends Expression {\n constructor(callee, args) {\n super();\n this.callee = callee;\n this.args = args;\n }\n type = \"CallExpression\";\n};\nvar Identifier = class extends Expression {\n /**\n * @param {string} value The name of the identifier\n */\n constructor(value) {\n super();\n this.value = value;\n }\n type = \"Identifier\";\n};\nvar Literal = class extends Expression {\n constructor(value) {\n super();\n this.value = value;\n }\n type = \"Literal\";\n};\nvar NumericLiteral = class extends Literal {\n type = \"NumericLiteral\";\n};\nvar StringLiteral = class extends Literal {\n type = \"StringLiteral\";\n};\nvar BooleanLiteral = class extends Literal {\n type = \"BooleanLiteral\";\n};\nvar ArrayLiteral = class extends Literal {\n type = \"ArrayLiteral\";\n};\nvar TupleLiteral = class extends Literal {\n type = \"TupleLiteral\";\n};\nvar ObjectLiteral = class extends Literal {\n type = \"ObjectLiteral\";\n};\nvar BinaryExpression = class extends Expression {\n constructor(operator, left, right) {\n super();\n this.operator = operator;\n this.left = left;\n this.right = right;\n }\n type = \"BinaryExpression\";\n};\nvar FilterExpression = class extends Expression {\n constructor(operand, filter) {\n super();\n this.operand = operand;\n this.filter = filter;\n }\n type = \"FilterExpression\";\n};\nvar SelectExpression = class extends Expression {\n constructor(iterable, test) {\n super();\n this.iterable = iterable;\n this.test = test;\n }\n type = \"SelectExpression\";\n};\nvar TestExpression = class extends Expression {\n constructor(operand, negate, test) {\n super();\n this.operand = operand;\n this.negate = negate;\n this.test = test;\n }\n type = \"TestExpression\";\n};\nvar UnaryExpression = class extends Expression {\n constructor(operator, argument) {\n super();\n this.operator = operator;\n this.argument = argument;\n }\n type = \"UnaryExpression\";\n};\nvar SliceExpression = class extends Expression {\n constructor(start = void 0, stop = void 0, step = void 0) {\n super();\n this.start = start;\n this.stop = stop;\n this.step = step;\n }\n type = \"SliceExpression\";\n};\nvar KeywordArgumentExpression = class extends Expression {\n constructor(key, value) {\n super();\n this.key = key;\n this.value = value;\n }\n type = \"KeywordArgumentExpression\";\n};\n\n// src/parser.ts\nfunction parse(tokens) {\n const program = new Program([]);\n let current = 0;\n function expect(type, error) {\n const prev = tokens[current++];\n if (!prev || prev.type !== type) {\n throw new Error(`Parser Error: ${error}. ${prev.type} !== ${type}.`);\n }\n return prev;\n }\n function parseAny() {\n switch (tokens[current].type) {\n case TOKEN_TYPES.Text:\n return parseText();\n case TOKEN_TYPES.OpenStatement:\n return parseJinjaStatement();\n case TOKEN_TYPES.OpenExpression:\n return parseJinjaExpression();\n default:\n throw new SyntaxError(`Unexpected token type: ${tokens[current].type}`);\n }\n }\n function not(...types) {\n return current + types.length <= tokens.length && types.some((type, i) => type !== tokens[current + i].type);\n }\n function is(...types) {\n return current + types.length <= tokens.length && types.every((type, i) => type === tokens[current + i].type);\n }\n function parseText() {\n return new StringLiteral(expect(TOKEN_TYPES.Text, \"Expected text token\").value);\n }\n function parseJinjaStatement() {\n expect(TOKEN_TYPES.OpenStatement, \"Expected opening statement token\");\n let result;\n switch (tokens[current].type) {\n case TOKEN_TYPES.Set:\n ++current;\n result = parseSetStatement();\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n break;\n case TOKEN_TYPES.If:\n ++current;\n result = parseIfStatement();\n expect(TOKEN_TYPES.OpenStatement, \"Expected {% token\");\n expect(TOKEN_TYPES.EndIf, \"Expected endif token\");\n expect(TOKEN_TYPES.CloseStatement, \"Expected %} token\");\n break;\n case TOKEN_TYPES.Macro:\n ++current;\n result = parseMacroStatement();\n expect(TOKEN_TYPES.OpenStatement, \"Expected {% token\");\n expect(TOKEN_TYPES.EndMacro, \"Expected endmacro token\");\n expect(TOKEN_TYPES.CloseStatement, \"Expected %} token\");\n break;\n case TOKEN_TYPES.For:\n ++current;\n result = parseForStatement();\n expect(TOKEN_TYPES.OpenStatement, \"Expected {% token\");\n expect(TOKEN_TYPES.EndFor, \"Expected endfor token\");\n expect(TOKEN_TYPES.CloseStatement, \"Expected %} token\");\n break;\n default:\n throw new SyntaxError(`Unknown statement type: ${tokens[current].type}`);\n }\n return result;\n }\n function parseJinjaExpression() {\n expect(TOKEN_TYPES.OpenExpression, \"Expected opening expression token\");\n const result = parseExpression();\n expect(TOKEN_TYPES.CloseExpression, \"Expected closing expression token\");\n return result;\n }\n function parseSetStatement() {\n const left = parseExpression();\n if (is(TOKEN_TYPES.Equals)) {\n ++current;\n const value = parseSetStatement();\n return new SetStatement(left, value);\n }\n return left;\n }\n function parseIfStatement() {\n const test = parseExpression();\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n const body = [];\n const alternate = [];\n while (!(tokens[current]?.type === TOKEN_TYPES.OpenStatement && (tokens[current + 1]?.type === TOKEN_TYPES.ElseIf || tokens[current + 1]?.type === TOKEN_TYPES.Else || tokens[current + 1]?.type === TOKEN_TYPES.EndIf))) {\n body.push(parseAny());\n }\n if (tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type !== TOKEN_TYPES.EndIf) {\n ++current;\n if (is(TOKEN_TYPES.ElseIf)) {\n expect(TOKEN_TYPES.ElseIf, \"Expected elseif token\");\n alternate.push(parseIfStatement());\n } else {\n expect(TOKEN_TYPES.Else, \"Expected else token\");\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n while (!(tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type === TOKEN_TYPES.EndIf)) {\n alternate.push(parseAny());\n }\n }\n }\n return new If(test, body, alternate);\n }\n function parseMacroStatement() {\n const name = parsePrimaryExpression();\n if (name.type !== \"Identifier\") {\n throw new SyntaxError(`Expected identifier following macro statement`);\n }\n const args = parseArgs();\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n const body = [];\n while (not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.EndMacro)) {\n body.push(parseAny());\n }\n return new Macro(name, args, body);\n }\n function parseExpressionSequence(primary = false) {\n const fn = primary ? parsePrimaryExpression : parseExpression;\n const expressions = [fn()];\n const isTuple = is(TOKEN_TYPES.Comma);\n while (isTuple) {\n ++current;\n expressions.push(fn());\n if (!is(TOKEN_TYPES.Comma)) {\n break;\n }\n }\n return isTuple ? new TupleLiteral(expressions) : expressions[0];\n }\n function parseForStatement() {\n const loopVariable = parseExpressionSequence(true);\n if (!(loopVariable instanceof Identifier || loopVariable instanceof TupleLiteral)) {\n throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${loopVariable.type} instead`);\n }\n expect(TOKEN_TYPES.In, \"Expected `in` keyword following loop variable\");\n const iterable = parseExpression();\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n const body = [];\n while (not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.EndFor) && not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.Else)) {\n body.push(parseAny());\n }\n const alternative = [];\n if (is(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.Else)) {\n ++current;\n ++current;\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n while (not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.EndFor)) {\n alternative.push(parseAny());\n }\n }\n return new For(loopVariable, iterable, body, alternative);\n }\n function parseExpression() {\n return parseIfExpression();\n }\n function parseIfExpression() {\n const a = parseLogicalOrExpression();\n if (is(TOKEN_TYPES.If)) {\n ++current;\n const predicate = parseLogicalOrExpression();\n if (is(TOKEN_TYPES.Else)) {\n ++current;\n const b = parseLogicalOrExpression();\n return new If(predicate, [a], [b]);\n } else {\n return new SelectExpression(a, predicate);\n }\n }\n return a;\n }\n function parseLogicalOrExpression() {\n let left = parseLogicalAndExpression();\n while (is(TOKEN_TYPES.Or)) {\n const operator = tokens[current];\n ++current;\n const right = parseLogicalAndExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseLogicalAndExpression() {\n let left = parseLogicalNegationExpression();\n while (is(TOKEN_TYPES.And)) {\n const operator = tokens[current];\n ++current;\n const right = parseLogicalNegationExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseLogicalNegationExpression() {\n let right;\n while (is(TOKEN_TYPES.Not)) {\n const operator = tokens[current];\n ++current;\n const arg = parseLogicalNegationExpression();\n right = new UnaryExpression(operator, arg);\n }\n return right ?? parseComparisonExpression();\n }\n function parseComparisonExpression() {\n let left = parseAdditiveExpression();\n while (is(TOKEN_TYPES.ComparisonBinaryOperator) || is(TOKEN_TYPES.In) || is(TOKEN_TYPES.NotIn)) {\n const operator = tokens[current];\n ++current;\n const right = parseAdditiveExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseAdditiveExpression() {\n let left = parseMultiplicativeExpression();\n while (is(TOKEN_TYPES.AdditiveBinaryOperator)) {\n const operator = tokens[current];\n ++current;\n const right = parseMultiplicativeExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseCallMemberExpression() {\n const member = parseMemberExpression();\n if (is(TOKEN_TYPES.OpenParen)) {\n return parseCallExpression(member);\n }\n return member;\n }\n function parseCallExpression(callee) {\n let callExpression = new CallExpression(callee, parseArgs());\n if (is(TOKEN_TYPES.OpenParen)) {\n callExpression = parseCallExpression(callExpression);\n }\n return callExpression;\n }\n function parseArgs() {\n expect(TOKEN_TYPES.OpenParen, \"Expected opening parenthesis for arguments list\");\n const args = parseArgumentsList();\n expect(TOKEN_TYPES.CloseParen, \"Expected closing parenthesis for arguments list\");\n return args;\n }\n function parseArgumentsList() {\n const args = [];\n while (!is(TOKEN_TYPES.CloseParen)) {\n let argument = parseExpression();\n if (is(TOKEN_TYPES.Equals)) {\n ++current;\n if (!(argument instanceof Identifier)) {\n throw new SyntaxError(`Expected identifier for keyword argument`);\n }\n const value = parseExpression();\n argument = new KeywordArgumentExpression(argument, value);\n }\n args.push(argument);\n if (is(TOKEN_TYPES.Comma)) {\n ++current;\n }\n }\n return args;\n }\n function parseMemberExpressionArgumentsList() {\n const slices = [];\n let isSlice = false;\n while (!is(TOKEN_TYPES.CloseSquareBracket)) {\n if (is(TOKEN_TYPES.Colon)) {\n slices.push(void 0);\n ++current;\n isSlice = true;\n } else {\n slices.push(parseExpression());\n if (is(TOKEN_TYPES.Colon)) {\n ++current;\n isSlice = true;\n }\n }\n }\n if (slices.length === 0) {\n throw new SyntaxError(`Expected at least one argument for member/slice expression`);\n }\n if (isSlice) {\n if (slices.length > 3) {\n throw new SyntaxError(`Expected 0-3 arguments for slice expression`);\n }\n return new SliceExpression(...slices);\n }\n return slices[0];\n }\n function parseMemberExpression() {\n let object = parsePrimaryExpression();\n while (is(TOKEN_TYPES.Dot) || is(TOKEN_TYPES.OpenSquareBracket)) {\n const operator = tokens[current];\n ++current;\n let property;\n const computed = operator.type !== TOKEN_TYPES.Dot;\n if (computed) {\n property = parseMemberExpressionArgumentsList();\n expect(TOKEN_TYPES.CloseSquareBracket, \"Expected closing square bracket\");\n } else {\n property = parsePrimaryExpression();\n if (property.type !== \"Identifier\") {\n throw new SyntaxError(`Expected identifier following dot operator`);\n }\n }\n object = new MemberExpression(object, property, computed);\n }\n return object;\n }\n function parseMultiplicativeExpression() {\n let left = parseTestExpression();\n while (is(TOKEN_TYPES.MultiplicativeBinaryOperator)) {\n const operator = tokens[current];\n ++current;\n const right = parseTestExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseTestExpression() {\n let operand = parseFilterExpression();\n while (is(TOKEN_TYPES.Is)) {\n ++current;\n const negate = is(TOKEN_TYPES.Not);\n if (negate) {\n ++current;\n }\n let filter = parsePrimaryExpression();\n if (filter instanceof BooleanLiteral) {\n filter = new Identifier(filter.value.toString());\n }\n if (!(filter instanceof Identifier)) {\n throw new SyntaxError(`Expected identifier for the test`);\n }\n operand = new TestExpression(operand, negate, filter);\n }\n return operand;\n }\n function parseFilterExpression() {\n let operand = parseCallMemberExpression();\n while (is(TOKEN_TYPES.Pipe)) {\n ++current;\n let filter = parsePrimaryExpression();\n if (!(filter instanceof Identifier)) {\n throw new SyntaxError(`Expected identifier for the filter`);\n }\n if (is(TOKEN_TYPES.OpenParen)) {\n filter = parseCallExpression(filter);\n }\n operand = new FilterExpression(operand, filter);\n }\n return operand;\n }\n function parsePrimaryExpression() {\n const token = tokens[current];\n switch (token.type) {\n case TOKEN_TYPES.NumericLiteral:\n ++current;\n return new NumericLiteral(Number(token.value));\n case TOKEN_TYPES.StringLiteral:\n ++current;\n return new StringLiteral(token.value);\n case TOKEN_TYPES.BooleanLiteral:\n ++current;\n return new BooleanLiteral(token.value.toLowerCase() === \"true\");\n case TOKEN_TYPES.Identifier:\n ++current;\n return new Identifier(token.value);\n case TOKEN_TYPES.OpenParen: {\n ++current;\n const expression = parseExpressionSequence();\n if (tokens[current].type !== TOKEN_TYPES.CloseParen) {\n throw new SyntaxError(`Expected closing parenthesis, got ${tokens[current].type} instead`);\n }\n ++current;\n return expression;\n }\n case TOKEN_TYPES.OpenSquareBracket: {\n ++current;\n const values = [];\n while (!is(TOKEN_TYPES.CloseSquareBracket)) {\n values.push(parseExpression());\n if (is(TOKEN_TYPES.Comma)) {\n ++current;\n }\n }\n ++current;\n return new ArrayLiteral(values);\n }\n case TOKEN_TYPES.OpenCurlyBracket: {\n ++current;\n const values = /* @__PURE__ */ new Map();\n while (!is(TOKEN_TYPES.CloseCurlyBracket)) {\n const key = parseExpression();\n expect(TOKEN_TYPES.Colon, \"Expected colon between key and value in object literal\");\n const value = parseExpression();\n values.set(key, value);\n if (is(TOKEN_TYPES.Comma)) {\n ++current;\n }\n }\n ++current;\n return new ObjectLiteral(values);\n }\n default:\n throw new SyntaxError(`Unexpected token: ${token.type}`);\n }\n }\n while (current < tokens.length) {\n program.body.push(parseAny());\n }\n return program;\n}\n\n// src/utils.ts\nfunction range(start, stop, step = 1) {\n if (stop === void 0) {\n stop = start;\n start = 0;\n }\n const result = [];\n for (let i = start; i < stop; i += step) {\n result.push(i);\n }\n return result;\n}\nfunction slice(array, start, stop, step = 1) {\n const direction = Math.sign(step);\n if (direction >= 0) {\n start = (start ??= 0) < 0 ? Math.max(array.length + start, 0) : Math.min(start, array.length);\n stop = (stop ??= array.length) < 0 ? Math.max(array.length + stop, 0) : Math.min(stop, array.length);\n } else {\n start = (start ??= array.length - 1) < 0 ? Math.max(array.length + start, -1) : Math.min(start, array.length - 1);\n stop = (stop ??= -1) < -1 ? Math.max(array.length + stop, -1) : Math.min(stop, array.length - 1);\n }\n const result = [];\n for (let i = start; direction * i < direction * stop; i += step) {\n result.push(array[i]);\n }\n return result;\n}\nfunction titleCase(value) {\n return value.replace(/\\b\\w/g, (c) => c.toUpperCase());\n}\n\n// src/runtime.ts\nvar RuntimeValue = class {\n type = \"RuntimeValue\";\n value;\n /**\n * A collection of built-in functions for this type.\n */\n builtins = /* @__PURE__ */ new Map();\n /**\n * Creates a new RuntimeValue.\n */\n constructor(value = void 0) {\n this.value = value;\n }\n /**\n * Determines truthiness or falsiness of the runtime value.\n * This function should be overridden by subclasses if it has custom truthiness criteria.\n * @returns {BooleanValue} BooleanValue(true) if the value is truthy, BooleanValue(false) otherwise.\n */\n __bool__() {\n return new BooleanValue(!!this.value);\n }\n};\nvar NumericValue = class extends RuntimeValue {\n type = \"NumericValue\";\n};\nvar StringValue = class extends RuntimeValue {\n type = \"StringValue\";\n builtins = /* @__PURE__ */ new Map([\n [\n \"upper\",\n new FunctionValue(() => {\n return new StringValue(this.value.toUpperCase());\n })\n ],\n [\n \"lower\",\n new FunctionValue(() => {\n return new StringValue(this.value.toLowerCase());\n })\n ],\n [\n \"strip\",\n new FunctionValue(() => {\n return new StringValue(this.value.trim());\n })\n ],\n [\n \"title\",\n new FunctionValue(() => {\n return new StringValue(titleCase(this.value));\n })\n ],\n [\"length\", new NumericValue(this.value.length)]\n ]);\n};\nvar BooleanValue = class extends RuntimeValue {\n type = \"BooleanValue\";\n};\nvar ObjectValue = class extends RuntimeValue {\n type = \"ObjectValue\";\n /**\n * NOTE: necessary to override since all JavaScript arrays are considered truthy,\n * while only non-empty Python arrays are consider truthy.\n *\n * e.g.,\n * - JavaScript: {} && 5 -> 5\n * - Python: {} and 5 -> {}\n */\n __bool__() {\n return new BooleanValue(this.value.size > 0);\n }\n builtins = /* @__PURE__ */ new Map([\n [\n \"get\",\n new FunctionValue(([key, defaultValue]) => {\n if (!(key instanceof StringValue)) {\n throw new Error(`Object key must be a string: got ${key.type}`);\n }\n return this.value.get(key.value) ?? defaultValue ?? new NullValue();\n })\n ],\n [\n \"items\",\n new FunctionValue(() => {\n return new ArrayValue(\n Array.from(this.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value]))\n );\n })\n ]\n ]);\n};\nvar KeywordArgumentsValue = class extends ObjectValue {\n type = \"KeywordArgumentsValue\";\n};\nvar ArrayValue = class extends RuntimeValue {\n type = \"ArrayValue\";\n builtins = /* @__PURE__ */ new Map([[\"length\", new NumericValue(this.value.length)]]);\n /**\n * NOTE: necessary to override since all JavaScript arrays are considered truthy,\n * while only non-empty Python arrays are consider truthy.\n *\n * e.g.,\n * - JavaScript: [] && 5 -> 5\n * - Python: [] and 5 -> []\n */\n __bool__() {\n return new BooleanValue(this.value.length > 0);\n }\n};\nvar TupleValue = class extends ArrayValue {\n type = \"TupleValue\";\n};\nvar FunctionValue = class extends RuntimeValue {\n type = \"FunctionValue\";\n};\nvar NullValue = class extends RuntimeValue {\n type = \"NullValue\";\n};\nvar UndefinedValue = class extends RuntimeValue {\n type = \"UndefinedValue\";\n};\nvar Environment = class {\n constructor(parent) {\n this.parent = parent;\n }\n /**\n * The variables declared in this environment.\n */\n variables = /* @__PURE__ */ new Map([\n [\n \"namespace\",\n new FunctionValue((args) => {\n if (args.length === 0) {\n return new ObjectValue(/* @__PURE__ */ new Map());\n }\n if (args.length !== 1 || !(args[0] instanceof ObjectValue)) {\n throw new Error(\"`namespace` expects either zero arguments or a single object argument\");\n }\n return args[0];\n })\n ]\n ]);\n /**\n * The tests available in this environment.\n */\n tests = /* @__PURE__ */ new Map([\n [\"boolean\", (operand) => operand.type === \"BooleanValue\"],\n [\"callable\", (operand) => operand instanceof FunctionValue],\n [\n \"odd\",\n (operand) => {\n if (operand.type !== \"NumericValue\") {\n throw new Error(`Cannot apply test \"odd\" to type: ${operand.type}`);\n }\n return operand.value % 2 !== 0;\n }\n ],\n [\n \"even\",\n (operand) => {\n if (operand.type !== \"NumericValue\") {\n throw new Error(`Cannot apply test \"even\" to type: ${operand.type}`);\n }\n return operand.value % 2 === 0;\n }\n ],\n [\"false\", (operand) => operand.type === \"BooleanValue\" && !operand.value],\n [\"true\", (operand) => operand.type === \"BooleanValue\" && operand.value],\n [\"string\", (operand) => operand.type === \"StringValue\"],\n [\"number\", (operand) => operand.type === \"NumericValue\"],\n [\"integer\", (operand) => operand.type === \"NumericValue\" && Number.isInteger(operand.value)],\n [\"iterable\", (operand) => operand instanceof ArrayValue || operand instanceof StringValue],\n [\n \"lower\",\n (operand) => {\n const str = operand.value;\n return operand.type === \"StringValue\" && str === str.toLowerCase();\n }\n ],\n [\n \"upper\",\n (operand) => {\n const str = operand.value;\n return operand.type === \"StringValue\" && str === str.toUpperCase();\n }\n ],\n [\"none\", (operand) => operand.type === \"NullValue\"],\n [\"defined\", (operand) => operand.type !== \"UndefinedValue\"],\n [\"undefined\", (operand) => operand.type === \"UndefinedValue\"],\n [\"equalto\", (a, b) => a.value === b.value],\n [\"eq\", (a, b) => a.value === b.value]\n ]);\n /**\n * Set the value of a variable in the current environment.\n */\n set(name, value) {\n return this.declareVariable(name, convertToRuntimeValues(value));\n }\n declareVariable(name, value) {\n if (this.variables.has(name)) {\n throw new SyntaxError(`Variable already declared: ${name}`);\n }\n this.variables.set(name, value);\n return value;\n }\n // private assignVariable(name: string, value: AnyRuntimeValue): AnyRuntimeValue {\n // \tconst env = this.resolve(name);\n // \tenv.variables.set(name, value);\n // \treturn value;\n // }\n /**\n * Set variable in the current scope.\n * See https://jinja.palletsprojects.com/en/3.0.x/templates/#assignments for more information.\n */\n setVariable(name, value) {\n this.variables.set(name, value);\n return value;\n }\n /**\n * Resolve the environment in which the variable is declared.\n * @param {string} name The name of the variable.\n * @returns {Environment} The environment in which the variable is declared.\n */\n resolve(name) {\n if (this.variables.has(name)) {\n return this;\n }\n if (this.parent) {\n return this.parent.resolve(name);\n }\n throw new Error(`Unknown variable: ${name}`);\n }\n lookupVariable(name) {\n try {\n return this.resolve(name).variables.get(name) ?? new UndefinedValue();\n } catch {\n return new UndefinedValue();\n }\n }\n};\nvar Interpreter = class {\n global;\n constructor(env) {\n this.global = env ?? new Environment();\n }\n /**\n * Run the program.\n */\n run(program) {\n return this.evaluate(program, this.global);\n }\n /**\n * Evaluates expressions following the binary operation type.\n */\n evaluateBinaryExpression(node, environment) {\n const left = this.evaluate(node.left, environment);\n switch (node.operator.value) {\n case \"and\":\n return left.__bool__().value ? this.evaluate(node.right, environment) : left;\n case \"or\":\n return left.__bool__().value ? left : this.evaluate(node.right, environment);\n }\n const right = this.evaluate(node.right, environment);\n switch (node.operator.value) {\n case \"==\":\n return new BooleanValue(left.value == right.value);\n case \"!=\":\n return new BooleanValue(left.value != right.value);\n }\n if (left instanceof UndefinedValue || right instanceof UndefinedValue) {\n throw new Error(\"Cannot perform operation on undefined values\");\n } else if (left instanceof NullValue || right instanceof NullValue) {\n throw new Error(\"Cannot perform operation on null values\");\n } else if (left instanceof NumericValue && right instanceof NumericValue) {\n switch (node.operator.value) {\n case \"+\":\n return new NumericValue(left.value + right.value);\n case \"-\":\n return new NumericValue(left.value - right.value);\n case \"*\":\n return new NumericValue(left.value * right.value);\n case \"/\":\n return new NumericValue(left.value / right.value);\n case \"%\":\n return new NumericValue(left.value % right.value);\n case \"<\":\n return new BooleanValue(left.value < right.value);\n case \">\":\n return new BooleanValue(left.value > right.value);\n case \">=\":\n return new BooleanValue(left.value >= right.value);\n case \"<=\":\n return new BooleanValue(left.value <= right.value);\n }\n } else if (left instanceof ArrayValue && right instanceof ArrayValue) {\n switch (node.operator.value) {\n case \"+\":\n return new ArrayValue(left.value.concat(right.value));\n }\n } else if (right instanceof ArrayValue) {\n const member = right.value.find((x) => x.value === left.value) !== void 0;\n switch (node.operator.value) {\n case \"in\":\n return new BooleanValue(member);\n case \"not in\":\n return new BooleanValue(!member);\n }\n }\n if (left instanceof StringValue || right instanceof StringValue) {\n switch (node.operator.value) {\n case \"+\":\n return new StringValue(left.value.toString() + right.value.toString());\n }\n }\n if (left instanceof StringValue && right instanceof StringValue) {\n switch (node.operator.value) {\n case \"in\":\n return new BooleanValue(right.value.includes(left.value));\n case \"not in\":\n return new BooleanValue(!right.value.includes(left.value));\n }\n }\n if (left instanceof StringValue && right instanceof ObjectValue) {\n switch (node.operator.value) {\n case \"in\":\n return new BooleanValue(right.value.has(left.value));\n case \"not in\":\n return new BooleanValue(!right.value.has(left.value));\n }\n }\n throw new SyntaxError(`Unknown operator \"${node.operator.value}\" between ${left.type} and ${right.type}`);\n }\n evaluateArguments(args, environment) {\n const positionalArguments = [];\n const keywordArguments = /* @__PURE__ */ new Map();\n for (const argument of args) {\n if (argument.type === \"KeywordArgumentExpression\") {\n const kwarg = argument;\n keywordArguments.set(kwarg.key.value, this.evaluate(kwarg.value, environment));\n } else {\n if (keywordArguments.size > 0) {\n throw new Error(\"Positional arguments must come before keyword arguments\");\n }\n positionalArguments.push(this.evaluate(argument, environment));\n }\n }\n return [positionalArguments, keywordArguments];\n }\n /**\n * Evaluates expressions following the filter operation type.\n */\n evaluateFilterExpression(node, environment) {\n const operand = this.evaluate(node.operand, environment);\n if (node.filter.type === \"Identifier\") {\n const filter = node.filter;\n if (filter.value === \"tojson\") {\n return new StringValue(toJSON(operand));\n }\n if (operand instanceof ArrayValue) {\n switch (filter.value) {\n case \"list\":\n return operand;\n case \"first\":\n return operand.value[0];\n case \"last\":\n return operand.value[operand.value.length - 1];\n case \"length\":\n return new NumericValue(operand.value.length);\n case \"reverse\":\n return new ArrayValue(operand.value.reverse());\n case \"sort\":\n return new ArrayValue(\n operand.value.sort((a, b) => {\n if (a.type !== b.type) {\n throw new Error(`Cannot compare different types: ${a.type} and ${b.type}`);\n }\n switch (a.type) {\n case \"NumericValue\":\n return a.value - b.value;\n case \"StringValue\":\n return a.value.localeCompare(b.value);\n default:\n throw new Error(`Cannot compare type: ${a.type}`);\n }\n })\n );\n default:\n throw new Error(`Unknown ArrayValue filter: ${filter.value}`);\n }\n } else if (operand instanceof StringValue) {\n switch (filter.value) {\n case \"length\":\n return new NumericValue(operand.value.length);\n case \"upper\":\n return new StringValue(operand.value.toUpperCase());\n case \"lower\":\n return new StringValue(operand.value.toLowerCase());\n case \"title\":\n return new StringValue(titleCase(operand.value));\n case \"capitalize\":\n return new StringValue(operand.value.charAt(0).toUpperCase() + operand.value.slice(1));\n case \"trim\":\n return new StringValue(operand.value.trim());\n case \"indent\":\n return new StringValue(\n operand.value.split(\"\\n\").map(\n (x, i) => (\n // By default, don't indent the first line or empty lines\n i === 0 || x.length === 0 ? x : \" \" + x\n )\n ).join(\"\\n\")\n );\n case \"string\":\n return operand;\n default:\n throw new Error(`Unknown StringValue filter: ${filter.value}`);\n }\n } else if (operand instanceof NumericValue) {\n switch (filter.value) {\n case \"abs\":\n return new NumericValue(Math.abs(operand.value));\n default:\n throw new Error(`Unknown NumericValue filter: ${filter.value}`);\n }\n } else if (operand instanceof ObjectValue) {\n switch (filter.value) {\n case \"items\":\n return new ArrayValue(\n Array.from(operand.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value]))\n );\n case \"length\":\n return new NumericValue(operand.value.size);\n default:\n throw new Error(`Unknown ObjectValue filter: ${filter.value}`);\n }\n }\n throw new Error(`Cannot apply filter \"${filter.value}\" to type: ${operand.type}`);\n } else if (node.filter.type === \"CallExpression\") {\n const filter = node.filter;\n if (filter.callee.type !== \"Identifier\") {\n throw new Error(`Unknown filter: ${filter.callee.type}`);\n }\n const filterName = filter.callee.value;\n if (filterName === \"tojson\") {\n const [, kwargs] = this.evaluateArguments(filter.args, environment);\n const indent = kwargs.get(\"indent\") ?? new NullValue();\n if (!(indent instanceof NumericValue || indent instanceof NullValue)) {\n throw new Error(\"If set, indent must be a number\");\n }\n return new StringValue(toJSON(operand, indent.value));\n }\n if (operand instanceof ArrayValue) {\n switch (filterName) {\n case \"selectattr\": {\n if (operand.value.some((x) => !(x instanceof ObjectValue))) {\n throw new Error(\"`selectattr` can only be applied to array of objects\");\n }\n if (filter.args.some((x) => x.type !== \"StringLiteral\")) {\n throw new Error(\"arguments of `selectattr` must be strings\");\n }\n const [attr, testName, value] = filter.args.map((x) => this.evaluate(x, environment));\n let testFunction;\n if (testName) {\n const test = environment.tests.get(testName.value);\n if (!test) {\n throw new Error(`Unknown test: ${testName.value}`);\n }\n testFunction = test;\n } else {\n testFunction = (...x) => x[0].__bool__().value;\n }\n const filtered = operand.value.filter((item) => {\n const a = item.value.get(attr.value);\n if (a) {\n return testFunction(a, value);\n }\n return false;\n });\n return new ArrayValue(filtered);\n }\n case \"map\": {\n const [, kwargs] = this.evaluateArguments(filter.args, environment);\n if (kwargs.has(\"attribute\")) {\n const attr = kwargs.get(\"attribute\");\n if (!(attr instanceof StringValue)) {\n throw new Error(\"attribute must be a string\");\n }\n const defaultValue = kwargs.get(\"default\");\n const mapped = operand.value.map((item) => {\n if (!(item instanceof ObjectValue)) {\n throw new Error(\"items in map must be an object\");\n }\n return item.value.get(attr.value) ?? defaultValue ?? new UndefinedValue();\n });\n return new ArrayValue(mapped);\n } else {\n throw new Error(\"`map` expressions without `attribute` set are not currently supported.\");\n }\n }\n }\n throw new Error(`Unknown ArrayValue filter: ${filterName}`);\n } else if (operand instanceof StringValue) {\n switch (filterName) {\n case \"indent\": {\n const [args, kwargs] = this.evaluateArguments(filter.args, environment);\n const width = args.at(0) ?? kwargs.get(\"width\") ?? new NumericValue(4);\n if (!(width instanceof NumericValue)) {\n throw new Error(\"width must be a number\");\n }\n const first = args.at(1) ?? kwargs.get(\"first\") ?? new BooleanValue(false);\n const blank = args.at(2) ?? kwargs.get(\"blank\") ?? new BooleanValue(false);\n const lines = operand.value.split(\"\\n\");\n const indent = \" \".repeat(width.value);\n const indented = lines.map(\n (x, i) => !first.value && i === 0 || !blank.value && x.length === 0 ? x : indent + x\n );\n return new StringValue(indented.join(\"\\n\"));\n }\n }\n throw new Error(`Unknown StringValue filter: ${filterName}`);\n } else {\n throw new Error(`Cannot apply filter \"${filterName}\" to type: ${operand.type}`);\n }\n }\n throw new Error(`Unknown filter: ${node.filter.type}`);\n }\n /**\n * Evaluates expressions following the test operation type.\n */\n evaluateTestExpression(node, environment) {\n const operand = this.evaluate(node.operand, environment);\n const test = environment.tests.get(node.test.value);\n if (!test) {\n throw new Error(`Unknown test: ${node.test.value}`);\n }\n const result = test(operand);\n return new BooleanValue(node.negate ? !result : result);\n }\n /**\n * Evaluates expressions following the unary operation type.\n */\n evaluateUnaryExpression(node, environment) {\n const argument = this.evaluate(node.argument, environment);\n switch (node.operator.value) {\n case \"not\":\n return new BooleanValue(!argument.value);\n default:\n throw new SyntaxError(`Unknown operator: ${node.operator.value}`);\n }\n }\n evalProgram(program, environment) {\n return this.evaluateBlock(program.body, environment);\n }\n evaluateBlock(statements, environment) {\n let result = \"\";\n for (const statement of statements) {\n const lastEvaluated = this.evaluate(statement, environment);\n if (lastEvaluated.type !== \"NullValue\" && lastEvaluated.type !== \"UndefinedValue\") {\n result += lastEvaluated.value;\n }\n }\n return new StringValue(result);\n }\n evaluateIdentifier(node, environment) {\n return environment.lookupVariable(node.value);\n }\n evaluateCallExpression(expr, environment) {\n const [args, kwargs] = this.evaluateArguments(expr.args, environment);\n if (kwargs.size > 0) {\n args.push(new KeywordArgumentsValue(kwargs));\n }\n const fn = this.evaluate(expr.callee, environment);\n if (fn.type !== \"FunctionValue\") {\n throw new Error(`Cannot call something that is not a function: got ${fn.type}`);\n }\n return fn.value(args, environment);\n }\n evaluateSliceExpression(object, expr, environment) {\n if (!(object instanceof ArrayValue || object instanceof StringValue)) {\n throw new Error(\"Slice object must be an array or string\");\n }\n const start = this.evaluate(expr.start, environment);\n const stop = this.evaluate(expr.stop, environment);\n const step = this.evaluate(expr.step, environment);\n if (!(start instanceof NumericValue || start instanceof UndefinedValue)) {\n throw new Error(\"Slice start must be numeric or undefined\");\n }\n if (!(stop instanceof NumericValue || stop instanceof UndefinedValue)) {\n throw new Error(\"Slice stop must be numeric or undefined\");\n }\n if (!(step instanceof NumericValue || step instanceof UndefinedValue)) {\n throw new Error(\"Slice step must be numeric or undefined\");\n }\n if (object instanceof ArrayValue) {\n return new ArrayValue(slice(object.value, start.value, stop.value, step.value));\n } else {\n return new StringValue(slice(Array.from(object.value), start.value, stop.value, step.value).join(\"\"));\n }\n }\n evaluateMemberExpression(expr, environment) {\n const object = this.evaluate(expr.object, environment);\n let property;\n if (expr.computed) {\n if (expr.property.type === \"SliceExpression\") {\n return this.evaluateSliceExpression(object, expr.property, environment);\n } else {\n property = this.evaluate(expr.property, environment);\n }\n } else {\n property = new StringValue(expr.property.value);\n }\n let value;\n if (object instanceof ObjectValue) {\n if (!(property instanceof StringValue)) {\n throw new Error(`Cannot access property with non-string: got ${property.type}`);\n }\n value = object.value.get(property.value) ?? object.builtins.get(property.value);\n } else if (object instanceof ArrayValue || object instanceof StringValue) {\n if (property instanceof NumericValue) {\n value = object.value.at(property.value);\n if (object instanceof StringValue) {\n value = new StringValue(object.value.at(property.value));\n }\n } else if (property instanceof StringValue) {\n value = object.builtins.get(property.value);\n } else {\n throw new Error(`Cannot access property with non-string/non-number: got ${property.type}`);\n }\n } else {\n if (!(property instanceof StringValue)) {\n throw new Error(`Cannot access property with non-string: got ${property.type}`);\n }\n value = object.builtins.get(property.value);\n }\n return value instanceof RuntimeValue ? value : new UndefinedValue();\n }\n evaluateSet(node, environment) {\n const rhs = this.evaluate(node.value, environment);\n if (node.assignee.type === \"Identifier\") {\n const variableName = node.assignee.value;\n environment.setVariable(variableName, rhs);\n } else if (node.assignee.type === \"MemberExpression\") {\n const member = node.assignee;\n const object = this.evaluate(member.object, environment);\n if (!(object instanceof ObjectValue)) {\n throw new Error(\"Cannot assign to member of non-object\");\n }\n if (member.property.type !== \"Identifier\") {\n throw new Error(\"Cannot assign to member with non-identifier property\");\n }\n object.value.set(member.property.value, rhs);\n } else {\n throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(node.assignee)}`);\n }\n return new NullValue();\n }\n evaluateIf(node, environment) {\n const test = this.evaluate(node.test, environment);\n return this.evaluateBlock(test.__bool__().value ? node.body : node.alternate, environment);\n }\n evaluateFor(node, environment) {\n const scope = new Environment(environment);\n let test, iterable;\n if (node.iterable.type === \"SelectExpression\") {\n const select = node.iterable;\n iterable = this.evaluate(select.iterable, scope);\n test = select.test;\n } else {\n iterable = this.evaluate(node.iterable, scope);\n }\n if (!(iterable instanceof ArrayValue)) {\n throw new Error(`Expected iterable type in for loop: got ${iterable.type}`);\n }\n const items = [];\n const scopeUpdateFunctions = [];\n for (let i = 0; i < iterable.value.length; ++i) {\n const loopScope = new Environment(scope);\n const current = iterable.value[i];\n let scopeUpdateFunction;\n if (node.loopvar.type === \"Identifier\") {\n scopeUpdateFunction = (scope2) => scope2.setVariable(node.loopvar.value, current);\n } else if (node.loopvar.type === \"TupleLiteral\") {\n const loopvar = node.loopvar;\n if (current.type !== \"ArrayValue\") {\n throw new Error(`Cannot unpack non-iterable type: ${current.type}`);\n }\n const c = current;\n if (loopvar.value.length !== c.value.length) {\n throw new Error(`Too ${loopvar.value.length > c.value.length ? \"few\" : \"many\"} items to unpack`);\n }\n scopeUpdateFunction = (scope2) => {\n for (let j = 0; j < loopvar.value.length; ++j) {\n if (loopvar.value[j].type !== \"Identifier\") {\n throw new Error(`Cannot unpack non-identifier type: ${loopvar.value[j].type}`);\n }\n scope2.setVariable(loopvar.value[j].value, c.value[j]);\n }\n };\n } else {\n throw new Error(`Invalid loop variable(s): ${node.loopvar.type}`);\n }\n if (test) {\n scopeUpdateFunction(loopScope);\n const testValue = this.evaluate(test, loopScope);\n if (!testValue.__bool__().value) {\n continue;\n }\n }\n items.push(current);\n scopeUpdateFunctions.push(scopeUpdateFunction);\n }\n let result = \"\";\n let noIteration = true;\n for (let i = 0; i < items.length; ++i) {\n const loop = /* @__PURE__ */ new Map([\n [\"index\", new NumericValue(i + 1)],\n [\"index0\", new NumericValue(i)],\n [\"revindex\", new NumericValue(items.length - i)],\n [\"revindex0\", new NumericValue(items.length - i - 1)],\n [\"first\", new BooleanValue(i === 0)],\n [\"last\", new BooleanValue(i === items.length - 1)],\n [\"length\", new NumericValue(items.length)],\n [\"previtem\", i > 0 ? items[i - 1] : new UndefinedValue()],\n [\"nextitem\", i < items.length - 1 ? items[i + 1] : new UndefinedValue()]\n ]);\n scope.setVariable(\"loop\", new ObjectValue(loop));\n scopeUpdateFunctions[i](scope);\n const evaluated = this.evaluateBlock(node.body, scope);\n result += evaluated.value;\n noIteration = false;\n }\n if (noIteration) {\n const defaultEvaluated = this.evaluateBlock(node.defaultBlock, scope);\n result += defaultEvaluated.value;\n }\n return new StringValue(result);\n }\n /**\n * See https://jinja.palletsprojects.com/en/3.1.x/templates/#macros for more information.\n */\n evaluateMacro(node, environment) {\n environment.setVariable(\n node.name.value,\n new FunctionValue((args, scope) => {\n const macroScope = new Environment(scope);\n args = args.slice();\n let kwargs;\n if (args.at(-1)?.type === \"KeywordArgumentsValue\") {\n kwargs = args.pop();\n }\n for (let i = 0; i < node.args.length; ++i) {\n const nodeArg = node.args[i];\n const passedArg = args[i];\n if (nodeArg.type === \"Identifier\") {\n const identifier = nodeArg;\n if (!passedArg) {\n throw new Error(`Missing positional argument: ${identifier.value}`);\n }\n macroScope.setVariable(identifier.value, passedArg);\n } else if (nodeArg.type === \"KeywordArgumentExpression\") {\n const kwarg = nodeArg;\n const value = passedArg ?? // Try positional arguments first\n kwargs?.value.get(kwarg.key.value) ?? // Look in user-passed kwargs\n this.evaluate(kwarg.value, macroScope);\n macroScope.setVariable(kwarg.key.value, value);\n } else {\n throw new Error(`Unknown argument type: ${nodeArg.type}`);\n }\n }\n return this.evaluateBlock(node.body, macroScope);\n })\n );\n return new NullValue();\n }\n evaluate(statement, environment) {\n if (statement === void 0)\n return new UndefinedValue();\n switch (statement.type) {\n case \"Program\":\n return this.evalProgram(statement, environment);\n case \"Set\":\n return this.evaluateSet(statement, environment);\n case \"If\":\n return this.evaluateIf(statement, environment);\n case \"For\":\n return this.evaluateFor(statement, environment);\n case \"Macro\":\n return this.evaluateMacro(statement, environment);\n case \"NumericLiteral\":\n return new NumericValue(Number(statement.value));\n case \"StringLiteral\":\n return new StringValue(statement.value);\n case \"BooleanLiteral\":\n return new BooleanValue(statement.value);\n case \"ArrayLiteral\":\n return new ArrayValue(statement.value.map((x) => this.evaluate(x, environment)));\n case \"TupleLiteral\":\n return new TupleValue(statement.value.map((x) => this.evaluate(x, environment)));\n case \"ObjectLiteral\": {\n const mapping = /* @__PURE__ */ new Map();\n for (const [key, value] of statement.value) {\n const evaluatedKey = this.evaluate(key, environment);\n if (!(evaluatedKey instanceof StringValue)) {\n throw new Error(`Object keys must be strings: got ${evaluatedKey.type}`);\n }\n mapping.set(evaluatedKey.value, this.evaluate(value, environment));\n }\n return new ObjectValue(mapping);\n }\n case \"Identifier\":\n return this.evaluateIdentifier(statement, environment);\n case \"CallExpression\":\n return this.evaluateCallExpression(statement, environment);\n case \"MemberExpression\":\n return this.evaluateMemberExpression(statement, environment);\n case \"UnaryExpression\":\n return this.evaluateUnaryExpression(statement, environment);\n case \"BinaryExpression\":\n return this.evaluateBinaryExpression(statement, environment);\n case \"FilterExpression\":\n return this.evaluateFilterExpression(statement, environment);\n case \"TestExpression\":\n return this.evaluateTestExpression(statement, environment);\n default:\n throw new SyntaxError(`Unknown node type: ${statement.type}`);\n }\n }\n};\nfunction convertToRuntimeValues(input) {\n switch (typeof input) {\n case \"number\":\n return new NumericValue(input);\n case \"string\":\n return new StringValue(input);\n case \"boolean\":\n return new BooleanValue(input);\n case \"undefined\":\n return new UndefinedValue();\n case \"object\":\n if (input === null) {\n return new NullValue();\n } else if (Array.isArray(input)) {\n return new ArrayValue(input.map(convertToRuntimeValues));\n } else {\n return new ObjectValue(\n new Map(Object.entries(input).map(([key, value]) => [key, convertToRuntimeValues(value)]))\n );\n }\n case \"function\":\n return new FunctionValue((args, _scope) => {\n const result = input(...args.map((x) => x.value)) ?? null;\n return convertToRuntimeValues(result);\n });\n default:\n throw new Error(`Cannot convert to runtime value: ${input}`);\n }\n}\nfunction toJSON(input, indent, depth) {\n const currentDepth = depth ?? 0;\n switch (input.type) {\n case \"NullValue\":\n case \"UndefinedValue\":\n return \"null\";\n case \"NumericValue\":\n case \"StringValue\":\n case \"BooleanValue\":\n return JSON.stringify(input.value);\n case \"ArrayValue\":\n case \"ObjectValue\": {\n const indentValue = indent ? \" \".repeat(indent) : \"\";\n const basePadding = \"\\n\" + indentValue.repeat(currentDepth);\n const childrenPadding = basePadding + indentValue;\n if (input.type === \"ArrayValue\") {\n const core = input.value.map((x) => toJSON(x, indent, currentDepth + 1));\n return indent ? `[${childrenPadding}${core.join(`,${childrenPadding}`)}${basePadding}]` : `[${core.join(\", \")}]`;\n } else {\n const core = Array.from(input.value.entries()).map(([key, value]) => {\n const v = `\"${key}\": ${toJSON(value, indent, currentDepth + 1)}`;\n return indent ? `${childrenPadding}${v}` : v;\n });\n return indent ? `{${core.join(\",\")}${basePadding}}` : `{${core.join(\", \")}}`;\n }\n }\n default:\n throw new Error(`Cannot convert to JSON: ${input.type}`);\n }\n}\n\n// src/index.ts\nvar Template = class {\n parsed;\n /**\n * @param {string} template The template string\n */\n constructor(template) {\n const tokens = tokenize(template, {\n lstrip_blocks: true,\n trim_blocks: true\n });\n this.parsed = parse(tokens);\n }\n render(items) {\n const env = new Environment();\n env.set(\"false\", false);\n env.set(\"true\", true);\n env.set(\"raise_exception\", (args) => {\n throw new Error(args);\n });\n env.set(\"range\", range);\n for (const [key, value] of Object.entries(items)) {\n env.set(key, value);\n }\n const interpreter = new Interpreter(env);\n const result = interpreter.run(this.parsed);\n return result.value;\n }\n};\nexport {\n Environment,\n Interpreter,\n Template,\n parse,\n tokenize\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nconst backends = new Map();\nconst backendsSortedByPriority = [];\n/**\n * Register a backend.\n *\n * @param name - the name as a key to lookup as an execution provider.\n * @param backend - the backend object.\n * @param priority - an integer indicating the priority of the backend. Higher number means higher priority. if priority\n * < 0, it will be considered as a 'beta' version and will not be used as a fallback backend by default.\n *\n * @ignore\n */\nexport const registerBackend = (name, backend, priority) => {\n if (backend && typeof backend.init === 'function' && typeof backend.createInferenceSessionHandler === 'function') {\n const currentBackend = backends.get(name);\n if (currentBackend === undefined) {\n backends.set(name, { backend, priority });\n }\n else if (currentBackend.priority > priority) {\n // same name is already registered with a higher priority. skip registeration.\n return;\n }\n else if (currentBackend.priority === priority) {\n if (currentBackend.backend !== backend) {\n throw new Error(`cannot register backend \"${name}\" using priority ${priority}`);\n }\n }\n if (priority >= 0) {\n const i = backendsSortedByPriority.indexOf(name);\n if (i !== -1) {\n backendsSortedByPriority.splice(i, 1);\n }\n for (let i = 0; i < backendsSortedByPriority.length; i++) {\n if (backends.get(backendsSortedByPriority[i]).priority <= priority) {\n backendsSortedByPriority.splice(i, 0, name);\n return;\n }\n }\n backendsSortedByPriority.push(name);\n }\n return;\n }\n throw new TypeError('not a valid backend');\n};\n/**\n * Try to resolve and initialize a backend.\n *\n * @param backendName - the name of the backend.\n * @returns the backend instance if resolved and initialized successfully, or an error message if failed.\n */\nconst tryResolveAndInitializeBackend = async (backendName) => {\n const backendInfo = backends.get(backendName);\n if (!backendInfo) {\n return 'backend not found.';\n }\n if (backendInfo.initialized) {\n return backendInfo.backend;\n }\n else if (backendInfo.aborted) {\n return backendInfo.error;\n }\n else {\n const isInitializing = !!backendInfo.initPromise;\n try {\n if (!isInitializing) {\n backendInfo.initPromise = backendInfo.backend.init(backendName);\n }\n await backendInfo.initPromise;\n backendInfo.initialized = true;\n return backendInfo.backend;\n }\n catch (e) {\n if (!isInitializing) {\n backendInfo.error = `${e}`;\n backendInfo.aborted = true;\n }\n return backendInfo.error;\n }\n finally {\n delete backendInfo.initPromise;\n }\n }\n};\n/**\n * Resolve execution providers from the specific session options.\n *\n * @param options - the session options object.\n * @returns a promise that resolves to a tuple of an initialized backend instance and a session options object with\n * filtered EP list.\n *\n * @ignore\n */\nexport const resolveBackendAndExecutionProviders = async (options) => {\n // extract backend hints from session options\n const eps = options.executionProviders || [];\n const backendHints = eps.map(i => typeof i === 'string' ? i : i.name);\n const backendNames = backendHints.length === 0 ? backendsSortedByPriority : backendHints;\n // try to resolve and initialize all requested backends\n let backend;\n const errors = [];\n const availableBackendNames = new Set();\n for (const backendName of backendNames) {\n const resolveResult = await tryResolveAndInitializeBackend(backendName);\n if (typeof resolveResult === 'string') {\n errors.push({ name: backendName, err: resolveResult });\n }\n else {\n if (!backend) {\n backend = resolveResult;\n }\n if (backend === resolveResult) {\n availableBackendNames.add(backendName);\n }\n }\n }\n // if no backend is available, throw error.\n if (!backend) {\n throw new Error(`no available backend found. ERR: ${errors.map(e => `[${e.name}] ${e.err}`).join(', ')}`);\n }\n // for each explicitly requested backend, if it's not available, output warning message.\n for (const { name, err } of errors) {\n if (backendHints.includes(name)) {\n // eslint-disable-next-line no-console\n console.warn(`removing requested execution provider \"${name}\" from session options because it is not available: ${err}`);\n }\n }\n const filteredEps = eps.filter(i => availableBackendNames.has(typeof i === 'string' ? i : i.name));\n return [\n backend, new Proxy(options, {\n get: (target, prop) => {\n if (prop === 'executionProviders') {\n return filteredEps;\n }\n return Reflect.get(target, prop);\n }\n })\n ];\n};\n//# sourceMappingURL=backend-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nexport { registerBackend } from './backend-impl.js';\n//# sourceMappingURL=backend.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { version } from './version.js';\nlet logLevelValue = 'warning';\nexport const env = {\n wasm: {},\n webgl: {},\n webgpu: {},\n versions: { common: version },\n set logLevel(value) {\n if (value === undefined) {\n return;\n }\n if (typeof value !== 'string' || ['verbose', 'info', 'warning', 'error', 'fatal'].indexOf(value) === -1) {\n throw new Error(`Unsupported logging level: ${value}`);\n }\n logLevelValue = value;\n },\n get logLevel() {\n return logLevelValue;\n },\n};\n// set property 'logLevel' so that they can be correctly transferred to worker by `postMessage()`.\nObject.defineProperty(env, 'logLevel', { enumerable: true });\n//# sourceMappingURL=env-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { env as envImpl } from './env-impl.js';\n/**\n * Represent a set of flags as a global singleton.\n */\nexport const env = envImpl;\n//# sourceMappingURL=env.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n/**\n * # ONNX Runtime JavaScript API\n *\n * ONNX Runtime JavaScript API is a unified API for all JavaScript usages, including the following NPM packages:\n *\n * - [onnxruntime-node](https://www.npmjs.com/package/onnxruntime-node)\n * - [onnxruntime-web](https://www.npmjs.com/package/onnxruntime-web)\n * - [onnxruntime-react-native](https://www.npmjs.com/package/onnxruntime-react-native)\n *\n * See also:\n * - [Get Started](https://onnxruntime.ai/docs/get-started/with-javascript/)\n * - [Inference examples](https://github.com/microsoft/onnxruntime-inference-examples/tree/main/js)\n *\n * @packageDocumentation\n */\nexport * from './backend.js';\nexport * from './env.js';\nexport * from './inference-session.js';\nexport * from './tensor.js';\nexport * from './tensor-conversion.js';\nexport * from './tensor-factory.js';\nexport * from './trace.js';\nexport * from './onnx-model.js';\nexport * from './onnx-value.js';\nexport * from './training-session.js';\n//# sourceMappingURL=index.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { resolveBackendAndExecutionProviders } from './backend-impl.js';\nimport { Tensor } from './tensor.js';\nimport { TRACE_FUNC_BEGIN, TRACE_FUNC_END } from './trace.js';\nexport class InferenceSession {\n constructor(handler) {\n this.handler = handler;\n }\n async run(feeds, arg1, arg2) {\n TRACE_FUNC_BEGIN();\n const fetches = {};\n let options = {};\n // check inputs\n if (typeof feeds !== 'object' || feeds === null || feeds instanceof Tensor || Array.isArray(feeds)) {\n throw new TypeError('\\'feeds\\' must be an object that use input names as keys and OnnxValue as corresponding values.');\n }\n let isFetchesEmpty = true;\n // determine which override is being used\n if (typeof arg1 === 'object') {\n if (arg1 === null) {\n throw new TypeError('Unexpected argument[1]: cannot be null.');\n }\n if (arg1 instanceof Tensor) {\n throw new TypeError('\\'fetches\\' cannot be a Tensor');\n }\n if (Array.isArray(arg1)) {\n if (arg1.length === 0) {\n throw new TypeError('\\'fetches\\' cannot be an empty array.');\n }\n isFetchesEmpty = false;\n // output names\n for (const name of arg1) {\n if (typeof name !== 'string') {\n throw new TypeError('\\'fetches\\' must be a string array or an object.');\n }\n if (this.outputNames.indexOf(name) === -1) {\n throw new RangeError(`'fetches' contains invalid output name: ${name}.`);\n }\n fetches[name] = null;\n }\n if (typeof arg2 === 'object' && arg2 !== null) {\n options = arg2;\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else {\n // decide whether arg1 is fetches or options\n // if any output name is present and its value is valid OnnxValue, we consider it fetches\n let isFetches = false;\n const arg1Keys = Object.getOwnPropertyNames(arg1);\n for (const name of this.outputNames) {\n if (arg1Keys.indexOf(name) !== -1) {\n const v = arg1[name];\n if (v === null || v instanceof Tensor) {\n isFetches = true;\n isFetchesEmpty = false;\n fetches[name] = v;\n }\n }\n }\n if (isFetches) {\n if (typeof arg2 === 'object' && arg2 !== null) {\n options = arg2;\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else {\n options = arg1;\n }\n }\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('Unexpected argument[1]: must be \\'fetches\\' or \\'options\\'.');\n }\n // check if all inputs are in feed\n for (const name of this.inputNames) {\n if (typeof feeds[name] === 'undefined') {\n throw new Error(`input '${name}' is missing in 'feeds'.`);\n }\n }\n // if no fetches is specified, we use the full output names list\n if (isFetchesEmpty) {\n for (const name of this.outputNames) {\n fetches[name] = null;\n }\n }\n // feeds, fetches and options are prepared\n const results = await this.handler.run(feeds, fetches, options);\n const returnValue = {};\n for (const key in results) {\n if (Object.hasOwnProperty.call(results, key)) {\n const result = results[key];\n if (result instanceof Tensor) {\n returnValue[key] = result;\n }\n else {\n returnValue[key] = new Tensor(result.type, result.data, result.dims);\n }\n }\n }\n TRACE_FUNC_END();\n return returnValue;\n }\n async release() {\n return this.handler.dispose();\n }\n static async create(arg0, arg1, arg2, arg3) {\n TRACE_FUNC_BEGIN();\n // either load from a file or buffer\n let filePathOrUint8Array;\n let options = {};\n if (typeof arg0 === 'string') {\n filePathOrUint8Array = arg0;\n if (typeof arg1 === 'object' && arg1 !== null) {\n options = arg1;\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else if (arg0 instanceof Uint8Array) {\n filePathOrUint8Array = arg0;\n if (typeof arg1 === 'object' && arg1 !== null) {\n options = arg1;\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else if (arg0 instanceof ArrayBuffer ||\n (typeof SharedArrayBuffer !== 'undefined' && arg0 instanceof SharedArrayBuffer)) {\n const buffer = arg0;\n let byteOffset = 0;\n let byteLength = arg0.byteLength;\n if (typeof arg1 === 'object' && arg1 !== null) {\n options = arg1;\n }\n else if (typeof arg1 === 'number') {\n byteOffset = arg1;\n if (!Number.isSafeInteger(byteOffset)) {\n throw new RangeError('\\'byteOffset\\' must be an integer.');\n }\n if (byteOffset < 0 || byteOffset >= buffer.byteLength) {\n throw new RangeError(`'byteOffset' is out of range [0, ${buffer.byteLength}).`);\n }\n byteLength = arg0.byteLength - byteOffset;\n if (typeof arg2 === 'number') {\n byteLength = arg2;\n if (!Number.isSafeInteger(byteLength)) {\n throw new RangeError('\\'byteLength\\' must be an integer.');\n }\n if (byteLength <= 0 || byteOffset + byteLength > buffer.byteLength) {\n throw new RangeError(`'byteLength' is out of range (0, ${buffer.byteLength - byteOffset}].`);\n }\n if (typeof arg3 === 'object' && arg3 !== null) {\n options = arg3;\n }\n else if (typeof arg3 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'byteLength\\' must be a number.');\n }\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n filePathOrUint8Array = new Uint8Array(buffer, byteOffset, byteLength);\n }\n else {\n throw new TypeError('Unexpected argument[0]: must be \\'path\\' or \\'buffer\\'.');\n }\n // resolve backend, update session options with validated EPs, and create session handler\n const [backend, optionsWithValidatedEPs] = await resolveBackendAndExecutionProviders(options);\n const handler = await backend.createInferenceSessionHandler(filePathOrUint8Array, optionsWithValidatedEPs);\n TRACE_FUNC_END();\n return new InferenceSession(handler);\n }\n startProfiling() {\n this.handler.startProfiling();\n }\n endProfiling() {\n this.handler.endProfiling();\n }\n get inputNames() {\n return this.handler.inputNames;\n }\n get outputNames() {\n return this.handler.outputNames;\n }\n}\n//# sourceMappingURL=inference-session-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { InferenceSession as InferenceSessionImpl } from './inference-session-impl.js';\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const InferenceSession = InferenceSessionImpl;\n//# sourceMappingURL=inference-session.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nexport {};\n//# sourceMappingURL=onnx-model.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nexport {};\n//# sourceMappingURL=onnx-value.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n/**\n * implementation of Tensor.toDataURL()\n */\nexport const tensorToDataURL = (tensor, options) => {\n const canvas = typeof document !== 'undefined' ? document.createElement('canvas') : (new OffscreenCanvas(1, 1));\n canvas.width = tensor.dims[3];\n canvas.height = tensor.dims[2];\n const pixels2DContext = canvas.getContext('2d');\n if (pixels2DContext != null) {\n // Default values for height and width & format\n let width;\n let height;\n if (options?.tensorLayout !== undefined && options.tensorLayout === 'NHWC') {\n width = tensor.dims[2];\n height = tensor.dims[3];\n }\n else { // Default layout is NCWH\n width = tensor.dims[3];\n height = tensor.dims[2];\n }\n const inputformat = options?.format !== undefined ? options.format : 'RGB';\n const norm = options?.norm;\n let normMean;\n let normBias;\n if (norm === undefined || norm.mean === undefined) {\n normMean = [255, 255, 255, 255];\n }\n else {\n if (typeof (norm.mean) === 'number') {\n normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n }\n else {\n normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 0];\n if (norm.mean[3] !== undefined) {\n normMean[3] = norm.mean[3];\n }\n }\n }\n if (norm === undefined || norm.bias === undefined) {\n normBias = [0, 0, 0, 0];\n }\n else {\n if (typeof (norm.bias) === 'number') {\n normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n }\n else {\n normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];\n if (norm.bias[3] !== undefined) {\n normBias[3] = norm.bias[3];\n }\n }\n }\n const stride = height * width;\n // Default pointer assignments\n let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;\n // Updating the pointer assignments based on the input image format\n if (inputformat === 'RGBA') {\n rTensorPointer = 0;\n gTensorPointer = stride;\n bTensorPointer = stride * 2;\n aTensorPointer = stride * 3;\n }\n else if (inputformat === 'RGB') {\n rTensorPointer = 0;\n gTensorPointer = stride;\n bTensorPointer = stride * 2;\n }\n else if (inputformat === 'RBG') {\n rTensorPointer = 0;\n bTensorPointer = stride;\n gTensorPointer = stride * 2;\n }\n for (let i = 0; i < height; i++) {\n for (let j = 0; j < width; j++) {\n const R = (tensor.data[rTensorPointer++] - normBias[0]) * normMean[0]; // R value\n const G = (tensor.data[gTensorPointer++] - normBias[1]) * normMean[1]; // G value\n const B = (tensor.data[bTensorPointer++] - normBias[2]) * normMean[2]; // B value\n const A = aTensorPointer === -1 ?\n 255 :\n (tensor.data[aTensorPointer++] - normBias[3]) * normMean[3]; // A value\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n pixels2DContext.fillStyle = 'rgba(' + R + ',' + G + ',' + B + ',' + A + ')';\n pixels2DContext.fillRect(j, i, 1, 1);\n }\n }\n if ('toDataURL' in canvas) {\n return canvas.toDataURL();\n }\n else {\n throw new Error('toDataURL is not supported');\n }\n }\n else {\n throw new Error('Can not access image data');\n }\n};\n/**\n * implementation of Tensor.toImageData()\n */\nexport const tensorToImageData = (tensor, options) => {\n const pixels2DContext = typeof document !== 'undefined' ?\n document.createElement('canvas').getContext('2d') :\n new OffscreenCanvas(1, 1).getContext('2d');\n let image;\n if (pixels2DContext != null) {\n // Default values for height and width & format\n let width;\n let height;\n let channels;\n if (options?.tensorLayout !== undefined && options.tensorLayout === 'NHWC') {\n width = tensor.dims[2];\n height = tensor.dims[1];\n channels = tensor.dims[3];\n }\n else { // Default layout is NCWH\n width = tensor.dims[3];\n height = tensor.dims[2];\n channels = tensor.dims[1];\n }\n const inputformat = options !== undefined ? (options.format !== undefined ? options.format : 'RGB') : 'RGB';\n const norm = options?.norm;\n let normMean;\n let normBias;\n if (norm === undefined || norm.mean === undefined) {\n normMean = [255, 255, 255, 255];\n }\n else {\n if (typeof (norm.mean) === 'number') {\n normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n }\n else {\n normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 255];\n if (norm.mean[3] !== undefined) {\n normMean[3] = norm.mean[3];\n }\n }\n }\n if (norm === undefined || norm.bias === undefined) {\n normBias = [0, 0, 0, 0];\n }\n else {\n if (typeof (norm.bias) === 'number') {\n normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n }\n else {\n normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];\n if (norm.bias[3] !== undefined) {\n normBias[3] = norm.bias[3];\n }\n }\n }\n const stride = height * width;\n if (options !== undefined) {\n if (options.format !== undefined && (channels === 4 && options.format !== 'RGBA') ||\n (channels === 3 && (options.format !== 'RGB' && options.format !== 'BGR'))) {\n throw new Error('Tensor format doesn\\'t match input tensor dims');\n }\n }\n // Default pointer assignments\n const step = 4;\n let rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;\n let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;\n // Updating the pointer assignments based on the input image format\n if (inputformat === 'RGBA') {\n rTensorPointer = 0;\n gTensorPointer = stride;\n bTensorPointer = stride * 2;\n aTensorPointer = stride * 3;\n }\n else if (inputformat === 'RGB') {\n rTensorPointer = 0;\n gTensorPointer = stride;\n bTensorPointer = stride * 2;\n }\n else if (inputformat === 'RBG') {\n rTensorPointer = 0;\n bTensorPointer = stride;\n gTensorPointer = stride * 2;\n }\n image = pixels2DContext.createImageData(width, height);\n for (let i = 0; i < height * width; rImagePointer += step, gImagePointer += step, bImagePointer += step, aImagePointer += step, i++) {\n image.data[rImagePointer] = (tensor.data[rTensorPointer++] - normBias[0]) * normMean[0]; // R value\n image.data[gImagePointer] = (tensor.data[gTensorPointer++] - normBias[1]) * normMean[1]; // G value\n image.data[bImagePointer] = (tensor.data[bTensorPointer++] - normBias[2]) * normMean[2]; // B value\n image.data[aImagePointer] = aTensorPointer === -1 ?\n 255 :\n (tensor.data[aTensorPointer++] - normBias[3]) * normMean[3]; // A value\n }\n }\n else {\n throw new Error('Can not access image data');\n }\n return image;\n};\n//# sourceMappingURL=tensor-conversion-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nexport {};\n//# sourceMappingURL=tensor-conversion.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { Tensor } from './tensor-impl.js';\n/**\n * Create a new tensor object from image object\n *\n * @param buffer - Extracted image buffer data - assuming RGBA format\n * @param imageFormat - input image configuration - required configurations height, width, format\n * @param tensorFormat - output tensor configuration - Default is RGB format\n */\nexport const bufferToTensor = (buffer, options) => {\n if (buffer === undefined) {\n throw new Error('Image buffer must be defined');\n }\n if (options.height === undefined || options.width === undefined) {\n throw new Error('Image height and width must be defined');\n }\n if (options.tensorLayout === 'NHWC') {\n throw new Error('NHWC Tensor layout is not supported yet');\n }\n const { height, width } = options;\n const norm = options.norm ?? { mean: 255, bias: 0 };\n let normMean;\n let normBias;\n if (typeof (norm.mean) === 'number') {\n normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n }\n else {\n normMean = [norm.mean[0], norm.mean[1], norm.mean[2], norm.mean[3] ?? 255];\n }\n if (typeof (norm.bias) === 'number') {\n normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n }\n else {\n normBias = [norm.bias[0], norm.bias[1], norm.bias[2], norm.bias[3] ?? 0];\n }\n const inputformat = options.format !== undefined ? options.format : 'RGBA';\n // default value is RGBA since imagedata and HTMLImageElement uses it\n const outputformat = options.tensorFormat !== undefined ? (options.tensorFormat !== undefined ? options.tensorFormat : 'RGB') : 'RGB';\n const stride = height * width;\n const float32Data = outputformat === 'RGBA' ? new Float32Array(stride * 4) : new Float32Array(stride * 3);\n // Default pointer assignments\n let step = 4, rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;\n let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;\n // Updating the pointer assignments based on the input image format\n if (inputformat === 'RGB') {\n step = 3;\n rImagePointer = 0;\n gImagePointer = 1;\n bImagePointer = 2;\n aImagePointer = -1;\n }\n // Updating the pointer assignments based on the output tensor format\n if (outputformat === 'RGBA') {\n aTensorPointer = stride * 3;\n }\n else if (outputformat === 'RBG') {\n rTensorPointer = 0;\n bTensorPointer = stride;\n gTensorPointer = stride * 2;\n }\n else if (outputformat === 'BGR') {\n bTensorPointer = 0;\n gTensorPointer = stride;\n rTensorPointer = stride * 2;\n }\n for (let i = 0; i < stride; i++, rImagePointer += step, bImagePointer += step, gImagePointer += step, aImagePointer += step) {\n float32Data[rTensorPointer++] = (buffer[rImagePointer] + normBias[0]) / normMean[0];\n float32Data[gTensorPointer++] = (buffer[gImagePointer] + normBias[1]) / normMean[1];\n float32Data[bTensorPointer++] = (buffer[bImagePointer] + normBias[2]) / normMean[2];\n if (aTensorPointer !== -1 && aImagePointer !== -1) {\n float32Data[aTensorPointer++] = (buffer[aImagePointer] + normBias[3]) / normMean[3];\n }\n }\n // Float32Array -> ort.Tensor\n const outputTensor = outputformat === 'RGBA' ? new Tensor('float32', float32Data, [1, 4, height, width]) :\n new Tensor('float32', float32Data, [1, 3, height, width]);\n return outputTensor;\n};\n/**\n * implementation of Tensor.fromImage().\n */\nexport const tensorFromImage = async (image, options) => {\n // checking the type of image object\n const isHTMLImageEle = typeof (HTMLImageElement) !== 'undefined' && image instanceof HTMLImageElement;\n const isImageDataEle = typeof (ImageData) !== 'undefined' && image instanceof ImageData;\n const isImageBitmap = typeof (ImageBitmap) !== 'undefined' && image instanceof ImageBitmap;\n const isString = typeof image === 'string';\n let data;\n let bufferToTensorOptions = options ?? {};\n const createCanvas = () => {\n if (typeof document !== 'undefined') {\n return document.createElement('canvas');\n }\n else if (typeof OffscreenCanvas !== 'undefined') {\n return new OffscreenCanvas(1, 1);\n }\n else {\n throw new Error('Canvas is not supported');\n }\n };\n const createCanvasContext = (canvas) => {\n if (canvas instanceof HTMLCanvasElement) {\n return canvas.getContext('2d');\n }\n else if (canvas instanceof OffscreenCanvas) {\n return canvas.getContext('2d');\n }\n else {\n return null;\n }\n };\n // filling and checking image configuration options\n if (isHTMLImageEle) {\n // HTMLImageElement - image object - format is RGBA by default\n const canvas = createCanvas();\n canvas.width = image.width;\n canvas.height = image.height;\n const pixels2DContext = createCanvasContext(canvas);\n if (pixels2DContext != null) {\n let height = image.height;\n let width = image.width;\n if (options !== undefined && options.resizedHeight !== undefined && options.resizedWidth !== undefined) {\n height = options.resizedHeight;\n width = options.resizedWidth;\n }\n if (options !== undefined) {\n bufferToTensorOptions = options;\n if (options.tensorFormat !== undefined) {\n throw new Error('Image input config format must be RGBA for HTMLImageElement');\n }\n else {\n bufferToTensorOptions.tensorFormat = 'RGBA';\n }\n bufferToTensorOptions.height = height;\n bufferToTensorOptions.width = width;\n }\n else {\n bufferToTensorOptions.tensorFormat = 'RGBA';\n bufferToTensorOptions.height = height;\n bufferToTensorOptions.width = width;\n }\n pixels2DContext.drawImage(image, 0, 0);\n data = pixels2DContext.getImageData(0, 0, width, height).data;\n }\n else {\n throw new Error('Can not access image data');\n }\n }\n else if (isImageDataEle) {\n let height;\n let width;\n if (options !== undefined && options.resizedWidth !== undefined && options.resizedHeight !== undefined) {\n height = options.resizedHeight;\n width = options.resizedWidth;\n }\n else {\n height = image.height;\n width = image.width;\n }\n if (options !== undefined) {\n bufferToTensorOptions = options;\n }\n bufferToTensorOptions.format = 'RGBA';\n bufferToTensorOptions.height = height;\n bufferToTensorOptions.width = width;\n if (options !== undefined) {\n const tempCanvas = createCanvas();\n tempCanvas.width = width;\n tempCanvas.height = height;\n const pixels2DContext = createCanvasContext(tempCanvas);\n if (pixels2DContext != null) {\n pixels2DContext.putImageData(image, 0, 0);\n data = pixels2DContext.getImageData(0, 0, width, height).data;\n }\n else {\n throw new Error('Can not access image data');\n }\n }\n else {\n data = image.data;\n }\n }\n else if (isImageBitmap) {\n // ImageBitmap - image object - format must be provided by user\n if (options === undefined) {\n throw new Error('Please provide image config with format for Imagebitmap');\n }\n const canvas = createCanvas();\n canvas.width = image.width;\n canvas.height = image.height;\n const pixels2DContext = createCanvasContext(canvas);\n if (pixels2DContext != null) {\n const height = image.height;\n const width = image.width;\n pixels2DContext.drawImage(image, 0, 0, width, height);\n data = pixels2DContext.getImageData(0, 0, width, height).data;\n bufferToTensorOptions.height = height;\n bufferToTensorOptions.width = width;\n return bufferToTensor(data, bufferToTensorOptions);\n }\n else {\n throw new Error('Can not access image data');\n }\n }\n else if (isString) {\n return new Promise((resolve, reject) => {\n const canvas = createCanvas();\n const context = createCanvasContext(canvas);\n if (!image || !context) {\n return reject();\n }\n const newImage = new Image();\n newImage.crossOrigin = 'Anonymous';\n newImage.src = image;\n newImage.onload = () => {\n canvas.width = newImage.width;\n canvas.height = newImage.height;\n context.drawImage(newImage, 0, 0, canvas.width, canvas.height);\n const img = context.getImageData(0, 0, canvas.width, canvas.height);\n bufferToTensorOptions.height = canvas.height;\n bufferToTensorOptions.width = canvas.width;\n resolve(bufferToTensor(img.data, bufferToTensorOptions));\n };\n });\n }\n else {\n throw new Error('Input data provided is not supported - aborted tensor creation');\n }\n if (data !== undefined) {\n return bufferToTensor(data, bufferToTensorOptions);\n }\n else {\n throw new Error('Input data provided is not supported - aborted tensor creation');\n }\n};\n/**\n * implementation of Tensor.fromTexture().\n */\nexport const tensorFromTexture = (texture, options) => {\n const { width, height, download, dispose } = options;\n // Always assume RGBAF32. TODO: support different texture format\n const dims = [1, height, width, 4];\n return new Tensor({ location: 'texture', type: 'float32', texture, dims, download, dispose });\n};\n/**\n * implementation of Tensor.fromGpuBuffer().\n */\nexport const tensorFromGpuBuffer = (gpuBuffer, options) => {\n const { dataType, dims, download, dispose } = options;\n return new Tensor({ location: 'gpu-buffer', type: dataType ?? 'float32', gpuBuffer, dims, download, dispose });\n};\n/**\n * implementation of Tensor.fromPinnedBuffer().\n */\nexport const tensorFromPinnedBuffer = (type, buffer, dims) => new Tensor({ location: 'cpu-pinned', type, data: buffer, dims: dims ?? [buffer.length] });\n//# sourceMappingURL=tensor-factory-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nexport {};\n//# sourceMappingURL=tensor-factory.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.\nexport const NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = new Map([\n ['float32', Float32Array],\n ['uint8', Uint8Array],\n ['int8', Int8Array],\n ['uint16', Uint16Array],\n ['int16', Int16Array],\n ['int32', Int32Array],\n ['bool', Uint8Array],\n ['float64', Float64Array],\n ['uint32', Uint32Array],\n]);\n// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.\nexport const NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = new Map([\n [Float32Array, 'float32'],\n [Uint8Array, 'uint8'],\n [Int8Array, 'int8'],\n [Uint16Array, 'uint16'],\n [Int16Array, 'int16'],\n [Int32Array, 'int32'],\n [Float64Array, 'float64'],\n [Uint32Array, 'uint32'],\n]);\n// the following code allows delaying execution of BigInt/Float16Array checking. This allows lazy initialization for\n// NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP and NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP, which allows BigInt/Float16Array\n// polyfill if available.\nlet isTypedArrayChecked = false;\nexport const checkTypedArray = () => {\n if (!isTypedArrayChecked) {\n isTypedArrayChecked = true;\n const isBigInt64ArrayAvailable = typeof BigInt64Array !== 'undefined' && BigInt64Array.from;\n const isBigUint64ArrayAvailable = typeof BigUint64Array !== 'undefined' && BigUint64Array.from;\n const isFloat16ArrayAvailable = typeof Float16Array !== 'undefined' && Float16Array.from;\n if (isBigInt64ArrayAvailable) {\n NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('int64', BigInt64Array);\n NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, 'int64');\n }\n if (isBigUint64ArrayAvailable) {\n NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('uint64', BigUint64Array);\n NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, 'uint64');\n }\n if (isFloat16ArrayAvailable) {\n NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('float16', Float16Array);\n NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(Float16Array, 'float16');\n }\n else {\n // if Float16Array is not available, use 'Uint16Array' to store the data.\n NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('float16', Uint16Array);\n }\n }\n};\n//# sourceMappingURL=tensor-impl-type-mapping.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { tensorToDataURL, tensorToImageData } from './tensor-conversion-impl.js';\nimport { tensorFromGpuBuffer, tensorFromImage, tensorFromPinnedBuffer, tensorFromTexture } from './tensor-factory-impl.js';\nimport { checkTypedArray, NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP, NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP } from './tensor-impl-type-mapping.js';\nimport { calculateSize, tensorReshape } from './tensor-utils-impl.js';\n/**\n * the implementation of Tensor interface.\n *\n * @ignore\n */\nexport class Tensor {\n /**\n * implementation.\n */\n constructor(arg0, arg1, arg2) {\n // perform one-time check for BigInt/Float16Array support\n checkTypedArray();\n let type;\n let dims;\n if (typeof arg0 === 'object' && 'location' in arg0) {\n //\n // constructing tensor from specific location\n //\n this.dataLocation = arg0.location;\n type = arg0.type;\n dims = arg0.dims;\n switch (arg0.location) {\n case 'cpu-pinned': {\n const expectedTypedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(type);\n if (!expectedTypedArrayConstructor) {\n throw new TypeError(`unsupported type \"${type}\" to create tensor from pinned buffer`);\n }\n if (!(arg0.data instanceof expectedTypedArrayConstructor)) {\n throw new TypeError(`buffer should be of type ${expectedTypedArrayConstructor.name}`);\n }\n this.cpuData = arg0.data;\n break;\n }\n case 'texture': {\n if (type !== 'float32') {\n throw new TypeError(`unsupported type \"${type}\" to create tensor from texture`);\n }\n this.gpuTextureData = arg0.texture;\n this.downloader = arg0.download;\n this.disposer = arg0.dispose;\n break;\n }\n case 'gpu-buffer': {\n if ((type !== 'float32' && type !== 'float16' && type !== 'int32' && type !== 'int64' && type !== 'uint32' &&\n type !== 'uint8' && type !== 'bool')) {\n throw new TypeError(`unsupported type \"${type}\" to create tensor from gpu buffer`);\n }\n this.gpuBufferData = arg0.gpuBuffer;\n this.downloader = arg0.download;\n this.disposer = arg0.dispose;\n break;\n }\n default:\n throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`);\n }\n }\n else {\n //\n // constructing tensor of location 'cpu'\n //\n let data;\n let maybeDims;\n // check whether arg0 is type or data\n if (typeof arg0 === 'string') {\n //\n // Override: constructor(type, data, ...)\n //\n type = arg0;\n maybeDims = arg2;\n if (arg0 === 'string') {\n // string tensor\n if (!Array.isArray(arg1)) {\n throw new TypeError('A string tensor\\'s data must be a string array.');\n }\n // we don't check whether every element in the array is string; this is too slow. we assume it's correct and\n // error will be populated at inference\n data = arg1;\n }\n else {\n // numeric tensor\n const typedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(arg0);\n if (typedArrayConstructor === undefined) {\n throw new TypeError(`Unsupported tensor type: ${arg0}.`);\n }\n if (Array.isArray(arg1)) {\n if (arg0 === 'float16' && typedArrayConstructor === Uint16Array) {\n // When no Float16Array polyfill is used, we cannot create 'float16' tensor from number array.\n //\n // Throw error here because when user try to use number array as data,\n // e.g. new Tensor('float16', [1, 2, 3, 4], dims)), it will actually call\n // Uint16Array.from(arg1) which generates wrong data.\n throw new TypeError('Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.');\n }\n else if (arg0 === 'uint64' || arg0 === 'int64') {\n // use 'as any' here because:\n // 1. TypeScript's check on type of 'Array.isArray()' does not work with readonly arrays.\n // see https://github.com/microsoft/TypeScript/issues/17002\n // 2. TypeScript's check on union type of '(BigInt64ArrayConstructor|BigUint64ArrayConstructor).from()'\n // does not accept parameter mapFn.\n // 3. parameters of 'SupportedTypedArrayConstructors.from()' does not match the requirement of the union\n // type.\n // assume 'arg1' is of type \"readonly number[]|readonly bigint[]\" here.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data = typedArrayConstructor.from(arg1, BigInt);\n }\n else {\n // assume 'arg1' is of type \"readonly number[]\" here.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data = typedArrayConstructor.from(arg1);\n }\n }\n else if (arg1 instanceof typedArrayConstructor) {\n data = arg1;\n }\n else {\n throw new TypeError(`A ${type} tensor's data must be type of ${typedArrayConstructor}`);\n }\n }\n }\n else {\n //\n // Override: constructor(data, ...)\n //\n maybeDims = arg1;\n if (Array.isArray(arg0)) {\n // only boolean[] and string[] is supported\n if (arg0.length === 0) {\n throw new TypeError('Tensor type cannot be inferred from an empty array.');\n }\n const firstElementType = typeof arg0[0];\n if (firstElementType === 'string') {\n type = 'string';\n data = arg0;\n }\n else if (firstElementType === 'boolean') {\n type = 'bool';\n // 'arg0' is of type 'boolean[]'. Uint8Array.from(boolean[]) actually works, but typescript thinks this is\n // wrong type. We use 'as any' to make it happy.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data = Uint8Array.from(arg0);\n }\n else {\n throw new TypeError(`Invalid element type of data array: ${firstElementType}.`);\n }\n }\n else {\n // get tensor type from TypedArray\n const mappedType = NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(arg0.constructor);\n if (mappedType === undefined) {\n throw new TypeError(`Unsupported type for tensor data: ${arg0.constructor}.`);\n }\n type = mappedType;\n data = arg0;\n }\n }\n // type and data is processed, now processing dims\n if (maybeDims === undefined) {\n // assume 1-D tensor if dims omitted\n maybeDims = [data.length];\n }\n else if (!Array.isArray(maybeDims)) {\n throw new TypeError('A tensor\\'s dims must be a number array');\n }\n dims = maybeDims;\n this.cpuData = data;\n this.dataLocation = 'cpu';\n }\n // perform check on dims\n const size = calculateSize(dims);\n // if data is on CPU, check whether data length matches tensor size\n if (this.cpuData && size !== this.cpuData.length) {\n throw new Error(`Tensor's size(${size}) does not match data length(${this.cpuData.length}).`);\n }\n this.type = type;\n this.dims = dims;\n this.size = size;\n }\n // #endregion\n // #region factory\n static async fromImage(image, options) {\n return tensorFromImage(image, options);\n }\n static fromTexture(texture, options) {\n return tensorFromTexture(texture, options);\n }\n static fromGpuBuffer(gpuBuffer, options) {\n return tensorFromGpuBuffer(gpuBuffer, options);\n }\n static fromPinnedBuffer(type, buffer, dims) {\n return tensorFromPinnedBuffer(type, buffer, dims);\n }\n // #endregion\n // #region conversions\n toDataURL(options) {\n return tensorToDataURL(this, options);\n }\n toImageData(options) {\n return tensorToImageData(this, options);\n }\n // #endregion\n // #region properties\n get data() {\n this.ensureValid();\n if (!this.cpuData) {\n throw new Error('The data is not on CPU. Use `getData()` to download GPU data to CPU, ' +\n 'or use `texture` or `gpuBuffer` property to access the GPU data directly.');\n }\n return this.cpuData;\n }\n get location() {\n return this.dataLocation;\n }\n get texture() {\n this.ensureValid();\n if (!this.gpuTextureData) {\n throw new Error('The data is not stored as a WebGL texture.');\n }\n return this.gpuTextureData;\n }\n get gpuBuffer() {\n this.ensureValid();\n if (!this.gpuBufferData) {\n throw new Error('The data is not stored as a WebGPU buffer.');\n }\n return this.gpuBufferData;\n }\n // #endregion\n // #region methods\n async getData(releaseData) {\n this.ensureValid();\n switch (this.dataLocation) {\n case 'cpu':\n case 'cpu-pinned':\n return this.data;\n case 'texture':\n case 'gpu-buffer': {\n if (!this.downloader) {\n throw new Error('The current tensor is not created with a specified data downloader.');\n }\n if (this.isDownloading) {\n throw new Error('The current tensor is being downloaded.');\n }\n try {\n this.isDownloading = true;\n const data = await this.downloader();\n this.downloader = undefined;\n this.dataLocation = 'cpu';\n this.cpuData = data;\n if (releaseData && this.disposer) {\n this.disposer();\n this.disposer = undefined;\n }\n return data;\n }\n finally {\n this.isDownloading = false;\n }\n }\n default:\n throw new Error(`cannot get data from location: ${this.dataLocation}`);\n }\n }\n dispose() {\n if (this.isDownloading) {\n throw new Error('The current tensor is being downloaded.');\n }\n if (this.disposer) {\n this.disposer();\n this.disposer = undefined;\n }\n this.cpuData = undefined;\n this.gpuTextureData = undefined;\n this.gpuBufferData = undefined;\n this.downloader = undefined;\n this.isDownloading = undefined;\n this.dataLocation = 'none';\n }\n // #endregion\n // #region tensor utilities\n ensureValid() {\n if (this.dataLocation === 'none') {\n throw new Error('The tensor is disposed.');\n }\n }\n reshape(dims) {\n this.ensureValid();\n if (this.downloader || this.disposer) {\n throw new Error('Cannot reshape a tensor that owns GPU resource.');\n }\n return tensorReshape(this, dims);\n }\n}\n//# sourceMappingURL=tensor-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { Tensor } from './tensor-impl.js';\n/**\n * calculate size from dims.\n *\n * @param dims the dims array. May be an illegal input.\n */\nexport const calculateSize = (dims) => {\n let size = 1;\n for (let i = 0; i < dims.length; i++) {\n const dim = dims[i];\n if (typeof dim !== 'number' || !Number.isSafeInteger(dim)) {\n throw new TypeError(`dims[${i}] must be an integer, got: ${dim}`);\n }\n if (dim < 0) {\n throw new RangeError(`dims[${i}] must be a non-negative integer, got: ${dim}`);\n }\n size *= dim;\n }\n return size;\n};\n/**\n * implementation of Tensor.reshape()\n */\nexport const tensorReshape = (tensor, dims) => {\n switch (tensor.location) {\n case 'cpu':\n return new Tensor(tensor.type, tensor.data, dims);\n case 'cpu-pinned':\n return new Tensor({\n location: 'cpu-pinned',\n data: tensor.data,\n type: tensor.type,\n dims,\n });\n case 'texture':\n return new Tensor({\n location: 'texture',\n texture: tensor.texture,\n type: tensor.type,\n dims,\n });\n case 'gpu-buffer':\n return new Tensor({\n location: 'gpu-buffer',\n gpuBuffer: tensor.gpuBuffer,\n type: tensor.type,\n dims,\n });\n default:\n throw new Error(`tensorReshape: tensor location ${tensor.location} is not supported`);\n }\n};\n//# sourceMappingURL=tensor-utils-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { Tensor as TensorImpl } from './tensor-impl.js';\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const Tensor = TensorImpl;\n//# sourceMappingURL=tensor.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { env } from './env-impl.js';\n/**\n * @ignore\n */\nexport const TRACE = (deviceType, label) => {\n if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n return;\n }\n // eslint-disable-next-line no-console\n console.timeStamp(`${deviceType}::ORT::${label}`);\n};\nconst TRACE_FUNC = (msg, extraMsg) => {\n const stack = new Error().stack?.split(/\\r\\n|\\r|\\n/g) || [];\n let hasTraceFunc = false;\n for (let i = 0; i < stack.length; i++) {\n if (hasTraceFunc && !stack[i].includes('TRACE_FUNC')) {\n let label = `FUNC_${msg}::${stack[i].trim().split(' ')[1]}`;\n if (extraMsg) {\n label += `::${extraMsg}`;\n }\n TRACE('CPU', label);\n return;\n }\n if (stack[i].includes('TRACE_FUNC')) {\n hasTraceFunc = true;\n }\n }\n};\n/**\n * @ignore\n */\nexport const TRACE_FUNC_BEGIN = (extraMsg) => {\n if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n return;\n }\n TRACE_FUNC('BEGIN', extraMsg);\n};\n/**\n * @ignore\n */\nexport const TRACE_FUNC_END = (extraMsg) => {\n if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n return;\n }\n TRACE_FUNC('END', extraMsg);\n};\n//# sourceMappingURL=trace.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { resolveBackendAndExecutionProviders } from './backend-impl.js';\nimport { Tensor } from './tensor.js';\nconst noBackendErrMsg = 'Training backend could not be resolved. ' +\n 'Make sure you\\'re using the correct configuration & WebAssembly files.';\nexport class TrainingSession {\n constructor(handler, hasOptimizerModel, hasEvalModel) {\n this.handler = handler;\n this.hasOptimizerModel = hasOptimizerModel;\n this.hasEvalModel = hasEvalModel;\n }\n get trainingInputNames() {\n return this.handler.inputNames;\n }\n get trainingOutputNames() {\n return this.handler.outputNames;\n }\n get evalInputNames() {\n if (this.hasEvalModel) {\n return this.handler.evalInputNames;\n }\n else {\n throw new Error('This training session has no evalModel loaded.');\n }\n }\n get evalOutputNames() {\n if (this.hasEvalModel) {\n return this.handler.evalOutputNames;\n }\n else {\n throw new Error('This training session has no evalModel loaded.');\n }\n }\n static async create(trainingOptions, sessionOptions) {\n const evalModel = trainingOptions.evalModel || '';\n const optimizerModel = trainingOptions.optimizerModel || '';\n const options = sessionOptions || {};\n // resolve backend, update session options with validated EPs, and create session handler\n const [backend, optionsWithValidatedEPs] = await resolveBackendAndExecutionProviders(options);\n if (backend.createTrainingSessionHandler) {\n const handler = await backend.createTrainingSessionHandler(trainingOptions.checkpointState, trainingOptions.trainModel, evalModel, optimizerModel, optionsWithValidatedEPs);\n return new TrainingSession(handler, !!trainingOptions.optimizerModel, !!trainingOptions.evalModel);\n }\n else {\n throw new Error(noBackendErrMsg);\n }\n }\n /**\n * Helper function for runTrainStep and future runStep methods that handles the type-narrowing conversion from\n * the given parameters to SessionHandler.FetchesType and RunOptions.\n *\n * @param inputNames the feeds object is checked that they contain all input names in the provided list of input\n * names.\n * @param outputNames the fetches object is checked that their keys match up with valid names in the list of output\n * names.\n * @param feeds the required input\n * @param arg1 narrowed & converted into the SessionHandler.FetchesType or RunOptions object\n * @param arg2 optional RunOptions object.\n * @returns\n */\n typeNarrowingForRunStep(inputNames, outputNames, feeds, arg1, arg2) {\n const fetches = {};\n let options = {};\n // check inputs\n if (typeof feeds !== 'object' || feeds === null || feeds instanceof Tensor || Array.isArray(feeds)) {\n throw new TypeError('\\'feeds\\' must be an object that use input names as keys and OnnxValue as corresponding values.');\n }\n let isFetchesEmpty = true;\n // determine which override is being used\n if (typeof arg1 === 'object') {\n if (arg1 === null) {\n throw new TypeError('Unexpected argument[1]: cannot be null.');\n }\n if (arg1 instanceof Tensor) {\n throw new TypeError('\\'fetches\\' cannot be a Tensor');\n }\n if (Array.isArray(arg1)) {\n if (arg1.length === 0) {\n throw new TypeError('\\'fetches\\' cannot be an empty array.');\n }\n isFetchesEmpty = false;\n // output names\n for (const name of arg1) {\n if (typeof name !== 'string') {\n throw new TypeError('\\'fetches\\' must be a string array or an object.');\n }\n if (outputNames.indexOf(name) === -1) {\n throw new RangeError(`'fetches' contains invalid output name: ${name}.`);\n }\n fetches[name] = null;\n }\n if (typeof arg2 === 'object' && arg2 !== null) {\n options = arg2;\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else {\n // decide whether arg1 is fetches or options\n // if any output name is present and its value is valid OnnxValue, we consider it fetches\n let isFetches = false;\n const arg1Keys = Object.getOwnPropertyNames(arg1);\n for (const name of outputNames) {\n if (arg1Keys.indexOf(name) !== -1) {\n const v = arg1[name];\n if (v === null || v instanceof Tensor) {\n isFetches = true;\n isFetchesEmpty = false;\n fetches[name] = v;\n }\n }\n }\n if (isFetches) {\n if (typeof arg2 === 'object' && arg2 !== null) {\n options = arg2;\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else {\n options = arg1;\n }\n }\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('Unexpected argument[1]: must be \\'fetches\\' or \\'options\\'.');\n }\n // check if all inputs are in feed\n for (const name of inputNames) {\n if (typeof feeds[name] === 'undefined') {\n throw new Error(`input '${name}' is missing in 'feeds'.`);\n }\n }\n // if no fetches is specified, we use the full output names list\n if (isFetchesEmpty) {\n for (const name of outputNames) {\n fetches[name] = null;\n }\n }\n return [fetches, options];\n }\n /**\n * Helper method for runTrainStep and any other runStep methods. Takes the ReturnType result from the SessionHandler\n * and changes it into a map of Tensors.\n *\n * @param results\n * @returns\n */\n convertHandlerReturnTypeToMapOfTensors(results) {\n const returnValue = {};\n for (const key in results) {\n if (Object.hasOwnProperty.call(results, key)) {\n const result = results[key];\n if (result instanceof Tensor) {\n returnValue[key] = result;\n }\n else {\n returnValue[key] = new Tensor(result.type, result.data, result.dims);\n }\n }\n }\n return returnValue;\n }\n async lazyResetGrad() {\n await this.handler.lazyResetGrad();\n }\n async runTrainStep(feeds, arg1, arg2) {\n const [fetches, options] = this.typeNarrowingForRunStep(this.trainingInputNames, this.trainingOutputNames, feeds, arg1, arg2);\n const results = await this.handler.runTrainStep(feeds, fetches, options);\n return this.convertHandlerReturnTypeToMapOfTensors(results);\n }\n async runOptimizerStep(options) {\n if (this.hasOptimizerModel) {\n await this.handler.runOptimizerStep(options || {});\n }\n else {\n throw new Error('This TrainingSession has no OptimizerModel loaded.');\n }\n }\n async runEvalStep(feeds, arg1, arg2) {\n if (this.hasEvalModel) {\n const [fetches, options] = this.typeNarrowingForRunStep(this.evalInputNames, this.evalOutputNames, feeds, arg1, arg2);\n const results = await this.handler.runEvalStep(feeds, fetches, options);\n return this.convertHandlerReturnTypeToMapOfTensors(results);\n }\n else {\n throw new Error('This TrainingSession has no EvalModel loaded.');\n }\n }\n async getParametersSize(trainableOnly = true) {\n return this.handler.getParametersSize(trainableOnly);\n }\n async loadParametersBuffer(array, trainableOnly = true) {\n const paramsSize = await this.getParametersSize(trainableOnly);\n // checking that the size of the Uint8Array is equivalent to the byte length of a Float32Array of the number\n // of parameters\n if (array.length !== 4 * paramsSize) {\n throw new Error('Size of the buffer passed into loadParametersBuffer must match the number of parameters in ' +\n 'the model. Please use getParametersSize method to check.');\n }\n return this.handler.loadParametersBuffer(array, trainableOnly);\n }\n async getContiguousParameters(trainableOnly = true) {\n return this.handler.getContiguousParameters(trainableOnly);\n }\n async release() {\n return this.handler.dispose();\n }\n}\n//# sourceMappingURL=training-session-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { TrainingSession as TrainingSessionImpl } from './training-session-impl.js';\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const TrainingSession = TrainingSessionImpl;\n//# sourceMappingURL=training-session.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n// This file is generated by /js/scripts/update-version.ts\n// Do not modify file content manually.\nexport const version = '1.19.2';\n//# sourceMappingURL=version.js.map","/*!\n * ONNX Runtime Web v1.21.0-dev.20241109-d3ad76b2cf\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\nvar Fn=Object.defineProperty;var Pp=Object.getOwnPropertyDescriptor;var zp=Object.getOwnPropertyNames;var Op=Object.prototype.hasOwnProperty;var qn=(e=>typeof require<\"u\"?require:typeof Proxy<\"u\"?new Proxy(e,{get:(t,r)=>(typeof require<\"u\"?require:t)[r]}):e)(function(e){if(typeof require<\"u\")return require.apply(this,arguments);throw Error('Dynamic require of \"'+e+'\" is not supported')});var R=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ft=(e,t)=>{for(var r in t)Fn(e,r,{get:t[r],enumerable:!0})},Dp=(e,t,r,n)=>{if(t&&typeof t==\"object\"||typeof t==\"function\")for(let o of zp(t))!Op.call(e,o)&&o!==r&&Fn(e,o,{get:()=>t[o],enumerable:!(n=Pp(t,o))||n.enumerable});return e};var vr=e=>Dp(Fn({},\"__esModule\",{value:!0}),e);var $r,$t,xt,Bp,xr,Sr=R(()=>{\"use strict\";$r=new Map,$t=[],xt=(e,t,r)=>{if(t&&typeof t.init==\"function\"&&typeof t.createInferenceSessionHandler==\"function\"){let n=$r.get(e);if(n===void 0)$r.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend \"${e}\" using priority ${r}`)}if(r>=0){let o=$t.indexOf(e);o!==-1&&$t.splice(o,1);for(let i=0;i<$t.length;i++)if($r.get($t[i]).priority<=r){$t.splice(i,0,e);return}$t.push(e)}return}throw new TypeError(\"not a valid backend\")},Bp=async e=>{let t=$r.get(e);if(!t)return\"backend not found.\";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},xr=async e=>{let t=e.executionProviders||[],r=t.map(d=>typeof d==\"string\"?d:d.name),n=r.length===0?$t:r,o,i=[],a=new Set;for(let d of n){let c=await Bp(d);typeof c==\"string\"?i.push({name:d,err:c}):(o||(o=c),o===c&&a.add(d))}if(!o)throw new Error(`no available backend found. ERR: ${i.map(d=>`[${d.name}] ${d.err}`).join(\", \")}`);for(let{name:d,err:c}of i)r.includes(d)&&console.warn(`removing requested execution provider \"${d}\" from session options because it is not available: ${c}`);let l=t.filter(d=>a.has(typeof d==\"string\"?d:d.name));return[o,new Proxy(e,{get:(d,c)=>c===\"executionProviders\"?l:Reflect.get(d,c)})]}});var oa=R(()=>{\"use strict\";Sr()});var ia,aa=R(()=>{\"use strict\";ia=\"1.21.0-dev.20241026-05fbb43b34\"});var sa,Re,jn=R(()=>{\"use strict\";aa();sa=\"warning\",Re={wasm:{},webgl:{},webgpu:{},versions:{common:ia},set logLevel(e){if(e!==void 0){if(typeof e!=\"string\"||[\"verbose\",\"info\",\"warning\",\"error\",\"fatal\"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);sa=e}},get logLevel(){return sa}};Object.defineProperty(Re,\"logLevel\",{enumerable:!0})});var ve,ua=R(()=>{\"use strict\";jn();ve=Re});var la,da,ca=R(()=>{\"use strict\";la=(e,t)=>{let r=typeof document<\"u\"?document.createElement(\"canvas\"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext(\"2d\");if(n!=null){let o,i;t?.tensorLayout!==void 0&&t.tensorLayout===\"NHWC\"?(o=e.dims[2],i=e.dims[3]):(o=e.dims[3],i=e.dims[2]);let a=t?.format!==void 0?t.format:\"RGB\",l=t?.norm,d,c;l===void 0||l.mean===void 0?d=[255,255,255,255]:typeof l.mean==\"number\"?d=[l.mean,l.mean,l.mean,l.mean]:(d=[l.mean[0],l.mean[1],l.mean[2],0],l.mean[3]!==void 0&&(d[3]=l.mean[3])),l===void 0||l.bias===void 0?c=[0,0,0,0]:typeof l.bias==\"number\"?c=[l.bias,l.bias,l.bias,l.bias]:(c=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(c[3]=l.bias[3]));let m=i*o,u=0,h=m,w=m*2,y=-1;a===\"RGBA\"?(u=0,h=m,w=m*2,y=m*3):a===\"RGB\"?(u=0,h=m,w=m*2):a===\"RBG\"&&(u=0,w=m,h=m*2);for(let g=0;g{let r=typeof document<\"u\"?document.createElement(\"canvas\").getContext(\"2d\"):new OffscreenCanvas(1,1).getContext(\"2d\"),n;if(r!=null){let o,i,a;t?.tensorLayout!==void 0&&t.tensorLayout===\"NHWC\"?(o=e.dims[2],i=e.dims[1],a=e.dims[3]):(o=e.dims[3],i=e.dims[2],a=e.dims[1]);let l=t!==void 0&&t.format!==void 0?t.format:\"RGB\",d=t?.norm,c,m;d===void 0||d.mean===void 0?c=[255,255,255,255]:typeof d.mean==\"number\"?c=[d.mean,d.mean,d.mean,d.mean]:(c=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(c[3]=d.mean[3])),d===void 0||d.bias===void 0?m=[0,0,0,0]:typeof d.bias==\"number\"?m=[d.bias,d.bias,d.bias,d.bias]:(m=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(m[3]=d.bias[3]));let u=i*o;if(t!==void 0&&(t.format!==void 0&&a===4&&t.format!==\"RGBA\"||a===3&&t.format!==\"RGB\"&&t.format!==\"BGR\"))throw new Error(\"Tensor format doesn't match input tensor dims\");let h=4,w=0,y=1,g=2,x=3,$=0,v=u,S=u*2,T=-1;l===\"RGBA\"?($=0,v=u,S=u*2,T=u*3):l===\"RGB\"?($=0,v=u,S=u*2):l===\"RBG\"&&($=0,S=u,v=u*2),n=r.createImageData(o,i);for(let C=0;C{\"use strict\";Tr();Kn=(e,t)=>{if(e===void 0)throw new Error(\"Image buffer must be defined\");if(t.height===void 0||t.width===void 0)throw new Error(\"Image height and width must be defined\");if(t.tensorLayout===\"NHWC\")throw new Error(\"NHWC Tensor layout is not supported yet\");let{height:r,width:n}=t,o=t.norm??{mean:255,bias:0},i,a;typeof o.mean==\"number\"?i=[o.mean,o.mean,o.mean,o.mean]:i=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias==\"number\"?a=[o.bias,o.bias,o.bias,o.bias]:a=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let l=t.format!==void 0?t.format:\"RGBA\",d=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:\"RGB\",c=r*n,m=d===\"RGBA\"?new Float32Array(c*4):new Float32Array(c*3),u=4,h=0,w=1,y=2,g=3,x=0,$=c,v=c*2,S=-1;l===\"RGB\"&&(u=3,h=0,w=1,y=2,g=-1),d===\"RGBA\"?S=c*3:d===\"RBG\"?(x=0,v=c,$=c*2):d===\"BGR\"&&(v=0,$=c,x=c*2);for(let C=0;C{let r=typeof HTMLImageElement<\"u\"&&e instanceof HTMLImageElement,n=typeof ImageData<\"u\"&&e instanceof ImageData,o=typeof ImageBitmap<\"u\"&&e instanceof ImageBitmap,i=typeof e==\"string\",a,l=t??{},d=()=>{if(typeof document<\"u\")return document.createElement(\"canvas\");if(typeof OffscreenCanvas<\"u\")return new OffscreenCanvas(1,1);throw new Error(\"Canvas is not supported\")},c=m=>typeof HTMLCanvasElement<\"u\"&&m instanceof HTMLCanvasElement||m instanceof OffscreenCanvas?m.getContext(\"2d\"):null;if(r){let m=d();m.width=e.width,m.height=e.height;let u=c(m);if(u!=null){let h=e.height,w=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(h=t.resizedHeight,w=t.resizedWidth),t!==void 0){if(l=t,t.tensorFormat!==void 0)throw new Error(\"Image input config format must be RGBA for HTMLImageElement\");l.tensorFormat=\"RGBA\",l.height=h,l.width=w}else l.tensorFormat=\"RGBA\",l.height=h,l.width=w;u.drawImage(e,0,0),a=u.getImageData(0,0,w,h).data}else throw new Error(\"Can not access image data\")}else if(n){let m,u;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(m=t.resizedHeight,u=t.resizedWidth):(m=e.height,u=e.width),t!==void 0&&(l=t),l.format=\"RGBA\",l.height=m,l.width=u,t!==void 0){let h=d();h.width=u,h.height=m;let w=c(h);if(w!=null)w.putImageData(e,0,0),a=w.getImageData(0,0,u,m).data;else throw new Error(\"Can not access image data\")}else a=e.data}else if(o){if(t===void 0)throw new Error(\"Please provide image config with format for Imagebitmap\");let m=d();m.width=e.width,m.height=e.height;let u=c(m);if(u!=null){let h=e.height,w=e.width;return u.drawImage(e,0,0,w,h),a=u.getImageData(0,0,w,h).data,l.height=h,l.width=w,Kn(a,l)}else throw new Error(\"Can not access image data\")}else{if(i)return new Promise((m,u)=>{let h=d(),w=c(h);if(!e||!w)return u();let y=new Image;y.crossOrigin=\"Anonymous\",y.src=e,y.onload=()=>{h.width=y.width,h.height=y.height,w.drawImage(y,0,0,h.width,h.height);let g=w.getImageData(0,0,h.width,h.height);l.height=h.height,l.width=h.width,m(Kn(g.data,l))}});throw new Error(\"Input data provided is not supported - aborted tensor creation\")}if(a!==void 0)return Kn(a,l);throw new Error(\"Input data provided is not supported - aborted tensor creation\")},ma=(e,t)=>{let{width:r,height:n,download:o,dispose:i}=t,a=[1,n,r,4];return new Oe({location:\"texture\",type:\"float32\",texture:e,dims:a,download:o,dispose:i})},fa=(e,t)=>{let{dataType:r,dims:n,download:o,dispose:i}=t;return new Oe({location:\"gpu-buffer\",type:r??\"float32\",gpuBuffer:e,dims:n,download:o,dispose:i})},ha=(e,t)=>{let{dataType:r,dims:n,download:o,dispose:i}=t;return new Oe({location:\"ml-tensor\",type:r??\"float32\",mlTensor:e,dims:n,download:o,dispose:i})},ga=(e,t,r)=>new Oe({location:\"cpu-pinned\",type:e,data:t,dims:r??[t.length]})});var St,qt,ya,wa,_a=R(()=>{\"use strict\";St=new Map([[\"float32\",Float32Array],[\"uint8\",Uint8Array],[\"int8\",Int8Array],[\"uint16\",Uint16Array],[\"int16\",Int16Array],[\"int32\",Int32Array],[\"bool\",Uint8Array],[\"float64\",Float64Array],[\"uint32\",Uint32Array],[\"int4\",Uint8Array],[\"uint4\",Uint8Array]]),qt=new Map([[Float32Array,\"float32\"],[Uint8Array,\"uint8\"],[Int8Array,\"int8\"],[Uint16Array,\"uint16\"],[Int16Array,\"int16\"],[Int32Array,\"int32\"],[Float64Array,\"float64\"],[Uint32Array,\"uint32\"]]),ya=!1,wa=()=>{if(!ya){ya=!0;let e=typeof BigInt64Array<\"u\"&&BigInt64Array.from,t=typeof BigUint64Array<\"u\"&&BigUint64Array.from,r=typeof Float16Array<\"u\"&&Float16Array.from;e&&(St.set(\"int64\",BigInt64Array),qt.set(BigInt64Array,\"int64\")),t&&(St.set(\"uint64\",BigUint64Array),qt.set(BigUint64Array,\"uint64\")),r?(St.set(\"float16\",Float16Array),qt.set(Float16Array,\"float16\")):St.set(\"float16\",Uint16Array)}}});var va,$a,xa=R(()=>{\"use strict\";Tr();va=e=>{let t=1;for(let r=0;r{switch(e.location){case\"cpu\":return new Oe(e.type,e.data,t);case\"cpu-pinned\":return new Oe({location:\"cpu-pinned\",data:e.data,type:e.type,dims:t});case\"texture\":return new Oe({location:\"texture\",texture:e.texture,type:e.type,dims:t});case\"gpu-buffer\":return new Oe({location:\"gpu-buffer\",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case\"ml-tensor\":return new Oe({location:\"ml-tensor\",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}});var Oe,Tr=R(()=>{\"use strict\";ca();ba();_a();xa();Oe=class{constructor(t,r,n){wa();let o,i;if(typeof t==\"object\"&&\"location\"in t)switch(this.dataLocation=t.location,o=t.type,i=t.dims,t.location){case\"cpu-pinned\":{let l=St.get(o);if(!l)throw new TypeError(`unsupported type \"${o}\" to create tensor from pinned buffer`);if(!(t.data instanceof l))throw new TypeError(`buffer should be of type ${l.name}`);this.cpuData=t.data;break}case\"texture\":{if(o!==\"float32\")throw new TypeError(`unsupported type \"${o}\" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case\"gpu-buffer\":{if(o!==\"float32\"&&o!==\"float16\"&&o!==\"int32\"&&o!==\"int64\"&&o!==\"uint32\"&&o!==\"uint8\"&&o!==\"bool\"&&o!==\"uint4\"&&o!==\"int4\")throw new TypeError(`unsupported type \"${o}\" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case\"ml-tensor\":{if(o!==\"float32\"&&o!==\"float16\"&&o!==\"int32\"&&o!==\"int64\"&&o!==\"uint32\"&&o!==\"uint64\"&&o!==\"int8\"&&o!==\"uint8\"&&o!==\"bool\"&&o!==\"uint4\"&&o!==\"int4\")throw new TypeError(`unsupported type \"${o}\" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let l,d;if(typeof t==\"string\")if(o=t,d=n,t===\"string\"){if(!Array.isArray(r))throw new TypeError(\"A string tensor's data must be a string array.\");l=r}else{let c=St.get(t);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t===\"float16\"&&c===Uint16Array||t===\"uint4\"||t===\"int4\")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${c.name} as data.`);t===\"uint64\"||t===\"int64\"?l=c.from(r,BigInt):l=c.from(r)}else if(r instanceof c)l=r;else if(r instanceof Uint8ClampedArray)if(t===\"uint8\")l=Uint8Array.from(r);else throw new TypeError(\"A Uint8ClampedArray tensor's data must be type of uint8\");else throw new TypeError(`A ${o} tensor's data must be type of ${c}`)}else if(d=r,Array.isArray(t)){if(t.length===0)throw new TypeError(\"Tensor type cannot be inferred from an empty array.\");let c=typeof t[0];if(c===\"string\")o=\"string\",l=t;else if(c===\"boolean\")o=\"bool\",l=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(t instanceof Uint8ClampedArray)o=\"uint8\",l=Uint8Array.from(t);else{let c=qt.get(t.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);o=c,l=t}if(d===void 0)d=[l.length];else if(!Array.isArray(d))throw new TypeError(\"A tensor's dims must be a number array\");i=d,this.cpuData=l,this.dataLocation=\"cpu\"}let a=va(i);if(this.cpuData&&a!==this.cpuData.length&&!((o===\"uint4\"||o===\"int4\")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=i,this.size=a}static async fromImage(t,r){return pa(t,r)}static fromTexture(t,r){return ma(t,r)}static fromGpuBuffer(t,r){return fa(t,r)}static fromMLTensor(t,r){return ha(t,r)}static fromPinnedBuffer(t,r,n){return ga(t,r,n)}toDataURL(t){return la(this,t)}toImageData(t){return da(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error(\"The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.\");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error(\"The data is not stored as a WebGL texture.\");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error(\"The data is not stored as a WebGPU buffer.\");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error(\"The data is not stored as a WebNN MLTensor.\");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case\"cpu\":case\"cpu-pinned\":return this.data;case\"texture\":case\"gpu-buffer\":case\"ml-tensor\":{if(!this.downloader)throw new Error(\"The current tensor is not created with a specified data downloader.\");if(this.isDownloading)throw new Error(\"The current tensor is being downloaded.\");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation=\"cpu\",this.cpuData=r,t&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error(\"The current tensor is being downloaded.\");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=\"none\"}ensureValid(){if(this.dataLocation===\"none\")throw new Error(\"The tensor is disposed.\")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error(\"Cannot reshape a tensor that owns GPU resource.\");return $a(this,t)}}});var De,Ir=R(()=>{\"use strict\";Tr();De=Oe});var Cr,Sa,Ue,Be,Yn=R(()=>{\"use strict\";jn();Cr=(e,t)=>{(typeof Re.trace>\"u\"?!Re.wasm.trace:!Re.trace)||console.timeStamp(`${e}::ORT::${t}`)},Sa=(e,t)=>{let r=new Error().stack?.split(/\\r\\n|\\r|\\n/g)||[],n=!1;for(let o=0;o{(typeof Re.trace>\"u\"?!Re.wasm.trace:!Re.trace)||Sa(\"BEGIN\",e)},Be=e=>{(typeof Re.trace>\"u\"?!Re.wasm.trace:!Re.trace)||Sa(\"END\",e)}});var Ar,Ta=R(()=>{\"use strict\";Sr();Ir();Yn();Ar=class e{constructor(t){this.handler=t}async run(t,r,n){Ue();let o={},i={};if(typeof t!=\"object\"||t===null||t instanceof De||Array.isArray(t))throw new TypeError(\"'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.\");let a=!0;if(typeof r==\"object\"){if(r===null)throw new TypeError(\"Unexpected argument[1]: cannot be null.\");if(r instanceof De)throw new TypeError(\"'fetches' cannot be a Tensor\");if(Array.isArray(r)){if(r.length===0)throw new TypeError(\"'fetches' cannot be an empty array.\");a=!1;for(let c of r){if(typeof c!=\"string\")throw new TypeError(\"'fetches' must be a string array or an object.\");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);o[c]=null}if(typeof n==\"object\"&&n!==null)i=n;else if(typeof n<\"u\")throw new TypeError(\"'options' must be an object.\")}else{let c=!1,m=Object.getOwnPropertyNames(r);for(let u of this.outputNames)if(m.indexOf(u)!==-1){let h=r[u];(h===null||h instanceof De)&&(c=!0,a=!1,o[u]=h)}if(c){if(typeof n==\"object\"&&n!==null)i=n;else if(typeof n<\"u\")throw new TypeError(\"'options' must be an object.\")}else i=r}}else if(typeof r<\"u\")throw new TypeError(\"Unexpected argument[1]: must be 'fetches' or 'options'.\");for(let c of this.inputNames)if(typeof t[c]>\"u\")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)o[c]=null;let l=await this.handler.run(t,o,i),d={};for(let c in l)if(Object.hasOwnProperty.call(l,c)){let m=l[c];m instanceof De?d[c]=m:d[c]=new De(m.type,m.data,m.dims)}return Be(),d}async release(){return this.handler.dispose()}static async create(t,r,n,o){Ue();let i,a={};if(typeof t==\"string\"){if(i=t,typeof r==\"object\"&&r!==null)a=r;else if(typeof r<\"u\")throw new TypeError(\"'options' must be an object.\")}else if(t instanceof Uint8Array){if(i=t,typeof r==\"object\"&&r!==null)a=r;else if(typeof r<\"u\")throw new TypeError(\"'options' must be an object.\")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<\"u\"&&t instanceof SharedArrayBuffer){let m=t,u=0,h=t.byteLength;if(typeof r==\"object\"&&r!==null)a=r;else if(typeof r==\"number\"){if(u=r,!Number.isSafeInteger(u))throw new RangeError(\"'byteOffset' must be an integer.\");if(u<0||u>=m.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${m.byteLength}).`);if(h=t.byteLength-u,typeof n==\"number\"){if(h=n,!Number.isSafeInteger(h))throw new RangeError(\"'byteLength' must be an integer.\");if(h<=0||u+h>m.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${m.byteLength-u}].`);if(typeof o==\"object\"&&o!==null)a=o;else if(typeof o<\"u\")throw new TypeError(\"'options' must be an object.\")}else if(typeof n<\"u\")throw new TypeError(\"'byteLength' must be a number.\")}else if(typeof r<\"u\")throw new TypeError(\"'options' must be an object.\");i=new Uint8Array(m,u,h)}else throw new TypeError(\"Unexpected argument[0]: must be 'path' or 'buffer'.\");let[l,d]=await xr(a),c=await l.createInferenceSessionHandler(i,d);return Be(),new e(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}});var Mp,Ia=R(()=>{\"use strict\";Ta();Mp=Ar});var Ca=R(()=>{\"use strict\"});var Aa=R(()=>{\"use strict\"});var ka=R(()=>{\"use strict\"});var Ea=R(()=>{\"use strict\"});var Rp,kr,Pa=R(()=>{\"use strict\";Sr();Ir();Rp=\"Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.\",kr=class e{constructor(t,r,n){this.handler=t,this.hasOptimizerModel=r,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error(\"This training session has no evalModel loaded.\")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error(\"This training session has no evalModel loaded.\")}static async create(t,r){let n=t.evalModel||\"\",o=t.optimizerModel||\"\",i=r||{},[a,l]=await xr(i);if(a.createTrainingSessionHandler){let d=await a.createTrainingSessionHandler(t.checkpointState,t.trainModel,n,o,l);return new e(d,!!t.optimizerModel,!!t.evalModel)}else throw new Error(Rp)}typeNarrowingForRunStep(t,r,n,o,i){let a={},l={};if(typeof n!=\"object\"||n===null||n instanceof De||Array.isArray(n))throw new TypeError(\"'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.\");let d=!0;if(typeof o==\"object\"){if(o===null)throw new TypeError(\"Unexpected argument[1]: cannot be null.\");if(o instanceof De)throw new TypeError(\"'fetches' cannot be a Tensor\");if(Array.isArray(o)){if(o.length===0)throw new TypeError(\"'fetches' cannot be an empty array.\");d=!1;for(let c of o){if(typeof c!=\"string\")throw new TypeError(\"'fetches' must be a string array or an object.\");if(r.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);a[c]=null}if(typeof i==\"object\"&&i!==null)l=i;else if(typeof i<\"u\")throw new TypeError(\"'options' must be an object.\")}else{let c=!1,m=Object.getOwnPropertyNames(o);for(let u of r)if(m.indexOf(u)!==-1){let h=o[u];(h===null||h instanceof De)&&(c=!0,d=!1,a[u]=h)}if(c){if(typeof i==\"object\"&&i!==null)l=i;else if(typeof i<\"u\")throw new TypeError(\"'options' must be an object.\")}else l=o}}else if(typeof o<\"u\")throw new TypeError(\"Unexpected argument[1]: must be 'fetches' or 'options'.\");for(let c of t)if(typeof n[c]>\"u\")throw new Error(`input '${c}' is missing in 'feeds'.`);if(d)for(let c of r)a[c]=null;return[a,l]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let n in t)if(Object.hasOwnProperty.call(t,n)){let o=t[n];o instanceof De?r[n]=o:r[n]=new De(o.type,o.data,o.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,n){let[o,i]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,n),a=await this.handler.runTrainStep(t,o,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}async runOptimizerStep(t){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(t||{});else throw new Error(\"This TrainingSession has no OptimizerModel loaded.\")}async runEvalStep(t,r,n){if(this.hasEvalModel){let[o,i]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,n),a=await this.handler.runEvalStep(t,o,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}else throw new Error(\"This TrainingSession has no EvalModel loaded.\")}async getParametersSize(t=!0){return this.handler.getParametersSize(t)}async loadParametersBuffer(t,r=!0){let n=await this.getParametersSize(r);if(t.length!==4*n)throw new Error(\"Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.\");return this.handler.loadParametersBuffer(t,r)}async getContiguousParameters(t=!0){return this.handler.getContiguousParameters(t)}async release(){return this.handler.dispose()}}});var Up,za=R(()=>{\"use strict\";Pa();Up=kr});var Zn={};Ft(Zn,{InferenceSession:()=>Mp,TRACE:()=>Cr,TRACE_FUNC_BEGIN:()=>Ue,TRACE_FUNC_END:()=>Be,Tensor:()=>De,TrainingSession:()=>Up,env:()=>ve,registerBackend:()=>xt});var He=R(()=>{\"use strict\";oa();ua();Ia();Ir();Ca();Aa();Yn();ka();Ea();za()});var Er=R(()=>{\"use strict\"});var Ma={};Ft(Ma,{default:()=>Vp});var Da,Ba,Vp,Ra=R(()=>{\"use strict\";Xn();gt();jt();Da=\"ort-wasm-proxy-worker\",Ba=globalThis.self?.name===Da;Ba&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case\"init-wasm\":Pr(r.wasm).then(()=>{zr(r).then(()=>{postMessage({type:t})},n=>{postMessage({type:t,err:n})})},n=>{postMessage({type:t,err:n})});break;case\"init-ep\":{let{epName:n,env:o}=r;Or(o,n).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case\"copy-from\":{let{buffer:n}=r,o=Kt(n);postMessage({type:t,out:o});break}case\"create\":{let{model:n,options:o}=r;Dr(n,o).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case\"release\":Br(r),postMessage({type:t});break;case\"run\":{let{sessionId:n,inputIndices:o,inputs:i,outputIndices:a,options:l}=r;Mr(n,o,i,a,new Array(a.length).fill(null),l).then(d=>{d.some(c=>c[3]!==\"cpu\")?postMessage({type:t,err:\"Proxy does not support non-cpu tensor location.\"}):postMessage({type:t,out:d},Ur([...i,...d]))},d=>{postMessage({type:t,err:d})});break}case\"end-profiling\":Rr(r),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}});Vp=Ba?null:e=>new Worker(e??Bt,{type:\"module\",name:Da})});var Va={};Ft(Va,{default:()=>Np});var Qn,Ua,Np,Na=R(()=>{\"use strict\";Ua=(Qn=import.meta.url,async function(e={}){function t(){return ue.buffer!=Q.buffer&&be(),Q}function r(){return ue.buffer!=Q.buffer&&be(),ne}function n(){return ue.buffer!=Q.buffer&&be(),we}function o(){return ue.buffer!=Q.buffer&&be(),Ae}function i(){return ue.buffer!=Q.buffer&&be(),$e}function a(){return ue.buffer!=Q.buffer&&be(),de}function l(){return ue.buffer!=Q.buffer&&be(),N}function d(){return ue.buffer!=Q.buffer&&be(),qe}var c,m,u=Object.assign({},e),h=new Promise((s,p)=>{c=s,m=p}),w=typeof window==\"object\",y=typeof importScripts==\"function\",g=y&&self.name==\"em-pthread\";u.mountExternalData=(s,p)=>{s.startsWith(\"./\")&&(s=s.substring(2)),(u.Eb||(u.Eb=new Map)).set(s,p)},u.unmountExternalData=()=>{delete u.Eb};var x=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let $=()=>{let s=(f,b,_)=>(...I)=>{let D=Qe,B=b?.();I=f(...I);let G=b?.();return B!==G&&(f=G,_(B),b=_=null),Qe!=D?new Promise((H,X)=>{Rn={resolve:H,reject:X}}):I},p=f=>async(...b)=>{try{if(u.Fb)throw Error(\"Session already started\");let _=u.Fb={fc:b[0],errors:[]},I=await f(...b);if(u.Fb!==_)throw Error(\"Session mismatch\");u.Gb?.flush();let D=_.errors;if(0G),0u._OrtCreateSession,f=>u._OrtCreateSession=f),u._OrtRun=p(s(u._OrtRun,()=>u._OrtRun,f=>u._OrtRun=f)),u._OrtRunWithBinding=p(s(u._OrtRunWithBinding,()=>u._OrtRunWithBinding,f=>u._OrtRunWithBinding=f)),u._OrtBindInput=s(u._OrtBindInput,()=>u._OrtBindInput,f=>u._OrtBindInput=f),$=void 0};u.jsepInit=(s,p)=>{if($?.(),s===\"webgpu\"){[u.Gb,u.Ub,u.Yb,u.Nb,u.Xb,u.jb,u.Zb,u.bc,u.Vb,u.Wb,u.$b]=p;let f=u.Gb;u.jsepRegisterBuffer=(b,_,I,D)=>f.registerBuffer(b,_,I,D),u.jsepGetBuffer=b=>f.getBuffer(b),u.jsepCreateDownloader=(b,_,I)=>f.createDownloader(b,_,I),u.jsepOnCreateSession=b=>{f.onCreateSession(b)},u.jsepOnReleaseSession=b=>{f.onReleaseSession(b)},u.jsepOnRunStart=b=>f.onRunStart(b),u.cc=(b,_)=>{f.upload(b,_)}}else if(s===\"webnn\"){[u.Gb,u.ac,u.Ob,u.jsepEnsureTensor,u.dc,u.jsepDownloadTensor]=p,u.jsepReleaseTensorId=u.Ob;let f=u.Gb;u.jsepOnRunStart=b=>f.onRunStart(b),u.jsepRegisterMLContext=(b,_)=>{f.registerMLContext(b,_)},u.jsepOnReleaseSession=b=>{f.onReleaseSession(b)},u.jsepCreateMLTensorDownloader=(b,_)=>f.createMLTensorDownloader(b,_),u.jsepRegisterMLTensor=(b,_,I)=>f.registerMLTensor(b,_,I),u.jsepCreateMLContext=b=>f.createMLContext(b),u.qc=(b,_,I,D,B)=>f.registerMLConstant(b,_,I,D,B,u.Eb)}};var v,S,T=Object.assign({},u),C=\"./this.program\",A=(s,p)=>{throw p},P=\"\";(w||y)&&(y?P=self.location.href:typeof document<\"u\"&&document.currentScript&&(P=document.currentScript.src),Qn&&(P=Qn),P=P.startsWith(\"blob:\")?\"\":P.substr(0,P.replace(/[?#].*/,\"\").lastIndexOf(\"/\")+1),y&&(S=s=>{var p=new XMLHttpRequest;return p.open(\"GET\",s,!1),p.responseType=\"arraybuffer\",p.send(null),new Uint8Array(p.response)}),v=(s,p,f)=>{var b=new XMLHttpRequest;b.open(\"GET\",s,!0),b.responseType=\"arraybuffer\",b.onload=()=>{b.status==200||b.status==0&&b.response?p(b.response):f()},b.onerror=f,b.send(null)});var O,U=console.log.bind(console),L=console.error.bind(console),j=U,K=L;if(Object.assign(u,T),T=null,g){let s=function(p){try{var f=p.data,b=f.cmd;if(b===\"load\"){let _=[];self.onmessage=I=>_.push(I),self.startWorker=()=>{postMessage({cmd:\"loaded\"});for(let I of _)s(I);self.onmessage=s};for(let I of f.handlers)u[I]&&!u[I].proxy||(u[I]=(...D)=>{postMessage({Mb:\"callHandler\",oc:I,args:D})},I==\"print\"&&(j=u[I]),I==\"printErr\"&&(K=u[I]));ue=f.wasmMemory,be(),W(f.wasmModule)}else if(b===\"run\"){Wn(f.pthread_ptr,0,0,1,0,0),Dn(f.pthread_ptr),hc(),Yo(),ee||(qi(),ee=!0);try{gc(f.start_routine,f.arg)}catch(_){if(_!=\"unwind\")throw _}}else b===\"cancel\"?Dt()&&wr(-1):f.target!==\"setimmediate\"&&(b===\"checkMailbox\"?ee&&dr():b&&(K(`worker: received unknown command ${b}`),K(f)))}catch(_){throw ji(),_}};var mg=s,W,ee=!1;K=function(...p){p=p.join(\" \"),console.error(p)},self.alert=function(...p){postMessage({Mb:\"alert\",text:p.join(\" \"),rc:Dt()})},u.instantiateWasm=(p,f)=>new Promise(b=>{W=_=>{_=new WebAssembly.Instance(_,Ho()),f(_),b()}}),self.onunhandledrejection=p=>{throw p.reason||p},self.onmessage=s}u.wasmBinary&&(O=u.wasmBinary);var ue,Z,J,Q,ne,we,Ae,$e,de,N,q,he,qe,_e=!1;function be(){var s=ue.buffer;u.HEAP8=Q=new Int8Array(s),u.HEAP16=we=new Int16Array(s),u.HEAPU8=ne=new Uint8Array(s),u.HEAPU16=Ae=new Uint16Array(s),u.HEAP32=$e=new Int32Array(s),u.HEAPU32=de=new Uint32Array(s),u.HEAPF32=N=new Float32Array(s),u.HEAPF64=qe=new Float64Array(s),u.HEAP64=q=new BigInt64Array(s),u.HEAPU64=he=new BigUint64Array(s)}if(!g){if(!((ue=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof x))throw K(\"requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag\"),Error(\"bad memory\");be()}var Ye=[],Lt=[],_n=[],Gt=0,vn=null,Ht=null;function Vo(){if(--Gt==0&&(vn!==null&&(clearInterval(vn),vn=null),Ht)){var s=Ht;Ht=null,s()}}function ct(s){throw K(s=\"Aborted(\"+s+\")\"),_e=!0,J=1,s=new WebAssembly.RuntimeError(s+\". Build with -sASSERTIONS for more info.\"),m(s),s}var $n,No=s=>s.startsWith(\"data:application/octet-stream;base64,\"),Wo=s=>s.startsWith(\"file://\");function Lo(s){if(s==$n&&O)return new Uint8Array(O);if(S)return S(s);throw\"both async and sync fetching of the wasm failed\"}function Go(s,p,f){return function(b){if(!O&&(w||y)){if(typeof fetch==\"function\"&&!Wo(b))return fetch(b,{credentials:\"same-origin\"}).then(_=>{if(!_.ok)throw`failed to load wasm binary file at '${b}'`;return _.arrayBuffer()}).catch(()=>Lo(b));if(v)return new Promise((_,I)=>{v(b,D=>_(new Uint8Array(D)),I)})}return Promise.resolve().then(()=>Lo(b))}(s).then(b=>WebAssembly.instantiate(b,p)).then(f,b=>{K(`failed to asynchronously prepare wasm: ${b}`),ct(b)})}function Ho(){return{a:{O:fc,Aa:mc,b:yc,aa:Jo,B:ri,qa:ni,Y:ii,_:ai,ra:si,oa:ui,ha:li,na:di,L:ci,Z:pi,W:mi,pa:fi,X:hi,wa:wc,F:vc,Q:$c,P:Sc,E:Ic,u:Cc,q:Ac,G:kc,A:Mc,R:Rc,ua:Uc,ka:Vc,U:Nc,ba:Wc,H:Lc,ja:Dn,ta:Gc,t:Hc,x:jc,o:Kc,l:Zc,c:zn,n:Xc,j:ep,w:tp,p:rp,g:np,s:op,m:ip,e:ap,k:sp,i:up,h:lp,d:dp,ea:cp,fa:pp,ga:mp,ca:ki,da:Ei,T:fp,f:hp,D:gp,I:bp,M:yp,y:wp,sa:_p,V:vp,v:zi,z:$p,N:xp,S:Sp,za:Tp,ya:Ip,la:Bi,ma:Mi,$:Cn,C:Ri,K:Ui,ia:Vi,J:Ni,a:ue,xa:In,va:Gi,r:kp}}}var xn={874964:(s,p,f,b,_)=>{if(u===void 0||!u.Eb)return 1;if((s=Ce(Number(s>>>0))).startsWith(\"./\")&&(s=s.substring(2)),!(s=u.Eb.get(s)))return 2;if(p=Number(p>>>0),f=Number(f>>>0),b=Number(b>>>0),p+f>s.byteLength)return 3;try{let I=s.subarray(p,p+f);switch(_){case 0:r().set(I,b>>>0);break;case 1:u.cc(b,I);break;default:return 4}return 0}catch{return 4}},875679:(s,p,f)=>{u.dc(s,r().subarray(p>>>0,p+f>>>0))},875742:()=>u.ac(),875783:s=>{u.Ob(s)},875819:()=>{u.Vb()},875850:()=>{u.Wb()},875879:()=>{u.$b()},875904:s=>u.Ub(s),875937:s=>u.Yb(s),875969:(s,p,f)=>{u.Nb(Number(s),Number(p),Number(f),!0)},876032:(s,p,f)=>{u.Nb(Number(s),Number(p),Number(f))},876089:()=>typeof wasmOffsetConverter<\"u\",876146:s=>{u.jb(\"Abs\",s,void 0)},876197:s=>{u.jb(\"Neg\",s,void 0)},876248:s=>{u.jb(\"Floor\",s,void 0)},876301:s=>{u.jb(\"Ceil\",s,void 0)},876353:s=>{u.jb(\"Reciprocal\",s,void 0)},876411:s=>{u.jb(\"Sqrt\",s,void 0)},876463:s=>{u.jb(\"Exp\",s,void 0)},876514:s=>{u.jb(\"Erf\",s,void 0)},876565:s=>{u.jb(\"Sigmoid\",s,void 0)},876620:(s,p,f)=>{u.jb(\"HardSigmoid\",s,{alpha:p,beta:f})},876699:s=>{u.jb(\"Log\",s,void 0)},876750:s=>{u.jb(\"Sin\",s,void 0)},876801:s=>{u.jb(\"Cos\",s,void 0)},876852:s=>{u.jb(\"Tan\",s,void 0)},876903:s=>{u.jb(\"Asin\",s,void 0)},876955:s=>{u.jb(\"Acos\",s,void 0)},877007:s=>{u.jb(\"Atan\",s,void 0)},877059:s=>{u.jb(\"Sinh\",s,void 0)},877111:s=>{u.jb(\"Cosh\",s,void 0)},877163:s=>{u.jb(\"Asinh\",s,void 0)},877216:s=>{u.jb(\"Acosh\",s,void 0)},877269:s=>{u.jb(\"Atanh\",s,void 0)},877322:s=>{u.jb(\"Tanh\",s,void 0)},877374:s=>{u.jb(\"Not\",s,void 0)},877425:(s,p,f)=>{u.jb(\"Clip\",s,{min:p,max:f})},877494:s=>{u.jb(\"Clip\",s,void 0)},877546:(s,p)=>{u.jb(\"Elu\",s,{alpha:p})},877604:s=>{u.jb(\"Gelu\",s,void 0)},877656:s=>{u.jb(\"Relu\",s,void 0)},877708:(s,p)=>{u.jb(\"LeakyRelu\",s,{alpha:p})},877772:(s,p)=>{u.jb(\"ThresholdedRelu\",s,{alpha:p})},877842:(s,p)=>{u.jb(\"Cast\",s,{to:p})},877900:s=>{u.jb(\"Add\",s,void 0)},877951:s=>{u.jb(\"Sub\",s,void 0)},878002:s=>{u.jb(\"Mul\",s,void 0)},878053:s=>{u.jb(\"Div\",s,void 0)},878104:s=>{u.jb(\"Pow\",s,void 0)},878155:s=>{u.jb(\"Equal\",s,void 0)},878208:s=>{u.jb(\"Greater\",s,void 0)},878263:s=>{u.jb(\"GreaterOrEqual\",s,void 0)},878325:s=>{u.jb(\"Less\",s,void 0)},878377:s=>{u.jb(\"LessOrEqual\",s,void 0)},878436:(s,p,f,b,_)=>{u.jb(\"ReduceMean\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},878611:(s,p,f,b,_)=>{u.jb(\"ReduceMax\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},878785:(s,p,f,b,_)=>{u.jb(\"ReduceMin\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},878959:(s,p,f,b,_)=>{u.jb(\"ReduceProd\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},879134:(s,p,f,b,_)=>{u.jb(\"ReduceSum\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},879308:(s,p,f,b,_)=>{u.jb(\"ReduceL1\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},879481:(s,p,f,b,_)=>{u.jb(\"ReduceL2\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},879654:(s,p,f,b,_)=>{u.jb(\"ReduceLogSum\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},879831:(s,p,f,b,_)=>{u.jb(\"ReduceSumSquare\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},880011:(s,p,f,b,_)=>{u.jb(\"ReduceLogSumExp\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},880191:s=>{u.jb(\"Where\",s,void 0)},880244:(s,p,f)=>{u.jb(\"Transpose\",s,{perm:p?Array.from(i().subarray(Number(p)>>>0,Number(f)>>>0)):[]})},880368:(s,p,f,b)=>{u.jb(\"DepthToSpace\",s,{blocksize:p,mode:Ce(f),format:b?\"NHWC\":\"NCHW\"})},880501:(s,p,f,b)=>{u.jb(\"DepthToSpace\",s,{blocksize:p,mode:Ce(f),format:b?\"NHWC\":\"NCHW\"})},880634:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z,le)=>{u.jb(\"ConvTranspose\",s,{format:G?\"NHWC\":\"NCHW\",autoPad:p,dilations:[f],group:b,kernelShape:[_],pads:[I,D],strides:[B],wIsConst:()=>!!t()[H>>>0],outputPadding:X?Array.from(i().subarray(Number(X)>>>0,Number(ce)>>>0)):[],outputShape:ge?Array.from(i().subarray(Number(ge)>>>0,Number(z)>>>0)):[],activation:Ce(le)})},881067:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z)=>{u.jb(\"ConvTranspose\",s,{format:B?\"NHWC\":\"NCHW\",autoPad:p,dilations:Array.from(i().subarray(Number(f)>>>0,2+(Number(f)>>>0)>>>0)),group:b,kernelShape:Array.from(i().subarray(Number(_)>>>0,2+(Number(_)>>>0)>>>0)),pads:Array.from(i().subarray(Number(I)>>>0,4+(Number(I)>>>0)>>>0)),strides:Array.from(i().subarray(Number(D)>>>0,2+(Number(D)>>>0)>>>0)),wIsConst:()=>!!t()[G>>>0],outputPadding:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],outputShape:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[],activation:Ce(z)})},881728:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z,le)=>{u.jb(\"ConvTranspose\",s,{format:G?\"NHWC\":\"NCHW\",autoPad:p,dilations:[f],group:b,kernelShape:[_],pads:[I,D],strides:[B],wIsConst:()=>!!t()[H>>>0],outputPadding:X?Array.from(i().subarray(Number(X)>>>0,Number(ce)>>>0)):[],outputShape:ge?Array.from(i().subarray(Number(ge)>>>0,Number(z)>>>0)):[],activation:Ce(le)})},882161:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z)=>{u.jb(\"ConvTranspose\",s,{format:B?\"NHWC\":\"NCHW\",autoPad:p,dilations:Array.from(i().subarray(Number(f)>>>0,2+(Number(f)>>>0)>>>0)),group:b,kernelShape:Array.from(i().subarray(Number(_)>>>0,2+(Number(_)>>>0)>>>0)),pads:Array.from(i().subarray(Number(I)>>>0,4+(Number(I)>>>0)>>>0)),strides:Array.from(i().subarray(Number(D)>>>0,2+(Number(D)>>>0)>>>0)),wIsConst:()=>!!t()[G>>>0],outputPadding:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],outputShape:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[],activation:Ce(z)})},882822:(s,p)=>{u.jb(\"GlobalAveragePool\",s,{format:p?\"NHWC\":\"NCHW\"})},882913:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z)=>{u.jb(\"AveragePool\",s,{format:z?\"NHWC\":\"NCHW\",auto_pad:p,ceil_mode:f,count_include_pad:b,storage_order:_,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(D)>>>0)):[],kernel_shape:B?Array.from(i().subarray(Number(B)>>>0,Number(G)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},883392:(s,p)=>{u.jb(\"GlobalAveragePool\",s,{format:p?\"NHWC\":\"NCHW\"})},883483:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z)=>{u.jb(\"AveragePool\",s,{format:z?\"NHWC\":\"NCHW\",auto_pad:p,ceil_mode:f,count_include_pad:b,storage_order:_,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(D)>>>0)):[],kernel_shape:B?Array.from(i().subarray(Number(B)>>>0,Number(G)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},883962:(s,p)=>{u.jb(\"GlobalMaxPool\",s,{format:p?\"NHWC\":\"NCHW\"})},884049:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z)=>{u.jb(\"MaxPool\",s,{format:z?\"NHWC\":\"NCHW\",auto_pad:p,ceil_mode:f,count_include_pad:b,storage_order:_,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(D)>>>0)):[],kernel_shape:B?Array.from(i().subarray(Number(B)>>>0,Number(G)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},884524:(s,p)=>{u.jb(\"GlobalMaxPool\",s,{format:p?\"NHWC\":\"NCHW\"})},884611:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z)=>{u.jb(\"MaxPool\",s,{format:z?\"NHWC\":\"NCHW\",auto_pad:p,ceil_mode:f,count_include_pad:b,storage_order:_,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(D)>>>0)):[],kernel_shape:B?Array.from(i().subarray(Number(B)>>>0,Number(G)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},885086:(s,p,f,b,_)=>{u.jb(\"Gemm\",s,{alpha:p,beta:f,transA:b,transB:_})},885190:s=>{u.jb(\"MatMul\",s,void 0)},885244:(s,p,f,b)=>{u.jb(\"ArgMax\",s,{keepDims:!!p,selectLastIndex:!!f,axis:b})},885352:(s,p,f,b)=>{u.jb(\"ArgMin\",s,{keepDims:!!p,selectLastIndex:!!f,axis:b})},885460:(s,p)=>{u.jb(\"Softmax\",s,{axis:p})},885523:(s,p)=>{u.jb(\"Concat\",s,{axis:p})},885583:(s,p,f,b,_)=>{u.jb(\"Split\",s,{axis:p,numOutputs:f,splitSizes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},885739:s=>{u.jb(\"Expand\",s,void 0)},885793:(s,p)=>{u.jb(\"Gather\",s,{axis:Number(p)})},885864:(s,p)=>{u.jb(\"GatherElements\",s,{axis:Number(p)})},885943:(s,p,f,b,_,I,D,B,G,H,X)=>{u.jb(\"Resize\",s,{antialias:p,axes:f?Array.from(i().subarray(Number(f)>>>0,Number(b)>>>0)):[],coordinateTransformMode:Ce(_),cubicCoeffA:I,excludeOutside:D,extrapolationValue:B,keepAspectRatioPolicy:Ce(G),mode:Ce(H),nearestMode:Ce(X)})},886305:(s,p,f,b,_,I,D)=>{u.jb(\"Slice\",s,{starts:p?Array.from(i().subarray(Number(p)>>>0,Number(f)>>>0)):[],ends:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[],axes:I?Array.from(i().subarray(Number(I)>>>0,Number(D)>>>0)):[]})},886569:s=>{u.jb(\"Tile\",s,void 0)},886621:(s,p,f)=>{u.jb(\"InstanceNormalization\",s,{epsilon:p,format:f?\"NHWC\":\"NCHW\"})},886735:(s,p,f)=>{u.jb(\"InstanceNormalization\",s,{epsilon:p,format:f?\"NHWC\":\"NCHW\"})},886849:s=>{u.jb(\"Range\",s,void 0)},886902:(s,p)=>{u.jb(\"Einsum\",s,{equation:Ce(p)})},886983:(s,p,f,b,_)=>{u.jb(\"Pad\",s,{mode:p,value:f,pads:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},887126:(s,p,f,b,_,I)=>{u.jb(\"BatchNormalization\",s,{epsilon:p,momentum:f,spatial:!!_,trainingMode:!!b,format:I?\"NHWC\":\"NCHW\"})},887295:(s,p,f,b,_,I)=>{u.jb(\"BatchNormalization\",s,{epsilon:p,momentum:f,spatial:!!_,trainingMode:!!b,format:I?\"NHWC\":\"NCHW\"})},887464:(s,p,f)=>{u.jb(\"CumSum\",s,{exclusive:Number(p),reverse:Number(f)})},887561:(s,p,f)=>{u.jb(\"DequantizeLinear\",s,{axis:p,blockSize:f})},887651:(s,p,f,b,_)=>{u.jb(\"GridSample\",s,{align_corners:p,mode:Ce(f),padding_mode:Ce(b),format:_?\"NHWC\":\"NCHW\"})},887821:(s,p,f,b,_)=>{u.jb(\"GridSample\",s,{align_corners:p,mode:Ce(f),padding_mode:Ce(b),format:_?\"NHWC\":\"NCHW\"})},887991:(s,p,f,b,_,I,D,B,G)=>{u.jb(\"Attention\",s,{numHeads:p,isUnidirectional:f,maskFilterValue:b,scale:_,doRotary:I,qkvHiddenSizes:D?Array.from(i().subarray(Number(B)>>>0,Number(B)+D>>>0)):[],pastPresentShareBuffer:!!G})},888263:s=>{u.jb(\"BiasAdd\",s,void 0)},888318:s=>{u.jb(\"BiasSplitGelu\",s,void 0)},888379:s=>{u.jb(\"FastGelu\",s,void 0)},888435:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z,le,Se)=>{u.jb(\"Conv\",s,{format:ce?\"NHWC\":\"NCHW\",auto_pad:p,dilations:f?Array.from(i().subarray(Number(f)>>>0,Number(b)>>>0)):[],group:_,kernel_shape:I?Array.from(i().subarray(Number(I)>>>0,Number(D)>>>0)):[],pads:B?Array.from(i().subarray(Number(B)>>>0,Number(G)>>>0)):[],strides:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],w_is_const:()=>!!t()[Number(ge)>>>0],activation:Ce(z),activation_params:le?Array.from(l().subarray(Number(le)>>>0,Number(Se)>>>0)):[]})},889019:s=>{u.jb(\"Gelu\",s,void 0)},889071:(s,p,f,b,_,I,D,B,G)=>{u.jb(\"GroupQueryAttention\",s,{numHeads:p,kvNumHeads:f,scale:b,softcap:_,doRotary:I,rotaryInterleaved:D,smoothSoftmax:B,localWindowSize:G})},889288:(s,p,f,b)=>{u.jb(\"LayerNormalization\",s,{axis:p,epsilon:f,simplified:!!b})},889399:(s,p,f,b)=>{u.jb(\"LayerNormalization\",s,{axis:p,epsilon:f,simplified:!!b})},889510:(s,p,f,b,_,I)=>{u.jb(\"MatMulNBits\",s,{k:p,n:f,accuracyLevel:b,bits:_,blockSize:I})},889637:(s,p,f,b,_,I)=>{u.jb(\"MultiHeadAttention\",s,{numHeads:p,isUnidirectional:f,maskFilterValue:b,scale:_,doRotary:I})},889796:(s,p)=>{u.jb(\"QuickGelu\",s,{alpha:p})},889860:(s,p,f,b,_)=>{u.jb(\"RotaryEmbedding\",s,{interleaved:!!p,numHeads:f,rotaryEmbeddingDim:b,scale:_})},889999:(s,p,f)=>{u.jb(\"SkipLayerNormalization\",s,{epsilon:p,simplified:!!f})},890101:(s,p,f)=>{u.jb(\"SkipLayerNormalization\",s,{epsilon:p,simplified:!!f})},890203:(s,p,f,b)=>{u.jb(\"GatherBlockQuantized\",s,{gatherAxis:p,quantizeAxis:f,blockSize:b})},890324:s=>{u.Zb(s)},890358:(s,p)=>u.bc(Number(s),Number(p),u.Fb.fc,u.Fb.errors)};function mc(s,p,f){return Si(async()=>{await u.Xb(Number(s),Number(p),Number(f))})}function fc(){return typeof wasmOffsetConverter<\"u\"}function Sn(s){this.name=\"ExitStatus\",this.message=`Program terminated with exit(${s})`,this.status=s}var Tn=s=>{s.terminate(),s.onmessage=()=>{}},Fo=s=>{pt.length==0&&(Xo(),Zo(pt[0]));var p=pt.pop();if(!p)return 6;_t.push(p),Ze[s.Ab]=p,p.Ab=s.Ab;var f={cmd:\"run\",start_routine:s.hc,arg:s.Qb,pthread_ptr:s.Ab};return p.postMessage(f,s.mc),0},wt=0,xe=(s,p,...f)=>{for(var b=2*f.length,_=Hn(),I=Gn(8*b),D=I>>>3,B=0;B>>0]=G)}return s=Ki(s,0,b,I,p),_r(_),s};function In(s){if(g)return xe(0,1,s);if(J=s,!(0{if(J=s,g)throw qo(s),\"unwind\";In(s)},pt=[],_t=[],jo=[],Ze={},Ko=s=>{var p=s.Ab;delete Ze[p],pt.push(s),_t.splice(_t.indexOf(s),1),s.Ab=0,Ln(p)};function Yo(){jo.forEach(s=>s())}var Zo=s=>new Promise(p=>{s.onmessage=_=>{var I=(_=_.data).cmd;if(_.targetThread&&_.targetThread!=Dt()){var D=Ze[_.targetThread];D?D.postMessage(_,_.transferList):K(`Internal error! Worker sent a message \"${I}\" to target pthread ${_.targetThread}, but that thread no longer exists!`)}else I===\"checkMailbox\"?dr():I===\"spawnThread\"?Fo(_):I===\"cleanupThread\"?Ko(Ze[_.thread]):I===\"killThread\"?(_=_.thread,I=Ze[_],delete Ze[_],Tn(I),Ln(_),_t.splice(_t.indexOf(I),1),I.Ab=0):I===\"cancelThread\"?Ze[_.thread].postMessage({cmd:\"cancel\"}):I===\"loaded\"?(s.loaded=!0,p(s)):I===\"alert\"?alert(`Thread ${_.threadId}: ${_.text}`):_.target===\"setimmediate\"?s.postMessage(_):I===\"callHandler\"?u[_.handler](..._.args):I&&K(`worker sent an unknown command ${I}`)},s.onerror=_=>{throw K(`worker sent an error! ${_.filename}:${_.lineno}: ${_.message}`),_};var f,b=[];for(f of[])u.hasOwnProperty(f)&&b.push(f);s.postMessage({cmd:\"load\",handlers:b,wasmMemory:ue,wasmModule:Z})});function Xo(){var s=new Worker(new URL(import.meta.url),{type:\"module\",workerData:\"em-pthread\",name:\"em-pthread\"});pt.push(s)}var lr=s=>{for(;0{var s=Dt(),p=a()[s+52>>>2>>>0];s=a()[s+56>>>2>>>0],Zi(p,p-s),_r(p)},gc=(s,p)=>{wt=0,s=Xi(s,p),0>>=0);throw p>>>=0,f>>>=0,a()[b.Jb+16>>>2>>>0]=0,a()[b.Jb+4>>>2>>>0]=p,a()[b.Jb+8>>>2>>>0]=f,s}function Qo(s,p,f,b){return g?xe(2,1,s,p,f,b):Jo(s,p,f,b)}function Jo(s,p,f,b){if(s>>>=0,p>>>=0,f>>>=0,b>>>=0,x===void 0)return K(\"Current environment does not support SharedArrayBuffer, pthreads are not available!\"),6;var _=[];return g&&_.length===0?Qo(s,p,f,b):(s={hc:f,Ab:s,Qb:b,mc:_},g?(s.Mb=\"spawnThread\",postMessage(s,_),0):Fo(s))}var ei=typeof TextDecoder<\"u\"?new TextDecoder(\"utf8\"):void 0,ti=(s,p,f)=>{var b=(p>>>=0)+f;for(f=p;s[f]&&!(f>=b);)++f;if(16(_=(240&_)==224?(15&_)<<12|I<<6|D:(7&_)<<18|I<<12|D<<6|63&s[p++])?b+=String.fromCharCode(_):(_-=65536,b+=String.fromCharCode(55296|_>>10,56320|1023&_))}}else b+=String.fromCharCode(_)}return b},Ce=(s,p)=>(s>>>=0)?ti(r(),s,p):\"\";function ri(s,p,f){return g?xe(3,1,s,p,f):0}function ni(s,p){if(g)return xe(4,1,s,p)}var An=s=>{for(var p=0,f=0;f=b?p++:2047>=b?p+=2:55296<=b&&57343>=b?(p+=4,++f):p+=3}return p},oi=(s,p,f,b)=>{if(!(0>>=0;b=f+b-1;for(var I=0;I=D&&(D=65536+((1023&D)<<10)|1023&s.charCodeAt(++I)),127>=D){if(f>=b)break;p[f++>>>0]=D}else{if(2047>=D){if(f+1>=b)break;p[f++>>>0]=192|D>>6}else{if(65535>=D){if(f+2>=b)break;p[f++>>>0]=224|D>>12}else{if(f+3>=b)break;p[f++>>>0]=240|D>>18,p[f++>>>0]=128|D>>12&63}p[f++>>>0]=128|D>>6&63}p[f++>>>0]=128|63&D}}return p[f>>>0]=0,f-_},Pt=(s,p,f)=>oi(s,r(),p,f);function ii(s,p){if(g)return xe(5,1,s,p)}function ai(s,p,f){if(g)return xe(6,1,s,p,f)}function si(s,p,f){return g?xe(7,1,s,p,f):0}function ui(s,p){if(g)return xe(8,1,s,p)}function li(s,p,f){if(g)return xe(9,1,s,p,f)}function di(s,p,f,b){if(g)return xe(10,1,s,p,f,b)}function ci(s,p,f,b){if(g)return xe(11,1,s,p,f,b)}function pi(s,p,f,b){if(g)return xe(12,1,s,p,f,b)}function mi(s){if(g)return xe(13,1,s)}function fi(s,p){if(g)return xe(14,1,s,p)}function hi(s,p,f){if(g)return xe(15,1,s,p,f)}var gi,mt,wc=()=>{ct(\"\")},Xe=s=>{for(var p=\"\";r()[s>>>0];)p+=gi[r()[s++>>>0]];return p},kn={},En={},_c={};function at(s,p,f={}){if(!(\"argPackAdvance\"in p))throw new TypeError(\"registerType registeredInstance requires argPackAdvance\");return function(b,_,I={}){var D=_.name;if(!b)throw new mt(`type \"${D}\" must have a positive integer typeid pointer`);if(En.hasOwnProperty(b)){if(I.Sb)return;throw new mt(`Cannot register type '${D}' twice`)}En[b]=_,delete _c[b],kn.hasOwnProperty(b)&&(_=kn[b],delete kn[b],_.forEach(B=>B()))}(s,p,f)}var bi=(s,p,f)=>{switch(p){case 1:return f?b=>t()[b>>>0]:b=>r()[b>>>0];case 2:return f?b=>n()[b>>>1>>>0]:b=>o()[b>>>1>>>0];case 4:return f?b=>i()[b>>>2>>>0]:b=>a()[b>>>2>>>0];case 8:return f?b=>q[b>>>3]:b=>he[b>>>3];default:throw new TypeError(`invalid integer width (${p}): ${s}`)}};function vc(s,p,f){f>>>=0,at(s>>>=0,{name:p=Xe(p>>>0),fromWireType:b=>b,toWireType:function(b,_){if(typeof _!=\"bigint\"&&typeof _!=\"number\")throw _=_===null?\"null\":(b=typeof _)==\"object\"||b===\"array\"||b===\"function\"?_.toString():\"\"+_,new TypeError(`Cannot convert \"${_}\" to ${this.name}`);return typeof _==\"number\"&&(_=BigInt(_)),_},argPackAdvance:ft,readValueFromPointer:bi(p,f,p.indexOf(\"u\")==-1),Db:null})}var ft=8;function $c(s,p,f,b){at(s>>>=0,{name:p=Xe(p>>>0),fromWireType:function(_){return!!_},toWireType:function(_,I){return I?f:b},argPackAdvance:ft,readValueFromPointer:function(_){return this.fromWireType(r()[_>>>0])},Db:null})}var Pn=[],st=[];function zn(s){9<(s>>>=0)&&--st[s+1]==0&&(st[s]=void 0,Pn.push(s))}var Le=s=>{if(!s)throw new mt(\"Cannot use deleted val. handle = \"+s);return st[s]},Ge=s=>{switch(s){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let p=Pn.pop()||st.length;return st[p]=s,st[p+1]=1,p}};function On(s){return this.fromWireType(a()[s>>>2>>>0])}var xc={name:\"emscripten::val\",fromWireType:s=>{var p=Le(s);return zn(s),p},toWireType:(s,p)=>Ge(p),argPackAdvance:ft,readValueFromPointer:On,Db:null};function Sc(s){return at(s>>>0,xc)}var Tc=(s,p)=>{switch(p){case 4:return function(f){return this.fromWireType(l()[f>>>2>>>0])};case 8:return function(f){return this.fromWireType(d()[f>>>3>>>0])};default:throw new TypeError(`invalid float width (${p}): ${s}`)}};function Ic(s,p,f){f>>>=0,at(s>>>=0,{name:p=Xe(p>>>0),fromWireType:b=>b,toWireType:(b,_)=>_,argPackAdvance:ft,readValueFromPointer:Tc(p,f),Db:null})}function Cc(s,p,f,b,_){if(s>>>=0,f>>>=0,p=Xe(p>>>0),_===-1&&(_=4294967295),_=B=>B,b===0){var I=32-8*f;_=B=>B<>>I}var D=p.includes(\"unsigned\")?function(B,G){return G>>>0}:function(B,G){return G};at(s,{name:p,fromWireType:_,toWireType:D,argPackAdvance:ft,readValueFromPointer:bi(p,f,b!==0),Db:null})}function Ac(s,p,f){function b(I){var D=a()[I>>>2>>>0];return I=a()[I+4>>>2>>>0],new _(t().buffer,I,D)}var _=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][p];at(s>>>=0,{name:f=Xe(f>>>0),fromWireType:b,argPackAdvance:ft,readValueFromPointer:b},{Sb:!0})}function kc(s,p){s>>>=0;var f=(p=Xe(p>>>0))===\"std::string\";at(s,{name:p,fromWireType:function(b){var _=a()[b>>>2>>>0],I=b+4;if(f)for(var D=I,B=0;B<=_;++B){var G=I+B;if(B==_||r()[G>>>0]==0){if(D=Ce(D,G-D),H===void 0)var H=D;else H+=String.fromCharCode(0),H+=D;D=G+1}}else{for(H=Array(_),B=0;B<_;++B)H[B]=String.fromCharCode(r()[I+B>>>0]);H=H.join(\"\")}return Je(b),H},toWireType:function(b,_){_ instanceof ArrayBuffer&&(_=new Uint8Array(_));var I=typeof _==\"string\";if(!(I||_ instanceof Uint8Array||_ instanceof Uint8ClampedArray||_ instanceof Int8Array))throw new mt(\"Cannot pass non-string to std::string\");var D=f&&I?An(_):_.length,B=yr(4+D+1),G=B+4;if(a()[B>>>2>>>0]=D,f&&I)Pt(_,G,D+1);else if(I)for(I=0;I>>0]=H}else for(I=0;I>>0]=_[I];return b!==null&&b.push(Je,B),B},argPackAdvance:ft,readValueFromPointer:On,Db(b){Je(b)}})}var yi=typeof TextDecoder<\"u\"?new TextDecoder(\"utf-16le\"):void 0,Ec=(s,p)=>{for(var f=s>>1,b=f+p/2;!(f>=b)&&o()[f>>>0];)++f;if(32<(f<<=1)-s&&yi)return yi.decode(r().slice(s,f));for(f=\"\",b=0;!(b>=p/2);++b){var _=n()[s+2*b>>>1>>>0];if(_==0)break;f+=String.fromCharCode(_)}return f},Pc=(s,p,f)=>{if(f??=2147483647,2>f)return 0;var b=p;f=(f-=2)<2*s.length?f/2:s.length;for(var _=0;_>>1>>>0]=I,p+=2}return n()[p>>>1>>>0]=0,p-b},zc=s=>2*s.length,Oc=(s,p)=>{for(var f=0,b=\"\";!(f>=p/4);){var _=i()[s+4*f>>>2>>>0];if(_==0)break;++f,65536<=_?(_-=65536,b+=String.fromCharCode(55296|_>>10,56320|1023&_)):b+=String.fromCharCode(_)}return b},Dc=(s,p,f)=>{if(p>>>=0,f??=2147483647,4>f)return 0;var b=p;f=b+f-4;for(var _=0;_=I&&(I=65536+((1023&I)<<10)|1023&s.charCodeAt(++_)),i()[p>>>2>>>0]=I,(p+=4)+4>f)break}return i()[p>>>2>>>0]=0,p-b},Bc=s=>{for(var p=0,f=0;f=b&&++f,p+=4}return p};function Mc(s,p,f){if(s>>>=0,p>>>=0,f=Xe(f>>>=0),p===2)var b=Ec,_=Pc,I=zc,D=B=>o()[B>>>1>>>0];else p===4&&(b=Oc,_=Dc,I=Bc,D=B=>a()[B>>>2>>>0]);at(s,{name:f,fromWireType:B=>{for(var G,H=a()[B>>>2>>>0],X=B+4,ce=0;ce<=H;++ce){var ge=B+4+ce*p;ce!=H&&D(ge)!=0||(X=b(X,ge-X),G===void 0?G=X:(G+=String.fromCharCode(0),G+=X),X=ge+p)}return Je(B),G},toWireType:(B,G)=>{if(typeof G!=\"string\")throw new mt(`Cannot pass non-string to C++ string type ${f}`);var H=I(G),X=yr(4+H+p);return a()[X>>>2>>>0]=H/p,_(G,X+4,H+p),B!==null&&B.push(Je,X),X},argPackAdvance:ft,readValueFromPointer:On,Db(B){Je(B)}})}function Rc(s,p){at(s>>>=0,{Tb:!0,name:p=Xe(p>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Uc=()=>1;function Vc(s){Wn(s>>>0,!y,1,!w,131072,!1),Yo()}var wi=s=>{if(!_e)try{if(s(),!(0>>=0,typeof Atomics.nc==\"function\"&&(Atomics.nc(i(),s>>>2,s).value.then(dr),s+=128,Atomics.store(i(),s>>>2,1))}var dr=()=>{var s=Dt();s&&(Dn(s),wi(Yi))};function Nc(s,p){(s>>>=0)==p>>>0?setTimeout(dr):g?postMessage({targetThread:s,cmd:\"checkMailbox\"}):(s=Ze[s])&&s.postMessage({cmd:\"checkMailbox\"})}var Bn=[];function Wc(s,p,f,b,_){for(p>>>=0,b/=2,Bn.length=b,f=_>>>0>>>3,_=0;_>>0];return(p?xn[p]:Ep[s])(...Bn)}function Lc(s){s>>>=0,g?postMessage({cmd:\"cleanupThread\",thread:s}):Ko(Ze[s])}function Gc(s){}var Mn=(s,p)=>{var f=En[s];if(f===void 0)throw s=Fi(s),f=Xe(s),Je(s),new mt(`${p} has unknown type ${f}`);return f},_i=(s,p,f)=>{var b=[];return s=s.toWireType(b,f),b.length&&(a()[p>>>2>>>0]=Ge(b)),s};function Hc(s,p,f){return p>>>=0,f>>>=0,s=Le(s>>>0),p=Mn(p,\"emval::as\"),_i(p,f,s)}var cr=s=>{try{s()}catch(p){ct(p)}},ht=0,Qe=null,vi=0,pr=[],$i={},xi={},Fc=0,Rn=null,qc=[];function Si(s){return function(p){if(!_e){if(ht===0){var f=!1,b=!1;p((_=0)=>{if(!_e&&(vi=_,f=!0,b)){ht=2,cr(()=>ea(Qe)),typeof Browser<\"u\"&&Browser.Kb.Rb&&Browser.Kb.resume(),_=!1;try{var I=function(){var G=i()[Qe+8>>>2>>>0];return G=Y[xi[G]],--wt,G()}()}catch(G){I=G,_=!0}var D=!1;if(!Qe){var B=Rn;B&&(Rn=null,(_?B.reject:B.resolve)(I),D=!0)}if(_&&!D)throw I}}),b=!0,f||(ht=1,Qe=function(){var _=yr(65548),I=_+12;a()[_>>>2>>>0]=I,a()[_+4>>>2>>>0]=I+65536,I=pr[0];var D=$i[I];return D===void 0&&(D=Fc++,$i[I]=D,xi[D]=I),I=D,i()[_+8>>>2>>>0]=I,_}(),typeof Browser<\"u\"&&Browser.Kb.Rb&&Browser.Kb.pause(),cr(()=>Qi(Qe)))}else ht===2?(ht=0,cr(ta),Je(Qe),Qe=null,qc.forEach(wi)):ct(`invalid state: ${ht}`);return vi}}(p=>{s().then(p)})}function jc(s){return s>>>=0,Si(()=>(s=Le(s)).then(Ge))}var mr=[];function Kc(s,p,f,b){return f>>>=0,b>>>=0,(s=mr[s>>>0])(null,p=Le(p>>>0),f,b)}var Yc={},fr=s=>{var p=Yc[s];return p===void 0?Xe(s):p};function Zc(s,p,f,b,_){return f>>>=0,b>>>=0,_>>>=0,(s=mr[s>>>0])(p=Le(p>>>0),p[f=fr(f)],b,_)}var Ti=()=>typeof globalThis==\"object\"?globalThis:Function(\"return this\")();function Xc(s){return(s>>>=0)==0?Ge(Ti()):(s=fr(s),Ge(Ti()[s]))}var Qc=s=>{var p=mr.length;return mr.push(s),p},Jc=(s,p)=>{for(var f=Array(s),b=0;b>>2>>>0],\"parameter \"+b);return f},Ii=(s,p)=>Object.defineProperty(p,\"name\",{value:s});function ep(s,p,f){var b=(p=Jc(s,p>>>0)).shift();s--;var _=`return function (obj, func, destructorsRef, args) {\n`,I=0,D=[];f===0&&D.push(\"obj\");for(var B=[\"retType\"],G=[b],H=0;HX.name).join(\", \")}) => ${b.name}>`,Qc(Ii(f,s))}function tp(s){return s=fr(s>>>0),Ge(u[s])}function rp(s,p){return p>>>=0,s=Le(s>>>0),p=Le(p),Ge(s[p])}function np(s){9<(s>>>=0)&&(st[s+1]+=1)}function op(){return Ge([])}function ip(s){s=Le(s>>>0);for(var p=Array(s.length),f=0;f>>0))}function sp(){return Ge({})}function up(s){for(var p=Le(s>>>=0);p.length;){var f=p.pop();p.pop()(f)}zn(s)}function lp(s,p,f){p>>>=0,f>>>=0,s=Le(s>>>0),p=Le(p),f=Le(f),s[p]=f}function dp(s,p){return p>>>=0,s=(s=Mn(s>>>0,\"_emval_take_value\")).readValueFromPointer(p),Ge(s)}function cp(s,p){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),i()[p>>>2>>>0]=s.getUTCSeconds(),i()[p+4>>>2>>>0]=s.getUTCMinutes(),i()[p+8>>>2>>>0]=s.getUTCHours(),i()[p+12>>>2>>>0]=s.getUTCDate(),i()[p+16>>>2>>>0]=s.getUTCMonth(),i()[p+20>>>2>>>0]=s.getUTCFullYear()-1900,i()[p+24>>>2>>>0]=s.getUTCDay(),s=(s.getTime()-Date.UTC(s.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[p+28>>>2>>>0]=s}var zt=s=>s%4==0&&(s%100!=0||s%400==0),Ci=[0,31,60,91,121,152,182,213,244,274,305,335],Ai=[0,31,59,90,120,151,181,212,243,273,304,334];function pp(s,p){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),i()[p>>>2>>>0]=s.getSeconds(),i()[p+4>>>2>>>0]=s.getMinutes(),i()[p+8>>>2>>>0]=s.getHours(),i()[p+12>>>2>>>0]=s.getDate(),i()[p+16>>>2>>>0]=s.getMonth(),i()[p+20>>>2>>>0]=s.getFullYear()-1900,i()[p+24>>>2>>>0]=s.getDay();var f=(zt(s.getFullYear())?Ci:Ai)[s.getMonth()]+s.getDate()-1|0;i()[p+28>>>2>>>0]=f,i()[p+36>>>2>>>0]=-60*s.getTimezoneOffset(),f=new Date(s.getFullYear(),6,1).getTimezoneOffset();var b=new Date(s.getFullYear(),0,1).getTimezoneOffset();s=0|(f!=b&&s.getTimezoneOffset()==Math.min(b,f)),i()[p+32>>>2>>>0]=s}function mp(s){s>>>=0;var p=new Date(i()[s+20>>>2>>>0]+1900,i()[s+16>>>2>>>0],i()[s+12>>>2>>>0],i()[s+8>>>2>>>0],i()[s+4>>>2>>>0],i()[s>>>2>>>0],0),f=i()[s+32>>>2>>>0],b=p.getTimezoneOffset(),_=new Date(p.getFullYear(),6,1).getTimezoneOffset(),I=new Date(p.getFullYear(),0,1).getTimezoneOffset(),D=Math.min(I,_);return 0>f?i()[s+32>>>2>>>0]=+(_!=I&&D==b):0>>2>>>0]=p.getDay(),f=(zt(p.getFullYear())?Ci:Ai)[p.getMonth()]+p.getDate()-1|0,i()[s+28>>>2>>>0]=f,i()[s>>>2>>>0]=p.getSeconds(),i()[s+4>>>2>>>0]=p.getMinutes(),i()[s+8>>>2>>>0]=p.getHours(),i()[s+12>>>2>>>0]=p.getDate(),i()[s+16>>>2>>>0]=p.getMonth(),i()[s+20>>>2>>>0]=p.getYear(),s=p.getTime(),BigInt(isNaN(s)?-1:s/1e3)}function ki(s,p,f,b,_,I,D){return g?xe(16,1,s,p,f,b,_,I,D):-52}function Ei(s,p,f,b,_,I){if(g)return xe(17,1,s,p,f,b,_,I)}function fp(s,p,f,b){s>>>=0,p>>>=0,f>>>=0,b>>>=0;var _=new Date().getFullYear(),I=new Date(_,0,1),D=new Date(_,6,1);_=I.getTimezoneOffset();var B=D.getTimezoneOffset(),G=Math.max(_,B);a()[s>>>2>>>0]=60*G,i()[p>>>2>>>0]=+(_!=B),I=(s=H=>H.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:\"short\"}).split(\" \")[1])(I),D=s(D),B<_?(Pt(I,f,17),Pt(D,b,17)):(Pt(I,b,17),Pt(D,f,17))}var Un=[],Pi=(s,p)=>{Un.length=0;for(var f;f=r()[s++>>>0];){var b=f!=105;p+=(b&=f!=112)&&p%8?4:0,Un.push(f==112?a()[p>>>2>>>0]:f==106?q[p>>>3]:f==105?i()[p>>>2>>>0]:d()[p>>>3>>>0]),p+=b?8:4}return Un};function hp(s,p,f){return s>>>=0,p=Pi(p>>>0,f>>>0),xn[s](...p)}function gp(s,p,f){return s>>>=0,p=Pi(p>>>0,f>>>0),xn[s](...p)}var bp=()=>{},yp=()=>Date.now();function wp(s,p){return K(Ce(s>>>0,p>>>0))}var zi,_p=()=>{throw wt+=1,\"unwind\"};function vp(){return 4294901760}zi=()=>performance.timeOrigin+performance.now();var $p=()=>navigator.hardwareConcurrency;function xp(){return ct(\"Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER\"),0}function Sp(s){s>>>=0;var p=r().length;if(s<=p||4294901760=f;f*=2){var b=p*(1+.2/f);b=Math.min(b,s+100663296);var _=Math;b=Math.max(s,b);e:{_=(_.min.call(_,4294901760,b+(65536-b%65536)%65536)-ue.buffer.byteLength+65535)/65536;try{ue.grow(_),be();var I=1;break e}catch{}I=void 0}if(I)return!0}return!1}var hr=()=>(ct(\"Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER\"),0),Ot={},Oi=s=>{s.forEach(p=>{var f=hr();f&&(Ot[f]=p)})};function Tp(){var s=Error().stack.toString().split(`\n`);return s[0]==\"Error\"&&s.shift(),Oi(s),Ot.Pb=hr(),Ot.ec=s,Ot.Pb}function Ip(s,p,f){if(s>>>=0,p>>>=0,Ot.Pb==s)var b=Ot.ec;else(b=Error().stack.toString().split(`\n`))[0]==\"Error\"&&b.shift(),Oi(b);for(var _=3;b[_]&&hr()!=s;)++_;for(s=0;s>>2>>>0]=hr();return s}var Vn,Nn={},Di=()=>{if(!Vn){var s,p={USER:\"web_user\",LOGNAME:\"web_user\",PATH:\"/\",PWD:\"/\",HOME:\"/home/web_user\",LANG:(typeof navigator==\"object\"&&navigator.languages&&navigator.languages[0]||\"C\").replace(\"-\",\"_\")+\".UTF-8\",_:C||\"./this.program\"};for(s in Nn)Nn[s]===void 0?delete p[s]:p[s]=Nn[s];var f=[];for(s in p)f.push(`${s}=${p[s]}`);Vn=f}return Vn};function Bi(s,p){if(g)return xe(18,1,s,p);s>>>=0,p>>>=0;var f=0;return Di().forEach((b,_)=>{var I=p+f;for(_=a()[s+4*_>>>2>>>0]=I,I=0;I>>0]=b.charCodeAt(I);t()[_>>>0]=0,f+=b.length+1}),0}function Mi(s,p){if(g)return xe(19,1,s,p);s>>>=0,p>>>=0;var f=Di();a()[s>>>2>>>0]=f.length;var b=0;return f.forEach(_=>b+=_.length+1),a()[p>>>2>>>0]=b,0}function Ri(s){return g?xe(20,1,s):52}function Ui(s,p,f,b){return g?xe(21,1,s,p,f,b):52}function Vi(s,p,f,b){return g?xe(22,1,s,p,f,b):70}var Cp=[null,[],[]];function Ni(s,p,f,b){if(g)return xe(23,1,s,p,f,b);p>>>=0,f>>>=0,b>>>=0;for(var _=0,I=0;I>>2>>>0],B=a()[p+4>>>2>>>0];p+=8;for(var G=0;G>>0],X=Cp[s];H===0||H===10?((s===1?j:K)(ti(X,0)),X.length=0):X.push(H)}_+=B}return a()[b>>>2>>>0]=_,0}var Wi=[31,29,31,30,31,30,31,31,30,31,30,31],Li=[31,28,31,30,31,30,31,31,30,31,30,31],Ap=(s,p)=>{t().set(s,p>>>0)};function Gi(s,p,f,b){function _(z,le,Se){for(z=typeof z==\"number\"?z.toString():z||\"\";z.lengthna?-1:0vt-z.getDate())){z.setDate(z.getDate()+le);break}le-=vt-z.getDate()+1,z.setDate(1),11>Se?z.setMonth(Se+1):(z.setMonth(0),z.setFullYear(z.getFullYear()+1))}return Se=new Date(z.getFullYear()+1,0,4),le=B(new Date(z.getFullYear(),0,4)),Se=B(Se),0>=D(le,z)?0>=D(Se,z)?z.getFullYear()+1:z.getFullYear():z.getFullYear()-1}s>>>=0,p>>>=0,f>>>=0,b>>>=0;var H=a()[b+40>>>2>>>0];for(var X in b={kc:i()[b>>>2>>>0],jc:i()[b+4>>>2>>>0],Hb:i()[b+8>>>2>>>0],Lb:i()[b+12>>>2>>>0],Ib:i()[b+16>>>2>>>0],Cb:i()[b+20>>>2>>>0],ub:i()[b+24>>>2>>>0],Bb:i()[b+28>>>2>>>0],sc:i()[b+32>>>2>>>0],ic:i()[b+36>>>2>>>0],lc:H?Ce(H):\"\"},f=Ce(f),H={\"%c\":\"%a %b %d %H:%M:%S %Y\",\"%D\":\"%m/%d/%y\",\"%F\":\"%Y-%m-%d\",\"%h\":\"%b\",\"%r\":\"%I:%M:%S %p\",\"%R\":\"%H:%M\",\"%T\":\"%H:%M:%S\",\"%x\":\"%m/%d/%y\",\"%X\":\"%H:%M:%S\",\"%Ec\":\"%c\",\"%EC\":\"%C\",\"%Ex\":\"%m/%d/%y\",\"%EX\":\"%H:%M:%S\",\"%Ey\":\"%y\",\"%EY\":\"%Y\",\"%Od\":\"%d\",\"%Oe\":\"%e\",\"%OH\":\"%H\",\"%OI\":\"%I\",\"%Om\":\"%m\",\"%OM\":\"%M\",\"%OS\":\"%S\",\"%Ou\":\"%u\",\"%OU\":\"%U\",\"%OV\":\"%V\",\"%Ow\":\"%w\",\"%OW\":\"%W\",\"%Oy\":\"%y\"})f=f.replace(new RegExp(X,\"g\"),H[X]);var ce=\"Sunday Monday Tuesday Wednesday Thursday Friday Saturday\".split(\" \"),ge=\"January February March April May June July August September October November December\".split(\" \");for(X in H={\"%a\":z=>ce[z.ub].substring(0,3),\"%A\":z=>ce[z.ub],\"%b\":z=>ge[z.Ib].substring(0,3),\"%B\":z=>ge[z.Ib],\"%C\":z=>I((z.Cb+1900)/100|0,2),\"%d\":z=>I(z.Lb,2),\"%e\":z=>_(z.Lb,2,\" \"),\"%g\":z=>G(z).toString().substring(2),\"%G\":G,\"%H\":z=>I(z.Hb,2),\"%I\":z=>((z=z.Hb)==0?z=12:12{for(var le=0,Se=0;Se<=z.Ib-1;le+=(zt(z.Cb+1900)?Wi:Li)[Se++]);return I(z.Lb+le,3)},\"%m\":z=>I(z.Ib+1,2),\"%M\":z=>I(z.jc,2),\"%n\":()=>`\n`,\"%p\":z=>0<=z.Hb&&12>z.Hb?\"AM\":\"PM\",\"%S\":z=>I(z.kc,2),\"%t\":()=>\"\t\",\"%u\":z=>z.ub||7,\"%U\":z=>I(Math.floor((z.Bb+7-z.ub)/7),2),\"%V\":z=>{var le=Math.floor((z.Bb+7-(z.ub+6)%7)/7);if(2>=(z.ub+371-z.Bb-2)%7&&le++,le)le==53&&((Se=(z.ub+371-z.Bb)%7)==4||Se==3&&zt(z.Cb)||(le=1));else{le=52;var Se=(z.ub+7-z.Bb-1)%7;(Se==4||Se==5&&zt(z.Cb%400-1))&&le++}return I(le,2)},\"%w\":z=>z.ub,\"%W\":z=>I(Math.floor((z.Bb+7-(z.ub+6)%7)/7),2),\"%y\":z=>(z.Cb+1900).toString().substring(2),\"%Y\":z=>z.Cb+1900,\"%z\":z=>{var le=0<=(z=z.ic);return z=Math.abs(z)/60,(le?\"+\":\"-\")+(\"0000\"+(z/60*100+z%60)).slice(-4)},\"%Z\":z=>z.lc,\"%%\":()=>\"%\"},f=f.replace(/%%/g,\"\\0\\0\"),H)f.includes(X)&&(f=f.replace(new RegExp(X,\"g\"),H[X](b)));return X=function(z){var le=Array(An(z)+1);return oi(z,le,0,le.length),le}(f=f.replace(/\\0\\0/g,\"%\")),X.length>p?0:(Ap(X,s),X.length-1)}function kp(s,p,f,b){return Gi(s>>>0,p>>>0,f>>>0,b>>>0)}g||function(){for(var s=u.numThreads-1;s--;)Xo();Ye.unshift(()=>{Gt++,function(p){g?p():Promise.all(pt.map(Zo)).then(p)}(()=>Vo())})}();for(var Hi=Array(256),gr=0;256>gr;++gr)Hi[gr]=String.fromCharCode(gr);gi=Hi,mt=u.BindingError=class extends Error{constructor(s){super(s),this.name=\"BindingError\"}},u.InternalError=class extends Error{constructor(s){super(s),this.name=\"InternalError\"}},st.push(0,1,void 0,1,null,1,!0,1,!1,1),u.count_emval_handles=()=>st.length/2-5-Pn.length;var Ep=[In,qo,Qo,ri,ni,ii,ai,si,ui,li,di,ci,pi,mi,fi,hi,ki,Ei,Bi,Mi,Ri,Ui,Vi,Ni],Y=function(){function s(f,b){return Y=f.exports,Y=function(){var _=Y,I={};for(let[D,B]of Object.entries(_))I[D]=typeof B==\"function\"?(...G)=>{pr.push(D);try{return B(...G)}finally{_e||(pr.pop(),Qe&&ht===1&&pr.length===0&&(ht=0,wt+=1,cr(Ji),typeof Fibers<\"u\"&&Fibers.tc()))}}:B;return I}(),Y=function(){var _=Y,I=B=>G=>B(G)>>>0,D=B=>()=>B()>>>0;return(_=Object.assign({},_)).Ca=I(_.Ca),_.fb=D(_.fb),_.hb=I(_.hb),_.emscripten_main_runtime_thread_id=D(_.emscripten_main_runtime_thread_id),_.sb=I(_.sb),_.tb=D(_.tb),_}(),jo.push(Y.ib),Lt.unshift(Y.Ba),Z=b,Vo(),Y}var p=Ho();if(Gt++,u.instantiateWasm)try{return u.instantiateWasm(p,s)}catch(f){K(`Module.instantiateWasm callback failed with error: ${f}`),m(f)}return $n||=u.locateFile?No(\"ort-wasm-simd-threaded.jsep.wasm\")?\"ort-wasm-simd-threaded.jsep.wasm\":u.locateFile?u.locateFile(\"ort-wasm-simd-threaded.jsep.wasm\",P):P+\"ort-wasm-simd-threaded.jsep.wasm\":new URL(\"ort-wasm-simd-threaded.jsep.wasm\",import.meta.url).href,function(f,b){var _=$n;return O||typeof WebAssembly.instantiateStreaming!=\"function\"||No(_)||Wo(_)||typeof fetch!=\"function\"?Go(_,f,b):fetch(_,{credentials:\"same-origin\"}).then(I=>WebAssembly.instantiateStreaming(I,f).then(b,function(D){return K(`wasm streaming compile failed: ${D}`),K(\"falling back to ArrayBuffer instantiation\"),Go(_,f,b)}))}(p,function(f){s(f.instance,f.module)}).catch(m),{}}(),Fi=s=>(Fi=Y.Ca)(s),qi=()=>(qi=Y.Da)();u._OrtInit=(s,p)=>(u._OrtInit=Y.Ea)(s,p),u._OrtGetLastError=(s,p)=>(u._OrtGetLastError=Y.Fa)(s,p),u._OrtCreateSessionOptions=(s,p,f,b,_,I,D,B,G,H)=>(u._OrtCreateSessionOptions=Y.Ga)(s,p,f,b,_,I,D,B,G,H),u._OrtAppendExecutionProvider=(s,p)=>(u._OrtAppendExecutionProvider=Y.Ha)(s,p),u._OrtAddFreeDimensionOverride=(s,p,f)=>(u._OrtAddFreeDimensionOverride=Y.Ia)(s,p,f),u._OrtAddSessionConfigEntry=(s,p,f)=>(u._OrtAddSessionConfigEntry=Y.Ja)(s,p,f),u._OrtReleaseSessionOptions=s=>(u._OrtReleaseSessionOptions=Y.Ka)(s),u._OrtCreateSession=(s,p,f)=>(u._OrtCreateSession=Y.La)(s,p,f),u._OrtReleaseSession=s=>(u._OrtReleaseSession=Y.Ma)(s),u._OrtGetInputOutputCount=(s,p,f)=>(u._OrtGetInputOutputCount=Y.Na)(s,p,f),u._OrtGetInputName=(s,p)=>(u._OrtGetInputName=Y.Oa)(s,p),u._OrtGetOutputName=(s,p)=>(u._OrtGetOutputName=Y.Pa)(s,p),u._OrtFree=s=>(u._OrtFree=Y.Qa)(s),u._OrtCreateTensor=(s,p,f,b,_,I)=>(u._OrtCreateTensor=Y.Ra)(s,p,f,b,_,I),u._OrtGetTensorData=(s,p,f,b,_)=>(u._OrtGetTensorData=Y.Sa)(s,p,f,b,_),u._OrtReleaseTensor=s=>(u._OrtReleaseTensor=Y.Ta)(s),u._OrtCreateRunOptions=(s,p,f,b)=>(u._OrtCreateRunOptions=Y.Ua)(s,p,f,b),u._OrtAddRunConfigEntry=(s,p,f)=>(u._OrtAddRunConfigEntry=Y.Va)(s,p,f),u._OrtReleaseRunOptions=s=>(u._OrtReleaseRunOptions=Y.Wa)(s),u._OrtCreateBinding=s=>(u._OrtCreateBinding=Y.Xa)(s),u._OrtBindInput=(s,p,f)=>(u._OrtBindInput=Y.Ya)(s,p,f),u._OrtBindOutput=(s,p,f,b)=>(u._OrtBindOutput=Y.Za)(s,p,f,b),u._OrtClearBoundOutputs=s=>(u._OrtClearBoundOutputs=Y._a)(s),u._OrtReleaseBinding=s=>(u._OrtReleaseBinding=Y.$a)(s),u._OrtRunWithBinding=(s,p,f,b,_)=>(u._OrtRunWithBinding=Y.ab)(s,p,f,b,_),u._OrtRun=(s,p,f,b,_,I,D,B)=>(u._OrtRun=Y.bb)(s,p,f,b,_,I,D,B),u._OrtEndProfiling=s=>(u._OrtEndProfiling=Y.cb)(s),u._JsepOutput=(s,p,f)=>(u._JsepOutput=Y.db)(s,p,f),u._JsepGetNodeName=s=>(u._JsepGetNodeName=Y.eb)(s);var br,Dt=()=>(Dt=Y.fb)(),Je=u._free=s=>(Je=u._free=Y.gb)(s),yr=u._malloc=s=>(yr=u._malloc=Y.hb)(s),Wn=(s,p,f,b,_,I)=>(Wn=Y.kb)(s,p,f,b,_,I),ji=()=>(ji=Y.lb)(),Ki=(s,p,f,b,_)=>(Ki=Y.mb)(s,p,f,b,_),Ln=s=>(Ln=Y.nb)(s),wr=s=>(wr=Y.ob)(s),Yi=()=>(Yi=Y.pb)(),Zi=(s,p)=>(Zi=Y.qb)(s,p),_r=s=>(_r=Y.rb)(s),Gn=s=>(Gn=Y.sb)(s),Hn=()=>(Hn=Y.tb)(),Xi=u.dynCall_ii=(s,p)=>(Xi=u.dynCall_ii=Y.vb)(s,p),Qi=s=>(Qi=Y.wb)(s),Ji=()=>(Ji=Y.xb)(),ea=s=>(ea=Y.yb)(s),ta=()=>(ta=Y.zb)();function ra(){0Hn(),u.stackRestore=s=>_r(s),u.stackAlloc=s=>Gn(s),u.setValue=function(s,p,f=\"i8\"){switch(f.endsWith(\"*\")&&(f=\"*\"),f){case\"i1\":case\"i8\":t()[s>>>0]=p;break;case\"i16\":n()[s>>>1>>>0]=p;break;case\"i32\":i()[s>>>2>>>0]=p;break;case\"i64\":q[s>>>3]=BigInt(p);break;case\"float\":l()[s>>>2>>>0]=p;break;case\"double\":d()[s>>>3>>>0]=p;break;case\"*\":a()[s>>>2>>>0]=p;break;default:ct(`invalid type for setValue: ${f}`)}},u.getValue=function(s,p=\"i8\"){switch(p.endsWith(\"*\")&&(p=\"*\"),p){case\"i1\":case\"i8\":return t()[s>>>0];case\"i16\":return n()[s>>>1>>>0];case\"i32\":return i()[s>>>2>>>0];case\"i64\":return q[s>>>3];case\"float\":return l()[s>>>2>>>0];case\"double\":return d()[s>>>3>>>0];case\"*\":return a()[s>>>2>>>0];default:ct(`invalid type for getValue: ${p}`)}},u.UTF8ToString=Ce,u.stringToUTF8=Pt,u.lengthBytesUTF8=An,Ht=function s(){br||ra(),br||(Ht=s)},ra(),u.PTR_SIZE=4,h}),Np=Ua;globalThis.self?.name===\"em-pthread\"&&Ua()});var Bt,Wp,Lp,Gp,Wa,La,Hp,Ga,jt=R(()=>{\"use strict\";Er();Bt=!1?void 0:import.meta.url??(typeof document<\"u\"?document.currentScript?.src:typeof self<\"u\"?self.location?.href:void 0),Wp=!1||typeof location>\"u\"?void 0:location.origin,Lp=(e,t)=>{try{let r=t??Bt;return(r?new URL(e,r):new URL(e)).origin===Wp}catch{return!1}},Gp=async e=>{let r=await(await fetch(e,{credentials:\"same-origin\"})).blob();return URL.createObjectURL(r)},Wa=(Ra(),vr(Ma)).default,La=async()=>{if(!Bt)throw new Error(\"Failed to load proxy worker: cannot determine the script source URL.\");if(Lp(Bt))return[void 0,Wa()];let e=await Gp(Bt);return[e,Wa(e)]},Hp=(Na(),vr(Va)).default,Ga=async(e,t,r)=>[void 0,Hp]});var Jn,eo,Vr,Ha,Fp,qp,Pr,Te,gt=R(()=>{\"use strict\";jt();eo=!1,Vr=!1,Ha=!1,Fp=()=>{if(typeof SharedArrayBuffer>\"u\")return!1;try{return typeof MessageChannel<\"u\"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},qp=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Pr=async e=>{if(eo)return Promise.resolve();if(Vr)throw new Error(\"multiple calls to 'initializeWebAssembly()' detected.\");if(Ha)throw new Error(\"previous call to 'initializeWebAssembly()' failed.\");Vr=!0;let t=e.initTimeout,r=e.numThreads;if(!qp())throw new Error(\"WebAssembly SIMD is not supported in the current environment.\");let n=Fp();r>1&&!n&&(typeof self<\"u\"&&!self.crossOriginIsolated&&console.warn(\"env.wasm.numThreads is set to \"+r+\", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info.\"),console.warn(\"WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading.\"),e.numThreads=r=1);let o=e.wasmPaths,i=typeof o==\"string\"?o:void 0,a=o?.mjs,l=a?.href??a,d=o?.wasm,c=d?.href??d,m=e.wasmBinary,[u,h]=await Ga(l,i,r>1),w=!1,y=[];if(t>0&&y.push(new Promise(g=>{setTimeout(()=>{w=!0,g()},t)})),y.push(new Promise((g,x)=>{let $={numThreads:r};m?$.wasmBinary=m:(c||i)&&($.locateFile=(v,S)=>c??(i??S)+v),h($).then(v=>{Vr=!1,eo=!0,Jn=v,g(),u&&URL.revokeObjectURL(u)},v=>{Vr=!1,Ha=!0,x(v)})})),await Promise.race(y),w)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Te=()=>{if(eo&&Jn)return Jn;throw new Error(\"WebAssembly is not initialized yet.\")}});var ke,Yt,pe,Nr=R(()=>{\"use strict\";gt();ke=(e,t)=>{let r=Te(),n=r.lengthBytesUTF8(e)+1,o=r._malloc(n);return r.stringToUTF8(e,o,n),t.push(o),o},Yt=(e,t,r,n)=>{if(typeof e==\"object\"&&e!==null){if(r.has(e))throw new Error(\"Circular reference in options\");r.add(e)}Object.entries(e).forEach(([o,i])=>{let a=t?t+o:o;if(typeof i==\"object\")Yt(i,a+\".\",r,n);else if(typeof i==\"string\"||typeof i==\"number\")n(a,i.toString());else if(typeof i==\"boolean\")n(a,i?\"1\":\"0\");else throw new Error(`Can't handle extra config type: ${typeof i}`)})},pe=e=>{let t=Te(),r=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetLastError(o,o+n);let i=Number(t.getValue(o,n===4?\"i32\":\"i64\")),a=t.getValue(o+n,\"*\"),l=a?t.UTF8ToString(a):\"\";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${l}`)}finally{t.stackRestore(r)}}});var Fa,qa=R(()=>{\"use strict\";gt();Nr();Fa=e=>{let t=Te(),r=0,n=[],o=e||{};try{if(e?.logSeverityLevel===void 0)o.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=\"number\"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)o.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=\"number\"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(o.terminate=!1);let i=0;return e?.tag!==void 0&&(i=ke(e.tag,n)),r=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,i),r===0&&pe(\"Can't create run options.\"),e?.extra!==void 0&&Yt(e.extra,\"\",new WeakSet,(a,l)=>{let d=ke(a,n),c=ke(l,n);t._OrtAddRunConfigEntry(r,d,c)!==0&&pe(`Can't set a run config entry: ${a} - ${l}.`)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(a=>t._free(a)),i}}});var jp,Kp,Yp,Zp,ja,Ka=R(()=>{\"use strict\";gt();Nr();jp=e=>{switch(e){case\"disabled\":return 0;case\"basic\":return 1;case\"extended\":return 2;case\"all\":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},Kp=e=>{switch(e){case\"sequential\":return 0;case\"parallel\":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Yp=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly=\"1\"),e.executionProviders&&e.executionProviders.some(r=>(typeof r==\"string\"?r:r.name)===\"webgpu\")&&(e.enableMemPattern=!1)},Zp=(e,t,r)=>{for(let n of t){let o=typeof n==\"string\"?n:n.name;switch(o){case\"webnn\":if(o=\"WEBNN\",typeof n!=\"string\"){let l=n?.deviceType;if(l){let d=ke(\"deviceType\",r),c=ke(l,r);Te()._OrtAddSessionConfigEntry(e,d,c)!==0&&pe(`Can't set a session config entry: 'deviceType' - ${l}.`)}}break;case\"webgpu\":if(o=\"JS\",typeof n!=\"string\"){let a=n;if(a?.preferredLayout){if(a.preferredLayout!==\"NCHW\"&&a.preferredLayout!==\"NHWC\")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${a.preferredLayout}`);let l=ke(\"preferredLayout\",r),d=ke(a.preferredLayout,r);Te()._OrtAddSessionConfigEntry(e,l,d)!==0&&pe(`Can't set a session config entry: 'preferredLayout' - ${a.preferredLayout}.`)}}break;case\"wasm\":case\"cpu\":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=ke(o,r);Te()._OrtAppendExecutionProvider(e,i)!==0&&pe(`Can't append execution provider: ${o}.`)}},ja=e=>{let t=Te(),r=0,n=[],o=e||{};Yp(o);try{let i=jp(o.graphOptimizationLevel??\"all\"),a=Kp(o.executionMode??\"sequential\"),l=typeof o.logId==\"string\"?ke(o.logId,n):0,d=o.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let c=o.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let m=typeof o.optimizedModelFilePath==\"string\"?ke(o.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(i,!!o.enableCpuMemArena,!!o.enableMemPattern,a,!!o.enableProfiling,0,l,d,c,m),r===0&&pe(\"Can't create session options.\"),o.executionProviders&&Zp(r,o.executionProviders,n),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!=\"boolean\")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);let u=ke(\"enableGraphCapture\",n),h=ke(o.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,u,h)!==0&&pe(`Can't set a session config entry: 'enableGraphCapture' - ${o.enableGraphCapture}.`)}if(o.freeDimensionOverrides)for(let[u,h]of Object.entries(o.freeDimensionOverrides)){if(typeof u!=\"string\")throw new Error(`free dimension override name must be a string: ${u}`);if(typeof h!=\"number\"||!Number.isInteger(h)||h<0)throw new Error(`free dimension override value must be a non-negative integer: ${h}`);let w=ke(u,n);t._OrtAddFreeDimensionOverride(r,w,h)!==0&&pe(`Can't set a free dimension override: ${u} - ${h}.`)}return o.extra!==void 0&&Yt(o.extra,\"\",new WeakSet,(u,h)=>{let w=ke(u,n),y=ke(h,n);t._OrtAddSessionConfigEntry(r,w,y)!==0&&pe(`Can't set a session config entry: ${u} - ${h}.`)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&pe(\"Can't release session options.\"),n.forEach(a=>t._free(a)),i}}});var Zt,bt,Tt,Wr,Xt,Lr,Gr,to,te=R(()=>{\"use strict\";Zt=e=>{switch(e){case\"int8\":return 3;case\"uint8\":return 2;case\"bool\":return 9;case\"int16\":return 5;case\"uint16\":return 4;case\"int32\":return 6;case\"uint32\":return 12;case\"float16\":return 10;case\"float32\":return 1;case\"float64\":return 11;case\"string\":return 8;case\"int64\":return 7;case\"uint64\":return 13;case\"int4\":return 22;case\"uint4\":return 21;default:throw new Error(`unsupported data type: ${e}`)}},bt=e=>{switch(e){case 3:return\"int8\";case 2:return\"uint8\";case 9:return\"bool\";case 5:return\"int16\";case 4:return\"uint16\";case 6:return\"int32\";case 12:return\"uint32\";case 10:return\"float16\";case 1:return\"float32\";case 11:return\"float64\";case 8:return\"string\";case 7:return\"int64\";case 13:return\"uint64\";case 22:return\"int4\";case 21:return\"uint4\";default:throw new Error(`unsupported data type: ${e}`)}},Tt=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t==\"number\"?t:t.reduce((o,i)=>o*i,1);return r>0?Math.ceil(n*r):void 0},Wr=e=>{switch(e){case\"float16\":return typeof Float16Array<\"u\"&&Float16Array.from?Float16Array:Uint16Array;case\"float32\":return Float32Array;case\"uint8\":return Uint8Array;case\"int8\":return Int8Array;case\"uint16\":return Uint16Array;case\"int16\":return Int16Array;case\"int32\":return Int32Array;case\"bool\":return Uint8Array;case\"float64\":return Float64Array;case\"uint32\":return Uint32Array;case\"int64\":return BigInt64Array;case\"uint64\":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Xt=e=>{switch(e){case\"verbose\":return 0;case\"info\":return 1;case\"warning\":return 2;case\"error\":return 3;case\"fatal\":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},Lr=e=>e===\"float32\"||e===\"float16\"||e===\"int32\"||e===\"int64\"||e===\"uint32\"||e===\"uint8\"||e===\"bool\"||e===\"uint4\"||e===\"int4\",Gr=e=>e===\"float32\"||e===\"float16\"||e===\"int32\"||e===\"int64\"||e===\"uint32\"||e===\"uint64\"||e===\"int8\"||e===\"uint8\"||e===\"bool\"||e===\"uint4\"||e===\"int4\",to=e=>{switch(e){case\"none\":return 0;case\"cpu\":return 1;case\"cpu-pinned\":return 2;case\"texture\":return 3;case\"gpu-buffer\":return 4;case\"ml-tensor\":return 5;default:throw new Error(`unsupported data location: ${e}`)}}});var Qt,ro=R(()=>{\"use strict\";Er();Qt=async e=>{if(typeof e==\"string\")if(!1)try{let{readFile:t}=qn(\"node:fs/promises\");return new Uint8Array(await t(e))}catch(t){if(t.code===\"ERR_FS_FILE_TOO_LARGE\"){let{createReadStream:r}=qn(\"node:fs\"),n=r(e),o=[];for await(let i of n)o.push(i);return new Uint8Array(Buffer.concat(o))}throw t}else{let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get(\"Content-Length\"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=t.body.getReader(),i;try{i=new ArrayBuffer(n)}catch(l){if(l instanceof RangeError){let d=Math.ceil(n/65536);i=new WebAssembly.Memory({initial:d,maximum:d}).buffer}else throw l}let a=0;for(;;){let{done:l,value:d}=await o.read();if(l)break;let c=d.byteLength;new Uint8Array(i,a,c).set(d),a+=c}return new Uint8Array(i,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}});var Xp,Qp,Ya,Za,Hr,Jp,se,je=R(()=>{\"use strict\";te();Xp=[\"V\",\"I\",\"W\",\"E\",\"F\"],Qp=(e,t)=>{console.log(`[${Xp[e]},${new Date().toISOString()}]${t}`)},Hr=(e,t)=>{Ya=e,Za=t},Jp=(e,t)=>{let r=Xt(e),n=Xt(Ya);r>=n&&Qp(r,typeof t==\"function\"?t():t)},se=(...e)=>{Za&&Jp(...e)}});var Fr,no=R(()=>{\"use strict\";te();Fr=(e,t)=>new(Wr(t))(e)});var qr=R(()=>{\"use strict\"});var Xa,oo,io,em,tm,Qa,so,ao,es,ts=R(()=>{\"use strict\";je();qr();Xa=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),oo=[],io=e=>Math.ceil(Number(e)/16)*16,em=e=>{for(let t=0;ttm++,so=async(e,t,r,n)=>{let o=io(r),i=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=e.getCommandEncoder();e.endComputePass(),a.copyBufferToBuffer(t,0,i,0,o),e.flush(),await i.mapAsync(GPUMapMode.READ);let l=i.getMappedRange();if(n){let d=n();return d.set(new Uint8Array(l,0,r)),d}else return new Uint8Array(l.slice(0,r))}finally{i.destroy()}},ao=class{constructor(t){this.backend=t;this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[r]of Xa)oo.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(t,r){let n=r.buffer,o=r.byteOffset,i=r.byteLength,a=io(i),l=this.storageCache.get(t);if(!l)throw new Error(\"gpu data for uploading does not exist\");if(Number(l.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${l.originalSize}, data size=${i}`);let d=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),c=d.getMappedRange();new Uint8Array(c).set(new Uint8Array(n,o,i)),d.unmap();let m=this.backend.device.createCommandEncoder();m.copyBufferToBuffer(d,0,l.gpuData.buffer,0,a),this.backend.device.queue.submit([m.finish()]),d.destroy(),se(\"verbose\",()=>`[WebGPU] GpuDataManager.upload(id=${t})`)}memcpy(t,r){let n=this.storageCache.get(t);if(!n)throw new Error(\"source gpu data for memcpy does not exist\");let o=this.storageCache.get(r);if(!o)throw new Error(\"destination gpu data for memcpy does not exist\");if(n.originalSize!==o.originalSize)throw new Error(\"inconsistent source and destination gpu data size\");let i=io(n.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(n.gpuData.buffer,0,o.gpuData.buffer,0,i)}registerExternalBuffer(t,r,n){let o;if(n){if(o=n[0],t===n[1])return se(\"verbose\",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, buffer is the same, skip.`),o;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.\n Please use the previous external buffer!`)}else o=Qa();return this.storageCache.set(o,{gpuData:{id:o,type:0,buffer:t},originalSize:r}),se(\"verbose\",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, registered.`),o}unregisterExternalBuffer(t){t!==void 0&&(this.storageCache.delete(t),se(\"verbose\",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`))}create(t,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=em(t),o,i=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let c=(i?this.freeBuffers:this.freeUniformBuffers).get(n);c?c.length>0?o=c.pop():o=this.backend.device.createBuffer({size:n,usage:r}):o=this.backend.device.createBuffer({size:n,usage:r})}else o=this.backend.device.createBuffer({size:n,usage:r});let l={id:Qa(),type:0,buffer:o};return this.storageCache.set(l.id,{gpuData:l,originalSize:Number(t)}),se(\"verbose\",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${l.id}`),l}get(t){return this.storageCache.get(t)?.gpuData}release(t){let r=typeof t==\"bigint\"?Number(t):t,n=this.storageCache.get(r);if(!n){if(this.storageCache.size===0)return 0;throw new Error(\"releasing data does not exist\")}return se(\"verbose\",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${n.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(t,r){let n=this.storageCache.get(Number(t));if(!n)throw new Error(\"data does not exist\");await so(this.backend,n.gpuData.buffer,n.originalSize,r)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus===\"default\"){for(let t of this.buffersPending){let r=Xa.get(t.size);if((t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(t.size)||[];r===void 0||n.length>=r?t.destroy():n.push(t)}else if((t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(t.size)||[];r===void 0||n.length>=r?t.destroy():n.push(t)}else t.destroy()}this.buffersPending=[]}else{let t=this.capturedPendingBuffers.get(this.backend.currentSessionId);t||(t=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,t));for(let r of this.buffersPending)t.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(t){let r=this.capturedPendingBuffers.get(t);r&&(r.forEach(n=>{n.destroy()}),this.capturedPendingBuffers.delete(t)),this.sessionCount-=1,this.sessionCount===0&&(se(\"warning\",()=>\"[WebGPU] Clearing webgpu buffer cache\"),this.storageCache.forEach(n=>{n.gpuData.buffer.destroy()}),this.storageCache=new Map)}},es=(...e)=>new ao(...e)});var uo,re,Ie=R(()=>{\"use strict\";uo=class{constructor(t){Object.assign(this,t)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(t=>`${this[t]}`).join(\";\")),this.key}},re=e=>new uo(e)});var lo,et,k,It,jr,rs,ns,oe=R(()=>{\"use strict\";lo=class{static calcMatMulShape(t,r){return t[1]!==r[0]?void 0:[t[0],r[1]]}},et=class{static calcShape(t,r,n=!1){let o=t.length,i=r.length;if(o===0)return r;if(i===0)return t;let a=Math.max(t.length,r.length),l=new Array(a);if(n){if(o<2||i<2)return;let d=lo.calcMatMulShape([t[o-2],t[o-1]],[r[i-2],r[i-1]]);if(d===void 0)return;[l[a-2],l[a-1]]=d}for(let d=n?3:1;d<=a;d++){let c=o-d<0?1:t[o-d],m=i-d<0?1:r[i-d];if(c!==m&&c>1&&m>1)return;let u=Math.max(c,m);if(c&&m)l[a-d]=Math.max(c,m);else{if(u>1)return;l[a-d]=0}}return l}static isValidBroadcast(t,r){let n=t.length,o=r.length;if(n>o)return!1;for(let i=1;i<=n;i++)if(t[n-i]!==1&&t[n-i]!==r[o-i])return!1;return!0}},k=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let o=new Array(n),i=n-1;for(;i>=0;){if(t[i]%r===0){o[i]=t[i]/r;break}if(r%t[i]!==0)throw new Error(\"cannot convert shape\");o[i]=1,r/=t[i],i--}for(i--;i>=0;i--)o[i]=t[i];return o}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let o=1;for(let i=r;i=0;--o)n[o]=n[o+1]*t[o+1];return n}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error(\"unsupported axis for this operation.\");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(n=>this.normalizeAxis(n,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(n=>t[n]):t.slice().reverse()}static padShape(t,r){let n=t.length;return t.map((o,i)=>o+r[i]+r[i+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,o)=>n===r[o])}},It=class e{static adjustPoolAttributes(t,r,n,o,i,a){if(!t&&n.length!==r.length-2)throw new Error(\"length of specified kernel shapes should be 2 less than length of input dimensions\");if(t)for(let l=0;l=n.length?n.push(r[l+2]):n[l]=r[l+2];for(let l=0;l=n[l]||a[l+n.length]>=n[l])throw new Error(\"pads should be smaller than kernel\")}}static adjustPadsBasedOnAutoPad(t,r,n,o,i,a,l){if(l){if(i.length!==2*(t.length-2))throw new Error(\"length of pads should be twice the length of data dimensions\");if(r.length!==t.length-2)throw new Error(\"length of strides should be the length of data dimensions\");if(o.length!==t.length-2)throw new Error(\"length of kernel shapes should be the length of data dimensions\");for(let d=0;d{\"use strict\";te();oe();Ct=64,po=(e,t)=>{if(t===3)throw new Error(\"vec3 has same alignment as vec4, use vec4 instead\");switch(Number(e)){case 10:return t>1?`vec${t}`:\"f16\";case 1:return t>1?`vec${t}`:\"f32\";case 6:return t>1?`vec${t}`:\"i32\";case 12:return t>1?`vec${t}`:\"u32\";case 7:if(t>1)throw new Error(\"currently not supported vecX of uint64 yet\");return[\"vec2\",\"i32\"];case 13:if(t>1)throw new Error(\"currently not supported vecX of uint64 yet\");return[\"vec2\",\"u32\"];case 9:if(t!==4)throw new Error(\"bool must be vec4\");return[\"u32\",\"vec4\"];case 22:return\"i32\";case 21:return\"u32\";default:throw new Error(`Unknown data type: ${e}`)}},me=(e,t=1)=>{let r=po(e,t);return typeof r==\"string\"?r:r[0]},Ee=(e,t=1)=>{let r=po(e,t);return typeof r==\"string\"?r:r[1]},V=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:k.computeStrides(r)})}),t},ye=e=>e%4===0?4:e%2===0?2:1,mo=(e=\"f32\",t,r=\"0\")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,At=(e,t,r)=>e===\"f32\"?r:t===1?`f32(${r})`:`vec${t}(${r})`,Ke=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,F=(e,t,r,n)=>e.startsWith(\"uniforms.\")&&r>4?typeof t==\"string\"?n===\"f16\"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n===\"f16\"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,fo=(e,t,r,n,o)=>{let i=typeof r==\"number\",a=i?r:r.length,l=[...new Array(a).keys()],d=a<2?\"u32\":a<=4?`vec${a}`:`array`,c=po(t,o),m=typeof c==\"string\"?c:c[1],u=typeof c==\"string\"?c:c[0],h={indices:d,value:m,storage:u,tensor:t},w=N=>typeof N==\"string\"?N:`${N}u`,y={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},g=i?\"uniforms.\":\"\",x=`${g}${e}_shape`,$=`${g}${e}_strides`,v=\"\";for(let N=0;N ${h.indices} {\n var indices: ${h.indices};\n var current = offset;\n ${v}\n return indices;\n }`,T=N=>(y.offsetToIndices=!0,a<2?N:`o2i_${e}(${N})`),C=[];if(a>=2)for(let N=a-1;N>=0;N--)C.push(`${F($,N,a)} * (indices[${N}])`);let A=a<2?\"\":`\n fn i2o_${e}(indices: ${h.indices}) -> u32 {\n return ${C.join(\"+\")};\n }`,P=N=>(y.indicesToOffset=!0,a<2?N:`i2o_${e}(${N})`),O=(...N)=>a===0?\"0u\":`${h.indices}(${N.map(w).join(\",\")})`,U=(N,q)=>a<2?`${N}`:`${F(N,q,a)}`,L=(N,q,he)=>a<2?`${N}=${he};`:`${F(N,q,a)}=${he};`,j={},K=(N,q)=>{y.broadcastedIndicesToOffset=!0;let he=`${q.name}broadcastedIndicesTo${e}Offset`;if(he in j)return`${he}(${N})`;let qe=[];for(let _e=a-1;_e>=0;_e--){let be=q.indicesGet(\"outputIndices\",_e+q.rank-a);qe.push(`${U($,_e)} * (${be} % ${U(x,_e)})`)}return j[he]=`fn ${he}(outputIndices: ${q.type.indices}) -> u32 {\n return ${qe.length>0?qe.join(\"+\"):\"0u\"};\n }`,`${he}(${N})`},W=(N,q)=>(()=>{if(h.storage===h.value)return`${e}[${N}]=${q};`;if(h.storage===\"vec2\"&&h.value===\"i32\")return`${e}[${N}]=vec2(u32(${q}), select(0u, 0xFFFFFFFFu, ${q} < 0));`;if(h.storage===\"vec2\"&&h.value===\"u32\")return`${e}[${N}]=vec2(u32(${q}), 0u);`;if(h.storage===\"u32\"&&h.value===\"vec4\")return`${e}[${N}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${q}));`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),ee=N=>(()=>{if(h.storage===h.value)return`${e}[${N}]`;if(h.storage===\"vec2\"&&h.value===\"i32\")return`i32(${e}[${N}].x)`;if(h.storage===\"vec2\"&&h.value===\"u32\")return`u32(${e}[${N}].x)`;if(h.storage===\"u32\"&&h.value===\"vec4\")return`vec4(bool(${e}[${N}] & 0xFFu), bool(${e}[${N}] & 0xFF00u), bool(${e}[${N}] & 0xFF0000u), bool(${e}[${N}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),ue=a<2?\"\":`\n fn get_${e}ByIndices(indices: ${h.indices}) -> ${m} {\n return ${ee(`i2o_${e}(indices)`)};\n }`,Z=a<2?\"\":(()=>{let N=l.map(he=>`d${he}: u32`).join(\", \"),q=l.map(he=>`d${he}`).join(\", \");return`\n fn get_${e}(${N}) -> ${m} {\n return get_${e}ByIndices(${O(q)});\n }`})(),J=(...N)=>{if(N.length!==a)throw new Error(`indices length must be ${a}`);let q=N.map(w).join(\",\");return a===0?ee(\"0u\"):a===1?ee(q[0]):(y.get=!0,y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}(${q})`)},Q=N=>a<2?ee(N):(y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}ByIndices(${N})`),ne=a<2?\"\":`\n fn set_${e}ByIndices(indices: ${h.indices}, value: ${m}) {\n ${W(`i2o_${e}(indices)`,\"value\")}\n }`,we=a<2?\"\":(()=>{let N=l.map(he=>`d${he}: u32`).join(\", \"),q=l.map(he=>`d${he}`).join(\", \");return`\n fn set_${e}(${N}, value: ${m}) {\n set_${e}ByIndices(${O(q)}, value);\n }`})();return{impl:()=>{let N=[],q=!1;return y.offsetToIndices&&(N.push(S),q=!0),y.indicesToOffset&&(N.push(A),q=!0),y.broadcastedIndicesToOffset&&(Object.values(j).forEach(he=>N.push(he)),q=!0),y.set&&(N.push(we),q=!0),y.setByIndices&&(N.push(ne),q=!0),y.get&&(N.push(Z),q=!0),y.getByIndices&&(N.push(ue),q=!0),!i&&q&&N.unshift(`const ${x} = ${h.indices}(${r.join(\",\")});`,`const ${$} = ${h.indices}(${k.computeStrides(r).join(\",\")});`),N.join(`\n`)},type:h,offsetToIndices:T,indicesToOffset:P,broadcastedIndicesToOffset:K,indices:O,indicesGet:U,indicesSet:L,set:(...N)=>{if(N.length!==a+1)throw new Error(`indices length must be ${a}`);let q=N[a];if(typeof q!=\"string\")throw new Error(\"value must be string\");let he=N.slice(0,a).map(w).join(\",\");return a===0?W(\"0u\",q):a===1?W(he[0],q):(y.set=!0,y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}(${he}, ${q})`)},setByOffset:W,setByIndices:(N,q)=>a<2?W(N,q):(y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}ByIndices(${N}, ${q});`),get:J,getByOffset:ee,getByIndices:Q,usage:n,name:e,strides:$,shape:x,rank:a}},E=(e,t,r,n=1)=>fo(e,t,r,\"input\",n),M=(e,t,r,n=1)=>fo(e,t,r,\"output\",n),Kr=(e,t,r,n=1)=>fo(e,t,r,\"internal\",n),co=class{constructor(t,r){this.normalizedDispatchGroup=t;this.limits=r;this.internalVariables=[];this.variables=[];this.uniforms=[];this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t==\"number\"?`${t}u`:t}) { return; }`}mainStart(t=Ct){let r=typeof t==\"number\"?t:t[0],n=typeof t==\"number\"?1:t[1],o=typeof t==\"number\"?1:t[2];if(r>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||o>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*n*o>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=i?`@builtin(global_invocation_id) global_id : vec3,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3,\n @builtin(local_invocation_id) local_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(num_workgroups) num_workgroups : vec3`,l=i?`let global_idx = global_id.x;\n let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] +\n workgroup_id.y * num_workgroups[0] + workgroup_id.x;\n let global_idx = workgroup_index * ${r*n*o}u + local_idx;`;return`@compute @workgroup_size(${r}, ${n}, ${o})\n fn main(${a}) {\n ${l}\n `}appendVariableUniforms(t){t.rank!==0&&(t.shape.startsWith(\"uniforms.\")&&this.uniforms.push({name:t.shape.replace(\"uniforms.\",\"\"),type:\"u32\",length:t.rank}),t.strides.startsWith(\"uniforms.\")&&this.uniforms.push({name:t.strides.replace(\"uniforms.\",\"\"),type:\"u32\",length:t.rank}))}declareVariable(t,r){if(t.usage===\"internal\")throw new Error(\"cannot use internal variable with declareVariable(). use registerInternalVariables() instead.\");this.variables.push(t),this.appendVariableUniforms(t);let n=t.usage===\"input\"?\"read\":\"read_write\",o=t.type.storage;return`@group(0) @binding(${r}) var ${t.name}: array<${o}>;`}declareVariables(...t){return t.map(r=>this.declareVariable(r,this.variableIndex++)).join(`\n`)}registerInternalVariable(t){if(t.usage!==\"internal\")throw new Error(\"cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.\");this.internalVariables.push(t),this.appendVariableUniforms(t)}registerInternalVariables(...t){return t.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(t,r,n=1){return this.uniforms.push({name:t,type:r,length:n}),this}registerUniforms(t){return this.uniforms=this.uniforms.concat(t),this}uniformDeclaration(){if(this.uniforms.length===0)return\"\";let t=[];for(let{name:r,type:n,length:o}of this.uniforms)if(o&&o>4)n===\"f16\"?t.push(`@align(16) ${r}:array, ${Math.ceil(o/8)}>`):t.push(`${r}:array, ${Math.ceil(o/4)}>`);else{let i=o==null||o===1?n:`vec${o}<${n}>`;t.push(`${r}:${i}`)}return`\n struct Uniforms { ${t.join(\", \")} };\n @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(t=>t.impl()).join(`\n`)+this.internalVariables.map(t=>t.impl()).join(`\n`)}get variablesInfo(){if(this.uniforms.length===0)return;let t=r=>[12,10,1,6][[\"u32\",\"f16\",\"f32\",\"i32\"].indexOf(r)];return this.uniforms.map(r=>[t(r.type),r.length??1])}},os=(e,t)=>new co(e,t)});var rm,is,nm,om,im,Pe,as,ss,ut=R(()=>{\"use strict\";te();oe();Ie();ae();rm=e=>{if(!e||e.length!==1)throw new Error(\"Transpose requires 1 input.\")},is=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,nm=(e,t)=>k.sortBasedOnPerm(e,is(e.length,t)),om=(e,t,r,n)=>{let o=`fn perm(i: ${n.type.indices}) -> ${r.type.indices} {\n var a: ${r.type.indices};`;for(let i=0;i{let r=[],n=[];for(let o=0;o{let r=e.dataType,n=e.dims.length,o=is(n,t),i=nm(e.dims,o),{newShape:a,newPerm:l}=im(e.dims,o),d=k.areEqual(l,[2,3,1]),c=k.areEqual(l,[3,1,2]),m=a.length===2&&l[0]>l[1]||d||c,u=m?a:e.dims,h=i;m&&(u=d?[a[0],a[1]*a[2]]:c?[a[0]*a[1],a[2]]:a,h=[u[1],u[0]]);let w=E(\"a\",r,u.length),y=M(\"output\",r,h.length),g=16,x;return m?x=$=>`\n ${$.registerUniform(\"output_size\",\"u32\").declareVariables(w,y)}\n var tile : array, ${g}>;\n ${$.mainStart([g,g,1])}\n let stride = (uniforms.output_shape[1] - 1) / ${g} + 1;\n let workgroup_id_x = workgroup_index % stride;\n let workgroup_id_y = workgroup_index / stride;\n let input_col = workgroup_id_y * ${g}u + local_id.x;\n let input_row = workgroup_id_x * ${g}u + local_id.y;\n if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) {\n tile[local_id.y][local_id.x] = ${w.getByIndices(`${w.type.indices}(input_row, input_col)`)};\n }\n workgroupBarrier();\n\n let output_col = workgroup_id_x * ${g}u + local_id.x;\n let output_row = workgroup_id_y * ${g}u + local_id.y;\n if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) {\n ${y.setByIndices(`${y.type.indices}(output_row, output_col)`,\"tile[local_id.x][local_id.y]\")}\n }\n }`:x=$=>`\n ${$.registerUniform(\"output_size\",\"u32\").declareVariables(w,y)}\n\n ${om(o,n,w,y)}\n\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let indices = ${y.offsetToIndices(\"global_idx\")};\n let aIndices = perm(indices);\n\n ${y.setByOffset(\"global_idx\",w.getByIndices(\"aIndices\"))}\n }`,{name:m?\"TransposeShared\":\"Transpose\",shaderCache:{hint:`${t}`,inputDependencies:[\"rank\"]},getRunData:()=>{let $=k.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:m?{x:Math.ceil(h[1]/g),y:Math.ceil(h[0]/g)}:{x:Math.ceil($/64)},programUniforms:[{type:12,data:$},...V(u,h)]}},getShaderSource:x}},as=(e,t)=>{rm(e.inputs),e.compute(Pe(e.inputs[0],t.perm))},ss=e=>re({perm:e.perm})});var am,sm,um,lm,dm,cm,pm,mm,fm,hm,tt,us,ls,ds,cs,ps,ms,fs,hs,gs,bs,ys=R(()=>{\"use strict\";te();oe();ae();Yr();ut();am={max:\"select(bestValue, candidate, candidate > bestValue)\",min:\"select(bestValue, candidate, candidate < bestValue)\",mean:\"bestValue + candidate\",sum:\"bestValue + candidate\",prod:\"bestValue * candidate\",sumSquare:\"bestValue + candidate * candidate\",logSumExp:\"bestValue + exp(candidate)\",l1:\"bestValue + abs(candidate)\",l2:\"bestValue + candidate * candidate\",logSum:\"bestValue + candidate\"},sm={max:\"select(bestValue, candidate, candidate > bestValue)\",min:\"select(bestValue, candidate, candidate < bestValue)\",mean:\"bestValue + candidate\",sum:\"bestValue + candidate\",prod:\"bestValue * candidate\",sumSquare:\"bestValue + candidate\",logSumExp:\"bestValue + candidate\",l1:\"bestValue + candidate\",l2:\"bestValue + candidate\",logSum:\"bestValue + candidate\"},um={max:\"_A[offset]\",min:\"_A[offset]\",mean:\"0\",sum:\"0\",prod:\"1\",sumSquare:\"0\",logSumExp:\"0\",l1:\"0\",l2:\"0\",logSum:\"0\"},lm={max:\"bestValue\",min:\"bestValue\",sum:\"bestValue\",prod:\"bestValue\",sumSquare:\"bestValue\",logSumExp:\"log(bestValue)\",l1:\"bestValue\",l2:\"sqrt(bestValue)\",logSum:\"log(bestValue)\"},dm=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let i=0;ie[i]);return[r,o]},pm=(e,t)=>{let r=e.length+t.length,n=[],o=0;for(let i=0;i{for(let r=0;r{let r=[];if(!mm(e,t)){for(let n=0;nr.push(n))}return r},hm=(e,t,r,n,o,i,a)=>{let l=r[0].dims,d=k.size(i),c=k.size(a),m=E(\"_A\",r[0].dataType,l),u=M(\"output\",o,i),h=64;d===1&&(h=256);let w=`\n var aBestValues : array;\n `,y=g=>`\n ${g.registerUniform(\"reduceSize\",\"u32\").declareVariables(m,u)}\n ${w}\n fn DIV_CEIL(a : u32, b : u32) -> u32 {\n return ((a - 1u) / b + 1u);\n }\n ${g.mainStart(h)}\n\n let outputIndex = global_idx / ${h};\n let offset = outputIndex * uniforms.reduceSize;\n\n var bestValue = f32(${um[n]});\n let Length = uniforms.reduceSize;\n for (var k = local_idx; k < Length; k = k + ${h}) {\n let candidate = f32(${m.getByOffset(\"offset + k\")});\n bestValue = ${am[n]};\n }\n aBestValues[local_idx] = bestValue;\n workgroupBarrier();\n\n var reduceSize = min(Length, ${h}u);\n for (var currentSize = reduceSize / 2u; reduceSize > 1u;\n currentSize = reduceSize / 2u) {\n let interval = DIV_CEIL(reduceSize, 2u);\n if (local_idx < currentSize) {\n let candidate = aBestValues[local_idx + interval];\n bestValue = ${sm[n]};\n aBestValues[local_idx] = bestValue;\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (local_idx == 0u) {\n ${u.setByOffset(\"outputIndex\",`${n===\"mean\"?`${u.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${u.type.storage}(${lm[n]})`}`)};\n }\n }`;return{name:e,shaderCache:{hint:`${t};${h}`,inputDependencies:[\"type\"]},getShaderSource:y,getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:d},programUniforms:[{type:12,data:c}]})}},tt=(e,t,r,n)=>{let o=e.inputs.length===1?r:ho(e.inputs,r),i=o.axes;i.length===0&&!o.noopWithEmptyAxes&&(i=e.inputs[0].dims.map((w,y)=>y));let a=k.normalizeAxes(i,e.inputs[0].dims.length),l=a,d=e.inputs[0],c=fm(l,e.inputs[0].dims.length);c.length>0&&(d=e.compute(Pe(e.inputs[0],c),{inputs:[0],outputs:[-1]})[0],l=dm(l.length,d.dims.length));let[m,u]=cm(d.dims,l),h=m;o.keepDims&&(h=pm(m,a)),e.compute(hm(t,o.cacheKey,[d],n,e.inputs[0].dataType,h,u),{inputs:[d]})},us=(e,t)=>{tt(e,\"ReduceMeanShared\",t,\"mean\")},ls=(e,t)=>{tt(e,\"ReduceL1Shared\",t,\"l1\")},ds=(e,t)=>{tt(e,\"ReduceL2Shared\",t,\"l2\")},cs=(e,t)=>{tt(e,\"ReduceLogSumExpShared\",t,\"logSumExp\")},ps=(e,t)=>{tt(e,\"ReduceMaxShared\",t,\"max\")},ms=(e,t)=>{tt(e,\"ReduceMinShared\",t,\"min\")},fs=(e,t)=>{tt(e,\"ReduceProdShared\",t,\"prod\")},hs=(e,t)=>{tt(e,\"ReduceSumShared\",t,\"sum\")},gs=(e,t)=>{tt(e,\"ReduceSumSquareShared\",t,\"sumSquare\")},bs=(e,t)=>{tt(e,\"ReduceLogSumShared\",t,\"logSum\")}});var rt,gm,Zr,ho,nt,bm,ym,wm,_m,vm,$m,xm,Sm,Tm,Im,ot,ws,_s,vs,$s,xs,Ss,Ts,Is,Cs,As,Yr=R(()=>{\"use strict\";te();oe();Ie();ae();ys();rt=e=>{if(!e||e.length===0||e.length>2)throw new Error(\"Reduce op requires 1 or 2 inputs.\");if(e.length===2&&e[1].dims.length!==1)throw new Error(\"Invalid axes input dims.\")},gm=e=>[\"\",\"\",`var value = ${e.getByIndices(\"input_indices\")};`,\"\"],Zr=(e,t,r,n,o,i,a=!1,l=!1)=>{let d=[],c=r[0].dims,m=c.length,u=k.normalizeAxes(o,m),h=!l&&u.length===0;c.forEach((x,$)=>{h||u.indexOf($)>=0?a&&d.push(1):d.push(x)});let w=d.length,y=k.size(d);return{name:e,shaderCache:t,getShaderSource:x=>{let $=[],v=E(\"_A\",r[0].dataType,m),S=M(\"output\",i,w),T=n(v,S,u),C=T[2];for(let A=0,P=0;A=0?(a&&P++,C=`for(var j${A}: u32 = 0; j${A} < ${c[A]}; j${A}++) {\n ${T[2].includes(\"last_index\")?`let last_index = j${A};`:\"\"}\n ${v.indicesSet(\"input_indices\",A,`j${A}`)}\n ${C}\n }`):($.push(`${v.indicesSet(\"input_indices\",A,S.indicesGet(\"output_indices\",P))};`),P++);return`\n\n ${x.registerUniform(\"output_size\",\"u32\").declareVariables(v,S)}\n\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n var input_indices: ${v.type.indices};\n let output_indices = ${S.offsetToIndices(\"global_idx\")};\n\n ${$.join(`\n`)}\n ${T[0]} // init ops for reduce max/min\n ${T[1]}\n ${C}\n ${T[3]}\n ${T.length===4?S.setByOffset(\"global_idx\",\"value\"):T.slice(4).join(`\n`)}\n }`},getRunData:()=>({outputs:[{dims:d,dataType:i}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:[{type:12,data:y},...V(c,d)]})}},ho=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),re({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},nt=(e,t,r,n)=>{let o=e.inputs,i=o.length===1?r:ho(o,r);e.compute(Zr(t,{hint:i.cacheKey,inputDependencies:[\"rank\"]},[o[0]],i.noopWithEmptyAxes&&i.axes.length===0?gm:n,i.axes,o[0].dataType,i.keepDims,i.noopWithEmptyAxes),{inputs:[0]})},bm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceLogSum\",t,(n,o)=>[`var value = ${o.type.storage}(0);`,\"\",`value += ${n.getByIndices(\"input_indices\")};`,\"value = log(value);\"])},ym=(e,t)=>{rt(e.inputs),nt(e,\"ReduceL1\",t,(n,o)=>[`var value = ${o.type.storage}(0);`,\"\",`value += abs(${n.getByIndices(\"input_indices\")});`,\"\"])},wm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceL2\",t,(n,o)=>[`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`,\"\",`t = ${n.getByIndices(\"input_indices\")}; value += (t * t);`,\"value = sqrt(value);\"])},_m=(e,t)=>{rt(e.inputs),nt(e,\"ReduceLogSumExp\",t,(n,o)=>[`var value = ${o.type.storage}(0);`,\"\",`value += exp(${n.getByIndices(\"input_indices\")});`,\"value = log(value);\"])},vm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceMax\",t,(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(n.indicesSet(\"input_indices\",l,0));return[`${a.join(`\n`)}`,`var value = ${n.getByIndices(\"input_indices\")};`,`value = max(value, ${n.getByIndices(\"input_indices\")});`,\"\"]})},$m=(e,t)=>{rt(e.inputs),nt(e,\"ReduceMean\",t,(n,o,i)=>{let a=1;for(let l=0;l=0||i.length===0)&&(a*=e.inputs[0].dims[l]);return[\"var sum = f32(0);\",\"\",`sum += f32(${n.getByIndices(\"input_indices\")});`,`let value = ${o.type.value}(sum / ${a});`]})},xm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceMin\",t,(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(`input_indices[${l}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${n.getByIndices(\"input_indices\")};`,`value = min(value, ${n.getByIndices(\"input_indices\")});`,\"\"]})},Sm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceProd\",t,(n,o)=>[`var value = ${o.type.storage}(1);`,\"\",`value *= ${n.getByIndices(\"input_indices\")};`,\"\"])},Tm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceSum\",t,(n,o)=>[`var value = ${o.type.storage}(0);`,\"\",`value += ${n.getByIndices(\"input_indices\")};`,\"\"])},Im=(e,t)=>{rt(e.inputs),nt(e,\"ReduceSumSquare\",t,(n,o)=>[`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`,\"\",`t = ${n.getByIndices(\"input_indices\")}; value += t * t;`,\"\"])},ot=(e,t,r)=>{if(t.length===0)return r;let n=1,o=1;for(let i=0;i1024},ws=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?$m(e,t):us(e,t)},_s=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ym(e,t):ls(e,t)},vs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?wm(e,t):ds(e,t)},$s=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?_m(e,t):cs(e,t)},xs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?vm(e,t):ps(e,t)},Ss=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?xm(e,t):ms(e,t)},Ts=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Sm(e,t):fs(e,t)},Is=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Tm(e,t):hs(e,t)},Cs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Im(e,t):gs(e,t)},As=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?bm(e,t):bs(e,t)}});var ks,Es,Ps,go,zs=R(()=>{\"use strict\";te();Ie();Yr();ks=e=>{if(!e||e.length===0||e.length>2)throw new Error(\"ArgMinMaxOp op requires 1 or 2 inputs.\");if(e[0].dataType!==1)throw new Error(\"Invalid input type.\")},Es=(e,t)=>{ks(e.inputs);let r=(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(`input_indices[${l}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${n.getByIndices(\"input_indices\")};\nvar best_index : i32 = 0;`,`if (${n.getByIndices(\"input_indices\")} ${t.selectLastIndex>0?\"<=\":\"<\"} value) {\n value = ${n.getByIndices(\"input_indices\")};\n best_index = i32(last_index);\n }`,\"\",o.setByOffset(\"global_idx\",\"best_index\")]};e.compute(Zr(\"ArgMin\",{hint:t.cacheKey,inputDependencies:[\"rank\"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Ps=(e,t)=>{ks(e.inputs);let r=(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(`input_indices[${l}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${n.getByIndices(\"input_indices\")};\nvar best_index : i32 = 0;`,`if (${n.getByIndices(\"input_indices\")} ${t.selectLastIndex>0?\">=\":\">\"} value) {\n value = ${n.getByIndices(\"input_indices\")};\n best_index = i32(last_index);\n }`,\"\",o.setByOffset(\"global_idx\",\"best_index\")]};e.compute(Zr(\"argMax\",{hint:t.cacheKey,inputDependencies:[\"rank\"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},go=e=>re(e)});var Cm,bo,Am,km,Em,Rt,Pm,Os,Xr=R(()=>{\"use strict\";te();oe();qr();ae();Cm=(e,t)=>{let r=e[0],n=e[1],o=e[2],i=e[3],a=e[4],l=e[5];if(a&&l)throw new Error(\"Attention cannot have both past and attention_bias\");if(r.dims.length!==3)throw new Error('Input \"input\" must have 3 dimensions');let d=r.dims[0],c=r.dims[1],m=r.dims[2];if(o.dims.length!==1)throw new Error('Input \"bias\" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input \"weights\" is expected to have 2 dimensions');if(n.dims[0]!==m)throw new Error(\"Input 1 dimension 0 should have same length as dimension 2 of input 0\");if(o.dims[0]!==n.dims[1])throw new Error('Input \"bias\" dimension 0 should have same length as dimension 1 of input \"weights\"');let u=o.dims[0]/3,h=u,w=h;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error(\"qkv_hidden_sizes attribute should have 3 elements\");for(let S of t.qkvHiddenSizes)if(S%t.numHeads!==0)throw new Error(\"qkv_hidden_sizes should be divisible by num_heads\");u=t.qkvHiddenSizes[0],h=t.qkvHiddenSizes[1],w=t.qkvHiddenSizes[2]}let y=c;if(u!==h)throw new Error(\"qkv_hidden_sizes first element should be same as the second\");if(o.dims[0]!==u+h+w)throw new Error('Input \"bias\" dimension 0 should have same length as sum of Q/K/V hidden sizes');let g=0;if(a){if(h!==w)throw new Error('Input \"past\" expect k_hidden_size == v_hidden_size');if(a.dims.length!==5)throw new Error('Input \"past\" must have 5 dimensions');if(a.dims[0]!==2)throw new Error('Input \"past\" first dimension must be 2');if(a.dims[1]!==d)throw new Error('Input \"past\" second dimension must be batch_size');if(a.dims[2]!==t.numHeads)throw new Error('Input \"past\" third dimension must be num_heads');if(a.dims[4]!==h/t.numHeads)throw new Error('Input \"past\" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(g=a.dims[3])}let x=y+g,$=-1,v=0;if(i)throw new Error(\"Mask not supported\");if(a)throw new Error(\"past is not supported\");if(l){if(l.dims.length!==4)throw new Error('Input \"attention_bias\" must have 4 dimensions');if(l.dims[0]!==d||l.dims[1]!==t.numHeads||l.dims[2]!==c||l.dims[3]!==x)throw new Error('Expect \"attention_bias\" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:d,sequenceLength:c,pastSequenceLength:g,kvSequenceLength:y,totalSequenceLength:x,maxSequenceLength:$,inputHiddenSize:m,hiddenSize:u,vHiddenSize:w,headSize:Math.floor(u/t.numHeads),vHeadSize:Math.floor(w/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:v,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},bo=(e,t,r)=>t&&e?`\n let total_sequence_length_input = u32(${t.getByOffset(\"0\")});\n let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);\n let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;\n let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input;\n total_sequence_length = u32(${e?.getByOffset(\"batchIdx\")}) + 1;\n var past_sequence_length: u32 = 0;\n if (is_first_prompt == false) {\n past_sequence_length = total_sequence_length - sequence_length;\n }\n `:`\n ${r?\"let past_sequence_length = uniforms.past_sequence_length\":\"\"};\n let present_sequence_length = total_sequence_length;\n `,Am=(e,t,r,n,o,i,a,l)=>{let d=ye(a?1:i),c=64,m=i/d;m{let v=M(\"x\",e.dataType,e.dims,d),S=[v],T=a?E(\"seq_lens\",a.dataType,a.dims):void 0;T&&S.push(T);let C=l?E(\"total_sequence_length_input\",l.dataType,l.dims):void 0;C&&S.push(C);let A=Ee(e.dataType),P=[{name:\"batch_size\",type:\"u32\"},{name:\"num_heads\",type:\"u32\"},{name:\"past_sequence_length\",type:\"u32\"},{name:\"sequence_length\",type:\"u32\"},{name:\"total_sequence_length\",type:\"u32\"},{name:\"elements_per_thread\",type:\"u32\"}];return`\n var thread_max: array;\n var thread_sum: array;\n ${$.registerUniforms(P).declareVariables(...S)}\n ${$.mainStart([c,1,1])}\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let sequence_length = uniforms.sequence_length;\n var total_sequence_length = uniforms.total_sequence_length;\n ${bo(T,C,!1)}\n let local_offset = local_idx * uniforms.elements_per_thread;\n let offset = (global_idx / ${c}) * uniforms.total_sequence_length + local_offset;\n let seq_causal_length = ${a?\"u32(past_sequence_length + workgroup_id.y + 1)\":\"total_sequence_length\"};\n var thread_max_vector = ${y}(-3.402823e+38f);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n thread_max_vector = max(${y}(x[offset + i]), thread_max_vector);\n }\n thread_max[local_idx] = ${(()=>{switch(d){case 1:return\"thread_max_vector\";case 2:return\"max(thread_max_vector.x, thread_max_vector.y)\";case 4:return\"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))\";default:throw new Error(`Unsupported components: ${d}`)}})()};\n workgroupBarrier();\n\n var max_value = f32(-3.402823e+38f);\n for (var i = 0u; i < ${c}; i++) {\n max_value = max(thread_max[i], max_value);\n }\n\n var sum_vector = ${y}(0);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n sum_vector += exp(${y}(x[offset + i]) - max_value);\n }\n thread_sum[local_idx] = ${(()=>{switch(d){case 1:return\"sum_vector\";case 2:return\"sum_vector.x + sum_vector.y\";case 4:return\"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w\";default:throw new Error(`Unsupported components: ${d}`)}})()};\n workgroupBarrier();\n\n var sum: f32 = 0;\n for (var i = 0u; i < ${c}; i++) {\n sum += thread_sum[i];\n }\n\n if (sum == 0) {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n x[offset + i] = ${v.type.value}(${A}(1.0) / ${A}(seq_causal_length));\n }\n } else {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n var f32input = ${y}(x[offset + i]);\n x[offset + i] = ${v.type.value}(exp(f32input - max_value) / sum);\n }\n }\n ${a?`\n for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) {\n x[offset + total_seq_id] = ${v.type.value}(${A}(0));\n }`:\"\"};\n }`};return{name:\"AttentionProbsSoftmax\",shaderCache:{hint:`${c};${w};${d}`,inputDependencies:g},getShaderSource:x,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(i/c),y:o,z:t*r},programUniforms:h})}},km=(e,t,r,n,o,i,a,l,d)=>{let c=a+i.kvSequenceLength,m=[i.batchSize,i.numHeads,i.sequenceLength,c],u=e>1&&n,h=i.kvNumHeads?i.kvNumHeads:i.numHeads,w=u?[i.batchSize,h,c,i.headSize]:void 0,y=i.nReps?i.nReps:1,g=i.scale===0?1/Math.sqrt(i.headSize):i.scale,x=ye(i.headSize),$=i.headSize/x,v=12,S={x:Math.ceil(c/v),y:Math.ceil(i.sequenceLength/v),z:i.batchSize*i.numHeads},T=[{type:12,data:i.sequenceLength},{type:12,data:$},{type:12,data:c},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:1,data:g},{type:12,data:a},{type:12,data:i.kvSequenceLength},{type:12,data:y}],C=u&&n&&k.size(n.dims)>0,A=[\"type\",\"type\"];C&&A.push(\"type\"),o&&A.push(\"type\"),l&&A.push(\"type\"),d&&A.push(\"type\");let P=[{dims:m,dataType:t.dataType,gpuDataType:0}];u&&P.push({dims:w,dataType:t.dataType,gpuDataType:0});let O=U=>{let L=E(\"q\",t.dataType,t.dims,x),j=E(\"key\",r.dataType,r.dims,x),K=[L,j];if(C){let ne=E(\"past_key\",n.dataType,n.dims,x);K.push(ne)}o&&K.push(E(\"attention_bias\",o.dataType,o.dims));let W=l?E(\"seq_lens\",l.dataType,l.dims):void 0;W&&K.push(W);let ee=d?E(\"total_sequence_length_input\",d.dataType,d.dims):void 0;ee&&K.push(ee);let ue=M(\"output\",t.dataType,m),Z=[ue];u&&Z.push(M(\"present_key\",t.dataType,w,x));let J=Ee(1,x),Q=[{name:\"M\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"num_heads\",type:\"u32\"},{name:\"head_size\",type:\"u32\"},{name:\"alpha\",type:\"f32\"},{name:\"past_sequence_length\",type:\"u32\"},{name:\"kv_sequence_length\",type:\"u32\"},{name:\"n_reps\",type:\"u32\"}];return`\n const TILE_SIZE = ${v}u;\n\n var tileQ: array<${L.type.storage}, ${v*v}>;\n var tileK: array<${L.type.storage}, ${v*v}>;\n ${U.registerUniforms(Q).declareVariables(...K,...Z)}\n ${U.mainStart([v,v,1])}\n // x holds the N and y holds the M\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let kvHeadIdx = ${y===1?\"headIdx\":\"headIdx / uniforms.n_reps\"};\n let kv_num_heads = ${y===1?\"uniforms.num_heads\":\"uniforms.num_heads / uniforms.n_reps\"};\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let m = workgroup_id.y * TILE_SIZE;\n let n = workgroup_id.x * TILE_SIZE;\n let sequence_length = uniforms.M;\n var total_sequence_length = uniforms.N;\n ${bo(W,ee,!0)}\n let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx;\n let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;\n ${C&&u?\"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;\":\"\"};\n let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K;\n ${u?\"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;\":\"\"}\n var value = ${J}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {\n var idx = TILE_SIZE * local_id.y + local_id.x;\n ${(()=>C&&u?`\n if (n + local_id.y < past_sequence_length) {\n tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x];\n } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {\n tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x];\n }`:`\n if (n + local_id.y < uniforms.kv_sequence_length) {\n tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x];\n }`)()}\n ${u?`if (n + local_id.y < present_sequence_length) {\n present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];\n }`:\"\"}\n }\n workgroupBarrier();\n\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {\n value += ${J}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);\n }\n\n workgroupBarrier();\n }\n\n if (global_id.y < uniforms.M && global_id.x < total_sequence_length) {\n let headOffset = workgroup_id.z * uniforms.M * uniforms.N;\n let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;\n var sum: f32 = ${(()=>{switch(x){case 1:return\"value\";case 2:return\"value.x + value.y\";case 4:return\"value.x + value.y + value.z + value.w\";default:throw new Error(`Unsupported components: ${x}`)}})()};\n output[outputIdx] = ${ue.type.value} (sum * uniforms.alpha) + ${o?\"attention_bias[outputIdx]\":\"0.0\"};\n }\n }`};return{name:\"AttentionProbs\",shaderCache:{hint:`${x};${o!==void 0};${n!==void 0};${e}`,inputDependencies:A},getRunData:()=>({outputs:P,dispatchGroup:S,programUniforms:T}),getShaderSource:O}},Em=(e,t,r,n,o,i,a=void 0,l=void 0)=>{let d=i+o.kvSequenceLength,c=o.nReps?o.nReps:1,m=o.vHiddenSize*c,u=e>1&&n,h=o.kvNumHeads?o.kvNumHeads:o.numHeads,w=u?[o.batchSize,h,d,o.headSize]:void 0,y=[o.batchSize,o.sequenceLength,m],g=12,x={x:Math.ceil(o.vHeadSize/g),y:Math.ceil(o.sequenceLength/g),z:o.batchSize*o.numHeads},$=[{type:12,data:o.sequenceLength},{type:12,data:d},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:m},{type:12,data:i},{type:12,data:o.kvSequenceLength},{type:12,data:c}],v=u&&n&&k.size(n.dims)>0,S=[\"type\",\"type\"];v&&S.push(\"type\"),a&&S.push(\"type\"),l&&S.push(\"type\");let T=[{dims:y,dataType:t.dataType,gpuDataType:0}];u&&T.push({dims:w,dataType:t.dataType,gpuDataType:0});let C=A=>{let P=E(\"probs\",t.dataType,t.dims),O=E(\"v\",r.dataType,r.dims),U=[P,O];v&&U.push(E(\"past_value\",n.dataType,n.dims));let L=a?E(\"seq_lens\",a.dataType,a.dims):void 0;a&&U.push(L);let j=l?E(\"total_sequence_length_input\",l.dataType,l.dims):void 0;l&&U.push(j);let W=[M(\"output\",t.dataType,y)];u&&W.push(M(\"present_value\",t.dataType,w));let ee=[{name:\"M\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"num_heads\",type:\"u32\"},{name:\"head_size\",type:\"u32\"},{name:\"v_hidden_size\",type:\"u32\"},{name:\"past_sequence_length\",type:\"u32\"},{name:\"kv_sequence_length\",type:\"u32\"},{name:\"n_reps\",type:\"u32\"}];return`\n const TILE_SIZE = ${g}u;\n var tileQ: array<${P.type.value}, ${g*g}>;\n var tileV: array<${P.type.value}, ${g*g}>;\n ${A.registerUniforms(ee).declareVariables(...U,...W)}\n ${A.mainStart([g,g,1])}\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let kvHeadIdx = ${c===1?\"headIdx\":\"headIdx / uniforms.n_reps\"};\n let kv_num_heads = ${c===1?\"uniforms.num_heads\":\"uniforms.num_heads / uniforms.n_reps\"};\n let m = global_id.y;\n let n = global_id.x;\n let sequence_length = uniforms.M;\n var total_sequence_length = uniforms.K;\n ${bo(L,j,!0)}\n let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;\n let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch\n ${v&&u?\"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;\":\"\"};\n let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n;\n ${u?\"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;\":\"\"}\n var value = ${P.type.storage}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n var idx = TILE_SIZE * local_id.y + local_id.x;\n ${(()=>v&&u?`\n if (w + local_id.y < past_sequence_length) {\n tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N];\n } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {\n tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N];\n }\n `:`\n if (w + local_id.y < uniforms.kv_sequence_length) {\n tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N];\n }`)()}\n ${u?`\n if (w + local_id.y < present_sequence_length) {\n present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx];\n }`:\"\"}\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) {\n value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x];\n }\n workgroupBarrier();\n }\n\n // we need to transpose output from BNSH_v to BSND_v\n if (m < uniforms.M && n < uniforms.N) {\n let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size\n + headIdx * uniforms.N + n;\n output[outputIdx] = value;\n }\n }`};return{name:\"AttentionScore\",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:S},getRunData:()=>({outputs:T,dispatchGroup:x,programUniforms:$}),getShaderSource:C}},Rt=(e,t,r,n,o,i,a,l,d,c,m=void 0,u=void 0)=>{let h=Math.min(e.outputCount,1+(a?1:0)+(l?1:0)),w=h>1?c.pastSequenceLength:0,y=w+c.kvSequenceLength,g=d&&k.size(d.dims)>0?d:void 0,x=[t,r];h>1&&a&&k.size(a.dims)>0&&x.push(a),g&&x.push(g),m&&x.push(m),u&&x.push(u);let $=e.compute(km(h,t,r,a,g,c,w,m,u),{inputs:x,outputs:h>1?[-1,1]:[-1]})[0];e.compute(Am($,c.batchSize,c.numHeads,w,c.sequenceLength,y,m,u),{inputs:m&&u?[$,m,u]:[$],outputs:[]});let v=[$,n];h>1&&l&&k.size(l.dims)>0&&v.push(l),m&&v.push(m),u&&v.push(u),e.compute(Em(h,$,n,l,c,w,m,u),{inputs:v,outputs:h>1?[0,2]:[0]})},Pm=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,o=t.inputHiddenSize,i=t.headSize,a=12,l={x:Math.ceil(t.headSize/a),y:Math.ceil(t.sequenceLength/a),z:t.batchSize*t.numHeads},d=[e.inputs[0],e.inputs[1],e.inputs[2]],c=[{type:12,data:n},{type:12,data:o},{type:12,data:i},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],m=u=>{let h=M(\"output_q\",d[0].dataType,r),w=M(\"output_k\",d[0].dataType,r),y=M(\"output_v\",d[0].dataType,r),g=E(\"input\",d[0].dataType,d[0].dims),x=E(\"weight\",d[1].dataType,d[1].dims),$=E(\"bias\",d[2].dataType,d[2].dims),v=g.type.storage,S=[{name:\"M\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"num_heads\",type:\"u32\"},{name:\"head_size\",type:\"u32\"},{name:\"hidden_size\",type:\"u32\"},{name:\"ldb\",type:\"u32\"}];return`\n const TILE_SIZE = ${a}u;\n var tileInput: array<${v}, ${a*a}>;\n var tileWeightQ: array<${v}, ${a*a}>;\n var tileWeightK: array<${v}, ${a*a}>;\n var tileWeightV: array<${v}, ${a*a}>;\n ${u.registerUniforms(S).declareVariables(g,x,$,h,w,y)}\n ${u.mainStart([a,a,1])}\n let batchIndex = workgroup_id.z / uniforms.num_heads;\n let headNumber = workgroup_id.z % uniforms.num_heads;\n let m = global_id.y;\n let n = global_id.x;\n\n let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;\n let biasOffsetQ = headNumber * uniforms.head_size;\n let biasOffsetK = uniforms.hidden_size + biasOffsetQ;\n let biasOffsetV = uniforms.hidden_size + biasOffsetK;\n\n var valueQ = ${v}(0);\n var valueK = ${v}(0);\n var valueV = ${v}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n let offset = n + (w + local_id.y) * uniforms.ldb;\n tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];\n tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];\n tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:l,programUniforms:c}),getShaderSource:m},{inputs:d,outputs:[-1,-1,-1]})},Os=(e,t)=>{let r=Cm(e.inputs,t),[n,o,i]=Pm(e,r);return Rt(e,n,o,i,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r)}});var zm,Om,Dm,Ds,Bs=R(()=>{\"use strict\";He();te();oe();Ie();ae();zm=(e,t)=>{if(!e||e.length!==5)throw new Error(\"BatchNormalization requires 5 inputs\");let r=(n,o,i)=>{let a=o.length;if(a!==n.length)throw new Error(`${i}: num dimensions != ${a}`);o.forEach((l,d)=>{if(l!==n[d])throw new Error(`${i}: dim[${d}] do not match`)})};if(e[0].dims.length>1){let n=t.format===\"NHWC\"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,n,\"Invalid input scale\"),r(e[2].dims,n,\"Invalid input B\"),r(e[3].dims,n,\"Invalid input mean\"),r(e[4].dims,n,\"Invalid input var\")}else r(e[1].dims,[1],\"Invalid input scale\"),r(e[2].dims,[1],\"Invalid input B\"),r(e[3].dims,[1],\"Invalid input mean\"),r(e[4].dims,[1],\"Invalid input var\")},Om=(e,t)=>{let{epsilon:r,spatial:n,format:o}=t,i=e[0].dims,a=n?ye(i[i.length-1]):1,l=o===\"NHWC\"&&i.length>1?a:1,d=k.size(i)/a,c=n,m=c?i.length:i,u=E(\"x\",e[0].dataType,e[0].dims,a),h=E(\"scale\",e[1].dataType,e[1].dims,l),w=E(\"bias\",e[2].dataType,e[2].dims,l),y=E(\"inputMean\",e[3].dataType,e[3].dims,l),g=E(\"inputVar\",e[4].dataType,e[4].dims,l),x=M(\"y\",e[0].dataType,m,a),$=()=>{let S=\"\";if(n)S=`let cOffset = ${i.length===1?\"0u\":o===\"NHWC\"?`outputIndices[${i.length-1}] / ${a}`:\"outputIndices[1]\"};`;else if(o===\"NCHW\")S=`\n ${x.indicesSet(\"outputIndices\",\"0\",\"0\")}\n let cOffset = ${x.indicesToOffset(\"outputIndices\")};`;else{S=`var cIndices = ${h.type.indices}(0);\n cIndices[0] = outputIndices[${i.length-1}];`;for(let T=1;T`\n const epsilon = ${r};\n ${S.registerUniform(\"outputSize\",\"u32\").declareVariables(u,h,w,y,g,x)}\n ${S.mainStart()}\n ${S.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n var outputIndices = ${x.offsetToIndices(`global_idx * ${a}`)};\n ${$()}\n let scale = ${h.getByOffset(\"cOffset\")};\n let bias = ${w.getByOffset(\"cOffset\")};\n let inputMean = ${y.getByOffset(\"cOffset\")};\n let inputVar = ${g.getByOffset(\"cOffset\")};\n let x = ${u.getByOffset(\"global_idx\")};\n let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;\n ${x.setByOffset(\"global_idx\",\"value\")}\n }`;return{name:\"BatchNormalization\",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${a}`,inputDependencies:c?[\"rank\",\"type\",\"type\",\"type\",\"type\"]:void 0},getShaderSource:v,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c?[{type:12,data:d},...V(i)]:[{type:12,data:d}]})}},Dm=e=>re(e),Ds=(e,t)=>{let{inputs:r,outputCount:n}=e,o=Dm({...t,outputCount:n});if(ve.webgpu.validateInputContent&&zm(r,o),t.trainingMode)throw new Error(\"BatchNormalization trainingMode is not supported yet.\");e.compute(Om(r,o))}});var Bm,Mm,Ms,Rs=R(()=>{\"use strict\";oe();ae();Bm=e=>{if(e[0].dims.length!==3)throw new Error(\"input should have 3 dimensions\");if(![320,640,1280].includes(e[0].dims[2]))throw new Error(\"number of channels should be 320, 640 or 1280\");if(e[1].dims.length!==1)throw new Error(\"bias is expected to have 1 dimensions\");if(e[0].dims[2]!==e[1].dims[0])throw new Error(\"last dimension of input and bias are not the same\")},Mm=e=>{let t=e[0].dims,r=e[0].dims[2],n=k.size(t)/4,o=e[0].dataType,i=E(\"input\",o,t,4),a=E(\"bias\",o,[r],4),l=E(\"residual\",o,t,4),d=M(\"output\",o,t,4);return{name:\"BiasAdd\",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:m=>`\n const channels = ${r}u / 4;\n ${m.declareVariables(i,a,l,d)}\n\n ${m.mainStart()}\n ${m.guardAgainstOutOfBoundsWorkgroupSizes(n)}\n let value = ${i.getByOffset(\"global_idx\")}\n + ${a.getByOffset(\"global_idx % channels\")} + ${l.getByOffset(\"global_idx\")};\n ${d.setByOffset(\"global_idx\",\"value\")}\n }`}},Ms=e=>{Bm(e.inputs),e.compute(Mm(e.inputs))}});var Rm,fe,Us,Vs,Ns,Ws,Ls,Gs,Hs,Fs,qs,Um,js,Ks,Ys,Zs,Jt,Xs,Qr,Qs,Js,eu,tu,ru,nu,ou,iu,au,su,uu,lu,du,cu,pu,mu,fu,hu,yo,wo,gu,bu,yu,Vm,Nm,wu,Jr=R(()=>{\"use strict\";te();oe();Ie();ae();Rm=(e,t,r,n,o,i,a)=>{let l=Math.ceil(t/4),d=\"\";typeof o==\"string\"?d=`${o}(a)`:d=o(\"a\");let c=E(\"inputData\",r,[l],4),m=M(\"outputData\",n,[l],4),u=[{name:\"vec_size\",type:\"u32\"}];return a&&u.push(...a),`\n ${e.registerUniforms(u).declareVariables(c,m)}\n\n ${i??\"\"}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.vec_size\")}\n\n let a = ${c.getByOffset(\"global_idx\")};\n ${m.setByOffset(\"global_idx\",d)}\n }`},fe=(e,t,r,n,o,i=e.dataType,a,l)=>{let d=[{type:12,data:Math.ceil(k.size(e.dims)/4)}];return a&&d.push(...a),{name:t,shaderCache:{hint:o,inputDependencies:[\"type\"]},getShaderSource:c=>Rm(c,k.size(e.dims),e.dataType,i,r,n,l),getRunData:c=>({outputs:[{dims:e.dims,dataType:i}],dispatchGroup:{x:Math.ceil(k.size(c[0].dims)/64/4)},programUniforms:d})}},Us=e=>{e.compute(fe(e.inputs[0],\"Abs\",\"abs\"))},Vs=e=>{e.compute(fe(e.inputs[0],\"Acos\",\"acos\"))},Ns=e=>{e.compute(fe(e.inputs[0],\"Acosh\",\"acosh\"))},Ws=e=>{e.compute(fe(e.inputs[0],\"Asin\",\"asin\"))},Ls=e=>{e.compute(fe(e.inputs[0],\"Asinh\",\"asinh\"))},Gs=e=>{e.compute(fe(e.inputs[0],\"Atan\",\"atan\"))},Hs=e=>{e.compute(fe(e.inputs[0],\"Atanh\",\"atanh\"))},Fs=e=>re(e),qs=(e,t)=>{let r;switch(t.to){case 10:r=\"vec4\";break;case 1:r=\"vec4\";break;case 12:r=\"vec4\";break;case 6:r=\"vec4\";break;case 9:r=\"vec4\";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(fe(e.inputs[0],\"Cast\",r,void 0,t.cacheKey,t.to))},Um=e=>{let t,r,n=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,r=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,r=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error(\"Unsupport data type\")}return re({min:t,max:r})},js=(e,t)=>{let r=t||Um(e.inputs),n=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Clip\",o=>`clamp(${o}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,r.cacheKey,void 0,[{type:e.inputs[0].dataType,data:r.min},{type:e.inputs[0].dataType,data:r.max}],[{name:\"min\",type:n},{name:\"max\",type:n}]),{inputs:[0]})},Ks=e=>{e.compute(fe(e.inputs[0],\"Ceil\",\"ceil\"))},Ys=e=>{e.compute(fe(e.inputs[0],\"Cos\",\"cos\"))},Zs=e=>{e.compute(fe(e.inputs[0],\"Cosh\",\"cosh\"))},Jt=e=>re(e),Xs=(e,t)=>{let r=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Elu\",n=>`elu_vf32(${n})`,`\n const elu_alpha_ = ${r}(${t.alpha});\n\n fn elu_f32(a: ${r}) -> ${r} {\n return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);\n }\n\n fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> {\n return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));\n }`,t.cacheKey))},Qr=(e=\"f32\")=>`\nconst r0: ${e} = 0.3275911;\nconst r1: ${e} = 0.254829592;\nconst r2: ${e} = -0.284496736;\nconst r3: ${e} = 1.421413741;\nconst r4: ${e} = -1.453152027;\nconst r5: ${e} = 1.061405429;\n\nfn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {\n let absv = abs(v);\n let x = 1.0 / (1.0 + r0 * absv);\n return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));\n}`,Qs=e=>{let t=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Erf\",r=>`erf_vf32(${r})`,Qr(t)))},Js=e=>{e.compute(fe(e.inputs[0],\"Exp\",\"exp\"))},eu=e=>{e.compute(fe(e.inputs[0],\"Floor\",\"floor\"))},tu=e=>{let t=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Gelu\",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Qr(t)))},ru=(e,t)=>{let r=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"LeakyRelu\",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},nu=e=>{e.compute(fe(e.inputs[0],\"Not\",t=>`!${t}`))},ou=e=>{e.compute(fe(e.inputs[0],\"Neg\",t=>`-${t}`))},iu=e=>{e.compute(fe(e.inputs[0],\"Reciprocal\",t=>`1.0/${t}`))},au=e=>{let t=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Relu\",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},su=e=>{e.compute(fe(e.inputs[0],\"Sigmoid\",t=>`(1.0 / (1.0 + exp(-${t})))`))},uu=e=>re(e),lu=(e,t)=>{let r=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"HardSigmoid\",n=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${n} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},du=e=>{e.compute(fe(e.inputs[0],\"Sin\",\"sin\"))},cu=e=>{e.compute(fe(e.inputs[0],\"Sinh\",\"sinh\"))},pu=e=>{e.compute(fe(e.inputs[0],\"Sqrt\",\"sqrt\"))},mu=e=>{e.compute(fe(e.inputs[0],\"Tan\",\"tan\"))},fu=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,hu=e=>{e.compute(fe(e.inputs[0],\"Tanh\",fu))},yo=(e=\"f32\")=>`\nconst fast_gelu_a: ${e} = 0.5;\nconst fast_gelu_b: ${e} = 0.7978845608028654;\nconst fast_gelu_c: ${e} = 0.035677408136300125;\n\nfn tanh_v(v: vec4<${e}>) -> vec4<${e}> {\n return ${fu(\"v\")};\n}\n`,wo=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,gu=e=>{let t=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"FastGelu\",wo,yo(t),void 0,e.inputs[0].dataType))},bu=(e,t)=>{let r=Ee(e.inputs[0].dataType);return e.compute(fe(e.inputs[0],\"ThresholdedRelu\",n=>`select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},yu=e=>{e.compute(fe(e.inputs[0],\"Log\",\"log\"))},Vm=(e,t)=>`\nconst alpha = vec4<${e}>(${t});\nconst one = ${e}(1.0);\nconst zero = ${e}(0.0);\n\nfn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {\n let v = x *alpha;\n var x1 : vec4<${e}>;\n for (var i = 0; i < 4; i = i + 1) {\n if (v[i] >= zero) {\n x1[i] = one / (one + exp(-v[i]));\n } else {\n x1[i] = one - one / (one + exp(v[i]));\n }\n }\n return x * x1;\n}\n`,Nm=e=>`quick_gelu_impl(${e})`,wu=(e,t)=>{let r=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"QuickGelu\",Nm,Vm(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}});var Wm,Lm,vu,$u=R(()=>{\"use strict\";oe();ae();Jr();Wm=e=>{if(e[0].dims.length!==3)throw new Error(\"input should have 3 dimensions\");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error(\"hidden state should be 2560, 5120 or 10240\");if(e[1].dims.length!==1)throw new Error(\"bias is expected to have 1 dimensions\");if(e[0].dims[2]!==e[1].dims[0])throw new Error(\"last dimension of input and bias are not the same\")},Lm=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=E(\"input\",e[0].dataType,e[0].dims,4),n=E(\"bias\",e[0].dataType,[e[0].dims[2]],4),o=M(\"output\",e[0].dataType,t,4),i=k.size(t)/4,a=me(e[0].dataType);return{name:\"BiasSplitGelu\",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:d=>`\n const M_SQRT2 = sqrt(2.0);\n const halfChannels = ${e[0].dims[2]/4/2}u;\n\n ${d.declareVariables(r,n,o)}\n\n ${Qr(a)}\n\n ${d.mainStart()}\n ${d.guardAgainstOutOfBoundsWorkgroupSizes(i)}\n let biasIdx = global_idx % halfChannels;\n let batchIndex = global_idx / halfChannels;\n let inputOffset = biasIdx + batchIndex * halfChannels * 2;\n let valueLeft = input[inputOffset] + bias[biasIdx];\n let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];\n let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);\n\n ${o.setByOffset(\"global_idx\",\"valueLeft * geluRight\")}\n }`}},vu=e=>{Wm(e.inputs),e.compute(Lm(e.inputs))}});var Gm,Hm,it,xu,Su,Tu,Iu,Cu,Au,ku,Eu,Pu,zu,Ou=R(()=>{\"use strict\";te();oe();ae();Gm=(e,t,r,n,o,i,a,l,d,c,m,u)=>{let h,w;typeof l==\"string\"?h=w=(v,S)=>`${l}((${v}),(${S}))`:typeof l==\"function\"?h=w=l:(h=l.scalar,w=l.vector);let y=M(\"outputData\",m,n.length,4),g=E(\"aData\",d,t.length,4),x=E(\"bData\",c,r.length,4),$;if(o)if(i){let v=k.size(t)===1,S=k.size(r)===1,T=t.length>0&&t[t.length-1]%4===0,C=r.length>0&&r[r.length-1]%4===0;v||S?$=y.setByOffset(\"global_idx\",w(v?`${g.type.value}(${g.getByOffset(\"0\")}.x)`:g.getByOffset(\"global_idx\"),S?`${x.type.value}(${x.getByOffset(\"0\")}.x)`:x.getByOffset(\"global_idx\"))):$=`\n let outputIndices = ${y.offsetToIndices(\"global_idx * 4u\")};\n let offsetA = ${g.broadcastedIndicesToOffset(\"outputIndices\",y)};\n let offsetB = ${x.broadcastedIndicesToOffset(\"outputIndices\",y)};\n ${y.setByOffset(\"global_idx\",w(a||T?g.getByOffset(\"offsetA / 4u\"):`${g.type.value}(${g.getByOffset(\"offsetA / 4u\")}[offsetA % 4u])`,a||C?x.getByOffset(\"offsetB / 4u\"):`${x.type.value}(${x.getByOffset(\"offsetB / 4u\")}[offsetB % 4u])`))}\n `}else $=y.setByOffset(\"global_idx\",w(g.getByOffset(\"global_idx\"),x.getByOffset(\"global_idx\")));else{if(!i)throw new Error(\"no necessary to use scalar implementation for element-wise binary op implementation.\");let v=(S,T,C=\"\")=>{let A=`aData[indexA${T}][componentA${T}]`,P=`bData[indexB${T}][componentB${T}]`;return`\n let outputIndices${T} = ${y.offsetToIndices(`global_idx * 4u + ${T}u`)};\n let offsetA${T} = ${g.broadcastedIndicesToOffset(`outputIndices${T}`,y)};\n let offsetB${T} = ${x.broadcastedIndicesToOffset(`outputIndices${T}`,y)};\n let indexA${T} = offsetA${T} / 4u;\n let indexB${T} = offsetB${T} / 4u;\n let componentA${T} = offsetA${T} % 4u;\n let componentB${T} = offsetB${T} % 4u;\n ${S}[${T}] = ${C}(${h(A,P)});\n `};m===9?$=`\n var data = vec4(0);\n ${v(\"data\",0,\"u32\")}\n ${v(\"data\",1,\"u32\")}\n ${v(\"data\",2,\"u32\")}\n ${v(\"data\",3,\"u32\")}\n outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:$=`\n ${v(\"outputData[global_idx]\",0)}\n ${v(\"outputData[global_idx]\",1)}\n ${v(\"outputData[global_idx]\",2)}\n ${v(\"outputData[global_idx]\",3)}\n `}return`\n ${e.registerUniform(\"vec_size\",\"u32\").declareVariables(g,x,y)}\n\n ${u??\"\"}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.vec_size\")}\n ${$}\n }`},Hm=(e,t,r,n,o,i,a=r.dataType)=>{let l=r.dims.map(g=>Number(g)??1),d=n.dims.map(g=>Number(g)??1),c=!k.areEqual(l,d),m=l,u=k.size(l),h=!1,w=!1,y=[c];if(c){let g=et.calcShape(l,d,!1);if(!g)throw new Error(\"Can't perform binary op on the given tensors\");m=g.slice(),u=k.size(m);let x=k.size(l)===1,$=k.size(d)===1,v=l.length>0&&l[l.length-1]%4===0,S=d.length>0&&d[d.length-1]%4===0;y.push(x),y.push($),y.push(v),y.push(S);let T=1;for(let C=1;Cg.toString()).join(\"_\"),inputDependencies:[\"rank\",\"rank\"]},getShaderSource:g=>Gm(g,l,d,m,h,c,w,o,r.dataType,n.dataType,a,i),getRunData:()=>({outputs:[{dims:m,dataType:a}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:Math.ceil(k.size(m)/4)},...V(l,d,m)]})}},it=(e,t,r,n,o,i)=>{e.compute(Hm(t,o??\"\",e.inputs[0],e.inputs[1],r,n,i))},xu=e=>{it(e,\"Add\",(t,r)=>`${t}+${r}`)},Su=e=>{it(e,\"Div\",(t,r)=>`${t}/${r}`)},Tu=e=>{it(e,\"Equal\",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},Iu=e=>{it(e,\"Mul\",(t,r)=>`${t}*${r}`)},Cu=e=>{let t=E(\"input\",e.inputs[0].dataType,e.inputs[0].dims).type.value;it(e,\"Pow\",{scalar:(n,o)=>`pow_custom(${n},${o})`,vector:(n,o)=>`pow_vector_custom(${n},${o})`},`\n fn pow_custom(a : ${t}, b : ${t}) -> ${t} {\n if (b == ${t}(0.0)) {\n return ${t}(1.0);\n } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {\n return ${t}(pow(f32(a), f32(b))); // NaN\n }\n return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t===\"i32\"?\"round\":\"\"}(pow(f32(abs(a)), f32(b))));\n }\n fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {\n // TODO: implement vectorized pow\n return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));\n }\n `)},Au=e=>{it(e,\"Sub\",(t,r)=>`${t}-${r}`)},ku=e=>{it(e,\"Greater\",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},Eu=e=>{it(e,\"Less\",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Pu=e=>{it(e,\"GreaterOrEqual\",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},zu=e=>{it(e,\"LessOrEqual\",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}});var qm,jm,Km,Ym,Du,Bu,Mu=R(()=>{\"use strict\";te();oe();Ie();ae();qm=(e,t)=>{if(!e||e.length<1)throw new Error(\"too few inputs\");let r=0,n=e[r],o=n.dataType,i=n.dims.length;e.forEach((a,l)=>{if(l!==r){if(a.dataType!==o)throw new Error(\"input tensors should be one type\");if(a.dims.length!==i)throw new Error(\"input tensors should have the same shape\");a.dims.forEach((d,c)=>{if(c!==t&&d!==n.dims[c])throw new Error(\"non concat dimensions must match\")})}})},jm=(e,t)=>`\n fn calculateInputIndex(index: u32) -> u32 {\n let sizeInConcatAxis = array(${t});\n for (var i: u32 = 0u; i < ${e}; i += 1u ) {\n if (index < sizeInConcatAxis[i]) {\n return i;\n }\n }\n return ${e}u;\n }`,Km=(e,t)=>{let r=e.length,n=[];for(let o=0;o{let o=k.size(r),i=new Array(e.length),a=new Array(e.length),l=0,d=[],c=[],m=[{type:12,data:o}];for(let g=0;g`uniforms.sizeInConcatAxis${g}`).join(\",\"),y=g=>`\n\n ${(()=>{g.registerUniform(\"outputSize\",\"u32\");for(let x=0;x(${w});\n ${h} -= sizeInConcatAxis[inputIndex - 1u];\n }\n\n ${Km(a,u)}\n }`;return{name:\"Concat\",shaderCache:{hint:`${t}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:m}),getShaderSource:y}},Du=(e,t)=>{let r=e.inputs,n=r[0].dims,o=k.normalizeAxis(t.axis,n.length);qm(r,o);let i=n.slice();i[o]=r.reduce((l,d)=>l+(d.dims.length>o?d.dims[o]:0),0);let a=r.filter(l=>k.size(l.dims)>0);e.compute(Ym(a,o,i,r[0].dataType),{inputs:a})},Bu=e=>re({axis:e.axis})});var Ve,Ne,We,en,lt=R(()=>{\"use strict\";te();oe();Ve=(e,t,r=\"f32\")=>{switch(e.activation){case\"Relu\":return`value = max(value, ${t}(0.0));`;case\"Sigmoid\":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case\"Clip\":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case\"HardSigmoid\":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case\"LeakyRelu\":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case\"Tanh\":return`let e2x = exp(-2.0 * abs(value));\n value = sign(value) * (1.0 - e2x) / (1.0 + e2x);\n `;case\"\":return\"\";default:throw new Error(`Unsupported activation ${e.activation}`)}},Ne=(e,t)=>{e.activation===\"Clip\"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation===\"HardSigmoid\"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation===\"LeakyRelu\"&&t.push({type:1,data:e.alpha})},We=(e,t)=>{e.activation===\"Clip\"?t.push({name:\"clip_max\",type:\"f32\"},{name:\"clip_min\",type:\"f32\"}):e.activation===\"HardSigmoid\"?t.push({name:\"alpha\",type:\"f32\"},{name:\"beta\",type:\"f32\"}):e.activation===\"LeakyRelu\"&&t.push({name:\"alpha\",type:\"f32\"})},en=e=>{let t=e?.activation||\"\";if(t===\"HardSigmoid\"){let[r,n]=e?.activation_params||[.2,.5];return{activation:t,alpha:r,beta:n}}else if(t===\"Clip\"){let[r,n]=e?.activation_params||[rs,ns];return{activation:t,clipMax:n,clipMin:r}}else if(t===\"LeakyRelu\"){let[r]=e?.activation_params||[.01];return{activation:t,alpha:r}}return{activation:t}}});var ze,tn,er=R(()=>{\"use strict\";ze=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},tn=e=>`\n ${e?\"value = value + getBiasByOutputCoords(coords);\":\"\"}\n `});var rn,_o=R(()=>{\"use strict\";rn=e=>`\nfn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 {\n return dot(coords, vec4(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n}\nfn getOutputIndexFromCoords(coords : vec4) -> i32 {\n return dot(coords, vec4(\n i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));\n}\n`});var tr,nn,on=R(()=>{\"use strict\";te();oe();ae();lt();tr=(e,t,r,n,o)=>{let i=n-r;return`\n ${Array.from({length:r}).map((a,l)=>`\n if (${F(t.shape,l,t.rank)} != 1) {\n ${t.indicesSet(e,l,F(o,l+i,n))}\n } else {\n ${t.indicesSet(e,l,0)}\n }`).join(\"\")}\n`},nn=(e,t,r,n,o=!1,i)=>{let a=e[0].dims,l=e[1].dims,d=a[a.length-2],c=l[l.length-1],m=a[a.length-1],u=ye(c),h=ye(m),w=ye(d),y=k.size(r)/u/w,g=e.length>2,x=n?n.slice(0,-2):r.slice(0,-2),v=[k.size(x),d,c],S=[{type:12,data:y},{type:12,data:d},{type:12,data:c},{type:12,data:m}];Ne(t,S),S.push(...V(x,a,l)),g&&S.push(...V(e[2].dims)),S.push(...V(v));let T=C=>{let A=Kr(\"batch_dims\",e[0].dataType,x.length),P=E(\"a\",e[0].dataType,a.length,h),O=E(\"b\",e[1].dataType,l.length,u),U=M(\"output\",e[0].dataType,v.length,u),L=me(U.type.tensor),j=Ve(t,U.type.value,L),K=[P,O],W=\"\";if(g){let Z=o?u:1;K.push(E(\"bias\",e[2].dataType,e[2].dims.length,Z)),W=`${o?`value += bias[col / ${Z}];`:`value += ${U.type.value}(bias[row + i]);`}`}let ee=[{name:\"output_size\",type:\"u32\"},{name:\"M\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"K\",type:\"u32\"}];We(t,ee);let ue=()=>{let Z=`var a_data: ${P.type.value};`;for(let J=0;J;\n for (var k: u32 = 0u; k < uniforms.K; k = k + ${h}) {\n ${ue()}\n }\n for (var i = 0u; i < ${w}u; i++) {\n var value = values[i];\n ${W}\n ${j}\n let cur_indices = ${U.type.indices}(batch, row + i, col);\n let offset = ${U.indicesToOffset(\"cur_indices\")};\n ${U.setByOffset(`offset / ${u}`,\"value\")};\n }\n }\n `};return{name:\"MatMulNaive\",shaderCache:{hint:`${t.activation};${u};${h};${w};${o}`,inputDependencies:g?[\"rank\",\"rank\",\"rank\"]:[\"rank\",\"rank\"]},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:S}),getShaderSource:T}}});var Zm,Xm,rr,Ru,Qm,nr,Jm,or,ir=R(()=>{\"use strict\";te();oe();ae();lt();on();er();Zm=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart / innerElementSize + inputCol${t?\", batchIndices\":\"\"});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRow + innerRow,\n kStart / innerElementSize + inputCol${t?\", batchIndices\":\"\"});\n `,Xm=(e,t)=>e?`\n let ACached0 = mm_Asub[k * innerElementSize][localRow];\n let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];\n let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];\n ${t===3?\"\":\"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];\"}\n for (var i = 0; i < rowPerThread; i = i + 1) {\n acc[i] = BCached0 * ACached0[i] + acc[i];\n acc[i] = BCached1 * ACached1[i] + acc[i];\n acc[i] = BCached2 * ACached2[i] + acc[i];\n ${t===3?\"\":\"acc[i] = BCached3 * ACached3[i] + acc[i];\"}\n }`:`\n for (var i = 0; i < rowPerThread; i = i + 1) {\n let ACached = mm_Asub[tileRow + i][k];\n acc[i] = BCached0 * ACached.x + acc[i];\n acc[i] = BCached1 * ACached.y + acc[i];\n acc[i] = BCached2 * ACached.z + acc[i];\n ${t===3?\"\":\"acc[i] = BCached3 * ACached.w + acc[i];\"}\n }`,rr=(e,t,r=\"f32\",n,o=!1,i=32,a=!1,l=32)=>{let d=t[1]*e[1],c=t[0]*e[0],m=o?d:i,u=o?i:d,h=m/t[0],w=i/t[1];if(!((o&&h===4&&e[1]===4||!o&&(h===3||h===4))&&m%t[0]===0&&i%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${h} and workPerThread[1] ${e[1]} must be 4.\n Otherwise, innerElementSize ${h} must be 3 or 4.\n tileAWidth ${m} must be divisible by workgroupSize[0]${t[0]}. tileInner ${i} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`\nvar mm_Asub: array, ${m/h}>, ${u}>;\nvar mm_Bsub: array, ${c/e[0]}>, ${i}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${h};\nconst tileInner = ${i};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let localRow = i32(localId.y);\n let tileRow = localRow * rowPerThread;\n let tileCol = i32(localId.x);\n\n let globalRow =i32(globalId.y) * rowPerThread;\n let globalCol = i32(globalId.x);\n let batch = ${a?\"0\":\"i32(globalId.z)\"};\n ${n?`let batchIndices = ${n.offsetToIndices(\"u32(batch)\")};`:\"\"}\n let globalRowStart = i32(workgroupId.y) * ${d};\n\n let num_tiles = ${a?`${Math.ceil(l/i)}`:\"(uniforms.dim_inner - 1) / tileInner + 1\"};\n var kStart = ${a?`i32(globalId.z) * ${l}`:\"0\"};\n\n var acc: array, rowPerThread>;\n\n // Loop over shared dimension.\n let tileRowB = localRow * ${w};\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileCol;\n ${Zm(o,n)}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?\", batchIndices\":\"\"});\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {\n let BCached0 = mm_Bsub[k * innerElementSize][tileCol];\n let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];\n let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];\n ${h===3?\"\":\"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];\"}\n\n ${Xm(o,h)}\n }\n\n workgroupBarrier();\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);\n }\n}`},Ru=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart + inputCol${t?\", batchIndices\":\"\"});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRowStart + inputRow,\n kStart + inputCol${t?\", batchIndices\":\"\"});\n `,Qm=e=>e?\"let ACached = mm_Asub[k][tileRow + innerRow];\":\"let ACached = mm_Asub[tileRow + innerRow][k];\",nr=(e,t,r=\"f32\",n,o=!1,i=32,a=!1,l=32,d=!1)=>{let c=e[1]*t[1],m=e[0]*t[0],u=o?c:i,h=o?i:c;if(!(h%t[1]===0&&u%t[0]===0&&i%t[1]===0))throw new Error(`tileAHight ${h} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${u} must be divisible by workgroupSize[0]${t[0]}, tileInner ${i} must be divisible by workgroupSize[1]${t[1]}`);let w=h/t[1],y=u/t[0],g=i/t[1],x=d?`\n let localRow = i32(localId.y);\n let localCol = i32(localId.x);\n let globalRowStart = i32(workgroupId.y) * ${c};\n let globalColStart = i32(workgroupId.x) * ${m};\n\n // Loop over shared dimension.\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var inputRow = localRow; inputRow < ${h}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${t[0]}) {\n ${Ru(o,n)}\n }\n }\n // Load one tile of B into local memory.\n for (var inputRow = localRow; inputRow < ${i}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${m}; inputCol = inputCol + ${t[0]}) {\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalColStart + inputCol${n?\", batchIndices\":\"\"});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] +\n ACached * BCached[innerCol];\n }\n }\n }\n workgroupBarrier();\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let gRow = globalRowStart + localRow + innerRow * ${t[1]};\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let gCol = globalColStart + localCol + innerCol * ${t[0]};\n mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);\n }\n }\n `:`\nlet tileRow = i32(localId.y) * rowPerThread;\nlet tileCol = i32(localId.x) * colPerThread;\n\nlet globalRow = i32(globalId.y) * rowPerThread;\nlet globalCol = i32(globalId.x) * colPerThread;\nlet globalRowStart = i32(workgroupId.y) * ${c};\n\nlet tileRowA = i32(localId.y) * ${w};\nlet tileColA = i32(localId.x) * ${y};\nlet tileRowB = i32(localId.y) * ${g};\n// Loop over shared dimension.\nfor (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${y}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${Ru(o,n)}\n }\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${g}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol + innerCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalCol + innerCol${n?\", batchIndices\":\"\"});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][tileCol + inner];\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n ${Qm(o)}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];\n }\n }\n }\n\n workgroupBarrier();\n}\n\nfor (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n mm_write(batch, globalRow + innerRow, globalCol + innerCol,\n acc[innerRow][innerCol]);\n }\n}\n`;return`\n var mm_Asub : array, ${h}>;\n var mm_Bsub : array, ${i}>;\n const rowPerThread = ${e[1]};\n const colPerThread = ${e[0]};\n const tileInner = ${i};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let batch = ${a?\"0\":\"i32(globalId.z)\"};\n ${n?`let batchIndices = ${n.offsetToIndices(\"u32(batch)\")};`:\"\"}\n let num_tiles = ${a?`${Math.ceil(l/i)}`:\"(uniforms.dim_inner - 1) / tileInner + 1\"};\n var kStart = ${a?`i32(globalId.z) * ${l}`:\"0\"};\n\n var acc : array, rowPerThread>;\n ${x}\n }\n`},Jm=(e,t,r,n,o=!1)=>{let[i,a,l,d]=n,c=me(n[0].type.tensor);return`\n fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${ze(e,c)} {\n var value = ${ze(e,c)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)\n {\n var aIndices: ${a.type.indices};\n ${tr(\"aIndices\",a,a.rank-2,i.rank,\"batchIndices\")}\n ${a.indicesSet(\"aIndices\",a.rank-2,\"u32(row)\")}\n ${a.indicesSet(\"aIndices\",a.rank-1,\"u32(colIn)\")}\n value = ${a.getByIndices(\"aIndices\")};\n }\n return value;\n }\n\n fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${ze(e,c)} {\n var value = ${ze(e,c)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)\n {\n var bIndices: ${l.type.indices};\n ${tr(\"bIndices\",l,l.rank-2,i.rank,\"batchIndices\")}\n ${l.indicesSet(\"bIndices\",l.rank-2,\"u32(row)\")}\n ${l.indicesSet(\"bIndices\",l.rank-1,\"u32(colIn)\")}\n value = ${l.getByIndices(\"bIndices\")};\n }\n return value;\n }\n\n fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${ze(e,c)}) {\n let col = colIn * ${e};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueIn;\n let coords = vec3(batch, row, colIn);\n ${t?`value = value + ${o?\"bias[colIn]\":`${ze(e,c)}(bias[row])`};`:\"\"}\n ${r}\n ${d.setByIndices(\"vec3(coords)\",\"value\")}\n }\n }\n `},or=(e,t,r,n,o=!1,i)=>{let a=e[0].dims,l=e[1].dims,d=a.slice(0,-2),c=l.slice(0,-2),m=n?n.slice(0,-2):r.slice(0,-2),u=k.size(m),h=a[a.length-2],w=a[a.length-1],y=l[l.length-1],g=w%4===0&&y%4===0,x=h<=8?[4,1,1]:[4,4,1],$=[8,8,1],v=[Math.ceil(y/$[0]/x[0]),Math.ceil(h/$[1]/x[1]),Math.ceil(u/$[2]/x[2])],S=g?4:1,T=[...d,h,w/S],C=T.length,A=[...c,w,y/S],P=A.length,O=[u,h,y/S],U=[{type:6,data:h},{type:6,data:y},{type:6,data:w}];Ne(t,U),U.push(...V(m,T,A));let L=[\"rank\",\"rank\"],j=e.length>2;j&&(U.push(...V(e[2].dims)),L.push(\"rank\")),U.push(...V(O));let K=W=>{let ee=m.length,ue=Kr(\"batchDims\",e[0].dataType,ee,1),Z=me(e[0].dataType),J=E(\"a\",e[0].dataType,C,S),Q=E(\"b\",e[1].dataType,P,S),ne=M(\"result\",e[0].dataType,O.length,S),we=[J,Q];if(j){let q=o?S:1;we.push(E(\"bias\",e[2].dataType,e[2].dims.length,q))}let Ae=[{name:\"dim_a_outer\",type:\"i32\"},{name:\"dim_b_outer\",type:\"i32\"},{name:\"dim_inner\",type:\"i32\"}];We(t,Ae);let $e=me(ne.type.tensor),de=Ve(t,ne.type.value,$e),N=Jm(S,j,de,[ue,J,Q,ne],o);return`\n ${W.registerUniforms(Ae).registerInternalVariables(ue).declareVariables(...we,ne)}\n ${N}\n ${g?rr(x,$,Z,ue):nr(x,$,Z,ue)}\n `};return{name:\"MatMul\",shaderCache:{hint:`${x};${t.activation};${g};${o}`,inputDependencies:L},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:v[0],y:v[1],z:v[2]},programUniforms:U}),getShaderSource:K}}});var ef,Uu,Vu=R(()=>{\"use strict\";te();je();ae();lt();er();_o();ir();ef=(e,t,r,n,o=!1,i,a=4,l=4,d=4,c=\"f32\")=>{let m=L=>{switch(L){case 1:return\"resData = x[xIndex];\";case 3:return`resData = vec3<${c}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return\"resData = x[xIndex / 4];\";default:throw new Error(`innerElementSize ${L} is not supported.`)}},u=L=>{switch(L){case 1:return\"return w[row * i32(uniforms.w_shape[3]) + colIn];\";case 4:return\"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];\";default:throw new Error(`innerElementSize ${L} is not supported.`)}},h=e?`\n let coord = vec4(batch, xRow, xCol, xCh);\n `:`\n let coord = vec4(batch, xCh, xRow, xCol);\n `,w=e?`\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n `:`\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n `,y=e?\"i32(uniforms.x_shape[1])\":\"i32(uniforms.x_shape[2])\",g=e?\"i32(uniforms.x_shape[2])\":\"i32(uniforms.x_shape[3])\",x=e?\"row\":\"col\",$=e?\"col\":\"row\",v=`\n let inChannels = i32(uniforms.w_shape[2]);\n let outWidth = ${e?\"i32(uniforms.result_shape[2])\":\"i32(uniforms.result_shape[3])\"};\n let outRow = ${x} / outWidth;\n let outCol = ${x} % outWidth;\n\n let WRow = ${$} / (i32(uniforms.w_shape[1]) * inChannels);\n let WCol = ${$} / inChannels % i32(uniforms.w_shape[1]);\n let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];\n let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];\n let xCh = ${$} % inChannels;\n var resData = ${ze(a,c)}(0.0);\n // The bounds checking is always needed since we use it to pad zero for\n // the 'same' padding type.\n if (xRow >= 0 && xRow < ${y} && xCol >= 0 && xCol < ${g}) {\n ${h}\n let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape));\n ${m(a)}\n }\n return resData;`,S=e?t&&n?`\n let col = colIn * ${a};\n ${v}`:`\n let col = colIn * ${a};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${v}\n }\n return ${ze(a,c)}(0.0);`:n&&r?`\n let col = colIn * ${a};\n ${v}`:`\n let col = colIn * ${a};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${v}\n }\n return ${ze(a,c)}(0.0);`,T=`${u(l)}`,C=ze(d,c),A=e?ze(a,c):ze(l,c),P=e?ze(l,c):ze(a,c),O=Ve(i,C,c);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${A} {\n ${e?S:T}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${P} {\n ${e?T:S}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${C}) {\n let col = colIn * ${d};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)\n {\n var value = valueIn;\n let outWidth = ${e?\"i32(uniforms.result_shape[2])\":\"i32(uniforms.result_shape[3])\"};\n ${w}\n ${tn(o)}\n ${O}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`},Uu=(e,t,r,n,o,i,a,l,d)=>{let c=t.format===\"NHWC\",m=c?e[0].dims[3]:e[0].dims[1],u=r[0],h=c?r[2]:r[3],w=c?r[1]:r[2],y=c?r[3]:r[1],g=c&&(m%4===0||m%3===0)&&y%4===0,x=c?y:h*w,$=c?h*w:y,v=[8,8,1],S=n<=8?[4,1,1]:[4,4,1],T=[Math.ceil(x/v[0]/S[0]),Math.ceil($/v[1]/S[1]),Math.ceil(u/v[2]/S[2])];se(\"verbose\",()=>`[conv2d_mm_webgpu] dispatch = ${T}`);let C=g?c&&m%4!==0?3:4:1,A=v[1]*S[1],P=v[0]*S[0],O=Math.max(v[0]*C,v[1]),U=n%A===0,L=o%P===0,j=i%O===0,K=g?[C,4,4]:[1,1,1],W=[{type:6,data:n},{type:6,data:o},{type:6,data:i},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Ne(t,W),W.push(...V(e[0].dims,e[1].dims));let ee=[\"rank\",\"rank\"];a&&(W.push(...V(e[2].dims)),ee.push(\"rank\")),W.push(...V(r));let ue=Z=>{let J=[{name:\"dim_a_outer\",type:\"i32\"},{name:\"dim_b_outer\",type:\"i32\"},{name:\"dim_inner\",type:\"i32\"},{name:\"pad\",type:\"i32\",length:2},{name:\"stride\",type:\"i32\",length:2},{name:\"dilation\",type:\"i32\",length:2}];We(t,J);let Q=g?4:1,ne=me(e[0].dataType),we=`\n fn setOutputAtIndex(flatIndex : i32, value : ${g?`vec4<${ne}>`:ne}) {\n result[flatIndex] = ${g?`vec4<${ne}>`:ne}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${g?`vec4<${ne}>`:ne}) {\n let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${g?\"/ 4\":\"\"}, value);\n }`,Ae=E(\"x\",e[0].dataType,e[0].dims.length,C===3?1:C),$e=E(\"w\",e[1].dataType,e[1].dims.length,Q),de=[Ae,$e],N=M(\"result\",e[0].dataType,r.length,Q);if(a){let q=E(\"bias\",e[2].dataType,e[2].dims.length,Q);de.push(q),we+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${g?`vec4<${ne}>`:ne} {\n return bias[coords.${c?\"w\":\"y\"}${g?\"/ 4\":\"\"}];\n }`}return`\n ${rn(\"uniforms.result_strides\")}\n //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4,\n // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2,\n // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };\n ${Z.registerUniforms(J).declareVariables(...de,N)}\n ${we}\n ${ef(c,U,L,j,a,t,K[0],K[1],K[2],ne)}\n ${g?rr(S,v,ne,void 0,!c,O):nr(S,v,ne,void 0,!c,O,!1,void 0,l)}`};return{name:\"Conv2DMatMul\",shaderCache:{hint:`${t.cacheKey};${C};${g};${U};${L};${j};${A};${P};${O}`,inputDependencies:ee},getRunData:()=>({outputs:[{dims:d?d(r):r,dataType:e[0].dataType}],dispatchGroup:{x:T[0],y:T[1],z:T[2]},programUniforms:W}),getShaderSource:ue}}});var tf,Nu,an,rf,Wu,nf,Lu,Gu,Hu=R(()=>{\"use strict\";te();je();oe();ae();lt();er();tf=e=>{let t=1;for(let r=0;rtypeof e==\"number\"?[e,e,e]:e,an=(e,t)=>t<=1?e:e+(e-1)*(t-1),rf=(e,t,r,n=1)=>{let o=an(t,n);return Math.floor((e[0]*(r-1)-r+o)/2)},Wu=(e,t,r,n,o)=>{o==null&&(o=rf(e,t[0],n[0]));let i=[0,0,0,r];for(let a=0;a<3;a++)e[a]+2*o>=t[a]&&(i[a]=Math.trunc((e[a]-t[a]+2*o)/n[a]+1));return i},nf=(e,t,r,n,o,i,a,l,d,c)=>{let m,u,h,w;if(e===\"VALID\"&&(e=0),typeof e==\"number\"){m={top:e,bottom:e,left:e,right:e,front:e,back:e};let y=Wu([t,r,n,1],[l,d,c],1,[o,i,a],e);u=y[0],h=y[1],w=y[2]}else if(Array.isArray(e)){if(!e.every((g,x,$)=>g===$[0]))throw Error(`Unsupported padding parameter: ${e}`);m={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let y=Wu([t,r,n,1],[l,d,c],1,[o,i,a],e[0]);u=y[0],h=y[1],w=y[2]}else if(e===\"SAME_UPPER\"){u=Math.ceil(t/o),h=Math.ceil(r/i),w=Math.ceil(n/a);let y=(u-1)*o+l-t,g=(h-1)*i+d-r,x=(w-1)*a+c-n,$=Math.floor(y/2),v=y-$,S=Math.floor(g/2),T=g-S,C=Math.floor(x/2),A=x-C;m={top:S,bottom:T,left:C,right:A,front:$,back:v}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:m,outDepth:u,outHeight:h,outWidth:w}},Lu=(e,t,r,n,o,i=!1,a=\"channelsLast\")=>{let l,d,c,m,u;if(a===\"channelsLast\")[l,d,c,m,u]=e;else if(a===\"channelsFirst\")[l,u,d,c,m]=e;else throw new Error(`Unknown dataFormat ${a}`);let[h,,w,y,g]=t,[x,$,v]=Nu(r),[S,T,C]=Nu(n),A=an(w,S),P=an(y,T),O=an(g,C),{padInfo:U,outDepth:L,outHeight:j,outWidth:K}=nf(o,d,c,m,x,$,v,A,P,O),W=i?h*u:h,ee=[0,0,0,0,0];return a===\"channelsFirst\"?ee=[l,W,L,j,K]:a===\"channelsLast\"&&(ee=[l,L,j,K,W]),{batchSize:l,dataFormat:a,inDepth:d,inHeight:c,inWidth:m,inChannels:u,outDepth:L,outHeight:j,outWidth:K,outChannels:W,padInfo:U,strideDepth:x,strideHeight:$,strideWidth:v,filterDepth:w,filterHeight:y,filterWidth:g,effectiveFilterDepth:A,effectiveFilterHeight:P,effectiveFilterWidth:O,dilationDepth:S,dilationHeight:T,dilationWidth:C,inShape:e,outShape:ee,filterShape:t}},Gu=(e,t,r,n,o,i)=>{let a=i===\"channelsLast\",l=a?e[0].dims[3]:e[0].dims[1],d=!1,c=[64,1,1],m={x:r.map((v,S)=>S)},u=[Math.ceil(tf(m.x.map(v=>r[v]))/c[0]),1,1];se(\"verbose\",()=>`[conv3d_naive_webgpu] dispatch = ${u}`);let h=d?a&&l%4!==0?3:4:1,w=k.size(r),y=[{type:12,data:w},{type:12,data:n},{type:12,data:o},{type:12,data:t.strides},{type:12,data:t.dilations}];Ne(t,y),y.push(...V(e[0].dims,e[1].dims));let g=[\"rank\",\"rank\"],x=e.length===3;x&&(y.push(...V(e[2].dims)),g.push(\"rank\")),y.push(...V(r));let $=v=>{let S=[{name:\"output_size\",type:\"u32\"},{name:\"filter_dims\",type:\"u32\",length:n.length},{name:\"pads\",type:\"u32\",length:o.length},{name:\"strides\",type:\"u32\",length:t.strides.length},{name:\"dilations\",type:\"u32\",length:t.dilations.length}];We(t,S);let T=d?4:1,C=me(e[0].dataType),A=E(\"x\",e[0].dataType,e[0].dims.length,h===3?1:h),P=E(\"W\",e[1].dataType,e[1].dims.length,T),O=[A,P],U=M(\"result\",e[0].dataType,r.length,T),L=\"\";if(x){let W=E(\"bias\",e[2].dataType,e[2].dims.length,T);O.push(W),L+=`\n fn getBiasByOutputCoords(coords : array) -> ${d?`vec4<${C}>`:C} {\n return bias[${a?F(\"coords\",4,5):F(\"coords\",1,5)}${d?\"/ 4\":\"\"}];\n }`}let j=ze(h,C),K=Ve(t,j,C);return`\n ${L}\n fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {\n let aIndices = array(d0, d1, d2, d3, d4);\n return ${A.getByIndices(\"aIndices\")};\n }\n fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {\n let aIndices = array(d0, d1, d2, d3, d4);\n return ${P.getByIndices(\"aIndices\")};\n }\n ${v.registerUniforms(S).declareVariables(...O,U)}\n ${v.mainStart()}\n ${v.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let coords = ${U.offsetToIndices(\"global_idx\")};\n let batch = ${F(\"coords\",0,A.rank)};\n let d2 = ${a?F(\"coords\",A.rank-1,A.rank):F(\"coords\",1,A.rank)};\n let xFRCCorner = vec3(${a?F(\"coords\",1,A.rank):F(\"coords\",2,A.rank)},\n ${a?F(\"coords\",2,A.rank):F(\"coords\",3,A.rank)},\n ${a?F(\"coords\",3,A.rank):F(\"coords\",4,A.rank)}) * uniforms.strides - uniforms.pads;\n let xFCorner = xFRCCorner.x;\n let xRCorner = xFRCCorner.y;\n let xCCorner = xFRCCorner.z;\n let xShapeY = ${a?F(\"uniforms.x_shape\",1,A.rank):F(\"uniforms.x_shape\",2,A.rank)};\n let xShapeZ = ${a?F(\"uniforms.x_shape\",2,A.rank):F(\"uniforms.x_shape\",3,A.rank)};\n let xShapeW = ${a?F(\"uniforms.x_shape\",3,A.rank):F(\"uniforms.x_shape\",4,A.rank)};\n let xShapeU = ${a?F(\"uniforms.x_shape\",4,A.rank):F(\"uniforms.x_shape\",1,A.rank)};\n let inputDepthNearestVec4 = (xShapeU / 4) * 4;\n let inputDepthVec4Remainder = xShapeU % 4;\n\n var value = 0.0;\n for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) {\n let xF = xFCorner + wF * uniforms.dilations[0];\n if (xF < 0 || xF >= xShapeY) {\n continue;\n }\n\n for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) {\n let xR = xRCorner + wR * uniforms.dilations[1];\n if (xR < 0 || xR >= xShapeZ) {\n continue;\n }\n\n for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) {\n let xC = xCCorner + wC * uniforms.dilations[2];\n if (xC < 0 || xC >= xShapeW) {\n continue;\n }\n\n for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) {\n ${a?`let 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 `:`let xValues = vec4(\n getX(batch, d1, xF, xR, xC),\n getX(batch, d1 + 1, xF, xR, xC),\n getX(batch, d1 + 2, xF, xR, xC),\n getX(batch, d1 + 3, xF, xR, xC));\n `}\n let wValues = vec4(\n getW(d2, d1, wF, wR, wC),\n getW(d2, d1 + 1, wF, wR, wC),\n getW(d2, d1 + 2, wF, wR, wC),\n getW(d2, d1 + 3, wF, wR, wC));\n value += dot(xValues, wValues);\n }\n if (inputDepthVec4Remainder == 1) {\n ${a?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4)\n * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC)\n * getW(d2, inputDepthNearestVec4, wF, wR, wC);`}\n } else if (inputDepthVec4Remainder == 2) {\n ${a?`let xValues = vec2(\n getX(batch, xF, xR, xC, inputDepthNearestVec4),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1));\n `:`let xValues = vec2(\n getX(batch, inputDepthNearestVec4, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC));\n `}\n let wValues = vec2(\n getW(d2, inputDepthNearestVec4, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC));\n value += dot(xValues, wValues);\n } else if (inputDepthVec4Remainder == 3) {\n ${a?`let xValues = vec3(\n getX(batch, xF, xR, xC, inputDepthNearestVec4),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2));\n `:`let xValues = vec3(\n getX(batch, inputDepthNearestVec4, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC));\n `}\n let wValues = vec3(\n getW(d2, inputDepthNearestVec4, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC));\n value += dot(xValues, wValues);\n }\n }\n }\n }\n ${x?\"value = value + getBiasByOutputCoords(coords)\":\"\"};\n ${K}\n result[global_idx] = f32(value);\n }`};return{name:\"Conv3DNaive\",shaderCache:{hint:`${t.cacheKey};${a};${h};${x}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:u[0],y:u[1],z:u[2]},programUniforms:y}),getShaderSource:$}}});var Fu,qu,ju=R(()=>{\"use strict\";te();oe();ae();lt();Fu=(e,t,r,n)=>{let o=e.length>2,i=o?\"value += b[output_channel];\":\"\",a=e[0].dims,l=e[1].dims,d=t.format===\"NHWC\",c=d?r[3]:r[1],m=c/t.group,u=d&&m>=4?ye(c):1,h=k.size(r)/u,w=[{type:12,data:h},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:m}];Ne(t,w),w.push(...V(a,[l[0],l[1],l[2],l[3]/u]));let y=o?[\"rank\",\"rank\",\"rank\"]:[\"rank\",\"rank\"];w.push(...V([r[0],r[1],r[2],r[3]/u]));let g=x=>{let $=M(\"output\",e[0].dataType,r.length,u),v=me($.type.tensor),S=Ve(t,$.type.value,v),T=E(\"x\",e[0].dataType,a.length),C=E(\"w\",e[1].dataType,l.length,u),A=[T,C];o&&A.push(E(\"b\",e[2].dataType,e[2].dims,u));let P=[{name:\"output_size\",type:\"u32\"},{name:\"dilations\",type:\"u32\",length:t.dilations.length},{name:\"strides\",type:\"u32\",length:2},{name:\"pads\",type:\"u32\",length:2},{name:\"output_channels_per_group\",type:\"u32\"}];We(t,P);let O=d?`\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) {\n continue;\n }\n\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) {\n let input_channel = in_channel_offset + wInChannel;\n let xVal = ${T.get(\"batch\",\"xHeight\",\"xWidth\",\"input_channel\")};\n let wVal = ${C.get(\"wHeight\",\"wWidth\",\"wInChannel\",\"output_channel\")};\n value += xVal * wVal;\n }\n }\n }\n `:`\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {\n let input_channel = in_channel_offset + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) {\n continue;\n }\n\n let xVal = ${T.get(\"batch\",\"input_channel\",\"xHeight\",\"xWidth\")};\n let wVal = ${C.get(\"output_channel\",\"wInChannel\",\"wHeight\",\"wWidth\")};\n value += xVal * wVal;\n }\n }\n }\n `;return`\n ${x.registerUniforms(P).declareVariables(...A,$)}\n\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let outputIndices = ${$.offsetToIndices(\"global_idx\")};\n let batch: u32 = outputIndices[0];\n let output_channel: u32 = outputIndices[${d?3:1}];\n let xRCCorner: vec2 = vec2(outputIndices[${d?1:2}], outputIndices[${d?2:3}]) * uniforms.strides - uniforms.pads;\n let group_id: u32 = output_channel * ${u} / uniforms.output_channels_per_group;\n var in_channel_offset = group_id * uniforms.w_shape[${d?2:1}];\n\n var value: ${$.type.value} = ${$.type.value}(0);\n ${O}\n ${i}\n ${S}\n ${$.setByOffset(\"global_idx\",\"value\")}\n }`};return{name:\"GroupedConv\",shaderCache:{hint:`${t.cacheKey}_${u}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:w}),getShaderSource:g}},qu=(e,t,r,n)=>{let o=e.length>2,i=ye(r[3]),a=ye(r[2]),l=k.size(r)/i/a,d=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/i],c=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/i],m=[r[0],r[1],r[2],r[3]/i],u=[{type:12,data:l},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Ne(t,u),u.push(...V(d,c,m));let h=(a-1)*t.strides[1]+c[1],w=y=>{let g=M(\"output\",e[0].dataType,m.length,i),x=me(g.type.tensor),$=Ve(t,g.type.value,x),v=E(\"x\",e[0].dataType,d.length,i),S=E(\"w\",e[1].dataType,c.length,i),T=[v,S];o&&T.push(E(\"b\",e[2].dataType,e[2].dims,i));let C=o?\"value += b[output_channel];\":\"\",A=[{name:\"output_size\",type:\"u32\"},{name:\"strides\",type:\"i32\",length:2},{name:\"pads\",type:\"i32\",length:2}];return We(t,A),`\n ${y.registerUniforms(A).declareVariables(...T,g)}\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let width0 = uniforms.output_shape[3];\n let output_channel = global_idx % width0;\n var index1 = global_idx / width0;\n let width1 = uniforms.output_shape[2] / ${a}u;\n let col = (index1 % width1) * ${a}u;\n index1 = index1 / width1;\n let row = index1 % uniforms.output_shape[1];\n let batch = index1 / uniforms.output_shape[1];\n\n let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads;\n\n var x_vals: array<${v.type.value}, ${h}>;\n var values: array<${g.type.value}, ${a}>;\n let input_channel = output_channel;\n // Use constant instead of uniform can give better performance for w's height/width.\n for (var w_height: u32 = 0u; w_height < ${c[0]}; w_height++) {\n let x_height = x_corner.x + i32(w_height);\n if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {\n for (var i = 0; i < ${h}; i++) {\n let x_width = x_corner.y + i;\n if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {\n x_vals[i] = ${v.get(\"batch\",\"u32(x_height)\",\"u32(x_width)\",\"input_channel\")};\n } else {\n x_vals[i] = ${v.type.value}(0);\n }\n }\n for (var w_width: u32 = 0u; w_width < ${c[1]}; w_width++) {\n let w_val = ${S.get(\"w_height\",\"w_width\",\"0\",\"output_channel\")};\n for (var i = 0u; i < ${a}u; i++) {\n values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);\n }\n }\n }\n }\n\n for (var i = 0u; i < ${a}u; i++) {\n var value = values[i];\n ${C}\n ${$}\n ${g.set(\"batch\",\"row\",\"col + i\",\"output_channel\",\"value\")};\n }\n }`};return{name:\"GroupedConv-Vectorize\",shaderCache:{hint:`${t.cacheKey};${i};${a};${h};${c[0]};${c[1]}`,inputDependencies:o?[\"rank\",\"rank\",\"type\"]:[\"rank\",\"rank\"]},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:w}}});var of,vo,af,$o,xo,Ku,sf,uf,So,Yu=R(()=>{\"use strict\";oe();Vu();Hu();ir();ju();lt();on();ut();of=(e,t,r,n,o,i)=>{let a=e[0],l=e.slice(i?1:2,i?3:4),d=l.length,c=t[0],u=t.slice(2).map((y,g)=>y+(y-1)*(r[g]-1)),w=l.map((y,g)=>y+n[g]+n[g+d]).map((y,g)=>Math.floor((y-u[g]+o[g])/o[g]));return w.splice(0,0,a),w.splice(i?3:1,0,c),w},vo=[2,3,1,0],af=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error(\"Conv requires 2 or 3 inputs\");if(e[0].dims.length>5)throw new Error(\"greater than 5D is not supported\");if(e[0].dims.length!==e[1].dims.length)throw new Error(\"filter does not have same dimension as input\");let r=e[0].dims[t.format===\"NHWC\"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(r!==n)throw new Error(\"FILTER_IN_CHANNEL should be equal to DATA_CHANNEL\");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error(\"invalid bias\");let o=e[0].dims.length-2;if(t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error(\"invalid kernel shape\")},$o=(e,t)=>{let r=e.kernelShape.slice();r.length{let t=en(e),r=e.format,n=[\"NOTSET\",\"VALID\",\"SAME_UPPER\",\"SAME_LOWER\"][e.auto_pad],o=e.dilations,i=e.group,a=e.kernel_shape,l=e.pads,d=e.strides,c=e.w_is_const();return{autoPad:n,format:r,dilations:o,group:i,kernelShape:a,pads:l,strides:d,wIsConst:c,...t,cacheKey:`${e.format};${t.activation};`}},Ku=(e,t,r,n)=>{let o=r.format===\"NHWC\",i=of(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,o);if(r.group!==1){let A=[t[0]];if(o){let O=e.kernelCustomData.wT??e.compute(Pe(t[1],vo),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=O),A.push(O)}else A.push(t[1]);t.length===3&&A.push(t[2]),!e.adapterInfo.isArchitecture(\"ampere\")&&o&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(qu(A,r,i,n),{inputs:A}):e.compute(Fu(A,r,i,n),{inputs:A});return}let a=t.length===3,l=t[0].dims[o?1:2],d=t[0].dims[o?2:3],c=t[0].dims[o?3:1],m=t[1].dims[2],u=t[1].dims[3],h=i[o?1:2],w=i[o?2:3],y=i[o?3:1],g=o&&m===l&&u===d&&r.pads[0]===0&&r.pads[1]===0;if(g||m===1&&u===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let A=i[0],P,O,U,L=[];if(o){let W=e.kernelCustomData.wT??e.compute(Pe(t[1],vo),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=W),g){let ee=l*d*c;P=t[0].reshape([1,A,ee]),O=W.reshape([1,ee,y]),U=[1,A,y]}else P=t[0].reshape([A,l*d,c]),O=W.reshape([1,c,y]),U=[A,h*w,y];L.push(P),L.push(O)}else P=t[0].reshape([A,c,l*d]),O=t[1].reshape([1,y,c]),U=[A,y,h*w],L.push(O),L.push(P);a&&L.push(t[2]);let j=U[2],K=L[0].dims[L[0].dims.length-1];j<8&&K<8?e.compute(nn(L,r,i,U,o,n),{inputs:L}):e.compute(or(L,r,i,U,o,n),{inputs:L});return}let x=!0,$=e.kernelCustomData.wT??e.compute(Pe(t[1],vo),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=$);let v=[t[0],$];a&&v.push(t[2]);let S=o?h*w:y,T=o?y:h*w,C=m*u*c;e.compute(Uu(v,r,i,S,T,C,a,x,n),{inputs:v})},sf=(e,t)=>{let r=t.format===\"NHWC\",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=[0,t.pads[0],0,t.pads[1]],i=[1].concat(t.strides),a=[1].concat(t.dilations),l=[1].concat(t.kernelShape),d=$o({...t,pads:o,strides:i,dilations:a,kernelShape:l},n);Ku(e,n,d,c=>r?[c[0],c[2],c[3]]:[c[0],c[1],c[3]])},uf=(e,t,r)=>{let n=r.format===\"NHWC\"?\"channelsLast\":\"channelsFirst\",o=$o(r,t),i=r.autoPad===\"NOTSET\"?r.pads:r.autoPad,a=Lu(t[0].dims,t[1].dims,r.strides,r.dilations,i,!1,n);e.compute(Gu(t,o,a.outShape,[a.filterDepth,a.filterHeight,a.filterWidth],[a.padInfo.front,a.padInfo.top,a.padInfo.left],n))},So=(e,t)=>{if(af(e.inputs,t),e.inputs[0].dims.length===3)sf(e,t);else if(e.inputs[0].dims.length===5)uf(e,e.inputs,t);else{let r=$o(t,e.inputs);Ku(e,e.inputs,r)}}});var lf,Zu,Xu=R(()=>{\"use strict\";te();je();ae();lt();er();_o();ir();lf=(e,t=!1,r,n,o=4)=>{let i=$=>{switch($){case 1:return\"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];\";case 4:return`\n let coord1 = vec4(coordX, coordY, col + 1, rowInner);\n let coord2 = vec4(coordX, coordY, col + 2, rowInner);\n let coord3 = vec4(coordX, coordY, col + 3, rowInner);\n let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];\n let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))];\n let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))];\n let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))];\n return ${n}(v0, v1, v2, v3);\n `;default:throw new Error(`innerElementSize ${$} is not supported.`)}},a=e?`\n let coord = vec4(batch, iXR, iXC, xCh);\n `:`\n let coord = vec4(batch, xCh, iXR, iXC);\n `,l=e?`\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n `:`\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n `,d=e?\"i32(uniforms.x_shape[1])\":\"i32(uniforms.x_shape[2])\",c=e?\"i32(uniforms.x_shape[2])\":\"i32(uniforms.x_shape[3])\",m=e?\"row\":\"col\",u=e?\"col\":\"row\",h=`\n let inChannels = ${e?\"i32(uniforms.x_shape[3])\":\"i32(uniforms.x_shape[1])\"};\n let outWidth = ${e?\"i32(uniforms.result_shape[2])\":\"i32(uniforms.result_shape[3])\"};\n let outRow = ${m} / outWidth;\n let outCol = ${m} % outWidth;\n\n let WRow = ${u} / (uniforms.filter_dims[1] * inChannels);\n let WCol = ${u} / inChannels % uniforms.filter_dims[1];\n let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]);\n let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]);\n if (xR < 0.0 || xR >= f32(${d}) || fract(xR) > 0.0) {\n return ${n}(0.0);\n }\n if (xC < 0.0 || xC >= f32(${c}) || fract(xC) > 0.0) {\n return ${n}(0.0);\n }\n let iXR = i32(xR);\n let iXC = i32(xC);\n let xCh = ${u} % inChannels;\n ${a}\n return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${o}];`,w=e?`\n let col = colIn * ${o};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${h}\n }\n return ${n}(0.0);`:`\n let col = colIn * ${o};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${h}\n }\n return ${n}(0.0);`,y=`\n let col = colIn * ${o};\n let inChannels = ${e?\"i32(uniforms.x_shape[3])\":\"i32(uniforms.x_shape[1])\"};\n let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels);\n let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1];\n if (${e?\"row < uniforms.dim_inner && col < uniforms.dim_b_outer\":\"row < uniforms.dim_inner && col < uniforms.dim_a_outer\"} && coordX >= 0 && coordY >= 0) {\n let rowInner = row % inChannels;\n let coord = vec4(coordX, coordY, col, rowInner);\n ${i(o)}\n }\n return ${n}(0.0);\n `,g=Ve(r,n);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} {\n ${e?w:y}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} {\n ${e?y:w}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) {\n let col = colIn * ${o};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueInput;\n let outWidth = ${e?\"i32(uniforms.result_shape[2])\":\"i32(uniforms.result_shape[3])\"};\n ${l}\n ${tn(t)}\n ${g}\n result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${o}] = value;\n }\n }`},Zu=(e,t,r,n,o,i,a,l)=>{let d=t.format===\"NHWC\",c=d?e[0].dims[3]:e[0].dims[1],m=r[0],u=d?r[2]:r[3],h=d?r[1]:r[2],w=d?r[3]:r[1],y=d&&c%4===0&&c%3&&w%4===0,g=d?w:u*h,x=d?u*h:w,$=[8,8,1],v=n<=8?[4,1,1]:[4,4,1],S=[Math.ceil(g/$[0]/v[0]),Math.ceil(x/$[1]/v[1]),Math.ceil(m/$[2]/v[2])];se(\"verbose\",()=>`[conv_backprop_mm_webgpu] dispatch = ${S}`);let T=y?4:1,C=Math.max($[0]*T,$[1]),A=y?4:1,P=[t.kernelShape[d?1:2],t.kernelShape[d?2:3]],O=[P[0]+(t.dilations[0]<=1?0:(P[0]-1)*(t.dilations[0]-1)),P[1]+(t.dilations[1]<=1?0:(P[1]-1)*(t.dilations[1]-1))],U=[O[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),O[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],L=[{type:6,data:n},{type:6,data:o},{type:6,data:i},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:P},{type:6,data:U}];Ne(t,L),L.push(...V(e[0].dims,e[1].dims));let j=[\"rank\",\"rank\"];a&&(L.push(...V(e[2].dims)),j.push(\"rank\")),L.push(...V(r));let K=W=>{let ee=E(\"x\",e[0].dataType,e[0].dims.length,A),ue=E(\"w\",e[1].dataType,e[1].dims.length,1),Z=M(\"result\",e[0].dataType,r.length,A),J=[ee,ue],Q=\"\";if(a){let Ae=E(\"bias\",e[2].dataType,e[2].dims.length,A);J.push(Ae),Q+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${Ae.type.value} {\n return bias[coords.${d?\"w\":\"y\"}${y?\"/ 4\":\"\"}];\n }`}let ne=[{name:\"dim_a_outer\",type:\"i32\"},{name:\"dim_b_outer\",type:\"i32\"},{name:\"dim_inner\",type:\"i32\"},{name:\"strides\",type:\"i32\",length:2},{name:\"dilations\",type:\"i32\",length:2},{name:\"filter_dims\",type:\"i32\",length:P.length},{name:\"pads\",type:\"i32\",length:U.length}];We(t,ne);let we=me(e[0].dataType,1);if(we!==\"f16\"&&we!==\"f32\")throw new Error(`elemType ${we} is not supported.`);return`\n ${rn(\"uniforms.result_strides\")}\n ${W.registerUniforms(ne).declareVariables(...J,Z)};\n ${Q}\n ${lf(d,a,t,ee.type.value,T)}\n ${y?rr(v,$,we,void 0,!d,C):nr(v,$,we,void 0,!d,C,!1,void 0,l)}`};return{name:\"Conv2DTransposeMatMul\",shaderCache:{hint:`${t.cacheKey};${v};${$};${y}`,inputDependencies:j},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:S[0],y:S[1],z:S[2]},programUniforms:L}),getShaderSource:K}}});var df,To,Qu=R(()=>{\"use strict\";te();je();oe();ae();df=(e,t,r,n,o,i=!1,a,l,d=!1)=>{let c=d?1:2,m=d?2:3,u=d?3:1,h=i?2:1,w=`\n fn setOutputAtIndex(flatIndex : u32, value : ${i?`vec4<${a}>`:a}) {\n result[flatIndex] = ${i?`vec4<${a}>`:a}(value);\n }`;n&&(w+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${i?`vec4<${a}>`:a} {\n return bias[coords.${d?\"w\":\"y\"}${i?\"/ 4\":\"\"}];\n }`);let y=i?4:1,g=E(\"W\",t[1].dataType,t[1].dims.length,y),x=E(\"Dy\",t[0].dataType,t[0].dims.length,y),$=[x,g];n&&$.push(E(\"bias\",t[2].dataType,[r[u]].length,y));let v=M(\"result\",t[0].dataType,r.length,y),S=`{\n let batch: u32 = ${o?\"global_id.z\":\"workgroup_id.z\"} / uniforms.result_shape[1];\n let r = ${o?\"global_id.z\":\"workgroup_id.z\"} % uniforms.result_shape[1];\n let c = ${o?\"global_id.y\":\"workgroup_id.y\"} * ${h};\n let d1: u32 = ${o?\"global_id.x\":\"workgroup_id.x\"} * 4;\n\n let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads);\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 var dotProd: array, ${h}>;\n for (var i = 0; i < ${h}; i++) {\n dotProd[i] = vec4<${a}>(0.0);\n }\n for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) {\n var dyR = (${a}(dyCorner.x) + ${a}(wR)) / ${a}(uniforms.strides.x);\n let wRPerm = uniforms.filter_dims[0] - 1 - wR;\n if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[1]) ||\n fract(dyR) > 0.0 || wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) {\n let dyC = (${a}(dyCorner.y) + ${a}(wC)) / ${a}(uniforms.strides.y);\n let dyC2 = (${a}(dyCorner.y) + 1.0 + ${a}(wC)) / ${a}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims[1] - 1 - wC;\n if (wCPerm < 0) {\n continue;\n }\n var bDyCVal = true;\n var bDyCVal2 = true;\n if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[2]) ||\n fract(dyC) > 0.0) {\n bDyCVal = false;\n }\n if (dyC2 < 0.0 || dyC2 >= ${a}(uniforms.Dy_shape[2]) ||\n fract(dyC2) > 0.0) {\n bDyCVal2 = false;\n }\n\n let idyC: u32 = u32(dyC);\n let idyC2: u32 = u32(dyC2);\n if (bDyCVal && bDyCVal2) {\n let d2Length = uniforms.Dy_shape[3];\n for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1\",\"d2\")};\n let wValue1 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1 + 1\",\"d2\")};\n let wValue2 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1 + 2\",\"d2\")};\n let wValue3 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1 + 3\",\"d2\")};\n\n var xValue = ${x.get(\"batch\",\"idyR\",\"idyC\",\"d2\")};\n let tmpval = vec4<${a}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n\n xValue = ${x.get(\"batch\",\"idyR\",\"idyC2\",\"d2\")};\n\n dotProd[1] = dotProd[1] + vec4<${a}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n }\n } else if (bDyCVal) {\n let d2Length = uniforms.Dy_shape[${u}];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1\",\"d2\")};\n let wValue1 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1 + 1\",\"d2\")};\n let wValue2 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1 + 2\",\"d2\")};\n let wValue3 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1 + 3\",\"d2\")};\n\n var xValue = ${x.get(\"batch\",\"idyR\",\"idyC\",\"d2\")};\n let tmpval = vec4<${a}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n }\n } else if (bDyCVal2) {\n let d2Length = uniforms.Dy_shape[3];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1\",\"d2\")};\n let wValue1 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1 + 1\",\"d2\")};\n let wValue2 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1 + 2\",\"d2\")};\n let wValue3 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1 + 3\",\"d2\")};\n\n var xValue = ${x.get(\"batch\",\"idyR\",\"idyC2\",\"d2\")};\n let tmpval = vec4<${a}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[1] = dotProd[1] + tmpval;\n }\n }\n }\n }\n\n for (var i: u32 = 0; i < ${h}; i = i + 1) {\n let value = dotProd[i] + ${n?\"bias[c+i]\":`vec4<${a}>(0.0)`};\n ${v.set(\"batch\",\"r\",\"c + i\",\"d1\",\"value\")};\n }\n }`,T=`\n let outputIndices = ${v.offsetToIndices(\"global_idx\")};\n let batch = ${v.indicesGet(\"outputIndices\",0)};\n let d1 = ${v.indicesGet(\"outputIndices\",u)};\n let r = ${v.indicesGet(\"outputIndices\",c)};\n let c = ${v.indicesGet(\"outputIndices\",m)};\n let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads;\n let dyRCorner = dyCorner.x;\n let dyCCorner = dyCorner.y;\n let groupId = d1 / uniforms.output_channels_per_group;\n let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;\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 var dotProd = ${a}(0.0);\n for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {\n if (wR % uniforms.dilations.x != 0) {\n continue;\n }\n let dyR = (${a}(dyRCorner) + ${a}(wR)) / ${a}(uniforms.strides[0]);\n let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;\n if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[${c}]) || fract(dyR) > 0.0 ||\n wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {\n if (wC % uniforms.dilations.y != 0) {\n continue;\n }\n let dyC = (${a}(dyCCorner) + ${a}(wC)) / ${a}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;\n if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[${m}]) ||\n fract(dyC) > 0.0 || wCPerm < 0) {\n continue;\n }\n let idyC: u32 = u32(dyC);\n var inputChannel = groupId * uniforms.input_channels_per_group;\n for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) {\n let xValue = ${d?x.get(\"batch\",\"idyR\",\"idyC\",\"inputChannel\"):x.get(\"batch\",\"inputChannel\",\"idyR\",\"idyC\")};\n let wValue = ${g.get(\"inputChannel\",\"wOutChannel\",\"u32(wRPerm)\",\"u32(wCPerm)\")};\n dotProd = dotProd + xValue * wValue;\n inputChannel = inputChannel + 1;\n }\n }\n }\n let value = dotProd + ${n?\"bias[d1]\":`${a}(0.0)`};\n ${v.setByOffset(\"global_idx\",\"value\")};\n `;return`\n ${e.registerUniforms(l).declareVariables(...$,v)}\n ${w}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")};\n ${i?S:T}}`},To=(e,t,r)=>{let n=e.length>2,o=t.outputShape,i=k.size(o),a=[Math.ceil(i/64),1,1];se(\"verbose\",()=>`[conv2d_backprop_webgpu] dispatch = ${a}`);let l=t.format===\"NHWC\",d=[\"rank\",\"rank\"],c=[t.strides[0],t.strides[1]],m=[t.kernelShape[l?1:2],t.kernelShape[l?2:3]],u=[t.dilations[0],t.dilations[1]],h=[m[0]+(t.dilations[0]<=1?0:(t.kernelShape[l?1:2]-1)*(t.dilations[0]-1)),m[1]+(t.dilations[1]<=1?0:(t.kernelShape[l?2:3]-1)*(t.dilations[1]-1))],w=[h[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),h[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],y=!1,g=t.group,x=e[1].dims,$=x[0]/g,v=x[1],S=[{type:12,data:i},{type:12,data:c},{type:12,data:m},{type:12,data:u},{type:12,data:h},{type:6,data:w},{type:12,data:$},{type:12,data:v},...V(e[0].dims,e[1].dims)];n&&(S.push(...V(e[2].dims)),d.push(\"rank\")),S.push(...V(o));let T=a[1]===1&&a[2]===1,C=A=>{let P=[{name:\"output_size\",type:\"u32\"},{name:\"strides\",type:\"u32\",length:c.length},{name:\"filter_dims\",type:\"u32\",length:m.length},{name:\"dilations\",type:\"u32\",length:m.length},{name:\"effective_filter_dims\",type:\"u32\",length:h.length},{name:\"pads\",type:\"i32\",length:w.length},{name:\"input_channels_per_group\",type:\"u32\"},{name:\"output_channels_per_group\",type:\"u32\"}],O=me(e[0].dataType);return`${df(A,e,o,n,T,y,O,P,l)}`};return{name:\"ConvTranspose2D\",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:d},getRunData:()=>({dispatchGroup:{x:a[0],y:a[1],z:a[2]},outputs:[{dims:r?r(o):o,dataType:e[0].dataType}],programUniforms:S}),getShaderSource:C}}});var cf,pf,mf,Ju,el,ff,hf,gf,bf,tl,rl=R(()=>{\"use strict\";Xu();Qu();lt();ut();cf=(e,t,r,n,o,i)=>(e-1)*t+r+(n-1)*o+1-i,pf=(e,t,r,n,o)=>{let i=Math.floor(e/2);t===\"SAME_UPPER\"?(r[n]=i,r[o]=e-i):t===\"SAME_LOWER\"&&(r[n]=e-i,r[o]=i)},mf=(e,t,r,n,o,i,a,l,d,c)=>{let m=e.length-2,u=c.length===0;d.length{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((u,h)=>u*h,1)===0){r.length=0;for(let u=2;uu+h,0)===0){let u=t[0].dims.length-2;d=new Array(u).fill(1)}let c=e.strides.slice();if(c.reduce((u,h)=>u+h,0)===0){let u=t[0].dims.length-2;c=new Array(u).fill(1)}mf(l,r,d,e.autoPad,e.group,o,c,n,a,i);let m=Object.assign({},e);return Object.assign(m,{kernelShape:r,pads:o,outputPadding:a,outputShape:i,dilations:d,strides:c}),m},el=e=>{let t=en(e),r=e.format,n=[\"NOTSET\",\"VALID\",\"SAME_UPPER\",\"SAME_LOWER\"][typeof e.autoPad>\"u\"?0:e.autoPad],o=e.dilations,i=e.group,a=e.kernelShape,l=e.pads,d=e.strides,c=e.wIsConst(),m=e.outputPadding,u=e.outputShape;return{autoPad:n,format:r,dilations:o,group:i,kernelShape:a,outputPadding:m,outputShape:u,pads:l,strides:d,wIsConst:c,...t,cacheKey:`${e.format};${t.activation};`}},ff=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error(\"Conv requires 2 or 3 inputs\");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error(\"currently only support 2-dimensional conv\");if(e[0].dims.length!==e[1].dims.length)throw new Error(\"filter does not have same dimension as input\");let r=e[0].dims[t.format===\"NHWC\"?e[0].dims.length-1:1],n=e[1].dims[0];if(r!==n)throw new Error(\"FILTER_IN_CHANNEL should be equal to DATA_CHANNEL\");let o=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error(\"invalid bias\");let i=e[0].dims.length-2;if(t.dilations.reduce((m,u)=>m+u,0)>0&&t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.reduce((m,u)=>m+u,0)>0&&t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.reduce((m,u)=>m+u,0)>0&&t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.outputPadding.length!==i&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${i}D`);if(t.kernelShape.reduce((m,u)=>m+u,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error(\"invalid kernel shape\");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error(\"invalid output shape\")},hf=[2,3,1,0],gf=(e,t,r)=>{let n=Ju(r,t),o=r.format===\"NHWC\",i=n.outputShape,a=i[o?3:1],l=t[0].dims[o?3:1];if(n.group!==1||a===1&&l===1){e.compute(To(t,n));return}let d=i[o?1:2],c=i[o?2:3],m=t[1].dims[2],u=t[1].dims[3],h=o?d*c:a,w=o?a:d*c,y=m*u*l,g=!0,x=e.kernelCustomData.wT??e.compute(Pe(t[1],hf),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=x);let $=[t[0],x],v=t.length===3;v&&(!o&&t[2].dims.length===1?$.push(t[2].reshape([t[2].dims[0],1,1])):$.push(t[2])),e.compute(Zu($,n,i,h,w,y,v,g),{inputs:$})},bf=(e,t)=>{let r=t.format===\"NHWC\",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=t.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let i=t.dilations;(i.length===0||i[0]===0)&&(i=[1]);let a=t.strides;(a.length===0||a[0]===0)&&(a=[1]);let l=t.pads;l.length===0&&(l=[0,0]),l=[0,l[0],0,l[1]],a=[1].concat(a),i=[1].concat(i),o=[1].concat(o);let d=Ju({...t,pads:l,strides:a,dilations:i,kernelShape:o},n);e.compute(To(n,d,c=>r?[c[0],c[2],c[3]]:[c[0],c[1],c[3]]))},tl=(e,t)=>{ff(e.inputs,t),e.inputs[0].dims.length===3?bf(e,t):gf(e,e.inputs,t)}});var yf,nl,ol,il=R(()=>{\"use strict\";te();oe();Ie();ae();yf=(e,t,r,n)=>{let o=k.size(t),i=t.length,a=E(\"input\",e,i),l=M(\"output\",e,i),d=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),c=k.normalizeAxis(d,i),m=u=>{let h=` i32(${a.indicesGet(\"inputIndices\",\"uniforms.axis\")}) `,w=F(\"uniforms.input_shape\",\"uniforms.axis\",i),y=n.reverse?h+(n.exclusive?\" + 1\":\"\"):\"0\",g=n.reverse?w:h+(n.exclusive?\"\":\" + 1\");return`\n ${u.registerUniform(\"outputSize\",\"u32\").registerUniform(\"axis\",\"u32\").declareVariables(a,l)}\n ${u.mainStart()}\n ${u.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n var inputIndices = ${l.offsetToIndices(\"global_idx\")};\n var sum = ${l.type.value}(0);\n let first : i32 = ${y};\n let last : i32 = ${g};\n for (var i : i32 = first; i < last; i++) {\n ${a.indicesSet(\"inputIndices\",\"uniforms.axis\",\"u32(i)\")};\n sum = sum + ${a.getByIndices(\"inputIndices\")};\n }\n ${l.setByOffset(\"global_idx\",\"sum\")};\n }`};return{name:\"CumSum\",shaderCache:{hint:n.cacheKey,inputDependencies:[\"rank\"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:c},...V(t,t)]}),getShaderSource:m}},nl=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,o=e.inputs[1];e.compute(yf(n,r,o,t),{inputs:[0]})},ol=e=>{let t=e.exclusive===1,r=e.reverse===1;return re({exclusive:t,reverse:r})}});var wf,_f,vf,al,sl,ul=R(()=>{\"use strict\";te();oe();Ie();ae();wf=e=>{if(!e||e.length!==1)throw new Error(\"DepthToSpace requires 1 input.\");if(e[0].dims.length!==4)throw new Error(\"DepthToSpace requires 4D input.\")},_f=(e,t,r,n)=>{let o=[];o.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} {\n var a: ${r.type.indices};`);for(let i=0;i{let r,n,o,i,a,l,d=t.format===\"NHWC\",c=t.blocksize,m=t.mode===\"DCR\";d?([r,n,o,i]=e.dims,a=m?[r,n,o,c,c,i/c**2]:[r,n,o,i/c**2,c,c],l=m?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,o,i]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],a=m?[r,c,c,i/c**2,n,o]:[r,i/c**2,c,c,n,o],l=m?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let u=e.reshape(a),h=u.dims.length,w=e.dataType,y=E(\"a\",w,h),g=M(\"output\",w,h),x=$=>`\n ${$.registerUniform(\"output_size\",\"u32\").declareVariables(y,g)}\n\n ${_f(l,h,y,g)}\n\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let indices = ${g.offsetToIndices(\"global_idx\")};\n let aIndices = perm(indices);\n\n ${g.setByOffset(\"global_idx\",y.getByIndices(\"aIndices\"))}\n }`;return{name:\"DepthToSpace\",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:[\"rank\"]},getRunData:$=>{let v=d?[r,n*c,o*c,i/c**2]:[r,i/c**2,n*c,o*c],S=k.size(v),T=u.dims,C=k.sortBasedOnPerm(T,l);return{outputs:[{dims:v,dataType:$[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...V(T,C)]}},getShaderSource:x}},al=(e,t)=>{wf(e.inputs),e.compute(vf(e.inputs[0],t))},sl=e=>re({blocksize:e.blocksize,mode:e.mode,format:e.format})});var Io,sn,ll,$f,xf,Co,Ao,dl,Sf,cl,pl,ml=R(()=>{\"use strict\";te();oe();Ie();ae();Io=\"[a-zA-Z]|\\\\.\\\\.\\\\.\",sn=\"(\"+Io+\")+\",ll=\"^\"+sn+\"$\",$f=\"(\"+sn+\",)*\"+sn,xf=\"^\"+$f+\"$\",Co=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,r){let n=this.symbolToIndices.get(t);n===void 0?n=[r]:n.push(r),this.symbolToIndices.set(t,n)}},Ao=class{constructor(t,r){this.equation=r;this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[n,o]=r.includes(\"->\")?r.split(\"->\",2):[r,\"\"];if(!n.match(RegExp(xf)))throw new Error(\"Invalid LHS term\");if(n.split(\",\").forEach((l,d)=>{let c=t[d].dims.slice();if(!l.match(RegExp(ll)))throw new Error(\"Invalid LHS term\");let m=this.processTerm(l,!0,c,d);this.lhs.push(m)}),o===\"\")o+=[...this.symbolToInfo.entries()].filter(([l,d])=>d.count===1||l===\"...\").map(([l])=>l).join(\"\");else if(!o.match(RegExp(sn)))throw new Error(\"Invalid RHS\");o.match(RegExp(Io,\"g\"))?.forEach(l=>{if(l===\"...\")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let d=this.symbolToInfo.get(l);if(d===void 0)throw new Error(\"Invalid RHS symbol\");this.outputDims.push(d.dimValue)}}),this.rhs=this.processTerm(o,!1,this.outputDims)}addSymbol(t,r,n){let o=this.symbolToInfo.get(t);if(o!==void 0){if(o.dimValue!==r&&o.count!==1)throw new Error(\"Dimension mismatch\");o.count++,o.inputIndices.push(n)}else o={count:1,dimValue:r,inputIndices:[n]};this.symbolToInfo.set(t,o)}processTerm(t,r,n,o=-1){let i=n.length,a=!1,l=[],d=0;if(!t.match(RegExp(ll))&&!r&&t!==\"\")throw new Error(\"Invalid LHS term\");let c=t.match(RegExp(Io,\"g\")),m=new Co(o);return c?.forEach((u,h)=>{if(u===\"...\"){if(a)throw new Error(\"Only one ellipsis is allowed per input term\");a=!0;let w=i-c.length+1;if(w<0)throw new Error(\"Ellipsis out of bounds\");if(l=n.slice(d,d+w),this.hasEllipsis){if(this.ellipsisDims.length!==l.length||this.ellipsisDims.toString()!==l.toString())throw new Error(\"Ellipsis dimensions mismatch\")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=l;else throw new Error(\"Ellipsis must be specified in the LHS\");for(let y=0;ye+\"_max\",Sf=(e,t,r,n)=>{let i=e.map(m=>m.length).map((m,u)=>E(`input${u}`,t,m)),a=k.size(n),l=M(\"output\",t,n.length),d=[...r.symbolToInfo.keys()].filter(m=>!r.rhs.symbolToIndices.has(m)),c=m=>{let u=[],h=\"var prod = 1.0;\",w=\"var sum = 0.0;\",y=\"sum += prod;\",g=[],x=[],$=[],v=[],S=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((C,A)=>{if(r.rhs.symbolToIndices.has(A)){let P=r.rhs.symbolToIndices.get(A)?.[0];P!==void 0&&r.lhs.forEach((O,U)=>{if(C.inputIndices.includes(U)){let L=O.symbolToIndices.get(A);if(L===void 0)throw new Error(\"Invalid symbol error\");L.forEach(j=>{u.push(`${i[U].indicesSet(`input${U}Indices`,j,l.indicesGet(\"outputIndices\",P))}`)})}})}else r.lhs.forEach((P,O)=>{if(C.inputIndices.includes(O)){let U=P.symbolToIndices.get(A);if(U===void 0)throw new Error(\"Invalid symbol error\");U.forEach(L=>{g.push(`${i[O].indicesSet(`input${O}Indices`,L,`${A}`)}`)}),v.push(`prod *= ${i[O].getByIndices(`input${O}Indices`)};`)}}),x.push(`for(var ${A}: u32 = 0; ${A} < uniforms.${dl(A)}; ${A}++) {`),$.push(\"}\")});let T=S?[...u,`let sum = ${i.map((C,A)=>C.getByIndices(`input${A}Indices`)).join(\" * \")};`]:[...u,w,...x,...g,h,...v,y,...$];return`\n ${m.registerUniforms(d.map(C=>({name:`${dl(C)}`,type:\"u32\"}))).registerUniform(\"outputSize\",\"u32\").declareVariables(...i,l)}\n\n ${m.mainStart()}\n ${m.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n var outputIndices = ${l.offsetToIndices(\"global_idx\")};\n ${i.map((C,A)=>`var input${A}Indices: ${i[A].type.indices};`).join(`\n`)}\n ${T.join(`\n`)};\n ${l.setByOffset(\"global_idx\",\"sum\")};\n }`};return{name:\"Einsum\",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>\"rank\")},getRunData:()=>{let m=d.filter(h=>r.symbolToInfo.has(h)).map(h=>({type:12,data:r.symbolToInfo.get(h)?.dimValue||0}));m.push({type:12,data:a});let u=e.map((h,w)=>[...V(h)]).reduce((h,w)=>h.concat(w),m);return u.push(...V(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:u}},getShaderSource:c}},cl=(e,t)=>{let r=new Ao(e.inputs,t.equation),n=r.outputDims,o=e.inputs.map((i,a)=>i.dims);e.compute(Sf(o,e.inputs[0].dataType,r,n))},pl=e=>{let t=e.equation.replace(/\\s+/g,\"\");return re({equation:t})}});var Tf,fl,If,Cf,hl,gl=R(()=>{\"use strict\";te();oe();ae();Tf=e=>{if(!e||e.length!==2)throw new Error(\"Expand requires 2 input.\");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=r.length{let r=e.length-t.length,n=[];for(let o=0;oe.length>t.length?fl(e,t):fl(t,e),Cf=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=If(t,r),o=e[0].dataType,i=o===9?4:1,a=Math.ceil(k.size(n)/i),l=c=>{let m=E(\"input\",o,t.length,i),u=M(\"output\",o,n.length,i),h;if(o===9){let w=(y,g,x=\"\")=>`\n let outputIndices${g} = ${u.offsetToIndices(`outputOffset + ${g}u`)};\n let offset${g} = ${m.broadcastedIndicesToOffset(`outputIndices${g}`,u)};\n let index${g} = offset${g} / 4u;\n let component${g} = offset${g} % 4u;\n ${y}[${g}] = ${x}(${m.getByOffset(`index${g}`)}[component${g}]);\n `;h=`\n let outputOffset = global_idx * ${i};\n var data = vec4(0);\n ${w(\"data\",0,\"u32\")}\n ${w(\"data\",1,\"u32\")}\n ${w(\"data\",2,\"u32\")}\n ${w(\"data\",3,\"u32\")}\n ${u.setByOffset(\"global_idx\",\"data\")}\n }`}else h=`\n let outputIndices = ${u.offsetToIndices(\"global_idx\")};\n let inputOffset = ${m.broadcastedIndicesToOffset(\"outputIndices\",u)};\n ${u.setByOffset(\"global_idx\",m.getByOffset(\"inputOffset\"))}\n }`;return`\n ${c.registerUniform(\"vec_size\",\"u32\").declareVariables(m,u)}\n ${c.mainStart()}\n ${c.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.vec_size\")}\n ${h}`},d=[{type:12,data:a},...V(t,n)];return{name:\"Expand\",shaderCache:{hint:`${n.length}`,inputDependencies:[\"rank\"]},getShaderSource:l,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:d})}},hl=e=>{Tf(e.inputs),e.compute(Cf(e.inputs),{inputs:[0]})}});var Af,bl,yl=R(()=>{\"use strict\";te();oe();ae();Jr();Af=e=>{let t=e[0].dataType,r=k.size(e[0].dims),n=k.size(e[1].dims),o=n%4===0,i=a=>{let l=E(\"x\",t,[1],4),d=E(\"bias\",t,[1],4),c=M(\"y\",t,[1],4),m=[{name:\"output_vec_size\",type:\"u32\"},{name:\"bias_size\",type:\"u32\"}],u=w=>`\n let bias${w}_offset: u32 = (global_idx * 4 + ${w}) % uniforms.bias_size;\n let bias${w} = ${d.getByOffset(`bias${w}_offset / 4`)}[bias${w}_offset % 4];`,h=o?`\n let bias = ${d.getByOffset(\"global_idx % (uniforms.bias_size / 4)\")};`:`${u(0)}${u(1)}${u(2)}${u(3)}\n let bias = ${l.type.value}(bias0, bias1, bias2, bias3);`;return`${a.registerUniforms(m).declareVariables(l,d,c)}\n\n ${yo(Ee(t))}\n\n ${a.mainStart(Ct)}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_vec_size\")}\n\n let x = ${l.getByOffset(\"global_idx\")};\n ${h}\n let x_in = x + bias;\n ${c.setByOffset(\"global_idx\",wo(\"x_in\"))}\n }`};return{name:\"FastGeluWithBias\",shaderCache:{hint:`${o}`,inputDependencies:[\"type\",\"type\"]},getShaderSource:i,getRunData:a=>({outputs:[{dims:a[0].dims,dataType:a[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/Ct/4)}})}},bl=e=>{e.inputs.length<2||k.size(e.inputs[1].dims)===0?gu(e):e.compute(Af(e.inputs))}});var kf,Ef,wl,_l,vl=R(()=>{\"use strict\";te();oe();Ie();ae();kf=e=>{if(!e||e.length!==2)throw new Error(\"Gather requires 2 inputs.\")},Ef=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r.length,i=k.normalizeAxis(t.axis,o),a=r.slice(0);a.splice(i,1,...n);let l=r[i],d=e[0].dataType===9?4:1,c=Math.ceil(k.size(a)/d),m=[{type:12,data:c},{type:6,data:l},{type:12,data:i},...V(e[0].dims,e[1].dims,a)],u=h=>{let w=E(\"data\",e[0].dataType,e[0].dims.length,d),y=E(\"inputIndices\",e[1].dataType,e[1].dims.length),g=M(\"output\",e[0].dataType,a.length,d),x=v=>{let S=n.length,T=`var indicesIndices${v} = ${y.type.indices}(0);`;for(let C=0;C1?`indicesIndices${v}[${C}]`:`indicesIndices${v}`} = ${a.length>1?`outputIndices${v}[uniforms.axis + ${C}]`:`outputIndices${v}`};`;T+=`\n var idx${v} = ${y.getByIndices(`indicesIndices${v}`)};\n if (idx${v} < 0) {\n idx${v} = idx${v} + uniforms.axisDimLimit;\n }\n var dataIndices${v} : ${w.type.indices};\n `;for(let C=0,A=0;C1?`dataIndices${v}[${C}]`:`dataIndices${v}`} = u32(idx${v});`,A+=S):(T+=`${o>1?`dataIndices${v}[${C}]`:`dataIndices${v}`} = ${a.length>1?`outputIndices${v}[${A}]`:`outputIndices${v}`};`,A++);return T},$;if(e[0].dataType===9){let v=(S,T,C=\"\")=>`\n let outputIndices${T} = ${g.offsetToIndices(`outputOffset + ${T}u`)};\n ${x(T)};\n let offset${T} = ${w.indicesToOffset(`dataIndices${T}`)};\n let index${T} = offset${T} / 4u;\n let component${T} = offset${T} % 4u;\n ${S}[${T}] = ${C}(${w.getByOffset(`index${T}`)}[component${T}]);\n `;$=`\n let outputOffset = global_idx * ${d};\n var value = vec4(0);\n ${v(\"value\",0,\"u32\")}\n ${v(\"value\",1,\"u32\")}\n ${v(\"value\",2,\"u32\")}\n ${v(\"value\",3,\"u32\")}\n ${g.setByOffset(\"global_idx\",\"value\")}\n `}else $=`\n let outputIndices = ${g.offsetToIndices(\"global_idx\")};\n ${x(\"\")};\n let value = ${w.getByIndices(\"dataIndices\")};\n ${g.setByOffset(\"global_idx\",\"value\")};\n `;return`\n ${h.registerUniform(\"outputSize\",\"u32\").registerUniform(\"axisDimLimit\",\"i32\").registerUniform(\"axis\",\"u32\").declareVariables(w,y,g)}\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n ${$}\n }`};return{name:\"Gather\",shaderCache:{hint:t.cacheKey,inputDependencies:[\"rank\",\"rank\"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:m}),getShaderSource:u}},wl=e=>re({axis:e.axis}),_l=(e,t)=>{let r=e.inputs;kf(r),e.compute(Ef(e.inputs,t))}});var Pf,zf,$l,xl,Sl=R(()=>{\"use strict\";te();oe();Ie();ae();Pf=(e,t)=>{if(e.length<3||e.length>4)throw new Error(\"GatherBlockQuantized requires 3 or 4 inputs.\");let r=k.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,o=e[0],i=e[2],a=e.length===4?e[3]:void 0;if(i.dims.length!==o.dims.length||!o.dims.map((l,d)=>d===r?Math.ceil(l/n)===i.dims[d]:l===i.dims[d]).reduce((l,d)=>l&&d,!0))throw new Error(\"Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.\");if(a){if(a.dataType!==o.dataType)throw new Error(\"Zero point must have the same data type as the input tensor.\");if(a.dims.length!==i.dims.length||!a.dims.map((l,d)=>l===i.dims[d]).reduce((l,d)=>l&&d,!0))throw new Error(\"Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.\")}},zf=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r.length,i=k.normalizeAxis(t.gatherAxis,o),a=k.normalizeAxis(t.quantizeAxis,o),l=r.slice(0);l.splice(i,1,...n);let d=k.size(l),c=e[2].dataType,u=e[0].dataType===22,h=[{type:12,data:d},{type:12,data:a},{type:12,data:i},{type:12,data:t.blockSize},...V(...e.map((y,g)=>y.dims),l)],w=y=>{let g=E(\"data\",e[0].dataType,e[0].dims.length),x=E(\"inputIndices\",e[1].dataType,e[1].dims.length),$=E(\"scales\",e[2].dataType,e[2].dims.length),v=e.length>3?E(\"zeroPoint\",e[3].dataType,e[3].dims.length):void 0,S=M(\"output\",c,l.length),T=[g,x,$];v&&T.push(v);let C=[{name:\"output_size\",type:\"u32\"},{name:\"quantize_axis\",type:\"u32\"},{name:\"gather_axis\",type:\"u32\"},{name:\"block_size\",type:\"u32\"}];return`\n ${y.registerUniforms(C).declareVariables(...T,S)}\n ${y.mainStart()}\n let output_indices = ${S.offsetToIndices(\"global_idx\")};\n var indices_indices = ${x.type.indices}(0);\n ${(()=>n.length>1?`\n for (var i: u32 = 0; i < ${n.length}; i++) {\n let index = ${S.indicesGet(\"output_indices\",\"uniforms.gather_axis + i\")};\n ${x.indicesSet(\"indices_indices\",\"i\",\"index\")};\n }`:`indices_indices = ${S.indicesGet(\"output_indices\",\"uniforms.gather_axis\")};`)()};\n var data_indices = ${g.type.indices}(0);\n for (var i: u32 = 0; i < uniforms.gather_axis; i++) {\n let index = ${S.indicesGet(\"output_indices\",\"i\")};\n ${g.indicesSet(\"data_indices\",\"i\",\"index\")};\n }\n var index_from_indices = ${x.getByIndices(\"indices_indices\")};\n if (index_from_indices < 0) {\n index_from_indices += ${r[i]};\n }\n ${g.indicesSet(\"data_indices\",\"uniforms.gather_axis\",\"u32(index_from_indices)\")};\n for (var i = uniforms.gather_axis + 1; i < ${l.length}; i++) {\n let index = ${S.indicesGet(\"output_indices\",`i + ${n.length} - 1`)};\n ${g.indicesSet(\"data_indices\",\"i\",\"index\")};\n }\n let data_offset = ${g.indicesToOffset(\"data_indices\")};\n let data_index = data_offset % 8;\n // Convert 4-bit packed data to 8-bit packed data.\n let packed_4bit_quantized_data = ${g.getByOffset(\"data_offset / 8\")};\n let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f;\n let quantized_data_vec = ${u?\"unpack4xI8\":\"unpack4xU8\"}(u32(packed_8bit_quantized_data));\n let quantized_data = quantized_data_vec[data_index / 2];\n var scale_indices = data_indices;\n let quantize_axis_index = ${$.indicesGet(\"data_indices\",\"uniforms.quantize_axis\")} / uniforms.block_size;\n ${$.indicesSet(\"scale_indices\",\"uniforms.quantize_axis\",\"quantize_axis_index\")};\n var scale = ${$.getByIndices(\"scale_indices\")};\n ${(()=>v?`\n let zero_point_indices = scale_indices;\n let zero_point_offset = ${v.indicesToOffset(\"zero_point_indices\")};\n let zero_point_index = zero_point_offset % 8;\n let packed_4bit_zero_points = ${v.getByOffset(\"zero_point_offset / 8\")};\n let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f;\n let zero_point_vec = ${u?\"unpack4xI8\":\"unpack4xU8\"}(u32(packed_8bit_zero_points));\n let zero_point = zero_point_vec[zero_point_index / 2];`:\"var zero_point = 0\")()};\n let dequantized_data = ${Ee(c)}(quantized_data - zero_point) * scale;\n ${S.setByOffset(\"global_idx\",\"dequantized_data\")};\n }`};return{name:\"GatherBlockQuantized\",shaderCache:{hint:`${t.cacheKey};${e.filter((y,g)=>g!==1).map(y=>y.dims.join(\"_\")).join(\";\")}`,inputDependencies:Array.from({length:e.length},(y,g)=>\"rank\")},getRunData:()=>({outputs:[{dims:l,dataType:c}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:h}),getShaderSource:w}},$l=(e,t)=>{let r=e.inputs;Pf(r,t),e.compute(zf(e.inputs,t))},xl=e=>re({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})});var Of,Df,Tl,Il,Cl=R(()=>{\"use strict\";te();oe();Ie();ae();Of=e=>{if(!e||e.length!==2)throw new Error(\"GatherElements requires 2 inputs.\");if(e[0].dims.length<1)throw new Error(\"GatherElements requires that the data input be rank >= 1.\");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and\n indices input tensors be of same rank.`)},Df=(e,t)=>{let r=e[0].dims,n=e[0].dataType,o=r.length,i=e[1].dims,a=e[1].dataType,l=k.normalizeAxis(t.axis,o),d=r[l],c=i.slice(0),m=k.size(c),u=E(\"input\",n,o),h=E(\"indicesInput\",a,i.length),w=M(\"output\",n,c.length),y=[{type:12,data:m},{type:6,data:d},{type:12,data:l}];return y.push(...V(r,i,c)),{name:\"GatherElements\",shaderCache:{inputDependencies:[\"rank\",\"rank\"]},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:y}),getShaderSource:$=>`\n ${$.registerUniform(\"outputSize\",\"u32\").registerUniform(\"axisDimLimit\",\"i32\").registerUniform(\"axis\",\"u32\").declareVariables(u,h,w)}\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n\n let outputIndices = ${w.offsetToIndices(\"global_idx\")};\n\n var idx = ${h.getByOffset(\"global_idx\")};\n if (idx < 0) {\n idx = idx + uniforms.axisDimLimit;\n }\n var inputIndices = ${u.type.indices}(outputIndices);\n ${u.indicesSet(\"inputIndices\",\"uniforms.axis\",\"u32(idx)\")};\n let value = ${u.getByIndices(\"inputIndices\")};\n\n ${w.setByOffset(\"global_idx\",\"value\")};\n }`}},Tl=e=>re({axis:e.axis}),Il=(e,t)=>{let r=e.inputs;Of(r),e.compute(Df(e.inputs,t))}});var Bf,Mf,Al,kl,El=R(()=>{\"use strict\";te();oe();ae();Bf=e=>{if(!e)throw new Error(\"Input is missing\");if(e.length<2||e.length>3)throw new Error(\"Invaid input number.\");if(e.length===3&&e[2].dims.length>2)throw new Error(\"Invalid input shape of C\");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error(\"Input types are mismatched\")},Mf=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[o,i,a]=jr.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),l=[o,i];if(!l)throw new Error(\"Can't use gemm on the given tensors\");let d=16,c=Math.ceil(i/d),m=Math.ceil(o/d),u=!0,h=k.size(l),w=[{type:12,data:u?c:h},{type:12,data:o},{type:12,data:i},{type:12,data:a},{type:1,data:t.alpha},{type:1,data:t.beta}],y=[\"type\",\"type\"];e.length===3&&(w.push(...V(e[2].dims)),y.push(\"rank\")),w.push(...V(l));let g=$=>{let v=\"\";t.transA&&t.transB?v=\"value += a[k * uniforms.M + m] * b[n * uniforms.K + k];\":t.transA&&!t.transB?v=\"value += a[k * uniforms.M + m] * b[k * uniforms.N + n];\":!t.transA&&t.transB?v=\"value += a[m * uniforms.K + k] * b[n * uniforms.K + k];\":!t.transA&&!t.transB&&(v=\"value += a[m * uniforms.K + k] * b[k * uniforms.N + n];\");let S=t.alpha===1?\"\":\"value *= uniforms.alpha;\",T=E(\"a\",e[0].dataType,e[0].dims),C=E(\"b\",e[1].dataType,e[1].dims),A=T.type.value,P=null,O=[T,C];e.length===3&&(P=E(\"c\",e[2].dataType,e[2].dims.length),O.push(P));let U=M(\"output\",e[0].dataType,l.length);O.push(U);let L=[{name:\"output_size\",type:\"u32\"},{name:\"M\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"alpha\",type:\"f32\"},{name:\"beta\",type:\"f32\"}];return`\n ${$.registerUniforms(L).declareVariables(...O)}\n\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let m = global_idx / uniforms.N;\n let n = global_idx % uniforms.N;\n\n var value = ${A}(0);\n for (var k: u32 = 0u; k < uniforms.K; k++) {\n ${v}\n }\n\n ${S}\n ${(()=>P!=null?`let cOffset = ${P.broadcastedIndicesToOffset(\"vec2(m, n)\",U)}; value += ${A}(uniforms.beta) * ${P.getByOffset(\"cOffset\")};`:\"\")()}\n output[global_idx] = value;\n }`},x=$=>{let v=E(\"a\",e[0].dataType,e[0].dims),S=E(\"b\",e[1].dataType,e[1].dims),T=null,C=[v,S];e.length===3&&(T=E(\"c\",e[2].dataType,e[2].dims.length),C.push(T));let A=M(\"output\",e[0].dataType,l.length);C.push(A);let P=[{name:\"num_tile_n\",type:\"u32\"},{name:\"M\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"alpha\",type:\"f32\"},{name:\"beta\",type:\"f32\"}],O=\"\",U=\"\";t.transA&&t.transB?(U=`\n var col = tile_row_start + local_id.x;\n var row = k_start + local_id.y;\n if (col < uniforms.M && row < uniforms.K) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${v.type.value}(0);\n }\n\n col = k_start + local_id.x;\n row = tile_col_start + local_id.y;\n if (col < uniforms.K && row < uniforms.N) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${S.type.value}(0);\n }\n `,O=\"value += tile_a[k][local_id.y] * tile_b[local_id.x][k];\"):t.transA&&!t.transB?(U=`\n var col = tile_row_start + local_id.x;\n var row = k_start + local_id.y;\n if (col < uniforms.M && row < uniforms.K) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${v.type.value}(0);\n }\n\n col = tile_col_start + local_id.x;\n row = k_start + local_id.y;\n if (col < uniforms.N && row < uniforms.K) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${S.type.value}(0);\n }\n `,O=\"value += tile_a[k][local_id.y] * tile_b[k][local_id.x];\"):!t.transA&&t.transB?(U=`\n var col = k_start + local_id.x;\n var row = tile_row_start + local_id.y;\n if (col < uniforms.K && row < uniforms.M) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${v.type.value}(0);\n }\n\n col = k_start + local_id.x;\n row = tile_col_start + local_id.y;\n if (col < uniforms.K && row < uniforms.N) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${S.type.value}(0);\n }\n `,O=\"value += tile_a[local_id.y][k] * tile_b[local_id.x][k];\"):!t.transA&&!t.transB&&(U=`\n var col = k_start + local_id.x;\n var row = tile_row_start + local_id.y;\n if (col < uniforms.K && row < uniforms.M) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${v.type.value}(0);\n }\n\n col = tile_col_start + local_id.x;\n row = k_start + local_id.y;\n if (col < uniforms.N && row < uniforms.K) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${S.type.value}(0);\n }\n `,O=\"value += tile_a[local_id.y][k] * tile_b[k][local_id.x];\");let L=t.alpha===1?\"\":\"value *= uniforms.alpha;\";return`\n ${$.registerUniforms(P).declareVariables(...C)}\n var tile_a: array, ${d}>;\n var tile_b: array, ${d}>;\n ${$.mainStart([d,d,1])}\n let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${d};\n let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${d};\n let num_tiles = (uniforms.K - 1) / ${d} + 1;\n var k_start = 0u;\n var value = ${A.type.value}(0);\n for (var t: u32 = 0u; t < num_tiles; t++) {\n ${U}\n k_start = k_start + ${d};\n workgroupBarrier();\n\n for (var k: u32 = 0u; k < ${d}; k++) {\n ${O}\n }\n workgroupBarrier();\n }\n\n ${L}\n let m = tile_row_start + local_id.y;\n let n = tile_col_start + local_id.x;\n ${(()=>T!=null?`let cOffset = ${T.broadcastedIndicesToOffset(\"vec2(m, n)\",A)}; value += ${A.type.value}(uniforms.beta) * ${T.getByOffset(\"cOffset\")};`:\"\")()}\n if (m < uniforms.M && n < uniforms.N) {\n output[m * uniforms.N + n] = value;\n }\n }`};return u?{name:\"GemmShared\",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:c*m},programUniforms:w}),getShaderSource:x}:{name:\"Gemm\",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:w}),getShaderSource:g}},Al=e=>{let t=e.transA,r=e.transB,n=e.alpha,o=e.beta;return{transA:t,transB:r,alpha:n,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},kl=(e,t)=>{Bf(e.inputs),e.compute(Mf(e.inputs,t))}});var dt,yt,Ut,Vt,Rf,Uf,Vf,Nf,Wf,Lf,Gf,Hf,Pl,zl,Ol=R(()=>{\"use strict\";te();oe();Ie();ae();[dt,yt,Ut,Vt]=[0,1,2,3],Rf=e=>{if(e[0].dims.length!==4)throw new Error(\"only 4-D tensor is supported.\");if(e[0].dims.length!==e[1].dims.length)throw new Error(\"input dimensions must be equal to grid dimensions\");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error(\"grid batch size must match input batch size\")},Uf=`\n fn gs_get_cubic_coeffs(x: f32) -> vec4 {\n let cubic_alpha = -0.75f;\n let x_abs = abs(x);\n var coeffs: vec4;\n coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha);\n coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1);\n coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1);\n coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha);\n return coeffs;\n }\n`,Vf=e=>`\n fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} {\n var v: vec4;\n var coeffs = gs_get_cubic_coeffs(x);\n for (var i = 0; i < 4; i++) {\n v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3];\n }\n coeffs = gs_get_cubic_coeffs(y);\n let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]);\n return pixel;\n }\n`,Nf=e=>`\n fn gs_denormalize(n: f32, length: i32) -> f32 {\n ${e.alignCorners===0?`\n // alignCorners: false => [-1, 1] to [-0.5, length - 0.5]\n return ((n + 1.0) * f32(length) - 1.0) / 2.0;\n `:`\n // alignCorners: true => [-1, 1] to [0, length - 1]\n return (n + 1.0) / 2.0 * (f32(length - 1));\n `}\n }\n`,Wf=e=>`\n ${e.paddingMode===\"reflection\"?`\n fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 {\n var dx = 0.0;\n var fx = f32(x);\n let range = x_max - x_min;\n if (fx < x_min) {\n dx = x_min - fx;\n let n = u32(dx / range);\n let r = dx - f32(n) * range;\n if (n % 2 == 0) {\n fx = x_min + r;\n } else {\n fx = x_max - r;\n }\n } else if (fx > x_max) {\n dx = fx - x_max;\n let n = u32(dx / range);\n let r = dx - f32(n) * range;\n if (n % 2 == 0) {\n fx = x_max - r;\n } else {\n fx = x_min + r;\n }\n }\n return u32(fx);\n }`:\"\"}\n`,Lf=(e,t,r)=>`\n fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} {\n var pixel = ${t}(0);\n var indices = vec4(0);\n indices[${dt}] = batch;\n indices[${yt}] = channel;`+(()=>{switch(r.paddingMode){case\"zeros\":return`\n if (r >= 0 && r < H && c >=0 && c < W) {\n indices[${Ut}] = u32(r);\n indices[${Vt}] = u32(c);\n }\n `;case\"border\":return`\n indices[${Ut}] = u32(clamp(r, 0, H - 1));\n indices[${Vt}] = u32(clamp(c, 0, W - 1));\n `;case\"reflection\":return`\n indices[${Ut}] = gs_reflect(r, border[1], border[3]);\n indices[${Vt}] = gs_reflect(c, border[0], border[2]);\n `;default:throw new Error(`padding mode ${r.paddingMode} is not supported`)}})()+`\n return ${e.getByIndices(\"indices\")};\n }\n`,Gf=(e,t,r)=>(()=>{switch(r.mode){case\"nearest\":return`\n let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${dt}], indices[${yt}], border);\n `;case\"bilinear\":return`\n let x1 = i32(floor(x));\n let y1 = i32(floor(y));\n let x2 = x1 + 1;\n let y2 = y1 + 1;\n\n let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${dt}], indices[${yt}], border);\n let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${dt}], indices[${yt}], border);\n let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${dt}], indices[${yt}], border);\n let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${dt}], indices[${yt}], border);\n\n let dx2 = ${t}(f32(x2) - x);\n let dx1 = ${t}(x - f32(x1));\n let dy2 = ${t}(f32(y2) - y);\n let dy1 = ${t}(y - f32(y1));\n let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22);\n `;case\"bicubic\":return`\n let x0 = i32(floor(x)) - 1;\n let y0 = i32(floor(y)) - 1;\n var p: mat4x4<${t}>;\n for (var h = 0; h < 4; h++) {\n for (var w = 0; w < 4; w++) {\n p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${dt}], indices[${yt}], border);\n }\n }\n\n let dx = x - f32(x0 + 1);\n let dy = y - f32(y0 + 1);\n let result = gs_bicubic_interpolate(p, dx, dy);\n `;default:throw new Error(`mode ${r.mode} is not supported`)}})()+`${e.setByOffset(\"global_idx\",\"result\")}`,Hf=(e,t)=>{let r=E(\"x\",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=E(\"grid\",e[1].dataType,n.length,2),i=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format===\"NHWC\"&&(i=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[dt,yt,Ut,Vt]=[0,3,1,2]);let a=M(\"output\",e[0].dataType,i.length),l=r.type.value,d=k.size(i),c=[{type:12,data:d},...V(e[0].dims,n,i)],m=u=>`\n ${u.registerUniform(\"output_size\",\"u32\").declareVariables(r,o,a)}\n ${Uf}\n ${Vf(l)}\n ${Nf(t)}\n ${Wf(t)}\n ${Lf(r,l,t)}\n\n ${u.mainStart()}\n ${u.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let H_in = i32(uniforms.x_shape[${Ut}]);\n let W_in = i32(uniforms.x_shape[${Vt}]);\n\n ${t.alignCorners===0?`\n let x_min = -0.5;\n let x_max = f32(W_in) - 0.5;\n let y_min = -0.5;\n let y_max = f32(H_in) - 0.5;\n `:`\n let x_min = 0.0;\n let x_max = f32(W_in) - 1.0;\n let y_min = 0.0;\n let y_max = f32(H_in) - 1.0;\n `};\n let border = vec4(x_min, y_min, x_max, y_max);\n\n let indices = ${a.offsetToIndices(\"global_idx\")};\n var grid_indices = vec3(indices[${dt}], indices[${Ut}], indices[${Vt}]);\n let nxy = ${o.getByIndices(\"grid_indices\")};\n var x = gs_denormalize(f32(nxy[0]), W_in);\n var y = gs_denormalize(f32(nxy[1]), H_in);\n\n ${Gf(a,l,t)}\n }`;return{name:\"GridSample\",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:[\"type\",\"type\"]},getRunData:u=>{let h=k.size(i);return{outputs:[{dims:i,dataType:u[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:c}},getShaderSource:m}},Pl=(e,t)=>{Rf(e.inputs),e.compute(Hf(e.inputs,t))},zl=e=>re({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})});var Me,jf,Bl,Dl,Kf,ar,Ml,ko=R(()=>{\"use strict\";te();oe();Ie();qr();Xr();ae();ut();Me=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,jf=(e,t)=>{let r=e[0],n=Me(e,1),o=Me(e,2),i=Me(e,3),a=Me(e,4),l=Me(e,5),d=Me(e,6),c=Me(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error(\"Input query is expected to have 3 or 5 dimensions\");let m=r.dims[0],u=r.dims[1],h=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],w=u,y=0,g=0,x=Math.floor(h/t.numHeads);if(d&&c&&k.size(d.dims)&&k.size(c.dims)){if(d.dims.length!==4)throw new Error('Input \"past_key\" is expected to have 4 dimensions');if(d.dims[0]!==m||d.dims[1]!==t.numHeads||d.dims[3]!==x)throw new Error('Input \"past_key\" shape (batch_size, num_heads, past_sequence_length, head_size)');if(c.dims[0]!==m||c.dims[1]!==t.numHeads||c.dims[3]!==x)throw new Error('Input \"past_value\" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.dims[2]!==c.dims[2])throw new Error('Input \"past_key\" and \"past_value\" shall have same dim 2 (past_sequence_length)');if(c.dims.length!==4)throw new Error('Input \"past_value\" is expected to have 4 dimensions');y=d.dims[2],g=d.dims[2]}else if(d&&k.size(d.dims)||c&&k.size(c.dims))throw new Error('Input \"past_key\" and \"past_value\" shall be both present or both absent');let $;if(n&&k.size(n.dims)>0){if(r.dims.length!==3)throw new Error('Input \"query\" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input \"key\" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input \"query\" and \"key\" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input \"query\" and \"key\" shall have same dim 2 (hidden_size)');$=2,w=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==x)throw new Error('Expect \"key\" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect \"value\" be none when \"key\" has packed kv format.');$=5,w=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==x)throw new Error('Expect \"key\" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');$=0,w=n.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input \"query\" is expected to have 5 dimensions when key is empty');if(r.dims[2]!==t.numHeads||r.dims[3]!==3)throw new Error('Expect \"query\" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');$=3}if(i&&k.size(i.dims)>0){if(i.dims.length!==1)throw new Error('Input \"bias\" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error(\"bias is not allowed for packed kv.\")}let v=y+w,S=0;if(a&&k.size(a.dims)>0){S=8;let P=a.dims;throw P.length===1?P[0]===m?S=1:P[0]===3*m+2&&(S=3):P.length===2&&P[0]===m&&P[1]===v&&(S=5),S===8?new Error('Input \"key_padding_mask\" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error(\"Mask not supported\")}let T=!1,C=h;if(o&&k.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input \"value\" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input \"query\" and \"value\" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(w!==o.dims[1])throw new Error('Input \"key\" and \"value\" shall have the same dim 1 (kv_sequence_length)');C=o.dims[2]}else{if(w!==o.dims[2])throw new Error('Input \"key\" and \"value\" shall have the same dim 2 (kv_sequence_length)');C=o.dims[1]*o.dims[3],T=!0}}let A=!1;if(a&&k.size(a.dims)>0)throw new Error(\"Key padding mask is not supported\");if(l&&k.size(l.dims)>0){if(l.dims.length!==4)throw new Error('Input \"attention_bias\" is expected to have 4 dimensions');if(l.dims[0]!==m||l.dims[1]!==t.numHeads||l.dims[2]!==u||l.dims[3]!==v)throw new Error('Expect \"attention_bias\" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:m,sequenceLength:u,pastSequenceLength:y,kvSequenceLength:w,totalSequenceLength:v,maxSequenceLength:g,inputHiddenSize:0,hiddenSize:h,vHiddenSize:C,headSize:x,vHeadSize:Math.floor(C/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:S,scale:t.scale,broadcastResPosBias:A,passPastInKv:T,qkvFormat:$}},Bl=e=>re({...e}),Dl=re({perm:[0,2,1,3]}),Kf=(e,t,r,n,o,i,a)=>{let l=[n,o,i],d=k.size(l),c=[{type:12,data:d},{type:12,data:a},{type:12,data:i}],m=u=>{let h=M(\"qkv_with_bias\",t.dataType,l),w=E(\"qkv\",t.dataType,l),y=E(\"bias\",r.dataType,l),g=[{name:\"output_size\",type:\"u32\"},{name:\"bias_offset\",type:\"u32\"},{name:\"hidden_size\",type:\"u32\"}];return`\n ${u.registerUniforms(g).declareVariables(w,y,h)}\n ${u.mainStart()}\n ${u.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;\n\n qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];\n }`};return e.compute({name:\"MultiHeadAttentionAddBias\",shaderCache:{inputDependencies:[\"type\",\"type\"]},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c}),getShaderSource:m},{inputs:[t,r],outputs:[-1]})[0]},ar=(e,t,r,n,o,i,a,l)=>{let d=i;if(a&&k.size(a.dims)>0){if(n===1)throw new Error(\"AddBiasReshape is not implemented. Please export your model with packed QKV or KV\");return d=Kf(e,i,a,t,n,r*o,l),d=d.reshape([t,n,r,o]),r===1||n===1?d:e.compute(Pe(d,Dl.perm),{inputs:[d],outputs:[-1]})[0]}else return i.dims.length===3&&(d=i.reshape([t,n,r,o])),r===1||n===1?d:e.compute(Pe(d,Dl.perm),{inputs:[d],outputs:[-1]})[0]},Ml=(e,t)=>{let r=jf(e.inputs,t),n=e.inputs[0],o=Me(e.inputs,1),i=Me(e.inputs,2),a=Me(e.inputs,3),l=Me(e.inputs,4),d=Me(e.inputs,5),c=Me(e.inputs,6),m=Me(e.inputs,7);if(n.dims.length===5)throw new Error(\"Packed QKV is not implemented\");if(o?.dims.length===5)throw new Error(\"Packed KV is not implemented\");let u=o&&i&&o.dims.length===4&&i.dims.length===4,h=ar(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,a,0);if(u)return Rt(e,h,o,i,l,void 0,c,m,d,r);if(!o||!i)throw new Error(\"key and value must be provided\");let w=ar(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,o,a,r.hiddenSize),y=ar(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,i,a,2*r.hiddenSize);Rt(e,h,w,y,l,void 0,c,m,d,r)}});var Yf,Zf,Xf,Qf,Eo,Rl,Ul,Po=R(()=>{\"use strict\";te();oe();Ie();ae();Yf=e=>{if(!e||e.length<1)throw new Error(\"too few inputs\")},Zf=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>r.push(Number(o))),n=r.length),re({numOutputs:n,axis:t.axis,splitSizes:r})},Xf=e=>`\nfn calculateOutputIndex(index: u32) -> u32 {\n for (var i: u32 = 0u; i < ${e}u; i += 1u ) {\n if (index < ${F(\"uniforms.size_in_split_axis\",\"i\",e)}) {\n return i;\n }\n }\n return ${e}u;\n}`,Qf=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=k.size(r),o=e[0].dataType,i=k.normalizeAxis(t.axis,r.length),a=new Array(t.numOutputs),l=E(\"input\",o,r.length),d=new Array(t.numOutputs),c=[],m=[],u=0,h=[{type:12,data:n}];for(let y=0;y`\n ${y.registerUniform(\"input_size\",\"u32\").registerUniform(\"size_in_split_axis\",\"u32\",d.length).declareVariables(l,...a)}\n ${Xf(d.length)}\n ${Qf(a)}\n\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.input_size\")}\n\n var indices = ${l.offsetToIndices(\"global_idx\")};\n var index = ${l.indicesGet(\"indices\",i)};\n let output_number = calculateOutputIndex(index);\n if (output_number != 0) {\n index -= ${F(\"uniforms.size_in_split_axis\",\"output_number - 1u\",d.length)};\n ${l.indicesSet(\"indices\",i,\"index\")};\n }\n writeBufferData(output_number, indices, global_idx);\n }`;return{name:\"Split\",shaderCache:{hint:t.cacheKey,inputDependencies:[\"rank\"]},getShaderSource:w,getRunData:()=>({outputs:c,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:h})}},Rl=(e,t)=>{Yf(e.inputs);let r=e.inputs.length===1?t:Zf(e.inputs,t);e.compute(Eo(e.inputs,r),{inputs:[0]})},Ul=e=>{let t=e.axis,r=e.splitSizes,n=e.numOutputs<0?r.length:e.numOutputs;if(n!==r.length)throw new Error(\"numOutputs and splitSizes lengh must be equal\");return re({axis:t,numOutputs:n,splitSizes:r})}});var Jf,eh,Vl,Nl,Wl=R(()=>{\"use strict\";Ie();Xr();ko();Po();ut();Jf=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error(\"cos_cache and sin_cache inputs are required if do_rotary is specified\");let r=e[0],n=e[1],o=e[2],i=e[3],a=e[4];if(t.localWindowSize!==-1)throw new Error(\"Local attention is not supported\");if(t.softcap!==0)throw new Error(\"Softcap is not supported\");if(t.rotaryInterleaved!==0)throw new Error(\"Rotary interleaved is not supported\");if(t.smoothSoftmax)throw new Error(\"Smooth softmax is not supported\");if(r.dims.length!==3&&r.dims.length!==5)throw new Error(\"Input query is expected to have 3 or 5 dimensions\");let l=!1,d=r.dims[0],c=r.dims[1],m=r.dims.length===3?l?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],u=c,h=0,w=!n||n.dims.length===0,y=Math.floor(w?m/(t.numHeads+2*t.kvNumHeads):m/t.numHeads);w&&(m=y*t.numHeads);let g=i&&i.dims.length!==0,x=a&&a.dims.length!==0;if(g&&i.dims.length===4&&i.dims[0]===d&&i.dims[1]!==t.kvNumHeads&&i.dims[2]===t.kvNumHeads&&i.dims[3]===y)throw new Error(\"BSNH pastKey/pastValue is not supported\");if(g&&x){if(i.dims.length!==4)throw new Error('Input \"past_key\" is expected to have 4 dimensions');if(a.dims.length!==4)throw new Error('Input \"past_value\" is expected to have 4 dimensions');h=i.dims[2]}else if(g||x)throw new Error('Input \"past_key\" and \"past_value\" shall be both present or both absent');let v=1;if(n&&n.dims.length>0){if(r.dims.length!==3)throw new Error('Input \"query\" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input \"key\" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input \"query\" and \"key\" shall have same dim 0 (batch size)');if(n.dims.length===3){if(r.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of \"query\" should be a multiple of \"key\"');u=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==y)throw new Error('Expect \"key\" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect \"value\" be none when \"key\" has packed kv format.');u=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==y)throw new Error('Expect \"key\" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');u=n.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input \"query\" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error('Expect \"query\" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');v=3}let S=0,T=!1,C=t.kvNumHeads?y*t.kvNumHeads:m;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input \"value\" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input \"query\" and \"value\" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(u!==o.dims[1])throw new Error('Input \"key\" and \"value\" shall have the same dim 1 (kv_sequence_length)');C=o.dims[2]}else{if(u!==o.dims[2])throw new Error('Input \"past_key\" and \"past_value\" shall have the same dim 2 (kv_sequence_length)');C=o.dims[1]*o.dims[3],T=!0}}let A=e.length>4?e[5]:void 0;if(A&&A.dims.length!==1&&A.dims[0]!==d)throw new Error('Input \"seqlens\" is expected to have 1 dimension and the same dim 0 as batch_size');let P=-1,O=-1,U=!1;return{batchSize:d,sequenceLength:c,pastSequenceLength:h,kvSequenceLength:u,totalSequenceLength:P,maxSequenceLength:O,inputHiddenSize:0,hiddenSize:m,vHiddenSize:C,headSize:y,vHeadSize:Math.floor(C/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:S,scale:t.scale,broadcastResPosBias:U,passPastInKv:T,qkvFormat:v}},eh=re({perm:[0,2,1,3]}),Vl=(e,t,r)=>{let n=t,o=r.kvNumHeads;return t.dims.length===3&&r.kvSequenceLength!==0&&(n=t.reshape([r.batchSize,r.kvSequenceLength,o,r.headSize]),n=e.compute(Pe(n,eh.perm),{inputs:[n],outputs:[-1]})[0]),n},Nl=(e,t)=>{let r=Jf(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error(\"Packed QKV is not implemented\");if(e.inputs[1]?.dims.length===5)throw new Error(\"Packed KV is not implemented\");let n=e.inputs[0],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,i=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,a=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,l=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,d=e.inputs.length>4?e.inputs[5]:void 0,c=e.inputs.length>5?e.inputs[6]:void 0,m=r.kvNumHeads?r.kvNumHeads:r.numHeads,u=re({axis:2,numOutputs:3,splitSizes:[r.numHeads*r.headSize,m*r.headSize,m*r.headSize]}),[h,w,y]=!o&&!i?e.compute(Eo([n],u),{inputs:[n],outputs:[-1,-1,-1]}):[n,o,i],g=ar(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,h,void 0,0);Rt(e,g,Vl(e,w,r),Vl(e,y,r),void 0,void 0,a,l,void 0,r,d,c)}});var Ll,th,rh,Gl,Hl=R(()=>{\"use strict\";te();oe();ut();ae();Ll=(e,t,r,n,o,i,a,l)=>{let d=ye(i),c=d===1?\"f32\":`vec${d}f`,m=d===1?\"vec2f\":`mat2x${d}f`,u=o*a,h=64;u===1&&(h=256);let w=[o,a,i/d],y=[o,a,2],g=[\"rank\",\"type\",\"type\"],x=[];x.push(...V(w,y));let $=v=>{let S=E(\"x\",t.dataType,3,d),T=E(\"scale\",r.dataType,r.dims),C=E(\"bias\",n.dataType,n.dims),A=M(\"output\",1,3,2),P=[S,T,C,A];return`\n var workgroup_shared : array<${m}, ${h}>;\n const workgroup_size = ${h}u;\n ${v.declareVariables(...P)}\n ${v.mainStart(h)}\n let batch = workgroup_index / uniforms.x_shape[1];\n let channel = workgroup_index % uniforms.x_shape[1];\n let hight = uniforms.x_shape[2];\n // initialize workgroup memory\n var sum = ${c}(0);\n var squared_sum = ${c}(0);\n for (var h = local_idx; h < hight; h += workgroup_size) {\n let value = ${c}(${S.get(\"batch\",\"channel\",\"h\")});\n sum += value;\n squared_sum += value * value;\n }\n workgroup_shared[local_idx] = ${m}(sum, squared_sum);\n workgroupBarrier();\n\n for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) {\n if (local_idx < currSize) {\n workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize];\n }\n workgroupBarrier();\n }\n if (local_idx == 0) {\n let sum_final = ${Ke(\"workgroup_shared[0][0]\",d)} / f32(hight * ${d});\n let squared_sum_final = ${Ke(\"workgroup_shared[0][1]\",d)} / f32(hight * ${d});\n\n let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${l}));\n let channel_scale = inv_std_dev * f32(scale[channel]);\n let channel_shift = f32(bias[channel]) - sum_final * channel_scale;\n output[workgroup_index] = vec2f(channel_scale, channel_shift);\n }\n }`};return e.compute({name:\"InstanceNormComputeChannelScaleShift\",shaderCache:{hint:`${d};${l};${h}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:y,dataType:1}],dispatchGroup:{x:u},programUniforms:x}),getShaderSource:$},{inputs:[t,r,n],outputs:[-1]})[0]},th=(e,t,r)=>{let n=t[0].dims,o=n,i=2,a=n[0],l=n[1],d=k.sizeFromDimension(n,i),c=ye(d),m=k.size(o)/c,u=Ll(e,t[0],t[1],t[2],a,d,l,r.epsilon),h=[a,l,d/c],w=[a,l],y=[\"type\",\"none\"],g=x=>{let $=E(\"x\",t[0].dataType,h.length,c),v=E(\"scale_shift\",1,w.length,2),S=M(\"output\",t[0].dataType,h.length,c),T=[$,v,S];return`\n ${x.registerUniform(\"output_size\",\"u32\").declareVariables(...T)}\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let outputIndices = ${S.offsetToIndices(\"global_idx\")};\n let batch = outputIndices[0];\n let channel = outputIndices[1];\n let scale_shift = ${v.getByIndices(\"vec2(batch, channel)\")};\n let value = ${$.getByOffset(\"global_idx\")} * ${S.type.value}(scale_shift.x) + ${S.type.value}(scale_shift.y);\n ${S.setByOffset(\"global_idx\",\"value\")};\n }`};e.compute({name:\"InstanceNormalization\",shaderCache:{hint:`${c}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...V(h,w,h)]}),getShaderSource:g},{inputs:[t[0],u]})},rh=(e,t,r)=>{let n=t[0].dims,o=n,i=n[0],a=n[n.length-1],l=k.sizeFromDimension(n,1)/a,d=ye(a),c=k.size(o)/d,m=[{type:12,data:l},{type:12,data:Math.floor(a/d)}],u=[\"type\",\"type\"],h=!1,w=[0,n.length-1];for(let $=0;$n[w[v]])),g=Ll(e,y,t[1],t[2],i,l,a,r.epsilon),x=$=>{let v=me(t[0].dataType),S=d===1?\"vec2f\":`mat${d}x2f`,T=P=>{let O=P===0?\"x\":\"y\",U=d===1?\"f32\":`vec${d}f`;switch(d){case 1:return`${v}(${U}(scale.${O}))`;case 2:return`vec2<${v}>(${U}(scale[0].${O}, scale[1].${O}))`;case 4:return`vec4<${v}>(${U}(scale[0].${O}, scale[1].${O}, scale[2].${O}, scale[3].${O}))`;default:throw new Error(`Not supported compoents ${d}`)}},C=E(\"input\",t[0].dataType,t[0].dims,d),A=M(\"output\",t[0].dataType,o,d);return`\n @group(0) @binding(0) var input : array<${C.type.storage}>;\n @group(0) @binding(1) var scale_input : array<${S}>;\n @group(0) @binding(2) var output : array<${A.type.storage}>;\n struct Uniforms {H: u32, C : u32};\n @group(0) @binding(3) var uniforms: Uniforms;\n\n ${$.mainStart()}\n let current_image_number = global_idx / (uniforms.C * uniforms.H);\n let current_channel_number = global_idx % uniforms.C;\n\n let scale_offset = current_image_number * uniforms.C + current_channel_number;\n let scale = scale_input[scale_offset];\n output[global_idx] = fma(input[global_idx], ${T(0)}, ${T(1)});\n }`};e.compute({name:\"InstanceNormalizationNHWC\",shaderCache:{hint:`${d}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:m}),getShaderSource:x},{inputs:[t[0],g]})},Gl=(e,t)=>{t.format===\"NHWC\"?rh(e,e.inputs,t):th(e,e.inputs,t)}});var nh,oh,Fl,ql=R(()=>{\"use strict\";te();oe();ae();nh=e=>{if(!e||e.length<2)throw new Error(\"layerNorm requires at least 2 inputs.\")},oh=(e,t,r)=>{let n=t.simplified,o=e[0].dims,i=e[1],a=!n&&e[2],l=o,d=k.normalizeAxis(t.axis,o.length),c=k.sizeToDimension(o,d),m=k.sizeFromDimension(o,d),u=k.size(i.dims),h=a?k.size(a.dims):0;if(u!==m||a&&h!==m)throw new Error(`Size of X.shape()[axis:] == ${m}.\n Size of scale and bias (if provided) must match this.\n Got scale size of ${u} and bias size of ${h}`);let w=[];for(let C=0;C1,v=r>2,S=C=>{let A=me(e[0].dataType),P=[E(\"x\",e[0].dataType,e[0].dims,y),E(\"scale\",i.dataType,i.dims,y)];a&&P.push(E(\"bias\",a.dataType,a.dims,y)),P.push(M(\"output\",e[0].dataType,l,y)),$&&P.push(M(\"mean_data_output\",1,w)),v&&P.push(M(\"inv_std_output\",1,w));let O=[{name:\"norm_count\",type:\"u32\"},{name:\"norm_size\",type:\"f32\"},{name:\"norm_size_vectorized\",type:\"u32\"},{name:\"epsilon\",type:\"f32\"}];return`\n ${C.registerUniforms(O).declareVariables(...P)}\n ${C.mainStart()}\n ${C.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.norm_count\")}\n let offset = global_idx * uniforms.norm_size_vectorized;\n var mean_vector = ${mo(\"f32\",y)};\n var mean_square_vector = ${mo(\"f32\",y)};\n\n for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {\n let value = ${At(A,y,\"x[h + offset]\")};\n mean_vector += value;\n mean_square_vector += value * value;\n }\n let mean = ${Ke(\"mean_vector\",y)} / uniforms.norm_size;\n let inv_std_dev = inverseSqrt(${Ke(\"mean_square_vector\",y)} / uniforms.norm_size ${n?\"\":\"- mean * mean\"} + uniforms.epsilon);\n\n for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {\n let f32input = ${At(A,y,\"x[j + offset]\")};\n let f32scale = ${At(A,y,\"scale[j]\")};\n output[j + offset] = ${P[0].type.value}((f32input ${n?\"\":\"- mean\"}) * inv_std_dev * f32scale\n ${a?`+ ${At(A,y,\"bias[j]\")}`:\"\"}\n );\n }\n\n ${$?\"mean_data_output[global_idx] = mean\":\"\"};\n ${v?\"inv_std_output[global_idx] = inv_std_dev\":\"\"};\n }`},T=[{dims:l,dataType:e[0].dataType}];return $&&T.push({dims:w,dataType:1}),v&&T.push({dims:w,dataType:1}),{name:\"LayerNormalization\",shaderCache:{hint:`${y};${r};${n}`,inputDependencies:g},getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(c/64)},programUniforms:x}),getShaderSource:S}},Fl=(e,t)=>{nh(e.inputs),e.compute(oh(e.inputs,t,e.outputCount))}});var ih,jl,Kl=R(()=>{\"use strict\";oe();on();ir();ih=e=>{if(!e||e.length!==2)throw new Error(\"MatMul requires 2 inputs.\");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error(\"shared dimension does not match.\")},jl=e=>{ih(e.inputs);let t=et.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error(\"Can't use matmul on the given tensors\");let r=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];if(r<8&&n<8)e.compute(nn(e.inputs,{activation:\"\"},t));else{let o=t[t.length-2],i=k.size(e.inputs[0].dims.slice(0,-2)),a=k.size(e.inputs[1].dims.slice(0,-2));if(i!==1&&o===1&&a===1){let l=e.inputs[0].reshape([1,i,n]),d=e.inputs[1].reshape([1,n,r]),c=[1,i,r],m=[l,d];e.compute(or(m,{activation:\"\"},t,c),{inputs:m})}else e.compute(or(e.inputs,{activation:\"\"},t))}}});var ah,sh,uh,Yl,Zl,Xl=R(()=>{\"use strict\";te();oe();Ie();ae();ah=(e,t)=>{if(e.length<3||e.length>4)throw new Error(\"MatMulNBits requires 3 or 4 inputs\");let r=e[0],n=r.dims.length;if(r.dims[n-1]!==t.k)throw new Error(\"The last dim of input shape does not match the k value\");let o=Math.floor((t.k+t.blockSize-1)/t.blockSize),i=t.blockSize/8*t.bits,a=e[1];if(!k.areEqual(a.dims,[t.n,o,i]))throw new Error(\"The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize\");let d=e[2].dims;if(k.size(d)!==t.n*o)throw new Error(\"scales input size error.\");if(e.length===4){let m=e[3].dims,u=t.bits>4?t.n*o:t.n*Math.floor((o+1)/2);if(k.size(m)!==u)throw new Error(\"zeroPoints input size error.\")}},sh=(e,t)=>{let r=e[0].dims,n=r.length,o=r[n-2],i=t.k,a=t.n,l=r.slice(0,n-2),d=k.size(l),m=e[1].dims[2]/4,u=e[0].dataType,h=ye(t.k),w=ye(m),y=ye(a),g=l.concat([o,a]),x=o>1&&a/y%2===0?2:1,$=k.size(g)/y/x,v=64,S=[],T=[d,o,i/h],C=k.convertShape(e[1].dims).slice();C.splice(-1,1,m/w),S.push(...V(T)),S.push(...V(C)),S.push(...V(e[2].dims)),e.length===4&&S.push(...V(k.convertShape(e[3].dims)));let A=[d,o,a/y];S.push(...V(A));let P=O=>{let U=T.length,L=E(\"a\",e[0].dataType,U,h),j=E(\"b\",12,C.length,w),K=E(\"scales\",e[2].dataType,e[2].dims.length),W=[L,j,K],ee=e.length===4?E(\"zero_points\",12,e[3].dims.length):void 0;ee&&W.push(ee);let ue=A.length,Z=M(\"output\",e[0].dataType,ue,y),J=me(e[0].dataType),Q=(()=>{switch(h){case 1:return`array<${J}, 8>`;case 2:return`mat4x2<${J}>`;case 4:return`mat2x4<${J}>`;default:throw new Error(`${h}-component is not supported.`)}})(),ne=()=>{let $e=`\n // reuse a data\n var input_offset = ${L.indicesToOffset(`${L.type.indices}(batch, row, word_offset)`)};\n var a_data: ${Q};\n for (var j: u32 = 0; j < ${8/h}; j++) {\n a_data[j] = ${L.getByOffset(\"input_offset\")};\n input_offset++;\n }\n `;for(let de=0;de> 4) & b_mask);\n b_quantized_values = ${Q}(${Array.from({length:4},(N,q)=>`${J}(b_value_lower[${q}]), ${J}(b_value_upper[${q}])`).join(\", \")});\n b_dequantized_values = ${(()=>h===1?`${Q}(${Array.from({length:8},(N,q)=>`(b_quantized_values[${q}] - ${ee?`zero_point${de}`:\"zero_point\"}) * scale${de}`).join(\", \")});`:`(b_quantized_values - ${Q}(${Array(8).fill(`${ee?`zero_point${de}`:\"zero_point\"}`).join(\",\")})) * scale${de};`)()};\n workgroup_shared[local_id.x * ${x} + ${Math.floor(de/y)}]${y>1?`[${de%y}]`:\"\"} += ${Array.from({length:8/h},(N,q)=>`${h===1?`a_data[${q}] * b_dequantized_values[${q}]`:`dot(a_data[${q}], b_dequantized_values[${q}])`}`).join(\" + \")};\n `;return $e},we=()=>{let $e=`\n var col_index = col * ${y};\n ${ee?`\n let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2;\n var zero_point_byte_count: u32;\n var zero_point_word_index: u32;\n var zero_point_byte_offset: u32;\n let zero_point_nibble_offset: u32 = block & 0x1u;\n var zero_point_bits_offset: u32;\n var zero_point_word: u32;`:`\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${J}(8);`}\n `;for(let de=0;de> 0x1u);\n zero_point_word_index = zero_point_byte_count >> 0x2u;\n zero_point_byte_offset = zero_point_byte_count & 0x3u;\n zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n zero_point_word = ${ee.getByOffset(\"zero_point_word_index\")} >> zero_point_bits_offset;\n let zero_point${de} = ${J}((zero_point_word) & 0xFu);`:\"\"}\n col_index += 1;`;return $e},Ae=()=>{let $e=`col_index = col * ${y};`;for(let de=0;de;\n var b_value_upper: vec4;\n var b_quantized_values: ${Q};\n var b_dequantized_values: ${Q};`,$e};return`\n var workgroup_shared: array<${Z.type.value}, ${x*v}>;\n ${O.declareVariables(...W,Z)}\n ${O.mainStart([v,1,1])}\n let output_indices = ${Z.offsetToIndices(`(global_idx / ${v}) * ${x}`)};\n let col = output_indices[2];\n let row = output_indices[1];\n let batch = output_indices[0];\n let nBlocksPerCol = uniforms.b_shape[1];\n\n for (var block = local_id.x; block < nBlocksPerCol; block += ${v}) {\n //process one block\n var word_offset: u32 = block * ${t.blockSize/h};\n ${we()}\n for (var word: u32 = 0; word < ${m}; word += ${w}) {\n ${Ae()}\n for (var i: u32 = 0; i < ${w}; i++) {\n ${ne()}\n word_offset += ${8/h};\n }\n }\n }\n workgroupBarrier();\n\n if (local_id.x < ${x}) {\n var output_value: ${Z.type.value} = ${Z.type.value}(0);\n var workgroup_shared_offset: u32 = local_id.x;\n for (var b: u32 = 0u; b < ${v}u; b++) {\n output_value += workgroup_shared[workgroup_shared_offset];\n workgroup_shared_offset += ${x};\n }\n ${Z.setByIndices(`${Z.type.indices}(batch, row, col + local_id.x)`,\"output_value\")};\n }\n }`};return{name:\"MatMulNBits\",shaderCache:{hint:`${t.blockSize};${t.bits};${h};${w};${y};${x};${v}`,inputDependencies:Array(e.length).fill(\"rank\")},getRunData:()=>({outputs:[{dims:g,dataType:u}],dispatchGroup:{x:$},programUniforms:S}),getShaderSource:P}},uh=(e,t)=>{let r=e[0].dims,n=r.length,o=r[n-2],i=t.k,a=t.n,l=r.slice(0,n-2),d=k.size(l),m=e[1].dims[2]/4,u=e[0].dataType,h=ye(t.k),w=ye(m),y=l.concat([o,a]),g=128,x=a%8===0?8:a%4===0?4:1,$=g/x,v=$*w*8,S=v/h,T=v/t.blockSize,C=k.size(y)/x,A=[],P=[d,o,i/h],O=k.convertShape(e[1].dims).slice();O.splice(-1,1,m/w),A.push(...V(P)),A.push(...V(O)),A.push(...V(e[2].dims)),e.length===4&&A.push(...V(k.convertShape(e[3].dims)));let U=[d,o,a];A.push(...V(U));let L=j=>{let K=P.length,W=E(\"a\",e[0].dataType,K,h),ee=E(\"b\",12,O.length,w),ue=E(\"scales\",e[2].dataType,e[2].dims.length),Z=[W,ee,ue],J=e.length===4?E(\"zero_points\",12,e[3].dims.length):void 0;J&&Z.push(J);let Q=U.length,ne=M(\"output\",e[0].dataType,Q),we=me(e[0].dataType),Ae=()=>{switch(h){case 1:return`\n let a_data0 = vec4<${we}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]);\n let a_data1 = vec4<${we}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return`\n let a_data0 = vec4<${we}>(sub_a[word_offset], sub_a[word_offset + 1]);\n let a_data1 = vec4<${we}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return`\n let a_data0 = sub_a[word_offset];\n let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${h}-component is not supported.`)}};return`\n var sub_a: array<${W.type.value}, ${S}>;\n var inter_results: array, ${x}>;\n ${j.declareVariables(...Z,ne)}\n ${j.mainStart([$,x,1])}\n let output_indices = ${ne.offsetToIndices(`workgroup_index * ${x}`)};\n let col = output_indices[2];\n let row = output_indices[1];\n let batch = output_indices[0];\n let n_blocks_per_col = uniforms.b_shape[1];\n let num_tiles = (n_blocks_per_col - 1) / ${T} + 1;\n\n // Loop over shared dimension.\n for (var tile: u32 = 0; tile < num_tiles; tile += 1) {\n let a_col_start = tile * ${S};\n // load one tile A data into shared memory.\n for (var a_offset = local_idx; a_offset < ${S}; a_offset += ${g})\n {\n let a_col = a_col_start + a_offset;\n if (a_col < uniforms.a_shape[2])\n {\n sub_a[a_offset] = ${W.getByIndices(`${W.type.indices}(batch, row, a_col)`)};\n } else {\n sub_a[a_offset] = ${W.type.value}(0);\n }\n }\n workgroupBarrier();\n\n // each thread process one block\n let b_row = col + local_id.y;\n let block = tile * ${T} + local_id.x;\n ${J?`\n let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2;\n let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u);\n let zero_point_word_index = zero_point_byte_count >> 0x2u;\n let zero_point_byte_offset = zero_point_byte_count & 0x3u;\n let zero_point_nibble_offset: u32 = block & 0x1u;\n let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n let zero_point_word = ${J.getByOffset(\"zero_point_word_index\")} >> zero_point_bits_offset;\n let zero_point = ${we}((zero_point_word) & 0xFu);`:`\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${we}(8);`}\n let scale = ${ue.getByOffset(\"b_row * n_blocks_per_col + block\")};\n let b_data = ${ee.getByIndices(`${ee.type.indices}(b_row, block, 0)`)};\n var word_offset = local_id.x * ${t.blockSize/h};\n for (var i: u32 = 0; i < ${w}; i++) {\n ${Ae()}\n let b_value = ${w===1?\"b_data\":\"b_data[i]\"};\n let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu);\n let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu);\n let b_quantized_values = mat2x4<${we}>(${Array.from({length:4},($e,de)=>`${we}(b_value_lower[${de}]), ${we}(b_value_upper[${de}])`).join(\", \")});\n let b_dequantized_values = (b_quantized_values - mat2x4<${we}>(${Array(8).fill(\"zero_point\").join(\",\")})) * scale;\n inter_results[local_id.y][local_id.x] += ${Array.from({length:2},($e,de)=>`${`dot(a_data${de}, b_dequantized_values[${de}])`}`).join(\" + \")};\n word_offset += ${8/h};\n }\n workgroupBarrier();\n }\n\n if (local_idx < ${x}) {\n var output_value: ${ne.type.value} = ${ne.type.value}(0);\n for (var b = 0u; b < ${$}; b++) {\n output_value += inter_results[local_idx][b];\n }\n if (col + local_idx < uniforms.output_shape[2])\n {\n ${ne.setByIndices(`${ne.type.indices}(batch, row, col + local_idx)`,\"output_value\")}\n }\n }\n }`};return{name:\"BlockwiseMatMulNBits32\",shaderCache:{hint:`${t.blockSize};${h};${w};${$};${x}`,inputDependencies:Array(e.length).fill(\"rank\")},getRunData:()=>({outputs:[{dims:y,dataType:u}],dispatchGroup:{x:C},programUniforms:A}),getShaderSource:L}},Yl=(e,t)=>{ah(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor(\"intel\")&&e.adapterInfo.isArchitecture(\"gen-12lp\")?e.compute(uh(e.inputs,t)):e.compute(sh(e.inputs,t))},Zl=e=>re(e)});var lh,dh,ch,ph,mh,fh,hh,gh,Ql,Jl=R(()=>{\"use strict\";te();oe();ae();lh=e=>{if(!e||e.length<1)throw new Error(\"Too few inputs\");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error(\"Input type must be float or float16.\");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error(\"The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].\")}},dh=(e,t,r)=>{let n=\"\";for(let o=t-1;o>=0;--o)n+=`\n k = i32(${e.indicesGet(\"indices\",o)}) - ${F(\"uniforms.pads\",o,r)};\n if (k < 0) {\n break;\n }\n if (k >= i32(${F(\"uniforms.x_shape\",o,t)})) {\n break;\n }\n offset += k * i32(${F(\"uniforms.x_strides\",o,t)});\n `;return`\n value = ${e.type.value}(uniforms.constant_value);\n for (var i = 0; i < 1; i++) {\n var offset = 0;\n var k = 0;\n ${n}\n value = x[offset];\n }\n `},ch=(e,t,r)=>{let n=\"\";for(let o=t-1;o>=0;--o)n+=`\n k = i32(${e.indicesGet(\"indices\",o)}) - ${F(\"uniforms.pads\",o,r)};\n if (k < 0) {\n k = -k;\n }\n {\n let _2n_1 = 2 * (i32(${F(\"uniforms.x_shape\",o,t)}) - 1);\n k = k % _2n_1;\n if(k >= i32(${F(\"uniforms.x_shape\",o,t)})) {\n k = _2n_1 - k;\n }\n }\n offset += k * i32(${F(\"uniforms.x_strides\",o,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${n}\n value = x[offset];\n `},ph=(e,t,r)=>{let n=\"\";for(let o=t-1;o>=0;--o)n+=`\n k = i32(${e.indicesGet(\"indices\",o)}) - ${F(\"uniforms.pads\",o,r)};\n if (k < 0) {\n k = 0;\n }\n if (k >= i32(${F(\"uniforms.x_shape\",o,t)})) {\n k = i32(${F(\"uniforms.x_shape\",o,t)}) - 1;\n }\n offset += k * i32(${F(\"uniforms.x_strides\",o,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${n}\n value = x[offset];\n `},mh=(e,t,r)=>{let n=\"\";for(let o=t-1;o>=0;--o)n+=`\n k = i32(${e.indicesGet(\"indices\",o)}) - ${F(\"uniforms.pads\",o,r)};\n if (k < 0) {\n k += i32(${F(\"uniforms.x_shape\",o,t)}]);\n }\n if (k >= i32(${F(\"uniforms.x_shape\",o,t)})) {\n k -= i32(${F(\"uniforms.x_shape\",o,t)});\n }\n offset += k * i32(${F(\"uniforms.x_strides\",o,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${n}\n value = x[offset];\n `},fh=(e,t,r)=>{switch(r.mode){case 0:return dh(e,t,r.pads.length);case 1:return ch(e,t,r.pads.length);case 2:return ph(e,t,r.pads.length);case 3:return mh(e,t,r.pads.length);default:throw new Error(\"Invalid mode\")}},hh=(e,t)=>{let r=k.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,o=k.size(r),i=[{type:12,data:o},{type:6,data:t.pads}],a=e.length>=3&&e[2].data;t.mode===0&&i.push({type:a?e[2].dataType:1,data:t.value}),i.push(...V(e[0].dims,r));let l=[\"rank\"],d=c=>{let m=M(\"output\",e[0].dataType,r.length),u=E(\"x\",e[0].dataType,n.length),h=u.type.value,w=fh(m,n.length,t),y=[{name:\"output_size\",type:\"u32\"},{name:\"pads\",type:\"i32\",length:t.pads.length}];return t.mode===0&&y.push({name:\"constant_value\",type:a?h:\"f32\"}),`\n ${c.registerUniforms(y).declareVariables(u,m)}\n ${c.mainStart()}\n ${c.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let indices = ${m.offsetToIndices(\"global_idx\")};\n\n var value = ${h}(0);\n ${w}\n output[global_idx] = value;\n }`};return{name:\"Pad\",shaderCache:{hint:`${t.mode}${a}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k.size(r)/64)},programUniforms:i}),getShaderSource:d}},gh=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,i=new Int32Array(2*o).fill(0);if(e.length>=4){let l=e[3].getBigInt64Array();for(let d=0;di[Number(d)]=Number(l));let a=[];return i.forEach(l=>a.push(l)),{mode:t.mode,value:n,pads:a}}else return t},Ql=(e,t)=>{lh(e.inputs);let r=gh(e.inputs,t);e.compute(hh(e.inputs,r),{inputs:[0]})}});var un,ed,td,rd,nd,bh,yh,od,id,ad,sd,ud,ld,dd,cd,pd,md,fd,hd,gd=R(()=>{\"use strict\";He();te();oe();ae();un=e=>{if(ve.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error(\"Pool ops requires 1 input.\")},ed=(e,t,r)=>{let n=t.format===\"NHWC\",o=e.dims.slice();n&&o.splice(1,0,o.pop());let i=Object.hasOwnProperty.call(t,\"dilations\"),a=t.kernelShape.slice(),l=t.strides.slice(),d=i?t.dilations.slice():[],c=t.pads.slice();It.adjustPoolAttributes(r,o,a,l,d,c);let m=It.computePoolOutputShape(r,o,l,d,a,c,t.autoPad),u=Object.assign({},t);i?Object.assign(u,{kernelShape:a,strides:l,pads:c,dilations:d,cacheKey:t.cacheKey}):Object.assign(u,{kernelShape:a,strides:l,pads:c,cacheKey:t.cacheKey});let h=m.slice();return h.push(h.splice(1,1)[0]),[u,n?h:m]},td=(e,t)=>{let r=t.format===\"NHWC\",n=k.size(e),o=k.size(t.kernelShape),i=[{type:12,data:n},{type:12,data:o}],a=[{name:\"outputSize\",type:\"u32\"},{name:\"kernelSize\",type:\"u32\"}];if(t.kernelShape.length<=2){let l=t.kernelShape[t.kernelShape.length-1],d=t.strides[t.strides.length-1],c=t.pads[t.pads.length/2-1],m=t.pads[t.pads.length-1],u=!!(c+m);i.push({type:12,data:l},{type:12,data:d},{type:12,data:c},{type:12,data:m}),a.push({name:\"kw\",type:\"u32\"},{name:\"sw\",type:\"u32\"},{name:\"pwStart\",type:\"u32\"},{name:\"pwEnd\",type:\"u32\"});let h=!1;if(t.kernelShape.length===2){let w=t.kernelShape[t.kernelShape.length-2],y=t.strides[t.strides.length-2],g=t.pads[t.pads.length/2-2],x=t.pads[t.pads.length-2];h=!!(g+x),i.push({type:12,data:w},{type:12,data:y},{type:12,data:g},{type:12,data:x}),a.push({name:\"kh\",type:\"u32\"},{name:\"sh\",type:\"u32\"},{name:\"phStart\",type:\"u32\"},{name:\"phEnd\",type:\"u32\"})}return[i,a,!0,u,h]}else{if(r)throw new Error(\"Pooling with kernelShape.length > 2 is not supported for NHWC format.\");let l=k.computeStrides(t.kernelShape);i.push({type:12,data:l},{type:12,data:t.pads},{type:12,data:t.strides}),a.push({name:\"kernelStrides\",type:\"u32\",length:l.length},{name:\"pads\",type:\"u32\",length:t.pads.length},{name:\"strides\",type:\"u32\",length:t.strides.length});let d=t.pads.reduce((c,m)=>c+m);return[i,a,!!d,!1,!1]}},rd=(e,t,r,n,o,i,a,l,d,c,m,u)=>{let h=o.format===\"NHWC\",w=t.type.value,y=M(\"output\",t.type.tensor,n);if(o.kernelShape.length<=2){let g=\"\",x=\"\",$=\"\",v=r-(h?2:1);if(m?g=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i;\n if (xIndices[${v}] < 0 || xIndices[${v}]\n >= uniforms.x_shape[${v}]) {\n pad++;\n continue;\n }\n let x_val = x[${t.indicesToOffset(\"xIndices\")}];\n ${i}\n }`:g=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i;\n let x_val = x[${t.indicesToOffset(\"xIndices\")}];\n ${i}\n }`,o.kernelShape.length===2){let T=r-(h?3:2);u?x=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j;\n if (xIndices[${T}] < 0 || xIndices[${T}] >= uniforms.x_shape[${T}]) {\n pad += i32(uniforms.kw);\n continue;\n }\n `:x=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j;\n `,$=`\n }\n `}return`\n ${e.registerUniforms(d).declareVariables(t,y)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n\n let indices = ${y.offsetToIndices(\"global_idx\")};\n var xIndices = ${y.offsetToIndices(\"global_idx\")};\n\n var value = ${w}(${l});\n var pad = 0;\n ${x}\n ${g}\n ${$}\n ${a}\n\n output[global_idx] = value;\n }`}else{if(h)throw new Error(\"Pooling with kernelShape.length > 2 is not supported for NHWC format.\");let g=o.kernelShape.length,x=o.pads.length,$=\"\";return c?$=`\n if (xIndices[j] >= uniforms.x_shape[j]) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n let x_val = x[${t.indicesToOffset(\"xIndices\")}];\n ${i}\n }`:$=`\n }\n let x_val = x[${t.indicesToOffset(\"xIndices\")}];\n ${i}\n `,`\n ${e.registerUniforms(d).declareVariables(t,y)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n let indices = ${y.offsetToIndices(\"global_idx\")};\n var xIndices = ${y.offsetToIndices(\"global_idx\")};\n\n var offsets: array;\n\n var value = ${w}(${l});\n var pad = 0;\n var isPad = false;\n\n for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {\n var offset = i;\n for (var j = 0u; j < ${g-1}u; j++) {\n offsets[j] = offset / ${F(\"uniforms.kernelStrides\",\"j\",g)};\n offset -= offsets[j] * ${F(\"uniforms.kernelStrides\",\"j\",g)};\n }\n offsets[${g-1}] = offset;\n\n isPad = false;\n for (var j = ${r-g}u; j < ${r}u; j++) {\n xIndices[j] = indices[j] * ${F(\"uniforms.strides\",`j - ${r-g}u`,g)}\n + offsets[j - ${r-g}u] - ${F(\"uniforms.pads\",\"j - 2u\",x)};\n ${$}\n }\n ${a}\n\n output[global_idx] = value;\n }`}},nd=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,bh=e=>`${nd(e)};${e.countIncludePad}`,yh=e=>`${nd(e)};${e.storageOrder};${e.dilations}`,od=e=>({format:e.format,autoPad:[\"NOTSET\",\"VALID\",\"SAME_UPPER\",\"SAME_LOWER\"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),id=(e,t,r,n)=>{let[o,i]=ed(t,n,r),a=E(\"x\",t.dataType,t.dims.length),l=a.type.value,d=\"value += x_val;\",c=\"\";o.countIncludePad?c+=`value /= ${l}(uniforms.kernelSize);`:c+=`value /= ${l}(i32(uniforms.kernelSize) - pad);`;let[m,u,h,w,y]=td(i,o);m.push(...V(t.dims,i));let g=[\"rank\"];return{name:e,shaderCache:{hint:`${n.cacheKey};${h};${w};${y}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(k.size(i)/64)},programUniforms:m}),getShaderSource:x=>rd(x,a,t.dims.length,i.length,o,d,c,0,u,h,w,y)}},ad=e=>{let t=e.count_include_pad!==0,r=od(e);if(r.ceilMode!==0)throw new Error(\"using ceil() in shape computation is not yet supported for AveragePool\");let n={countIncludePad:t,...r,cacheKey:\"\"};return{...n,cacheKey:bh(n)}},sd=(e,t)=>{un(e.inputs),e.compute(id(\"AveragePool\",e.inputs[0],!1,t))},ud={autoPad:\"\",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},ld=e=>{let t=e.format;return{format:t,...ud,cacheKey:t}},dd=(e,t)=>{un(e.inputs),e.compute(id(\"GlobalAveragePool\",e.inputs[0],!0,t))},cd=(e,t,r,n)=>{let[o,i]=ed(t,n,r),a=`\n value = max(x_val, value);\n `,l=\"\",d=E(\"x\",t.dataType,t.dims.length),c=[\"rank\"],[m,u,h,w,y]=td(i,o);return m.push(...V(t.dims,i)),{name:e,shaderCache:{hint:`${n.cacheKey};${h};${w};${y}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(k.size(i)/64)},programUniforms:m}),getShaderSource:g=>rd(g,d,t.dims.length,i.length,o,a,l,t.dataType===10?-65504:-1e5,u,h,w,y)}},pd=(e,t)=>{un(e.inputs),e.compute(cd(\"MaxPool\",e.inputs[0],!1,t))},md=e=>{let t=e.storage_order,r=e.dilations,n=od(e);if(t!==0)throw new Error(\"column major storage order is not yet supported for MaxPool\");if(n.ceilMode!==0)throw new Error(\"using ceil() in shape computation is not yet supported for MaxPool\");let o={storageOrder:t,dilations:r,...n,cacheKey:\"\"};return{...o,cacheKey:yh(o)}},fd=e=>{let t=e.format;return{format:t,...ud,cacheKey:t}},hd=(e,t)=>{un(e.inputs),e.compute(cd(\"GlobalMaxPool\",e.inputs[0],!0,t))}});var _h,vh,bd,yd,wd=R(()=>{\"use strict\";te();oe();Ie();ae();_h=(e,t)=>{if(e.length<2||e.length>3)throw new Error(\"DequantizeLinear requires 2 or 3 inputs.\");if(e.length===3&&e[1].dims===e[2].dims)throw new Error(\"x-scale and x-zero-point must have the same shape.\");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error(\"x and x-zero-point must have the same data type.\");if(e[0].dataType===6&&e.length>2)throw new Error(\"In the case of dequantizing int32 there is no zero point.\");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error(\"scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.\");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error(\"x and x-zero-point must have the same data type.\");if(e[1].dims.length!==e[2].dims.length)throw new Error(\"scale and zero-point inputs must have the same rank.\");if(!e[1].dims.map((r,n)=>r===e[2].dims[n]).reduce((r,n)=>r&&n,!0))throw new Error(\"scale and zero-point inputs must have the same shape.\")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error(\"blockSize must be set only for block quantization.\");if(!e[1].dims.map((o,i)=>i===t.axis||o===e[0].dims[i]).reduce((o,i)=>o&&i,!0))throw new Error(\"For block qunatization, scale input shape to match the input shape except for the axis\");if(e[1].dims.length!==e[0].dims.length)throw new Error(\"For block qunatization the scale input rank must be the same as the x rank.\");let r=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(n-1)-1))throw new Error(\"blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].\")}},vh=(e,t)=>{let r=k.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,o=n===3,i=e[0].dims,a=e[1].dataType,l=k.size(i),d=n===3||n===2,c=d?[Math.ceil(k.size(e[0].dims)/4)]:e[0].dims,m=e[1].dims,u=e.length>2?e[2]:void 0,h=u?d?[Math.ceil(k.size(u.dims)/4)]:u.dims:void 0,w=m.length===0||m.length===1&&m[0]===1,y=w===!1&&m.length===1,g=ye(l),x=w&&(!d||g===4),$=x?g:1,v=x&&!d?g:1,S=E(\"input\",d?12:n,c.length,v),T=E(\"scale\",a,m.length),C=u?E(\"zero_point\",d?12:n,h.length):void 0,A=M(\"output\",a,i.length,$),P=[S,T];C&&P.push(C);let O=[c,m];u&&O.push(h);let U=[{type:12,data:l/$},{type:12,data:r},{type:12,data:t.blockSize},...V(...O,i)],L=j=>{let K=[{name:\"output_size\",type:\"u32\"},{name:\"axis\",type:\"u32\"},{name:\"block_size\",type:\"u32\"}];return`\n ${j.registerUniforms(K).declareVariables(...P,A)}\n ${j.mainStart()}\n ${j.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let output_indices = ${A.offsetToIndices(\"global_idx\")};\n\n // Set input x\n ${(()=>d?`\n let input = ${S.getByOffset(\"global_idx / 4\")};\n let x_vec = ${o?\"unpack4xI8(input)\":\"unpack4xU8(input)\"};\n let x_value = ${$===1?\"x_vec[global_idx % 4]\":\"x_vec\"};`:`let x_value = ${S.getByOffset(\"global_idx\")};`)()};\n\n // Set scale input\n ${(()=>w?`let scale_value= ${T.getByOffset(\"0\")}`:y?`\n let scale_index = ${A.indicesGet(\"output_indices\",\"uniforms.axis\")};\n let scale_value= ${T.getByOffset(\"scale_index\")};`:`\n var scale_indices: ${T.type.indices} = output_indices;\n let index = ${T.indicesGet(\"scale_indices\",\"uniforms.axis\")} / uniforms.block_size;\n ${T.indicesSet(\"scale_indices\",\"uniforms.axis\",\"index\")};\n let scale_value= ${T.getByIndices(\"scale_indices\")};`)()};\n\n // Set zero-point input\n ${(()=>C?w?d?`\n let zero_point_input = ${C.getByOffset(\"0\")};\n let zero_point_vec = ${o?\"unpack4xI8(zero_point_input)\":\"unpack4xU8(zero_point_input)\"};\n let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${C.getByOffset(\"0\")}`:y?d?`\n let zero_point_index = ${A.indicesGet(\"output_indices\",\"uniforms.axis\")};\n let zero_point_input = ${C.getByOffset(\"zero_point_index / 4\")};\n let zero_point_vec = ${o?\"unpack4xI8(zero_point_input)\":\"unpack4xU8(zero_point_input)\"};\n let zero_point_value = zero_point_vec[zero_point_index % 4]`:`\n let zero_point_index = ${A.indicesGet(\"output_indices\",\"uniforms.axis\")};\n let zero_point_value = ${C.getByOffset(\"zero_point_index\")};`:d?`\n let zero_point_offset = ${T.indicesToOffset(\"scale_indices\")};\n let zero_point_input = ${C.getByOffset(\"zero_point_offset / 4\")};\n let zero_point_vec = ${o?\"unpack4xI8(zero_point_input)\":\"unpack4xU8(zero_point_input)\"};\n let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${C.getByIndices(\"scale_indices\")};`:`let zero_point_value = ${d?o?\"i32\":\"u32\":S.type.value}(0);`)()};\n // Compute and write output\n ${A.setByOffset(\"global_idx\",`${A.type.value}(x_value - zero_point_value) * scale_value`)};\n }`};return{name:\"DequantizeLinear\",shaderCache:{hint:t.cacheKey,inputDependencies:C?[\"rank\",\"rank\",\"rank\"]:[\"rank\",\"rank\"]},getShaderSource:L,getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:Math.ceil(l/$/64),y:1,z:1},programUniforms:U})}},bd=(e,t)=>{_h(e.inputs,t),e.compute(vh(e.inputs,t))},yd=e=>re({axis:e.axis,blockSize:e.blockSize})});var $h,xh,_d,vd=R(()=>{\"use strict\";He();te();ae();$h=(e,t,r)=>{let n=e===t,o=et&&r>0;if(n||o||i)throw new Error(\"Range these inputs' contents are invalid.\")},xh=(e,t,r,n)=>{let o=Math.abs(Math.ceil((t-e)/r)),i=[o],a=o,l=[{type:12,data:a},{type:n,data:e},{type:n,data:r},...V(i)],d=c=>{let m=M(\"output\",n,i.length),u=m.type.value,h=[{name:\"outputSize\",type:\"u32\"},{name:\"start\",type:u},{name:\"delta\",type:u}];return`\n ${c.registerUniforms(h).declareVariables(m)}\n ${c.mainStart()}\n ${c.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n output[global_idx] = uniforms.start + ${u}(global_idx) * uniforms.delta;\n }`};return{name:\"Range\",shaderCache:{hint:`${n}`},getShaderSource:d,getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l})}},_d=e=>{let t=0,r=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),ve.webgpu.validateInputContent&&$h(t,r,n),e.compute(xh(t,r,n,e.inputs[0].dataType),{inputs:[]})}});var Sh,Th,Ih,Ch,Ah,kh,Eh,Ph,zh,Oh,Dh,$d,Bh,Mh,Rh,Uh,Vh,xd,Sd,Td=R(()=>{\"use strict\";te();oe();Ie();ae();Sh=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error(\"Resize requires scales input values to be positive\")})),e.length>0){if(t.mode===\"linear\"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and\n one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode===\"cubic\"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error(\"Resize requires scales input size to be 2 or 4 for cubic mode\")}},Th=(e,t,r)=>{t.every(o=>o>=0&&o{throw new Error(\"Resize requires axes input values to be positive and less than rank\")}));let n=new Array(r).fill(1);return t.forEach((o,i)=>n[o]=e[i]),n},Ih=(e,t,r,n,o,i)=>{let[a,l,d]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],c=e[0].dims.length;if(a>0&&e.length>a&&e[a].dims.length>0)e[a].getFloat32Array().forEach(m=>i.push(m));else if(t.coordinateTransformMode===\"tf_crop_and_resize\")throw new Error(\"Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize\");if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0){if(e[l].getFloat32Array().forEach(m=>n.push(m)),n.length!==0&&n.length!==c&&r>=18&&n.length!==t.axes.length)throw new Error(\"Resize requires scales input size to be same as input rank or axes size for opset 18 and up\");Sh(n,t),t.axes.length>0&&Th(n,t.axes,c).forEach((m,u)=>n[u]=m)}if(d>0&&e.length>d&&e[d].dims.length===1&&e[d].dims[0]>0&&(e[d].getBigInt64Array().forEach(m=>o.push(Number(m))),o.length!==0&&o.length!==c&&r>=18&&o.length!==t.axes.length))throw new Error(\"Resize requires sizes input size to be same as input rank or axes size for opset 18 and up\");if(t.axes.length>0){if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires \"scales\" input size to be of axes rank when axes attributes is specified');if(o.length!==0&&o.length!==t.axes.length)throw new Error('Resize requires \"sizes\" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<\"u\"&&typeof o<\"u\"&&n.length>0&&o.length>c)throw new Error(\"Resize requires only of scales or sizes to be specified\")},Ch=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,\n lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case\"asymmetric\":return`return ${t}(xResized) / ${t}(xScale);`;case\"pytorch_half_pixel\":return`if (lengthResized > 1) {\n return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;\n } else {\n return 0.0;\n }`;case\"tf_half_pixel_for_nn\":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case\"align_corners\":return`if (lengthResized == 1) {\n return 0.0;\n } else {\n // The whole part and the fractional part are calculated separately due to inaccuracy of floating\n // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an\n // offset-by-one error later in floor().\n let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1));\n let fract =\n ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1);\n return whole + fract;\n }`;case\"tf_crop_and_resize\":return`if (lengthResized > 1) {\n return ${t}(roiStart) * ${t}(lengthOriginal - 1) +\n (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /\n ${t}(lengthResized - 1);\n } else {\n return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);\n }`;case\"half_pixel_symmetric\":return`const outputWidth = ${t}xScale * ${t}(lengthResized);\n const adjustment = ${t}(lengthResized) / outputWidth;\n const center = ${t}(lengthOriginal) / 2;\n const offset = center * (1 - adjustment);\n return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case\"half_pixel\":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+\"}\",Ah=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case\"round_prefer_ceil\":return\"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }\";case\"floor\":return\"return floor(xOriginal);\";case\"ceil\":return\"return ceil(xOriginal);\";case\"round_prefer_floor\":return\"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }\";case\"simple\":default:if(t<11)return\"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }\";throw new Error(`Nearest mode ${e} is not supported`)}})()+\"}\",kh=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),o=e.length===0?n:e.slice();return t.length>0?(t.forEach((i,a)=>{n[i]=o[a],n[a+r]=o[t.length+a]}),n):o},Eh=(e,t,r,n)=>{let o=[];if(r.length>0)if(n.length>0){if(e.forEach(i=>o.push(i)),Math.max(...n)>e.length)throw new Error(\"axes is out of bound\");n.forEach((i,a)=>o[i]=r[a])}else r.forEach(i=>o.push(i));else{if(t.length===0)throw new Error(\"Resize requires either scales or sizes.\");o=e.map((i,a)=>Math.round(i*t[a]))}return o},Ph=(e,t,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case\"not_larger\":return r.axes.length>0?Math.min(...r.axes.map(i=>t[i]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case\"not_smaller\":return r.axes.length>0?Math.max(...r.axes.map(i=>t[i]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let o=e.slice();return r.axes.length>0?(r.axes.forEach(i=>t[i]=n),r.axes.forEach(i=>o[i]=Math.round(e[i]*t[i]))):(t.fill(n,0,t.length),o.forEach((i,a)=>o[a]=Math.round(i*t[a]))),o},zh=(e,t,r,n,o)=>`\n fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> {\n var original_indices: array<${e.type.value}, ${r.length}>;\n for (var i:u32 = 0; i < ${r.length}; i++) {\n var output_index = ${e.indicesGet(\"output_indices\",\"i\")};\n var scale = ${F(\"uniforms.scales\",\"i\",n)};\n var roi_low = ${F(\"uniforms.roi\",\"i\",o)};\n var roi_hi = ${F(\"uniforms.roi\",`i + ${t.length}`,o)};\n if (scale == 1.0) {\n original_indices[i] = ${e.type.value}(output_index);\n } else {\n var input_shape_i = ${F(\"uniforms.input_shape\",\"i\",t.length)};\n var output_shape_i = ${F(\"uniforms.output_shape\",\"i\",r.length)};\n original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n }\n }\n return original_indices;\n }`,Oh=(e,t,r,n,o,i,a)=>`\n fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n for (var i:u32 = 0; i < ${n.length}; i++) {\n var output_index = ${t.indicesGet(\"output_indices\",\"i\")};\n var input_index: u32;\n var scale = ${F(\"uniforms.scales\",\"i\",o)};\n if (scale == 1.0) {\n input_index = output_index;\n } else {\n var roi_low = ${F(\"uniforms.roi\",\"i\",i)};\n var roi_hi = ${F(\"uniforms.roi\",`i + ${r.length}`,i)};\n var input_shape_i = ${F(\"uniforms.input_shape\",\"i\",r.length)};\n var output_shape_i = ${F(\"uniforms.output_shape\",\"i\",n.length)};\n var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n if (!${a} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {\n if (original_idx < 0) {\n input_index = 0;\n } else if (original_idx > ${t.type.value}(input_shape_i - 1)) {\n input_index = input_shape_i - 1;\n } else {\n input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));\n }\n } else {\n input_index = u32(original_idx);\n }\n }\n ${e.indicesSet(\"input_indices\",\"i\",\" input_index\")}\n }\n return input_indices;\n }`,Dh=(e,t)=>`\n fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {\n for (var i:u32 = 0; i < ${t.length}; i++) {\n var input_index = ${e.indicesGet(\"input_indices\",\"i\")};\n if (input_index < 0 || input_index >= ${F(\"uniforms.input_shape\",\"i\",t.length)}) {\n return false;\n }\n }\n return true;\n }`,$d=(e,t,r,n)=>e.rank>n?`\n ${e.indicesSet(\"input_indices\",t,\"channel\")};\n ${e.indicesSet(\"input_indices\",r,\"batch\")};\n`:\"\",Bh=(e,t,r,n,o)=>{let[a,l,d,c]=r.length===2?[-1,0,1,-1]:[0,2,3,1],m=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${m} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet(\"input_indices\",l,`max(0, min(row, ${r[l]} - 1))`)};\n ${e.indicesSet(\"input_indices\",d,`max(0, min(col, ${r[d]} - 1))`)};\n ${$d(e,c,a,2)}\n return ${e.getByIndices(\"input_indices\")};\n }\n\n fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${m} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var row:${m} = originalIndices[${l}];\n var col:${m} = originalIndices[${d}];\n ${n?`if (row < 0 || row > (${r[l]} - 1) || col < 0 || col > (${r[d]} - 1)) {\n return ${o};\n }`:\"\"};\n row = max(0, min(row, ${r[l]} - 1));\n col = max(0, min(col, ${r[d]} - 1));\n var row1: u32 = u32(row);\n var col1: u32 = u32(col);\n var row2: u32 = u32(row + 1);\n var col2: u32 = u32(col + 1);\n var channel: u32 = ${r.length>2?`u32(originalIndices[${c}])`:\"0\"};\n var batch: u32 = ${r.length>2?`u32(originalIndices[${a}])`:\"0\"};\n var x11: ${m} = getInputValue(batch, channel, row1, col1);\n var x12: ${m} = getInputValue(batch, channel, row1, col2);\n var x21: ${m} = getInputValue(batch, channel, row2, col1);\n var x22: ${m} = getInputValue(batch, channel, row2, col2);\n var dx1: ${m} = abs(row - ${m}(row1));\n var dx2: ${m} = abs(${m}(row2) - row);\n var dy1: ${m} = abs(col - ${m}(col1));\n var dy2: ${m} = abs(${m}(col2) - col);\n if (row1 == row2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (col1 == col2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);\n }`},Mh=(e,t,r,n,o,i,a,l,d,c)=>{let m=r.length===2,u=!0,[h,w]=m?[0,1]:u?[2,3]:[1,2],y=e.type.value,g=x=>{let $=x===h?\"row\":\"col\";return`\n fn ${$}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${y} {\n var output_index = ${t.indicesGet(\"output_indices\",x)};\n var originalIdx: ${y} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[x]},\n ${n[x]}, ${r[x]}, ${i[x]}, ${i[x]} + ${r.length});\n var fractOriginalIdx: ${y} = originalIdx - floor(originalIdx);\n var coefs = getCubicInterpolationCoefs(fractOriginalIdx);\n\n if (${l} && (originalIdx < 0 || originalIdx > (${r[x]} - 1))) {\n return ${d};\n }\n var data: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0);\n for (var i: i32 = -1; i < 3; i++) {\n var ${$}: ${y} = originalIdx + ${y}(i);\n if (${$} < 0 || ${$} >= ${r[x]}) {\n ${(()=>c?`coefs[i + 1] = 0.0;\n continue;`:l?`return ${d};`:`${$} = max(0, min(${$}, ${r[x]} - 1));`)()};\n }\n var input_indices_copy: ${e.type.indices} = input_indices;\n ${e.indicesSet(\"input_indices_copy\",x,`u32(${$})`)};\n data[i + 1] = ${x===h?e.getByIndices(\"input_indices_copy\"):\"rowCubicInterpolation(input_indices_copy, output_indices)\"};\n }\n return cubicInterpolation1D(data, coefs);\n }`};return`\n ${g(h)};\n ${g(w)};\n fn getCubicInterpolationCoefs(s: ${y}) -> array<${y}, 4> {\n var absS = abs(s);\n var coeffs: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0);\n var oneMinusAbsS: ${y} = 1.0 - absS;\n var twoMinusAbsS: ${y} = 2.0 - absS;\n var onePlusAbsS: ${y} = 1.0 + absS;\n coeffs[0] = ((${a} * onePlusAbsS - 5 * ${a}) * onePlusAbsS + 8 * ${a}) * onePlusAbsS - 4 * ${a};\n coeffs[1] = ((${a} + 2) * absS - (${a} + 3)) * absS * absS + 1;\n coeffs[2] = ((${a} + 2) * oneMinusAbsS - (${a} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;\n coeffs[3] = ((${a} * twoMinusAbsS - 5 * ${a}) * twoMinusAbsS + 8 * ${a}) * twoMinusAbsS - 4 * ${a};\n return coeffs;\n }\n\n fn cubicInterpolation1D(x: array<${y}, 4>, coefs: array<${y}, 4>) -> ${y} {\n var coefsSum: ${y} = coefs[0] + coefs[1] + coefs[2] + coefs[3];\n return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;\n }\n\n fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${y} {\n var input_indices: ${e.type.indices} = output_indices;\n return colCubicInterpolation(input_indices, output_indices);\n }\n `},Rh=(e,t,r,n,o)=>{let[a,l,d,c,m]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],u=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${u} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet(\"input_indices\",l,`max(0, min(depth, ${r[l]} - 1))`)};\n ${e.indicesSet(\"input_indices\",d,`max(0, min(height, ${r[d]} - 1))`)};\n ${e.indicesSet(\"input_indices\",c,`max(0, min(width, ${r[c]} - 1))`)};\n ${$d(e,m,a,3)}\n return ${e.getByIndices(\"input_indices\")};\n }\n\n fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${u} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var depth:${u} = originalIndices[${l}];\n var height:${u} = originalIndices[${d}];\n var width:${u} = originalIndices[${c}];\n ${n?`if (depth < 0 || depth > (${r[l]} - 1) || height < 0 || height > (${r[d]} - 1) || width < 0 || (width > ${r[c]} - 1)) {\n return ${o};\n }`:\"\"};\n\n depth = max(0, min(depth, ${r[l]} - 1));\n height = max(0, min(height, ${r[d]} - 1));\n width = max(0, min(width, ${r[c]} - 1));\n var depth1: u32 = u32(depth);\n var height1: u32 = u32(height);\n var width1: u32 = u32(width);\n var depth2: u32 = u32(depth + 1);\n var height2: u32 = u32(height + 1);\n var width2: u32 = u32(width + 1);\n var channel: u32 = ${r.length>3?`u32(originalIndices[${m}])`:\"0\"};\n var batch: u32 = ${r.length>3?`u32(originalIndices[${a}])`:\"0\"};\n\n var x111: ${u} = getInputValue(batch, channel, depth1, height1, width1);\n var x112: ${u} = getInputValue(batch, channel, depth1, height1, width2);\n var x121: ${u} = getInputValue(batch, channel, depth1, height2, width1);\n var x122: ${u} = getInputValue(batch, channel, depth1, height2, width2);\n var x211: ${u} = getInputValue(batch, channel, depth2, height1, width1);\n var x212: ${u} = getInputValue(batch, channel, depth2, height1, width2);\n var x221: ${u} = getInputValue(batch, channel, depth2, height2, width1);\n var x222: ${u} = getInputValue(batch, channel, depth2, height2, width2);\n var dx1: ${u} = abs(depth - ${u}(depth1));\n var dx2: ${u} = abs(${u}(depth2) - depth);\n var dy1: ${u} = abs(height - ${u}(height1));\n var dy2: ${u} = abs(${u}(height2) - height);\n var dz1: ${u} = abs(width - ${u}(width1));\n var dz2: ${u} = abs(${u}(width2) - width);\n if (depth1 == depth2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (height1 == height2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n if (width1 == width2) {\n dz1 = 0.5;\n dz2 = 0.5;\n }\n return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +\n x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);\n }`},Uh=(e,t,r,n,o,i)=>{let a=e.dims,l=kh(i,t.axes,a.length),d=Eh(a,n,o,t.axes),c=n.slice();n.length===0&&(c=a.map((v,S)=>v===0?1:d[S]/v),t.keepAspectRatioPolicy!==\"stretch\"&&(d=Ph(a,c,t)));let m=M(\"output\",e.dataType,d.length),u=E(\"input\",e.dataType,a.length),h=k.size(d),w=a.length===d.length&&a.every((v,S)=>v===d[S]),y=t.coordinateTransformMode===\"tf_crop_and_resize\",g=t.extrapolationValue,x=u.type.value,$=v=>`\n ${w?\"\":`\n ${Ch(t.coordinateTransformMode,x)};\n ${(()=>{switch(t.mode){case\"nearest\":return`\n ${Dh(u,a)};\n ${Ah(t.nearestMode,r,x)};\n ${Oh(u,m,a,d,c.length,l.length,y)};\n `;case\"linear\":return`\n ${zh(m,a,d,c.length,l.length)};\n ${(()=>{if(a.length===2||a.length===4)return`${Bh(u,m,a,y,g)}`;if(a.length===3||a.length===5)return`${Rh(u,m,a,y,g)}`;throw Error(\"Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.\")})()};\n `;case\"cubic\":return`\n ${(()=>{if(a.length===2||a.length===4)return`${Mh(u,m,a,d,c,l,t.cubicCoeffA,y,t.extrapolationValue,t.excludeOutside)}`;throw Error(\"Cubic mode only supports input dims 2 and 4 are supported in linear mode.\")})()};\n `;default:throw Error(\"Invalid resize mode\")}})()};\n `}\n ${v.registerUniform(\"output_size\",\"u32\").registerUniform(\"scales\",\"f32\",c.length).registerUniform(\"roi\",\"f32\",l.length).declareVariables(u,m)}\n ${v.mainStart()}\n ${v.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n ${w?\"output[global_idx] = input[global_idx];\":`\n let output_indices = ${m.offsetToIndices(\"global_idx\")};\n var input_indices: ${u.type.indices};\n ${(()=>{switch(t.mode){case\"nearest\":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);\n if (checkInputIndices(input_indices)) {\n output[global_idx] = ${u.getByIndices(\"input_indices\")};\n } else {\n output[global_idx] = ${t.extrapolationValue};\n }`;case\"linear\":return`output[global_idx] = ${a.length===2||a.length===4?\"bilinearInterpolation\":\"trilinearInterpolation\"}(output_indices);`;case\"cubic\":return\"output[global_idx] = bicubicInterpolation(output_indices);\";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};\n`}\n }`;return{name:\"Resize\",shaderCache:{hint:`${t.cacheKey}|${r}|${c.length>0?c:\"\"}|${o.length>0?o:\"\"}|${l.length>0?l:\"\"}|${w}|${a}`,inputDependencies:[\"rank\"]},getShaderSource:$,getRunData:()=>({outputs:[{dims:d,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:[{type:12,data:h},{type:1,data:c},{type:1,data:l},...V(a,d)]})}},Vh=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},xd=(e,t)=>{let r=[],n=[],o=[],i=Vh(e);if(t.antialias!==0)throw Error(\"Only default value (0) for Antialias attribute is supported\");Ih(e.inputs,t,i,r,n,o),e.compute(Uh(e.inputs[0],t,i,r,n,o),{inputs:[0]})},Sd=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,o=e.cubicCoeffA,i=e.excludeOutside!==0,a=e.extrapolationValue,l=e.keepAspectRatioPolicy,d=e.mode,c=e.nearestMode===\"\"?\"simple\":e.nearestMode;return re({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:o,excludeOutside:i,extrapolationValue:a,keepAspectRatioPolicy:l,mode:d,nearestMode:c})}});var Nh,Wh,Id,Cd=R(()=>{\"use strict\";te();oe();Ie();ae();Nh=(e,t)=>{let[r,n,o,i]=e,{numHeads:a,rotaryEmbeddingDim:l}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!k.areEqual(n.dims,[])&&!k.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(!k.areEqual(o.dims,i.dims))throw new Error(\"Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape\");if(l>0&&a===0)throw new Error(\"num_heads must be provided if rotary_embedding_dim is specified\");let d=r.dims[0],c=r.dims[r.dims.length-2],m=o.dims[0],u=k.sizeFromDimension(r.dims,1)/c,h=l===0?o.dims[1]*2:u/a;if(l>h)throw new Error(\"rotary_embedding_dim must be less than or equal to head_size\");if(n.dims.length===2){if(d!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(c!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(h/2!==o.dims[1]&&l/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(c>m)throw new Error(\"Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported\")},Wh=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:o,scale:i}=t,a=e[0].dims[0],l=k.sizeFromDimension(e[0].dims,1),d=e[0].dims[e[0].dims.length-2],c=l/d,m=e[2].dims[1],u=o===0?m*2:c/n,h=new Array(a,d,c/u,u-m),w=k.computeStrides(h),y=[{type:1,data:i},{type:12,data:h},{type:12,data:w},...e[0].dims.length===3?new Array({type:12,data:[l,c,u,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[l,u,d*u,1]}):[],...V(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],g=x=>{let $=E(\"input\",e[0].dataType,e[0].dims.length),v=E(\"position_ids\",e[1].dataType,e[1].dims.length),S=E(\"cos_cache\",e[2].dataType,e[2].dims.length),T=E(\"sin_cache\",e[3].dataType,e[3].dims.length),C=M(\"output\",e[0].dataType,e[0].dims.length);return x.registerUniforms([{name:\"scale\",type:\"f32\"},{name:\"global_shape\",type:\"u32\",length:h.length},{name:\"global_strides\",type:\"u32\",length:w.length},{name:\"input_output_strides\",type:\"u32\",length:w.length}]),`\n ${x.declareVariables($,v,S,T,C)}\n\n ${x.mainStart(Ct)}\n let half_rotary_emb_dim = uniforms.${S.name}_shape[1];\n let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;\n let size = uniforms.global_shape[0] * uniforms.global_strides[0];\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(\"size\")}\n\n if (bsnh[3] < half_rotary_emb_dim) {\n let position_ids_idx =\n ${v.broadcastedIndicesToOffset(\"bsnh.xy\",M(\"\",v.type.tensor,2))};\n let position_id =\n u32(${v.getByOffset(\"position_ids_idx\")}) + select(0, bsnh[1], position_ids_idx == 0);\n let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r});\n let j = i + select(half_rotary_emb_dim, 1, ${r});\n let re = ${$.getByOffset(\"i\")} * ${S.get(\"position_id\",\"bsnh[3]\")} -\n ${$.getByOffset(\"j\")} * ${T.get(\"position_id\",\"bsnh[3]\")};\n ${C.setByOffset(\"i\",\"re\")}\n let im = ${$.getByOffset(\"i\")} * ${T.get(\"position_id\",\"bsnh[3]\")} +\n ${$.getByOffset(\"j\")} * ${S.get(\"position_id\",\"bsnh[3]\")};\n ${C.setByOffset(\"j\",\"im\")}\n } else {\n let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;\n ${C.setByOffset(\"k\",$.getByOffset(\"k\"))}\n }\n }`};return{name:\"RotaryEmbedding\",shaderCache:{hint:re({interleaved:r}).cacheKey,inputDependencies:[\"rank\",\"rank\",\"rank\",\"rank\"]},getShaderSource:g,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k.size(h)/Ct)},programUniforms:y})}},Id=(e,t)=>{Nh(e.inputs,t),e.compute(Wh(e.inputs,t))}});var Lh,Gh,Ad,kd=R(()=>{\"use strict\";te();oe();ae();Lh=e=>{if(!e||e.length<3)throw new Error(\"layerNorm requires at least 3 inputs.\");let t=e[0],r=e[1],n=e[2];if(t.dataType!==r.dataType||t.dataType!==n.dataType)throw new Error(\"All inputs must have the same data type\");if(t.dims.length!==3&&t.dims.length!==2)throw new Error(\"Input must be 2D or 3D\");if(r.dims.length!==3&&r.dims.length!==2)throw new Error(\"Skip must be 2D or 3D\");let o=t.dims[t.dims.length-1],i=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==o)throw new Error(\"Skip must have the same hidden size as input\");if(r.dims[r.dims.length-2]!==i)throw new Error(\"Skip must have the same sequence length as input\");if(n.dims.length!==1)throw new Error(\"Gamma must be 1D\");if(n.dims[n.dims.length-1]!==o)throw new Error(\"Gamma must have the same hidden size as input\");if(e.length>3){let a=e[3];if(a.dims.length!==1)throw new Error(\"Beta must be 1D\");if(a.dims[a.dims.length-1]!==o)throw new Error(\"Beta must have the same hidden size as input\")}if(e.length>4){let a=e[4];if(a.dims.length!==1)throw new Error(\"Bias must be 1D\");if(a.dims[a.dims.length-1]!==o)throw new Error(\"Bias must have the same hidden size as input\")}},Gh=(e,t,r,n)=>{let o=t.simplified,i=e[0].dims,a=k.size(i),l=i,d=a,c=i.slice(-1)[0],m=n?i.slice(0,-1).concat(1):[],u=!o&&e.length>3,h=e.length>4,w=n&&r>1,y=n&&r>2,g=r>3,x=64,$=ye(c),v=[{type:12,data:d},{type:12,data:$},{type:12,data:c},{type:1,data:t.epsilon}],S=C=>{let A=[{name:\"output_size\",type:\"u32\"},{name:\"components\",type:\"u32\"},{name:\"hidden_size\",type:\"u32\"},{name:\"epsilon\",type:\"f32\"}],P=[E(\"x\",e[0].dataType,e[0].dims,$),E(\"skip\",e[1].dataType,e[1].dims,$),E(\"gamma\",e[2].dataType,e[2].dims,$)];u&&P.push(E(\"beta\",e[3].dataType,e[3].dims,$)),h&&P.push(E(\"bias\",e[4].dataType,e[4].dims,$)),P.push(M(\"output\",e[0].dataType,l,$)),w&&P.push(M(\"mean_output\",1,m)),y&&P.push(M(\"inv_std_output\",1,m)),g&&P.push(M(\"input_skip_bias_sum\",e[0].dataType,l,$));let O=me(e[0].dataType),U=me(1,$);return`\n\n ${C.registerUniforms(A).declareVariables(...P)}\n var sum_shared : array<${U}, ${x}>;\n var sum_squared_shared : array<${U}, ${x}>;\n\n ${C.mainStart([x,1,1])}\n let ix = local_id.x;\n let iy = global_id.x / ${x};\n\n let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;\n var stride = hidden_size_vectorized / ${x};\n let offset = ix * stride + iy * hidden_size_vectorized;\n let offset1d = stride * ix;\n if (ix == ${x-1}) {\n stride = hidden_size_vectorized - stride * ix;\n }\n for (var i: u32 = 0; i < stride; i++) {\n let skip_value = skip[offset + i];\n let bias_value = ${h?\"bias[offset1d + i]\":O+\"(0.0)\"};\n let input_value = x[offset + i];\n let value = input_value + skip_value + bias_value;\n ${g?\"input_skip_bias_sum[offset + i] = value;\":\"\"}\n output[offset + i] = value;\n let f32_value = ${At(O,$,\"value\")};\n sum_shared[ix] += f32_value;\n sum_squared_shared[ix] += f32_value * f32_value;\n }\n workgroupBarrier();\n\n var reduce_size : u32 = ${x};\n for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) {\n reduce_size = curr_size + (reduce_size & 1);\n if (ix < curr_size) {\n sum_shared[ix] += sum_shared[ix + reduce_size];\n sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size];\n }\n workgroupBarrier();\n }\n\n let sum = sum_shared[0];\n let square_sum = sum_squared_shared[0];\n let mean = ${Ke(\"sum\",$)} / f32(uniforms.hidden_size);\n let inv_std_dev = inverseSqrt(${Ke(\"square_sum\",$)} / f32(uniforms.hidden_size) ${o?\"\":\"- mean * mean\"} + uniforms.epsilon);\n ${w?\"mean_output[global_idx] = mean;\":\"\"}\n ${y?\"inv_std_output[global_idx] = inv_std_dev;\":\"\"}\n\n for (var i: u32 = 0; i < stride; i++) {\n output[offset + i] = (output[offset + i] ${o?\"\":`- ${O}(mean)`}) *\n ${O}(inv_std_dev) * gamma[offset1d + i]\n ${u?\"+ beta[offset1d + i]\":\"\"};\n }\n }`},T=[{dims:l,dataType:e[0].dataType}];return r>1&&T.push({dims:m,dataType:1}),r>2&&T.push({dims:m,dataType:1}),r>3&&T.push({dims:i,dataType:e[0].dataType}),{name:\"SkipLayerNormalization\",shaderCache:{hint:`${$};${w};${y};${g}`,inputDependencies:e.map((C,A)=>\"type\")},getShaderSource:S,getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(d/c)},programUniforms:v})}},Ad=(e,t)=>{Lh(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(Gh(e.inputs,t,e.outputCount,!1),{outputs:n})}});var Hh,ln,Fh,Ed,qh,jh,Pd,zd,Od=R(()=>{\"use strict\";te();oe();Ie();ae();Hh=(e,t)=>{if(!e||e.length<1)throw new Error(\"too few inputs\");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error(\"axes, starts and ends must have the same length\")}else if(t.starts.length!==t.ends.length)throw new Error(\"starts and ends must have the same length\");e.slice(1).forEach((r,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},ln=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>r.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>r.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},Fh=(e,t)=>{if(e.length>1){let r=ln(e,1),n=ln(e,2),o=ln(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),re({starts:r,ends:n,axes:o})}else return t},Ed=(e,t,r,n,o)=>{let i=e;return e<0&&(i+=r[n[t]]),o[t]<0?Math.max(0,Math.min(i,r[n[t]]-1)):Math.max(0,Math.min(i,r[n[t]]))},qh=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n var carry = 0u;\n for (var i = ${r.length}; i >= 0; i--) {\n let input_shape_i = ${F(\"uniforms.input_shape\",\"i\",r.length)};\n let steps_i = ${F(\"uniforms.steps\",\"i\",r.length)};\n let signs_i = ${F(\"uniforms.signs\",\"i\",r.length)};\n let starts_i = ${F(\"uniforms.starts\",\"i\",r.length)};\n var output_index = ${t.indicesGet(\"output_indices\",\"i\")};\n var input_index = output_index * steps_i + starts_i + carry;\n carry = input_index / input_shape_i;\n input_index = input_index % input_shape_i;\n if (signs_i < 0) {\n input_index = input_shape_i - input_index - 1u + starts_i;\n }\n ${e.indicesSet(\"input_indices\",\"i\",\"input_index\")};\n }\n return input_indices;\n }`,jh=(e,t)=>{let r=e[0].dims,n=k.size(r),o=t.axes.length>0?k.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],i=ln(e,4);i.forEach($=>$!==0||(()=>{throw new Error(\"step cannot be 0\")})),i.length===0&&(i=Array(o.length).fill(1));let a=t.starts.map(($,v)=>Ed($,v,r,o,i)),l=t.ends.map(($,v)=>Ed($,v,r,o,i));if(o.length!==a.length||o.length!==l.length)throw new Error(\"start, ends and axes should have the same number of elements\");if(o.length!==r.length)for(let $=0;$Math.sign($));i.forEach(($,v,S)=>{if($<0){let T=(l[v]-a[v])/$,C=a[v],A=C+T*i[v];a[v]=A,l[v]=C,S[v]=-$}});let c=r.slice(0);o.forEach(($,v)=>{c[$]=Math.ceil((l[$]-a[$])/i[$])});let m={dims:c,dataType:e[0].dataType},u=M(\"output\",e[0].dataType,c.length),h=E(\"input\",e[0].dataType,e[0].dims.length),w=k.size(c),y=[{name:\"outputSize\",type:\"u32\"},{name:\"starts\",type:\"u32\",length:a.length},{name:\"signs\",type:\"i32\",length:d.length},{name:\"steps\",type:\"u32\",length:i.length}],g=[{type:12,data:w},{type:12,data:a},{type:6,data:d},{type:12,data:i},...V(e[0].dims,c)],x=$=>`\n ${$.registerUniforms(y).declareVariables(h,u)}\n ${qh(h,u,r)}\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n let output_indices = ${u.offsetToIndices(\"global_idx\")};\n let input_indices = calculateInputIndices(output_indices);\n ${u.setByOffset(\"global_idx\",h.getByIndices(\"input_indices\"))}\n }`;return{name:\"Slice\",shaderCache:{hint:`${d.length}_${a.length}_${i.length}`,inputDependencies:[\"rank\"]},getShaderSource:x,getRunData:()=>({outputs:[m],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:g})}},Pd=(e,t)=>{Hh(e.inputs,t);let r=Fh(e.inputs,t);e.compute(jh(e.inputs,r),{inputs:[0]})},zd=e=>{let t=e.starts,r=e.ends,n=e.axes;return re({starts:t,ends:r,axes:n})}});var Kh,Yh,Dd,Bd,Md=R(()=>{\"use strict\";te();oe();Ie();ut();ae();Kh=e=>{if(!e||e.length!==1)throw new Error(\"Softmax op requires 1 input.\")},Yh=(e,t)=>{let r=e.inputs[0],n=r.dims,o=k.size(n),i=n.length,a=k.normalizeAxis(t.axis,i),l=aO),c[a]=i-1,c[i-1]=a,d=e.compute(Pe(r,c),{inputs:[r],outputs:[-1]})[0]):d=r;let m=d.dims,u=m[i-1],h=o/u,w=ye(u),y=u/w,g=64;h===1&&(g=256);let x=(P,O)=>O===4?`max(max(${P}.x, ${P}.y), max(${P}.z, ${P}.w))`:O===2?`max(${P}.x, ${P}.y)`:O===3?`max(max(${P}.x, ${P}.y), ${P}.z)`:P,$=E(\"x\",d.dataType,d.dims,w),v=M(\"result\",d.dataType,d.dims,w),S=$.type.value,T=me(d.dataType)===\"f32\"?`var threadMax = ${S}(-3.402823e+38f);`:`var threadMax = ${S}(-65504.0h);`,C=P=>`\n var rowMaxShared : ${S};\n var rowSumShared : ${S};\n var threadShared : array<${S}, ${g}>;\n\n fn getValue(row: i32, col: i32, row_stride: i32) -> ${S} {\n let index = row * row_stride + col;\n return x[index];\n }\n\n fn setValue(row: i32, col: i32, row_stride: i32, value: ${S}) {\n let index = row * row_stride + col;\n result[index] = value;\n }\n ${P.registerUniform(\"packedCols\",\"i32\").declareVariables($,v)}\n ${P.mainStart(g)}\n let gindex = i32(global_idx);\n let lindex = i32(local_idx);\n const wg = ${g};\n let row = gindex / wg;\n let cols = uniforms.packedCols;\n let row_stride : i32 = uniforms.packedCols;\n\n // find the rows max\n ${T}\n for (var col = lindex; col < cols; col += wg) {\n let value = getValue(row, col, row_stride);\n threadMax = max(threadMax, value);\n }\n if (lindex < cols) {\n threadShared[lindex] = threadMax;\n }\n workgroupBarrier();\n\n var reduceSize = min(cols, wg);\n for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {\n reduceSize = currSize + (reduceSize & 1);\n if (lindex < currSize) {\n threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowMaxShared = ${S}(${x(\"threadShared[0]\",w)});\n }\n workgroupBarrier();\n\n // find the rows sum\n var threadSum = ${S}(0.0);\n for (var col = lindex; col < cols; col += wg) {\n let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);\n threadSum += subExp;\n }\n threadShared[lindex] = threadSum;\n workgroupBarrier();\n\n for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {\n if (lindex < currSize) {\n threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowSumShared = ${S}(${Ke(\"threadShared[0]\",w)});\n }\n workgroupBarrier();\n\n // calculate final value for each element in the row\n for (var col = lindex; col < cols; col += wg) {\n let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;\n setValue(row, col, row_stride, value);\n }\n }`,A=e.compute({name:\"Softmax\",shaderCache:{hint:`${w};${g}`,inputDependencies:[\"type\"]},getRunData:()=>({outputs:[{dims:m,dataType:d.dataType}],dispatchGroup:{x:h},programUniforms:[{type:6,data:y}]}),getShaderSource:C},{inputs:[d],outputs:[l?-1:0]})[0];l&&e.compute(Pe(A,c),{inputs:[A]})},Dd=(e,t)=>{Kh(e.inputs),Yh(e,t)},Bd=e=>re({axis:e.axis})});var Rd,Zh,Xh,Qh,Ud,Vd=R(()=>{\"use strict\";te();oe();ae();Rd=e=>Array.from(e.getBigInt64Array(),Number),Zh=e=>{if(!e||e.length!==2)throw new Error(\"Tile requires 2 inputs.\");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error(\"Tile only support float, float16, int32, and uint32 data types\");if(e[1].dataType!==7)throw new Error(\"Tile `repeats` input should be of int64 data type\");if(e[1].dims.length!==1)throw new Error(\"Tile `repeats` input should be 1-D\");if(Rd(e[1]).length!==e[0].dims.length)throw new Error(\"Tile `repeats` input should have same number of elements as rank of input data tensor\")},Xh=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??Rd(e[1]),o=Xh(r,n),i=k.size(o),a=e[0].dataType,l=E(\"input\",a,r.length),d=M(\"output\",a,o.length),c=m=>`\n const inputShape = ${l.indices(...r)};\n ${m.registerUniform(\"output_size\",\"u32\").declareVariables(l,d)}\n ${m.mainStart()}\n ${m.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let output_indices = ${d.offsetToIndices(\"global_idx\")};\n var input_indices: ${l.type.indices};\n for (var i = 0; i < ${r.length}; i++) {\n let input_dim_i = ${l.indicesGet(\"uniforms.input_shape\",\"i\")};\n let input_dim_value = ${d.indicesGet(\"output_indices\",\"i\")} % input_dim_i;\n\n ${l.indicesSet(\"input_indices\",\"i\",\"input_dim_value\")}\n }\n ${d.setByOffset(\"global_idx\",l.getByIndices(\"input_indices\"))}\n }`;return{name:\"Tile\",shaderCache:{hint:`${n}`,inputDependencies:[\"rank\"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...V(e[0].dims,o)]}),getShaderSource:c}},Ud=e=>{Zh(e.inputs),e.compute(Qh(e.inputs),{inputs:[0]})}});var Jh,eg,Nd,Wd=R(()=>{\"use strict\";te();oe();ae();Jh=(e,t,r,n,o)=>{let i=M(\"output_data\",o,r.length,4),a=E(\"a_data\",t[1].dataType,t[1].dims.length,4),l=E(\"b_data\",t[2].dataType,t[2].dims.length,4),d=E(\"c_data\",t[0].dataType,t[0].dims.length,4),c,m=(u,h,w)=>`select(${h}, ${u}, ${w})`;if(!n)c=i.setByOffset(\"global_idx\",m(a.getByOffset(\"global_idx\"),l.getByOffset(\"global_idx\"),d.getByOffset(\"global_idx\")));else{let u=(h,w,y=\"\")=>{let g=`a_data[index_a${w}][component_a${w}]`,x=`b_data[index_b${w}][component_b${w}]`,$=`bool(c_data[index_c${w}] & (0xffu << (component_c${w} * 8)))`;return`\n let output_indices${w} = ${i.offsetToIndices(`global_idx * 4u + ${w}u`)};\n let offset_a${w} = ${a.broadcastedIndicesToOffset(`output_indices${w}`,i)};\n let offset_b${w} = ${l.broadcastedIndicesToOffset(`output_indices${w}`,i)};\n let offset_c${w} = ${d.broadcastedIndicesToOffset(`output_indices${w}`,i)};\n let index_a${w} = offset_a${w} / 4u;\n let index_b${w} = offset_b${w} / 4u;\n let index_c${w} = offset_c${w} / 4u;\n let component_a${w} = offset_a${w} % 4u;\n let component_b${w} = offset_b${w} % 4u;\n let component_c${w} = offset_c${w} % 4u;\n ${h}[${w}] = ${y}(${m(g,x,$)});\n `};o===9?c=`\n var data = vec4(0);\n ${u(\"data\",0,\"u32\")}\n ${u(\"data\",1,\"u32\")}\n ${u(\"data\",2,\"u32\")}\n ${u(\"data\",3,\"u32\")}\n output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:c=`\n ${u(\"output_data[global_idx]\",0)}\n ${u(\"output_data[global_idx]\",1)}\n ${u(\"output_data[global_idx]\",2)}\n ${u(\"output_data[global_idx]\",3)}\n `}return`\n ${e.registerUniform(\"vec_size\",\"u32\").declareVariables(d,a,l,i)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.vec_size\")}\n ${c}\n }`},eg=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,o=e[1].dataType,i=!(k.areEqual(t,r)&&k.areEqual(r,n)),a=t,l=k.size(t);if(i){let c=et.calcShape(et.calcShape(t,r,!1),n,!1);if(!c)throw new Error(\"Can't perform where op on the given tensors\");a=c,l=k.size(a)}let d=Math.ceil(l/4);return{name:\"Where\",shaderCache:{inputDependencies:[\"rank\",\"rank\",\"rank\"]},getShaderSource:c=>Jh(c,e,a,i,o),getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:Math.ceil(l/64/4)},programUniforms:[{type:12,data:d},...V(n,t,r,a)]})}},Nd=e=>{e.compute(eg(e.inputs))}});var Ld,Gd=R(()=>{\"use strict\";zs();Xr();Bs();Rs();$u();Ou();Mu();Yu();rl();il();ul();ml();gl();yl();vl();Sl();Cl();El();Ol();Wl();Hl();ql();Kl();Xl();ko();Jl();gd();wd();vd();Yr();Td();Cd();kd();Od();Md();Po();Vd();ut();Jr();Wd();Ld=new Map([[\"Abs\",[Us]],[\"Acos\",[Vs]],[\"Acosh\",[Ns]],[\"Add\",[xu]],[\"ArgMax\",[Ps,go]],[\"ArgMin\",[Es,go]],[\"Asin\",[Ws]],[\"Asinh\",[Ls]],[\"Atan\",[Gs]],[\"Atanh\",[Hs]],[\"Attention\",[Os]],[\"AveragePool\",[sd,ad]],[\"BatchNormalization\",[Ds]],[\"BiasAdd\",[Ms]],[\"BiasSplitGelu\",[vu]],[\"Cast\",[qs,Fs]],[\"Ceil\",[Ks]],[\"Clip\",[js]],[\"Concat\",[Du,Bu]],[\"Conv\",[So,xo]],[\"ConvTranspose\",[tl,el]],[\"Cos\",[Ys]],[\"Cosh\",[Zs]],[\"CumSum\",[nl,ol]],[\"DepthToSpace\",[al,sl]],[\"DequantizeLinear\",[bd,yd]],[\"Div\",[Su]],[\"Einsum\",[cl,pl]],[\"Elu\",[Xs,Jt]],[\"Equal\",[Tu]],[\"Erf\",[Qs]],[\"Exp\",[Js]],[\"Expand\",[hl]],[\"FastGelu\",[bl]],[\"Floor\",[eu]],[\"FusedConv\",[So,xo]],[\"Gather\",[_l,wl]],[\"GatherElements\",[Il,Tl]],[\"GatherBlockQuantized\",[$l,xl]],[\"Gelu\",[tu]],[\"Gemm\",[kl,Al]],[\"GlobalAveragePool\",[dd,ld]],[\"GlobalMaxPool\",[hd,fd]],[\"Greater\",[ku]],[\"GreaterOrEqual\",[Pu]],[\"GridSample\",[Pl,zl]],[\"GroupQueryAttention\",[Nl]],[\"HardSigmoid\",[lu,uu]],[\"InstanceNormalization\",[Gl]],[\"LayerNormalization\",[Fl]],[\"LeakyRelu\",[ru,Jt]],[\"Less\",[Eu]],[\"LessOrEqual\",[zu]],[\"Log\",[yu]],[\"MatMul\",[jl]],[\"MatMulNBits\",[Yl,Zl]],[\"MaxPool\",[pd,md]],[\"Mul\",[Iu]],[\"MultiHeadAttention\",[Ml,Bl]],[\"Neg\",[ou]],[\"Not\",[nu]],[\"Pad\",[Ql]],[\"Pow\",[Cu]],[\"QuickGelu\",[wu,Jt]],[\"Range\",[_d]],[\"Reciprocal\",[iu]],[\"ReduceMin\",[Ss]],[\"ReduceMean\",[ws]],[\"ReduceMax\",[xs]],[\"ReduceSum\",[Is]],[\"ReduceProd\",[Ts]],[\"ReduceL1\",[_s]],[\"ReduceL2\",[vs]],[\"ReduceLogSum\",[As]],[\"ReduceLogSumExp\",[$s]],[\"ReduceSumSquare\",[Cs]],[\"Relu\",[au]],[\"Resize\",[xd,Sd]],[\"RotaryEmbedding\",[Id]],[\"Sigmoid\",[su]],[\"Sin\",[du]],[\"Sinh\",[cu]],[\"Slice\",[Pd,zd]],[\"SkipLayerNormalization\",[Ad]],[\"Split\",[Rl,Ul]],[\"Sqrt\",[pu]],[\"Softmax\",[Dd,Bd]],[\"Sub\",[Au]],[\"Tan\",[mu]],[\"Tanh\",[hu]],[\"ThresholdedRelu\",[bu,Jt]],[\"Tile\",[Ud]],[\"Transpose\",[as,ss]],[\"Where\",[Nd]]])});var dn,Hd=R(()=>{\"use strict\";He();je();ae();dn=class{constructor(t){this.backend=t;this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,r){this.repo.set(t,r)}run(t,r,n,o,i){Ue(t.programInfo.name);let a=this.backend.device,l=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let d=[];for(let m of r)d.push({binding:d.length,resource:{buffer:m.buffer}});for(let m of n)d.push({binding:d.length,resource:{buffer:m.buffer}});i&&d.push({binding:d.length,resource:i});let c=a.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:d,label:t.programInfo.name});if(this.backend.sessionStatus===\"capturing\"){let m={kernelId:this.backend.currentKernelId,computePipeline:t.computePipeline,bindGroup:c,dispatchGroup:o};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(m)}l.setPipeline(t.computePipeline),l.setBindGroup(0,c),l.dispatchWorkgroups(...o),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType===\"at-passes\")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Be(t.programInfo.name)}dispose(){}build(t,r){Ue(t.name);let n=this.backend.device,o=[];[{feature:\"shader-f16\",extension:\"f16\"},{feature:\"subgroups\",extension:\"subgroups\"},{feature:\"subgroups-f16\",extension:\"subgroups_f16\"}].forEach(u=>{n.features.has(u.feature)&&o.push(`enable ${u.extension};`)});let a=os(r,this.backend.device.limits),l=t.getShaderSource(a),d=`${o.join(`\n`)}\n${a.additionalImplementations}\n${l}`,c=n.createShaderModule({code:d,label:t.name});se(\"verbose\",()=>`[WebGPU] ${t.name} shader code: ${d}`);let m=n.createComputePipeline({compute:{module:c,entryPoint:\"main\"},layout:\"auto\",label:t.name});return Be(t.name),{programInfo:t,computePipeline:m,uniformVariablesInfo:a.variablesInfo}}normalizeDispatchGroupSize(t){let r=typeof t==\"number\"?t:t.x,n=typeof t==\"number\"?1:t.y||1,o=typeof t==\"number\"?1:t.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=i&&n<=i&&o<=i)return[r,n,o];let a=r*n*o,l=Math.ceil(Math.sqrt(a));if(l>i){if(l=Math.ceil(Math.cbrt(a)),l>i)throw new Error(\"Total dispatch size exceeds WebGPU maximum.\");return[l,l,l]}else return[l,l,1]}}});var tg,rg,zo,Oo,cn,Fd=R(()=>{\"use strict\";He();te();je();no();ts();Gd();Hd();tg=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let n=0;n{let n=e.name;return e.shaderCache?.hint&&(n+=\"[\"+e.shaderCache.hint+\"]\"),n+=\":\"+r+`:${tg(t,e.shaderCache?.inputDependencies??new Array(t.length).fill(\"dims\"))}`,n},zo=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},Oo=class{constructor(t){this.subgroupsSupported=t.features.has(\"subgroups\"),this.subgroupsF16Supported=t.features.has(\"subgroups\");let r=t.limits;!this.subgroupsSupported||!r.minSubgroupSize||!r.maxSubgroupSize?this.subgroupSizeRange=void 0:this.subgroupSizeRange=[r.minSubgroupSize,r.maxSubgroupSize]}},cn=class{constructor(){this.currentSessionId=null;this.currentKernelId=null;this.commandEncoder=null;this.computePassEncoder=null;this.maxDispatchNumber=16;this.pendingDispatchNumber=0;this.pendingKernels=[];this.pendingQueries=new Map;this.sessionStatus=\"default\";this.capturedCommandList=new Map;this.capturedPendingKernels=new Map;this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error(\"currentKernelCustomData(): currentKernelId is null. (should not happen)\");let t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,r){this.env=t;let n=[],o={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},i=a=>r.features.has(a)&&n.push(a)&&!0;i(\"chromium-experimental-timestamp-query-inside-passes\")||i(\"timestamp-query\"),i(\"shader-f16\"),i(\"subgroups\")&&i(\"subgroups-f16\"),this.device=await r.requestDevice(o),this.deviceInfo=new Oo(this.device),this.adapterInfo=new zo(r.info||await r.requestAdapterInfo()),this.gpuDataManager=es(this),this.programManager=new dn(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Hr(t.logLevel,!!t.debug),this.device.onuncapturederror=a=>{a.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${a.error.message}`)},Object.defineProperty(this.env.webgpu,\"device\",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,\"adapter\",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<\"u\"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t=this.getCommandEncoder(),r={};this.queryType===\"at-passes\"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ue(),this.endComputePass();let t;this.queryType!==\"none\"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),t=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(t,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,t,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!==\"none\"&&t.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(t.getMappedRange()),n=this.pendingQueries.get(t);for(let o=0;o\"u\"&&(this.queryTimeBase=w);let g=Number(w-this.queryTimeBase),x=Number(y-this.queryTimeBase);if(!Number.isSafeInteger(g)||!Number.isSafeInteger(x))throw new RangeError(\"incorrect timestamp range\");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:u.map($=>({dims:$.dims,dataType:bt($.dataType)})),outputsMetadata:h.map($=>({dims:$.dims,dataType:bt($.dataType)})),kernelId:a,kernelType:d,kernelName:c,programName:m,startTime:g,endTime:x});else{let $=\"\";u.forEach((S,T)=>{$+=`input[${T}]: [${S.dims}] | ${bt(S.dataType)}, `});let v=\"\";h.forEach((S,T)=>{v+=`output[${T}]: [${S.dims}] | ${bt(S.dataType)}, `}),console.log(`[profiling] kernel \"${a}|${d}|${c}|${m}\" ${$}${v}execution time: ${x-g} ns`)}Cr(\"GPU\",`${m}::${w}::${y}`)}t.unmap(),this.pendingQueries.delete(t)}),Be()}run(t,r,n,o,i,a){Ue(t.name);let l=[];for(let S=0;ST):n;if(u.length!==d.length)throw new Error(`Output size ${u.length} must be equal to ${d.length}.`);let h=[],w=[];for(let S=0;S=a)throw new Error(`Invalid output index: ${u[S]}`);if(u[S]===-3)continue;let T=u[S]===-1,C=u[S]===-2,A=T||C?i(d[S].dataType,d[S].dims):o(u[S],d[S].dataType,d[S].dims);if(h.push(A),A.data===0)continue;let P=this.gpuDataManager.get(A.data);if(!P)throw new Error(`no GPU data for output: ${A.data}`);if(T&&this.temporaryData.push(P),C){let O=this.kernelPersistentData.get(this.currentKernelId);O||(O=[],this.kernelPersistentData.set(this.currentKernelId,O)),O.push(P)}w.push(P)}if(l.length!==r.length||w.length!==h.length){if(w.length===0)return Be(t.name),h;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let y;if(m){let S=0,T=[];m.forEach(O=>{let U=typeof O.data==\"number\"?[O.data]:O.data;if(U.length===0)return;let L=O.type===10?2:4,j,K;O.type===10?(K=U.length>4?16:U.length>2?8:U.length*L,j=U.length>4?16:L*U.length):(K=U.length<=2?U.length*L:16,j=16),S=Math.ceil(S/K)*K,T.push(S);let W=O.type===10?8:4;S+=U.length>4?Math.ceil(U.length/W)*j:U.length*L});let C=16;S=Math.ceil(S/C)*C;let A=new ArrayBuffer(S);m.forEach((O,U)=>{let L=T[U],j=typeof O.data==\"number\"?[O.data]:O.data;if(O.type===6)new Int32Array(A,L,j.length).set(j);else if(O.type===12)new Uint32Array(A,L,j.length).set(j);else if(O.type===10)new Uint16Array(A,L,j.length).set(j);else if(O.type===1)new Float32Array(A,L,j.length).set(j);else throw new Error(`Unsupported uniform type: ${bt(O.type)}`)});let P=this.gpuDataManager.create(S,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(P.buffer,0,A,0,S),this.gpuDataManager.release(P.id),y={offset:0,size:S,buffer:P.buffer}}let g=this.programManager.normalizeDispatchGroupSize(c),x=g[1]===1&&g[2]===1,$=rg(t,r,x),v=this.programManager.getArtifact($);if(v||(v=this.programManager.build(t,g),this.programManager.setArtifact($,v),se(\"info\",()=>`[artifact] key: ${$}, programName: ${t.name}`)),m&&v.uniformVariablesInfo){if(m.length!==v.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${v.uniformVariablesInfo.length}, got ${m.length} in program \"${v.programInfo.name}\".`);for(let S=0;S`[ProgramManager] run \"${t.name}\" (key=${$}) with ${g[0]}x${g[1]}x${g[2]}`),this.queryType!==\"none\"||this.sessionStatus===\"capturing\"){let S={kernelId:this.currentKernelId,programName:v.programInfo.name,inputTensorViews:r,outputTensorViews:h};this.pendingKernels.push(S),this.sessionStatus===\"capturing\"&&this.capturedPendingKernels.get(this.currentSessionId).push(S)}return this.programManager.run(v,l,w,g,y),Be(t.name),h}upload(t,r){this.gpuDataManager.upload(t,r)}memcpy(t,r){this.gpuDataManager.memcpy(t,r)}async download(t,r){await this.gpuDataManager.download(t,r)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,r,n,o){let i=Ld.get(t);if(!i)throw new Error(`kernel not implemented: ${t}`);let a={kernelType:t,kernelName:o,kernelEntry:i[0],attributes:[i[1],n]};this.kernels.set(r,a)}releaseKernel(t){let r=this.kernelPersistentData.get(t);if(r){for(let n of r)this.gpuDataManager.release(n.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,r,n){let o=this.kernels.get(t);if(!o)throw new Error(`kernel not created: ${t}`);let i=o.kernelType,a=o.kernelName,l=o.kernelEntry,d=o.attributes;if(this.currentKernelId!==null)throw new Error(`kernel \"[${i}] ${a}\" is not allowed to be called recursively`);this.currentKernelId=t,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),se(\"info\",()=>`[WebGPU] Start to run kernel \"[${i}] ${a}\"...`);let c=this.env.debug;this.temporaryData=[];try{return c&&this.device.pushErrorScope(\"validation\"),l(r,d[1]),0}catch(m){return n.push(Promise.resolve(`[WebGPU] Kernel \"[${i}] ${a}\" failed. ${m}`)),1}finally{c&&n.push(this.device.popErrorScope().then(m=>m?`GPU validation error for kernel \"[${i}] ${a}\": ${m.message}`:null));for(let m of this.temporaryData)this.gpuDataManager.release(m.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,r,n,o){let i=this.sessionExternalDataMapping.get(t);i||(i=new Map,this.sessionExternalDataMapping.set(t,i));let a=i.get(r),l=this.gpuDataManager.registerExternalBuffer(n,o,a);return i.set(r,[l,n]),l}unregisterBuffers(t){let r=this.sessionExternalDataMapping.get(t);r&&(r.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[0])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let r=this.gpuDataManager.get(t);if(!r)throw new Error(`no GPU data for buffer: ${t}`);return r.buffer}createDownloader(t,r,n){return async()=>{let o=await so(this,t,r);return Fr(o.buffer,n)}}writeTimestamp(t){this.queryType===\"inside-passes\"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}setQueryType(){this.queryType=\"none\",(this.env.webgpu.profiling?.mode===\"default\"||(typeof this.env.trace>\"u\"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has(\"chromium-experimental-timestamp-query-inside-passes\")?this.queryType=\"inside-passes\":this.device.features.has(\"timestamp-query\")&&(this.queryType=\"at-passes\"),this.queryType!==\"none\"&&typeof this.querySet>\"u\"&&(this.querySet=this.device.createQuerySet({type:\"timestamp\",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){se(\"info\",\"captureBegin\"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus=\"capturing\"}captureEnd(){se(\"info\",\"captureEnd\"),this.flush(),this.sessionStatus=\"default\"}replay(){se(\"info\",\"replay\"),this.sessionStatus=\"replaying\";let t=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),n=t.length;this.pendingKernels=[];for(let o=0;o=this.maxDispatchNumber||this.queryType===\"at-passes\")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus=\"default\"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}});var ng,qd,og,jd,pn,mn,Do,Kd,Yd=R(()=>{\"use strict\";je();ng=1,qd=()=>ng++,og=new Map([[\"float32\",32],[\"float16\",16],[\"int32\",32],[\"uint32\",32],[\"int64\",64],[\"uint64\",64],[\"int8\",8],[\"uint8\",8],[\"int4\",4],[\"uint4\",4]]),jd=(e,t)=>{let r=og.get(e);if(!r)throw new Error(\"Unsupported data type.\");return Math.ceil(t.reduce((n,o)=>n*o)*r/8)},pn=class{constructor(t){this.sessionId=t.sessionId,this.mlContext=t.context,this.mlTensor=t.tensor,this.dataType=t.dataType,this.tensorShape=t.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return jd(this.dataType,this.tensorShape)}destroy(){se(\"verbose\",()=>\"[WebNN] TensorWrapper.destroy\"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t){return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}sameTypeAndShape(t,r){return this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((n,o)=>n===r[o])}},mn=class{constructor(t,r){this.tensorManager=t;this.wrapper=r}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(t,r,n){if(this.wrapper){if(this.wrapper.sameTypeAndShape(t,r))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==jd(t,r))throw new Error(\"Unable to copy data to tensor with different size.\");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let o=MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,r,o,!0,!0),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(t){if(this.wrapper)if(t.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else se(\"verbose\",()=>\"Data size does not match tensor size. Releasing tensor.\"),this.releaseTensor();this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(t){if(this.activeUpload)if(t){t instanceof ArrayBuffer?new Uint8Array(t).set(this.activeUpload):new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.wrapper)throw new Error(\"Tensor has not been created.\");return t?this.wrapper.read(t):this.wrapper.read()}},Do=class{constructor(t){this.backend=t;this.tensorTrackersById=new Map;this.freeTensors=[];this.externalTensors=new Set}reserveTensorId(){let t=qd();return this.tensorTrackersById.set(t,new mn(this)),t}releaseTensorId(t){let r=this.tensorTrackersById.get(t);r&&(this.tensorTrackersById.delete(t),r.tensorWrapper&&this.releaseTensor(r.tensorWrapper))}async ensureTensor(t,r,n,o){se(\"verbose\",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${n}, copyOld: ${o}}`);let i=this.tensorTrackersById.get(t);if(!i)throw new Error(\"Tensor not found.\");return i.ensureTensor(r,n,o)}upload(t,r){let n=this.tensorTrackersById.get(t);if(!n)throw new Error(\"Tensor not found.\");n.upload(r)}async download(t,r){se(\"verbose\",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${r?.byteLength}}`);let n=this.tensorTrackersById.get(t);if(!n)throw new Error(\"Tensor not found.\");return n.download(r)}releaseTensorsForSession(t){for(let r of this.freeTensors)r.sessionId===t&&r.destroy();this.freeTensors=this.freeTensors.filter(r=>r.sessionId!==t)}registerTensor(t,r,n,o){let i=qd(),a=new pn({sessionId:this.backend.currentSessionId,context:t,tensor:r,dataType:n,shape:o});return this.tensorTrackersById.set(i,new mn(this,a)),this.externalTensors.add(a),i}async getCachedTensor(t,r,n,o,i){let a=this.backend.currentSessionId;for(let[c,m]of this.freeTensors.entries())if(m.sameTypeAndShape(t,r)){se(\"verbose\",()=>`[WebNN] Reusing tensor {dataType: ${t}, shape: ${r}}`);let u=this.freeTensors.splice(c,1)[0];return u.sessionId=a,u}let l=this.backend.currentContext;se(\"verbose\",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, shape: ${r}}`);let d=await l.createTensor({dataType:t,shape:r,dimensions:r,usage:n,writable:o,readable:i});return new pn({sessionId:a,context:l,tensor:d,dataType:t,shape:r})}releaseTensor(t){this.externalTensors.has(t)&&this.externalTensors.delete(t),this.freeTensors.push(t)}},Kd=(...e)=>new Do(...e)});var Zd,ig,fn,Xd=R(()=>{\"use strict\";te();gt();no();Yd();je();Zd=new Map([[1,\"float32\"],[10,\"float16\"],[6,\"int32\"],[12,\"uint32\"],[7,\"int64\"],[13,\"uint64\"],[22,\"int4\"],[21,\"uint4\"],[3,\"int8\"],[2,\"uint8\"],[9,\"uint8\"]]),ig=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.length===n.length&&r.every((o,i)=>o===n[i]&&e[o]===t[o])},fn=class{constructor(t){this.tensorManager=Kd(this);this.mlContextBySessionId=new Map;this.sessionIdsByMLContext=new Map;this.mlContextCache=[];Hr(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error(\"No active session\");return this.activeSessionId}onRunStart(t){this.activeSessionId=t}async createMLContext(t){if(t instanceof GPUDevice){let n=this.mlContextCache.findIndex(o=>o.gpuDevice===t);if(n!==-1)return this.mlContextCache[n].mlContext;{let o=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:o}),o}}else if(t===void 0){let n=this.mlContextCache.findIndex(o=>o.options===void 0&&o.gpuDevice===void 0);if(n!==-1)return this.mlContextCache[n].mlContext;{let o=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:o}),o}}let r=this.mlContextCache.findIndex(n=>ig(n.options,t));if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:n}),n}}get currentContext(){let t=this.getMLContext(this.currentSessionId);if(!t)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return t}registerMLContext(t,r){this.mlContextBySessionId.set(t,r);let n=this.sessionIdsByMLContext.get(r);n||(n=new Set,this.sessionIdsByMLContext.set(r,n)),n.add(t)}onReleaseSession(t){let r=this.mlContextBySessionId.get(t);if(!r)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t);let n=this.sessionIdsByMLContext.get(r);if(n.delete(t),n.size===0){this.sessionIdsByMLContext.delete(r);let o=this.mlContextCache.findIndex(i=>i.mlContext===r);o!==-1&&this.mlContextCache.splice(o,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){se(\"verbose\",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,r,n,o){let i=Zd.get(r);if(!i)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(t,i,n,o)}uploadTensor(t,r){if(!Te().shouldTransferToMLTensor)throw new Error(\"Trying to upload to a MLTensor while shouldTransferToMLTensor is false\");se(\"verbose\",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${r.byteLength}}`),this.tensorManager.upload(t,r)}async downloadTensor(t,r){return this.tensorManager.download(t,r)}createMLTensorDownloader(t,r){return async()=>{let n=await this.tensorManager.download(t);return Fr(n,r)}}registerMLTensor(t,r,n){let o=Zd.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);let i=this.tensorManager.registerTensor(this.currentContext,t,o,n);return se(\"verbose\",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${o}, dimensions: ${n}} -> {tensorId: ${i}}`),i}registerMLConstant(t,r,n,o,i,a){if(!a)throw new Error(\"External mounted files are not available.\");let l=t;t.startsWith(\"./\")&&(l=t.substring(2));let d=a.get(l);if(!d)throw new Error(`File with name ${l} not found in preloaded files.`);if(r+n>d.byteLength)throw new Error(\"Out of bounds: data offset and length exceed the external file data size.\");let c=d.slice(r,r+n).buffer,m;switch(i.dataType){case\"float32\":m=new Float32Array(c);break;case\"float16\":m=new Uint16Array(c);break;case\"int32\":m=new Int32Array(c);break;case\"uint32\":m=new Uint32Array(c);break;case\"int64\":m=new BigInt64Array(c);break;case\"uint64\":m=new BigUint64Array(c);break;case\"int8\":m=new Int8Array(c);break;case\"int4\":case\"uint4\":case\"uint8\":m=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return se(\"verbose\",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`),o.constant(i,m)}flush(){}}});var Qd={};Ft(Qd,{init:()=>ag});var sr,Bo,ag,Jd=R(()=>{\"use strict\";te();Fd();je();oe();Xd();sr=class e{constructor(t,r,n,o){this.module=t;this.dataType=r;this.data=n;this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error(\"Invalid data type\");let t=k.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error(\"Invalid data type\");let t=k.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error(\"Invalid data type\");let t=k.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error(\"Invalid data type\");let t=k.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(k.size(t)!==k.size(this.dims))throw new Error(\"Invalid new shape\");return new e(this.module,this.dataType,this.data,t)}},Bo=class{constructor(t,r,n){this.module=t;this.backend=r;this.customDataOffset=0;this.customDataSize=0;this.adapterInfo=r.adapterInfo,this.deviceInfo=r.deviceInfo;let o=t.PTR_SIZE,i=n/t.PTR_SIZE,a=o===4?\"i32\":\"i64\";this.opKernelContext=Number(t.getValue(o*i++,a));let l=Number(t.getValue(o*i++,a));this.outputCount=Number(t.getValue(o*i++,a)),this.customDataOffset=Number(t.getValue(o*i++,\"*\")),this.customDataSize=Number(t.getValue(o*i++,a));let d=[];for(let c=0;ctypeof l==\"number\"?this.inputs[l]:l)??this.inputs,o=r?.outputs??[],i=(l,d,c)=>new sr(this.module,d,this.output(l,c),c),a=(l,d)=>{let c=Tt(l,d);if(!c)throw new Error(`Unsupported data type: ${l}`);let m=c>0?this.backend.gpuDataManager.create(c).id:0;return new sr(this.module,l,m,d)};return this.backend.run(t,n,o,i,a,this.outputCount)}output(t,r){let n=this.module.stackSave();try{let o=this.module.PTR_SIZE,i=o===4?\"i32\":\"i64\",a=this.module.stackAlloc((1+r.length)*o);this.module.setValue(a,r.length,i);for(let l=0;l{let o=t.jsepInit;if(!o)throw new Error(\"Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.\");if(e===\"webgpu\"){let i=new cn;await i.initialize(r,n),o(\"webgpu\",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,d,c=!1)=>{if(c)se(\"verbose\",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(d)}`),i.memcpy(Number(a),Number(l));else{se(\"verbose\",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(d)}`);let m=t.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(d));i.upload(Number(l),m)}},async(a,l,d)=>{se(\"verbose\",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${d}`),await i.download(Number(a),()=>t.HEAPU8.subarray(Number(l)>>>0,Number(l+d)>>>0))},(a,l,d)=>i.createKernel(a,Number(l),d,t.UTF8ToString(t._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,d,c)=>{se(\"verbose\",()=>`[WebGPU] jsepRun: sessionHandle=${d}, kernel=${a}, contextDataOffset=${l}`);let m=new Bo(t,i,Number(l));return i.computeKernel(Number(a),m,c)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let i=new fn(r);o(\"webnn\",[i,()=>i.reserveTensorId(),a=>i.releaseTensorId(a),async(a,l,d,c)=>i.ensureTensor(a,l,d,c),(a,l)=>{i.uploadTensor(a,l)},async(a,l)=>i.downloadTensor(a,l)])}}});var sg,zr,Or,kt,ug,Kt,Dr,Br,ec,Mr,Rr,Ur,Xn=R(()=>{\"use strict\";qa();Ka();te();gt();Nr();ro();sg=(e,t)=>{Te()._OrtInit(e,t)!==0&&pe(\"Can't initialize onnxruntime.\")},zr=async e=>{sg(e.wasm.numThreads,Xt(e.logLevel))},Or=async(e,t)=>{{let r=(Jd(),vr(Qd)).init;if(t===\"webgpu\"){if(typeof navigator>\"u\"||!navigator.gpu)throw new Error(\"WebGPU is not supported in current environment\");let n=e.webgpu.adapter;if(n){if(typeof n.limits!=\"object\"||typeof n.features!=\"object\"||typeof n.requestDevice!=\"function\")throw new Error(\"Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.\")}else{let o=e.webgpu.powerPreference;if(o!==void 0&&o!==\"low-power\"&&o!==\"high-performance\")throw new Error(`Invalid powerPreference setting: \"${o}\"`);let i=e.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!=\"boolean\")throw new Error(`Invalid forceFallbackAdapter setting: \"${i}\"`);if(n=await navigator.gpu.requestAdapter({powerPreference:o,forceFallbackAdapter:i}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag \"--enable-unsafe-webgpu\" if you are using Chrome.')}await r(\"webgpu\",Te(),e,n)}if(t===\"webnn\"){if(typeof navigator>\"u\"||!navigator.ml)throw new Error(\"WebNN is not supported in current environment\");await r(\"webnn\",Te(),e)}}},kt=new Map,ug=e=>{let t=Te(),r=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,o,o+n)!==0&&pe(\"Can't get session input/output count.\");let a=n===4?\"i32\":\"i64\";return[Number(t.getValue(o,a)),Number(t.getValue(o+n,a))]}finally{t.stackRestore(r)}},Kt=e=>{let t=Te(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},Dr=async(e,t)=>{let r,n,o=Te();Array.isArray(e)?[r,n]=e:e.buffer===o.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=Kt(e);let i=0,a=0,l=0,d=[],c=[],m=[];try{if([a,d]=ja(t),t?.externalData&&o.mountExternalData){let v=[];for(let S of t.externalData){let T=typeof S==\"string\"?S:S.path;v.push(Qt(typeof S==\"string\"?S:S.data).then(C=>{o.mountExternalData(T,C)}))}await Promise.all(v)}for(let v of t?.executionProviders??[])if((typeof v==\"string\"?v:v.name)===\"webnn\"){if(o.shouldTransferToMLTensor=!1,o.currentContext)throw new Error(\"WebNN execution provider is already set.\");if(typeof v!=\"string\"){let T=v,C=T?.context,A=T?.gpuDevice,P=T?.deviceType,O=T?.powerPreference;C?o.currentContext=C:A?o.currentContext=await o.jsepCreateMLContext(A):o.currentContext=await o.jsepCreateMLContext({deviceType:P,powerPreference:O})}else o.currentContext=await o.jsepCreateMLContext();break}i=await o._OrtCreateSession(r,n,a),i===0&&pe(\"Can't create a session.\"),o.jsepOnCreateSession?.(),o.currentContext&&(o.jsepRegisterMLContext(i,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[u,h]=ug(i),w=!!t?.enableGraphCapture,y=[],g=[],x=[];for(let v=0;vv===\"gpu-buffer\"||v===\"ml-tensor\")&&(l=o._OrtCreateBinding(i),l===0&&pe(\"Can't create IO binding.\"),$={handle:l,outputPreferredLocations:x,outputPreferredLocationsEncoded:x.map(v=>to(v))}),kt.set(i,[i,c,m,$,w,!1]),[i,y,g]}catch(u){throw c.forEach(h=>o._OrtFree(h)),m.forEach(h=>o._OrtFree(h)),l!==0&&o._OrtReleaseBinding(l)!==0&&pe(\"Can't release IO binding.\"),i!==0&&o._OrtReleaseSession(i)!==0&&pe(\"Can't release session.\"),u}finally{o._free(r),a!==0&&o._OrtReleaseSessionOptions(a)!==0&&pe(\"Can't release session options.\"),d.forEach(u=>o._free(u)),o.unmountExternalData?.()}},Br=e=>{let t=Te(),r=kt.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,o,i,a,l]=r;a&&(l&&t._OrtClearBoundOutputs(a.handle)!==0&&pe(\"Can't clear bound outputs.\"),t._OrtReleaseBinding(a.handle)!==0&&pe(\"Can't release IO binding.\")),t.jsepOnReleaseSession?.(e),o.forEach(d=>t._OrtFree(d)),i.forEach(d=>t._OrtFree(d)),t._OrtReleaseSession(n)!==0&&pe(\"Can't release session.\"),kt.delete(e)},ec=(e,t,r,n,o,i=!1)=>{if(!e){t.push(0);return}let a=Te(),l=a.PTR_SIZE,d=e[0],c=e[1],m=e[3],u,h;if(d===\"string\"&&(m===\"gpu-buffer\"||m===\"ml-tensor\"))throw new Error(\"String tensor is not supported on GPU.\");if(i&&m!==\"gpu-buffer\")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(m===\"gpu-buffer\"){let g=e[2].gpuBuffer;h=Tt(Zt(d),c);let x=a.jsepRegisterBuffer;if(!x)throw new Error('Tensor location \"gpu-buffer\" is not supported without using WebGPU.');u=x(n,o,g,h)}else if(m===\"ml-tensor\"){let g=e[2].mlTensor;h=Tt(Zt(d),c);let x=a.jsepRegisterMLTensor;if(!x)throw new Error('Tensor location \"ml-tensor\" is not supported without using WebNN.');u=x(g,Zt(d),c)}else{let g=e[2];if(Array.isArray(g)){h=l*g.length,u=a._malloc(h),r.push(u);for(let x=0;xa.setValue(y+$*l,x,l===4?\"i32\":\"i64\"));let g=a._OrtCreateTensor(Zt(d),u,h,y,c.length,to(m));g===0&&pe(`Can't create tensor for input/output. session=${n}, index=${o}.`),t.push(g)}finally{a.stackRestore(w)}},Mr=async(e,t,r,n,o,i)=>{let a=Te(),l=a.PTR_SIZE,d=kt.get(e);if(!d)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=d[0],m=d[1],u=d[2],h=d[3],w=d[4],y=d[5],g=t.length,x=n.length,$=0,v=[],S=[],T=[],C=[],A=a.stackSave(),P=a.stackAlloc(g*l),O=a.stackAlloc(g*l),U=a.stackAlloc(x*l),L=a.stackAlloc(x*l);try{a.jsepOnRunStart?.(c),[$,v]=Fa(i);for(let W=0;W_e*be,1);Q=bt($e);let qe=h?.outputPreferredLocations[n[W]];if(Q===\"string\"){if(qe===\"gpu-buffer\"||qe===\"ml-tensor\")throw new Error(\"String tensor is not supported on GPU.\");let _e=[];for(let be=0;be0){let _e=a.jsepGetBuffer;if(!_e)throw new Error('preferredLocation \"gpu-buffer\" is not supported without using WebGPU.');let be=_e(ne),Ye=Tt($e,he);if(Ye===void 0||!Lr(Q))throw new Error(`Unsupported data type: ${Q}`);J=!0,K.push([Q,q,{gpuBuffer:be,download:a.jsepCreateDownloader(be,Ye,Q),dispose:()=>{a._OrtReleaseTensor(ee)!==0&&pe(\"Can't release tensor.\")}},\"gpu-buffer\"])}else if(qe===\"ml-tensor\"&&he>0){let _e=a.jsepEnsureTensor;if(!_e)throw new Error('preferredLocation \"ml-tensor\" is not supported without using WebNN.');if(Tt($e,he)===void 0||!Gr(Q))throw new Error(`Unsupported data type: ${Q}`);let Ye=await _e(ne,$e,q,!1);J=!0,K.push([Q,q,{mlTensor:Ye,download:a.jsepCreateMLTensorDownloader(ne,Q),dispose:()=>{a.jsepReleaseTensorId(ne),a._OrtReleaseTensor(ee)}},\"ml-tensor\"])}else{let _e=Wr(Q),be=new _e(he);new Uint8Array(be.buffer,be.byteOffset,be.byteLength).set(a.HEAPU8.subarray(ne,ne+be.byteLength)),K.push([Q,q,be,\"cpu\"])}}finally{a.stackRestore(ue),Q===\"string\"&&ne&&a._free(ne),J||a._OrtReleaseTensor(ee)}}return h&&!w&&(a._OrtClearBoundOutputs(h.handle)!==0&&pe(\"Can't clear bound outputs.\"),kt.set(e,[c,m,u,h,w,!1])),K}finally{a.stackRestore(A),S.forEach(j=>a._OrtReleaseTensor(j)),T.forEach(j=>a._OrtReleaseTensor(j)),C.forEach(j=>a._free(j)),$!==0&&a._OrtReleaseRunOptions($),v.forEach(j=>a._free(j))}},Rr=e=>{let t=Te(),r=kt.get(e);if(!r)throw new Error(\"invalid session id\");let n=r[0],o=t._OrtEndProfiling(n);o===0&&pe(\"Can't get an profile file name.\"),t._OrtFree(o)},Ur=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&\"buffer\"in n&&t.push(n.buffer)}return t}});var Et,Fe,ur,gn,bn,hn,Mo,Ro,Nt,Wt,dg,tc,rc,nc,oc,ic,ac,sc,Uo=R(()=>{\"use strict\";He();Xn();gt();jt();Et=()=>!!ve.wasm.proxy&&typeof document<\"u\",ur=!1,gn=!1,bn=!1,Ro=new Map,Nt=(e,t)=>{let r=Ro.get(e);r?r.push(t):Ro.set(e,[t])},Wt=()=>{if(ur||!gn||bn||!Fe)throw new Error(\"worker not ready\")},dg=e=>{switch(e.data.type){case\"init-wasm\":ur=!1,e.data.err?(bn=!0,Mo[1](e.data.err)):(gn=!0,Mo[0]()),hn&&(URL.revokeObjectURL(hn),hn=void 0);break;case\"init-ep\":case\"copy-from\":case\"create\":case\"release\":case\"run\":case\"end-profiling\":{let t=Ro.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},tc=async()=>{if(!gn){if(ur)throw new Error(\"multiple calls to 'initWasm()' detected.\");if(bn)throw new Error(\"previous call to 'initWasm()' failed.\");if(ur=!0,Et())return new Promise((e,t)=>{Fe?.terminate(),La().then(([r,n])=>{try{Fe=n,Fe.onerror=i=>t(i),Fe.onmessage=dg,Mo=[e,t];let o={type:\"init-wasm\",in:ve};Fe.postMessage(o),hn=r}catch(o){t(o)}},t)});try{await Pr(ve.wasm),await zr(ve),gn=!0}catch(e){throw bn=!0,e}finally{ur=!1}}},rc=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Nt(\"init-ep\",[t,r]);let n={type:\"init-ep\",in:{epName:e,env:ve}};Fe.postMessage(n)});await Or(ve,e)},nc=async e=>Et()?(Wt(),new Promise((t,r)=>{Nt(\"copy-from\",[t,r]);let n={type:\"copy-from\",in:{buffer:e}};Fe.postMessage(n,[e.buffer])})):Kt(e),oc=async(e,t)=>{if(Et()){if(t?.preferredOutputLocation)throw new Error('session option \"preferredOutputLocation\" is not supported for proxy.');return Wt(),new Promise((r,n)=>{Nt(\"create\",[r,n]);let o={type:\"create\",in:{model:e,options:{...t}}},i=[];e instanceof Uint8Array&&i.push(e.buffer),Fe.postMessage(o,i)})}else return Dr(e,t)},ic=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Nt(\"release\",[t,r]);let n={type:\"release\",in:e};Fe.postMessage(n)});Br(e)},ac=async(e,t,r,n,o,i)=>{if(Et()){if(r.some(a=>a[3]!==\"cpu\"))throw new Error(\"input tensor on GPU is not supported for proxy.\");if(o.some(a=>a))throw new Error(\"pre-allocated output tensor is not supported for proxy.\");return Wt(),new Promise((a,l)=>{Nt(\"run\",[a,l]);let d=r,c={type:\"run\",in:{sessionId:e,inputIndices:t,inputs:d,outputIndices:n,options:i}};Fe.postMessage(c,Ur(d))})}else return Mr(e,t,r,n,o,i)},sc=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Nt(\"end-profiling\",[t,r]);let n={type:\"end-profiling\",in:e};Fe.postMessage(n)});Rr(e)}});var uc,cg,yn,lc=R(()=>{\"use strict\";He();Uo();te();Er();ro();uc=(e,t)=>{switch(e.location){case\"cpu\":return[e.type,e.dims,e.data,\"cpu\"];case\"gpu-buffer\":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},\"gpu-buffer\"];case\"ml-tensor\":return[e.type,e.dims,{mlTensor:e.mlTensor},\"ml-tensor\"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},cg=e=>{switch(e[3]){case\"cpu\":return new De(e[0],e[2],e[1]);case\"gpu-buffer\":{let t=e[0];if(!Lr(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:o}=e[2];return De.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:o})}case\"ml-tensor\":{let t=e[0];if(!Gr(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:o}=e[2];return De.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},yn=class{async fetchModelAndCopyToWasmMemory(t){return nc(await Qt(t))}async loadModel(t,r){Ue();let n;typeof t==\"string\"?!1?n=await Qt(t):n=await this.fetchModelAndCopyToWasmMemory(t):n=t,[this.sessionId,this.inputNames,this.outputNames]=await oc(n,r),Be()}async dispose(){return ic(this.sessionId)}async run(t,r,n){Ue();let o=[],i=[];Object.entries(t).forEach(h=>{let w=h[0],y=h[1],g=this.inputNames.indexOf(w);if(g===-1)throw new Error(`invalid input '${w}'`);o.push(y),i.push(g)});let a=[],l=[];Object.entries(r).forEach(h=>{let w=h[0],y=h[1],g=this.outputNames.indexOf(w);if(g===-1)throw new Error(`invalid output '${w}'`);a.push(y),l.push(g)});let d=o.map((h,w)=>uc(h,()=>`input \"${this.inputNames[i[w]]}\"`)),c=a.map((h,w)=>h?uc(h,()=>`output \"${this.outputNames[l[w]]}\"`):null),m=await ac(this.sessionId,i,d,l,c,n),u={};for(let h=0;hwn,initializeFlags:()=>dc,wasmBackend:()=>pg});var dc,wn,pg,pc=R(()=>{\"use strict\";He();Uo();lc();jt();dc=()=>{if((typeof ve.wasm.initTimeout!=\"number\"||ve.wasm.initTimeout<0)&&(ve.wasm.initTimeout=0),ve.wasm.simd===!1&&console.warn('Deprecated property \"env.wasm.simd\" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof ve.wasm.proxy!=\"boolean\"&&(ve.wasm.proxy=!1),typeof ve.wasm.trace!=\"boolean\"&&(ve.wasm.trace=!1),typeof ve.wasm.numThreads!=\"number\"||!Number.isInteger(ve.wasm.numThreads)||ve.wasm.numThreads<=0)if(typeof self<\"u\"&&!self.crossOriginIsolated)ve.wasm.numThreads=1;else{let e=typeof navigator>\"u\"?qn(\"node:os\").cpus().length:navigator.hardwareConcurrency;ve.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},wn=class{async init(t){dc(),await tc(),await rc(t)}async createInferenceSessionHandler(t,r){let n=new yn;return await n.loadModel(t,r),Promise.resolve(n)}},pg=new wn});He();He();He();var Oa=\"1.21.0-dev.20241109-d3ad76b2cf\";var y1=Zn;{let e=(pc(),vr(cc)).wasmBackend;xt(\"webgpu\",e,5),xt(\"webnn\",e,5),xt(\"cpu\",e,10),xt(\"wasm\",e,10)}Object.defineProperty(ve.versions,\"web\",{value:Oa,enumerable:!0});export{Mp as InferenceSession,Cr as TRACE,Ue as TRACE_FUNC_BEGIN,Be as TRACE_FUNC_END,De as Tensor,Up as TrainingSession,y1 as default,ve as env,xt as registerBackend};\n/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n//# sourceMappingURL=ort.webgpu.bundle.min.mjs.map\n","/**\n * @file Handler file for choosing the correct version of ONNX Runtime, based on the environment.\n * Ideally, we could import the `onnxruntime-web` and `onnxruntime-node` packages only when needed,\n * but dynamic imports don't seem to work with the current webpack version and/or configuration.\n * This is possibly due to the experimental nature of top-level await statements.\n * So, we just import both packages, and use the appropriate one based on the environment:\n * - When running in node, we use `onnxruntime-node`.\n * - When running in the browser, we use `onnxruntime-web` (`onnxruntime-node` is not bundled).\n * \n * This module is not directly exported, but can be accessed through the environment variables:\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * console.log(env.backends.onnx);\n * ```\n * \n * @module backends/onnx\n */\n\nimport { env, apis } from '../env.js';\n\n// NOTE: Import order matters here. We need to import `onnxruntime-node` before `onnxruntime-web`.\n// In either case, we select the default export if it exists, otherwise we use the named export.\nimport * as ONNX_NODE from 'onnxruntime-node';\n\n// Use subpath-imports to ensure Node.js and browser interoperability.\n// See package.json and https://nodejs.org/api/packages.html#subpath-imports\n// for more information.\n// @ts-ignore\nimport * as ONNX_WEB from '#onnxruntime-webgpu';\n\nexport { Tensor } from 'onnxruntime-common';\n\n/**\n * @typedef {import('onnxruntime-common').InferenceSession.ExecutionProviderConfig} ONNXExecutionProviders\n */\n\n/** @type {Record} */\nconst DEVICE_TO_EXECUTION_PROVIDER_MAPPING = Object.freeze({\n auto: null, // Auto-detect based on device and environment\n gpu: null, // Auto-detect GPU\n cpu: 'cpu', // CPU\n wasm: 'wasm', // WebAssembly\n webgpu: 'webgpu', // WebGPU\n cuda: 'cuda', // CUDA\n dml: 'dml', // DirectML\n\n webnn: { name: 'webnn', deviceType: 'cpu' }, // WebNN (default)\n 'webnn-npu': { name: 'webnn', deviceType: 'npu' }, // WebNN NPU\n 'webnn-gpu': { name: 'webnn', deviceType: 'gpu' }, // WebNN GPU\n 'webnn-cpu': { name: 'webnn', deviceType: 'cpu' }, // WebNN CPU\n});\n\n/** \n * The list of supported devices, sorted by priority/performance.\n * @type {import(\"../utils/devices.js\").DeviceType[]}\n */\nconst supportedDevices = [];\n\n/** @type {ONNXExecutionProviders[]} */\nlet defaultDevices;\nlet ONNX;\nconst ORT_SYMBOL = Symbol.for('onnxruntime');\n\nif (ORT_SYMBOL in globalThis) {\n // If the JS runtime exposes their own ONNX runtime, use it\n ONNX = globalThis[ORT_SYMBOL];\n\n} else if (apis.IS_NODE_ENV) {\n ONNX = ONNX_NODE.default ?? ONNX_NODE;\n\n // Updated as of ONNX Runtime 1.18.0\n // The following table lists the supported versions of ONNX Runtime Node.js binding provided with pre-built binaries.\n // | EPs/Platforms | Windows x64 | Windows arm64 | Linux x64 | Linux arm64 | MacOS x64 | MacOS arm64 |\n // | ------------- | ----------- | ------------- | ----------------- | ----------- | --------- | ----------- |\n // | CPU | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |\n // | DirectML | ✔️ | ✔️ | ❌ | ❌ | ❌ | ❌ |\n // | CUDA | ❌ | ❌ | ✔️ (CUDA v11.8) | ❌ | ❌ | ❌ |\n switch (process.platform) {\n case 'win32': // Windows x64 and Windows arm64\n supportedDevices.push('dml');\n break;\n case 'linux': // Linux x64 and Linux arm64\n if (process.arch === 'x64') {\n supportedDevices.push('cuda');\n }\n break;\n case 'darwin': // MacOS x64 and MacOS arm64\n break;\n }\n\n supportedDevices.push('cpu');\n defaultDevices = ['cpu'];\n} else {\n ONNX = ONNX_WEB;\n\n if (apis.IS_WEBNN_AVAILABLE) {\n // TODO: Only push supported providers (depending on available hardware)\n supportedDevices.push('webnn-npu', 'webnn-gpu', 'webnn-cpu', 'webnn');\n }\n\n if (apis.IS_WEBGPU_AVAILABLE) {\n supportedDevices.push('webgpu');\n }\n\n supportedDevices.push('wasm');\n defaultDevices = ['wasm'];\n}\n\n// @ts-ignore\nconst InferenceSession = ONNX.InferenceSession;\n\n/**\n * Map a device to the execution providers to use for the given device.\n * @param {import(\"../utils/devices.js\").DeviceType|\"auto\"|null} [device=null] (Optional) The device to run the inference on.\n * @returns {ONNXExecutionProviders[]} The execution providers to use for the given device.\n */\nexport function deviceToExecutionProviders(device = null) {\n // Use the default execution providers if the user hasn't specified anything\n if (!device) return defaultDevices;\n\n // Handle overloaded cases\n switch (device) {\n case \"auto\":\n return supportedDevices;\n case \"gpu\":\n return supportedDevices.filter(x =>\n [\"webgpu\", \"cuda\", \"dml\", \"webnn-gpu\"].includes(x),\n );\n }\n\n if (supportedDevices.includes(device)) {\n return [DEVICE_TO_EXECUTION_PROVIDER_MAPPING[device] ?? device];\n }\n\n throw new Error(`Unsupported device: \"${device}\". Should be one of: ${supportedDevices.join(', ')}.`)\n}\n\n\n/**\n * To prevent multiple calls to `initWasm()`, we store the first call in a Promise\n * that is resolved when the first InferenceSession is created. Subsequent calls\n * will wait for this Promise to resolve before creating their own InferenceSession.\n * @type {Promise|null}\n */\nlet wasmInitPromise = null;\n\n/**\n * Create an ONNX inference session.\n * @param {Uint8Array} buffer The ONNX model buffer.\n * @param {import('onnxruntime-common').InferenceSession.SessionOptions} session_options ONNX inference session options.\n * @param {Object} session_config ONNX inference session configuration.\n * @returns {Promise} The ONNX inference session.\n */\nexport async function createInferenceSession(buffer, session_options, session_config) {\n if (wasmInitPromise) {\n // A previous session has already initialized the WASM runtime\n // so we wait for it to resolve before creating this new session.\n await wasmInitPromise;\n }\n\n const sessionPromise = InferenceSession.create(buffer, session_options);\n wasmInitPromise ??= sessionPromise;\n const session = await sessionPromise;\n session.config = session_config;\n return session;\n}\n\n/**\n * Check if an object is an ONNX tensor.\n * @param {any} x The object to check\n * @returns {boolean} Whether the object is an ONNX tensor.\n */\nexport function isONNXTensor(x) {\n return x instanceof ONNX.Tensor;\n}\n\n/** @type {import('onnxruntime-common').Env} */\n// @ts-ignore\nconst ONNX_ENV = ONNX?.env;\nif (ONNX_ENV?.wasm) {\n // Initialize wasm backend with suitable default settings.\n\n // (Optional) Set path to wasm files. This is needed when running in a web worker.\n // https://onnxruntime.ai/docs/api/js/interfaces/Env.WebAssemblyFlags.html#wasmPaths\n // We use remote wasm files by default to make it easier for newer users.\n // In practice, users should probably self-host the necessary .wasm files.\n ONNX_ENV.wasm.wasmPaths = `https://cdn.jsdelivr.net/npm/@huggingface/transformers@${env.version}/dist/`;\n\n // TODO: Add support for loading WASM files from cached buffer when we upgrade to onnxruntime-web@1.19.0\n // https://github.com/microsoft/onnxruntime/pull/21534\n\n // Users may wish to proxy the WASM backend to prevent the UI from freezing,\n // However, this is not necessary when using WebGPU, so we default to false.\n ONNX_ENV.wasm.proxy = false;\n\n // https://developer.mozilla.org/en-US/docs/Web/API/crossOriginIsolated\n if (typeof crossOriginIsolated === 'undefined' || !crossOriginIsolated) {\n ONNX_ENV.wasm.numThreads = 1;\n }\n}\n\nif (ONNX_ENV?.webgpu) {\n ONNX_ENV.webgpu.powerPreference = 'high-performance';\n}\n\n/**\n * Check if ONNX's WASM backend is being proxied.\n * @returns {boolean} Whether ONNX's WASM backend is being proxied.\n */\nexport function isONNXProxy() {\n // TODO: Update this when allowing non-WASM backends.\n return ONNX_ENV?.wasm?.proxy;\n}\n\n// Expose ONNX environment variables to `env.backends.onnx`\nenv.backends.onnx = ONNX_ENV;\n","\n/**\n * @file Helper module for using model configs. For more information, see the corresponding\n * [Python documentation](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoConfig).\n * \n * **Example:** Load an `AutoConfig`.\n * \n * ```javascript\n * import { AutoConfig } from '@huggingface/transformers';\n * const config = await AutoConfig.from_pretrained('bert-base-uncased');\n * console.log(config);\n * // PretrainedConfig {\n * // \"model_type\": \"bert\",\n * // \"is_encoder_decoder\": false,\n * // \"architectures\": [\n * // \"BertForMaskedLM\"\n * // ],\n * // \"vocab_size\": 30522\n * // \"num_attention_heads\": 12,\n * // \"num_hidden_layers\": 12,\n * // \"hidden_size\": 768,\n * // \"max_position_embeddings\": 512,\n * // ...\n * // }\n * ```\n * \n * @module configs\n */\n\nimport { pick } from './utils/core.js';\nimport {\n getModelJSON,\n} from './utils/hub.js';\n\n/**\n * @typedef {import('./utils/hub.js').PretrainedOptions} PretrainedOptions\n */\n\n\n/**\n * Loads a config from the specified path.\n * @param {string} pretrained_model_name_or_path The path to the config directory.\n * @param {PretrainedOptions} options Additional options for loading the config.\n * @returns {Promise} A promise that resolves with information about the loaded config.\n */\nasync function loadConfig(pretrained_model_name_or_path, options) {\n return await getModelJSON(pretrained_model_name_or_path, 'config.json', true, options);\n}\n\n/**\n * \n * @param {PretrainedConfig} config \n * @returns {Object} The normalized configuration.\n */\nfunction getNormalizedConfig(config) {\n const mapping = {};\n\n let init_normalized_config = {};\n switch (config.model_type) {\n // Sub-configs\n case 'llava':\n case 'paligemma':\n case 'florence2':\n init_normalized_config = getNormalizedConfig(config.text_config);\n break;\n case 'moondream1':\n init_normalized_config = getNormalizedConfig(config.phi_config);\n break;\n case 'musicgen':\n init_normalized_config = getNormalizedConfig(config.decoder);\n break;\n\n // Decoder-only models\n case 'gpt2':\n case 'gptj':\n case 'jais':\n case 'codegen':\n case 'gpt_bigcode':\n mapping['num_heads'] = 'n_head';\n mapping['num_layers'] = 'n_layer';\n mapping['hidden_size'] = 'n_embd';\n break;\n case 'gpt_neox':\n case 'stablelm':\n case 'opt':\n case 'phi':\n case 'phi3':\n case 'falcon':\n mapping['num_heads'] = 'num_attention_heads';\n mapping['num_layers'] = 'num_hidden_layers';\n mapping['hidden_size'] = 'hidden_size';\n break;\n case 'llama':\n case 'granite':\n case 'cohere':\n case 'mistral':\n case 'starcoder2':\n case 'qwen2':\n mapping['num_heads'] = 'num_key_value_heads';\n mapping['num_layers'] = 'num_hidden_layers';\n mapping['hidden_size'] = 'hidden_size';\n mapping['num_attention_heads'] = 'num_attention_heads';\n break;\n case 'gemma':\n case 'gemma2':\n mapping['num_heads'] = 'num_key_value_heads';\n mapping['num_layers'] = 'num_hidden_layers';\n mapping['dim_kv'] = 'head_dim';\n break;\n case 'openelm':\n mapping['num_heads'] = 'num_kv_heads';\n mapping['num_layers'] = 'num_transformer_layers';\n mapping['dim_kv'] = 'head_dim';\n break;\n case 'gpt_neo':\n case 'donut-swin':\n mapping['num_heads'] = 'num_heads';\n mapping['num_layers'] = 'num_layers';\n mapping['hidden_size'] = 'hidden_size';\n break;\n case 'bloom':\n mapping['num_heads'] = 'n_head';\n mapping['num_layers'] = 'n_layer';\n mapping['hidden_size'] = 'hidden_size';\n break;\n case 'mpt':\n mapping['num_heads'] = 'n_heads';\n mapping['num_layers'] = 'n_layers';\n mapping['hidden_size'] = 'd_model';\n break;\n\n // Encoder-decoder models\n case 't5':\n case 'mt5':\n case 'longt5':\n mapping['num_decoder_layers'] = 'num_decoder_layers';\n mapping['num_decoder_heads'] = 'num_heads';\n mapping['decoder_dim_kv'] = 'd_kv';\n mapping['num_encoder_layers'] = 'num_layers';\n mapping['num_encoder_heads'] = 'num_heads';\n mapping['encoder_dim_kv'] = 'd_kv';\n break;\n case 'bart':\n case 'mbart':\n case 'marian':\n case 'whisper':\n case 'm2m_100':\n case 'blenderbot':\n case 'blenderbot-small':\n case 'florence2_language':\n mapping['num_decoder_layers'] = 'decoder_layers';\n mapping['num_decoder_heads'] = 'decoder_attention_heads';\n mapping['decoder_hidden_size'] = 'd_model';\n mapping['num_encoder_layers'] = 'encoder_layers';\n mapping['num_encoder_heads'] = 'encoder_attention_heads';\n mapping['encoder_hidden_size'] = 'd_model';\n break;\n case 'speecht5':\n mapping['num_decoder_layers'] = 'decoder_layers';\n mapping['num_decoder_heads'] = 'decoder_attention_heads';\n mapping['decoder_hidden_size'] = 'hidden_size';\n mapping['num_encoder_layers'] = 'encoder_layers';\n mapping['num_encoder_heads'] = 'encoder_attention_heads';\n mapping['encoder_hidden_size'] = 'hidden_size';\n break;\n case 'trocr':\n mapping['num_encoder_layers'] = mapping['num_decoder_layers'] = 'decoder_layers';\n mapping['num_encoder_heads'] = mapping['num_decoder_heads'] = 'decoder_attention_heads';\n mapping['encoder_hidden_size'] = mapping['decoder_hidden_size'] = 'd_model';\n break;\n case 'musicgen_decoder':\n mapping['num_encoder_layers'] = mapping['num_decoder_layers'] = 'num_hidden_layers';\n mapping['num_encoder_heads'] = mapping['num_decoder_heads'] = 'num_attention_heads';\n mapping['encoder_hidden_size'] = mapping['decoder_hidden_size'] = 'hidden_size';\n break;\n\n case 'vision-encoder-decoder':\n const decoderConfig = getNormalizedConfig(config.decoder);\n\n const add_encoder_pkv = 'num_decoder_layers' in decoderConfig;\n const result = pick(config, ['model_type', 'is_encoder_decoder']);\n if (add_encoder_pkv) {\n // Decoder is part of an encoder-decoder model\n result.num_decoder_layers = decoderConfig.num_decoder_layers;\n result.num_decoder_heads = decoderConfig.num_decoder_heads;\n result.decoder_hidden_size = decoderConfig.decoder_hidden_size;\n\n result.num_encoder_layers = decoderConfig.num_encoder_layers;\n result.num_encoder_heads = decoderConfig.num_encoder_heads;\n result.encoder_hidden_size = decoderConfig.encoder_hidden_size;\n } else {\n // Decoder is a decoder-only model\n result.num_layers = decoderConfig.num_layers;\n result.num_heads = decoderConfig.num_heads;\n result.hidden_size = decoderConfig.hidden_size;\n }\n return result;\n\n }\n\n // NOTE: If `num_attention_heads` is not set, it is assumed to be equal to `num_heads`\n const normalized_config = {\n ...init_normalized_config,\n ...pick(config, ['model_type', 'multi_query', 'is_encoder_decoder']),\n };\n for (const key in mapping) {\n normalized_config[key] = config[mapping[key]];\n }\n return normalized_config;\n}\n\n/**\n * \n * @param {PretrainedConfig} config \n * @returns {Record}\n */\nexport function getKeyValueShapes(config, {\n prefix = 'past_key_values',\n} = {}) {\n /** @type {Record} */\n const decoderFeeds = {};\n const normalized_config = config.normalized_config;\n\n // TODO support batches (i.e., batch_size > 1)\n const batch_size = 1;\n\n if (normalized_config.is_encoder_decoder && (\n 'num_encoder_heads' in normalized_config && 'num_decoder_heads' in normalized_config\n )) {\n const encoder_dim_kv = normalized_config.encoder_dim_kv ?? (\n normalized_config.encoder_hidden_size / normalized_config.num_encoder_heads\n );\n const decoder_dim_kv = normalized_config.decoder_dim_kv ?? (\n normalized_config.decoder_hidden_size / normalized_config.num_decoder_heads\n );\n\n const encoder_dims = [batch_size, normalized_config.num_encoder_heads, 0, encoder_dim_kv];\n const decoder_dims = [batch_size, normalized_config.num_decoder_heads, 0, decoder_dim_kv];\n for (let i = 0; i < normalized_config.num_decoder_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.encoder.key`] = encoder_dims;\n decoderFeeds[`${prefix}.${i}.encoder.value`] = encoder_dims;\n decoderFeeds[`${prefix}.${i}.decoder.key`] = decoder_dims;\n decoderFeeds[`${prefix}.${i}.decoder.value`] = decoder_dims;\n }\n } else { // Decoders\n const num_heads = normalized_config.num_heads;\n const num_layers = normalized_config.num_layers;\n const dim_kv = normalized_config.dim_kv ?? (\n normalized_config.hidden_size /\n (normalized_config.num_attention_heads ?? num_heads)\n );\n\n if (normalized_config.model_type === 'falcon') {\n // NOTE: Custom implementation for Falcon\n const dims = [batch_size * num_heads, 0, dim_kv]\n for (let i = 0; i < num_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.key`] = dims;\n decoderFeeds[`${prefix}.${i}.value`] = dims;\n }\n } else if (normalized_config.multi_query) { // e.g., for `gpt_bigcode`\n const dims = [batch_size * num_heads, 0, 2 * dim_kv]\n\n for (let i = 0; i < num_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.key_value`] = dims;\n }\n } else if (normalized_config.model_type === 'bloom') {\n // NOTE: Custom implementation for Bloom\n\n const keyDims = [batch_size * num_heads, dim_kv, 0] // [batch_size x num_heads,64,past_sequence_length]\n const valueDims = [batch_size * num_heads, 0, dim_kv] // [batch_size x num_heads,past_sequence_length,64]\n for (let i = 0; i < num_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.key`] = keyDims;\n decoderFeeds[`${prefix}.${i}.value`] = valueDims;\n }\n } else if (normalized_config.model_type === 'openelm') {\n for (let i = 0; i < num_layers; ++i) {\n const dims = [batch_size, num_heads[i], 0, dim_kv]\n\n decoderFeeds[`${prefix}.${i}.key`] = dims;\n decoderFeeds[`${prefix}.${i}.value`] = dims;\n }\n } else { // Decoder-only\n const dims = [batch_size, num_heads, 0, dim_kv]\n for (let i = 0; i < num_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.key`] = dims;\n decoderFeeds[`${prefix}.${i}.value`] = dims;\n }\n }\n }\n\n return decoderFeeds;\n}\n/**\n * Base class for all configuration classes. For more information, see the corresponding\n * [Python documentation](https://huggingface.co/docs/transformers/main/en/main_classes/configuration#transformers.PretrainedConfig).\n */\nexport class PretrainedConfig {\n // NOTE: Typo in original\n\n /** @type {string|null} */\n model_type = null;\n\n /** @type {boolean} */\n is_encoder_decoder = false;\n\n /** @type {number} */\n max_position_embeddings;\n\n /** @type {TransformersJSConfig} */\n 'transformers.js_config';\n\n /**\n * Create a new PreTrainedTokenizer instance.\n * @param {Object} configJSON The JSON of the config.\n */\n constructor(configJSON) {\n Object.assign(this, configJSON);\n this.normalized_config = getNormalizedConfig(this);\n }\n\n /**\n * Loads a pre-trained config from the given `pretrained_model_name_or_path`. \n * \n * @param {string} pretrained_model_name_or_path The path to the pre-trained config.\n * @param {PretrainedOptions} options Additional options for loading the config.\n * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.\n * \n * @returns {Promise} A new instance of the `PretrainedConfig` class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n } = {}) {\n if (config && !(config instanceof PretrainedConfig)) {\n config = new PretrainedConfig(config);\n }\n\n const data = config ?? await loadConfig(pretrained_model_name_or_path, {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n })\n return new this(data);\n }\n}\n\n/**\n * Helper class which is used to instantiate pretrained configs with the `from_pretrained` function.\n * \n * @example\n * const config = await AutoConfig.from_pretrained('Xenova/bert-base-uncased'); \n */\nexport class AutoConfig {\n /** @type {typeof PretrainedConfig.from_pretrained} */\n static async from_pretrained(...args) {\n return PretrainedConfig.from_pretrained(...args);\n }\n}\n\n/**\n * Transformers.js-specific configuration, possibly present in config.json under the key `transformers.js_config`.\n * @typedef {Object} TransformersJSConfig\n * @property {import('./utils/tensor.js').DataType|Record} [kv_cache_dtype] The data type of the key-value cache.\n * @property {Record} [free_dimension_overrides] Override the free dimensions of the model.\n * See https://onnxruntime.ai/docs/tutorials/web/env-flags-and-session-options.html#freedimensionoverrides\n * for more information.\n * @property {import('./utils/devices.js').DeviceType} [device] The default device to use for the model.\n * @property {import('./utils/dtypes.js').DataType} [dtype] The default data type to use for the model.\n * @property {boolean|Record} [use_external_data_format=false] Whether to load the model using the external data format (used for models >= 2GB in size).\n */\n","/**\n * @file Module used to configure Transformers.js.\n * \n * **Example:** Disable remote models.\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * env.allowRemoteModels = false;\n * ```\n * \n * **Example:** Set local model path.\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * env.localModelPath = '/path/to/local/models/';\n * ```\n * \n * **Example:** Set cache directory.\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * env.cacheDir = '/path/to/cache/directory/';\n * ```\n * \n * @module env\n */\n\nimport fs from 'fs';\nimport path from 'path';\nimport url from 'url';\n\nconst VERSION = '3.0.0';\n\n// Check if various APIs are available (depends on environment)\nconst IS_BROWSER_ENV = typeof self !== 'undefined';\nconst IS_WEBWORKER_ENV = IS_BROWSER_ENV && self.constructor.name === 'DedicatedWorkerGlobalScope';\nconst IS_WEB_CACHE_AVAILABLE = IS_BROWSER_ENV && 'caches' in self;\nconst IS_WEBGPU_AVAILABLE = typeof navigator !== 'undefined' && 'gpu' in navigator;\nconst IS_WEBNN_AVAILABLE = typeof navigator !== 'undefined' && 'ml' in navigator;\n\nconst IS_PROCESS_AVAILABLE = typeof process !== 'undefined';\nconst IS_NODE_ENV = IS_PROCESS_AVAILABLE && process?.release?.name === 'node';\nconst IS_FS_AVAILABLE = !isEmpty(fs);\nconst IS_PATH_AVAILABLE = !isEmpty(path);\n\n/**\n * A read-only object containing information about the APIs available in the current environment.\n */\nexport const apis = Object.freeze({\n /** Whether we are running in a browser environment */\n IS_BROWSER_ENV,\n\n /** Whether we are running in a web worker environment */\n IS_WEBWORKER_ENV,\n\n /** Whether the Cache API is available */\n IS_WEB_CACHE_AVAILABLE,\n\n /** Whether the WebGPU API is available */\n IS_WEBGPU_AVAILABLE,\n\n /** Whether the WebNN API is available */\n IS_WEBNN_AVAILABLE,\n\n /** Whether the Node.js process API is available */\n IS_PROCESS_AVAILABLE,\n\n /** Whether we are running in a Node.js environment */\n IS_NODE_ENV,\n\n /** Whether the filesystem API is available */\n IS_FS_AVAILABLE,\n\n /** Whether the path API is available */\n IS_PATH_AVAILABLE,\n});\n\nconst RUNNING_LOCALLY = IS_FS_AVAILABLE && IS_PATH_AVAILABLE;\nconst dirname__ = RUNNING_LOCALLY\n ? path.dirname(path.dirname(url.fileURLToPath(import.meta.url)))\n : './';\n\n// Only used for environments with access to file system\nconst DEFAULT_CACHE_DIR = RUNNING_LOCALLY\n ? path.join(dirname__, '/.cache/')\n : null;\n\n// Set local model path, based on available APIs\nconst DEFAULT_LOCAL_MODEL_PATH = '/models/';\nconst localModelPath = RUNNING_LOCALLY\n ? path.join(dirname__, DEFAULT_LOCAL_MODEL_PATH)\n : DEFAULT_LOCAL_MODEL_PATH;\n\n/**\n * Global variable given visible to users to control execution. This provides users a simple way to configure Transformers.js.\n * @typedef {Object} TransformersEnvironment\n * @property {string} version This version of Transformers.js.\n * @property {{onnx: Partial}} backends Expose environment variables of different backends,\n * allowing users to set these variables if they want to.\n * @property {boolean} allowRemoteModels Whether to allow loading of remote files, defaults to `true`.\n * If set to `false`, it will have the same effect as setting `local_files_only=true` when loading pipelines, models, tokenizers, processors, etc.\n * @property {string} remoteHost Host URL to load models from. Defaults to the Hugging Face Hub.\n * @property {string} remotePathTemplate Path template to fill in and append to `remoteHost` when loading models.\n * @property {boolean} allowLocalModels Whether to allow loading of local files, defaults to `false` if running in-browser, and `true` otherwise.\n * If set to `false`, it will skip the local file check and try to load the model from the remote host.\n * @property {string} localModelPath Path to load local models from. Defaults to `/models/`.\n * @property {boolean} useFS Whether to use the file system to load files. By default, it is `true` if available.\n * @property {boolean} useBrowserCache Whether to use Cache API to cache models. By default, it is `true` if available.\n * @property {boolean} useFSCache Whether to use the file system to cache files. By default, it is `true` if available.\n * @property {string} cacheDir The directory to use for caching files with the file system. By default, it is `./.cache`.\n * @property {boolean} useCustomCache Whether to use a custom cache system (defined by `customCache`), defaults to `false`.\n * @property {Object} customCache The custom cache to use. Defaults to `null`. Note: this must be an object which\n * implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache\n */\n\n/** @type {TransformersEnvironment} */\nexport const env = {\n version: VERSION,\n\n /////////////////// Backends settings ///////////////////\n // NOTE: These will be populated later by the backends themselves.\n backends: {\n // onnxruntime-web/onnxruntime-node\n onnx: {},\n },\n\n /////////////////// Model settings ///////////////////\n allowRemoteModels: true,\n remoteHost: 'https://huggingface.co/',\n remotePathTemplate: '{model}/resolve/{revision}/',\n\n allowLocalModels: !IS_BROWSER_ENV,\n localModelPath: localModelPath,\n useFS: IS_FS_AVAILABLE,\n\n /////////////////// Cache settings ///////////////////\n useBrowserCache: IS_WEB_CACHE_AVAILABLE,\n\n useFSCache: IS_FS_AVAILABLE,\n cacheDir: DEFAULT_CACHE_DIR,\n\n useCustomCache: false,\n customCache: null,\n //////////////////////////////////////////////////////\n}\n\n\n/**\n * @param {Object} obj\n * @private\n */\nfunction isEmpty(obj) {\n return Object.keys(obj).length === 0;\n}\n\n","\n/**\n * @module generation/configuration_utils\n */\n\nimport { pick } from \"../utils/core.js\";\n\n/**\n * Class that holds a configuration for a generation task.\n */\nexport class GenerationConfig {\n // Parameters that control the length of the output\n /**\n * The maximum length the generated tokens can have.\n * Corresponds to the length of the input prompt + `max_new_tokens`.\n * Its effect is overridden by `max_new_tokens`, if also set.\n * @type {number}\n * @default 20\n */\n max_length = 20;\n\n /**\n * The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt.\n * @type {number}\n * @default null\n */\n max_new_tokens = null;\n\n /**\n * The minimum length of the sequence to be generated.\n * Corresponds to the length of the input prompt + `min_new_tokens`.\n * Its effect is overridden by `min_new_tokens`, if also set.\n * @type {number}\n * @default 0\n */\n min_length = 0;\n\n /**\n * The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt.\n * @type {number}\n * @default null\n */\n min_new_tokens = null;\n\n /**\n * Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:\n * - `true`, where the generation stops as soon as there are `num_beams` complete candidates;\n * - `false`, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates;\n * - `\"never\"`, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm).\n * @type {boolean|\"never\"}\n * @default false\n */\n early_stopping = false;\n\n /**\n * The maximum amount of time you allow the computation to run for in seconds.\n * Generation will still finish the current pass after allocated time has been passed.\n * @type {number}\n * @default null\n */\n max_time = null;\n\n // Parameters that control the generation strategy used\n /**\n * Whether or not to use sampling; use greedy decoding otherwise.\n * @type {boolean}\n * @default false\n */\n do_sample = false;\n\n /**\n * Number of beams for beam search. 1 means no beam search.\n * @type {number}\n * @default 1\n */\n num_beams = 1;\n\n /**\n * Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams.\n * See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.\n * @type {number}\n * @default 1\n */\n num_beam_groups = 1;\n\n /**\n * The values balance the model confidence and the degeneration penalty in contrastive search decoding.\n * @type {number}\n * @default null\n */\n penalty_alpha = null;\n\n /**\n * Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding.\n * @type {boolean}\n * @default true\n */\n use_cache = true;\n\n // Parameters for manipulation of the model output logits\n /**\n * The value used to modulate the next token probabilities.\n * @type {number}\n * @default 1.0\n */\n temperature = 1.0;\n\n /**\n * The number of highest probability vocabulary tokens to keep for top-k-filtering.\n * @type {number}\n * @default 50\n */\n top_k = 50;\n\n /**\n * If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation.\n * @type {number}\n * @default 1.0\n */\n top_p = 1.0;\n\n /**\n * Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated.\n * If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to `typical_p` or higher are kept for generation.\n * See [this paper](https://arxiv.org/pdf/2202.00666.pdf) for more details.\n * @type {number}\n * @default 1.0\n */\n typical_p = 1.0;\n\n /**\n * If set to float strictly between 0 and 1, only tokens with a conditional probability greater than `epsilon_cutoff` will be sampled.\n * In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model.\n * See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.\n * @type {number}\n * @default 0.0\n */\n epsilon_cutoff = 0.0;\n\n /**\n * Eta sampling is a hybrid of locally typical sampling and epsilon sampling.\n * If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`.\n * The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model.\n * See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.\n * @type {number}\n * @default 0.0\n */\n eta_cutoff = 0.0;\n\n /**\n * This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time.\n * Note that `diversity_penalty` is only effective if `group beam search` is enabled.\n * @type {number}\n * @default 0.0\n */\n diversity_penalty = 0.0;\n\n /**\n * The parameter for repetition penalty. 1.0 means no penalty.\n * See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.\n * @type {number}\n * @default 1.0\n */\n repetition_penalty = 1.0;\n\n /**\n * The paramater for encoder_repetition_penalty.\n * An exponential penalty on sequences that are not in the original input.\n * 1.0 means no penalty.\n * @type {number}\n * @default 1.0\n */\n encoder_repetition_penalty = 1.0;\n\n /**\n * Exponential penalty to the length that is used with beam-based generation.\n * It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence.\n * Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences.\n * @type {number}\n * @default 1.0\n */\n length_penalty = 1.0;\n\n /**\n * If set to int > 0, all ngrams of that size can only occur once.\n * @type {number}\n * @default 0\n */\n no_repeat_ngram_size = 0;\n\n /**\n * List of token ids that are not allowed to be generated.\n * In order to get the token ids of the words that should not appear in the generated text, use\n * `tokenizer(bad_words, { add_prefix_space: true, add_special_tokens: false }).input_ids`.\n * @type {number[][]}\n * @default null\n */\n bad_words_ids = null;\n\n /**\n * List of token ids that must be generated.\n * If given a `number[][]`, this is treated as a simple list of words that must be included, the opposite to `bad_words_ids`.\n * If given `number[][][]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one can allow different forms of each word.\n * @type {number[][]|number[][][]}\n * @default null\n */\n force_words_ids = null;\n\n /**\n * Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones).\n * It's highly recommended to set this flag to `true` as the search algorithms suppose the score logits are normalized but some logit processors or warpers break the normalization.\n * @type {boolean}\n * @default false\n */\n renormalize_logits = false;\n\n /**\n * Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by `Constraint` objects, in the most sensible way possible.\n * @type {Object[]}\n * @default null\n */\n constraints = null;\n\n /**\n * The id of the token to force as the first generated token after the `decoder_start_token_id`.\n * Useful for multilingual models like mBART where the first generated token needs to be the target language token.\n * @type {number}\n * @default null\n */\n forced_bos_token_id = null;\n\n /**\n * The id of the token to force as the last generated token when `max_length` is reached.\n * Optionally, use a list to set multiple *end-of-sequence* tokens.\n * @type {number|number[]}\n * @default null\n */\n forced_eos_token_id = null;\n\n /**\n * Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash. Note that using `remove_invalid_values` can slow down generation.\n * @type {boolean}\n */\n remove_invalid_values = false;\n\n /**\n * This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been generated.\n * The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty starts and `decay_factor` represents the factor of exponential decay.\n * @type {[number, number]}\n * @default null\n */\n exponential_decay_length_penalty = null;\n\n /**\n * A list of tokens that will be suppressed at generation.\n * The `SuppressTokens` logit processor will set their log probs to `-inf` so that they are not sampled.\n * @type {number[]}\n * @default null\n */\n suppress_tokens = null;\n\n /**\n * A list of tokens that will be suppressed at the beginning of the generation.\n * The `SuppressBeginTokens` logit processor will set their log probs to `-inf` so that they are not sampled.\n * @type {number[]}\n * @default null\n */\n begin_suppress_tokens = null;\n\n /**\n * A list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling.\n * For example, `[[1, 123]]` means the second generated token will always be a token of index 123.\n * @type {[number, number][]}\n * @default null\n */\n forced_decoder_ids = null;\n\n /**\n * The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.\n * Higher guidance scale encourages the model to generate samples that are more closely linked to the input\n * prompt, usually at the expense of poorer quality.\n * @type {number}\n * @default null\n */\n guidance_scale = null;\n\n // Parameters that define the output variables of `generate`\n /**\n * The number of independently computed returned sequences for each element in the batch.\n * @type {number}\n * @default 1\n */\n num_return_sequences = 1;\n\n /**\n * Whether or not to return the attentions tensors of all attention layers.\n * See `attentions` under returned tensors for more details.\n * @type {boolean}\n * @default false\n */\n output_attentions = false;\n\n /**\n * Whether or not to return the hidden states of all layers.\n * See `hidden_states` under returned tensors for more details.\n * @type {boolean}\n * @default false\n */\n output_hidden_states = false;\n\n /**\n * Whether or not to return the prediction scores.\n * See `scores` under returned tensors for more details.\n * @type {boolean}\n * @default false\n */\n output_scores = false;\n\n /**\n * Whether or not to return a `ModelOutput` instead of a plain tuple.\n * @type {boolean}\n * @default false\n */\n return_dict_in_generate = false;\n\n // Special tokens that can be used at generation time\n /**\n * The id of the *padding* token.\n * @type {number}\n * @default null\n */\n pad_token_id = null;\n\n /**\n * The id of the *beginning-of-sequence* token.\n * @type {number}\n * @default null\n */\n bos_token_id = null;\n\n /**\n * The id of the *end-of-sequence* token.\n * Optionally, use a list to set multiple *end-of-sequence* tokens.\n * @type {number|number[]}\n * @default null\n */\n eos_token_id = null;\n\n // Generation parameters exclusive to encoder-decoder models\n /**\n * If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`.\n * @type {number}\n * @default 0\n */\n encoder_no_repeat_ngram_size = 0;\n\n /**\n * If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token.\n * @type {number}\n * @default null\n */\n decoder_start_token_id = null;\n\n // Wild card\n /**\n * Additional generation kwargs will be forwarded to the `generate` function of the model.\n * Kwargs that are not present in `generate`'s signature will be used in the model forward pass.\n * @type {Object}\n * @default {}\n */\n generation_kwargs = {};\n\n /**\n * \n * @param {GenerationConfig|import('../configs.js').PretrainedConfig} config \n */\n constructor(config) {\n Object.assign(this, pick(config, Object.getOwnPropertyNames(this)));\n }\n}\n\n","\n/**\n * @module generation/logits_process\n */\n\nimport { Callable } from \"../utils/generic.js\";\nimport { Tensor } from \"../utils/tensor.js\";\n\nimport { max, log_softmax } from \"../utils/maths.js\";\n\n/**\n * Abstract base class for all logit processors that can be applied during generation.\n */\nexport class LogitsProcessor extends Callable {\n /**\n * Apply the processor to the input logits.\n *\n * @abstract\n * @param {bigint[][]} input_ids The input ids.\n * @param {Tensor} logits The logits to process.\n * @throws {Error} Throws an error if `_call` is not implemented in the subclass.\n */\n _call(input_ids, logits) {\n throw Error(\"`_call` should be implemented in a subclass\")\n }\n}\n\n\n/**\n * Abstract base class for all logit warpers that can be applied during generation with multinomial sampling.\n */\nexport class LogitsWarper extends Callable {\n /**\n * Apply the processor to the input logits.\n *\n * @abstract\n * @param {bigint[][]} input_ids The input ids.\n * @param {Tensor} logits The logits to process.\n * @throws {Error} Throws an error if `_call` is not implemented in the subclass.\n */\n _call(input_ids, logits) {\n throw Error(\"`_call` should be implemented in a subclass\")\n }\n}\n\n\n/**\n * A class representing a list of logits processors. A logits processor is a function that modifies the logits\n * output of a language model. This class provides methods for adding new processors and applying all processors to a\n * batch of logits.\n */\nexport class LogitsProcessorList extends Callable {\n /**\n * Constructs a new instance of `LogitsProcessorList`.\n */\n constructor() {\n super();\n this.processors = [];\n }\n\n /**\n * Adds a new logits processor to the list.\n *\n * @param {LogitsProcessor} item The logits processor function to add.\n */\n push(item) {\n this.processors.push(item);\n }\n\n /**\n * Adds multiple logits processors to the list.\n *\n * @param {LogitsProcessor[]} items The logits processor functions to add.\n */\n extend(items) {\n this.processors.push(...items);\n }\n\n /**\n * Applies all logits processors in the list to a batch of logits, modifying them in-place.\n *\n * @param {bigint[][]} input_ids The input IDs for the language model.\n * @param {Tensor} logits\n */\n _call(input_ids, logits) {\n let toReturn = logits;\n // NOTE: Most processors modify logits inplace\n for (const processor of this.processors) {\n toReturn = processor(input_ids, toReturn);\n }\n return toReturn;\n }\n\n [Symbol.iterator]() {\n return this.processors.values();\n }\n}\n\n// DEPRECATED: https://github.com/huggingface/transformers/pull/29485\n// /**\n// * A logits processor that forces a specific token to be generated by the decoder.\n// */\n// export class ForceTokensLogitsProcessor extends LogitsProcessor {\n// /**\n// * Constructs a new instance of `ForceTokensLogitsProcessor`.\n// * \n// * @param {[number, number][]} forced_decoder_ids The ids of tokens that should be forced.\n// */\n// constructor(forced_decoder_ids) {\n// super();\n// // TODO: convert to `new Map(forced_decoder_ids)`\n// this.force_token_map = Object.fromEntries(forced_decoder_ids ?? []);\n// }\n\n// /**\n// * Apply the processor to the input logits.\n// *\n// * @param {bigint[][]} input_ids The input ids.\n// * @param {Tensor} logits The logits to process.\n// * @returns {Tensor} The processed logits.\n// */\n// _call(input_ids, logits) {\n// console.log('this.force_token_map', this.force_token_map)\n// console.log('call ForceTokensLogitsProcessor', input_ids, logits)\n// console.log('input_ids.length', input_ids.length)\n// let map = this.force_token_map[input_ids.length];\n// if (map) { // There exists a mapping\n// logits.data.fill(-Infinity)\n// logits.data[map] = 0;\n// }\n// console.log('map', map)\n// // throw Error(\"Not implemented\")\n// return logits;\n// }\n// }\n\n/**\n * A LogitsProcessor that forces a BOS token at the beginning of the generated sequence.\n */\nexport class ForcedBOSTokenLogitsProcessor extends LogitsProcessor {\n /**\n * Create a ForcedBOSTokenLogitsProcessor.\n * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced.\n */\n constructor(bos_token_id) {\n super();\n this.bos_token_id = bos_token_id;\n }\n\n /**\n * Apply the BOS token forcing to the logits.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The logits with BOS token forcing.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n if (input_ids[i].length === 1) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n batch_logits_data.fill(-Infinity);\n batch_logits_data[this.bos_token_id] = 0;\n }\n }\n return logits;\n }\n}\n\n/**\n * A logits processor that enforces the specified token as the last generated token when `max_length` is reached.\n */\nexport class ForcedEOSTokenLogitsProcessor extends LogitsProcessor {\n /**\n * Create a ForcedEOSTokenLogitsProcessor.\n * @param {number} max_length The maximum length of the sequence to be generated.\n * @param {number|number[]} eos_token_id The id(s) of the *end-of-sequence* token.\n */\n constructor(max_length, eos_token_id) {\n super();\n this.max_length = max_length;\n this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];\n }\n\n /**\n * Apply the processor to input_ids and logits.\n * \n * @param {bigint[][]} input_ids The input ids.\n * @param {Tensor} logits The logits tensor.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n if (input_ids[i].length === this.max_length - 1) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n batch_logits_data.fill(-Infinity);\n for (const eos_token of this.eos_token_id) {\n batch_logits_data[eos_token] = 0;\n }\n }\n }\n return logits;\n }\n}\n\n/**\n * A LogitsProcessor that suppresses a list of tokens as soon as the `generate` function starts\n * generating using `begin_index` tokens. This should ensure that the tokens defined by\n * `begin_suppress_tokens` at not sampled at the begining of the generation.\n */\nexport class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor {\n /**\n * Create a SuppressTokensAtBeginLogitsProcessor.\n * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress.\n * @param {number} begin_index The number of tokens to generate before suppressing tokens.\n */\n constructor(begin_suppress_tokens, begin_index) {\n super();\n this.begin_suppress_tokens = begin_suppress_tokens;\n this.begin_index = begin_index;\n }\n\n /**\n * Apply the BOS token forcing to the logits.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The logits with BOS token forcing.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n if (input_ids[i].length === this.begin_index) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n for (const token_id of this.begin_suppress_tokens) {\n batch_logits_data[token_id] = -Infinity;\n }\n }\n }\n return logits;\n }\n}\n\n/**\n * A LogitsProcessor that handles adding timestamps to generated text.\n */\nexport class WhisperTimeStampLogitsProcessor extends LogitsProcessor {\n /**\n * Constructs a new WhisperTimeStampLogitsProcessor.\n * @param {import('../models/whisper/generation_whisper.js').WhisperGenerationConfig} generate_config The config object passed to the `generate()` method of a transformer model.\n * @param {number[]} init_tokens The initial tokens of the input sequence.\n */\n constructor(generate_config, init_tokens) {\n super();\n this.eos_token_id =\n Array.isArray(generate_config.eos_token_id)\n ? generate_config.eos_token_id[0]\n : generate_config.eos_token_id;\n\n this.no_timestamps_token_id = generate_config.no_timestamps_token_id;\n this.timestamp_begin = this.no_timestamps_token_id + 1;\n\n this.begin_index = init_tokens.length;\n if (init_tokens.at(-1) === this.no_timestamps_token_id) {\n this.begin_index -= 1;\n }\n this.max_initial_timestamp_index = generate_config.max_initial_timestamp_index;\n }\n\n /**\n * Modify the logits to handle timestamp tokens.\n * @param {bigint[][]} input_ids The input sequence of tokens.\n * @param {Tensor} logits The logits output by the model.\n * @returns {Tensor} The modified logits.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n\n // suppress <|notimestamps|> which is handled by without_timestamps\n batch_logits_data[this.no_timestamps_token_id] = -Infinity;\n\n if (input_ids[i].length === this.begin_index - 1) {\n batch_logits_data.fill(-Infinity);\n batch_logits_data[this.timestamp_begin] = 0;\n continue;\n }\n\n // timestamps have to appear in pairs, except directly before eos_token; mask logits accordingly\n const seq = input_ids[i].slice(this.begin_index);\n const last_was_timestamp = seq.length >= 1 && seq[seq.length - 1] >= this.timestamp_begin;\n const penultimate_was_timestamp = seq.length < 2 || seq[seq.length - 2] >= this.timestamp_begin;\n\n if (last_was_timestamp) {\n if (penultimate_was_timestamp) { // has to be non-timestamp\n batch_logits_data.subarray(this.timestamp_begin).fill(-Infinity);\n } else { // cannot be normal text tokens\n batch_logits_data.subarray(0, this.eos_token_id).fill(-Infinity);\n }\n }\n\n // apply the `max_initial_timestamp` option\n if (input_ids[i].length === this.begin_index && this.max_initial_timestamp_index !== null) {\n const last_allowed = this.timestamp_begin + this.max_initial_timestamp_index;\n batch_logits_data.subarray(last_allowed + 1).fill(-Infinity);\n }\n\n // if sum of probability over timestamps is above any other token, sample timestamp\n const logprobs = log_softmax(batch_logits_data);\n const timestamp_logprob = Math.log(logprobs.subarray(this.timestamp_begin).map(Math.exp).reduce((a, b) => a + b));\n const max_text_token_logprob = max(logprobs.subarray(0, this.timestamp_begin))[0];\n\n if (timestamp_logprob > max_text_token_logprob) {\n batch_logits_data.subarray(0, this.timestamp_begin).fill(-Infinity);\n }\n }\n\n return logits;\n }\n}\n\n/**\n * A logits processor that disallows ngrams of a certain size to be repeated.\n */\nexport class NoRepeatNGramLogitsProcessor extends LogitsProcessor {\n /**\n * Create a NoRepeatNGramLogitsProcessor.\n * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once.\n */\n constructor(no_repeat_ngram_size) {\n super();\n this.no_repeat_ngram_size = no_repeat_ngram_size;\n }\n\n /**\n * Generate n-grams from a sequence of token ids.\n * @param {bigint[]} prevInputIds List of previous input ids\n * @returns {Map} Map of generated n-grams\n */\n getNgrams(prevInputIds) {\n const curLen = prevInputIds.length;\n\n /**@type {number[][]} */\n const ngrams = [];\n for (let j = 0; j < curLen + 1 - this.no_repeat_ngram_size; ++j) {\n const ngram = [];\n for (let k = 0; k < this.no_repeat_ngram_size; ++k) {\n ngram.push(prevInputIds[j + k]);\n }\n ngrams.push(ngram.map(Number));\n }\n\n /** @type {Map} */\n const generatedNgram = new Map();\n for (const ngram of ngrams) {\n const prevNgram = ngram.slice(0, ngram.length - 1);\n const prevNgramKey = JSON.stringify(prevNgram);\n const prevNgramValue = generatedNgram.get(prevNgramKey) ?? [];\n prevNgramValue.push(ngram[ngram.length - 1]);\n generatedNgram.set(prevNgramKey, prevNgramValue);\n }\n return generatedNgram;\n }\n\n /**\n * Generate n-grams from a sequence of token ids.\n * @param {Map} bannedNgrams Map of banned n-grams\n * @param {bigint[]} prevInputIds List of previous input ids\n * @returns {number[]} Map of generated n-grams\n */\n getGeneratedNgrams(bannedNgrams, prevInputIds) {\n const ngramIdx = prevInputIds.slice(prevInputIds.length + 1 - this.no_repeat_ngram_size, prevInputIds.length);\n const banned = bannedNgrams.get(JSON.stringify(ngramIdx.map(Number))) ?? [];\n return banned;\n }\n\n /**\n * Calculate banned n-gram tokens\n * @param {bigint[]} prevInputIds List of previous input ids\n * @returns {number[]} Map of generated n-grams\n */\n calcBannedNgramTokens(prevInputIds) {\n const bannedTokens = [];\n if (prevInputIds.length + 1 < this.no_repeat_ngram_size) {\n // return no banned tokens if we haven't generated no_repeat_ngram_size tokens yet\n return bannedTokens;\n\n } else {\n const generatedNgrams = this.getNgrams(prevInputIds);\n const bannedTokens = this.getGeneratedNgrams(generatedNgrams, prevInputIds);\n return bannedTokens;\n }\n }\n\n /**\n * Apply the no-repeat-ngram processor to the logits.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The logits with no-repeat-ngram processing.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n const bannedTokens = this.calcBannedNgramTokens(input_ids[i]);\n for (const token of bannedTokens) {\n batch_logits_data[token] = -Infinity;\n }\n }\n return logits;\n }\n}\n\n/**\n * A logits processor that penalises repeated output tokens.\n */\nexport class RepetitionPenaltyLogitsProcessor extends LogitsProcessor {\n /**\n * Create a RepetitionPenaltyLogitsProcessor.\n * @param {number} penalty The penalty to apply for repeated tokens.\n */\n constructor(penalty) {\n super();\n this.penalty = penalty;\n }\n\n /**\n * Apply the repetition penalty to the logits.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The logits with repetition penalty processing.\n */\n _call(input_ids, logits) {\n // Modify the logits corresponding to each element in `input_ids`.\n // As a consequence, the logits corresponding to tokens that appear\n // many times in the output will be penalised more.\n\n for (let i = 0; i < input_ids.length; ++i) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n for (const input_id of input_ids[i]) {\n const token = Number(input_id);\n if (batch_logits_data[token] < 0) {\n batch_logits_data[token] *= this.penalty;\n } else {\n batch_logits_data[token] /= this.penalty;\n }\n }\n }\n\n return logits\n }\n}\n\n/**\n * A logits processor that enforces a minimum number of tokens.\n */\nexport class MinLengthLogitsProcessor extends LogitsProcessor {\n /**\n * Create a MinLengthLogitsProcessor.\n * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity.\n * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.\n */\n constructor(min_length, eos_token_id) {\n super();\n this.min_length = min_length;\n this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];\n }\n\n /**\n * Apply logit processor.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n if (input_ids[i].length < this.min_length) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n\n for (const eos_token of this.eos_token_id) {\n batch_logits_data[eos_token] = -Infinity;\n }\n }\n }\n\n return logits\n }\n}\n\n/**\n * A logits processor that enforces a minimum number of new tokens.\n */\nexport class MinNewTokensLengthLogitsProcessor extends LogitsProcessor {\n /**\n * Create a MinNewTokensLengthLogitsProcessor.\n * @param {number} prompt_length_to_skip The input tokens length.\n * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity.\n * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.\n */\n constructor(prompt_length_to_skip, min_new_tokens, eos_token_id) {\n super();\n this.prompt_length_to_skip = prompt_length_to_skip;\n this.min_new_tokens = min_new_tokens;\n this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];\n }\n\n /**\n * Apply logit processor.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n const new_tokens_length = input_ids[i].length - this.prompt_length_to_skip;\n if (new_tokens_length < this.min_new_tokens) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n\n for (const eos_token of this.eos_token_id) {\n batch_logits_data[eos_token] = -Infinity;\n }\n }\n }\n return logits\n }\n}\n\nexport class NoBadWordsLogitsProcessor extends LogitsProcessor {\n /**\n * Create a `NoBadWordsLogitsProcessor`.\n * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated.\n * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.\n */\n constructor(bad_words_ids, eos_token_id) {\n super();\n this.bad_words_ids = bad_words_ids;\n this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];\n }\n\n /**\n * Apply logit processor.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n const ids = input_ids[i];\n for (const bad_word_ids of this.bad_words_ids) {\n // Whether to modify the logits of the last token in the bad word id sequence\n let mark = true;\n\n // For each bad word in the list, if the current sequence of input ids ends with this sequence (excluding the last),\n // then we set the logits of the last bad word id to -Infinity.\n for (let j = 1; j <= bad_word_ids.length - 1 && bad_word_ids.length < ids.length; ++j) {\n\n // NOTE: We use != instead of !== to compare bigint and number\n // @ts-ignore\n if (bad_word_ids.at(-j - 1) != ids.at(-j)) {\n // We have found a mismatch\n mark = false;\n break;\n }\n }\n if (mark) {\n batch_logits_data[bad_word_ids.at(-1)] = -Infinity;\n }\n }\n }\n return logits\n }\n}\n\n/**\n * [`LogitsProcessor`] for classifier free guidance (CFG). The scores are split over the batch dimension,\n * where the first half correspond to the conditional logits (predicted from the input prompt) and the second half\n * correspond to the unconditional logits (predicted from an empty or 'null' prompt). The processor computes a\n * weighted average across the conditional and unconditional logits, parameterised by the `guidance_scale`.\n * \n * See [the paper](https://arxiv.org/abs/2306.05284) for more information.\n */\nexport class ClassifierFreeGuidanceLogitsProcessor extends LogitsProcessor {\n\n /**\n * Create a `ClassifierFreeGuidanceLogitsProcessor`.\n * @param {number} guidance_scale The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.\n * Higher guidance scale encourages the model to generate samples that are more closely linked to the input\n * prompt, usually at the expense of poorer quality.\n */\n constructor(guidance_scale) {\n super();\n if (guidance_scale <= 1) {\n throw new Error(\n `Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${guidance_scale}.`\n )\n }\n this.guidance_scale = guidance_scale;\n }\n\n /**\n * Apply logit processor.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n if (logits.dims[0] !== 2 * input_ids.length) {\n throw new Error(\n `Logits should have twice the batch size of the input ids, the first half of batches corresponding to ` +\n `the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got ` +\n `batch size ${logits.dims[0]} for the logits and ${input_ids.length} for the input ids.`\n )\n }\n\n const unguided_bsz = input_ids.length;\n const cond_logits = logits.slice([0, unguided_bsz], null);\n const uncond_logits = logits.slice([unguided_bsz, logits.dims[0]], null);\n\n // Merge into uncond_logits (to save memory). This is equivalent to the following:\n // scores = uncond_logits + (cond_logits - uncond_logits) * guidance_scale\n for (let i = 0; i < uncond_logits.data.length; ++i) {\n uncond_logits.data[i] += (cond_logits.data[i] - uncond_logits.data[i]) * this.guidance_scale;\n }\n\n return uncond_logits;\n }\n}\n\n/**\n * [`LogitsWarper`] for temperature (exponential scaling output probability distribution), which effectively means\n * that it can control the randomness of the predicted tokens. Often used together with [`TopPLogitsWarper`] and [`TopKLogitsWarper`].\n */\nexport class TemperatureLogitsWarper extends LogitsWarper {\n /**\n * Create a `TemperatureLogitsWarper`.\n * @param {number} temperature Strictly positive float value used to modulate the logits distribution.\n * A value smaller than `1` decreases randomness (and vice versa), with `0` being equivalent to shifting\n * all probability mass to the most likely token.\n */\n constructor(temperature) {\n super();\n\n if (typeof temperature !== 'number' || temperature <= 0) {\n let errorMessage =\n `\\`temperature\\` (=${temperature}) must be a strictly positive float, otherwise your next token scores will be invalid.`;\n\n if (temperature === 0) {\n errorMessage += \" If you're looking for greedy decoding strategies, set `do_sample=false`.\"\n }\n }\n this.temperature = temperature;\n }\n\n /**\n * Apply logit warper.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n const batch_logits_data = /** @type {Float32Array} */(logits.data);\n for (let i = 0; i < batch_logits_data.length; ++i) {\n batch_logits_data[i] /= this.temperature;\n }\n return logits;\n }\n}\n\n/**\n * [`LogitsWarper`] that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off.\n * Often used together with [`TemperatureLogitsWarper`] and [`TopKLogitsWarper`].\n */\nexport class TopPLogitsWarper extends LogitsWarper {\n /**\n * Create a `TopPLogitsWarper`.\n * @param {number} top_p If set to < 1, only the smallest set of most probable tokens with\n * probabilities that add up to `top_p` or higher are kept for generation.\n * @param {Object} options Additional options for the top-p sampling.\n * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value.\n * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered.\n */\n constructor(top_p, {\n filter_value = -Infinity,\n min_tokens_to_keep = 1,\n } = {}) {\n super();\n if (top_p < 0 || top_p > 1.0) {\n throw new Error(`\\`top_p\\` must be a float > 0 and < 1, but is ${top_p}`)\n }\n if (!Number.isInteger(min_tokens_to_keep) || min_tokens_to_keep < 1) {\n throw new Error(`\\`min_tokens_to_keep\\` must be a positive integer, but is ${min_tokens_to_keep}`)\n }\n\n this.top_p = top_p\n this.filter_value = filter_value\n this.min_tokens_to_keep = min_tokens_to_keep\n }\n}\n\n/**\n * [`LogitsWarper`] that performs top-k, i.e. restricting to the k highest probability elements.\n * Often used together with [`TemperatureLogitsWarper`] and [`TopPLogitsWarper`].\n */\nexport class TopKLogitsWarper extends LogitsWarper {\n /**\n * Create a `TopKLogitsWarper`.\n * @param {number} top_k If set to > 0, only the top `top_k` tokens are kept for generation.\n * @param {Object} options Additional options for the top-k sampling.\n * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value.\n * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered.\n */\n constructor(top_k, {\n filter_value = -Infinity,\n min_tokens_to_keep = 1,\n } = {}) {\n super();\n if (!Number.isInteger(top_k) || top_k < 0) {\n throw new Error(`\\`top_k\\` must be a positive integer, but is ${top_k}`)\n }\n\n this.top_k = Math.max(top_k, min_tokens_to_keep)\n this.filter_value = filter_value\n }\n}","\n/**\n * @module generation/logits_sampler\n */\n\nimport { Callable } from \"../utils/generic.js\";\nimport { Tensor, topk } from \"../utils/tensor.js\";\n\nimport {\n max,\n softmax,\n} from '../utils/maths.js';\nimport { GenerationConfig } from '../generation/configuration_utils.js';\n\n/**\n * Sampler is a base class for all sampling methods used for text generation.\n */\nexport class LogitsSampler extends Callable {\n /**\n * Creates a new Sampler object with the specified generation config.\n * @param {GenerationConfig} generation_config The generation config.\n */\n constructor(generation_config) {\n super();\n this.generation_config = generation_config;\n }\n\n /**\n * Executes the sampler, using the specified logits.\n * @param {Tensor} logits\n * @returns {Promise<[bigint, number][]>}\n */\n async _call(logits) {\n // Sample from logits, of dims [batch, sequence_length, vocab_size].\n // If index is specified, sample from [batch, index, vocab_size].\n return this.sample(logits);\n }\n\n /**\n * Abstract method for sampling the logits.\n * @param {Tensor} logits\n * @throws {Error} If not implemented in subclass.\n * @returns {Promise<[bigint, number][]>}\n */\n async sample(logits) {\n throw Error(\"sample should be implemented in subclasses.\")\n }\n\n /**\n * Returns the specified logits as an array, with temperature applied.\n * @param {Tensor} logits\n * @param {number} index\n * @returns {Float32Array}\n */\n getLogits(logits, index) {\n let vocabSize = logits.dims.at(-1);\n\n let logs = /** @type {Float32Array} */(logits.data);\n\n if (index === -1) {\n logs = logs.slice(-vocabSize);\n } else {\n let startIndex = index * vocabSize;\n logs = logs.slice(startIndex, startIndex + vocabSize);\n }\n return logs;\n }\n\n /**\n * Selects an item randomly based on the specified probabilities.\n * @param {import(\"../transformers.js\").DataArray} probabilities An array of probabilities to use for selection.\n * @returns {number} The index of the selected item.\n */\n randomSelect(probabilities) {\n // Return index of chosen item\n let sumProbabilities = 0;\n for (let i = 0; i < probabilities.length; ++i) {\n sumProbabilities += probabilities[i];\n }\n\n let r = Math.random() * sumProbabilities;\n for (let i = 0; i < probabilities.length; ++i) {\n r -= probabilities[i];\n if (r <= 0) {\n return i;\n }\n }\n return 0; // return first (most probable) as a fallback\n }\n\n /**\n * Returns a Sampler object based on the specified options.\n * @param {GenerationConfig} generation_config An object containing options for the sampler.\n * @returns {LogitsSampler} A Sampler object.\n */\n static getSampler(generation_config) {\n // - *greedy decoding*: `num_beams=1` and `do_sample=False`\n // - *contrastive search*: `penalty_alpha>0` and `top_k>1`\n // - *multinomial sampling*: `num_beams=1` and `do_sample=True`\n // - *beam-search decoding*: `num_beams>1` and `do_sample=False`\n // - *beam-search multinomial sampling*: `num_beams>1` and `do_sample=True`\n // - *diverse beam-search decoding*: `num_beams>1` and `num_beam_groups>1`\n // - *constrained beam-search decoding*: `constraints!=None` or `force_words_ids!=None`\n\n // NOTE: beam search is implemented directly into the generation function\n if (generation_config.do_sample) {\n return new MultinomialSampler(generation_config);\n\n } else if (generation_config.num_beams > 1) {\n return new BeamSearchSampler(generation_config);\n\n } else {\n if (generation_config.num_return_sequences > 1) {\n throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${generation_config.num_return_sequences}.`)\n }\n return new GreedySampler(generation_config);\n }\n }\n}\n\n/**\n * Class representing a Greedy Sampler.\n */\nclass GreedySampler extends LogitsSampler {\n /**\n * Sample the maximum probability of a given logits tensor.\n * @param {Tensor} logits\n * @returns {Promise<[bigint, number][]>} An array with a single tuple, containing the index of the maximum value and a meaningless score (since this is a greedy search).\n */\n async sample(logits) {\n // NOTE: no need to do log_softmax here since we only take the maximum\n const argmax = max(logits.data)[1];\n\n // Note: score is meaningless in this context, since we are performing\n // greedy search (p = 1 => log(p) = 0)\n return [\n [BigInt(argmax), 0]\n ];\n }\n}\n\n/**\n * Class representing a MultinomialSampler.\n */\nclass MultinomialSampler extends LogitsSampler {\n\n /**\n * Sample from the logits.\n * @param {Tensor} logits\n * @returns {Promise<[bigint, number][]>}\n */\n async sample(logits) {\n let k = logits.dims.at(-1); // defaults to vocab size\n if (this.generation_config.top_k > 0) {\n k = Math.min(this.generation_config.top_k, k);\n }\n\n // Get top k tokens\n const [v, i] = await topk(logits, k);\n\n // Compute softmax over logits\n const probabilities = softmax(/** @type {Float32Array} */(v.data));\n\n return Array.from({ length: this.generation_config.num_beams }, () => {\n const sampledIndex = this.randomSelect(probabilities);\n return [\n i.data[sampledIndex], // token id\n Math.log(probabilities[sampledIndex]), // score\n ];\n });\n }\n}\n\n\n/**\n * Class representing a BeamSearchSampler.\n */\nclass BeamSearchSampler extends LogitsSampler {\n\n /**\n * Sample from the logits.\n * @param {Tensor} logits\n * @returns {Promise<[bigint, number][]>}\n */\n async sample(logits) {\n let k = logits.dims.at(-1); // defaults to vocab size\n if (this.generation_config.top_k > 0) {\n k = Math.min(this.generation_config.top_k, k);\n }\n\n // Get top k tokens\n const [v, i] = await topk(logits, k);\n\n // Compute softmax over logits\n const probabilities = softmax(/** @type {Float32Array} */(v.data));\n\n return Array.from({ length: this.generation_config.num_beams }, (_, x) => {\n return [\n i.data[x], // token id\n Math.log(probabilities[x]), // score\n ];\n });\n }\n}\n","\n/**\n * @module generation/stopping_criteria\n */\n\nimport { Callable } from \"../utils/generic.js\";\n\n// NOTE:\n// Stopping Criteria returns a list of `batch_size` booleans, indicating whether each sequence in the batch should be stopped.\n\n/**\n * Abstract base class for all stopping criteria that can be applied during generation.\n */\nexport class StoppingCriteria extends Callable {\n /**\n * \n * @param {number[][]} input_ids (`number[][]` of shape `(batch_size, sequence_length)`):\n * Indices of input sequence tokens in the vocabulary.\n * @param {number[][]} scores scores (`number[][]` of shape `(batch_size, config.vocab_size)`):\n * Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax\n * or scores for each vocabulary token after SoftMax.\n * @returns {boolean[]} A list of booleans indicating whether each sequence should be stopped.\n */\n _call(input_ids, scores) {\n throw Error(\"StoppingCriteria needs to be subclassed\");\n }\n}\n/**\n */\nexport class StoppingCriteriaList extends Callable {\n /**\n * Constructs a new instance of `StoppingCriteriaList`.\n */\n constructor() {\n super();\n this.criteria = [];\n }\n\n /**\n * Adds a new stopping criterion to the list.\n *\n * @param {StoppingCriteria} item The stopping criterion to add.\n */\n push(item) {\n this.criteria.push(item);\n }\n\n /**\n * Adds multiple stopping criteria to the list.\n *\n * @param {StoppingCriteria|StoppingCriteriaList|StoppingCriteria[]} items The stopping criteria to add.\n */\n extend(items) {\n if (items instanceof StoppingCriteriaList) {\n items = items.criteria;\n } else if (items instanceof StoppingCriteria) {\n items = [items];\n }\n this.criteria.push(...items);\n }\n\n _call(input_ids, scores) {\n const is_done = new Array(input_ids.length).fill(false);\n for (const criterion of this.criteria) {\n const criterion_done = criterion(input_ids, scores);\n for (let i = 0; i < is_done.length; ++i) {\n is_done[i] ||= criterion_done[i];\n }\n }\n return is_done;\n }\n\n [Symbol.iterator]() {\n return this.criteria.values();\n }\n}\n\n/**\n * This class can be used to stop generation whenever the full generated number of tokens exceeds `max_length`.\n * Keep in mind for decoder-only type of transformers, this will include the initial prompted tokens.\n */\nexport class MaxLengthCriteria extends StoppingCriteria {\n\n /**\n * \n * @param {number} max_length The maximum length that the output sequence can have in number of tokens.\n * @param {number} [max_position_embeddings=null] The maximum model length, as defined by the model's `config.max_position_embeddings` attribute.\n */\n constructor(max_length, max_position_embeddings = null) {\n super();\n this.max_length = max_length;\n this.max_position_embeddings = max_position_embeddings;\n }\n\n _call(input_ids) {\n return input_ids.map(ids => ids.length >= this.max_length);\n }\n}\n\n// TODO: add MaxTimeCriteria\n\n/**\n * This class can be used to stop generation whenever the \"end-of-sequence\" token is generated.\n * By default, it uses the `model.generation_config.eos_token_id`.\n */\nexport class EosTokenCriteria extends StoppingCriteria {\n\n /**\n * \n * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token.\n * Optionally, use a list to set multiple *end-of-sequence* tokens.\n */\n constructor(eos_token_id) {\n super();\n if (!Array.isArray(eos_token_id)) {\n eos_token_id = [eos_token_id];\n }\n this.eos_token_id = eos_token_id;\n }\n\n /**\n * \n * @param {number[][]} input_ids \n * @param {number[][]} scores \n * @returns {boolean[]}\n */\n _call(input_ids, scores) {\n return input_ids.map(ids => {\n const last = ids.at(-1);\n // NOTE: We use == instead of === to allow for number/bigint comparison\n return this.eos_token_id.some(eos_id => last == eos_id);\n });\n }\n}\n\n/**\n * This class can be used to stop generation whenever the user interrupts the process.\n */\nexport class InterruptableStoppingCriteria extends StoppingCriteria {\n constructor() {\n super();\n this.interrupted = false;\n }\n\n interrupt() {\n this.interrupted = true;\n }\n\n reset() {\n this.interrupted = false;\n }\n\n _call(input_ids, scores) {\n return new Array(input_ids.length).fill(this.interrupted);\n }\n}\n","\n/**\n * @module generation/streamers\n */\n\nimport { mergeArrays } from '../utils/core.js';\nimport { is_chinese_char } from '../tokenizers.js';\nimport { apis } from '../env.js';\n\nexport class BaseStreamer {\n /**\n * Function that is called by `.generate()` to push new tokens\n * @param {bigint[][]} value \n */\n put(value) {\n throw Error('Not implemented');\n }\n\n /**\n * Function that is called by `.generate()` to signal the end of generation\n */\n end() {\n throw Error('Not implemented');\n }\n}\n\nconst stdout_write = apis.IS_PROCESS_AVAILABLE\n ? x => process.stdout.write(x)\n : x => console.log(x);\n\n/**\n * Simple text streamer that prints the token(s) to stdout as soon as entire words are formed.\n */\nexport class TextStreamer extends BaseStreamer {\n /**\n * \n * @param {import('../tokenizers.js').PreTrainedTokenizer} tokenizer \n */\n constructor(tokenizer, {\n skip_prompt = false,\n callback_function = null,\n token_callback_function = null,\n decode_kwargs = {},\n ...kwargs\n } = {}) {\n super();\n this.tokenizer = tokenizer;\n this.skip_prompt = skip_prompt;\n this.callback_function = callback_function ?? stdout_write;\n this.token_callback_function = token_callback_function;\n this.decode_kwargs = { ...decode_kwargs, ...kwargs };\n\n // variables used in the streaming process\n this.token_cache = [];\n this.print_len = 0;\n this.next_tokens_are_prompt = true;\n }\n\n /**\n * Receives tokens, decodes them, and prints them to stdout as soon as they form entire words.\n * @param {bigint[][]} value \n */\n put(value) {\n if (value.length > 1) {\n throw Error('TextStreamer only supports batch size of 1');\n }\n\n if (this.skip_prompt && this.next_tokens_are_prompt) {\n this.next_tokens_are_prompt = false;\n return;\n }\n\n const tokens = value[0];\n this.token_callback_function?.(tokens)\n\n // Add the new token to the cache and decodes the entire thing.\n this.token_cache = mergeArrays(this.token_cache, tokens);\n const text = this.tokenizer.decode(this.token_cache, this.decode_kwargs);\n\n let printable_text;\n if (text.endsWith('\\n')) {\n // After the symbol for a new line, we flush the cache.\n printable_text = text.slice(this.print_len);\n this.token_cache = [];\n this.print_len = 0;\n } else if (text.length > 0 && is_chinese_char(text.charCodeAt(text.length - 1))) {\n // If the last token is a CJK character, we print the characters.\n printable_text = text.slice(this.print_len);\n this.print_len += printable_text.length;\n } else {\n // Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words,\n // which may change with the subsequent token -- there are probably smarter ways to do this!)\n printable_text = text.slice(this.print_len, text.lastIndexOf(' ') + 1);\n this.print_len += printable_text.length;\n }\n\n this.on_finalized_text(printable_text, false);\n }\n\n /**\n * Flushes any remaining cache and prints a newline to stdout.\n */\n end() {\n let printable_text;\n if (this.token_cache.length > 0) {\n const text = this.tokenizer.decode(this.token_cache, this.decode_kwargs);\n printable_text = text.slice(this.print_len);\n this.token_cache = [];\n this.print_len = 0;\n } else {\n printable_text = '';\n }\n this.next_tokens_are_prompt = true;\n this.on_finalized_text(printable_text, true);\n }\n\n /**\n * Prints the new text to stdout. If the stream is ending, also prints a newline.\n * @param {string} text \n * @param {boolean} stream_end \n */\n on_finalized_text(text, stream_end) {\n if (text.length > 0) {\n this.callback_function?.(text);\n }\n if (stream_end && this.callback_function === stdout_write && apis.IS_PROCESS_AVAILABLE) {\n this.callback_function?.('\\n');\n }\n }\n}\n\n/**\n * Utility class to handle streaming of tokens generated by whisper speech-to-text models.\n * Callback functions are invoked when each of the following events occur:\n * - A new chunk starts (on_chunk_start)\n * - A new token is generated (callback_function)\n * - A chunk ends (on_chunk_end)\n * - The stream is finalized (on_finalize)\n */\nexport class WhisperTextStreamer extends TextStreamer {\n /**\n * @param {import('../tokenizers.js').WhisperTokenizer} tokenizer\n * @param {Object} options\n * @param {boolean} [options.skip_prompt=false] Whether to skip the prompt tokens\n * @param {function(string): void} [options.callback_function=null] Function to call when a piece of text is ready to display\n * @param {function(string): void} [options.token_callback_function=null] Function to call when a new token is generated\n * @param {function(number): void} [options.on_chunk_start=null] Function to call when a new chunk starts\n * @param {function(number): void} [options.on_chunk_end=null] Function to call when a chunk ends\n * @param {function(): void} [options.on_finalize=null] Function to call when the stream is finalized\n * @param {number} [options.time_precision=0.02] Precision of the timestamps\n * @param {boolean} [options.skip_special_tokens=true] Whether to skip special tokens when decoding\n * @param {Object} [options.decode_kwargs={}] Additional keyword arguments to pass to the tokenizer's decode method\n */\n constructor(tokenizer, {\n skip_prompt = false,\n callback_function = null,\n token_callback_function = null,\n on_chunk_start = null,\n on_chunk_end = null,\n on_finalize = null,\n time_precision = 0.02,\n skip_special_tokens = true,\n decode_kwargs = {},\n } = {}) {\n super(tokenizer, {\n skip_prompt,\n callback_function,\n token_callback_function,\n decode_kwargs: { skip_special_tokens, ...decode_kwargs },\n });\n this.timestamp_begin = tokenizer.timestamp_begin;\n\n this.on_chunk_start = on_chunk_start;\n this.on_chunk_end = on_chunk_end;\n this.on_finalize = on_finalize;\n\n this.time_precision = time_precision;\n\n this.waiting_for_timestamp = false;\n }\n\n /**\n * @param {bigint[][]} value \n */\n put(value) {\n if (value.length > 1) {\n throw Error('WhisperTextStreamer only supports batch size of 1');\n }\n const tokens = value[0];\n\n // Check if the token is a timestamp\n if (tokens.length === 1) {\n const offset = Number(tokens[0]) - this.timestamp_begin;\n if (offset >= 0) {\n const time = offset * this.time_precision;\n if (this.waiting_for_timestamp) {\n this.on_chunk_end?.(time);\n } else {\n this.on_chunk_start?.(time);\n }\n this.waiting_for_timestamp = !this.waiting_for_timestamp; // Toggle\n value = [[]]; // Skip timestamp\n }\n }\n return super.put(value);\n }\n\n end() {\n super.end();\n this.on_finalize?.();\n }\n}\n","\n/**\n * @file Definitions of all models available in Transformers.js.\n * \n * **Example:** Load and run an `AutoModel`.\n * \n * ```javascript\n * import { AutoModel, AutoTokenizer } from '@huggingface/transformers';\n * \n * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');\n * let model = await AutoModel.from_pretrained('Xenova/bert-base-uncased');\n * \n * let inputs = await tokenizer('I love transformers!');\n * let { logits } = await model(inputs);\n * // Tensor {\n * // data: Float32Array(183132) [-7.117443084716797, -7.107812881469727, -7.092104911804199, ...]\n * // dims: (3) [1, 6, 30522],\n * // type: \"float32\",\n * // size: 183132,\n * // }\n * ```\n * \n * We also provide other `AutoModel`s (listed below), which you can use in the same way as the Python library. For example:\n * \n * **Example:** Load and run an `AutoModelForSeq2SeqLM`.\n * ```javascript\n * import { AutoModelForSeq2SeqLM, AutoTokenizer } from '@huggingface/transformers';\n * \n * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/t5-small');\n * let model = await AutoModelForSeq2SeqLM.from_pretrained('Xenova/t5-small');\n * \n * let { input_ids } = await tokenizer('translate English to German: I love transformers!');\n * let outputs = await model.generate(input_ids);\n * let decoded = tokenizer.decode(outputs[0], { skip_special_tokens: true });\n * // 'Ich liebe Transformatoren!'\n * ```\n * \n * @module models\n */\n\nimport {\n AutoConfig,\n getKeyValueShapes,\n} from './configs.js';\n\nimport {\n deviceToExecutionProviders,\n createInferenceSession,\n isONNXTensor,\n isONNXProxy,\n} from './backends/onnx.js';\nimport {\n DATA_TYPES,\n DEFAULT_DEVICE_DTYPE_MAPPING,\n DEFAULT_DTYPE_SUFFIX_MAPPING,\n isWebGpuFp16Supported,\n} from './utils/dtypes.js';\n\nimport {\n Callable,\n} from './utils/generic.js';\n\nimport {\n isIntegralNumber,\n mergeArrays,\n pick,\n} from './utils/core.js';\n\nimport {\n getModelFile,\n getModelJSON,\n} from './utils/hub.js';\n\nimport {\n GITHUB_ISSUE_URL,\n} from './utils/constants.js';\n\nimport {\n LogitsProcessorList,\n ForcedBOSTokenLogitsProcessor,\n ForcedEOSTokenLogitsProcessor,\n SuppressTokensAtBeginLogitsProcessor,\n WhisperTimeStampLogitsProcessor,\n NoRepeatNGramLogitsProcessor,\n RepetitionPenaltyLogitsProcessor,\n NoBadWordsLogitsProcessor,\n MinLengthLogitsProcessor,\n MinNewTokensLengthLogitsProcessor,\n\n TemperatureLogitsWarper,\n TopKLogitsWarper,\n TopPLogitsWarper,\n ClassifierFreeGuidanceLogitsProcessor,\n} from './generation/logits_process.js';\n\nimport {\n GenerationConfig,\n} from './generation/configuration_utils.js';\n\nimport {\n cat,\n full_like,\n mean,\n ones,\n ones_like,\n stack,\n std_mean,\n Tensor,\n zeros_like,\n} from './utils/tensor.js';\n\nimport { dynamic_time_warping, medianFilter } from './utils/maths.js';\nimport { EosTokenCriteria, MaxLengthCriteria, StoppingCriteriaList } from './generation/stopping_criteria.js';\nimport { LogitsSampler } from './generation/logits_sampler.js';\nimport { apis } from './env.js';\n\nimport { WhisperGenerationConfig } from './models/whisper/generation_whisper.js';\nimport { whisper_language_to_code } from './models/whisper/common_whisper.js';\n\n//////////////////////////////////////////////////\n// Model types: used internally\nconst MODEL_TYPES = {\n EncoderOnly: 0,\n EncoderDecoder: 1,\n Seq2Seq: 2,\n Vision2Seq: 3,\n DecoderOnly: 4,\n MaskGeneration: 5,\n ImageTextToText: 6,\n Musicgen: 7,\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Helper functions\n\n// NOTE: These will be populated fully later\nconst MODEL_TYPE_MAPPING = new Map();\nconst MODEL_NAME_TO_CLASS_MAPPING = new Map();\nconst MODEL_CLASS_TO_NAME_MAPPING = new Map();\n\n\n/**\n * Constructs an InferenceSession using a model file located at the specified path.\n * @param {string} pretrained_model_name_or_path The path to the directory containing the model file.\n * @param {string} fileName The name of the model file.\n * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the model.\n * @returns {Promise<{buffer: Uint8Array, session_options: Object, session_config: Object}>} A Promise that resolves to the data needed to create an InferenceSession object.\n * @private\n */\nasync function getSession(pretrained_model_name_or_path, fileName, options) {\n const custom_config = options.config?.['transformers.js_config'] ?? {};\n let device = options.device ?? custom_config.device;\n if (device && typeof device !== 'string') {\n if (device.hasOwnProperty(fileName)) {\n device = device[fileName];\n } else {\n console.warn(`device not specified for \"${fileName}\". Using the default device.`);\n device = null;\n }\n }\n\n // If the device is not specified, we use the default (supported) execution providers.\n const selectedDevice = /** @type {import(\"./utils/devices.js\").DeviceType} */(\n device ?? (apis.IS_NODE_ENV ? 'cpu' : 'wasm')\n );\n const executionProviders = deviceToExecutionProviders(selectedDevice);\n\n // If options.dtype is specified, we use it to choose the suffix for the model file.\n // Otherwise, we use the default dtype for the device.\n let dtype = options.dtype ?? custom_config.dtype;\n if (typeof dtype !== 'string') {\n if (dtype && dtype.hasOwnProperty(fileName)) {\n dtype = dtype[fileName];\n } else {\n dtype = DEFAULT_DEVICE_DTYPE_MAPPING[selectedDevice] ?? DATA_TYPES.fp32;\n console.warn(`dtype not specified for \"${fileName}\". Using the default dtype (${dtype}) for this device (${selectedDevice}).`);\n }\n }\n\n const selectedDtype = /** @type {import(\"./utils/dtypes.js\").DataType} */(dtype);\n\n if (!DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(selectedDtype)) {\n throw new Error(`Invalid dtype: ${selectedDtype}. Should be one of: ${Object.keys(DATA_TYPES).join(', ')}`);\n } else if (selectedDtype === DATA_TYPES.fp16 && selectedDevice === 'webgpu' && !(await isWebGpuFp16Supported())) {\n throw new Error(`The device (${selectedDevice}) does not support fp16.`);\n }\n\n // Only valid for models with a decoder\n const kv_cache_dtype = custom_config.kv_cache_dtype\n ? (typeof custom_config.kv_cache_dtype === 'string'\n ? custom_config.kv_cache_dtype\n : custom_config.kv_cache_dtype[selectedDtype] ?? 'float32')\n : undefined;\n\n if (kv_cache_dtype && !['float32', 'float16'].includes(kv_cache_dtype)) {\n throw new Error(`Invalid kv_cache_dtype: ${kv_cache_dtype}. Should be one of: float32, float16`);\n }\n\n const session_config = {\n dtype: selectedDtype,\n kv_cache_dtype,\n }\n\n // Construct the model file name\n const suffix = DEFAULT_DTYPE_SUFFIX_MAPPING[selectedDtype];\n const modelFileName = `${options.subfolder ?? ''}/${fileName}${suffix}.onnx`;\n\n const session_options = { ...options.session_options };\n\n // Overwrite `executionProviders` if not specified\n session_options.executionProviders ??= executionProviders;\n\n // Overwrite `freeDimensionOverrides` if specified in config and not set in session options\n const free_dimension_overrides = custom_config.free_dimension_overrides;\n if (free_dimension_overrides) {\n session_options.freeDimensionOverrides ??= free_dimension_overrides;\n } else if (selectedDevice.startsWith('webnn') && !session_options.freeDimensionOverrides) {\n console.warn(\n 'WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within \"transformers.js_config\". ' +\n 'When `free_dimension_overrides` is not set, you may experience significant performance degradation.'\n );\n }\n\n const bufferPromise = getModelFile(pretrained_model_name_or_path, modelFileName, true, options);\n\n // handle onnx external data files\n const use_external_data_format = options.use_external_data_format ?? custom_config.use_external_data_format;\n /** @type {Promise<{path: string, data: Uint8Array}>[]} */\n let externalDataPromises = [];\n if (use_external_data_format && (\n use_external_data_format === true ||\n (\n typeof use_external_data_format === 'object' &&\n use_external_data_format.hasOwnProperty(fileName) &&\n use_external_data_format[fileName] === true\n )\n )) {\n if (apis.IS_NODE_ENV) {\n throw new Error('External data format is not yet supported in Node.js');\n }\n const path = `${fileName}${suffix}.onnx_data`;\n const fullPath = `${options.subfolder ?? ''}/${path}`;\n externalDataPromises.push(new Promise(async (resolve, reject) => {\n const data = await getModelFile(pretrained_model_name_or_path, fullPath, true, options);\n resolve({ path, data })\n }));\n\n } else if (session_options.externalData !== undefined) {\n externalDataPromises = session_options.externalData.map(async (ext) => {\n // if the external data is a string, fetch the file and replace the string with its content\n if (typeof ext.data === \"string\") {\n const ext_buffer = await getModelFile(pretrained_model_name_or_path, ext.data, true, options);\n return { ...ext, data: ext_buffer };\n }\n return ext;\n });\n }\n\n if (externalDataPromises.length > 0) {\n session_options.externalData = await Promise.all(externalDataPromises);\n }\n\n if (selectedDevice === 'webgpu') {\n const shapes = getKeyValueShapes(options.config, {\n prefix: 'present',\n });\n if (Object.keys(shapes).length > 0 && !isONNXProxy()) {\n // Only set preferredOutputLocation if shapes are present and we aren't proxying ONNX\n /** @type {Record} */\n const preferredOutputLocation = {};\n for (const key in shapes) {\n preferredOutputLocation[key] = 'gpu-buffer';\n }\n session_options.preferredOutputLocation = preferredOutputLocation;\n }\n }\n\n const buffer = await bufferPromise;\n\n return { buffer, session_options, session_config };\n}\n\n/**\n * Helper function to create multiple InferenceSession objects.\n * \n * @param {string} pretrained_model_name_or_path The path to the directory containing the model file.\n * @param {Record} names The names of the model files to load.\n * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the model.\n * @returns {Promise>} A Promise that resolves to a dictionary of InferenceSession objects.\n * @private\n */\nasync function constructSessions(pretrained_model_name_or_path, names, options) {\n return Object.fromEntries(await Promise.all(\n Object.keys(names).map(async (name) => {\n const { buffer, session_options, session_config } = await getSession(pretrained_model_name_or_path, names[name], options);\n const session = await createInferenceSession(buffer, session_options, session_config);\n return [name, session];\n })\n ));\n}\n\n/**\n * Helper function to load multiple optional configuration files\n * @param {string} pretrained_model_name_or_path The path to the directory containing the config file.\n * @param {Record} names The names of the config files to load.\n * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the configs.\n * @returns {Promise>} A Promise that resolves to a dictionary of configuration objects.\n * @private\n */\nasync function getOptionalConfigs(pretrained_model_name_or_path, names, options) {\n return Object.fromEntries(await Promise.all(\n Object.keys(names).map(async (name) => {\n const config = await getModelJSON(pretrained_model_name_or_path, names[name], false, options);\n return [name, config];\n })\n ));\n}\n\n/**\n * Validate model inputs\n * @param {Object} session The InferenceSession object that will be run.\n * @param {Object} inputs The inputs to check.\n * @returns {Record} The checked inputs.\n * @throws {Error} If any inputs are missing.\n * @private\n */\nfunction validateInputs(session, inputs) {\n /**\n * NOTE: Create either a shallow or deep copy based on `onnx.wasm.proxy`\n * @type {Record}\n */\n const checkedInputs = Object.create(null);\n const missingInputs = [];\n for (const inputName of session.inputNames) {\n const tensor = inputs[inputName];\n // Rare case where one of the model's input names corresponds to a built-in\n // object name (e.g., toString), which would cause a simple (!tensor) check to fail,\n // because it's not undefined but a function.\n if (!(tensor instanceof Tensor)) {\n missingInputs.push(inputName);\n continue;\n }\n // NOTE: When `env.wasm.proxy is true` the tensor is moved across the Worker\n // boundary, transferring ownership to the worker and invalidating the tensor.\n // So, in this case, we simply sacrifice a clone for it.\n checkedInputs[inputName] = isONNXProxy() ? tensor.clone() : tensor;\n }\n if (missingInputs.length > 0) {\n throw new Error(\n `An error occurred during model execution: \"Missing the following inputs: ${missingInputs.join(', ')}.`);\n }\n\n const numInputsProvided = Object.keys(inputs).length;\n const numInputsNeeded = session.inputNames.length;\n if (numInputsProvided > numInputsNeeded) {\n // No missing inputs, but too many inputs were provided.\n // Warn the user and ignore the extra inputs.\n let ignored = Object.keys(inputs).filter(inputName => !session.inputNames.includes(inputName));\n console.warn(`WARNING: Too many inputs were provided (${numInputsProvided} > ${numInputsNeeded}). The following inputs will be ignored: \"${ignored.join(', ')}\".`);\n }\n\n return checkedInputs;\n}\n\nconst getQueryValue = (name) => {\n const urlParams = new URLSearchParams(window.location.search);\n return urlParams.get(name);\n};\n\nlet runs = 1;\n\nlet perf = {\n warmup: 0,\n inference: [],\n throughput: 0\n};\n\nexport function getPerf() {\n return perf;\n}\n\n/**\n * Executes an InferenceSession using the specified inputs.\n * NOTE: `inputs` must contain at least the input names of the model.\n * - If additional inputs are passed, they will be ignored.\n * - If inputs are missing, an error will be thrown.\n * \n * @param {Object} session The InferenceSession object to run.\n * @param {Object} inputs An object that maps input names to input tensors.\n * @returns {Promise} A Promise that resolves to an object that maps output names to output tensors.\n * @private\n */\nasync function sessionRun(session, inputs) {\n perf = {\n warmup: 0,\n inference: [],\n throughput: 0\n };\n const checkedInputs = validateInputs(session, inputs);\n try {\n // pass the original ort tensor\n const ortFeed = Object.fromEntries(Object.entries(checkedInputs).map(([k, v]) => [k, v.ort_tensor]));\n let output;\n let numOfWarmups = 1;\n // let numOfRuns = 100;\n console.log(`-- number of test runs --`);\n if (getQueryValue(\"run\")) {\n runs = parseInt(getQueryValue(\"run\"));\n } else {\n runs = 1;\n }\n console.log(runs);\n let start = performance.now();\n let loopStart;\n let current;\n let arrayInference = [];\n for(let i=0; i < numOfWarmups + runs; i++) {\n loopStart = performance.now();\n output = await session.run(ortFeed);\n current = performance.now() - loopStart;\n if(i==0) {\n perf.warmup = current;\n } else {\n arrayInference.push(current);\n }\n console.log(`Session run time: ${current}ms`);\n }\n perf.inference = arrayInference;\n perf.throughput = parseFloat((1000.00 / ((performance.now() - start) / (numOfWarmups + runs))).toFixed(2));\n output = replaceTensors(output);\n return output;\n } catch (e) {\n // This usually occurs when the inputs are of the wrong type.\n console.error(`An error occurred during model execution: \"${e}\".`);\n console.error('Inputs given to model:', checkedInputs);\n throw e;\n }\n}\n\n/**\n * Replaces ONNX Tensor objects with custom Tensor objects to support additional functions.\n * @param {Object} obj The object to replace tensor objects in.\n * @returns {Object} The object with tensor objects replaced by custom Tensor objects.\n * @private\n */\nfunction replaceTensors(obj) {\n for (let prop in obj) {\n if (isONNXTensor(obj[prop])) {\n obj[prop] = new Tensor(obj[prop]);\n } else if (typeof obj[prop] === 'object') {\n replaceTensors(obj[prop]);\n }\n }\n return obj;\n}\n\n\n/**\n * Converts an array or Tensor of integers to an int64 Tensor.\n * @param {Array|Tensor} items The input integers to be converted.\n * @returns {Tensor} The int64 Tensor with the converted values.\n * @throws {Error} If the input array is empty or the input is a batched Tensor and not all sequences have the same length.\n * @private\n */\nfunction toI64Tensor(items) {\n if (items instanceof Tensor) {\n return items;\n }\n // items is an array\n if (items.length === 0) {\n throw Error(\"items must be non-empty\");\n }\n\n if (Array.isArray(items[0])) {\n // batched\n if (items.some(x => x.length !== items[0].length)) {\n throw Error(\"Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.\")\n }\n\n return new Tensor('int64',\n BigInt64Array.from(items.flat().map(x => BigInt(x))),\n [items.length, items[0].length]\n );\n } else {\n //flat\n return new Tensor('int64',\n BigInt64Array.from(items.map(x => BigInt(x))),\n [1, items.length]\n );\n }\n}\n\n/**\n * Creates a boolean tensor with a single value.\n * @param {boolean} value The value of the tensor.\n * @returns {Tensor} The boolean tensor.\n * @private\n */\nfunction boolTensor(value) {\n return new Tensor('bool', [value], [1]);\n}\n\n// JS doesn't support mixins, so we define some reused functions here, and allow \"this\" to be passed in\n/**\n * Perform forward pass on the seq2seq model (both encoder and decoder).\n * @param {Object} self The seq2seq model object.\n * @param {Object} model_inputs The input object for the model containing encoder and decoder inputs.\n * @returns {Promise} Promise that resolves with the output of the seq2seq model.\n * @private\n */\nasync function seq2seqForward(self, model_inputs) {\n let { encoder_outputs, input_ids, decoder_input_ids, ...other_decoder_inputs } = model_inputs;\n // Encode if needed\n if (!encoder_outputs) {\n const encoder_inputs = pick(model_inputs, self.sessions['model'].inputNames);\n // Encoder outputs are not given, so we must compute them.\n encoder_outputs = (await encoderForward(self, encoder_inputs)).last_hidden_state;\n }\n\n other_decoder_inputs.input_ids = decoder_input_ids;\n other_decoder_inputs.encoder_hidden_states = encoder_outputs;\n\n if (self.sessions['decoder_model_merged'].inputNames.includes('encoder_attention_mask')) {\n other_decoder_inputs.encoder_attention_mask = model_inputs.attention_mask\n }\n\n const decoderResults = await decoderForward(self, other_decoder_inputs, true);\n\n return decoderResults;\n}\n\n/**\n * Forward pass of an encoder model.\n * @param {Object} self The encoder model.\n * @param {Object} model_inputs The input data to be used for the forward pass.\n * @returns {Promise} The model's outputs.\n * @private\n */\nasync function encoderForward(self, model_inputs) {\n const session = self.sessions['model'];\n const encoderFeeds = pick(model_inputs, session.inputNames);\n\n if (session.inputNames.includes('inputs_embeds') && !encoderFeeds.inputs_embeds) {\n if (!model_inputs.input_ids) {\n throw new Error('Both `input_ids` and `inputs_embeds` are missing in the model inputs.');\n }\n encoderFeeds.inputs_embeds = await self.encode_text({ input_ids: model_inputs.input_ids });\n }\n if (session.inputNames.includes('token_type_ids') && !encoderFeeds.token_type_ids) {\n // Assign default `token_type_ids` (all zeroes) to the `encoderFeeds` if the model expects it,\n // but they weren't created by the tokenizer.\n encoderFeeds.token_type_ids = new Tensor(\n 'int64',\n new BigInt64Array(encoderFeeds.input_ids.data.length),\n encoderFeeds.input_ids.dims\n )\n }\n return await sessionRun(session, encoderFeeds);\n}\n\n/**\n * Forward pass of a decoder model.\n * @param {Object} self The decoder model.\n * @param {Object} model_inputs The input data to be used for the forward pass.\n * @returns {Promise} The logits and past key values.\n * @private\n */\nasync function decoderForward(self, model_inputs, is_encoder_decoder = false) {\n\n const session = self.sessions[\n is_encoder_decoder ? 'decoder_model_merged' : 'model'\n ]\n\n const { past_key_values, ...new_model_inputs } = model_inputs;\n\n if (session.inputNames.includes('use_cache_branch')) {\n new_model_inputs.use_cache_branch = boolTensor(!!past_key_values);\n }\n if (session.inputNames.includes('position_ids') && new_model_inputs.attention_mask && !new_model_inputs.position_ids) {\n new_model_inputs.position_ids = createPositionIds(new_model_inputs, past_key_values);\n }\n\n // Unpack the `past_key_values` object into model inputs\n self.addPastKeyValues(new_model_inputs, past_key_values);\n\n // Select only the inputs that are needed for the current session\n const fixed = pick(new_model_inputs, session.inputNames);\n return await sessionRun(session, fixed);\n}\n\n\n/**\n * Forward pass of an image-text-to-text model.\n * @param {Object} self The image-text-to-text model model.\n * @param {Object} model_inputs The input data to be used for the forward pass.\n * @param {Tensor} [model_inputs.input_ids=null]\n * @param {Tensor} [model_inputs.attention_mask=null]\n * @param {Tensor} [model_inputs.pixel_values=null]\n * @param {Tensor} [model_inputs.position_ids=null]\n * @param {Tensor} [model_inputs.inputs_embeds=null]\n * @param {Tensor} [model_inputs.past_key_values=null]\n * @param {Object} [model_inputs.generation_config=null]\n * @param {Object} [model_inputs.logits_processor=null]\n * @returns {Promise} The model's output tensor\n * @private\n */\nasync function imageTextToTextForward(self, {\n // Produced by the tokenizer/processor:\n input_ids = null,\n attention_mask = null,\n pixel_values = null,\n\n // Used during generation:\n position_ids = null,\n inputs_embeds = null,\n past_key_values = null,\n\n // Generic generation parameters\n generation_config = null,\n logits_processor = null,\n\n // TODO: needed?\n ...kwargs\n}) {\n\n if (!inputs_embeds) {\n // 1. Extract the input embeddings\n inputs_embeds = await self.encode_text({ input_ids });\n\n // 2. Possibly, merge text and images\n if (pixel_values && input_ids.dims[1] !== 1) {\n const image_features = await self.encode_image({ pixel_values });\n\n ({ inputs_embeds, attention_mask } = self._merge_input_ids_with_image_features({\n image_features,\n inputs_embeds,\n input_ids,\n attention_mask,\n }));\n\n } else if (past_key_values && pixel_values && input_ids.dims[1] === 1) {\n // This is the case when we are generating with cache\n const target_length = input_ids.dims[1]; // always 1\n const past_length = Object.values(past_key_values)[0].dims.at(-2);\n\n attention_mask = cat([\n ones([input_ids.dims[0], past_length]),\n attention_mask.slice(null, [attention_mask.dims[1] - target_length, attention_mask.dims[1]]),\n ], 1);\n }\n }\n\n const outputs = await decoderForward(self, {\n inputs_embeds,\n past_key_values,\n attention_mask,\n position_ids,\n generation_config,\n logits_processor,\n }, true);\n return outputs;\n}\n\nfunction createPositionIds(model_inputs, past_key_values = null) {\n // If the model supports providing position_ids, we create position_ids on the fly for batch generation,\n // by computing the cumulative sum of the attention mask along the sequence length dimension.\n // \n // Equivalent to:\n // position_ids = attention_mask.long().cumsum(-1) - 1\n // position_ids.masked_fill_(attention_mask == 0, 1)\n // if past_key_values:\n // position_ids = position_ids[:, -input_ids.shape[1] :]\n const { input_ids, inputs_embeds, attention_mask } = model_inputs;\n const [bz, seq_len] = attention_mask.dims;\n\n const data = new BigInt64Array(attention_mask.data.length);\n for (let i = 0; i < bz; ++i) {\n const start = i * seq_len;\n let sum = BigInt(0);\n for (let j = 0; j < seq_len; ++j) {\n const index = start + j;\n if (attention_mask.data[index] === 0n) {\n data[index] = BigInt(1);\n } else { // === 1n\n data[index] = sum;\n sum += attention_mask.data[index];\n }\n }\n }\n\n let position_ids = new Tensor('int64', data, attention_mask.dims);\n if (past_key_values) {\n const offset = -(input_ids ?? inputs_embeds).dims.at(1);\n position_ids = position_ids.slice(null, [offset, null]);\n }\n return position_ids;\n}\n\nfunction decoder_prepare_inputs_for_generation(self, input_ids, model_inputs, generation_config) {\n if (model_inputs.past_key_values) {\n const past_length = Object.values(model_inputs.past_key_values)[0].dims.at(-2);\n const { input_ids, attention_mask } = model_inputs;\n\n // Keep only the unprocessed tokens:\n // 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where\n // some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as\n // input)\n if (attention_mask && attention_mask.dims[1] > input_ids.dims[1]) {\n // NOTE: not needed since we only pass the generated tokens to the next forward pass\n // const offset = -(attention_mask.dims[1] - past_length);\n // model_inputs.input_ids = input_ids.slice(null, [offset, null]);\n }\n // 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens.\n // We can discard input_ids based on the past_length.\n else if (past_length < input_ids.dims[1]) {\n // NOTE: Required for phi models.\n // See https://github.com/huggingface/transformers/issues/30809#issuecomment-2111918479 for more information.\n model_inputs.input_ids = input_ids.slice(null, [past_length, null]);\n }\n // 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.\n else {\n if (\n // NOTE: Only used by VLMs (!= so that null matches undefined)\n self.config.image_token_index != null &&\n // Equivalent to `self.config.image_token_index in input_ids` (== so that int matches bigint)\n input_ids.data.some(x => x == self.config.image_token_index)\n ) {\n // TODO: Support multiple image tokens\n const num_image_tokens = self.config.num_image_tokens;\n if (!num_image_tokens) {\n throw new Error('`num_image_tokens` is missing in the model configuration.');\n }\n\n const num_new_tokens = input_ids.dims[1] - (past_length - num_image_tokens);\n model_inputs.input_ids = input_ids.slice(null, [-num_new_tokens, null]);\n\n // TODO: The attention mask should be formed from the attention mask passed in model_inputs\n model_inputs.attention_mask = ones([1, past_length + num_new_tokens]);\n }\n }\n }\n\n return model_inputs;\n}\n\nfunction encoder_decoder_prepare_inputs_for_generation(self, input_ids, model_inputs, generation_config) {\n if (model_inputs.past_key_values) {\n input_ids = input_ids.map(x => [x.at(-1)]);\n }\n\n return {\n ...model_inputs,\n decoder_input_ids: toI64Tensor(input_ids),\n };\n}\n\nfunction image_text_to_text_prepare_inputs_for_generation(self, ...args) {\n if (self.config.is_encoder_decoder) {\n return encoder_decoder_prepare_inputs_for_generation(self, ...args);\n } else {\n return decoder_prepare_inputs_for_generation(self, ...args);\n }\n}\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n/**\n * A base class for pre-trained models that provides the model configuration and an ONNX session.\n */\nexport class PreTrainedModel extends Callable {\n main_input_name = 'input_ids';\n forward_params = ['input_ids', 'attention_mask'];\n /**\n * Creates a new instance of the `PreTrainedModel` class.\n * @param {import('./configs.js').PretrainedConfig} config The model configuration.\n * @param {Record} sessions The inference sessions for the model.\n * @param {Record} configs Additional configuration files (e.g., generation_config.json).\n */\n constructor(config, sessions, configs) {\n super();\n\n this.config = config;\n this.sessions = sessions;\n this.configs = configs;\n\n const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);\n const modelType = MODEL_TYPE_MAPPING.get(modelName);\n\n this.can_generate = false;\n this._forward = null;\n\n this._prepare_inputs_for_generation = null;\n switch (modelType) {\n case MODEL_TYPES.DecoderOnly:\n this.can_generate = true;\n this._forward = decoderForward;\n this._prepare_inputs_for_generation = decoder_prepare_inputs_for_generation;\n break;\n case MODEL_TYPES.Seq2Seq:\n case MODEL_TYPES.Vision2Seq:\n case MODEL_TYPES.Musicgen:\n this.can_generate = true;\n\n this._forward = seq2seqForward;\n this._prepare_inputs_for_generation = encoder_decoder_prepare_inputs_for_generation;\n break;\n\n case MODEL_TYPES.EncoderDecoder:\n this._forward = seq2seqForward;\n break;\n case MODEL_TYPES.ImageTextToText:\n this.can_generate = true;\n this._forward = imageTextToTextForward;\n this._prepare_inputs_for_generation = image_text_to_text_prepare_inputs_for_generation;\n break;\n\n default:\n // should be MODEL_TYPES.EncoderOnly\n this._forward = encoderForward;\n break;\n }\n\n if (this.can_generate) {\n this.forward_params.push('past_key_values');\n }\n\n /** @type {import('./configs.js').TransformersJSConfig} */\n this.custom_config = this.config['transformers.js_config'] ?? {};\n }\n\n /**\n * Disposes of all the ONNX sessions that were created during inference.\n * @returns {Promise} An array of promises, one for each ONNX session that is being disposed.\n * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n */\n async dispose() {\n const promises = [];\n for (const session of Object.values(this.sessions)) {\n if (session?.handler?.dispose) {\n promises.push(session.handler.dispose())\n }\n }\n return await Promise.all(promises);\n }\n\n /**\n * Instantiate one of the model classes of the library from a pretrained model.\n * \n * The model class to instantiate is selected based on the `model_type` property of the config object\n * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)\n * \n * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:\n * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.\n * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a\n * user or organization name, like `dbmdz/bert-base-german-cased`.\n * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`.\n * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the model.\n * \n * @returns {Promise} A new instance of the `PreTrainedModel` class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n model_file_name = null,\n subfolder = 'onnx',\n device = null,\n dtype = null,\n use_external_data_format = null,\n session_options = {},\n } = {}) {\n\n let options = {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n model_file_name,\n subfolder,\n device,\n dtype,\n use_external_data_format,\n session_options,\n }\n\n const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this);\n const modelType = MODEL_TYPE_MAPPING.get(modelName);\n\n config = options.config = await AutoConfig.from_pretrained(pretrained_model_name_or_path, options);\n\n let info;\n if (modelType === MODEL_TYPES.DecoderOnly) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: options.model_file_name ?? 'model',\n }, options),\n getOptionalConfigs(pretrained_model_name_or_path, {\n generation_config: 'generation_config.json',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: 'encoder_model',\n decoder_model_merged: 'decoder_model_merged',\n }, options),\n getOptionalConfigs(pretrained_model_name_or_path, {\n generation_config: 'generation_config.json',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.MaskGeneration) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: 'vision_encoder',\n prompt_encoder_mask_decoder: 'prompt_encoder_mask_decoder',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.EncoderDecoder) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: 'encoder_model',\n decoder_model_merged: 'decoder_model_merged',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.ImageTextToText) {\n const sessions = {\n embed_tokens: 'embed_tokens',\n vision_encoder: 'vision_encoder',\n decoder_model_merged: 'decoder_model_merged',\n }\n if (config.is_encoder_decoder) {\n sessions['model'] = 'encoder_model';\n }\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, sessions, options),\n getOptionalConfigs(pretrained_model_name_or_path, {\n generation_config: 'generation_config.json',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.Musicgen) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: 'text_encoder',\n decoder_model_merged: 'decoder_model_merged',\n encodec_decode: 'encodec_decode',\n }, options),\n getOptionalConfigs(pretrained_model_name_or_path, {\n generation_config: 'generation_config.json',\n }, options),\n ]);\n\n } else { // should be MODEL_TYPES.EncoderOnly\n if (modelType !== MODEL_TYPES.EncoderOnly) {\n console.warn(`Model type for '${modelName ?? config?.model_type}' not found, assuming encoder-only architecture. Please report this at ${GITHUB_ISSUE_URL}.`)\n }\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: options.model_file_name ?? 'model',\n }, options),\n ]);\n }\n\n // @ts-ignore\n return new this(config, ...info);\n }\n\n /**\n * Runs the model with the provided inputs\n * @param {Object} model_inputs Object containing input tensors\n * @returns {Promise} Object containing output tensors\n */\n async _call(model_inputs) {\n return await this.forward(model_inputs);\n }\n\n /**\n * Forward method for a pretrained model. If not overridden by a subclass, the correct forward method\n * will be chosen based on the model type.\n * @param {Object} model_inputs The input data to the model in the format specified in the ONNX model.\n * @returns {Promise} The output data from the model in the format specified in the ONNX model.\n * @throws {Error} This method must be implemented in subclasses.\n */\n async forward(model_inputs) {\n return await this._forward(this, model_inputs);\n }\n\n /**\n * Get the model's generation config, if it exists.\n * @returns {GenerationConfig|null} The model's generation config if it exists, otherwise `null`.\n */\n get generation_config() {\n return this.configs?.generation_config ?? null;\n }\n\n /**\n * This function returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsWarper`]\n * instances used for multinomial sampling.\n * @param {GenerationConfig} generation_config The generation config.\n * @returns {LogitsProcessorList} generation_config \n */\n _get_logits_warper(generation_config) {\n\n // instantiate warpers list\n const warpers = new LogitsProcessorList();\n\n if (generation_config.temperature !== null && generation_config.temperature !== 1.0) {\n warpers.push(new TemperatureLogitsWarper(generation_config.temperature));\n }\n if (generation_config.top_k !== null && generation_config.top_k !== 0) {\n // TODO: add min_tokens_to_keep\n warpers.push(new TopKLogitsWarper(generation_config.top_k));\n }\n if (generation_config.top_p !== null && generation_config.top_p < 1.0) {\n // TODO: add min_tokens_to_keep\n warpers.push(new TopPLogitsWarper(generation_config.top_p));\n }\n\n return warpers;\n }\n\n /**\n * @param {GenerationConfig} generation_config \n * @param {number} input_ids_seq_length The starting sequence length for the input ids.\n * @returns {LogitsProcessorList}\n * @private\n */\n _get_logits_processor(\n generation_config,\n input_ids_seq_length,\n // encoder_input_ids, TODO\n // prefix_allowed_tokens_fn, TODO\n logits_processor = null\n ) {\n const processors = new LogitsProcessorList();\n\n // if (generation_config.diversity_penalty !== null && generation_config.diversity_penalty > 0.0) {\n // processors.push(new HammingDiversityLogitsProcessor(\n // generation_config.diversity_penalty,\n // generation_config.num_beams,\n // generation_config.num_beam_groups\n // ));\n // }\n\n // if (generation_config.encoder_repetition_penalty !== null && generation_config.encoder_repetition_penalty !== 1.0) {\n // processors.push(new EncoderRepetitionPenaltyLogitsProcessor(\n // generation_config.encoder_repetition_penalty,\n // encoder_input_ids\n // ));\n // }\n\n if (generation_config.repetition_penalty !== null && generation_config.repetition_penalty !== 1.0) {\n processors.push(new RepetitionPenaltyLogitsProcessor(generation_config.repetition_penalty));\n }\n\n if (generation_config.no_repeat_ngram_size !== null && generation_config.no_repeat_ngram_size > 0) {\n processors.push(new NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size));\n }\n\n // if (generation_config.encoder_no_repeat_ngram_size !== null && generation_config.encoder_no_repeat_ngram_size > 0) {\n // if (this.config.is_encoder_decoder) {\n // processors.push(new EncoderNoRepeatNGramLogitsProcessor(\n // generation_config.encoder_no_repeat_ngram_size,\n // encoder_input_ids\n // ));\n // } else {\n // throw new Error(\"It's impossible to use `encoder_no_repeat_ngram_size` with decoder-only architecture\");\n // }\n // }\n\n if (generation_config.bad_words_ids !== null) {\n processors.push(new NoBadWordsLogitsProcessor(generation_config.bad_words_ids, generation_config.eos_token_id));\n }\n\n if (generation_config.min_length !== null && generation_config.eos_token_id !== null && generation_config.min_length > 0) {\n processors.push(new MinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id));\n }\n\n if (generation_config.min_new_tokens !== null && generation_config.eos_token_id !== null && generation_config.min_new_tokens > 0) {\n processors.push(new MinNewTokensLengthLogitsProcessor(\n input_ids_seq_length,\n generation_config.min_new_tokens,\n generation_config.eos_token_id\n ));\n }\n\n // if (prefix_allowed_tokens_fn !== null) {\n // processors.push(new PrefixConstrainedLogitsProcessor(\n // prefix_allowed_tokens_fn,\n // generation_config.num_beams / generation_config.num_beam_groups\n // ));\n // }\n\n\n if (generation_config.forced_bos_token_id !== null) {\n processors.push(new ForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id));\n }\n\n if (generation_config.forced_eos_token_id !== null) {\n processors.push(new ForcedEOSTokenLogitsProcessor(\n generation_config.max_length,\n generation_config.forced_eos_token_id\n ));\n }\n\n // if (generation_config.remove_invalid_values === true) {\n // processors.push(new InfNanRemoveLogitsProcessor());\n // }\n\n // if (generation_config.exponential_decay_length_penalty !== null) {\n // processors.push(new ExponentialDecayLengthPenalty(\n // generation_config.exponential_decay_length_penalty,\n // generation_config.eos_token_id,\n // input_ids_seq_length\n // ));\n // }\n\n // if (generation_config.suppress_tokens !== null) {\n // processors.push(new SuppressTokensLogitsProcessor(generation_config.suppress_tokens));\n // }\n\n if (generation_config.begin_suppress_tokens !== null) {\n const begin_index = (input_ids_seq_length > 1 || generation_config.forced_bos_token_id === null)\n ? input_ids_seq_length\n : input_ids_seq_length + 1;\n\n processors.push(new SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index));\n }\n\n // DEPRECATED: https://github.com/huggingface/transformers/pull/29485\n // if (generation_config.forced_decoder_ids !== null) {\n // processors.push(new ForceTokensLogitsProcessor(generation_config.forced_decoder_ids));\n // }\n\n\n // 8. prepare batched CFG externally\n if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) {\n processors.push(new ClassifierFreeGuidanceLogitsProcessor(generation_config.guidance_scale));\n }\n\n if (logits_processor !== null) {\n processors.extend(logits_processor)\n }\n\n // `LogitNormalization` should always be the last logit processor, when present\n // if (generation_config.renormalize_logits === true) {\n // processors.push(new LogitNormalization());\n // }\n\n return processors;\n }\n\n /**\n * This function merges multiple generation configs together to form a final generation config to be used by the model for text generation.\n * It first creates an empty `GenerationConfig` object, then it applies the model's own `generation_config` property to it. Finally, if a `generation_config` object was passed in the arguments, it overwrites the corresponding properties in the final config with those of the passed config object.\n * @param {GenerationConfig|null} generation_config A `GenerationConfig` object containing generation parameters.\n * @param {Object} kwargs Additional generation parameters to be used in place of those in the `generation_config` object.\n * @returns {GenerationConfig} The final generation config object to be used by the model for text generation.\n */\n _prepare_generation_config(generation_config, kwargs, cls = GenerationConfig) {\n // Create empty generation config (contains defaults)\n // We pass `this.config` so that if `eos_token_id` or `bos_token_id` exist in the model's config, we will use them\n const config = { ...this.config };\n for (const key of [\"decoder\", \"generator\", \"text_config\"]) {\n // Special case: some models have generation attributes set in the decoder.\n // Use them if still unset in the generation config.\n if (key in config) {\n Object.assign(config, config[key]);\n }\n }\n\n const gen_config = new cls(config);\n\n // Apply model's generation config, if it exists\n Object.assign(gen_config, this.generation_config ?? {});\n\n // Next, use any generation config specified by the user\n // when calling `generate`\n if (generation_config) {\n Object.assign(gen_config, generation_config);\n }\n\n // Finally, if any kwargs were passed, use them to overwrite\n if (kwargs) {\n Object.assign(gen_config, pick(kwargs, Object.getOwnPropertyNames(gen_config)));\n }\n\n return gen_config;\n }\n\n /**\n * \n * @param {GenerationConfig} generation_config \n * @param {StoppingCriteriaList} [stopping_criteria=null] \n */\n _get_stopping_criteria(generation_config, stopping_criteria = null) {\n const criteria = new StoppingCriteriaList();\n\n if (generation_config.max_length !== null) {\n criteria.push(new MaxLengthCriteria(\n generation_config.max_length,\n this.config.max_position_embeddings ?? null,\n ));\n }\n // if (generation_config.max_time !== null) {\n // criteria.push(new MaxTimeCriteria(generation_config.max_time));\n // }\n if (generation_config.eos_token_id !== null) {\n criteria.push(new EosTokenCriteria(generation_config.eos_token_id));\n }\n\n if (stopping_criteria) {\n criteria.extend(stopping_criteria);\n }\n return criteria;\n\n }\n\n /**\n * Confirms that the model class is compatible with generation.\n * If not, raises an exception that points to the right class to use.\n */\n _validate_model_class() {\n if (!this.can_generate) {\n const generate_compatible_mappings = [\n MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,\n // MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING, // TODO\n MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,\n MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,\n MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES,\n ];\n\n const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);\n\n const generate_compatible_classes = new Set();\n const modelType = this.config.model_type;\n for (const model_mapping of generate_compatible_mappings) {\n const supported_models = model_mapping.get(modelType);\n if (supported_models) {\n generate_compatible_classes.add(supported_models[0]);\n }\n }\n\n let errorMessage = `The current model class (${modelName}) is not compatible with \\`.generate()\\`, as it doesn't have a language model head.`\n if (generate_compatible_classes.size > 0) {\n errorMessage += ` Please use the following class instead: ${[...generate_compatible_classes].join(', ')}`;\n }\n throw Error(errorMessage);\n }\n }\n\n prepare_inputs_for_generation(...args) {\n return this._prepare_inputs_for_generation(this, ...args);\n }\n\n /**\n * \n * @param {Object} inputs\n * @param {bigint[][]} inputs.generated_input_ids\n * @param {Object} inputs.outputs\n * @param {Object} inputs.model_inputs\n * @param {boolean} inputs.is_encoder_decoder\n * @returns {Object} The updated model inputs for the next generation iteration.\n */\n _update_model_kwargs_for_generation({ generated_input_ids, outputs, model_inputs, is_encoder_decoder }) {\n // update past_key_values\n model_inputs['past_key_values'] = this.getPastKeyValues(outputs, model_inputs.past_key_values);\n\n // update inputs for next run\n model_inputs['input_ids'] = new Tensor('int64', generated_input_ids.flat(), [generated_input_ids.length, 1]);\n\n if (!is_encoder_decoder) {\n // update attention mask\n model_inputs.attention_mask = cat(\n [\n model_inputs.attention_mask,\n ones([model_inputs.attention_mask.dims[0], 1]),\n ], 1\n );\n } else if ('decoder_attention_mask' in model_inputs) {\n // TODO: update decoder attention mask if the model requires it\n }\n\n // force recreate position_ids in next iteration\n model_inputs['position_ids'] = null;\n\n return model_inputs;\n }\n\n /**\n * This function extracts the model-specific `inputs` for generation.\n * @param {Object} params\n * @param {Tensor} [params.inputs=null]\n * @param {number} [params.bos_token_id=null]\n * @param {Record} [params.model_kwargs]\n * @returns {{inputs_tensor: Tensor, model_inputs: Record, model_input_name: string}} The model-specific inputs for generation.\n */\n _prepare_model_inputs({ inputs, bos_token_id, model_kwargs }) {\n const model_inputs = pick(model_kwargs, this.forward_params);\n const input_name = this.main_input_name;\n if (input_name in model_inputs) {\n if (inputs) {\n throw new Error(\n \"`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. \" +\n \"Make sure to either pass {inputs} or {input_name}=...\"\n );\n }\n } else {\n model_inputs[input_name] = inputs;\n }\n\n const inputs_tensor = model_inputs[input_name];\n\n return { inputs_tensor, model_inputs, model_input_name: input_name };\n }\n\n async _prepare_encoder_decoder_kwargs_for_generation({ inputs_tensor, model_inputs, model_input_name, generation_config }) {\n if (\n this.sessions['model'].inputNames.includes('inputs_embeds')\n && !model_inputs.inputs_embeds\n && '_prepare_inputs_embeds' in this\n ) {\n // Encoder expects `inputs_embeds` instead of `input_ids`\n const { input_ids, pixel_values, attention_mask, ...kwargs } = model_inputs;\n // @ts-ignore\n const prepared_inputs = await this._prepare_inputs_embeds(model_inputs);\n model_inputs = {\n ...kwargs,\n ...pick(prepared_inputs, ['inputs_embeds', 'attention_mask']),\n };\n }\n let { last_hidden_state } = await encoderForward(this, model_inputs);\n\n // for classifier free guidance we need to add a 'null' input to our encoder hidden states\n if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) {\n\n last_hidden_state = cat([\n last_hidden_state,\n full_like(last_hidden_state, 0.0),\n ], 0);\n\n if ('attention_mask' in model_inputs) {\n model_inputs['attention_mask'] = cat([\n model_inputs['attention_mask'],\n zeros_like(model_inputs['attention_mask']),\n ], 0);\n }\n\n } else if (model_inputs.decoder_input_ids) {\n // Ensure that the encoder outputs have the same batch size as the decoder inputs,\n // allowing for more efficient batched generation for single inputs\n const decoder_input_ids_batch_size = toI64Tensor(model_inputs.decoder_input_ids).dims[0];\n if (decoder_input_ids_batch_size !== last_hidden_state.dims[0]) {\n if (last_hidden_state.dims[0] !== 1) {\n throw new Error(\n `The encoder outputs have a different batch size (${last_hidden_state.dims[0]}) than the decoder inputs (${decoder_input_ids_batch_size}).`\n )\n }\n last_hidden_state = cat(Array.from({ length: decoder_input_ids_batch_size }, () => last_hidden_state), 0);\n }\n }\n model_inputs['encoder_outputs'] = last_hidden_state;\n\n return model_inputs;\n }\n\n /**\n * Prepares `decoder_input_ids` for generation with encoder-decoder models\n * @param {*} param0 \n */\n _prepare_decoder_input_ids_for_generation({ batch_size, model_input_name, model_kwargs, decoder_start_token_id, bos_token_id, generation_config }) {\n let { decoder_input_ids, ...model_inputs } = model_kwargs;\n\n // Prepare input ids if the user has not defined `decoder_input_ids` manually.\n if (!decoder_input_ids) {\n decoder_start_token_id ??= bos_token_id;\n\n if (this.config.model_type === 'musicgen') {\n // Custom logic (TODO: move to Musicgen class)\n decoder_input_ids = Array.from({\n length: batch_size * this.config.decoder.num_codebooks\n }, () => [decoder_start_token_id]);\n\n } else if (Array.isArray(decoder_start_token_id)) {\n if (decoder_start_token_id.length !== batch_size) {\n throw new Error(\n `\\`decoder_start_token_id\\` expcted to have length ${batch_size} but got ${decoder_start_token_id.length}`\n )\n }\n decoder_input_ids = decoder_start_token_id;\n } else {\n decoder_input_ids = Array.from({\n length: batch_size,\n }, () => [decoder_start_token_id]);\n }\n } else if (!Array.isArray(decoder_input_ids[0])) {\n // Correct batch size\n decoder_input_ids = Array.from({\n length: batch_size,\n }, () => decoder_input_ids);\n }\n\n decoder_input_ids = toI64Tensor(decoder_input_ids);\n model_kwargs['decoder_attention_mask'] = ones_like(decoder_input_ids);\n\n return { input_ids: decoder_input_ids, model_inputs };\n }\n\n /**\n * Generates sequences of token ids for models with a language modeling head.\n * @param {import('./generation/parameters.js').GenerationFunctionParameters} options\n * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores.\n */\n async generate({\n inputs = null,\n generation_config = null,\n logits_processor = null,\n stopping_criteria = null,\n streamer = null,\n\n // inputs_attention_mask = null,\n ...kwargs\n }) {\n this._validate_model_class();\n\n // Update generation config with defaults and kwargs\n generation_config = this._prepare_generation_config(generation_config, kwargs);\n\n // 3. Define model inputs\n let { inputs_tensor, model_inputs, model_input_name } = this._prepare_model_inputs({\n inputs,\n model_kwargs: kwargs,\n });\n\n const is_encoder_decoder = this.config.is_encoder_decoder;\n\n // 4. Define other model kwargs\n if (!is_encoder_decoder) {\n // decoder-only models should use left-padding for generation\n } else if (!('encoder_outputs' in model_inputs)) {\n // if model is encoder decoder encoder_outputs are created\n // and added to `model_kwargs`\n model_inputs = await this._prepare_encoder_decoder_kwargs_for_generation(\n { inputs_tensor, model_inputs, model_input_name, generation_config }\n )\n }\n\n // 5. Prepare `input_ids` which will be used for auto-regressive generation\n // TODO: Update to align with HF transformers' implementation\n let input_ids;\n if (is_encoder_decoder) {\n // Generating from the encoder outputs\n ({ input_ids, model_inputs } = this._prepare_decoder_input_ids_for_generation({\n batch_size: model_inputs[model_input_name].dims.at(0),\n model_input_name,\n model_kwargs: model_inputs,\n decoder_start_token_id: generation_config.decoder_start_token_id,\n bos_token_id: generation_config.bos_token_id,\n generation_config,\n }));\n } else {\n input_ids = model_inputs[model_input_name]\n }\n\n // 6. Prepare `max_length` depending on other stopping criteria.\n let input_ids_length = input_ids.dims.at(-1);\n\n if (generation_config.max_new_tokens !== null) {\n generation_config.max_length = input_ids_length + generation_config.max_new_tokens;\n }\n\n // input_ids_length = model_inputs[model_input_name].dims.at(1);\n // // inputs instanceof Tensor ? : inputs.length;\n\n // // decoder-only\n // if (input_ids_length === 0) {\n // throw Error(\"Must supply a non-empty array of input token ids.\")\n // }\n\n // let decoder_input_ids =\n // generation_config.decoder_input_ids\n // ?? generation_config.decoder_start_token_id\n // ?? generation_config.bos_token_id\n // ?? generation_config.eos_token_id;\n\n // Update logits processor\n // 8. prepare distribution pre_processing samplers\n const prepared_logits_processor = this._get_logits_processor(\n generation_config,\n input_ids_length,\n logits_processor,\n )\n\n // 9. prepare stopping criteria\n const prepared_stopping_criteria = this._get_stopping_criteria(\n generation_config, stopping_criteria\n )\n\n // /** @type {number[]} */\n // let eos_token_ids = generation_config.eos_token_id;\n // if (eos_token_ids !== null && !Array.isArray(eos_token_ids)) {\n // eos_token_ids = [eos_token_ids];\n // }\n\n const numInputs = model_inputs[model_input_name].dims.at(0);\n\n // TODO:\n // done is a list of booleans to keep track of which inputs are done\n // const done = new Array(numInputs).fill(false);\n // For efficiency purposes, we remove completed rows from model_inputs\n // when the beam is complete, and we keep track of the row index\n // const rowIndexToBatchIndex = new Map();\n\n const sampler = LogitsSampler.getSampler(generation_config);\n\n // TODO make > numInputs\n const scores = new Array(numInputs).fill(0);\n /** @type {bigint[][]} */\n const all_input_ids = input_ids.tolist();\n if (streamer) {\n streamer.put(all_input_ids);\n }\n // const all_generated_input_ids = Array.from({ length: numInputs }, () => []);\n\n // NOTE: For now, we don't support spawning new beams\n // TODO: when we do, we simply copy past key values and accumulate into single large tensor\n\n ////////////////////////////////////////////////////\n // Generic search which handles 4 generation modes:\n // - GenerationMode.GREEDY_SEARCH\n // - GenerationMode.SAMPLE\n // - GenerationMode.BEAM_SEARCH\n // - GenerationMode.BEAM_SAMPLE\n ////////////////////////////////////////////////////\n let outputs;\n let attentions = {};\n while (true) {\n // prepare model inputs\n model_inputs = this.prepare_inputs_for_generation(all_input_ids, model_inputs, generation_config);\n outputs = await this.forward(model_inputs);\n\n if (generation_config.output_attentions && generation_config.return_dict_in_generate) {\n // Get attentions if they are present\n const token_attentions = this.getAttentions(outputs);\n for (const key in token_attentions) {\n if (!(key in attentions)) {\n attentions[key] = [];\n }\n attentions[key].push(token_attentions[key]);\n }\n }\n\n // Logits are of the form [batch_size, out_seq_length, vocab_size]\n // In most cases, this will be [batch_size, 1, vocab_size]\n // So, we select the last token's logits:\n // (equivalent to `logits = outputs.logits[:, -1, :]`)\n const logits = outputs.logits.slice(null, -1, null);\n\n const next_tokens_scores = prepared_logits_processor(all_input_ids, logits);\n\n /** @type {[bigint][]} */\n const generated_input_ids = [];\n // const new_kv_cache = [];// NOTE: Only used for beam search when concatenating new kv\n // Loop over each batch\n for (let batch_idx = 0; batch_idx < next_tokens_scores.dims.at(0); ++batch_idx) {\n const logs = next_tokens_scores[batch_idx];\n\n const sampledTokens = await sampler(logs);\n for (const [newTokenId, logProb] of sampledTokens) {\n const bigint = BigInt(newTokenId);\n // TODO: If branching, use previous beam as a starting point\n // update generated ids, model inputs, and length for next step\n scores[batch_idx] += logProb;\n all_input_ids[batch_idx].push(bigint);\n generated_input_ids.push([bigint]);\n\n // TODO: Support beam search\n break;\n }\n }\n if (streamer) {\n streamer.put(generated_input_ids);\n }\n\n const stop = prepared_stopping_criteria(all_input_ids);\n if (stop.every(x => x)) {\n break;\n }\n\n model_inputs = this._update_model_kwargs_for_generation({\n generated_input_ids, outputs, model_inputs, is_encoder_decoder,\n });\n }\n\n if (streamer) {\n streamer.end();\n }\n\n // Retrieve and dispose all final past key values (including encoder attentions)\n const past_key_values = this.getPastKeyValues(outputs, model_inputs.past_key_values, true);\n\n // TODO: ensure all_input_ids is padded correctly...\n const sequences = new Tensor('int64', all_input_ids.flat(), [all_input_ids.length, all_input_ids[0].length]);\n\n if (generation_config.return_dict_in_generate) {\n return {\n sequences,\n past_key_values,\n ...attentions,\n // TODO:\n // scores,\n // logits,\n }\n } else {\n // Dispose all remaining tensors\n for (const tensor of Object.values(outputs)) {\n if (tensor.location === 'gpu-buffer') {\n tensor.dispose();\n }\n }\n return sequences;\n }\n }\n\n /**\n * Returns an object containing past key values from the given decoder results object.\n *\n * @param {Object} decoderResults The decoder results object.\n * @param {Object} pastKeyValues The previous past key values.\n * @returns {Object} An object containing past key values.\n */\n getPastKeyValues(decoderResults, pastKeyValues, disposeEncoderPKVs = false) {\n const pkvs = Object.create(null);\n\n for (const name in decoderResults) {\n if (name.startsWith('present')) {\n const newName = name.replace('present', 'past_key_values');\n const is_encoder_pkv = name.includes('encoder');\n if (is_encoder_pkv && pastKeyValues) {\n // Optimization introduced by optimum to reuse past key values.\n // So, we just replace the constant outputs (`decoderResults[name]`) with the previous past key values.\n // https://github.com/huggingface/optimum/blob/0bf2c05fb7e1182b52d21b703cfc95fd9e4ea3dc/optimum/onnxruntime/base.py#L677-L704\n pkvs[newName] = pastKeyValues[newName];\n } else { // decoder or using first encoder PKVs\n pkvs[newName] = decoderResults[name];\n }\n\n if (pastKeyValues && (!is_encoder_pkv || disposeEncoderPKVs)) {\n // - Always dispose decoder PKVs\n // - Only dispose encoder past key values when requested (after generation)\n const t = pastKeyValues[newName];\n if (t.location === 'gpu-buffer') {\n t.dispose();\n }\n }\n }\n }\n return pkvs;\n }\n\n /**\n * Returns an object containing attentions from the given model output object.\n *\n * @param {Object} model_output The output of the model.\n * @returns {{cross_attentions?: Tensor[]}} An object containing attentions.\n */\n getAttentions(model_output) {\n const attentions = {};\n\n for (const attnName of ['cross_attentions', 'encoder_attentions', 'decoder_attentions']) {\n for (const name in model_output) {\n if (name.startsWith(attnName)) {\n if (!(attnName in attentions)) {\n attentions[attnName] = [];\n }\n attentions[attnName].push(model_output[name]);\n }\n }\n }\n return attentions;\n }\n\n /**\n * Adds past key values to the decoder feeds object. If pastKeyValues is null, creates new tensors for past key values.\n *\n * @param {Object} decoderFeeds The decoder feeds object to add past key values to.\n * @param {Object} pastKeyValues An object containing past key values.\n */\n addPastKeyValues(decoderFeeds, pastKeyValues) {\n if (pastKeyValues) {\n Object.assign(decoderFeeds, pastKeyValues)\n } else {\n const session = this.sessions['decoder_model_merged'] ?? this.sessions['model'];\n const dtype = session?.config?.kv_cache_dtype ?? 'float32';\n const empty = (dtype === 'float16') ? new Uint16Array() : [];\n\n const shapes = getKeyValueShapes(this.config);\n\n for (const name in shapes) {\n decoderFeeds[name] = new Tensor(dtype, empty, shapes[name]);\n }\n }\n }\n\n async encode_image({ pixel_values }) {\n // image_inputs === { pixel_values }\n const features = (await sessionRun(this.sessions['vision_encoder'], { pixel_values })).image_features;\n if (!this.config.num_image_tokens) {\n console.warn(\n 'The number of image tokens was not set in the model configuration. ' +\n `Setting it to the number of features detected by the vision encoder (${features.dims[1]}).`\n )\n this.config.num_image_tokens = features.dims[1];\n }\n return features;\n }\n\n async encode_text({ input_ids }) {\n // text_inputs === { input_ids, attention_mask }\n return (await sessionRun(this.sessions['embed_tokens'], { input_ids })).inputs_embeds;\n }\n}\n\n//////////////////////////////////////////////////\n// Base model output class\nexport class ModelOutput { }\n\n/**\n * Base class for model's outputs, with potential hidden states and attentions.\n */\nexport class BaseModelOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.last_hidden_state Sequence of hidden-states at the output of the last layer of the model.\n * @param {Tensor} [output.hidden_states] Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.\n * @param {Tensor} [output.attentions] Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n */\n constructor({ last_hidden_state, hidden_states = null, attentions = null }) {\n super();\n this.last_hidden_state = last_hidden_state;\n this.hidden_states = hidden_states;\n this.attentions = attentions;\n }\n}\n//////////////////////////////////////////////////\n// Bert models\nexport class BertPreTrainedModel extends PreTrainedModel { }\nexport class BertModel extends BertPreTrainedModel { }\n\n/**\n * BertForMaskedLM is a class representing a BERT model for masked language modeling.\n */\nexport class BertForMaskedLM extends BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * BertForSequenceClassification is a class representing a BERT model for sequence classification.\n */\nexport class BertForSequenceClassification extends BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * BertForTokenClassification is a class representing a BERT model for token classification.\n */\nexport class BertForTokenClassification extends BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * BertForQuestionAnswering is a class representing a BERT model for question answering.\n */\nexport class BertForQuestionAnswering extends BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// NomicBert models\nexport class NomicBertPreTrainedModel extends PreTrainedModel { }\nexport class NomicBertModel extends NomicBertPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// RoFormer models\nexport class RoFormerPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare RoFormer Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class RoFormerModel extends RoFormerPreTrainedModel { }\n\n/**\n * RoFormer Model with a `language modeling` head on top.\n */\nexport class RoFormerForMaskedLM extends RoFormerPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RoFormer Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class RoFormerForSequenceClassification extends RoFormerPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RoFormer Model with a token classification head on top (a linear layer on top of the hidden-states output)\n * e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class RoFormerForTokenClassification extends RoFormerPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RoFormer Model with a span classification head on top for extractive question-answering tasks like SQuAD\n * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n */\nexport class RoFormerForQuestionAnswering extends RoFormerPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n// TODO: Add RoFormerForCausalLM and RoFormerForMultipleChoice\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// ConvBert models\nexport class ConvBertPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ConvBERT Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class ConvBertModel extends ConvBertPreTrainedModel { }\n\n/**\n * ConvBERT Model with a language modeling head on top.\n */\nexport class ConvBertForMaskedLM extends ConvBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ConvBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class ConvBertForSequenceClassification extends ConvBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ConvBERT Model with a token classification head on top (a linear layer on top of the hidden-states output)\n * e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class ConvBertForTokenClassification extends ConvBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ConvBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD\n * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`)\n */\nexport class ConvBertForQuestionAnswering extends ConvBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Electra models\nexport class ElectraPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Electra Model transformer outputting raw hidden-states without any specific head on top.\n * Identical to the BERT model except that it uses an additional linear layer between the embedding\n * layer and the encoder if the hidden size and embedding size are different.\n */\nexport class ElectraModel extends ElectraPreTrainedModel { }\n// TODO add ElectraForPreTraining\n/**\n * Electra model with a language modeling head on top.\n */\nexport class ElectraForMaskedLM extends ElectraPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ELECTRA Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class ElectraForSequenceClassification extends ElectraPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * Electra model with a token classification head on top.\n */\nexport class ElectraForTokenClassification extends ElectraPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * LECTRA Model with a span classification head on top for extractive question-answering tasks like SQuAD\n * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n */\nexport class ElectraForQuestionAnswering extends ElectraPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// CamemBERT models\nexport class CamembertPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare CamemBERT Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class CamembertModel extends CamembertPreTrainedModel { }\n\n/**\n * CamemBERT Model with a `language modeling` head on top.\n */\nexport class CamembertForMaskedLM extends CamembertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * CamemBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.\n */\nexport class CamembertForSequenceClassification extends CamembertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * CamemBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class CamembertForTokenClassification extends CamembertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * CamemBERT Model with a span classification head on top for extractive question-answering tasks\n */\nexport class CamembertForQuestionAnswering extends CamembertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// DeBERTa models\nexport class DebertaPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare DeBERTa Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class DebertaModel extends DebertaPreTrainedModel { }\n\n/**\n * DeBERTa Model with a `language modeling` head on top.\n */\nexport class DebertaForMaskedLM extends DebertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class DebertaForSequenceClassification extends DebertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class DebertaForTokenClassification extends DebertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear\n * layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n */\nexport class DebertaForQuestionAnswering extends DebertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// DeBERTa-v2 models\nexport class DebertaV2PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare DeBERTa-V2 Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class DebertaV2Model extends DebertaV2PreTrainedModel { }\n\n/**\n * DeBERTa-V2 Model with a `language modeling` head on top.\n */\nexport class DebertaV2ForMaskedLM extends DebertaV2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa-V2 Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class DebertaV2ForSequenceClassification extends DebertaV2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa-V2 Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class DebertaV2ForTokenClassification extends DebertaV2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa-V2 Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear\n * layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n */\nexport class DebertaV2ForQuestionAnswering extends DebertaV2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// DistilBert models\nexport class DistilBertPreTrainedModel extends PreTrainedModel { }\nexport class DistilBertModel extends DistilBertPreTrainedModel { }\n\n/**\n * DistilBertForSequenceClassification is a class representing a DistilBERT model for sequence classification.\n */\nexport class DistilBertForSequenceClassification extends DistilBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DistilBertForTokenClassification is a class representing a DistilBERT model for token classification.\n */\nexport class DistilBertForTokenClassification extends DistilBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n\n/**\n * DistilBertForQuestionAnswering is a class representing a DistilBERT model for question answering.\n */\nexport class DistilBertForQuestionAnswering extends DistilBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DistilBertForMaskedLM is a class representing a DistilBERT model for masking task.\n */\nexport class DistilBertForMaskedLM extends DistilBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// ESM models\nexport class EsmPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ESM Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class EsmModel extends EsmPreTrainedModel { }\n\n/**\n * ESM Model with a `language modeling` head on top.\n */\nexport class EsmForMaskedLM extends EsmPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ESM Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class EsmForSequenceClassification extends EsmPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ESM Model with a token classification head on top (a linear layer on top of the hidden-states output)\n * e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class EsmForTokenClassification extends EsmPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// MobileBert models\nexport class MobileBertPreTrainedModel extends PreTrainedModel { }\nexport class MobileBertModel extends MobileBertPreTrainedModel { }\n\n/**\n * MobileBertForMaskedLM is a class representing a MobileBERT model for masking task.\n */\nexport class MobileBertForMaskedLM extends MobileBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class MobileBertForSequenceClassification extends MobileBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MobileBert Model with a span classification head on top for extractive question-answering tasks\n */\nexport class MobileBertForQuestionAnswering extends MobileBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MPNet models\nexport class MPNetPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MPNet Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class MPNetModel extends MPNetPreTrainedModel { }\n\n/**\n * MPNetForMaskedLM is a class representing a MPNet model for masked language modeling.\n */\nexport class MPNetForMaskedLM extends MPNetPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MPNetForSequenceClassification is a class representing a MPNet model for sequence classification.\n */\nexport class MPNetForSequenceClassification extends MPNetPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MPNetForTokenClassification is a class representing a MPNet model for token classification.\n */\nexport class MPNetForTokenClassification extends MPNetPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MPNetForQuestionAnswering is a class representing a MPNet model for question answering.\n */\nexport class MPNetForQuestionAnswering extends MPNetPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// SqueezeBert models\nexport class SqueezeBertPreTrainedModel extends PreTrainedModel { }\nexport class SqueezeBertModel extends SqueezeBertPreTrainedModel { }\nexport class SqueezeBertForMaskedLM extends SqueezeBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\nexport class SqueezeBertForSequenceClassification extends SqueezeBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\nexport class SqueezeBertForQuestionAnswering extends SqueezeBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Albert models\nexport class AlbertPreTrainedModel extends PreTrainedModel { }\nexport class AlbertModel extends AlbertPreTrainedModel { }\nexport class AlbertForSequenceClassification extends AlbertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\nexport class AlbertForQuestionAnswering extends AlbertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\nexport class AlbertForMaskedLM extends AlbertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// T5 models\nexport class T5PreTrainedModel extends PreTrainedModel {\n forward_params = [\n 'input_ids',\n 'attention_mask',\n 'encoder_outputs',\n 'decoder_input_ids',\n 'decoder_attention_mask',\n 'past_key_values',\n ];\n};\n\nexport class T5Model extends T5PreTrainedModel { }\n\n/**\n * T5Model is a class representing a T5 model for conditional generation.\n */\nexport class T5ForConditionalGeneration extends T5PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// LONGT5 models\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class LongT5PreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare LONGT5 Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class LongT5Model extends LongT5PreTrainedModel { }\n\n/**\n * LONGT5 Model with a `language modeling` head on top.\n */\nexport class LongT5ForConditionalGeneration extends LongT5PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// MT5 models\nexport class MT5PreTrainedModel extends PreTrainedModel { };\n\nexport class MT5Model extends MT5PreTrainedModel { }\n\n/**\n * A class representing a conditional sequence-to-sequence model based on the MT5 architecture.\n */\nexport class MT5ForConditionalGeneration extends MT5PreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Bart models\nexport class BartPretrainedModel extends PreTrainedModel { };\n\n/**\n * The bare BART Model outputting raw hidden-states without any specific head on top.\n */\nexport class BartModel extends BartPretrainedModel { }\n\n/**\n * The BART Model with a language modeling head. Can be used for summarization.\n */\nexport class BartForConditionalGeneration extends BartPretrainedModel { }\n\n/**\n * Bart model with a sequence classification/head on top (a linear layer on top of the pooled output)\n */\nexport class BartForSequenceClassification extends BartPretrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MBart models\nexport class MBartPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare MBART Model outputting raw hidden-states without any specific head on top.\n */\nexport class MBartModel extends MBartPreTrainedModel { }\n\n/**\n * The MBART Model with a language modeling head. Can be used for summarization, after fine-tuning the pretrained models.\n */\nexport class MBartForConditionalGeneration extends MBartPreTrainedModel { }\n\n/**\n * MBart model with a sequence classification/head on top (a linear layer on top of the pooled output).\n */\nexport class MBartForSequenceClassification extends MBartPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n\nexport class MBartForCausalLM extends MBartPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Blenderbot models\nexport class BlenderbotPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare Blenderbot Model outputting raw hidden-states without any specific head on top.\n */\nexport class BlenderbotModel extends BlenderbotPreTrainedModel { }\n\n/**\n * The Blenderbot Model with a language modeling head. Can be used for summarization.\n */\nexport class BlenderbotForConditionalGeneration extends BlenderbotPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Blenderbot models\nexport class BlenderbotSmallPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare BlenderbotSmall Model outputting raw hidden-states without any specific head on top.\n */\nexport class BlenderbotSmallModel extends BlenderbotSmallPreTrainedModel { }\n\n/**\n * The BlenderbotSmall Model with a language modeling head. Can be used for summarization.\n */\nexport class BlenderbotSmallForConditionalGeneration extends BlenderbotSmallPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Roberta models\nexport class RobertaPreTrainedModel extends PreTrainedModel { }\nexport class RobertaModel extends RobertaPreTrainedModel { }\n\n/**\n * RobertaForMaskedLM class for performing masked language modeling on Roberta models.\n */\nexport class RobertaForMaskedLM extends RobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RobertaForSequenceClassification class for performing sequence classification on Roberta models.\n */\nexport class RobertaForSequenceClassification extends RobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RobertaForTokenClassification class for performing token classification on Roberta models.\n */\nexport class RobertaForTokenClassification extends RobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RobertaForQuestionAnswering class for performing question answering on Roberta models.\n */\nexport class RobertaForQuestionAnswering extends RobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// XLM models\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class XLMPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare XLM Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class XLMModel extends XLMPreTrainedModel { }\n\n/**\n * The XLM Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class XLMWithLMHeadModel extends XLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLM Model with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class XLMForSequenceClassification extends XLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLM Model with a token classification head on top (a linear layer on top of the hidden-states output)\n */\nexport class XLMForTokenClassification extends XLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLM Model with a span classification head on top for extractive question-answering tasks\n */\nexport class XLMForQuestionAnswering extends XLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// XLMRoberta models\nexport class XLMRobertaPreTrainedModel extends PreTrainedModel { }\nexport class XLMRobertaModel extends XLMRobertaPreTrainedModel { }\n\n/**\n * XLMRobertaForMaskedLM class for performing masked language modeling on XLMRoberta models.\n */\nexport class XLMRobertaForMaskedLM extends XLMRobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLMRobertaForSequenceClassification class for performing sequence classification on XLMRoberta models.\n */\nexport class XLMRobertaForSequenceClassification extends XLMRobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLMRobertaForTokenClassification class for performing token classification on XLMRoberta models.\n */\nexport class XLMRobertaForTokenClassification extends XLMRobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLMRobertaForQuestionAnswering class for performing question answering on XLMRoberta models.\n */\nexport class XLMRobertaForQuestionAnswering extends XLMRobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Audio Spectrogram Transformer (AST) models\nexport class ASTPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare AST Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class ASTModel extends ASTPreTrainedModel { }\n\n/**\n * Audio Spectrogram Transformer model with an audio classification head on top\n * (a linear layer on top of the pooled output) e.g. for datasets like AudioSet, Speech Commands v2.\n */\nexport class ASTForAudioClassification extends ASTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Whisper models\nexport class WhisperPreTrainedModel extends PreTrainedModel {\n\n requires_attention_mask = false;\n main_input_name = 'input_features';\n forward_params = [\n 'input_features',\n 'attention_mask',\n 'decoder_input_ids',\n 'decoder_attention_mask',\n 'past_key_values',\n ];\n};\n\n/**\n * WhisperModel class for training Whisper models without a language model head.\n */\nexport class WhisperModel extends WhisperPreTrainedModel { }\n\n\n/**\n * WhisperForConditionalGeneration class for generating conditional outputs from Whisper models.\n */\nexport class WhisperForConditionalGeneration extends WhisperPreTrainedModel {\n\n _prepare_generation_config(generation_config, kwargs) {\n return /** @type {WhisperGenerationConfig} */ (super._prepare_generation_config(generation_config, kwargs, WhisperGenerationConfig));\n }\n\n /**\n * \n * @param {WhisperGenerationConfig} generation_config \n */\n _retrieve_init_tokens(generation_config) {\n // prefix tokens are of the form: \n // - Multilingual: <|startoftranscript|> <|lang_id|> <|task|> [<|notimestamps|>]\n // - English-only: <|startoftranscript|> [<|notimestamps|>]\n\n // 1. Handle <|startoftranscript|> token\n const init_tokens = [generation_config.decoder_start_token_id];\n\n // 2. Handle <|lang_id|> and <|task> tokens\n let language = generation_config.language;\n const task = generation_config.task;\n if (generation_config.is_multilingual) {\n if (!language) {\n // TODO: Implement language detection\n console.warn('No language specified - defaulting to English (en).');\n language = 'en';\n }\n\n // Add language token\n const language_code = whisper_language_to_code(language);\n const language_token = `<|${language_code}|>`;\n init_tokens.push(generation_config.lang_to_id[language_token])\n\n // Add task token\n // NOTE: Defaults to 'transcribe' if no task is specified\n init_tokens.push(generation_config.task_to_id[task ?? 'transcribe']);\n\n } else if (language || task) {\n throw new Error(\n \"Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.\"\n )\n }\n\n // 3. Handle <|notimestamps|> token\n if (\n !generation_config.return_timestamps\n && generation_config.no_timestamps_token_id\n && init_tokens.at(-1) !== generation_config.no_timestamps_token_id\n ) {\n init_tokens.push(generation_config.no_timestamps_token_id);\n } else if (\n generation_config.return_timestamps\n &&\n init_tokens.at(-1) === generation_config.no_timestamps_token_id\n ) {\n console.warn(\"<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`.\");\n init_tokens.pop();\n }\n\n // let's make sure we don't pass `null` tokens as prompt tokens\n return init_tokens.filter(token => token != null);\n }\n\n /**\n * Transcribes or translates log-mel input features to a sequence of auto-regressively generated token ids.\n * @param {import('./models/whisper/generation_whisper.js').WhisperGenerationFunctionParameters} options\n * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores.\n */\n async generate({\n inputs = null,\n generation_config = null,\n logits_processor = null,\n stopping_criteria = null,\n\n // Whisper-specific options (passed to kwargs)\n // prompt_ids = null,\n // language = null,\n // task = null,\n\n ...kwargs\n }) {\n generation_config = this._prepare_generation_config(generation_config, kwargs);\n\n const init_tokens = kwargs.decoder_input_ids ?? this._retrieve_init_tokens(generation_config);\n\n if (generation_config.return_timestamps) {\n logits_processor ??= new LogitsProcessorList();\n logits_processor.push(\n new WhisperTimeStampLogitsProcessor(generation_config, init_tokens)\n );\n }\n\n if (generation_config.begin_suppress_tokens) {\n logits_processor ??= new LogitsProcessorList();\n logits_processor.push(\n new SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, init_tokens.length)\n );\n }\n\n if (generation_config.return_token_timestamps) {\n if (!generation_config.alignment_heads) {\n throw new Error(\n \"Model generation config has no `alignment_heads`, token-level timestamps not available. \" +\n \"See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.\"\n )\n }\n\n if (generation_config.task === 'translate') {\n console.warn(\"Token-level timestamps may not be reliable for task 'translate'.\")\n }\n\n generation_config.output_attentions = true;\n generation_config.return_dict_in_generate = true;\n }\n\n const outputs = await super.generate({\n inputs,\n generation_config,\n logits_processor,\n decoder_input_ids: init_tokens,\n ...kwargs\n });\n\n if (generation_config.return_token_timestamps) {\n outputs[\"token_timestamps\"] = this._extract_token_timestamps(\n outputs,\n generation_config.alignment_heads,\n generation_config.num_frames,\n );\n }\n\n return outputs;\n }\n\n /**\n * Calculates token-level timestamps using the encoder-decoder cross-attentions and\n * dynamic time-warping (DTW) to map each output token to a position in the input audio.\n * If `num_frames` is specified, the encoder-decoder cross-attentions will be cropped before applying DTW.\n * @param {Object} generate_outputs Outputs generated by the model\n * @param {Tensor[][]} generate_outputs.cross_attentions The cross attentions output by the model\n * @param {Tensor} generate_outputs.sequences The sequences output by the model\n * @param {number[][]} alignment_heads Alignment heads of the model\n * @param {number} [num_frames=null] Number of frames in the input audio.\n * @param {number} [time_precision=0.02] Precision of the timestamps in seconds\n * @returns {Tensor} tensor containing the timestamps in seconds for each predicted token\n */\n _extract_token_timestamps(generate_outputs, alignment_heads, num_frames = null, time_precision = 0.02) {\n if (!generate_outputs.cross_attentions) {\n throw new Error(\n \"Model outputs must contain cross attentions to extract timestamps. \" +\n \"This is most likely because the model was not exported with `output_attentions=True`.\"\n )\n }\n if (num_frames == null) {\n console.warn(\n \"`num_frames` has not been set, meaning the entire audio will be analyzed. \" +\n \"This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).\"\n );\n }\n\n let median_filter_width = this.config.median_filter_width;\n if (median_filter_width === undefined) {\n console.warn(\"Model config has no `median_filter_width`, using default value of 7.\")\n median_filter_width = 7;\n }\n\n // TODO: Improve batch processing\n const batch = generate_outputs.cross_attentions;\n // Create a list with `decoder_layers` elements, each a tensor of shape\n // (batch size, attention_heads, output length, input length).\n const cross_attentions = Array.from({ length: this.config.decoder_layers },\n // Concatenate the cross attentions for each layer across sequence length dimension.\n (_, i) => cat(batch.map(x => x[i]), 2)\n );\n\n const weights = stack(alignment_heads.map(([l, h]) => {\n if (l >= cross_attentions.length) {\n throw new Error(`Layer index ${l} is out of bounds for cross attentions (length ${cross_attentions.length}).`)\n }\n return num_frames\n ? cross_attentions[l].slice(null, h, null, [0, num_frames])\n : cross_attentions[l].slice(null, h);\n })).transpose(1, 0, 2, 3);\n\n const [std, calculatedMean] = std_mean(weights, -2, 0, true);\n\n // Normalize and smoothen the weights.\n const smoothedWeights = weights.clone(); // [1, 8, seqLength, 1500]\n\n for (let a = 0; a < smoothedWeights.dims[0]; ++a) {\n const aTensor = smoothedWeights[a]; // [8, seqLength, 1500]\n\n for (let b = 0; b < aTensor.dims[0]; ++b) {\n const bTensor = aTensor[b]; // [seqLength, 1500]\n\n const stdTensorData = std[a][b][0].data; // [1500]\n const meanTensorData = calculatedMean[a][b][0].data; // [1500]\n\n for (let c = 0; c < bTensor.dims[0]; ++c) {\n\n let cTensorData = bTensor[c].data; // [1500]\n for (let d = 0; d < cTensorData.length; ++d) {\n cTensorData[d] = (cTensorData[d] - meanTensorData[d]) / stdTensorData[d]\n }\n\n // Apply median filter.\n cTensorData.set(medianFilter(cTensorData, median_filter_width))\n }\n }\n }\n\n // Average the different cross-attention heads.\n const batchedMatrices = [mean(smoothedWeights, 1)];\n\n const timestampsShape = generate_outputs.sequences.dims;\n\n const timestamps = new Tensor(\n 'float32',\n new Float32Array(timestampsShape[0] * timestampsShape[1]),\n timestampsShape\n );\n\n // Perform dynamic time warping on each element of the batch.\n for (let batch_idx = 0; batch_idx < timestampsShape[0]; ++batch_idx) {\n // NOTE: Since we run only one batch at a time, we can squeeze to get the same dimensions\n // as the python implementation\n const matrix = batchedMatrices[batch_idx].neg().squeeze_(0);\n const [text_indices, time_indices] = dynamic_time_warping(matrix.tolist());\n\n const diffs = Array.from({ length: text_indices.length - 1 }, (v, i) => text_indices[i + 1] - text_indices[i]);\n const jumps = mergeArrays([1], diffs).map(x => !!x); // convert to boolean\n\n const jump_times = [];\n for (let i = 0; i < jumps.length; ++i) {\n if (jumps[i]) {\n // NOTE: No point in rounding here, since we set to Float32Array later\n jump_times.push(time_indices[i] * time_precision);\n }\n }\n timestamps[batch_idx].data.set(jump_times, 1)\n }\n\n return timestamps;\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n/**\n * Vision Encoder-Decoder model based on OpenAI's GPT architecture for image captioning and other vision tasks\n */\nexport class VisionEncoderDecoderModel extends PreTrainedModel {\n main_input_name = 'pixel_values';\n forward_params = [\n 'pixel_values',\n 'input_ids',\n 'encoder_hidden_states',\n 'past_key_values',\n ];\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// LLaVa Models\nexport class LlavaPreTrainedModel extends PreTrainedModel {\n forward_params = [\n 'input_ids',\n 'pixel_values',\n 'attention_mask',\n 'position_ids',\n 'past_key_values',\n ];\n}\n\n/**\n * The LLAVA model which consists of a vision backbone and a language model.\n */\nexport class LlavaForConditionalGeneration extends LlavaPreTrainedModel {\n\n _merge_input_ids_with_image_features({\n inputs_embeds,\n image_features,\n input_ids,\n attention_mask,\n }) {\n\n const image_token_index = this.config.image_token_index;\n\n const idsList = input_ids.tolist();\n\n // NOTE: we use .findIndex instead of .indexOf to perform weak comparison (==) between BigInt and Number\n const indexOfImage = idsList.map(x => x.findIndex(x => x == image_token_index));\n\n const noImages = indexOfImage.every(x => x === -1);\n const allImages = indexOfImage.every(x => x !== -1);\n if (!noImages && !allImages) {\n // Check for padding reasons\n throw new Error('Every input should contain either 0 or 1 image token.');\n }\n\n if (noImages) {\n return {\n inputs_embeds,\n attention_mask,\n }\n }\n\n const stacked = [];\n const stacked_attention_mask = [];\n for (let i = 0; i < indexOfImage.length; ++i) {\n const index = indexOfImage[i];\n\n const e = inputs_embeds[i];\n const im = image_features[i];\n const am = attention_mask[i];\n stacked.push(\n cat([\n e.slice([0, index]),\n im,\n e.slice([index + 1, e.dims[0]]),\n ], 0)\n );\n\n stacked_attention_mask.push(\n cat([\n am.slice([0, index]),\n ones([im.dims[0]]),\n am.slice([index + 1, am.dims[0]])\n ], 0)\n )\n }\n\n return {\n inputs_embeds: stack(stacked, 0),\n attention_mask: stack(stacked_attention_mask, 0),\n }\n }\n}\n//////////////////////////////////////////////////\n\nexport class Moondream1ForConditionalGeneration extends LlavaForConditionalGeneration { } // NOTE: extends LlavaForConditionalGeneration\n\nexport class Florence2PreTrainedModel extends PreTrainedModel {\n forward_params = [\n // Encoder inputs\n 'input_ids',\n 'inputs_embeds',\n 'attention_mask',\n 'pixel_values',\n\n // Decoder inputs\n 'encoder_outputs',\n 'decoder_input_ids',\n 'decoder_inputs_embeds',\n 'decoder_attention_mask',\n 'past_key_values',\n ];\n main_input_name = 'inputs_embeds';\n}\n\nexport class Florence2ForConditionalGeneration extends Florence2PreTrainedModel {\n\n _merge_input_ids_with_image_features({\n inputs_embeds,\n image_features,\n input_ids,\n attention_mask,\n }) {\n return {\n inputs_embeds: cat([\n image_features, // image embeds\n inputs_embeds, // task prefix embeds\n ], 1),\n attention_mask: cat([\n ones(image_features.dims.slice(0, 2)), // image attention mask\n attention_mask, // task prefix attention mask\n ], 1),\n }\n }\n\n async _prepare_inputs_embeds({ input_ids, pixel_values, inputs_embeds, attention_mask }) {\n if (!input_ids && !pixel_values) {\n throw new Error('Either `input_ids` or `pixel_values` should be provided.');\n }\n\n // 1. Possibly, extract the input embeddings\n let text_features, image_features;\n if (input_ids) {\n text_features = await this.encode_text({ input_ids });\n }\n if (pixel_values) {\n image_features = await this.encode_image({ pixel_values });\n }\n\n // 2. Possibly, merge text and images\n if (text_features && image_features) {\n ({ inputs_embeds, attention_mask } = this._merge_input_ids_with_image_features({\n inputs_embeds: text_features,\n image_features,\n input_ids,\n attention_mask,\n }));\n } else {\n inputs_embeds = text_features || image_features;\n }\n\n return { inputs_embeds, attention_mask };\n }\n\n async forward({\n input_ids,\n pixel_values,\n attention_mask,\n decoder_input_ids,\n decoder_attention_mask,\n encoder_outputs,\n past_key_values,\n\n inputs_embeds,\n decoder_inputs_embeds,\n }) {\n if (!inputs_embeds) {\n ({ inputs_embeds, attention_mask } = await this._prepare_inputs_embeds({ input_ids, pixel_values, inputs_embeds, attention_mask }));\n }\n\n if (!encoder_outputs) {\n // Must compute encoder outputs\n let { last_hidden_state } = await encoderForward(this, { inputs_embeds, attention_mask });\n encoder_outputs = last_hidden_state;\n }\n\n if (!decoder_inputs_embeds) {\n if (!decoder_input_ids) {\n throw new Error('Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.');\n }\n decoder_inputs_embeds = await this.encode_text({ input_ids: decoder_input_ids });\n }\n\n const decoderFeeds = {\n inputs_embeds: decoder_inputs_embeds,\n attention_mask: decoder_attention_mask,\n encoder_attention_mask: attention_mask,\n encoder_hidden_states: encoder_outputs,\n past_key_values,\n };\n const decoder_outputs = await decoderForward(this, decoderFeeds, true);\n return decoder_outputs;\n }\n}\nexport class CLIPPreTrainedModel extends PreTrainedModel { }\n\n/**\n * CLIP Text and Vision Model with a projection layers on top\n * \n * **Example:** Perform zero-shot image classification with a `CLIPModel`.\n * \n * ```javascript\n * import { AutoTokenizer, AutoProcessor, CLIPModel, RawImage } from '@huggingface/transformers';\n * \n * // Load tokenizer, processor, and model\n * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/clip-vit-base-patch16');\n * let processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16');\n * let model = await CLIPModel.from_pretrained('Xenova/clip-vit-base-patch16');\n * \n * // Run tokenization\n * let texts = ['a photo of a car', 'a photo of a football match']\n * let text_inputs = tokenizer(texts, { padding: true, truncation: true });\n * \n * // Read image and run processor\n * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * let image_inputs = await processor(image);\n * \n * // Run model with both text and pixel inputs\n * let output = await model({ ...text_inputs, ...image_inputs });\n * // {\n * // logits_per_image: Tensor {\n * // dims: [ 1, 2 ],\n * // data: Float32Array(2) [ 18.579734802246094, 24.31830596923828 ],\n * // },\n * // logits_per_text: Tensor {\n * // dims: [ 2, 1 ],\n * // data: Float32Array(2) [ 18.579734802246094, 24.31830596923828 ],\n * // },\n * // text_embeds: Tensor {\n * // dims: [ 2, 512 ],\n * // data: Float32Array(1024) [ ... ],\n * // },\n * // image_embeds: Tensor {\n * // dims: [ 1, 512 ],\n * // data: Float32Array(512) [ ... ],\n * // }\n * // }\n * ```\n */\nexport class CLIPModel extends CLIPPreTrainedModel { }\n\n/**\n * The text model from CLIP without any head or projection on top.\n */\nexport class CLIPTextModel extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'text_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * CLIP Text Model with a projection layer on top (a linear layer on top of the pooled output)\n * \n * **Example:** Compute text embeddings with `CLIPTextModelWithProjection`.\n * \n * ```javascript\n * import { AutoTokenizer, CLIPTextModelWithProjection } from '@huggingface/transformers';\n * \n * // Load tokenizer and text model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clip-vit-base-patch16');\n * const text_model = await CLIPTextModelWithProjection.from_pretrained('Xenova/clip-vit-base-patch16');\n * \n * // Run tokenization\n * let texts = ['a photo of a car', 'a photo of a football match'];\n * let text_inputs = tokenizer(texts, { padding: true, truncation: true });\n * \n * // Compute embeddings\n * const { text_embeds } = await text_model(text_inputs);\n * // Tensor {\n * // dims: [ 2, 512 ],\n * // type: 'float32',\n * // data: Float32Array(1024) [ ... ],\n * // size: 1024\n * // }\n * ```\n */\nexport class CLIPTextModelWithProjection extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'text_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * The vision model from CLIP without any head or projection on top.\n */\nexport class CLIPVisionModel extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'vision_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * CLIP Vision Model with a projection layer on top (a linear layer on top of the pooled output)\n * \n * **Example:** Compute vision embeddings with `CLIPVisionModelWithProjection`.\n * \n * ```javascript\n * import { AutoProcessor, CLIPVisionModelWithProjection, RawImage} from '@huggingface/transformers';\n * \n * // Load processor and vision model\n * const processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16');\n * const vision_model = await CLIPVisionModelWithProjection.from_pretrained('Xenova/clip-vit-base-patch16');\n * \n * // Read image and run processor\n * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * let image_inputs = await processor(image);\n * \n * // Compute embeddings\n * const { image_embeds } = await vision_model(image_inputs);\n * // Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [ ... ],\n * // size: 512\n * // }\n * ```\n */\nexport class CLIPVisionModelWithProjection extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'vision_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// SigLIP models\nexport class SiglipPreTrainedModel extends PreTrainedModel { }\n\n/**\n * SigLIP Text and Vision Model with a projection layers on top\n * \n * **Example:** Perform zero-shot image classification with a `SiglipModel`.\n * \n * ```javascript\n * import { AutoTokenizer, AutoProcessor, SiglipModel, RawImage } from '@huggingface/transformers';\n * \n * // Load tokenizer, processor, and model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/siglip-base-patch16-224');\n * const processor = await AutoProcessor.from_pretrained('Xenova/siglip-base-patch16-224');\n * const model = await SiglipModel.from_pretrained('Xenova/siglip-base-patch16-224');\n * \n * // Run tokenization\n * const texts = ['a photo of 2 cats', 'a photo of 2 dogs'];\n * const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true });\n * \n * // Read image and run processor\n * const image = await RawImage.read('http://images.cocodataset.org/val2017/000000039769.jpg');\n * const image_inputs = await processor(image);\n * \n * // Run model with both text and pixel inputs\n * const output = await model({ ...text_inputs, ...image_inputs });\n * // {\n * // logits_per_image: Tensor {\n * // dims: [ 1, 2 ],\n * // data: Float32Array(2) [ -1.6019744873046875, -10.720091819763184 ],\n * // },\n * // logits_per_text: Tensor {\n * // dims: [ 2, 1 ],\n * // data: Float32Array(2) [ -1.6019744873046875, -10.720091819763184 ],\n * // },\n * // text_embeds: Tensor {\n * // dims: [ 2, 768 ],\n * // data: Float32Array(1536) [ ... ],\n * // },\n * // image_embeds: Tensor {\n * // dims: [ 1, 768 ],\n * // data: Float32Array(768) [ ... ],\n * // }\n * // }\n * ```\n */\nexport class SiglipModel extends SiglipPreTrainedModel { }\n\n/**\n * The text model from SigLIP without any head or projection on top.\n * \n * **Example:** Compute text embeddings with `SiglipTextModel`.\n * \n * ```javascript\n * import { AutoTokenizer, SiglipTextModel } from '@huggingface/transformers';\n * \n * // Load tokenizer and text model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/siglip-base-patch16-224');\n * const text_model = await SiglipTextModel.from_pretrained('Xenova/siglip-base-patch16-224');\n * \n * // Run tokenization\n * const texts = ['a photo of 2 cats', 'a photo of 2 dogs'];\n * const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true });\n * \n * // Compute embeddings\n * const { pooler_output } = await text_model(text_inputs);\n * // Tensor {\n * // dims: [ 2, 768 ],\n * // type: 'float32',\n * // data: Float32Array(1536) [ ... ],\n * // size: 1536\n * // }\n * ```\n */\nexport class SiglipTextModel extends SiglipPreTrainedModel {\n\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'text_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * The vision model from SigLIP without any head or projection on top.\n * \n * **Example:** Compute vision embeddings with `SiglipVisionModel`.\n * \n * ```javascript\n * import { AutoProcessor, SiglipVisionModel, RawImage} from '@huggingface/transformers';\n * \n * // Load processor and vision model\n * const processor = await AutoProcessor.from_pretrained('Xenova/siglip-base-patch16-224');\n * const vision_model = await SiglipVisionModel.from_pretrained('Xenova/siglip-base-patch16-224');\n * \n * // Read image and run processor\n * const image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * const image_inputs = await processor(image);\n * \n * // Compute embeddings\n * const { pooler_output } = await vision_model(image_inputs);\n * // Tensor {\n * // dims: [ 1, 768 ],\n * // type: 'float32',\n * // data: Float32Array(768) [ ... ],\n * // size: 768\n * // }\n * ```\n */\nexport class SiglipVisionModel extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'vision_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n//////////////////////////////////////////////////\n// ChineseCLIP models\nexport class ChineseCLIPPreTrainedModel extends PreTrainedModel { }\n\nexport class ChineseCLIPModel extends ChineseCLIPPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// CLIPSeg models\nexport class CLIPSegPreTrainedModel extends PreTrainedModel { }\n\nexport class CLIPSegModel extends CLIPSegPreTrainedModel { }\n\n/**\n * CLIPSeg model with a Transformer-based decoder on top for zero-shot and one-shot image segmentation.\n * \n * **Example:** Perform zero-shot image segmentation with a `CLIPSegForImageSegmentation` model.\n * \n * ```javascript\n * import { AutoTokenizer, AutoProcessor, CLIPSegForImageSegmentation, RawImage } from '@huggingface/transformers';\n * \n * // Load tokenizer, processor, and model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clipseg-rd64-refined');\n * const processor = await AutoProcessor.from_pretrained('Xenova/clipseg-rd64-refined');\n * const model = await CLIPSegForImageSegmentation.from_pretrained('Xenova/clipseg-rd64-refined');\n * \n * // Run tokenization\n * const texts = ['a glass', 'something to fill', 'wood', 'a jar'];\n * const text_inputs = tokenizer(texts, { padding: true, truncation: true });\n * \n * // Read image and run processor\n * const image = await RawImage.read('https://github.com/timojl/clipseg/blob/master/example_image.jpg?raw=true');\n * const image_inputs = await processor(image);\n * \n * // Run model with both text and pixel inputs\n * const { logits } = await model({ ...text_inputs, ...image_inputs });\n * // logits: Tensor {\n * // dims: [4, 352, 352],\n * // type: 'float32',\n * // data: Float32Array(495616) [ ... ],\n * // size: 495616\n * // }\n * ```\n * \n * You can visualize the predictions as follows:\n * ```javascript\n * const preds = logits\n * .unsqueeze_(1)\n * .sigmoid_()\n * .mul_(255)\n * .round_()\n * .to('uint8');\n * \n * for (let i = 0; i < preds.dims[0]; ++i) {\n * const img = RawImage.fromTensor(preds[i]);\n * img.save(`prediction_${i}.png`);\n * }\n * ```\n */\nexport class CLIPSegForImageSegmentation extends CLIPSegPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// GPT2 models\nexport class GPT2PreTrainedModel extends PreTrainedModel { }\n\nexport class GPT2Model extends GPT2PreTrainedModel { }\n\n/**\n * GPT-2 language model head on top of the GPT-2 base model. This model is suitable for text generation tasks.\n */\nexport class GPT2LMHeadModel extends GPT2PreTrainedModel { }\n// export class GPT2ForSequenceClassification extends GPT2PreTrainedModel {\n// TODO\n// }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// JAIS models\nexport class JAISPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare JAIS Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class JAISModel extends JAISPreTrainedModel { }\n\n/**\n * The JAIS Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class JAISLMHeadModel extends JAISPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// GPTNeo models\nexport class GPTNeoPreTrainedModel extends PreTrainedModel { }\nexport class GPTNeoModel extends GPTNeoPreTrainedModel { }\n\nexport class GPTNeoForCausalLM extends GPTNeoPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// GPTNeoX models\nexport class GPTNeoXPreTrainedModel extends PreTrainedModel { }\nexport class GPTNeoXModel extends GPTNeoXPreTrainedModel { }\n\nexport class GPTNeoXForCausalLM extends GPTNeoXPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// GPT-J models\nexport class GPTJPreTrainedModel extends PreTrainedModel { }\n\nexport class GPTJModel extends GPTJPreTrainedModel { }\n\nexport class GPTJForCausalLM extends GPTJPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// GPTBigCode models\nexport class GPTBigCodePreTrainedModel extends PreTrainedModel { }\n\nexport class GPTBigCodeModel extends GPTBigCodePreTrainedModel { }\n\nexport class GPTBigCodeForCausalLM extends GPTBigCodePreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// CodeGen models\nexport class CodeGenPreTrainedModel extends PreTrainedModel { }\n/**\n * CodeGenModel is a class representing a code generation model without a language model head.\n */\nexport class CodeGenModel extends CodeGenPreTrainedModel { }\n\n/**\n * CodeGenForCausalLM is a class that represents a code generation model based on the GPT-2 architecture. It extends the `CodeGenPreTrainedModel` class.\n */\nexport class CodeGenForCausalLM extends CodeGenPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// LLama models\n\n/**\n * The bare LLama Model outputting raw hidden-states without any specific head on top.\n */\nexport class LlamaPreTrainedModel extends PreTrainedModel { }\n/**\n * The bare LLaMA Model outputting raw hidden-states without any specific head on top.\n */\nexport class LlamaModel extends LlamaPreTrainedModel { }\n\nexport class LlamaForCausalLM extends LlamaPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Granite models\nexport class GranitePreTrainedModel extends PreTrainedModel { }\nexport class GraniteModel extends GranitePreTrainedModel { }\nexport class GraniteForCausalLM extends GranitePreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Cohere models\n\n/**\n * The bare Cohere Model outputting raw hidden-states without any specific head on top.\n */\nexport class CoherePreTrainedModel extends PreTrainedModel { }\nexport class CohereModel extends CoherePreTrainedModel { }\n\nexport class CohereForCausalLM extends CoherePreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Gemma models\n\n/**\n * The bare Gemma Model outputting raw hidden-states without any specific head on top.\n */\nexport class GemmaPreTrainedModel extends PreTrainedModel { }\n/**\n * The bare Gemma Model outputting raw hidden-states without any specific head on top.\n */\nexport class GemmaModel extends GemmaPreTrainedModel { }\n\nexport class GemmaForCausalLM extends GemmaPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Gemma2 models\n\n/**\n * The bare Gemma2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Gemma2PreTrainedModel extends PreTrainedModel { }\n/**\n * The bare Gemma2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Gemma2Model extends Gemma2PreTrainedModel { }\n\nexport class Gemma2ForCausalLM extends Gemma2PreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class OpenELMPreTrainedModel extends PreTrainedModel { }\nexport class OpenELMModel extends OpenELMPreTrainedModel { }\n\nexport class OpenELMForCausalLM extends OpenELMPreTrainedModel { }\n\n\n//////////////////////////////////////////////////\n// Qwen2 models\n\n/**\n * The bare Qwen2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Qwen2PreTrainedModel extends PreTrainedModel { }\n/**\n * The bare Qwen2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Qwen2Model extends Qwen2PreTrainedModel { }\n\nexport class Qwen2ForCausalLM extends Qwen2PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Phi models\nexport class PhiPreTrainedModel extends PreTrainedModel { }\n/**\n * The bare Phi Model outputting raw hidden-states without any specific head on top.\n */\nexport class PhiModel extends PhiPreTrainedModel { }\n\nexport class PhiForCausalLM extends PhiPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Phi3 models\nexport class Phi3PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Phi3 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Phi3Model extends Phi3PreTrainedModel { }\n\nexport class Phi3ForCausalLM extends Phi3PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Bloom models\n/**\n * The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class BloomPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Bloom Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class BloomModel extends BloomPreTrainedModel { }\n\n/**\n * The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class BloomForCausalLM extends BloomPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MPT models\nexport class MptPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Mpt Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class MptModel extends MptPreTrainedModel { }\n\n/**\n * The MPT Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class MptForCausalLM extends MptPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// OPT models\nexport class OPTPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare OPT Model outputting raw hidden-states without any specific head on top.\n */\nexport class OPTModel extends OPTPreTrainedModel { }\n\n/**\n * The OPT Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class OPTForCausalLM extends OPTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class ViTPreTrainedModel extends PreTrainedModel { }\nexport class ViTModel extends ViTPreTrainedModel { }\nexport class ViTForImageClassification extends ViTPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class PvtPreTrainedModel extends PreTrainedModel { }\nexport class PvtModel extends PvtPreTrainedModel { }\nexport class PvtForImageClassification extends PvtPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class ViTMAEPreTrainedModel extends PreTrainedModel { }\nexport class ViTMAEModel extends ViTMAEPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class ViTMSNPreTrainedModel extends PreTrainedModel { }\nexport class ViTMSNModel extends ViTMSNPreTrainedModel { }\nexport class ViTMSNForImageClassification extends ViTMSNPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class GroupViTPreTrainedModel extends PreTrainedModel { }\nexport class GroupViTModel extends GroupViTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class FastViTPreTrainedModel extends PreTrainedModel { }\nexport class FastViTModel extends FastViTPreTrainedModel { }\nexport class FastViTForImageClassification extends FastViTPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class VitMattePreTrainedModel extends PreTrainedModel { }\n\n/**\n * ViTMatte framework leveraging any vision backbone e.g. for ADE20k, CityScapes.\n * \n * **Example:** Perform image matting with a `VitMatteForImageMatting` model.\n * ```javascript\n * import { AutoProcessor, VitMatteForImageMatting, RawImage } from '@huggingface/transformers';\n * \n * // Load processor and model\n * const processor = await AutoProcessor.from_pretrained('Xenova/vitmatte-small-distinctions-646');\n * const model = await VitMatteForImageMatting.from_pretrained('Xenova/vitmatte-small-distinctions-646');\n * \n * // Load image and trimap\n * const image = await RawImage.fromURL('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/vitmatte_image.png');\n * const trimap = await RawImage.fromURL('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/vitmatte_trimap.png');\n * \n * // Prepare image + trimap for the model\n * const inputs = await processor(image, trimap);\n * \n * // Predict alpha matte\n * const { alphas } = await model(inputs);\n * // Tensor {\n * // dims: [ 1, 1, 640, 960 ],\n * // type: 'float32',\n * // size: 614400,\n * // data: Float32Array(614400) [ 0.9894027709960938, 0.9970508813858032, ... ]\n * // }\n * ```\n * \n * You can visualize the alpha matte as follows:\n * ```javascript\n * import { Tensor, cat } from '@huggingface/transformers';\n * \n * // Visualize predicted alpha matte\n * const imageTensor = image.toTensor();\n * \n * // Convert float (0-1) alpha matte to uint8 (0-255)\n * const alphaChannel = alphas\n * .squeeze(0)\n * .mul_(255)\n * .clamp_(0, 255)\n * .round_()\n * .to('uint8');\n * \n * // Concatenate original image with predicted alpha\n * const imageData = cat([imageTensor, alphaChannel], 0);\n * \n * // Save output image\n * const outputImage = RawImage.fromTensor(imageData);\n * outputImage.save('output.png');\n * ```\n */\nexport class VitMatteForImageMatting extends VitMattePreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new ImageMattingOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class MobileViTPreTrainedModel extends PreTrainedModel { }\nexport class MobileViTModel extends MobileViTPreTrainedModel { }\nexport class MobileViTForImageClassification extends MobileViTPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n// TODO: MobileViTForSemanticSegmentation\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class MobileViTV2PreTrainedModel extends PreTrainedModel { }\nexport class MobileViTV2Model extends MobileViTV2PreTrainedModel { }\nexport class MobileViTV2ForImageClassification extends MobileViTV2PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n// TODO: MobileViTV2ForSemanticSegmentation\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class OwlViTPreTrainedModel extends PreTrainedModel { }\nexport class OwlViTModel extends OwlViTPreTrainedModel { }\nexport class OwlViTForObjectDetection extends OwlViTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class Owlv2PreTrainedModel extends PreTrainedModel { }\nexport class Owlv2Model extends Owlv2PreTrainedModel { }\nexport class Owlv2ForObjectDetection extends Owlv2PreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Beit Models\nexport class BeitPreTrainedModel extends PreTrainedModel { }\nexport class BeitModel extends BeitPreTrainedModel { }\nexport class BeitForImageClassification extends BeitPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class DetrPreTrainedModel extends PreTrainedModel { }\nexport class DetrModel extends DetrPreTrainedModel { }\nexport class DetrForObjectDetection extends DetrPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new DetrObjectDetectionOutput(await super._call(model_inputs));\n }\n}\n\nexport class DetrForSegmentation extends DetrPreTrainedModel {\n /**\n * Runs the model with the provided inputs\n * @param {Object} model_inputs Model inputs\n * @returns {Promise} Object containing segmentation outputs\n */\n async _call(model_inputs) {\n return new DetrSegmentationOutput(await super._call(model_inputs));\n }\n}\n\nexport class DetrObjectDetectionOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification logits (including no-object) for all queries.\n * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).\n * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).\n */\n constructor({ logits, pred_boxes }) {\n super();\n this.logits = logits;\n this.pred_boxes = pred_boxes;\n }\n}\n\nexport class DetrSegmentationOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits The output logits of the model.\n * @param {Tensor} output.pred_boxes Predicted boxes.\n * @param {Tensor} output.pred_masks Predicted masks.\n */\n constructor({ logits, pred_boxes, pred_masks }) {\n super();\n this.logits = logits;\n this.pred_boxes = pred_boxes;\n this.pred_masks = pred_masks;\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class RTDetrPreTrainedModel extends PreTrainedModel { }\nexport class RTDetrModel extends RTDetrPreTrainedModel { }\nexport class RTDetrForObjectDetection extends RTDetrPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new RTDetrObjectDetectionOutput(await super._call(model_inputs));\n }\n}\n\nexport class RTDetrObjectDetectionOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification logits (including no-object) for all queries.\n * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).\n * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).\n */\n constructor({ logits, pred_boxes }) {\n super();\n this.logits = logits;\n this.pred_boxes = pred_boxes;\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class TableTransformerPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Table Transformer Model (consisting of a backbone and encoder-decoder Transformer)\n * outputting raw hidden-states without any specific head on top.\n */\nexport class TableTransformerModel extends TableTransformerPreTrainedModel { }\n\n/**\n * Table Transformer Model (consisting of a backbone and encoder-decoder Transformer)\n * with object detection heads on top, for tasks such as COCO detection.\n */\nexport class TableTransformerForObjectDetection extends TableTransformerPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new TableTransformerObjectDetectionOutput(await super._call(model_inputs));\n }\n}\nexport class TableTransformerObjectDetectionOutput extends DetrObjectDetectionOutput { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class DeiTPreTrainedModel extends PreTrainedModel { }\nexport class DeiTModel extends DeiTPreTrainedModel { }\nexport class DeiTForImageClassification extends DeiTPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class HieraPreTrainedModel extends PreTrainedModel { }\nexport class HieraModel extends HieraPreTrainedModel { }\nexport class HieraForImageClassification extends HieraPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class ResNetPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ResNet model outputting raw features without any specific head on top.\n */\nexport class ResNetModel extends ResNetPreTrainedModel { }\n\n/**\n * ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.\n */\nexport class ResNetForImageClassification extends ResNetPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class SwinPreTrainedModel extends PreTrainedModel { }\nexport class SwinModel extends SwinPreTrainedModel { }\nexport class SwinForImageClassification extends SwinPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class Swin2SRPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Swin2SR Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class Swin2SRModel extends Swin2SRPreTrainedModel { }\n\n/**\n * Swin2SR Model transformer with an upsampler head on top for image super resolution and restoration.\n * \n * **Example:** Super-resolution w/ `Xenova/swin2SR-classical-sr-x2-64`.\n * \n * ```javascript\n * import { AutoProcessor, Swin2SRForImageSuperResolution, RawImage } from '@huggingface/transformers';\n * \n * // Load processor and model\n * const model_id = 'Xenova/swin2SR-classical-sr-x2-64';\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * const model = await Swin2SRForImageSuperResolution.from_pretrained(model_id);\n * \n * // Prepare model inputs\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg';\n * const image = await RawImage.fromURL(url);\n * const inputs = await processor(image);\n * \n * // Run model\n * const outputs = await model(inputs);\n * \n * // Convert Tensor to RawImage\n * const output = outputs.reconstruction.squeeze().clamp_(0, 1).mul_(255).round_().to('uint8');\n * const outputImage = RawImage.fromTensor(output);\n * // RawImage {\n * // data: Uint8Array(786432) [ 41, 31, 24, ... ],\n * // width: 512,\n * // height: 512,\n * // channels: 3\n * // }\n * ```\n */\nexport class Swin2SRForImageSuperResolution extends Swin2SRPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class DPTPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare DPT Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class DPTModel extends DPTPreTrainedModel { }\n\n/**\n * DPT Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2.\n * \n * **Example:** Depth estimation w/ `Xenova/dpt-hybrid-midas`.\n * ```javascript\n * import { DPTForDepthEstimation, AutoProcessor, RawImage, interpolate, max } from '@huggingface/transformers';\n * \n * // Load model and processor\n * const model_id = 'Xenova/dpt-hybrid-midas';\n * const model = await DPTForDepthEstimation.from_pretrained(model_id);\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * \n * // Load image from URL\n * const url = 'http://images.cocodataset.org/val2017/000000039769.jpg';\n * const image = await RawImage.fromURL(url);\n * \n * // Prepare image for the model\n * const inputs = await processor(image);\n * \n * // Run model\n * const { predicted_depth } = await model(inputs);\n * \n * // Interpolate to original size\n * const prediction = interpolate(predicted_depth, image.size.reverse(), 'bilinear', false);\n * \n * // Visualize the prediction\n * const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8');\n * const depth = RawImage.fromTensor(formatted);\n * // RawImage {\n * // data: Uint8Array(307200) [ 85, 85, 84, ... ],\n * // width: 640,\n * // height: 480,\n * // channels: 1\n * // }\n * ```\n */\nexport class DPTForDepthEstimation extends DPTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class DepthAnythingPreTrainedModel extends PreTrainedModel { }\n\n/**\n * Depth Anything Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2.\n */\nexport class DepthAnythingForDepthEstimation extends DepthAnythingPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class SapiensPreTrainedModel extends PreTrainedModel { }\nexport class SapiensForSemanticSegmentation extends SapiensPreTrainedModel { }\nexport class SapiensForDepthEstimation extends SapiensPreTrainedModel { }\nexport class SapiensForNormalEstimation extends SapiensPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class DepthProPreTrainedModel extends PreTrainedModel { }\nexport class DepthProForDepthEstimation extends DepthProPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class MaskFormerPreTrainedModel extends PreTrainedModel { }\nexport class MaskFormerModel extends MaskFormerPreTrainedModel { }\nexport class MaskFormerForInstanceSegmentation extends MaskFormerPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class GLPNPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare GLPN encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top.\n */\nexport class GLPNModel extends GLPNPreTrainedModel { }\n\n/**\n * GLPN Model transformer with a lightweight depth estimation head on top e.g. for KITTI, NYUv2.\n * \n * **Example:** Depth estimation w/ `Xenova/glpn-kitti`.\n * ```javascript\n * import { GLPNForDepthEstimation, AutoProcessor, RawImage, interpolate, max } from '@huggingface/transformers';\n * \n * // Load model and processor\n * const model_id = 'Xenova/glpn-kitti';\n * const model = await GLPNForDepthEstimation.from_pretrained(model_id);\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * \n * // Load image from URL\n * const url = 'http://images.cocodataset.org/val2017/000000039769.jpg';\n * const image = await RawImage.fromURL(url);\n * \n * // Prepare image for the model\n * const inputs = await processor(image);\n * \n * // Run model\n * const { predicted_depth } = await model(inputs);\n * \n * // Interpolate to original size\n * const prediction = interpolate(predicted_depth, image.size.reverse(), 'bilinear', false);\n * \n * // Visualize the prediction\n * const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8');\n * const depth = RawImage.fromTensor(formatted);\n * // RawImage {\n * // data: Uint8Array(307200) [ 207, 169, 154, ... ],\n * // width: 640,\n * // height: 480,\n * // channels: 1\n * // }\n * ```\n */\nexport class GLPNForDepthEstimation extends GLPNPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class DonutSwinPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Donut Swin Model transformer outputting raw hidden-states without any specific head on top.\n * \n * **Example:** Step-by-step Document Parsing.\n * \n * ```javascript\n * import { AutoProcessor, AutoTokenizer, AutoModelForVision2Seq, RawImage } from '@huggingface/transformers';\n * \n * // Choose model to use\n * const model_id = 'Xenova/donut-base-finetuned-cord-v2';\n * \n * // Prepare image inputs\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/receipt.png';\n * const image = await RawImage.read(url);\n * const image_inputs = await processor(image);\n * \n * // Prepare decoder inputs\n * const tokenizer = await AutoTokenizer.from_pretrained(model_id);\n * const task_prompt = '';\n * const decoder_input_ids = tokenizer(task_prompt, {\n * add_special_tokens: false,\n * }).input_ids;\n * \n * // Create the model\n * const model = await AutoModelForVision2Seq.from_pretrained(model_id);\n * \n * // Run inference\n * const output = await model.generate(image_inputs.pixel_values, {\n * decoder_input_ids,\n * max_length: model.config.decoder.max_position_embeddings,\n * });\n * \n * // Decode output\n * const decoded = tokenizer.batch_decode(output)[0];\n * // CINNAMON SUGAR 17,000 1 x 17,000 17,000 17,000 20,000 3,000\n * ```\n * \n * **Example:** Step-by-step Document Visual Question Answering (DocVQA)\n * \n * ```javascript\n * import { AutoProcessor, AutoTokenizer, AutoModelForVision2Seq, RawImage } from '@huggingface/transformers';\n * \n * // Choose model to use\n * const model_id = 'Xenova/donut-base-finetuned-docvqa';\n * \n * // Prepare image inputs\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/invoice.png';\n * const image = await RawImage.read(url);\n * const image_inputs = await processor(image);\n * \n * // Prepare decoder inputs\n * const tokenizer = await AutoTokenizer.from_pretrained(model_id);\n * const question = 'What is the invoice number?';\n * const task_prompt = `${question}`;\n * const decoder_input_ids = tokenizer(task_prompt, {\n * add_special_tokens: false,\n * }).input_ids;\n * \n * // Create the model\n * const model = await AutoModelForVision2Seq.from_pretrained(model_id);\n * \n * // Run inference\n * const output = await model.generate(image_inputs.pixel_values, {\n * decoder_input_ids,\n * max_length: model.config.decoder.max_position_embeddings,\n * });\n * \n * // Decode output\n * const decoded = tokenizer.batch_decode(output)[0];\n * // What is the invoice number? us-001\n * ```\n */\nexport class DonutSwinModel extends DonutSwinPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class ConvNextPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ConvNext model outputting raw features without any specific head on top.\n */\nexport class ConvNextModel extends ConvNextPreTrainedModel { }\n\n/**\n * ConvNext Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.\n */\nexport class ConvNextForImageClassification extends ConvNextPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class ConvNextV2PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ConvNextV2 model outputting raw features without any specific head on top.\n */\nexport class ConvNextV2Model extends ConvNextV2PreTrainedModel { }\n\n/**\n * ConvNextV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.\n */\nexport class ConvNextV2ForImageClassification extends ConvNextV2PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class Dinov2PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare DINOv2 Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class Dinov2Model extends Dinov2PreTrainedModel { }\n\n/**\n * Dinov2 Model transformer with an image classification head on top (a linear layer on top of the final hidden state of the [CLS] token) e.g. for ImageNet.\n */\nexport class Dinov2ForImageClassification extends Dinov2PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class YolosPreTrainedModel extends PreTrainedModel { }\nexport class YolosModel extends YolosPreTrainedModel { }\nexport class YolosForObjectDetection extends YolosPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new YolosObjectDetectionOutput(await super._call(model_inputs));\n }\n}\n\nexport class YolosObjectDetectionOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification logits (including no-object) for all queries.\n * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).\n * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).\n */\n constructor({ logits, pred_boxes }) {\n super();\n this.logits = logits;\n this.pred_boxes = pred_boxes;\n }\n}\n//////////////////////////////////////////////////\n\n\n\n\n//////////////////////////////////////////////////\nexport class SamPreTrainedModel extends PreTrainedModel { }\n\n/**\n * Segment Anything Model (SAM) for generating segmentation masks, given an input image\n * and optional 2D location and bounding boxes.\n * \n * **Example:** Perform mask generation w/ `Xenova/sam-vit-base`.\n * ```javascript\n * import { SamModel, AutoProcessor, RawImage } from '@huggingface/transformers';\n * \n * const model = await SamModel.from_pretrained('Xenova/sam-vit-base');\n * const processor = await AutoProcessor.from_pretrained('Xenova/sam-vit-base');\n * \n * const img_url = 'https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png';\n * const raw_image = await RawImage.read(img_url);\n * const input_points = [[[450, 600]]] // 2D localization of a window\n * \n * const inputs = await processor(raw_image, { input_points });\n * const outputs = await model(inputs);\n * \n * const masks = await processor.post_process_masks(outputs.pred_masks, inputs.original_sizes, inputs.reshaped_input_sizes);\n * // [\n * // Tensor {\n * // dims: [ 1, 3, 1764, 2646 ],\n * // type: 'bool',\n * // data: Uint8Array(14002632) [ ... ],\n * // size: 14002632\n * // }\n * // ]\n * const scores = outputs.iou_scores;\n * // Tensor {\n * // dims: [ 1, 1, 3 ],\n * // type: 'float32',\n * // data: Float32Array(3) [\n * // 0.8892380595207214,\n * // 0.9311248064041138,\n * // 0.983696699142456\n * // ],\n * // size: 3\n * // }\n * ```\n */\nexport class SamModel extends SamPreTrainedModel {\n\n /**\n * Compute image embeddings and positional image embeddings, given the pixel values of an image.\n * @param {Object} model_inputs Object containing the model inputs.\n * @param {Tensor} model_inputs.pixel_values Pixel values obtained using a `SamProcessor`.\n * @returns {Promise<{ image_embeddings: Tensor, image_positional_embeddings: Tensor }>} The image embeddings and positional image embeddings.\n */\n async get_image_embeddings({ pixel_values }) {\n // in:\n // - pixel_values: tensor.float32[batch_size,3,1024,1024]\n // \n // out:\n // - image_embeddings: tensor.float32[batch_size,256,64,64]\n // - image_positional_embeddings: tensor.float32[batch_size,256,64,64]\n return await encoderForward(this, { pixel_values })\n }\n\n /**\n * @typedef {Object} SamModelInputs Object containing the model inputs.\n * @property {Tensor} pixel_values Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`.\n * These can be obtained using a `SamProcessor`.\n * @property {Tensor} [input_points] Input 2D spatial points with shape `(batch_size, num_points, 2)`.\n * This is used by the prompt encoder to encode the prompt.\n * @property {Tensor} [input_labels] Input labels for the points, as a Tensor of shape `(batch_size, point_batch_size, num_points)`.\n * This is used by the prompt encoder to encode the prompt. There are 4 types of labels:\n * - `1`: the point is a point that contains the object of interest\n * - `0`: the point is a point that does not contain the object of interest\n * - `-1`: the point corresponds to the background\n * - `-10`: the point is a padding point, thus should be ignored by the prompt encoder\n * @property {Tensor} [input_boxes] Input bounding boxes with shape `(batch_size, num_boxes, 4)`.\n * @property {Tensor} [image_embeddings] Image embeddings used by the mask decoder.\n * @property {Tensor} [image_positional_embeddings] Image positional embeddings used by the mask decoder.\n */\n\n /**\n * @param {SamModelInputs} model_inputs Object containing the model inputs.\n * @returns {Promise} The output of the model.\n */\n async forward(model_inputs) {\n if (!model_inputs.image_embeddings || !model_inputs.image_positional_embeddings) {\n // Compute the image embeddings if they are missing\n model_inputs = {\n ...model_inputs,\n ...(await this.get_image_embeddings(model_inputs))\n }\n }\n\n if (!model_inputs.input_labels && model_inputs.input_points) {\n // Set default input labels if they are missing\n const shape = model_inputs.input_points.dims.slice(0, -1);\n const numElements = shape.reduce((a, b) => a * b, 1);\n model_inputs.input_labels = new Tensor(\n 'int64',\n new BigInt64Array(numElements).fill(1n),\n shape\n );\n }\n\n const decoder_inputs = {\n image_embeddings: model_inputs.image_embeddings,\n image_positional_embeddings: model_inputs.image_positional_embeddings,\n };\n if (model_inputs.input_points) {\n decoder_inputs.input_points = model_inputs.input_points;\n }\n if (model_inputs.input_labels) {\n decoder_inputs.input_labels = model_inputs.input_labels;\n }\n if (model_inputs.input_boxes) {\n decoder_inputs.input_boxes = model_inputs.input_boxes;\n }\n\n // Returns:\n // - iou_scores: tensor.float32[batch_size,point_batch_size,3]\n // - pred_masks: tensor.float32[batch_size,point_batch_size,3,256,256]\n return await sessionRun(this.sessions['prompt_encoder_mask_decoder'], decoder_inputs);\n }\n\n /**\n * Runs the model with the provided inputs\n * @param {Object} model_inputs Model inputs\n * @returns {Promise} Object containing segmentation outputs\n */\n async _call(model_inputs) {\n return new SamImageSegmentationOutput(await super._call(model_inputs));\n }\n}\n\n\n/**\n * Base class for Segment-Anything model's output.\n */\nexport class SamImageSegmentationOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.iou_scores The output logits of the model.\n * @param {Tensor} output.pred_masks Predicted boxes.\n */\n constructor({ iou_scores, pred_masks }) {\n super();\n this.iou_scores = iou_scores;\n this.pred_masks = pred_masks;\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// MarianMT models\nexport class MarianPreTrainedModel extends PreTrainedModel { };\n\nexport class MarianModel extends MarianPreTrainedModel { }\n\nexport class MarianMTModel extends MarianPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// M2M100 models\nexport class M2M100PreTrainedModel extends PreTrainedModel { };\n\nexport class M2M100Model extends M2M100PreTrainedModel { }\n\nexport class M2M100ForConditionalGeneration extends M2M100PreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Wav2Vec2 models\nexport class Wav2Vec2PreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare Wav2Vec2 Model transformer outputting raw hidden-states without any specific head on top.\n * \n * **Example:** Load and run a `Wav2Vec2Model` for feature extraction.\n * \n * ```javascript\n * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/mms-300m');\n * const audio = await read_audio('https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac', 16000);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const model = await AutoModel.from_pretrained('Xenova/mms-300m');\n * const output = await model(inputs);\n * // {\n * // last_hidden_state: Tensor {\n * // dims: [ 1, 1144, 1024 ],\n * // type: 'float32',\n * // data: Float32Array(1171456) [ ... ],\n * // size: 1171456\n * // }\n * // }\n * ```\n */\nexport class Wav2Vec2Model extends Wav2Vec2PreTrainedModel { }\n\nexport class Wav2Vec2ForCTC extends Wav2Vec2PreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\nexport class Wav2Vec2ForSequenceClassification extends Wav2Vec2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * Wav2Vec2 Model with a frame classification head on top for tasks like Speaker Diarization.\n */\nexport class Wav2Vec2ForAudioFrameClassification extends Wav2Vec2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// PyAnnote models\nexport class PyAnnotePreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare PyAnnote Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class PyAnnoteModel extends PyAnnotePreTrainedModel { }\n\n/**\n * PyAnnote Model with a frame classification head on top for tasks like Speaker Diarization.\n * \n * **Example:** Load and run a `PyAnnoteForAudioFrameClassification` for speaker diarization.\n * \n * ```javascript\n * import { AutoProcessor, AutoModelForAudioFrameClassification, read_audio } from '@huggingface/transformers';\n * \n * // Load model and processor\n * const model_id = 'onnx-community/pyannote-segmentation-3.0';\n * const model = await AutoModelForAudioFrameClassification.from_pretrained(model_id);\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * \n * // Read and preprocess audio\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/mlk.wav';\n * const audio = await read_audio(url, processor.feature_extractor.config.sampling_rate);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const { logits } = await model(inputs);\n * // {\n * // logits: Tensor {\n * // dims: [ 1, 767, 7 ], // [batch_size, num_frames, num_classes]\n * // type: 'float32',\n * // data: Float32Array(5369) [ ... ],\n * // size: 5369\n * // }\n * // }\n * \n * const result = processor.post_process_speaker_diarization(logits, audio.length);\n * // [\n * // [\n * // { id: 0, start: 0, end: 1.0512535626298245, confidence: 0.8220156481664611 },\n * // { id: 2, start: 1.0512535626298245, end: 2.3398869619825127, confidence: 0.9008811707860472 },\n * // ...\n * // ]\n * // ]\n * \n * // Display result\n * console.table(result[0], ['start', 'end', 'id', 'confidence']);\n * // ┌─────────┬────────────────────┬────────────────────┬────┬─────────────────────┐\n * // │ (index) │ start │ end │ id │ confidence │\n * // ├─────────┼────────────────────┼────────────────────┼────┼─────────────────────┤\n * // │ 0 │ 0 │ 1.0512535626298245 │ 0 │ 0.8220156481664611 │\n * // │ 1 │ 1.0512535626298245 │ 2.3398869619825127 │ 2 │ 0.9008811707860472 │\n * // │ 2 │ 2.3398869619825127 │ 3.5946089560890773 │ 0 │ 0.7521651315796233 │\n * // │ 3 │ 3.5946089560890773 │ 4.578039708226655 │ 2 │ 0.8491978128022479 │\n * // │ 4 │ 4.578039708226655 │ 4.594995410849717 │ 0 │ 0.2935352600416393 │\n * // │ 5 │ 4.594995410849717 │ 6.121008646925269 │ 3 │ 0.6788051309866024 │\n * // │ 6 │ 6.121008646925269 │ 6.256654267909762 │ 0 │ 0.37125512393851134 │\n * // │ 7 │ 6.256654267909762 │ 8.630452635138397 │ 2 │ 0.7467035186353542 │\n * // │ 8 │ 8.630452635138397 │ 10.088643060721703 │ 0 │ 0.7689364814666032 │\n * // │ 9 │ 10.088643060721703 │ 12.58113134631177 │ 2 │ 0.9123324509131324 │\n * // │ 10 │ 12.58113134631177 │ 13.005023911888312 │ 0 │ 0.4828358177572041 │\n * // └─────────┴────────────────────┴────────────────────┴────┴─────────────────────┘\n * ```\n */\nexport class PyAnnoteForAudioFrameClassification extends PyAnnotePreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// WeSpeakerResNet models\nexport class WeSpeakerResNetPreTrainedModel extends PreTrainedModel { };\nexport class WeSpeakerResNetModel extends WeSpeakerResNetPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// UniSpeech models\nexport class UniSpeechPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare UniSpeech Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class UniSpeechModel extends UniSpeechPreTrainedModel { }\n\n/**\n * UniSpeech Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class UniSpeechForCTC extends UniSpeechPreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * UniSpeech Model with a sequence classification head on top (a linear layer over the pooled output).\n */\nexport class UniSpeechForSequenceClassification extends UniSpeechPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// UniSpeechSat models\nexport class UniSpeechSatPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare UniSpeechSat Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class UniSpeechSatModel extends UniSpeechSatPreTrainedModel { }\n\n/**\n * UniSpeechSat Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class UniSpeechSatForCTC extends UniSpeechSatPreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * UniSpeechSat Model with a sequence classification head on top (a linear layer over the pooled output).\n */\nexport class UniSpeechSatForSequenceClassification extends UniSpeechSatPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * UniSpeechSat Model with a frame classification head on top for tasks like Speaker Diarization.\n */\nexport class UniSpeechSatForAudioFrameClassification extends UniSpeechSatPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Wav2Vec2Bert models\nexport class Wav2Vec2BertPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare Wav2Vec2Bert Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class Wav2Vec2BertModel extends Wav2Vec2BertPreTrainedModel { }\n\n/**\n * Wav2Vec2Bert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class Wav2Vec2BertForCTC extends Wav2Vec2BertPreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_features Float values of input mel-spectrogram.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * Wav2Vec2Bert Model with a sequence classification head on top (a linear layer over the pooled output).\n */\nexport class Wav2Vec2BertForSequenceClassification extends Wav2Vec2BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Hubert models\nexport class HubertPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Hubert Model transformer outputting raw hidden-states without any specific head on top.\n * \n * **Example:** Load and run a `HubertModel` for feature extraction.\n * \n * ```javascript\n * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/hubert-base-ls960');\n * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav', 16000);\n * const inputs = await processor(audio);\n * \n * // Load and run model with inputs\n * const model = await AutoModel.from_pretrained('Xenova/hubert-base-ls960');\n * const output = await model(inputs);\n * // {\n * // last_hidden_state: Tensor {\n * // dims: [ 1, 549, 768 ],\n * // type: 'float32',\n * // data: Float32Array(421632) [0.0682469978928566, 0.08104046434164047, -0.4975186586380005, ...],\n * // size: 421632\n * // }\n * // }\n * ```\n */\nexport class HubertModel extends Wav2Vec2PreTrainedModel { }\n\n/**\n * Hubert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class HubertForCTC extends Wav2Vec2PreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * Hubert Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like SUPERB Keyword Spotting.\n */\nexport class HubertForSequenceClassification extends Wav2Vec2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// WavLM models\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class WavLMPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare WavLM Model transformer outputting raw hidden-states without any specific head on top.\n * \n * **Example:** Load and run a `WavLMModel` for feature extraction.\n * \n * ```javascript\n * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base');\n * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav', 16000);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const model = await AutoModel.from_pretrained('Xenova/wavlm-base');\n * const output = await model(inputs);\n * // {\n * // last_hidden_state: Tensor {\n * // dims: [ 1, 549, 768 ],\n * // type: 'float32',\n * // data: Float32Array(421632) [-0.349443256855011, -0.39341306686401367, 0.022836603224277496, ...],\n * // size: 421632\n * // }\n * // }\n * ```\n */\nexport class WavLMModel extends WavLMPreTrainedModel { }\n\n/**\n * WavLM Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class WavLMForCTC extends WavLMPreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * WavLM Model with a sequence classification head on top (a linear layer over the pooled output).\n */\nexport class WavLMForSequenceClassification extends WavLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * WavLM Model with an XVector feature extraction head on top for tasks like Speaker Verification.\n * \n * **Example:** Extract speaker embeddings with `WavLMForXVector`.\n * ```javascript\n * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base-plus-sv');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const audio = await read_audio(url, 16000);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const model = await AutoModel.from_pretrained('Xenova/wavlm-base-plus-sv');\n * const outputs = await model(inputs);\n * // {\n * // logits: Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [0.5847219228744507, ...],\n * // size: 512\n * // },\n * // embeddings: Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [-0.09079201519489288, ...],\n * // size: 512\n * // }\n * // }\n * ```\n */\nexport class WavLMForXVector extends WavLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits and speaker embeddings.\n */\n async _call(model_inputs) {\n return new XVectorOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * WavLM Model with a frame classification head on top for tasks like Speaker Diarization.\n * \n * **Example:** Perform speaker diarization with `WavLMForAudioFrameClassification`.\n * ```javascript\n * import { AutoProcessor, AutoModelForAudioFrameClassification, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base-plus-sd');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const audio = await read_audio(url, 16000);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const model = await AutoModelForAudioFrameClassification.from_pretrained('Xenova/wavlm-base-plus-sd');\n * const { logits } = await model(inputs);\n * // {\n * // logits: Tensor {\n * // dims: [ 1, 549, 2 ], // [batch_size, num_frames, num_speakers]\n * // type: 'float32',\n * // data: Float32Array(1098) [-3.5301010608673096, ...],\n * // size: 1098\n * // }\n * // }\n * \n * const labels = logits[0].sigmoid().tolist().map(\n * frames => frames.map(speaker => speaker > 0.5 ? 1 : 0)\n * );\n * console.log(labels); // labels is a one-hot array of shape (num_frames, num_speakers)\n * // [\n * // [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],\n * // [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],\n * // [0, 0], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1],\n * // ...\n * // ]\n * ```\n */\nexport class WavLMForAudioFrameClassification extends WavLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n//////////////////////////////////////////////////\n// SpeechT5 models\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class SpeechT5PreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare SpeechT5 Encoder-Decoder Model outputting raw hidden-states without any specific pre- or post-nets.\n */\nexport class SpeechT5Model extends SpeechT5PreTrainedModel { };\n\n/**\n * SpeechT5 Model with a speech encoder and a text decoder.\n * \n * **Example:** Generate speech from text with `SpeechT5ForSpeechToText`.\n * ```javascript\n * import { AutoTokenizer, AutoProcessor, SpeechT5ForTextToSpeech, SpeechT5HifiGan, Tensor } from '@huggingface/transformers';\n * \n * // Load the tokenizer and processor\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/speecht5_tts');\n * const processor = await AutoProcessor.from_pretrained('Xenova/speecht5_tts');\n * \n * // Load the models\n * // NOTE: We use the full-precision versions as they are more accurate\n * const model = await SpeechT5ForTextToSpeech.from_pretrained('Xenova/speecht5_tts', { dtype: 'fp32' });\n * const vocoder = await SpeechT5HifiGan.from_pretrained('Xenova/speecht5_hifigan', { dtype: 'fp32' });\n * \n * // Load speaker embeddings from URL\n * const speaker_embeddings_data = new Float32Array(\n * await (await fetch('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin')).arrayBuffer()\n * );\n * const speaker_embeddings = new Tensor(\n * 'float32',\n * speaker_embeddings_data,\n * [1, speaker_embeddings_data.length]\n * )\n * \n * // Run tokenization\n * const { input_ids } = tokenizer('Hello, my dog is cute');\n * \n * // Generate waveform\n * const { waveform } = await model.generate_speech(input_ids, speaker_embeddings, { vocoder });\n * console.log(waveform)\n * // Tensor {\n * // dims: [ 26112 ],\n * // type: 'float32',\n * // size: 26112,\n * // data: Float32Array(26112) [ -0.00043630177970044315, -0.00018082228780258447, ... ],\n * // }\n * ```\n */\nexport class SpeechT5ForSpeechToText extends SpeechT5PreTrainedModel { }\n\n/**\n * SpeechT5 Model with a text encoder and a speech decoder.\n */\nexport class SpeechT5ForTextToSpeech extends SpeechT5PreTrainedModel {\n\n /**\n * @typedef {Object} SpeechOutput\n * @property {Tensor} [spectrogram] The predicted log-mel spectrogram of shape\n * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided\n * @property {Tensor} [waveform] The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided.\n * @property {Tensor} [cross_attentions] The outputs of the decoder's cross-attention layers of shape\n * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`.\n */\n\n /**\n * Converts a sequence of input tokens into a sequence of mel spectrograms, which are subsequently turned into a speech waveform using a vocoder.\n * @param {Tensor} input_values Indices of input sequence tokens in the vocabulary.\n * @param {Tensor} speaker_embeddings Tensor containing the speaker embeddings.\n * @param {Object} options Optional parameters for generating speech.\n * @param {number} [options.threshold=0.5] The generated sequence ends when the predicted stop token probability exceeds this value.\n * @param {number} [options.minlenratio=0.0] Used to calculate the minimum required length for the output sequence.\n * @param {number} [options.maxlenratio=20.0] Used to calculate the maximum allowed length for the output sequence.\n * @param {Object} [options.vocoder=null] The vocoder that converts the mel spectrogram into a speech waveform. If `null`, the output is the mel spectrogram.\n * @param {boolean} [options.output_cross_attentions=false] Whether or not to return the attentions tensors of the decoder's cross-attention layers.\n * @returns {Promise} A promise which resolves to an object containing the spectrogram, waveform, and cross-attention tensors.\n */\n async generate_speech(input_values, speaker_embeddings, {\n threshold = 0.5,\n minlenratio = 0.0,\n maxlenratio = 20.0,\n vocoder = null,\n // output_cross_attentions = false, // TODO add\n } = {}) {\n\n const model_inputs = {\n input_ids: input_values\n }\n\n const { encoder_outputs, encoder_attention_mask } = await encoderForward(this, model_inputs);\n\n const r = encoder_outputs.dims[1] / this.config.reduction_factor;\n const maxlen = Math.floor(r * maxlenratio);\n const minlen = Math.floor(r * minlenratio);\n\n const num_mel_bins = this.config.num_mel_bins;\n\n let spectrogramParts = [];\n let past_key_values = null;\n let decoder_outputs = null;\n let idx = 0;\n\n while (true) {\n ++idx;\n\n const use_cache_branch = boolTensor(!!decoder_outputs);\n let output_sequence;\n if (decoder_outputs) {\n output_sequence = decoder_outputs.output_sequence_out;\n } else {\n output_sequence = new Tensor(\n 'float32',\n new Float32Array(num_mel_bins),\n [1, 1, num_mel_bins],\n )\n }\n let decoderFeeds = {\n use_cache_branch,\n output_sequence,\n encoder_attention_mask: encoder_attention_mask,\n speaker_embeddings: speaker_embeddings,\n encoder_hidden_states: encoder_outputs,\n };\n\n this.addPastKeyValues(decoderFeeds, past_key_values);\n decoder_outputs = await sessionRun(this.sessions['decoder_model_merged'], decoderFeeds);\n past_key_values = this.getPastKeyValues(decoder_outputs, past_key_values);\n\n const { prob, spectrum } = decoder_outputs;\n spectrogramParts.push(spectrum);\n\n if (idx >= minlen && (\n // Finished when stop token or maximum length is reached.\n Array.from(prob.data).filter(p => p >= threshold).length > 0 || idx >= maxlen\n )) {\n break;\n }\n }\n\n const spectrogram = cat(spectrogramParts);\n const { waveform } = await sessionRun(vocoder.sessions['model'], { spectrogram });\n\n return {\n spectrogram,\n waveform,\n // cross_attentions: null, // TODO add\n }\n }\n}\n\n/**\n * HiFi-GAN vocoder.\n * \n * See [SpeechT5ForSpeechToText](./models#module_models.SpeechT5ForSpeechToText) for example usage.\n */\nexport class SpeechT5HifiGan extends PreTrainedModel {\n main_input_name = 'spectrogram';\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// TrOCR models\nexport class TrOCRPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The TrOCR Decoder with a language modeling head.\n */\nexport class TrOCRForCausalLM extends TrOCRPreTrainedModel { }\n\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Mistral models\n/**\n * The bare Mistral Model outputting raw hidden-states without any specific head on top.\n */\nexport class MistralPreTrainedModel extends PreTrainedModel { }\n\nexport class MistralModel extends MistralPreTrainedModel { }\n\nexport class MistralForCausalLM extends MistralPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Starcoder2 models\n/**\n * The bare Starcoder2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Starcoder2PreTrainedModel extends PreTrainedModel { }\n\nexport class Starcoder2Model extends Starcoder2PreTrainedModel { }\n\nexport class Starcoder2ForCausalLM extends Starcoder2PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Falcon models\n/**\n * The bare Falcon Model outputting raw hidden-states without any specific head on top.\n */\nexport class FalconPreTrainedModel extends PreTrainedModel { }\n\nexport class FalconModel extends FalconPreTrainedModel { }\n\nexport class FalconForCausalLM extends FalconPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// CLAP models\nexport class ClapPreTrainedModel extends PreTrainedModel { }\n\nexport class ClapModel extends ClapPreTrainedModel { }\n\n/**\n * CLAP Text Model with a projection layer on top (a linear layer on top of the pooled output).\n * \n * **Example:** Compute text embeddings with `ClapTextModelWithProjection`.\n * \n * ```javascript\n * import { AutoTokenizer, ClapTextModelWithProjection } from '@huggingface/transformers';\n * \n * // Load tokenizer and text model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clap-htsat-unfused');\n * const text_model = await ClapTextModelWithProjection.from_pretrained('Xenova/clap-htsat-unfused');\n * \n * // Run tokenization\n * const texts = ['a sound of a cat', 'a sound of a dog'];\n * const text_inputs = tokenizer(texts, { padding: true, truncation: true });\n * \n * // Compute embeddings\n * const { text_embeds } = await text_model(text_inputs);\n * // Tensor {\n * // dims: [ 2, 512 ],\n * // type: 'float32',\n * // data: Float32Array(1024) [ ... ],\n * // size: 1024\n * // }\n * ```\n */\nexport class ClapTextModelWithProjection extends ClapPreTrainedModel {\n\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'text_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * CLAP Audio Model with a projection layer on top (a linear layer on top of the pooled output).\n * \n * **Example:** Compute audio embeddings with `ClapAudioModelWithProjection`.\n * \n * ```javascript\n * import { AutoProcessor, ClapAudioModelWithProjection, read_audio } from '@huggingface/transformers';\n * \n * // Load processor and audio model\n * const processor = await AutoProcessor.from_pretrained('Xenova/clap-htsat-unfused');\n * const audio_model = await ClapAudioModelWithProjection.from_pretrained('Xenova/clap-htsat-unfused');\n * \n * // Read audio and run processor\n * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cat_meow.wav');\n * const audio_inputs = await processor(audio);\n * \n * // Compute embeddings\n * const { audio_embeds } = await audio_model(audio_inputs);\n * // Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [ ... ],\n * // size: 512\n * // }\n * ```\n */\nexport class ClapAudioModelWithProjection extends ClapPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'audio_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// VITS models\nexport class VitsPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The complete VITS model, for text-to-speech synthesis.\n * \n * **Example:** Generate speech from text with `VitsModel`.\n * ```javascript\n * import { AutoTokenizer, VitsModel } from '@huggingface/transformers';\n * \n * // Load the tokenizer and model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/mms-tts-eng');\n * const model = await VitsModel.from_pretrained('Xenova/mms-tts-eng');\n * \n * // Run tokenization\n * const inputs = tokenizer('I love transformers');\n * \n * // Generate waveform\n * const { waveform } = await model(inputs);\n * // Tensor {\n * // dims: [ 1, 35328 ],\n * // type: 'float32',\n * // data: Float32Array(35328) [ ... ],\n * // size: 35328,\n * // }\n * ```\n */\nexport class VitsModel extends VitsPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} The outputs for the VITS model.\n */\n async _call(model_inputs) {\n return new VitsModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Segformer models\nexport class SegformerPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare SegFormer encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top.\n */\nexport class SegformerModel extends SegformerPreTrainedModel { }\n\n/**\n * SegFormer Model transformer with an image classification head on top (a linear layer on top of the final hidden states) e.g. for ImageNet.\n */\nexport class SegformerForImageClassification extends SegformerPreTrainedModel { }\n\n/**\n * SegFormer Model transformer with an all-MLP decode head on top e.g. for ADE20k, CityScapes.\n */\nexport class SegformerForSemanticSegmentation extends SegformerPreTrainedModel { }\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// StableLm models\nexport class StableLmPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare StableLm Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class StableLmModel extends StableLmPreTrainedModel { }\n\n/**\n * StableLm Model with a `language modeling` head on top for Causal Language Modeling (with past).\n */\nexport class StableLmForCausalLM extends StableLmPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class EfficientNetPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare EfficientNet model outputting raw features without any specific head on top.\n */\nexport class EfficientNetModel extends EfficientNetPreTrainedModel { }\n\n/**\n * EfficientNet Model with an image classification head on top (a linear layer on top of the pooled features).\n */\nexport class EfficientNetForImageClassification extends EfficientNetPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Musicgen models\nexport class MusicgenPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Musicgen decoder model outputting raw hidden-states without any specific head on top.\n */\nexport class MusicgenModel extends MusicgenPreTrainedModel { }\n\n/**\n * The MusicGen decoder model with a language modelling head on top.\n */\nexport class MusicgenForCausalLM extends MusicgenPreTrainedModel { }\n\n/**\n * The composite MusicGen model with a text encoder, audio encoder and Musicgen decoder,\n * for music generation tasks with one or both of text and audio prompts.\n * \n * **Example:** Generate music from text with `Xenova/musicgen-small`.\n * ```javascript\n * import { AutoTokenizer, MusicgenForConditionalGeneration } from '@huggingface/transformers';\n * \n * // Load tokenizer and model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/musicgen-small');\n * const model = await MusicgenForConditionalGeneration.from_pretrained(\n * 'Xenova/musicgen-small', { dtype: 'fp32' }\n * );\n * \n * // Prepare text input\n * const prompt = '80s pop track with bassy drums and synth';\n * const inputs = tokenizer(prompt);\n * \n * // Generate audio\n * const audio_values = await model.generate({\n * ...inputs,\n * max_new_tokens: 512,\n * do_sample: true,\n * guidance_scale: 3,\n * });\n * \n * // (Optional) Write the output to a WAV file\n * import wavefile from 'wavefile';\n * import fs from 'fs';\n * \n * const wav = new wavefile.WaveFile();\n * wav.fromScratch(1, model.config.audio_encoder.sampling_rate, '32f', audio_values.data);\n * fs.writeFileSync('musicgen_out.wav', wav.toBuffer());\n * ```\n */\nexport class MusicgenForConditionalGeneration extends PreTrainedModel { // NOTE: not MusicgenPreTrainedModel\n forward_params = [\n 'input_ids',\n 'attention_mask',\n 'encoder_outputs',\n 'decoder_input_ids',\n 'decoder_attention_mask',\n 'past_key_values',\n ];\n\n /**\n * Apply the pattern mask to the final ids,\n * then revert the pattern delay mask by filtering the pad token id in a single step.\n * @param {Tensor} outputs The output tensor from the model.\n * @returns {Tensor} The filtered output tensor.\n */\n _apply_and_filter_by_delay_pattern_mask(outputs) {\n const [bs_x_codebooks, seqLength] = outputs.dims;\n const num_codebooks = this.config.decoder.num_codebooks;\n const upperBound = (seqLength - num_codebooks);\n\n let newDataSize = 0;\n for (let i = 0; i < outputs.size; ++i) {\n if (outputs.data[i] === this.config.decoder.pad_token_id) {\n continue;\n }\n\n const row = (i % seqLength);\n const col = Math.floor(i / seqLength) % num_codebooks;\n\n const diff = row - col;\n if (diff > 0 && diff <= upperBound) {\n outputs.data[newDataSize++] = outputs.data[i];\n }\n }\n\n const batch_size = Math.floor(bs_x_codebooks / num_codebooks);\n const inferred = newDataSize / (batch_size * num_codebooks);\n // TODO: assert `inferred` is an integer\n return new Tensor(\n outputs.type,\n outputs.data.slice(0, newDataSize),\n [batch_size, num_codebooks, inferred]\n );\n }\n\n\n prepare_inputs_for_generation(input_ids, model_inputs, generation_config) {\n // apply the delay pattern mask\n let clonedInputIds = structuredClone(input_ids);\n for (let i = 0; i < clonedInputIds.length; ++i) {\n for (let j = 0; j < clonedInputIds[i].length; ++j) {\n if ((i % this.config.decoder.num_codebooks) >= j) {\n clonedInputIds[i][j] = BigInt(this.config.decoder.pad_token_id);\n }\n }\n }\n // for classifier free guidance we need to replicate the decoder args across the batch dim\n // (we'll split these before sampling)\n if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) {\n // [batch, seqLength] -> [2 * batch, seqLength]\n clonedInputIds = clonedInputIds.concat(clonedInputIds);\n }\n\n const prepped = super.prepare_inputs_for_generation(clonedInputIds, model_inputs, generation_config);\n return prepped;\n }\n\n /**\n * Generates sequences of token ids for models with a language modeling head.\n * @param {import('./generation/parameters.js').GenerationFunctionParameters} options\n * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores.\n */\n async generate(options) {\n\n const output_ids = await super.generate(options);\n\n // apply the pattern mask to the final ids\n // tensor: int64[1,batch_size,4,chunk_length]\n const audio_codes = this._apply_and_filter_by_delay_pattern_mask(\n /** @type {Tensor} */(output_ids)\n ).unsqueeze_(0); // append the frame dimension back to the audio codes\n\n const { audio_values } = await sessionRun(this.sessions['encodec_decode'], { audio_codes })\n\n return audio_values;\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MobileNetV1 models\nexport class MobileNetV1PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.\n */\nexport class MobileNetV1Model extends MobileNetV1PreTrainedModel { }\n\n/**\n * MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features),\n * e.g. for ImageNet.\n */\nexport class MobileNetV1ForImageClassification extends MobileNetV1PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MobileNetV2 models\nexport class MobileNetV2PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MobileNetV2 model outputting raw hidden-states without any specific head on top.\n */\nexport class MobileNetV2Model extends MobileNetV2PreTrainedModel { }\n\n/**\n * MobileNetV2 model with an image classification head on top (a linear layer on top of the pooled features),\n * e.g. for ImageNet.\n */\nexport class MobileNetV2ForImageClassification extends MobileNetV2PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MobileNetV3 models\nexport class MobileNetV3PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MobileNetV3 model outputting raw hidden-states without any specific head on top.\n */\nexport class MobileNetV3Model extends MobileNetV3PreTrainedModel { }\n\n/**\n * MobileNetV3 model with an image classification head on top (a linear layer on top of the pooled features),\n * e.g. for ImageNet.\n */\nexport class MobileNetV3ForImageClassification extends MobileNetV3PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MobileNetV4 models\nexport class MobileNetV4PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MobileNetV4 model outputting raw hidden-states without any specific head on top.\n */\nexport class MobileNetV4Model extends MobileNetV4PreTrainedModel { }\n\n/**\n * MobileNetV4 model with an image classification head on top (a linear layer on top of the pooled features),\n * e.g. for ImageNet.\n */\nexport class MobileNetV4ForImageClassification extends MobileNetV4PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Decision Transformer models\nexport class DecisionTransformerPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The model builds upon the GPT2 architecture to perform autoregressive prediction of actions in an offline RL setting.\n * Refer to the paper for more details: https://arxiv.org/abs/2106.01345\n */\nexport class DecisionTransformerModel extends DecisionTransformerPreTrainedModel { }\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// AutoModels, used to simplify construction of PreTrainedModels\n// (uses config to instantiate correct class)\n\n/**\n * Base class of all AutoModels. Contains the `from_pretrained` function\n * which is used to instantiate pretrained models.\n */\nexport class PretrainedMixin {\n /**\n * Mapping from model type to model class.\n * @type {Map[]}\n */\n static MODEL_CLASS_MAPPINGS = null;\n\n /**\n * Whether to attempt to instantiate the base class (`PretrainedModel`) if \n * the model type is not found in the mapping.\n */\n static BASE_IF_FAIL = false;\n\n\n /** @type {typeof PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n model_file_name = null,\n subfolder = 'onnx',\n device = null,\n dtype = null,\n use_external_data_format = null,\n session_options = {},\n } = {}) {\n\n const options = {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n model_file_name,\n subfolder,\n device,\n dtype,\n use_external_data_format,\n session_options,\n }\n options.config = await AutoConfig.from_pretrained(pretrained_model_name_or_path, options);\n\n if (!this.MODEL_CLASS_MAPPINGS) {\n throw new Error(\"`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: \" + this.name);\n }\n\n for (const MODEL_CLASS_MAPPING of this.MODEL_CLASS_MAPPINGS) {\n const modelInfo = MODEL_CLASS_MAPPING.get(options.config.model_type);\n if (!modelInfo) {\n continue; // Item not found in this mapping\n }\n return await modelInfo[1].from_pretrained(pretrained_model_name_or_path, options);\n }\n\n if (this.BASE_IF_FAIL) {\n console.warn(`Unknown model class \"${options.config.model_type}\", attempting to construct from base class.`);\n return await PreTrainedModel.from_pretrained(pretrained_model_name_or_path, options);\n } else {\n throw Error(`Unsupported model type: ${options.config.model_type}`)\n }\n }\n}\n\nconst MODEL_MAPPING_NAMES_ENCODER_ONLY = new Map([\n ['bert', ['BertModel', BertModel]],\n ['nomic_bert', ['NomicBertModel', NomicBertModel]],\n ['roformer', ['RoFormerModel', RoFormerModel]],\n ['electra', ['ElectraModel', ElectraModel]],\n ['esm', ['EsmModel', EsmModel]],\n ['convbert', ['ConvBertModel', ConvBertModel]],\n ['camembert', ['CamembertModel', CamembertModel]],\n ['deberta', ['DebertaModel', DebertaModel]],\n ['deberta-v2', ['DebertaV2Model', DebertaV2Model]],\n ['mpnet', ['MPNetModel', MPNetModel]],\n ['albert', ['AlbertModel', AlbertModel]],\n ['distilbert', ['DistilBertModel', DistilBertModel]],\n ['roberta', ['RobertaModel', RobertaModel]],\n ['xlm', ['XLMModel', XLMModel]],\n ['xlm-roberta', ['XLMRobertaModel', XLMRobertaModel]],\n ['clap', ['ClapModel', ClapModel]],\n ['clip', ['CLIPModel', CLIPModel]],\n ['clipseg', ['CLIPSegModel', CLIPSegModel]],\n ['chinese_clip', ['ChineseCLIPModel', ChineseCLIPModel]],\n ['siglip', ['SiglipModel', SiglipModel]],\n ['mobilebert', ['MobileBertModel', MobileBertModel]],\n ['squeezebert', ['SqueezeBertModel', SqueezeBertModel]],\n ['wav2vec2', ['Wav2Vec2Model', Wav2Vec2Model]],\n ['wav2vec2-bert', ['Wav2Vec2BertModel', Wav2Vec2BertModel]],\n ['unispeech', ['UniSpeechModel', UniSpeechModel]],\n ['unispeech-sat', ['UniSpeechSatModel', UniSpeechSatModel]],\n ['hubert', ['HubertModel', HubertModel]],\n ['wavlm', ['WavLMModel', WavLMModel]],\n ['audio-spectrogram-transformer', ['ASTModel', ASTModel]],\n ['vits', ['VitsModel', VitsModel]],\n ['pyannote', ['PyAnnoteModel', PyAnnoteModel]],\n ['wespeaker-resnet', ['WeSpeakerResNetModel', WeSpeakerResNetModel]],\n\n ['detr', ['DetrModel', DetrModel]],\n ['rt_detr', ['RTDetrModel', RTDetrModel]],\n ['table-transformer', ['TableTransformerModel', TableTransformerModel]],\n ['vit', ['ViTModel', ViTModel]],\n ['pvt', ['PvtModel', PvtModel]],\n ['vit_msn', ['ViTMSNModel', ViTMSNModel]],\n ['vit_mae', ['ViTMAEModel', ViTMAEModel]],\n ['groupvit', ['GroupViTModel', GroupViTModel]],\n ['fastvit', ['FastViTModel', FastViTModel]],\n ['mobilevit', ['MobileViTModel', MobileViTModel]],\n ['mobilevitv2', ['MobileViTV2Model', MobileViTV2Model]],\n ['owlvit', ['OwlViTModel', OwlViTModel]],\n ['owlv2', ['Owlv2Model', Owlv2Model]],\n ['beit', ['BeitModel', BeitModel]],\n ['deit', ['DeiTModel', DeiTModel]],\n ['hiera', ['HieraModel', HieraModel]],\n ['convnext', ['ConvNextModel', ConvNextModel]],\n ['convnextv2', ['ConvNextV2Model', ConvNextV2Model]],\n ['dinov2', ['Dinov2Model', Dinov2Model]],\n ['resnet', ['ResNetModel', ResNetModel]],\n ['swin', ['SwinModel', SwinModel]],\n ['swin2sr', ['Swin2SRModel', Swin2SRModel]],\n ['donut-swin', ['DonutSwinModel', DonutSwinModel]],\n ['yolos', ['YolosModel', YolosModel]],\n ['dpt', ['DPTModel', DPTModel]],\n ['glpn', ['GLPNModel', GLPNModel]],\n\n ['hifigan', ['SpeechT5HifiGan', SpeechT5HifiGan]],\n ['efficientnet', ['EfficientNetModel', EfficientNetModel]],\n\n ['decision_transformer', ['DecisionTransformerModel', DecisionTransformerModel]],\n\n ['mobilenet_v1', ['MobileNetV1Model', MobileNetV1Model]],\n ['mobilenet_v2', ['MobileNetV2Model', MobileNetV2Model]],\n ['mobilenet_v3', ['MobileNetV3Model', MobileNetV3Model]],\n ['mobilenet_v4', ['MobileNetV4Model', MobileNetV4Model]],\n\n ['maskformer', ['MaskFormerModel', MaskFormerModel]],\n]);\n\nconst MODEL_MAPPING_NAMES_ENCODER_DECODER = new Map([\n ['t5', ['T5Model', T5Model]],\n ['longt5', ['LongT5Model', LongT5Model]],\n ['mt5', ['MT5Model', MT5Model]],\n ['bart', ['BartModel', BartModel]],\n ['mbart', ['MBartModel', MBartModel]],\n ['marian', ['MarianModel', MarianModel]],\n ['whisper', ['WhisperModel', WhisperModel]],\n ['m2m_100', ['M2M100Model', M2M100Model]],\n ['blenderbot', ['BlenderbotModel', BlenderbotModel]],\n ['blenderbot-small', ['BlenderbotSmallModel', BlenderbotSmallModel]],\n]);\n\n\nconst MODEL_MAPPING_NAMES_DECODER_ONLY = new Map([\n ['bloom', ['BloomModel', BloomModel]],\n ['jais', ['JAISModel', JAISModel]],\n ['gpt2', ['GPT2Model', GPT2Model]],\n ['gptj', ['GPTJModel', GPTJModel]],\n ['gpt_bigcode', ['GPTBigCodeModel', GPTBigCodeModel]],\n ['gpt_neo', ['GPTNeoModel', GPTNeoModel]],\n ['gpt_neox', ['GPTNeoXModel', GPTNeoXModel]],\n ['codegen', ['CodeGenModel', CodeGenModel]],\n ['llama', ['LlamaModel', LlamaModel]],\n ['granite', ['GraniteModel', GraniteModel]],\n ['cohere', ['CohereModel', CohereModel]],\n ['gemma', ['GemmaModel', GemmaModel]],\n ['gemma2', ['Gemma2Model', Gemma2Model]],\n ['openelm', ['OpenELMModel', OpenELMModel]],\n ['qwen2', ['Qwen2Model', Qwen2Model]],\n ['phi', ['PhiModel', PhiModel]],\n ['phi3', ['Phi3Model', Phi3Model]],\n ['mpt', ['MptModel', MptModel]],\n ['opt', ['OPTModel', OPTModel]],\n ['mistral', ['MistralModel', MistralModel]],\n ['starcoder2', ['Starcoder2Model', Starcoder2Model]],\n ['falcon', ['FalconModel', FalconModel]],\n ['stablelm', ['StableLmModel', StableLmModel]],\n]);\n\nconst MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = new Map([\n ['speecht5', ['SpeechT5ForSpeechToText', SpeechT5ForSpeechToText]],\n ['whisper', ['WhisperForConditionalGeneration', WhisperForConditionalGeneration]],\n]);\n\nconst MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES = new Map([\n ['speecht5', ['SpeechT5ForTextToSpeech', SpeechT5ForTextToSpeech]],\n]);\n\nconst MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES = new Map([\n ['vits', ['VitsModel', VitsModel]],\n ['musicgen', ['MusicgenForConditionalGeneration', MusicgenForConditionalGeneration]],\n]);\n\nconst MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['bert', ['BertForSequenceClassification', BertForSequenceClassification]],\n ['roformer', ['RoFormerForSequenceClassification', RoFormerForSequenceClassification]],\n ['electra', ['ElectraForSequenceClassification', ElectraForSequenceClassification]],\n ['esm', ['EsmForSequenceClassification', EsmForSequenceClassification]],\n ['convbert', ['ConvBertForSequenceClassification', ConvBertForSequenceClassification]],\n ['camembert', ['CamembertForSequenceClassification', CamembertForSequenceClassification]],\n ['deberta', ['DebertaForSequenceClassification', DebertaForSequenceClassification]],\n ['deberta-v2', ['DebertaV2ForSequenceClassification', DebertaV2ForSequenceClassification]],\n ['mpnet', ['MPNetForSequenceClassification', MPNetForSequenceClassification]],\n ['albert', ['AlbertForSequenceClassification', AlbertForSequenceClassification]],\n ['distilbert', ['DistilBertForSequenceClassification', DistilBertForSequenceClassification]],\n ['roberta', ['RobertaForSequenceClassification', RobertaForSequenceClassification]],\n ['xlm', ['XLMForSequenceClassification', XLMForSequenceClassification]],\n ['xlm-roberta', ['XLMRobertaForSequenceClassification', XLMRobertaForSequenceClassification]],\n ['bart', ['BartForSequenceClassification', BartForSequenceClassification]],\n ['mbart', ['MBartForSequenceClassification', MBartForSequenceClassification]],\n ['mobilebert', ['MobileBertForSequenceClassification', MobileBertForSequenceClassification]],\n ['squeezebert', ['SqueezeBertForSequenceClassification', SqueezeBertForSequenceClassification]],\n]);\n\nconst MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['bert', ['BertForTokenClassification', BertForTokenClassification]],\n ['roformer', ['RoFormerForTokenClassification', RoFormerForTokenClassification]],\n ['electra', ['ElectraForTokenClassification', ElectraForTokenClassification]],\n ['esm', ['EsmForTokenClassification', EsmForTokenClassification]],\n ['convbert', ['ConvBertForTokenClassification', ConvBertForTokenClassification]],\n ['camembert', ['CamembertForTokenClassification', CamembertForTokenClassification]],\n ['deberta', ['DebertaForTokenClassification', DebertaForTokenClassification]],\n ['deberta-v2', ['DebertaV2ForTokenClassification', DebertaV2ForTokenClassification]],\n ['mpnet', ['MPNetForTokenClassification', MPNetForTokenClassification]],\n ['distilbert', ['DistilBertForTokenClassification', DistilBertForTokenClassification]],\n ['roberta', ['RobertaForTokenClassification', RobertaForTokenClassification]],\n ['xlm', ['XLMForTokenClassification', XLMForTokenClassification]],\n ['xlm-roberta', ['XLMRobertaForTokenClassification', XLMRobertaForTokenClassification]],\n]);\n\nconst MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = new Map([\n ['t5', ['T5ForConditionalGeneration', T5ForConditionalGeneration]],\n ['longt5', ['LongT5ForConditionalGeneration', LongT5ForConditionalGeneration]],\n ['mt5', ['MT5ForConditionalGeneration', MT5ForConditionalGeneration]],\n ['bart', ['BartForConditionalGeneration', BartForConditionalGeneration]],\n ['mbart', ['MBartForConditionalGeneration', MBartForConditionalGeneration]],\n ['marian', ['MarianMTModel', MarianMTModel]],\n ['m2m_100', ['M2M100ForConditionalGeneration', M2M100ForConditionalGeneration]],\n ['blenderbot', ['BlenderbotForConditionalGeneration', BlenderbotForConditionalGeneration]],\n ['blenderbot-small', ['BlenderbotSmallForConditionalGeneration', BlenderbotSmallForConditionalGeneration]],\n]);\n\nconst MODEL_FOR_CAUSAL_LM_MAPPING_NAMES = new Map([\n ['bloom', ['BloomForCausalLM', BloomForCausalLM]],\n ['gpt2', ['GPT2LMHeadModel', GPT2LMHeadModel]],\n ['jais', ['JAISLMHeadModel', JAISLMHeadModel]],\n ['gptj', ['GPTJForCausalLM', GPTJForCausalLM]],\n ['gpt_bigcode', ['GPTBigCodeForCausalLM', GPTBigCodeForCausalLM]],\n ['gpt_neo', ['GPTNeoForCausalLM', GPTNeoForCausalLM]],\n ['gpt_neox', ['GPTNeoXForCausalLM', GPTNeoXForCausalLM]],\n ['codegen', ['CodeGenForCausalLM', CodeGenForCausalLM]],\n ['llama', ['LlamaForCausalLM', LlamaForCausalLM]],\n ['granite', ['GraniteForCausalLM', GraniteForCausalLM]],\n ['cohere', ['CohereForCausalLM', CohereForCausalLM]],\n ['gemma', ['GemmaForCausalLM', GemmaForCausalLM]],\n ['gemma2', ['Gemma2ForCausalLM', Gemma2ForCausalLM]],\n ['openelm', ['OpenELMForCausalLM', OpenELMForCausalLM]],\n ['qwen2', ['Qwen2ForCausalLM', Qwen2ForCausalLM]],\n ['phi', ['PhiForCausalLM', PhiForCausalLM]],\n ['phi3', ['Phi3ForCausalLM', Phi3ForCausalLM]],\n ['mpt', ['MptForCausalLM', MptForCausalLM]],\n ['opt', ['OPTForCausalLM', OPTForCausalLM]],\n ['mbart', ['MBartForCausalLM', MBartForCausalLM]],\n ['mistral', ['MistralForCausalLM', MistralForCausalLM]],\n ['starcoder2', ['Starcoder2ForCausalLM', Starcoder2ForCausalLM]],\n ['falcon', ['FalconForCausalLM', FalconForCausalLM]],\n ['trocr', ['TrOCRForCausalLM', TrOCRForCausalLM]],\n ['stablelm', ['StableLmForCausalLM', StableLmForCausalLM]],\n]);\n\nconst MODEL_FOR_MASKED_LM_MAPPING_NAMES = new Map([\n ['bert', ['BertForMaskedLM', BertForMaskedLM]],\n ['roformer', ['RoFormerForMaskedLM', RoFormerForMaskedLM]],\n ['electra', ['ElectraForMaskedLM', ElectraForMaskedLM]],\n ['esm', ['EsmForMaskedLM', EsmForMaskedLM]],\n ['convbert', ['ConvBertForMaskedLM', ConvBertForMaskedLM]],\n ['camembert', ['CamembertForMaskedLM', CamembertForMaskedLM]],\n ['deberta', ['DebertaForMaskedLM', DebertaForMaskedLM]],\n ['deberta-v2', ['DebertaV2ForMaskedLM', DebertaV2ForMaskedLM]],\n ['mpnet', ['MPNetForMaskedLM', MPNetForMaskedLM]],\n ['albert', ['AlbertForMaskedLM', AlbertForMaskedLM]],\n ['distilbert', ['DistilBertForMaskedLM', DistilBertForMaskedLM]],\n ['roberta', ['RobertaForMaskedLM', RobertaForMaskedLM]],\n ['xlm', ['XLMWithLMHeadModel', XLMWithLMHeadModel]],\n ['xlm-roberta', ['XLMRobertaForMaskedLM', XLMRobertaForMaskedLM]],\n ['mobilebert', ['MobileBertForMaskedLM', MobileBertForMaskedLM]],\n ['squeezebert', ['SqueezeBertForMaskedLM', SqueezeBertForMaskedLM]],\n]);\n\nconst MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = new Map([\n ['bert', ['BertForQuestionAnswering', BertForQuestionAnswering]],\n ['roformer', ['RoFormerForQuestionAnswering', RoFormerForQuestionAnswering]],\n ['electra', ['ElectraForQuestionAnswering', ElectraForQuestionAnswering]],\n ['convbert', ['ConvBertForQuestionAnswering', ConvBertForQuestionAnswering]],\n ['camembert', ['CamembertForQuestionAnswering', CamembertForQuestionAnswering]],\n ['deberta', ['DebertaForQuestionAnswering', DebertaForQuestionAnswering]],\n ['deberta-v2', ['DebertaV2ForQuestionAnswering', DebertaV2ForQuestionAnswering]],\n ['mpnet', ['MPNetForQuestionAnswering', MPNetForQuestionAnswering]],\n ['albert', ['AlbertForQuestionAnswering', AlbertForQuestionAnswering]],\n ['distilbert', ['DistilBertForQuestionAnswering', DistilBertForQuestionAnswering]],\n ['roberta', ['RobertaForQuestionAnswering', RobertaForQuestionAnswering]],\n ['xlm', ['XLMForQuestionAnswering', XLMForQuestionAnswering]],\n ['xlm-roberta', ['XLMRobertaForQuestionAnswering', XLMRobertaForQuestionAnswering]],\n ['mobilebert', ['MobileBertForQuestionAnswering', MobileBertForQuestionAnswering]],\n ['squeezebert', ['SqueezeBertForQuestionAnswering', SqueezeBertForQuestionAnswering]],\n]);\n\nconst MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = new Map([\n ['vision-encoder-decoder', ['VisionEncoderDecoderModel', VisionEncoderDecoderModel]],\n]);\n\nconst MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES = new Map([\n ['llava', ['LlavaForConditionalGeneration', LlavaForConditionalGeneration]],\n ['moondream1', ['Moondream1ForConditionalGeneration', Moondream1ForConditionalGeneration]],\n ['florence2', ['Florence2ForConditionalGeneration', Florence2ForConditionalGeneration]],\n]);\n\nconst MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES = new Map([\n ['vision-encoder-decoder', ['VisionEncoderDecoderModel', VisionEncoderDecoderModel]],\n]);\n\nconst MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['vit', ['ViTForImageClassification', ViTForImageClassification]],\n ['pvt', ['PvtForImageClassification', PvtForImageClassification]],\n ['vit_msn', ['ViTMSNForImageClassification', ViTMSNForImageClassification]],\n ['fastvit', ['FastViTForImageClassification', FastViTForImageClassification]],\n ['mobilevit', ['MobileViTForImageClassification', MobileViTForImageClassification]],\n ['mobilevitv2', ['MobileViTV2ForImageClassification', MobileViTV2ForImageClassification]],\n ['beit', ['BeitForImageClassification', BeitForImageClassification]],\n ['deit', ['DeiTForImageClassification', DeiTForImageClassification]],\n ['hiera', ['HieraForImageClassification', HieraForImageClassification]],\n ['convnext', ['ConvNextForImageClassification', ConvNextForImageClassification]],\n ['convnextv2', ['ConvNextV2ForImageClassification', ConvNextV2ForImageClassification]],\n ['dinov2', ['Dinov2ForImageClassification', Dinov2ForImageClassification]],\n ['resnet', ['ResNetForImageClassification', ResNetForImageClassification]],\n ['swin', ['SwinForImageClassification', SwinForImageClassification]],\n ['segformer', ['SegformerForImageClassification', SegformerForImageClassification]],\n ['efficientnet', ['EfficientNetForImageClassification', EfficientNetForImageClassification]],\n ['mobilenet_v1', ['MobileNetV1ForImageClassification', MobileNetV1ForImageClassification]],\n ['mobilenet_v2', ['MobileNetV2ForImageClassification', MobileNetV2ForImageClassification]],\n ['mobilenet_v3', ['MobileNetV3ForImageClassification', MobileNetV3ForImageClassification]],\n ['mobilenet_v4', ['MobileNetV4ForImageClassification', MobileNetV4ForImageClassification]],\n]);\n\nconst MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = new Map([\n ['detr', ['DetrForObjectDetection', DetrForObjectDetection]],\n ['rt_detr', ['RTDetrForObjectDetection', RTDetrForObjectDetection]],\n ['table-transformer', ['TableTransformerForObjectDetection', TableTransformerForObjectDetection]],\n ['yolos', ['YolosForObjectDetection', YolosForObjectDetection]],\n]);\n\nconst MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = new Map([\n ['owlvit', ['OwlViTForObjectDetection', OwlViTForObjectDetection]],\n ['owlv2', ['Owlv2ForObjectDetection', Owlv2ForObjectDetection]],\n]);\n\nconst MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = new Map([\n // TODO: Do not add new models here\n ['detr', ['DetrForSegmentation', DetrForSegmentation]],\n ['clipseg', ['CLIPSegForImageSegmentation', CLIPSegForImageSegmentation]],\n]);\n\nconst MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = new Map([\n ['segformer', ['SegformerForSemanticSegmentation', SegformerForSemanticSegmentation]],\n ['sapiens', ['SapiensForSemanticSegmentation', SapiensForSemanticSegmentation]],\n]);\n\nconst MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES = new Map([\n ['detr', ['DetrForSegmentation', DetrForSegmentation]],\n ['maskformer', ['MaskFormerForInstanceSegmentation', MaskFormerForInstanceSegmentation]],\n]);\n\nconst MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = new Map([\n ['sam', ['SamModel', SamModel]],\n]);\n\nconst MODEL_FOR_CTC_MAPPING_NAMES = new Map([\n ['wav2vec2', ['Wav2Vec2ForCTC', Wav2Vec2ForCTC]],\n ['wav2vec2-bert', ['Wav2Vec2BertForCTC', Wav2Vec2BertForCTC]],\n ['unispeech', ['UniSpeechForCTC', UniSpeechForCTC]],\n ['unispeech-sat', ['UniSpeechSatForCTC', UniSpeechSatForCTC]],\n ['wavlm', ['WavLMForCTC', WavLMForCTC]],\n ['hubert', ['HubertForCTC', HubertForCTC]],\n]);\n\nconst MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['wav2vec2', ['Wav2Vec2ForSequenceClassification', Wav2Vec2ForSequenceClassification]],\n ['wav2vec2-bert', ['Wav2Vec2BertForSequenceClassification', Wav2Vec2BertForSequenceClassification]],\n ['unispeech', ['UniSpeechForSequenceClassification', UniSpeechForSequenceClassification]],\n ['unispeech-sat', ['UniSpeechSatForSequenceClassification', UniSpeechSatForSequenceClassification]],\n ['wavlm', ['WavLMForSequenceClassification', WavLMForSequenceClassification]],\n ['hubert', ['HubertForSequenceClassification', HubertForSequenceClassification]],\n ['audio-spectrogram-transformer', ['ASTForAudioClassification', ASTForAudioClassification]],\n]);\n\nconst MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES = new Map([\n ['wavlm', ['WavLMForXVector', WavLMForXVector]],\n]);\n\nconst MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['unispeech-sat', ['UniSpeechSatForAudioFrameClassification', UniSpeechSatForAudioFrameClassification]],\n ['wavlm', ['WavLMForAudioFrameClassification', WavLMForAudioFrameClassification]],\n ['wav2vec2', ['Wav2Vec2ForAudioFrameClassification', Wav2Vec2ForAudioFrameClassification]],\n ['pyannote', ['PyAnnoteForAudioFrameClassification', PyAnnoteForAudioFrameClassification]],\n]);\n\nconst MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES = new Map([\n ['vitmatte', ['VitMatteForImageMatting', VitMatteForImageMatting]],\n]);\n\nconst MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES = new Map([\n ['swin2sr', ['Swin2SRForImageSuperResolution', Swin2SRForImageSuperResolution]],\n])\n\nconst MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = new Map([\n ['dpt', ['DPTForDepthEstimation', DPTForDepthEstimation]],\n ['depth_anything', ['DepthAnythingForDepthEstimation', DepthAnythingForDepthEstimation]],\n ['glpn', ['GLPNForDepthEstimation', GLPNForDepthEstimation]],\n ['sapiens', ['SapiensForDepthEstimation', SapiensForDepthEstimation]],\n ['depth_pro', ['DepthProForDepthEstimation', DepthProForDepthEstimation]],\n])\n\nconst MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES = new Map([\n ['sapiens', ['SapiensForNormalEstimation', SapiensForNormalEstimation]],\n])\n\n// NOTE: This is custom to Transformers.js, and is necessary because certain models\n// (e.g., CLIP) are split into vision and text components\nconst MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES = new Map([\n ['clip', ['CLIPVisionModelWithProjection', CLIPVisionModelWithProjection]],\n ['siglip', ['SiglipVisionModel', SiglipVisionModel]],\n])\n\nconst MODEL_CLASS_TYPE_MAPPING = [\n [MODEL_MAPPING_NAMES_ENCODER_ONLY, MODEL_TYPES.EncoderOnly],\n [MODEL_MAPPING_NAMES_ENCODER_DECODER, MODEL_TYPES.EncoderDecoder],\n [MODEL_MAPPING_NAMES_DECODER_ONLY, MODEL_TYPES.DecoderOnly],\n [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],\n [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],\n [MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.DecoderOnly],\n [MODEL_FOR_MASKED_LM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Vision2Seq],\n [MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES, MODEL_TYPES.ImageTextToText],\n [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES, MODEL_TYPES.MaskGeneration],\n [MODEL_FOR_CTC_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],\n [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n\n // Custom:\n [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n];\n\nfor (const [mappings, type] of MODEL_CLASS_TYPE_MAPPING) {\n // @ts-ignore\n for (const [name, model] of mappings.values()) {\n MODEL_TYPE_MAPPING.set(name, type);\n MODEL_CLASS_TO_NAME_MAPPING.set(model, name);\n MODEL_NAME_TO_CLASS_MAPPING.set(name, model);\n }\n}\n\nconst CUSTOM_MAPPING = [\n // OVERRIDE:\n // TODO: Refactor to allow class to specify model\n ['MusicgenForConditionalGeneration', MusicgenForConditionalGeneration, MODEL_TYPES.Musicgen],\n\n ['CLIPTextModelWithProjection', CLIPTextModelWithProjection, MODEL_TYPES.EncoderOnly],\n ['SiglipTextModel', SiglipTextModel, MODEL_TYPES.EncoderOnly],\n ['ClapTextModelWithProjection', ClapTextModelWithProjection, MODEL_TYPES.EncoderOnly],\n ['ClapAudioModelWithProjection', ClapAudioModelWithProjection, MODEL_TYPES.EncoderOnly],\n]\nfor (const [name, model, type] of CUSTOM_MAPPING) {\n MODEL_TYPE_MAPPING.set(name, type);\n MODEL_CLASS_TO_NAME_MAPPING.set(model, name);\n MODEL_NAME_TO_CLASS_MAPPING.set(name, model);\n}\n\n\n/**\n * Helper class which is used to instantiate pretrained models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModel.from_pretrained('Xenova/bert-base-uncased');\n */\nexport class AutoModel extends PretrainedMixin {\n /** @type {Map[]} */\n // @ts-ignore\n static MODEL_CLASS_MAPPINGS = MODEL_CLASS_TYPE_MAPPING.map(x => x[0]);\n static BASE_IF_FAIL = true;\n}\n\n/**\n * Helper class which is used to instantiate pretrained sequence classification models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForSequenceClassification.from_pretrained('Xenova/distilbert-base-uncased-finetuned-sst-2-english');\n */\nexport class AutoModelForSequenceClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained token classification models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForTokenClassification.from_pretrained('Xenova/distilbert-base-multilingual-cased-ner-hrl');\n */\nexport class AutoModelForTokenClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained sequence-to-sequence models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForSeq2SeqLM.from_pretrained('Xenova/t5-small');\n */\nexport class AutoModelForSeq2SeqLM extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained sequence-to-sequence speech-to-text models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForSpeechSeq2Seq.from_pretrained('openai/whisper-tiny.en');\n */\nexport class AutoModelForSpeechSeq2Seq extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained sequence-to-sequence text-to-spectrogram models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForTextToSpectrogram.from_pretrained('microsoft/speecht5_tts');\n */\nexport class AutoModelForTextToSpectrogram extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained text-to-waveform models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForTextToSpectrogram.from_pretrained('facebook/mms-tts-eng');\n */\nexport class AutoModelForTextToWaveform extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained causal language models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForCausalLM.from_pretrained('Xenova/gpt2');\n */\nexport class AutoModelForCausalLM extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_CAUSAL_LM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained masked language models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForMaskedLM.from_pretrained('Xenova/bert-base-uncased');\n */\nexport class AutoModelForMaskedLM extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_MASKED_LM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained question answering models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForQuestionAnswering.from_pretrained('Xenova/distilbert-base-cased-distilled-squad');\n */\nexport class AutoModelForQuestionAnswering extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained vision-to-sequence models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForVision2Seq.from_pretrained('Xenova/vit-gpt2-image-captioning');\n */\nexport class AutoModelForVision2Seq extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained image classification models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForImageClassification.from_pretrained('Xenova/vit-base-patch16-224');\n */\nexport class AutoModelForImageClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained image segmentation models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForImageSegmentation.from_pretrained('Xenova/detr-resnet-50-panoptic');\n */\nexport class AutoModelForImageSegmentation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained image segmentation models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForSemanticSegmentation.from_pretrained('nvidia/segformer-b3-finetuned-cityscapes-1024-1024');\n */\nexport class AutoModelForSemanticSegmentation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained universal image segmentation models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForUniversalSegmentation.from_pretrained('hf-internal-testing/tiny-random-MaskFormerForInstanceSegmentation');\n */\nexport class AutoModelForUniversalSegmentation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained object detection models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForObjectDetection.from_pretrained('Xenova/detr-resnet-50');\n */\nexport class AutoModelForObjectDetection extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES];\n}\n\nexport class AutoModelForZeroShotObjectDetection extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES];\n}\n\n\n/**\n * Helper class which is used to instantiate pretrained mask generation models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForMaskGeneration.from_pretrained('Xenova/sam-vit-base');\n */\nexport class AutoModelForMaskGeneration extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForCTC extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_CTC_MAPPING_NAMES];\n}\n\nexport class AutoModelForAudioClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForXVector extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES];\n}\n\nexport class AutoModelForAudioFrameClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForDocumentQuestionAnswering extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES];\n}\n\nexport class AutoModelForImageMatting extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES];\n}\n\nexport class AutoModelForImageToImage extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES];\n}\n\nexport class AutoModelForDepthEstimation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForNormalEstimation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForImageFeatureExtraction extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES];\n}\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class Seq2SeqLMOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits The output logits of the model.\n * @param {Tensor} output.past_key_values An tensor of key/value pairs that represent the previous state of the model.\n * @param {Tensor} output.encoder_outputs The output of the encoder in a sequence-to-sequence model.\n * @param {Tensor} [output.decoder_attentions] Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.\n * @param {Tensor} [output.cross_attentions] Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.\n */\n constructor({ logits, past_key_values, encoder_outputs, decoder_attentions = null, cross_attentions = null }) {\n super();\n this.logits = logits;\n this.past_key_values = past_key_values;\n this.encoder_outputs = encoder_outputs;\n this.decoder_attentions = decoder_attentions;\n this.cross_attentions = cross_attentions;\n }\n}\n\n/**\n * Base class for outputs of sentence classification models.\n */\nexport class SequenceClassifierOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits classification (or regression if config.num_labels==1) scores (before SoftMax).\n */\n constructor({ logits }) {\n super();\n this.logits = logits;\n }\n}\n\n/**\n * Base class for outputs of XVector models.\n */\nexport class XVectorOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification hidden states before AMSoftmax, of shape `(batch_size, config.xvector_output_dim)`.\n * @param {Tensor} output.embeddings Utterance embeddings used for vector similarity-based retrieval, of shape `(batch_size, config.xvector_output_dim)`.\n */\n constructor({ logits, embeddings }) {\n super();\n this.logits = logits;\n this.embeddings = embeddings;\n }\n}\n\n/**\n * Base class for outputs of token classification models.\n */\nexport class TokenClassifierOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification scores (before SoftMax).\n */\n constructor({ logits }) {\n super();\n this.logits = logits;\n }\n}\n\n/**\n * Base class for masked language models outputs.\n */\nexport class MaskedLMOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).\n */\n constructor({ logits }) {\n super();\n this.logits = logits;\n }\n}\n\n/**\n * Base class for outputs of question answering models.\n */\nexport class QuestionAnsweringModelOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.start_logits Span-start scores (before SoftMax).\n * @param {Tensor} output.end_logits Span-end scores (before SoftMax).\n */\n constructor({ start_logits, end_logits }) {\n super();\n this.start_logits = start_logits;\n this.end_logits = end_logits;\n }\n}\n\n\n/**\n * Base class for causal language model (or autoregressive) outputs.\n */\nexport class CausalLMOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax).\n */\n constructor({ logits }) {\n super();\n this.logits = logits;\n }\n}\n\n/**\n * Base class for causal language model (or autoregressive) outputs.\n */\nexport class CausalLMOutputWithPast extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax).\n * @param {Tensor} output.past_key_values Contains pre-computed hidden-states (key and values in the self-attention blocks)\n * that can be used (see `past_key_values` input) to speed up sequential decoding.\n */\n constructor({ logits, past_key_values }) {\n super();\n this.logits = logits;\n this.past_key_values = past_key_values;\n }\n}\n\nexport class ImageMattingOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.alphas Estimated alpha values, of shape `(batch_size, num_channels, height, width)`.\n */\n constructor({ alphas }) {\n super();\n this.alphas = alphas;\n }\n}\n\n/**\n * Describes the outputs for the VITS model.\n */\nexport class VitsModelOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.waveform The final audio waveform predicted by the model, of shape `(batch_size, sequence_length)`.\n * @param {Tensor} output.spectrogram The log-mel spectrogram predicted at the output of the flow model.\n * This spectrogram is passed to the Hi-Fi GAN decoder model to obtain the final audio waveform.\n */\n constructor({ waveform, spectrogram }) {\n super();\n this.waveform = waveform;\n this.spectrogram = spectrogram;\n }\n}\n","\n\nconst WHISPER_LANGUAGES = [\n [\"en\", \"english\"],\n [\"zh\", \"chinese\"],\n [\"de\", \"german\"],\n [\"es\", \"spanish\"],\n [\"ru\", \"russian\"],\n [\"ko\", \"korean\"],\n [\"fr\", \"french\"],\n [\"ja\", \"japanese\"],\n [\"pt\", \"portuguese\"],\n [\"tr\", \"turkish\"],\n [\"pl\", \"polish\"],\n [\"ca\", \"catalan\"],\n [\"nl\", \"dutch\"],\n [\"ar\", \"arabic\"],\n [\"sv\", \"swedish\"],\n [\"it\", \"italian\"],\n [\"id\", \"indonesian\"],\n [\"hi\", \"hindi\"],\n [\"fi\", \"finnish\"],\n [\"vi\", \"vietnamese\"],\n [\"he\", \"hebrew\"],\n [\"uk\", \"ukrainian\"],\n [\"el\", \"greek\"],\n [\"ms\", \"malay\"],\n [\"cs\", \"czech\"],\n [\"ro\", \"romanian\"],\n [\"da\", \"danish\"],\n [\"hu\", \"hungarian\"],\n [\"ta\", \"tamil\"],\n [\"no\", \"norwegian\"],\n [\"th\", \"thai\"],\n [\"ur\", \"urdu\"],\n [\"hr\", \"croatian\"],\n [\"bg\", \"bulgarian\"],\n [\"lt\", \"lithuanian\"],\n [\"la\", \"latin\"],\n [\"mi\", \"maori\"],\n [\"ml\", \"malayalam\"],\n [\"cy\", \"welsh\"],\n [\"sk\", \"slovak\"],\n [\"te\", \"telugu\"],\n [\"fa\", \"persian\"],\n [\"lv\", \"latvian\"],\n [\"bn\", \"bengali\"],\n [\"sr\", \"serbian\"],\n [\"az\", \"azerbaijani\"],\n [\"sl\", \"slovenian\"],\n [\"kn\", \"kannada\"],\n [\"et\", \"estonian\"],\n [\"mk\", \"macedonian\"],\n [\"br\", \"breton\"],\n [\"eu\", \"basque\"],\n [\"is\", \"icelandic\"],\n [\"hy\", \"armenian\"],\n [\"ne\", \"nepali\"],\n [\"mn\", \"mongolian\"],\n [\"bs\", \"bosnian\"],\n [\"kk\", \"kazakh\"],\n [\"sq\", \"albanian\"],\n [\"sw\", \"swahili\"],\n [\"gl\", \"galician\"],\n [\"mr\", \"marathi\"],\n [\"pa\", \"punjabi\"],\n [\"si\", \"sinhala\"],\n [\"km\", \"khmer\"],\n [\"sn\", \"shona\"],\n [\"yo\", \"yoruba\"],\n [\"so\", \"somali\"],\n [\"af\", \"afrikaans\"],\n [\"oc\", \"occitan\"],\n [\"ka\", \"georgian\"],\n [\"be\", \"belarusian\"],\n [\"tg\", \"tajik\"],\n [\"sd\", \"sindhi\"],\n [\"gu\", \"gujarati\"],\n [\"am\", \"amharic\"],\n [\"yi\", \"yiddish\"],\n [\"lo\", \"lao\"],\n [\"uz\", \"uzbek\"],\n [\"fo\", \"faroese\"],\n [\"ht\", \"haitian creole\"],\n [\"ps\", \"pashto\"],\n [\"tk\", \"turkmen\"],\n [\"nn\", \"nynorsk\"],\n [\"mt\", \"maltese\"],\n [\"sa\", \"sanskrit\"],\n [\"lb\", \"luxembourgish\"],\n [\"my\", \"myanmar\"],\n [\"bo\", \"tibetan\"],\n [\"tl\", \"tagalog\"],\n [\"mg\", \"malagasy\"],\n [\"as\", \"assamese\"],\n [\"tt\", \"tatar\"],\n [\"haw\", \"hawaiian\"],\n [\"ln\", \"lingala\"],\n [\"ha\", \"hausa\"],\n [\"ba\", \"bashkir\"],\n [\"jw\", \"javanese\"],\n [\"su\", \"sundanese\"],\n]\n\n// @ts-ignore\nexport const WHISPER_LANGUAGE_MAPPING = new Map(WHISPER_LANGUAGES);\n// @ts-ignore\nexport const WHISPER_TO_LANGUAGE_CODE_MAPPING = new Map([\n ...WHISPER_LANGUAGES.map(([k, v]) => [v, k]),\n ...[\n [\"burmese\", \"my\"],\n [\"valencian\", \"ca\"],\n [\"flemish\", \"nl\"],\n [\"haitian\", \"ht\"],\n [\"letzeburgesch\", \"lb\"],\n [\"pushto\", \"ps\"],\n [\"panjabi\", \"pa\"],\n [\"moldavian\", \"ro\"],\n [\"moldovan\", \"ro\"],\n [\"sinhalese\", \"si\"],\n [\"castilian\", \"es\"],\n ]\n]);\n\n/**\n * @param {string} language The language name or code\n * @returns {string} The language code\n */\nexport function whisper_language_to_code(language) {\n language = language.toLowerCase();\n\n // Map to code from user-friendly name (e.g., \"english\" -> \"en\")\n let language_code = WHISPER_TO_LANGUAGE_CODE_MAPPING.get(language);\n\n if (language_code === undefined) {\n // User provided something that is not a language name\n\n if (WHISPER_LANGUAGE_MAPPING.has(language)) {\n // User provided the language code directly (e.g., \"en\")\n language_code = language;\n\n } else {\n // User provided something that is not a language code or name\n const is_language_code = language.length === 2;\n const langs = is_language_code ? WHISPER_LANGUAGE_MAPPING.keys() : WHISPER_LANGUAGE_MAPPING.values();\n\n throw new Error(`Language \"${language}\" is not supported. Must be one of: ${JSON.stringify(langs)}`);\n }\n }\n return language_code;\n}\n","import { GenerationConfig } from \"../../generation/configuration_utils.js\";\n\nexport class WhisperGenerationConfig extends GenerationConfig {\n\n /**\n * Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`.\n * @type {boolean}\n */\n return_timestamps = null;\n\n /**\n * Whether to return token-level timestamps\n * with the text. This can be used with or without the `return_timestamps` option. To get word-level\n * timestamps, use the tokenizer to group the tokens into words.\n * @type {boolean}\n */\n return_token_timestamps = null;\n\n /**\n * The number of audio frames available in this chunk. This is only used generating word-level timestamps.\n * @type {number}\n */\n num_frames = null;\n\n /**\n * Alignment heads to predict word-level timestamps. This is a list of [layer, head] pairs that\n * select the cross-attention heads that are highly correlated to word-level timing.\n * @type {[number, number][]}\n */\n alignment_heads = null;\n\n /**\n * Task to use for generation, either \"translate\" or \"transcribe\".\n * @type {string}\n */\n task = null;\n\n /**\n * Language token to use for generation, can be either in the form of `<|en|>`, `en` or `english`.\n * You can find all the possible language tokens in the `model.generation_config.lang_to_id` dictionary.\n * @type {string}\n */\n language = null;\n\n /**\n * The id of the `\"<|notimestamps|>\"` token.\n * @type {number}\n */\n no_timestamps_token_id = null;\n\n /**\n * Rank-1 list of token IDs created by passing text to [`~WhisperProcessor.get_prompt_ids`] that is\n * provided as a prompt to each chunk. This can be used to provide or \"prompt-engineer\" a context for\n * transcription, e.g. custom vocabularies or proper nouns to make it more likely to predict those words\n * correctly. It cannot be used in conjunction with `decoder_start_token_id` as it overwrites this value.\n * @type {number[]}\n */\n prompt_ids = null;\n\n /**\n * Whether the model is multilingual or not.\n * @type {boolean}\n */\n is_multilingual = null;\n\n /**\n * (Optional) A mapping from language tokens to their corresponding IDs.\n * Only required if the model is multilingual.\n * @type {Record|null}\n */\n lang_to_id = null;\n\n /**\n * (Optional) A mapping from task tokens to their corresponding IDs.\n * @type {Record|null}\n */\n task_to_id = null;\n\n /**\n * Used to set the maximum value of the initial timestamp. This is used to prevent the model from\n * predicting timestamps that are too far in the future.\n * @type {number}\n */\n max_initial_timestamp_index = 1;\n}\n\n/**\n * @typedef {import('../../generation/parameters.js').GenerationFunctionParameters & {generation_config: WhisperGenerationConfig} & WhisperGenerationConfig} WhisperGenerationFunctionParameters\n */\n","import { createInferenceSession } from \"../backends/onnx.js\";\nimport { Tensor } from \"../utils/tensor.js\";\n\n/**\n * Asynchronously creates a wrapper function for running an ONNX inference session.\n *\n * @param {number[]} session_bytes The session data in bytes.\n * @param {import('onnxruntime-common').InferenceSession.SessionOptions} session_options The options for the ONNX session.\n * @template {string | [string] | string[]} T\n * @param {T} names The name(s) of the output tensor(s).\n * \n * @returns {Promise): Promise>}\n * The wrapper function for running the ONNX inference session.\n */\nconst wrap = async (session_bytes, session_options, names) => {\n const session = await createInferenceSession(\n new Uint8Array(session_bytes), session_options,\n );\n return /** @type {any} */(async (/** @type {Record} */ inputs) => {\n const ortFeed = Object.fromEntries(Object.entries(inputs).map(([k, v]) => [k, v.ort_tensor]));\n const outputs = await session.run(ortFeed);\n\n if (Array.isArray(names)) {\n return names.map((n) => new Tensor(outputs[n]));\n } else {\n return new Tensor(outputs[/** @type {string} */(names)]);\n }\n })\n}\n\n// In-memory registry of initialized ONNX operators\nexport class TensorOpRegistry {\n static session_options = {\n // TODO: Allow for multiple execution providers\n // executionProviders: ['webgpu'],\n };\n\n static get bilinear_interpolate_4d() {\n if (!this._bilinear_interpolate_4d) {\n this._bilinear_interpolate_4d = wrap(\n [8, 9, 18, 0, 58, 128, 1, 10, 40, 10, 1, 120, 10, 0, 10, 0, 10, 1, 115, 18, 1, 121, 34, 6, 82, 101, 115, 105, 122, 101, 42, 17, 10, 4, 109, 111, 100, 101, 34, 6, 108, 105, 110, 101, 97, 114, 160, 1, 3, 18, 1, 114, 90, 31, 10, 1, 120, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 90, 15, 10, 1, 115, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 4, 98, 31, 10, 1, 121, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 66, 2, 16, 20],\n this.session_options,\n 'y',\n );\n }\n return this._bilinear_interpolate_4d;\n }\n\n static get bicubic_interpolate_4d() {\n if (!this._bicubic_interpolate_4d) {\n this._bicubic_interpolate_4d = wrap(\n [8, 9, 18, 0, 58, 127, 10, 39, 10, 1, 120, 10, 0, 10, 0, 10, 1, 115, 18, 1, 121, 34, 6, 82, 101, 115, 105, 122, 101, 42, 16, 10, 4, 109, 111, 100, 101, 34, 5, 99, 117, 98, 105, 99, 160, 1, 3, 18, 1, 114, 90, 31, 10, 1, 120, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 90, 15, 10, 1, 115, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 4, 98, 31, 10, 1, 121, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 66, 2, 16, 20],\n this.session_options,\n 'y',\n );\n }\n return this._bicubic_interpolate_4d;\n }\n\n static get matmul() {\n if (!this._matmul) {\n this._matmul = wrap(\n [8, 9, 18, 0, 58, 55, 10, 17, 10, 1, 97, 10, 1, 98, 18, 1, 99, 34, 6, 77, 97, 116, 77, 117, 108, 18, 1, 114, 90, 9, 10, 1, 97, 18, 4, 10, 2, 8, 1, 90, 9, 10, 1, 98, 18, 4, 10, 2, 8, 1, 98, 9, 10, 1, 99, 18, 4, 10, 2, 8, 1, 66, 2, 16, 20],\n this.session_options,\n 'c',\n );\n }\n return this._matmul;\n }\n\n static get stft() {\n if (!this._stft) {\n this._stft = wrap(\n [8, 7, 18, 0, 58, 148, 1, 10, 38, 10, 1, 115, 10, 1, 106, 10, 1, 119, 10, 1, 108, 18, 1, 111, 34, 4, 83, 84, 70, 84, 42, 15, 10, 8, 111, 110, 101, 115, 105, 100, 101, 100, 24, 1, 160, 1, 2, 18, 1, 115, 90, 26, 10, 1, 115, 18, 21, 10, 19, 8, 1, 18, 15, 10, 3, 18, 1, 98, 10, 3, 18, 1, 115, 10, 3, 18, 1, 99, 90, 11, 10, 1, 106, 18, 6, 10, 4, 8, 7, 18, 0, 90, 16, 10, 1, 119, 18, 11, 10, 9, 8, 1, 18, 5, 10, 3, 18, 1, 119, 90, 11, 10, 1, 108, 18, 6, 10, 4, 8, 7, 18, 0, 98, 31, 10, 1, 111, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 102, 10, 3, 18, 1, 100, 10, 3, 18, 1, 99, 66, 2, 16, 17],\n this.session_options,\n 'o',\n )\n }\n return this._stft;\n }\n\n static get rfft() {\n if (!this._rfft) {\n this._rfft = wrap(\n [8, 9, 18, 0, 58, 97, 10, 33, 10, 1, 120, 10, 0, 10, 1, 97, 18, 1, 121, 34, 3, 68, 70, 84, 42, 15, 10, 8, 111, 110, 101, 115, 105, 100, 101, 100, 24, 1, 160, 1, 2, 18, 1, 100, 90, 21, 10, 1, 120, 18, 16, 10, 14, 8, 1, 18, 10, 10, 3, 18, 1, 115, 10, 3, 18, 1, 99, 90, 11, 10, 1, 97, 18, 6, 10, 4, 8, 7, 18, 0, 98, 21, 10, 1, 121, 18, 16, 10, 14, 8, 1, 18, 10, 10, 3, 18, 1, 115, 10, 3, 18, 1, 99, 66, 2, 16, 20],\n this.session_options,\n 'y',\n )\n }\n return this._rfft;\n }\n\n static get top_k() {\n if (!this._top_k) {\n this._top_k = wrap(\n [8, 10, 18, 0, 58, 73, 10, 18, 10, 1, 120, 10, 1, 107, 18, 1, 118, 18, 1, 105, 34, 4, 84, 111, 112, 75, 18, 1, 116, 90, 9, 10, 1, 120, 18, 4, 10, 2, 8, 1, 90, 15, 10, 1, 107, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 1, 98, 9, 10, 1, 118, 18, 4, 10, 2, 8, 1, 98, 9, 10, 1, 105, 18, 4, 10, 2, 8, 7, 66, 2, 16, 21],\n this.session_options,\n [ /* Values */ 'v', /* Indices */ 'i']\n )\n }\n return this._top_k;\n }\n}\n","/**\n * @file Pipelines provide a high-level, easy to use, API for running machine learning models.\n * \n * **Example:** Instantiate pipeline using the `pipeline` function.\n * ```javascript\n * import { pipeline } from '@huggingface/transformers';\n * \n * const classifier = await pipeline('sentiment-analysis');\n * const output = await classifier('I love transformers!');\n * // [{'label': 'POSITIVE', 'score': 0.999817686}]\n * ```\n * \n * @module pipelines\n */\n\nimport {\n AutoTokenizer,\n PreTrainedTokenizer,\n} from './tokenizers.js';\nimport {\n AutoModel,\n AutoModelForSequenceClassification,\n AutoModelForAudioClassification,\n AutoModelForTokenClassification,\n AutoModelForQuestionAnswering,\n AutoModelForMaskedLM,\n AutoModelForSeq2SeqLM,\n AutoModelForSpeechSeq2Seq,\n AutoModelForTextToWaveform,\n AutoModelForTextToSpectrogram,\n AutoModelForCTC,\n AutoModelForCausalLM,\n AutoModelForVision2Seq,\n AutoModelForImageClassification,\n AutoModelForImageSegmentation,\n AutoModelForSemanticSegmentation,\n AutoModelForUniversalSegmentation,\n AutoModelForObjectDetection,\n AutoModelForZeroShotObjectDetection,\n AutoModelForDocumentQuestionAnswering,\n AutoModelForImageToImage,\n AutoModelForDepthEstimation,\n AutoModelForImageFeatureExtraction,\n PreTrainedModel,\n} from './models.js';\nimport {\n AutoProcessor,\n Processor\n} from './processors.js';\n\nimport {\n Callable,\n} from './utils/generic.js';\n\nimport {\n dispatchCallback,\n pop,\n product,\n} from './utils/core.js';\nimport {\n softmax,\n max,\n round,\n} from './utils/maths.js';\nimport {\n read_audio\n} from './utils/audio.js';\nimport {\n Tensor,\n mean_pooling,\n interpolate,\n quantize_embeddings,\n topk,\n} from './utils/tensor.js';\nimport { RawImage } from './utils/image.js';\n\n\n/**\n * @typedef {string | RawImage | URL} ImageInput\n * @typedef {ImageInput|ImageInput[]} ImagePipelineInputs\n */\n\n/**\n * Prepare images for further tasks.\n * @param {ImagePipelineInputs} images images to prepare.\n * @returns {Promise} returns processed images.\n * @private\n */\nasync function prepareImages(images) {\n if (!Array.isArray(images)) {\n images = [images];\n }\n\n // Possibly convert any non-images to images\n return await Promise.all(images.map(x => RawImage.read(x)));\n}\n\n/**\n * @typedef {string | URL | Float32Array | Float64Array} AudioInput\n * @typedef {AudioInput|AudioInput[]} AudioPipelineInputs\n */\n\n/**\n * Prepare audios for further tasks.\n * @param {AudioPipelineInputs} audios audios to prepare.\n * @param {number} sampling_rate sampling rate of the audios.\n * @returns {Promise} The preprocessed audio data.\n * @private\n */\nasync function prepareAudios(audios, sampling_rate) {\n if (!Array.isArray(audios)) {\n audios = [audios];\n }\n\n return await Promise.all(audios.map(x => {\n if (typeof x === 'string' || x instanceof URL) {\n return read_audio(x, sampling_rate);\n } else if (x instanceof Float64Array) {\n return new Float32Array(x);\n }\n return x;\n }));\n}\n\n/**\n * @typedef {Object} BoundingBox\n * @property {number} xmin The minimum x coordinate of the bounding box.\n * @property {number} ymin The minimum y coordinate of the bounding box.\n * @property {number} xmax The maximum x coordinate of the bounding box.\n * @property {number} ymax The maximum y coordinate of the bounding box.\n */\n\n/**\n * Helper function to convert list [xmin, xmax, ymin, ymax] into object { \"xmin\": xmin, ... }\n * @param {number[]} box The bounding box as a list.\n * @param {boolean} asInteger Whether to cast to integers.\n * @returns {BoundingBox} The bounding box as an object.\n * @private\n */\nfunction get_bounding_box(box, asInteger) {\n if (asInteger) {\n box = box.map(x => x | 0);\n }\n const [xmin, ymin, xmax, ymax] = box;\n\n return { xmin, ymin, xmax, ymax };\n}\n\n\n/**\n * @callback DisposeType Disposes the item.\n * @returns {Promise} A promise that resolves when the item has been disposed.\n * \n * @typedef {Object} Disposable\n * @property {DisposeType} dispose A promise that resolves when the pipeline has been disposed.\n */\n\n/**\n * The Pipeline class is the class from which all pipelines inherit.\n * Refer to this class for methods shared across different pipelines.\n * @extends Callable\n */\nexport class Pipeline extends Callable {\n /**\n * Create a new Pipeline.\n * @param {Object} options An object containing the following properties:\n * @param {string} [options.task] The task of the pipeline. Useful for specifying subtasks.\n * @param {PreTrainedModel} [options.model] The model used by the pipeline.\n * @param {PreTrainedTokenizer} [options.tokenizer=null] The tokenizer used by the pipeline (if any).\n * @param {Processor} [options.processor=null] The processor used by the pipeline (if any).\n */\n constructor({ task, model, tokenizer = null, processor = null }) {\n super();\n this.task = task;\n this.model = model;\n this.tokenizer = tokenizer;\n this.processor = processor;\n }\n\n /** @type {DisposeType} */\n async dispose() {\n await this.model.dispose();\n }\n}\n\n/**\n * @typedef {Object} ModelTokenizerConstructorArgs\n * @property {string} task The task of the pipeline. Useful for specifying subtasks.\n * @property {PreTrainedModel} model The model used by the pipeline.\n * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline.\n * \n * @typedef {ModelTokenizerConstructorArgs} TextPipelineConstructorArgs An object used to instantiate a text-based pipeline.\n */\n\n/**\n * @typedef {Object} ModelProcessorConstructorArgs\n * @property {string} task The task of the pipeline. Useful for specifying subtasks.\n * @property {PreTrainedModel} model The model used by the pipeline.\n * @property {Processor} processor The processor used by the pipeline.\n * \n * @typedef {ModelProcessorConstructorArgs} AudioPipelineConstructorArgs An object used to instantiate an audio-based pipeline.\n * @typedef {ModelProcessorConstructorArgs} ImagePipelineConstructorArgs An object used to instantiate an image-based pipeline.\n */\n\n\n/**\n * @typedef {Object} ModelTokenizerProcessorConstructorArgs\n * @property {string} task The task of the pipeline. Useful for specifying subtasks.\n * @property {PreTrainedModel} model The model used by the pipeline.\n * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline.\n * @property {Processor} processor The processor used by the pipeline.\n * \n * @typedef {ModelTokenizerProcessorConstructorArgs} TextAudioPipelineConstructorArgs An object used to instantiate a text- and audio-based pipeline.\n * @typedef {ModelTokenizerProcessorConstructorArgs} TextImagePipelineConstructorArgs An object used to instantiate a text- and image-based pipeline.\n */\n\n/**\n * @typedef {Object} TextClassificationSingle\n * @property {string} label The label predicted.\n * @property {number} score The corresponding probability.\n * @typedef {TextClassificationSingle[]} TextClassificationOutput\n * \n * @typedef {Object} TextClassificationPipelineOptions Parameters specific to text classification pipelines.\n * @property {number} [top_k=1] The number of top predictions to be returned.\n * \n * @callback TextClassificationPipelineCallback Classify the text(s) given as inputs.\n * @param {string|string[]} texts The input text(s) to be classified.\n * @param {TextClassificationPipelineOptions} [options] The options to use for text classification.\n * @returns {Promise} An array or object containing the predicted labels and scores.\n * \n * @typedef {TextPipelineConstructorArgs & TextClassificationPipelineCallback & Disposable} TextClassificationPipelineType\n */\n\n/**\n * Text classification pipeline using any `ModelForSequenceClassification`.\n *\n * **Example:** Sentiment-analysis w/ `Xenova/distilbert-base-uncased-finetuned-sst-2-english`.\n * ```javascript\n * const classifier = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english');\n * const output = await classifier('I love transformers!');\n * // [{ label: 'POSITIVE', score: 0.999788761138916 }]\n * ```\n * \n * **Example:** Multilingual sentiment-analysis w/ `Xenova/bert-base-multilingual-uncased-sentiment` (and return top 5 classes).\n * ```javascript\n * const classifier = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment');\n * const output = await classifier('Le meilleur film de tous les temps.', { top_k: 5 });\n * // [\n * // { label: '5 stars', score: 0.9610759615898132 },\n * // { label: '4 stars', score: 0.03323351591825485 },\n * // { label: '3 stars', score: 0.0036155181005597115 },\n * // { label: '1 star', score: 0.0011325967498123646 },\n * // { label: '2 stars', score: 0.0009423971059732139 }\n * // ]\n * ```\n * \n * **Example:** Toxic comment classification w/ `Xenova/toxic-bert` (and return all classes).\n * ```javascript\n * const classifier = await pipeline('text-classification', 'Xenova/toxic-bert');\n * const output = await classifier('I hate you!', { top_k: null });\n * // [\n * // { label: 'toxic', score: 0.9593140482902527 },\n * // { label: 'insult', score: 0.16187334060668945 },\n * // { label: 'obscene', score: 0.03452680632472038 },\n * // { label: 'identity_hate', score: 0.0223250575363636 },\n * // { label: 'threat', score: 0.019197041168808937 },\n * // { label: 'severe_toxic', score: 0.005651099607348442 }\n * // ]\n * ```\n */\nexport class TextClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TextClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new TextClassificationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {TextClassificationPipelineCallback} */\n async _call(texts, {\n top_k = 1\n } = {}) {\n\n // Run tokenization\n const model_inputs = this.tokenizer(texts, {\n padding: true,\n truncation: true,\n });\n\n // Run model\n const outputs = await this.model(model_inputs)\n\n // TODO: Use softmax tensor function\n const function_to_apply =\n this.model.config.problem_type === 'multi_label_classification'\n ? batch => batch.sigmoid()\n : batch => new Tensor(\n 'float32',\n softmax(batch.data),\n batch.dims,\n ); // single_label_classification (default)\n\n const id2label = this.model.config.id2label;\n\n const toReturn = [];\n for (const batch of outputs.logits) {\n const output = function_to_apply(batch);\n\n const scores = await topk(output, top_k);\n\n const values = scores[0].tolist();\n const indices = scores[1].tolist();\n const vals = indices.map((x, i) => ({\n label: id2label ? id2label[x] : `LABEL_${x}`,\n score: values[i],\n }));\n if (top_k === 1) {\n toReturn.push(...vals);\n } else {\n toReturn.push(vals);\n }\n }\n\n return Array.isArray(texts) || top_k === 1 ? /** @type {TextClassificationOutput} */ (toReturn) : /** @type {TextClassificationOutput[]} */ (toReturn)[0];\n }\n}\n\n/**\n * @typedef {Object} TokenClassificationSingle\n * @property {string} word The token/word classified. This is obtained by decoding the selected tokens.\n * @property {number} score The corresponding probability for `entity`.\n * @property {string} entity The entity predicted for that token/word.\n * @property {number} index The index of the corresponding token in the sentence.\n * @property {number} [start] The index of the start of the corresponding entity in the sentence.\n * @property {number} [end] The index of the end of the corresponding entity in the sentence.\n * @typedef {TokenClassificationSingle[]} TokenClassificationOutput\n * \n * @typedef {Object} TokenClassificationPipelineOptions Parameters specific to token classification pipelines.\n * @property {string[]} [ignore_labels] A list of labels to ignore.\n * \n * @callback TokenClassificationPipelineCallback Classify each token of the text(s) given as inputs.\n * @param {string|string[]} texts One or several texts (or one list of texts) for token classification.\n * @param {TokenClassificationPipelineOptions} [options] The options to use for token classification.\n * @returns {Promise} The result.\n * \n * @typedef {TextPipelineConstructorArgs & TokenClassificationPipelineCallback & Disposable} TokenClassificationPipelineType\n */\n\n/**\n * Named Entity Recognition pipeline using any `ModelForTokenClassification`.\n * \n * **Example:** Perform named entity recognition with `Xenova/bert-base-NER`.\n * ```javascript\n * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER');\n * const output = await classifier('My name is Sarah and I live in London');\n * // [\n * // { entity: 'B-PER', score: 0.9980202913284302, index: 4, word: 'Sarah' },\n * // { entity: 'B-LOC', score: 0.9994474053382874, index: 9, word: 'London' }\n * // ]\n * ```\n * \n * **Example:** Perform named entity recognition with `Xenova/bert-base-NER` (and return all labels).\n * ```javascript\n * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER');\n * const output = await classifier('Sarah lives in the United States of America', { ignore_labels: [] });\n * // [\n * // { entity: 'B-PER', score: 0.9966587424278259, index: 1, word: 'Sarah' },\n * // { entity: 'O', score: 0.9987385869026184, index: 2, word: 'lives' },\n * // { entity: 'O', score: 0.9990072846412659, index: 3, word: 'in' },\n * // { entity: 'O', score: 0.9988298416137695, index: 4, word: 'the' },\n * // { entity: 'B-LOC', score: 0.9995510578155518, index: 5, word: 'United' },\n * // { entity: 'I-LOC', score: 0.9990395307540894, index: 6, word: 'States' },\n * // { entity: 'I-LOC', score: 0.9986724853515625, index: 7, word: 'of' },\n * // { entity: 'I-LOC', score: 0.9975294470787048, index: 8, word: 'America' }\n * // ]\n * ```\n */\nexport class TokenClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TokenClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new TokenClassificationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {TokenClassificationPipelineCallback} */\n async _call(texts, {\n ignore_labels = ['O'],\n } = {}) {\n\n const isBatched = Array.isArray(texts);\n\n // Run tokenization\n const model_inputs = this.tokenizer(isBatched ? texts : [texts], {\n padding: true,\n truncation: true,\n });\n\n // Run model\n const outputs = await this.model(model_inputs)\n\n const logits = outputs.logits;\n const id2label = this.model.config.id2label;\n\n const toReturn = [];\n for (let i = 0; i < logits.dims[0]; ++i) {\n const ids = model_inputs.input_ids[i];\n const batch = logits[i];\n\n // List of tokens that aren't ignored\n const tokens = [];\n for (let j = 0; j < batch.dims[0]; ++j) {\n const tokenData = batch[j];\n const topScoreIndex = max(tokenData.data)[1];\n\n const entity = id2label ? id2label[topScoreIndex] : `LABEL_${topScoreIndex}`;\n if (ignore_labels.includes(entity)) {\n // We predicted a token that should be ignored. So, we skip it.\n continue;\n }\n\n // TODO add option to keep special tokens?\n const word = this.tokenizer.decode([ids[j].item()], { skip_special_tokens: true });\n if (word === '') {\n // Was a special token. So, we skip it.\n continue;\n }\n\n const scores = softmax(tokenData.data);\n\n tokens.push({\n entity: entity,\n score: scores[topScoreIndex],\n index: j,\n word: word,\n\n // TODO: Add support for start and end\n // start: null,\n // end: null,\n });\n }\n toReturn.push(tokens);\n }\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} QuestionAnsweringOutput\n * @property {number} score The probability associated to the answer.\n * @property {number} [start] The character start index of the answer (in the tokenized version of the input).\n * @property {number} [end] The character end index of the answer (in the tokenized version of the input).\n * @property {string} answer The answer to the question.\n * \n * @typedef {Object} QuestionAnsweringPipelineOptions Parameters specific to question answering pipelines.\n * @property {number} [top_k=1] The number of top answer predictions to be returned.\n * \n * @callback QuestionAnsweringPipelineCallback Answer the question(s) given as inputs by using the context(s).\n * @param {string|string[]} question One or several question(s) (must be used in conjunction with the `context` argument).\n * @param {string|string[]} context One or several context(s) associated with the question(s) (must be used in conjunction with the `question` argument).\n * @param {QuestionAnsweringPipelineOptions} [options] The options to use for question answering.\n * @returns {Promise} An array or object containing the predicted answers and scores.\n * \n * @typedef {TextPipelineConstructorArgs & QuestionAnsweringPipelineCallback & Disposable} QuestionAnsweringPipelineType\n */\n\n/**\n * Question Answering pipeline using any `ModelForQuestionAnswering`.\n * \n * **Example:** Run question answering with `Xenova/distilbert-base-uncased-distilled-squad`.\n * ```javascript\n * const answerer = await pipeline('question-answering', 'Xenova/distilbert-base-uncased-distilled-squad');\n * const question = 'Who was Jim Henson?';\n * const context = 'Jim Henson was a nice puppet.';\n * const output = await answerer(question, context);\n * // {\n * // answer: \"a nice puppet\",\n * // score: 0.5768911502526741\n * // }\n * ```\n */\nexport class QuestionAnsweringPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => QuestionAnsweringPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new QuestionAnsweringPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {QuestionAnsweringPipelineCallback} */\n async _call(question, context, {\n top_k = 1\n } = {}) {\n\n // Run tokenization\n const inputs = this.tokenizer(question, {\n text_pair: context,\n padding: true,\n truncation: true,\n });\n\n const { start_logits, end_logits } = await this.model(inputs);\n const input_ids = inputs.input_ids.tolist();\n const attention_mask = inputs.attention_mask.tolist();\n\n // TODO: add support for `return_special_tokens_mask`\n const special_tokens = this.tokenizer.all_special_ids;\n\n /** @type {QuestionAnsweringOutput[]} */\n const toReturn = [];\n for (let j = 0; j < start_logits.dims[0]; ++j) {\n const ids = input_ids[j];\n const sepIndex = ids.findIndex(x =>\n // We use == to match bigint with number\n // @ts-ignore\n x == this.tokenizer.sep_token_id\n );\n\n\n const valid_mask = attention_mask[j].map((y, ix) => (\n y == 1\n && (\n ix === 0 // is cls_token\n || (\n ix > sepIndex\n && special_tokens.findIndex(x => x == ids[ix]) === -1 // token is not a special token (special_tokens_mask == 0)\n )\n )\n ));\n\n const start = start_logits[j].tolist();\n const end = end_logits[j].tolist();\n\n // Now, we mask out values that can't be in the answer\n // NOTE: We keep the cls_token unmasked (some models use it to indicate unanswerable questions)\n for (let i = 1; i < start.length; ++i) {\n if (\n attention_mask[j] == 0 // is part of padding\n || i <= sepIndex // is before the sep_token\n || special_tokens.findIndex(x => x == ids[i]) !== -1 // Is a special token\n ) {\n // Make sure non-context indexes in the tensor cannot contribute to the softmax\n start[i] = -Infinity;\n end[i] = -Infinity;\n }\n }\n\n // Normalize logits and spans to retrieve the answer\n const start_scores = softmax(start).map((x, i) => [x, i]);\n const end_scores = softmax(end).map((x, i) => [x, i]);\n\n // Mask CLS\n start_scores[0][0] = 0;\n end_scores[0][0] = 0;\n\n // Generate all valid spans and select best ones\n const options = product(start_scores, end_scores)\n .filter(x => x[0][1] <= x[1][1])\n .map(x => [x[0][1], x[1][1], x[0][0] * x[1][0]])\n .sort((a, b) => b[2] - a[2]);\n\n for (let k = 0; k < Math.min(options.length, top_k); ++k) {\n const [start, end, score] = options[k];\n\n const answer_tokens = ids.slice(start, end + 1)\n\n const answer = this.tokenizer.decode(answer_tokens, {\n skip_special_tokens: true,\n });\n\n // TODO add start and end?\n // NOTE: HF returns character index\n toReturn.push({\n answer, score\n });\n }\n }\n\n // Mimic HF's return type based on top_k\n return (top_k === 1) ? toReturn[0] : toReturn;\n }\n}\n\n\n/**\n * @typedef {Object} FillMaskSingle\n * @property {string} sequence The corresponding input with the mask token prediction.\n * @property {number} score The corresponding probability.\n * @property {number} token The predicted token id (to replace the masked one).\n * @property {string} token_str The predicted token (to replace the masked one).\n * @typedef {FillMaskSingle[]} FillMaskOutput\n * \n * @typedef {Object} FillMaskPipelineOptions Parameters specific to fill mask pipelines.\n * @property {number} [top_k=5] When passed, overrides the number of predictions to return.\n * \n * @callback FillMaskPipelineCallback Fill the masked token in the text(s) given as inputs.\n * @param {string|string[]} texts One or several texts (or one list of prompts) with masked tokens.\n * @param {FillMaskPipelineOptions} [options] The options to use for masked language modelling.\n * @returns {Promise} An array of objects containing the score, predicted token, predicted token string,\n * and the sequence with the predicted token filled in, or an array of such arrays (one for each input text).\n * If only one input text is given, the output will be an array of objects.\n * @throws {Error} When the mask token is not found in the input text.\n * \n * @typedef {TextPipelineConstructorArgs & FillMaskPipelineCallback & Disposable} FillMaskPipelineType\n */\n\n/**\n * Masked language modeling prediction pipeline using any `ModelWithLMHead`.\n * \n * **Example:** Perform masked language modelling (a.k.a. \"fill-mask\") with `Xenova/bert-base-uncased`.\n * ```javascript\n * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased');\n * const output = await unmasker('The goal of life is [MASK].');\n * // [\n * // { token_str: 'survival', score: 0.06137419492006302, token: 8115, sequence: 'The goal of life is survival.' },\n * // { token_str: 'love', score: 0.03902450203895569, token: 1567, sequence: 'The goal of life is love.' },\n * // { token_str: 'happiness', score: 0.03253183513879776, token: 9266, sequence: 'The goal of life is happiness.' },\n * // { token_str: 'freedom', score: 0.018736306577920914, token: 4438, sequence: 'The goal of life is freedom.' },\n * // { token_str: 'life', score: 0.01859794743359089, token: 1297, sequence: 'The goal of life is life.' }\n * // ]\n * ```\n * \n * **Example:** Perform masked language modelling (a.k.a. \"fill-mask\") with `Xenova/bert-base-cased` (and return top result).\n * ```javascript\n * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased');\n * const output = await unmasker('The Milky Way is a [MASK] galaxy.', { top_k: 1 });\n * // [{ token_str: 'spiral', score: 0.6299987435340881, token: 14061, sequence: 'The Milky Way is a spiral galaxy.' }]\n * ```\n */\nexport class FillMaskPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => FillMaskPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new FillMaskPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {FillMaskPipelineCallback} */\n async _call(texts, {\n top_k = 5\n } = {}) {\n\n // Run tokenization\n const model_inputs = this.tokenizer(texts, {\n padding: true,\n truncation: true,\n });\n\n // Run model\n const { logits } = await this.model(model_inputs)\n\n const toReturn = [];\n\n /** @type {bigint[][]} */\n const input_ids = model_inputs.input_ids.tolist();\n for (let i = 0; i < input_ids.length; ++i) {\n const ids = input_ids[i];\n const mask_token_index = ids.findIndex(x =>\n // We use == to match bigint with number\n // @ts-ignore\n x == this.tokenizer.mask_token_id\n );\n if (mask_token_index === -1) {\n throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`)\n }\n const itemLogits = logits[i][mask_token_index];\n\n const scores = await topk(new Tensor(\n 'float32',\n softmax(itemLogits.data),\n itemLogits.dims,\n ), top_k);\n const values = scores[0].tolist();\n const indices = scores[1].tolist();\n\n toReturn.push(indices.map((x, i) => {\n const sequence = ids.slice();\n sequence[mask_token_index] = x;\n\n return {\n score: values[i],\n token: Number(x),\n token_str: this.tokenizer.model.vocab[x],\n sequence: this.tokenizer.decode(sequence, { skip_special_tokens: true }),\n }\n }));\n }\n return Array.isArray(texts) ? toReturn : toReturn[0];\n }\n}\n\n\n/**\n * @typedef {Object} Text2TextGenerationSingle\n * @property {string} generated_text The generated text.\n * @typedef {Text2TextGenerationSingle[]} Text2TextGenerationOutput\n * \n * @callback Text2TextGenerationPipelineCallback Generate the output text(s) using text(s) given as inputs.\n * @param {string|string[]} texts Input text for the encoder.\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise}\n * \n * @typedef {TextPipelineConstructorArgs & Text2TextGenerationPipelineCallback & Disposable} Text2TextGenerationPipelineType\n */\n\n/**\n * Text2TextGenerationPipeline class for generating text using a model that performs text-to-text generation tasks.\n * \n * **Example:** Text-to-text generation w/ `Xenova/LaMini-Flan-T5-783M`.\n * ```javascript\n * const generator = await pipeline('text2text-generation', 'Xenova/LaMini-Flan-T5-783M');\n * const output = await generator('how can I become more healthy?', {\n * max_new_tokens: 100,\n * });\n * // [{ generated_text: \"To become more healthy, you can: 1. Eat a balanced diet with plenty of fruits, vegetables, whole grains, lean proteins, and healthy fats. 2. Stay hydrated by drinking plenty of water. 3. Get enough sleep and manage stress levels. 4. Avoid smoking and excessive alcohol consumption. 5. Regularly exercise and maintain a healthy weight. 6. Practice good hygiene and sanitation. 7. Seek medical attention if you experience any health issues.\" }]\n * ```\n */\nexport class Text2TextGenerationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => Text2TextGenerationPipelineType} */ (Pipeline)) {\n /** @type {'generated_text'} */\n _key = 'generated_text';\n\n /**\n * Create a new Text2TextGenerationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {Text2TextGenerationPipelineCallback} */\n async _call(texts, generate_kwargs = {}) {\n if (!Array.isArray(texts)) {\n texts = [texts];\n }\n\n\n // Add global prefix, if present\n if (this.model.config.prefix) {\n texts = texts.map(x => this.model.config.prefix + x)\n }\n\n // Handle task specific params:\n const task_specific_params = this.model.config.task_specific_params\n if (task_specific_params && task_specific_params[this.task]) {\n // Add prefixes, if present\n if (task_specific_params[this.task].prefix) {\n texts = texts.map(x => task_specific_params[this.task].prefix + x)\n }\n\n // TODO update generation config\n }\n\n const tokenizer = this.tokenizer;\n const tokenizer_options = {\n padding: true,\n truncation: true,\n }\n let inputs;\n if (this instanceof TranslationPipeline && '_build_translation_inputs' in tokenizer) {\n // TODO: move to Translation pipeline?\n // Currently put here to avoid code duplication\n // @ts-ignore\n inputs = tokenizer._build_translation_inputs(texts, tokenizer_options, generate_kwargs);\n\n } else {\n inputs = tokenizer(texts, tokenizer_options);\n }\n\n const outputTokenIds = await this.model.generate({ ...inputs, ...generate_kwargs });\n return tokenizer.batch_decode(/** @type {Tensor} */(outputTokenIds), {\n skip_special_tokens: true,\n }).map(text => ({ [this._key]: text }));\n }\n}\n\n\n/**\n * @typedef {Object} SummarizationSingle\n * @property {string} summary_text The summary text.\n * @typedef {SummarizationSingle[]} SummarizationOutput\n * \n * @callback SummarizationPipelineCallback Summarize the text(s) given as inputs.\n * @param {string|string[]} texts One or several articles (or one list of articles) to summarize.\n * @param {import('./generation/configuration_utils.js').GenerationConfig} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise}\n * \n * @typedef {TextPipelineConstructorArgs & SummarizationPipelineCallback & Disposable} SummarizationPipelineType\n */\n\n/**\n * A pipeline for summarization tasks, inheriting from Text2TextGenerationPipeline.\n * \n * **Example:** Summarization w/ `Xenova/distilbart-cnn-6-6`.\n * ```javascript\n * const generator = await pipeline('summarization', 'Xenova/distilbart-cnn-6-6');\n * const text = 'The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, ' +\n * 'and the tallest structure in Paris. Its base is square, measuring 125 metres (410 ft) on each side. ' +\n * 'During its construction, the Eiffel Tower surpassed the Washington Monument to become the tallest ' +\n * 'man-made structure in the world, a title it held for 41 years until the Chrysler Building in New ' +\n * 'York City was finished in 1930. It was the first structure to reach a height of 300 metres. Due to ' +\n * 'the addition of a broadcasting aerial at the top of the tower in 1957, it is now taller than the ' +\n * 'Chrysler Building by 5.2 metres (17 ft). Excluding transmitters, the Eiffel Tower is the second ' +\n * 'tallest free-standing structure in France after the Millau Viaduct.';\n * const output = await generator(text, {\n * max_new_tokens: 100,\n * });\n * // [{ summary_text: ' The Eiffel Tower is about the same height as an 81-storey building and the tallest structure in Paris. It is the second tallest free-standing structure in France after the Millau Viaduct.' }]\n * ```\n */\nexport class SummarizationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => SummarizationPipelineType} */ (/** @type {any} */ (Text2TextGenerationPipeline))) {\n /** @type {'summary_text'} */\n _key = 'summary_text';\n\n /**\n * Create a new SummarizationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n}\n\n\n/**\n * @typedef {Object} TranslationSingle\n * @property {string} translation_text The translated text.\n * @typedef {TranslationSingle[]} TranslationOutput\n * \n * @callback TranslationPipelineCallback Translate the text(s) given as inputs.\n * @param {string|string[]} texts Texts to be translated.\n * @param {import('./generation/configuration_utils.js').GenerationConfig} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise}\n * \n * @typedef {TextPipelineConstructorArgs & TranslationPipelineCallback & Disposable} TranslationPipelineType\n */\n\n/**\n * Translates text from one language to another.\n * \n * **Example:** Multilingual translation w/ `Xenova/nllb-200-distilled-600M`.\n * \n * See [here](https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200)\n * for the full list of languages and their corresponding codes.\n * \n * ```javascript\n * const translator = await pipeline('translation', 'Xenova/nllb-200-distilled-600M');\n * const output = await translator('जीवन एक चॉकलेट बॉक्स की तरह है।', {\n * src_lang: 'hin_Deva', // Hindi\n * tgt_lang: 'fra_Latn', // French\n * });\n * // [{ translation_text: 'La vie est comme une boîte à chocolat.' }]\n * ```\n * \n * **Example:** Multilingual translation w/ `Xenova/m2m100_418M`.\n * \n * See [here](https://huggingface.co/facebook/m2m100_418M#languages-covered)\n * for the full list of languages and their corresponding codes.\n * \n * ```javascript\n * const translator = await pipeline('translation', 'Xenova/m2m100_418M');\n * const output = await translator('生活就像一盒巧克力。', {\n * src_lang: 'zh', // Chinese\n * tgt_lang: 'en', // English\n * });\n * // [{ translation_text: 'Life is like a box of chocolate.' }]\n * ```\n * \n * **Example:** Multilingual translation w/ `Xenova/mbart-large-50-many-to-many-mmt`.\n * \n * See [here](https://huggingface.co/facebook/mbart-large-50-many-to-many-mmt#languages-covered)\n * for the full list of languages and their corresponding codes.\n * \n * ```javascript\n * const translator = await pipeline('translation', 'Xenova/mbart-large-50-many-to-many-mmt');\n * const output = await translator('संयुक्त राष्ट्र के प्रमुख का कहना है कि सीरिया में कोई सैन्य समाधान नहीं है', {\n * src_lang: 'hi_IN', // Hindi\n * tgt_lang: 'fr_XX', // French\n * });\n * // [{ translation_text: 'Le chef des Nations affirme qu 'il n 'y a military solution in Syria.' }]\n * ```\n */\nexport class TranslationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TranslationPipelineType} */ (/** @type {any} */ (Text2TextGenerationPipeline))) {\n /** @type {'translation_text'} */\n _key = 'translation_text';\n\n /**\n * Create a new TranslationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n}\n\nfunction isChat(x) {\n return Array.isArray(x) && x.every(x => 'role' in x && 'content' in x);\n}\n\n/**\n * @typedef {import('./tokenizers.js').Message[]} Chat\n * \n * @typedef {Object} TextGenerationSingle\n * @property {string|Chat} generated_text The generated text.\n * @typedef {TextGenerationSingle[]} TextGenerationOutput\n * \n * @typedef {Object} TextGenerationSpecificParams Parameters specific to text-generation pipelines.\n * @property {boolean} [add_special_tokens] Whether or not to add special tokens when tokenizing the sequences.\n * @property {boolean} [return_full_text=true] If set to `false` only added text is returned, otherwise the full text is returned.\n * @typedef {import('./generation/configuration_utils.js').GenerationConfig & TextGenerationSpecificParams} TextGenerationConfig\n * \n * @callback TextGenerationPipelineCallback Complete the prompt(s) given as inputs.\n * @param {string|string[]|Chat|Chat[]} texts One or several prompts (or one list of prompts) to complete.\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise} An array or object containing the generated texts.\n * \n * @typedef {TextPipelineConstructorArgs & TextGenerationPipelineCallback & Disposable} TextGenerationPipelineType\n */\n\n/**\n * Language generation pipeline using any `ModelWithLMHead` or `ModelForCausalLM`.\n * This pipeline predicts the words that will follow a specified text prompt.\n * NOTE: For the full list of generation parameters, see [`GenerationConfig`](./utils/generation#module_utils/generation.GenerationConfig).\n * \n * **Example:** Text generation with `Xenova/distilgpt2` (default settings).\n * ```javascript\n * const generator = await pipeline('text-generation', 'Xenova/distilgpt2');\n * const text = 'I enjoy walking with my cute dog,';\n * const output = await generator(text);\n * // [{ generated_text: \"I enjoy walking with my cute dog, and I love to play with the other dogs.\" }]\n * ```\n * \n * **Example:** Text generation with `Xenova/distilgpt2` (custom settings).\n * ```javascript\n * const generator = await pipeline('text-generation', 'Xenova/distilgpt2');\n * const text = 'Once upon a time, there was';\n * const output = await generator(text, {\n * temperature: 2,\n * max_new_tokens: 10,\n * repetition_penalty: 1.5,\n * no_repeat_ngram_size: 2,\n * num_beams: 2,\n * num_return_sequences: 2,\n * });\n * // [{\n * // \"generated_text\": \"Once upon a time, there was an abundance of information about the history and activities that\"\n * // }, {\n * // \"generated_text\": \"Once upon a time, there was an abundance of information about the most important and influential\"\n * // }]\n * ```\n * \n * **Example:** Run code generation with `Xenova/codegen-350M-mono`.\n * ```javascript\n * const generator = await pipeline('text-generation', 'Xenova/codegen-350M-mono');\n * const text = 'def fib(n):';\n * const output = await generator(text, {\n * max_new_tokens: 44,\n * });\n * // [{\n * // generated_text: 'def fib(n):\\n' +\n * // ' if n == 0:\\n' +\n * // ' return 0\\n' +\n * // ' elif n == 1:\\n' +\n * // ' return 1\\n' +\n * // ' else:\\n' +\n * // ' return fib(n-1) + fib(n-2)\\n'\n * // }]\n * ```\n */\nexport class TextGenerationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TextGenerationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new TextGenerationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {TextGenerationPipelineCallback} */\n async _call(texts, generate_kwargs = {}) {\n let isBatched = false;\n let isChatInput = false;\n\n // Normalize inputs\n /** @type {string[]} */\n let inputs;\n if (typeof texts === 'string') {\n inputs = texts = [texts];\n } else if (Array.isArray(texts) && texts.every(x => typeof x === 'string')) {\n isBatched = true;\n inputs = /** @type {string[]} */(texts);\n } else {\n if (isChat(texts)) {\n texts = [/** @type {Chat} */(texts)];\n } else if (Array.isArray(texts) && texts.every(isChat)) {\n isBatched = true;\n } else {\n throw new Error('Input must be a string, an array of strings, a Chat, or an array of Chats');\n }\n isChatInput = true;\n\n // If the input is a chat, we need to apply the chat template\n inputs = /** @type {string[]} */(/** @type {Chat[]} */ (texts).map(\n x => this.tokenizer.apply_chat_template(x, {\n tokenize: false,\n add_generation_prompt: true,\n })\n ));\n }\n\n // By default, do not add special tokens\n const add_special_tokens = generate_kwargs.add_special_tokens ?? false;\n\n // By default, return full text\n const return_full_text = isChatInput\n ? false\n : generate_kwargs.return_full_text ?? true;\n\n this.tokenizer.padding_side = 'left';\n const text_inputs = this.tokenizer(inputs, {\n add_special_tokens,\n padding: true,\n truncation: true,\n });\n\n const outputTokenIds = /** @type {Tensor} */(await this.model.generate({\n ...text_inputs,\n ...generate_kwargs\n }));\n\n const decoded = this.tokenizer.batch_decode(outputTokenIds, {\n skip_special_tokens: true,\n });\n\n let promptLengths;\n if (!return_full_text && text_inputs.input_ids.dims.at(-1) > 0) {\n promptLengths = this.tokenizer.batch_decode(text_inputs.input_ids, {\n skip_special_tokens: true,\n }).map(x => x.length);\n }\n\n /** @type {TextGenerationOutput[]} */\n const toReturn = Array.from({ length: texts.length }, _ => []);\n for (let i = 0; i < decoded.length; ++i) {\n const textIndex = Math.floor(i / outputTokenIds.dims[0] * texts.length);\n\n if (promptLengths) {\n // Trim the decoded text to only include the generated part\n decoded[i] = decoded[i].slice(promptLengths[textIndex]);\n }\n toReturn[textIndex].push({\n generated_text: isChatInput\n ? [\n ...((/** @type {Chat[]} */(texts)[textIndex])),\n { role: 'assistant', content: decoded[i] },\n ]\n : decoded[i]\n });\n }\n return (!isBatched && toReturn.length === 1) ? toReturn[0] : toReturn;\n }\n}\n\n/**\n * @typedef {Object} ZeroShotClassificationOutput\n * @property {string} sequence The sequence for which this is the output.\n * @property {string[]} labels The labels sorted by order of likelihood.\n * @property {number[]} scores The probabilities for each of the labels.\n * \n * @typedef {Object} ZeroShotClassificationPipelineOptions Parameters specific to zero-shot classification pipelines.\n * @property {string} [hypothesis_template=\"This example is {}.\"] The template used to turn each\n * candidate label into an NLI-style hypothesis. The candidate label will replace the {} placeholder.\n * @property {boolean} [multi_label=false] Whether or not multiple candidate labels can be true.\n * If `false`, the scores are normalized such that the sum of the label likelihoods for each sequence\n * is 1. If `true`, the labels are considered independent and probabilities are normalized for each\n * candidate by doing a softmax of the entailment score vs. the contradiction score.\n * \n * @callback ZeroShotClassificationPipelineCallback Classify the sequence(s) given as inputs.\n * @param {string|string[]} texts The sequence(s) to classify, will be truncated if the model input is too large.\n * @param {string|string[]} candidate_labels The set of possible class labels to classify each sequence into.\n * Can be a single label, a string of comma-separated labels, or a list of labels.\n * @param {ZeroShotClassificationPipelineOptions} [options] The options to use for zero-shot classification.\n * @returns {Promise} An array or object containing the predicted labels and scores.\n * \n * @typedef {TextPipelineConstructorArgs & ZeroShotClassificationPipelineCallback & Disposable} ZeroShotClassificationPipelineType\n */\n\n/**\n * NLI-based zero-shot classification pipeline using a `ModelForSequenceClassification`\n * trained on NLI (natural language inference) tasks. Equivalent of `text-classification`\n * pipelines, but these models don't require a hardcoded number of potential classes, they\n * can be chosen at runtime. It usually means it's slower but it is **much** more flexible.\n * \n * **Example:** Zero shot classification with `Xenova/mobilebert-uncased-mnli`.\n * ```javascript\n * const classifier = await pipeline('zero-shot-classification', 'Xenova/mobilebert-uncased-mnli');\n * const text = 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.';\n * const labels = [ 'mobile', 'billing', 'website', 'account access' ];\n * const output = await classifier(text, labels);\n * // {\n * // sequence: 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.',\n * // labels: [ 'mobile', 'website', 'billing', 'account access' ],\n * // scores: [ 0.5562091040482018, 0.1843621307860853, 0.13942646639336376, 0.12000229877234923 ]\n * // }\n * ```\n * \n * **Example:** Zero shot classification with `Xenova/nli-deberta-v3-xsmall` (multi-label).\n * ```javascript\n * const classifier = await pipeline('zero-shot-classification', 'Xenova/nli-deberta-v3-xsmall');\n * const text = 'I have a problem with my iphone that needs to be resolved asap!';\n * const labels = [ 'urgent', 'not urgent', 'phone', 'tablet', 'computer' ];\n * const output = await classifier(text, labels, { multi_label: true });\n * // {\n * // sequence: 'I have a problem with my iphone that needs to be resolved asap!',\n * // labels: [ 'urgent', 'phone', 'computer', 'tablet', 'not urgent' ],\n * // scores: [ 0.9958870956360275, 0.9923963400697035, 0.002333537946160235, 0.0015134138567598765, 0.0010699384208377163 ]\n * // }\n * ```\n */\nexport class ZeroShotClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => ZeroShotClassificationPipelineType} */ (Pipeline)) {\n /**\n * Create a new ZeroShotClassificationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n\n // Use model config to get label2id mapping\n this.label2id = Object.fromEntries(\n Object.entries((/** @type {any} */(this).model).config.label2id).map(\n ([k, v]) => [k.toLowerCase(), v]\n )\n );\n\n this.entailment_id = this.label2id['entailment'];\n if (this.entailment_id === undefined) {\n console.warn(\"Could not find 'entailment' in label2id mapping. Using 2 as entailment_id.\");\n this.entailment_id = 2;\n }\n\n this.contradiction_id = this.label2id['contradiction'] ?? this.label2id['not_entailment'];\n if (this.contradiction_id === undefined) {\n console.warn(\"Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id.\");\n this.contradiction_id = 0;\n }\n }\n\n /** @type {ZeroShotClassificationPipelineCallback} */\n async _call(texts, candidate_labels, {\n hypothesis_template = \"This example is {}.\",\n multi_label = false,\n } = {}) {\n\n const isBatched = Array.isArray(texts);\n if (!isBatched) {\n texts = [/** @type {string} */ (texts)];\n }\n if (!Array.isArray(candidate_labels)) {\n candidate_labels = [candidate_labels];\n }\n\n // Insert labels into hypothesis template\n const hypotheses = candidate_labels.map(\n x => hypothesis_template.replace('{}', x)\n );\n\n // How to perform the softmax over the logits:\n // - true: softmax over the entailment vs. contradiction dim for each label independently\n // - false: softmax the \"entailment\" logits over all candidate labels\n const softmaxEach = multi_label || candidate_labels.length === 1;\n\n /** @type {ZeroShotClassificationOutput[]} */\n const toReturn = [];\n for (const premise of texts) {\n const entails_logits = [];\n\n for (const hypothesis of hypotheses) {\n const inputs = this.tokenizer(premise, {\n text_pair: hypothesis,\n padding: true,\n truncation: true,\n })\n const outputs = await this.model(inputs)\n\n if (softmaxEach) {\n entails_logits.push([\n outputs.logits.data[this.contradiction_id],\n outputs.logits.data[this.entailment_id]\n ])\n } else {\n entails_logits.push(outputs.logits.data[this.entailment_id])\n }\n }\n\n /** @type {number[]} */\n const scores = softmaxEach\n ? entails_logits.map(x => softmax(x)[1])\n : softmax(entails_logits);\n\n // Sort by scores (desc) and return scores with indices\n const scores_sorted = scores\n .map((x, i) => [x, i])\n .sort((a, b) => (b[0] - a[0]));\n\n toReturn.push({\n sequence: premise,\n labels: scores_sorted.map(x => candidate_labels[x[1]]),\n scores: scores_sorted.map(x => x[0]),\n });\n }\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} FeatureExtractionPipelineOptions Parameters specific to feature extraction pipelines.\n * @property {'none'|'mean'|'cls'} [pooling=\"none\"] The pooling method to use.\n * @property {boolean} [normalize=false] Whether or not to normalize the embeddings in the last dimension.\n * @property {boolean} [quantize=false] Whether or not to quantize the embeddings.\n * @property {'binary'|'ubinary'} [precision='binary'] The precision to use for quantization. \n * \n * @callback FeatureExtractionPipelineCallback Extract the features of the input(s).\n * @param {string|string[]} texts One or several texts (or one list of texts) to get the features of.\n * @param {FeatureExtractionPipelineOptions} [options] The options to use for feature extraction.\n * @returns {Promise} The features computed by the model.\n * \n * @typedef {TextPipelineConstructorArgs & FeatureExtractionPipelineCallback & Disposable} FeatureExtractionPipelineType\n */\n\n/**\n * Feature extraction pipeline using no model head. This pipeline extracts the hidden\n * states from the base transformer, which can be used as features in downstream tasks.\n * \n * **Example:** Run feature extraction with `bert-base-uncased` (without pooling/normalization).\n * ```javascript\n * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' });\n * const output = await extractor('This is a simple test.');\n * // Tensor {\n * // type: 'float32',\n * // data: Float32Array [0.05939924716949463, 0.021655935794115067, ...],\n * // dims: [1, 8, 768]\n * // }\n * ```\n * \n * **Example:** Run feature extraction with `bert-base-uncased` (with pooling/normalization).\n * ```javascript\n * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' });\n * const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true });\n * // Tensor {\n * // type: 'float32',\n * // data: Float32Array [0.03373778983950615, -0.010106077417731285, ...],\n * // dims: [1, 768]\n * // }\n * ```\n * \n * **Example:** Calculating embeddings with `sentence-transformers` models.\n * ```javascript\n * const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');\n * const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true });\n * // Tensor {\n * // type: 'float32',\n * // data: Float32Array [0.09094982594251633, -0.014774246141314507, ...],\n * // dims: [1, 384]\n * // }\n * ```\n * **Example:** Calculating binary embeddings with `sentence-transformers` models.\n * ```javascript\n * const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');\n * const output = await extractor('This is a simple test.', { pooling: 'mean', quantize: true, precision: 'binary' });\n * // Tensor {\n * // type: 'int8',\n * // data: Int8Array [49, 108, 24, ...],\n * // dims: [1, 48]\n * // }\n * ```\n */\nexport class FeatureExtractionPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => FeatureExtractionPipelineType} */ (Pipeline)) {\n /**\n * Create a new FeatureExtractionPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {FeatureExtractionPipelineCallback} */\n async _call(texts, {\n pooling = /** @type {'none'} */('none'),\n normalize = false,\n quantize = false,\n precision = /** @type {'binary'} */('binary'),\n } = {}) {\n\n // Run tokenization\n const model_inputs = this.tokenizer(texts, {\n padding: true,\n truncation: true,\n });\n\n // Run model\n const outputs = await this.model(model_inputs)\n\n // TODO: Provide warning to the user that they might be using model which was not exported\n // specifically for feature extraction\n // console.log(this.model.config)\n // console.log(outputs)\n\n /** @type {Tensor} */\n let result = outputs.last_hidden_state ?? outputs.logits ?? outputs.token_embeddings;\n if (pooling === 'none') {\n // Skip pooling\n } else if (pooling === 'mean') {\n result = mean_pooling(result, model_inputs.attention_mask);\n } else if (pooling === 'cls') {\n result = result.slice(null, 0);\n } else {\n throw Error(`Pooling method '${pooling}' not supported.`);\n }\n\n if (normalize) {\n result = result.normalize(2, -1);\n }\n\n if (quantize) {\n result = quantize_embeddings(result, precision);\n }\n\n return result;\n }\n}\n\n\n/**\n * @typedef {Object} ImageFeatureExtractionPipelineOptions Parameters specific to image feature extraction pipelines.\n * @property {boolean} [pool=null] Whether or not to return the pooled output. If set to `false`, the model will return the raw hidden states.\n * \n * @callback ImageFeatureExtractionPipelineCallback Extract the features of the input(s).\n * @param {ImagePipelineInputs} images One or several images (or one list of images) to get the features of.\n * @param {ImageFeatureExtractionPipelineOptions} [options] The options to use for image feature extraction.\n * @returns {Promise} The image features computed by the model.\n * \n * @typedef {ImagePipelineConstructorArgs & ImageFeatureExtractionPipelineCallback & Disposable} ImageFeatureExtractionPipelineType\n */\n\n/**\n * Image feature extraction pipeline using no model head. This pipeline extracts the hidden\n * states from the base transformer, which can be used as features in downstream tasks.\n * \n * **Example:** Perform image feature extraction with `Xenova/vit-base-patch16-224-in21k`.\n * ```javascript\n * const image_feature_extractor = await pipeline('image-feature-extraction', 'Xenova/vit-base-patch16-224-in21k');\n * const url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png';\n * const features = await image_feature_extractor(url);\n * // Tensor {\n * // dims: [ 1, 197, 768 ],\n * // type: 'float32',\n * // data: Float32Array(151296) [ ... ],\n * // size: 151296\n * // }\n * ```\n * \n * **Example:** Compute image embeddings with `Xenova/clip-vit-base-patch32`.\n * ```javascript\n * const image_feature_extractor = await pipeline('image-feature-extraction', 'Xenova/clip-vit-base-patch32');\n * const url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png';\n * const features = await image_feature_extractor(url);\n * // Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [ ... ],\n * // size: 512\n * // }\n * ```\n */\nexport class ImageFeatureExtractionPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageFeatureExtractionPipelineType} */ (Pipeline)) {\n /**\n * Create a new ImageFeatureExtractionPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ImageFeatureExtractionPipelineCallback} */\n async _call(images, {\n pool = null,\n } = {}) {\n\n const preparedImages = await prepareImages(images);\n const { pixel_values } = await this.processor(preparedImages);\n const outputs = await this.model({ pixel_values });\n\n /** @type {Tensor} */\n let result;\n if (pool) {\n if (!('pooler_output' in outputs)) {\n throw Error(`No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.`);\n }\n result = outputs.pooler_output;\n\n } else {\n result = outputs.last_hidden_state ?? outputs.logits ?? outputs.image_embeds;\n }\n return result;\n }\n}\n\n// TODO\n// export class SentenceSimilarityPipeline extends Pipeline {\n// }\n\n/**\n * @typedef {Object} AudioClassificationSingle\n * @property {string} label The label predicted.\n * @property {number} score The corresponding probability.\n * @typedef {AudioClassificationSingle[]} AudioClassificationOutput\n * \n * @typedef {Object} AudioClassificationPipelineOptions Parameters specific to audio classification pipelines.\n * @property {number} [top_k=5] The number of top labels that will be returned by the pipeline.\n * If the provided number is `null` or higher than the number of labels available in the model configuration,\n * it will default to the number of labels.\n * \n * @callback AudioClassificationPipelineCallback Classify the sequence(s) given as inputs.\n * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either:\n * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate\n * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API.\n * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`.\n * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).\n * @param {AudioClassificationPipelineOptions} [options] The options to use for audio classification.\n * @returns {Promise} An array or object containing the predicted labels and scores.\n * \n * @typedef {AudioPipelineConstructorArgs & AudioClassificationPipelineCallback & Disposable} AudioClassificationPipelineType\n */\n\n/**\n * Audio classification pipeline using any `AutoModelForAudioClassification`.\n * This pipeline predicts the class of a raw waveform or an audio file.\n * \n * **Example:** Perform audio classification with `Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech`.\n * ```javascript\n * const classifier = await pipeline('audio-classification', 'Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const output = await classifier(url);\n * // [\n * // { label: 'male', score: 0.9981542229652405 },\n * // { label: 'female', score: 0.001845747814513743 }\n * // ]\n * ```\n * \n * **Example:** Perform audio classification with `Xenova/ast-finetuned-audioset-10-10-0.4593` and return top 4 results.\n * ```javascript\n * const classifier = await pipeline('audio-classification', 'Xenova/ast-finetuned-audioset-10-10-0.4593');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cat_meow.wav';\n * const output = await classifier(url, { top_k: 4 });\n * // [\n * // { label: 'Meow', score: 0.5617874264717102 },\n * // { label: 'Cat', score: 0.22365376353263855 },\n * // { label: 'Domestic animals, pets', score: 0.1141069084405899 },\n * // { label: 'Animal', score: 0.08985692262649536 },\n * // ]\n * ```\n */\nexport class AudioClassificationPipeline extends (/** @type {new (options: AudioPipelineConstructorArgs) => AudioClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new AudioClassificationPipeline.\n * @param {AudioPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {AudioClassificationPipelineCallback} */\n async _call(audio, {\n top_k = 5\n } = {}) {\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n const preparedAudios = await prepareAudios(audio, sampling_rate);\n\n const id2label = this.model.config.id2label;\n\n const toReturn = [];\n for (const aud of preparedAudios) {\n const inputs = await this.processor(aud);\n const output = await this.model(inputs);\n const logits = output.logits[0];\n\n const scores = await topk(new Tensor(\n 'float32',\n softmax(logits.data),\n logits.dims,\n ), top_k);\n\n const values = scores[0].tolist();\n const indices = scores[1].tolist();\n\n const vals = indices.map((x, i) => ({\n label: /** @type {string} */ (id2label ? id2label[x] : `LABEL_${x}`),\n score: /** @type {number} */ (values[i]),\n }));\n\n toReturn.push(vals);\n };\n return Array.isArray(audio) ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} ZeroShotAudioClassificationOutput\n * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`.\n * @property {number} score The score attributed by the model for that label (between 0 and 1).\n * \n * @typedef {Object} ZeroShotAudioClassificationPipelineOptions Parameters specific to zero-shot audio classification pipelines.\n * @property {string} [hypothesis_template=\"This is a sound of {}.\"] The sentence used in conjunction with `candidate_labels`\n * to attempt the audio classification by replacing the placeholder with the candidate_labels.\n * Then likelihood is estimated by using `logits_per_audio`.\n * \n * @callback ZeroShotAudioClassificationPipelineCallback Classify the sequence(s) given as inputs.\n * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either:\n * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate\n * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API.\n * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`.\n * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).\n * @param {string[]} candidate_labels The candidate labels for this audio.\n * @param {ZeroShotAudioClassificationPipelineOptions} [options] The options to use for zero-shot audio classification.\n * @returns {Promise} An array of objects containing the predicted labels and scores.\n * \n * @typedef {TextAudioPipelineConstructorArgs & ZeroShotAudioClassificationPipelineCallback & Disposable} ZeroShotAudioClassificationPipelineType\n */\n\n/**\n * Zero shot audio classification pipeline using `ClapModel`. This pipeline predicts the class of an audio when you\n * provide an audio and a set of `candidate_labels`.\n * \n * **Example**: Perform zero-shot audio classification with `Xenova/clap-htsat-unfused`.\n * ```javascript\n * const classifier = await pipeline('zero-shot-audio-classification', 'Xenova/clap-htsat-unfused');\n * const audio = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/dog_barking.wav';\n * const candidate_labels = ['dog', 'vaccum cleaner'];\n * const scores = await classifier(audio, candidate_labels);\n * // [\n * // { score: 0.9993992447853088, label: 'dog' },\n * // { score: 0.0006007603369653225, label: 'vaccum cleaner' }\n * // ]\n * ```\n */\nexport class ZeroShotAudioClassificationPipeline extends (/** @type {new (options: TextAudioPipelineConstructorArgs) => ZeroShotAudioClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ZeroShotAudioClassificationPipeline.\n * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ZeroShotAudioClassificationPipelineCallback} */\n async _call(audio, candidate_labels, {\n hypothesis_template = \"This is a sound of {}.\"\n } = {}) {\n\n const single = !Array.isArray(audio);\n if (single) {\n audio = [/** @type {AudioInput} */ (audio)];\n }\n\n // Insert label into hypothesis template \n const texts = candidate_labels.map(\n x => hypothesis_template.replace('{}', x)\n );\n\n // Run tokenization\n const text_inputs = this.tokenizer(texts, {\n padding: true,\n truncation: true,\n });\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n const preparedAudios = await prepareAudios(audio, sampling_rate);\n\n const toReturn = [];\n for (const aud of preparedAudios) {\n const audio_inputs = await this.processor(aud);\n\n // Run model with both text and audio inputs\n const output = await this.model({ ...text_inputs, ...audio_inputs });\n\n // Compute softmax per audio\n const probs = softmax(output.logits_per_audio.data);\n\n toReturn.push([...probs].map((x, i) => ({\n score: x,\n label: candidate_labels[i]\n })));\n }\n return single ? toReturn[0] : toReturn;\n }\n}\n\n/**\n * @typedef {Object} Chunk\n * @property {[number, number]} timestamp The start and end timestamp of the chunk in seconds.\n * @property {string} text The recognized text.\n */\n\n/**\n * @typedef {Object} AutomaticSpeechRecognitionOutput\n * @property {string} text The recognized text.\n * @property {Chunk[]} [chunks] When using `return_timestamps`, the `chunks` will become a list\n * containing all the various text chunks identified by the model.\n * \n * @typedef {Object} AutomaticSpeechRecognitionSpecificParams Parameters specific to automatic-speech-recognition pipelines.\n * @property {boolean|'word'} [return_timestamps] Whether to return timestamps or not. Default is `false`.\n * @property {number} [chunk_length_s] The length of audio chunks to process in seconds. Default is 0 (no chunking).\n * @property {number} [stride_length_s] The length of overlap between consecutive audio chunks in seconds. If not provided, defaults to `chunk_length_s / 6`.\n * @property {boolean} [force_full_sequences] Whether to force outputting full sequences or not. Default is `false`.\n * @property {string} [language] The source language. Default is `null`, meaning it should be auto-detected. Use this to potentially improve performance if the source language is known.\n * @property {string} [task] The task to perform. Default is `null`, meaning it should be auto-detected.\n * @property {number} [num_frames] The number of frames in the input audio.\n * @typedef {import('./generation/configuration_utils.js').GenerationConfig & AutomaticSpeechRecognitionSpecificParams} AutomaticSpeechRecognitionConfig\n * \n * @callback AutomaticSpeechRecognitionPipelineCallback Transcribe the audio sequence(s) given as inputs to text.\n * @param {AudioPipelineInputs} audio The input audio file(s) to be transcribed. The input is either:\n * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate\n * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API.\n * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`.\n * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise} An object containing the transcription text and optionally timestamps if `return_timestamps` is `true`.\n * \n * @typedef {TextAudioPipelineConstructorArgs & AutomaticSpeechRecognitionPipelineCallback & Disposable} AutomaticSpeechRecognitionPipelineType\n */\n\n/**\n * Pipeline that aims at extracting spoken text contained within some audio.\n *\n * **Example:** Transcribe English.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const output = await transcriber(url);\n * // { text: \" And so my fellow Americans ask not what your country can do for you, ask what you can do for your country.\" }\n * ```\n * \n * **Example:** Transcribe English w/ timestamps.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const output = await transcriber(url, { return_timestamps: true });\n * // {\n * // text: \" And so my fellow Americans ask not what your country can do for you, ask what you can do for your country.\"\n * // chunks: [\n * // { timestamp: [0, 8], text: \" And so my fellow Americans ask not what your country can do for you\" }\n * // { timestamp: [8, 11], text: \" ask what you can do for your country.\" }\n * // ]\n * // }\n * ```\n * \n * **Example:** Transcribe English w/ word-level timestamps.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const output = await transcriber(url, { return_timestamps: 'word' });\n * // {\n * // \"text\": \" And so my fellow Americans ask not what your country can do for you ask what you can do for your country.\",\n * // \"chunks\": [\n * // { \"text\": \" And\", \"timestamp\": [0, 0.78] },\n * // { \"text\": \" so\", \"timestamp\": [0.78, 1.06] },\n * // { \"text\": \" my\", \"timestamp\": [1.06, 1.46] },\n * // ...\n * // { \"text\": \" for\", \"timestamp\": [9.72, 9.92] },\n * // { \"text\": \" your\", \"timestamp\": [9.92, 10.22] },\n * // { \"text\": \" country.\", \"timestamp\": [10.22, 13.5] }\n * // ]\n * // }\n * ```\n * \n * **Example:** Transcribe French.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3';\n * const output = await transcriber(url, { language: 'french', task: 'transcribe' });\n * // { text: \" J'adore, j'aime, je n'aime pas, je déteste.\" }\n * ```\n * \n * **Example:** Translate French to English.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3';\n * const output = await transcriber(url, { language: 'french', task: 'translate' });\n * // { text: \" I love, I like, I don't like, I hate.\" }\n * ```\n * \n * **Example:** Transcribe/translate audio longer than 30 seconds.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/ted_60.wav';\n * const output = await transcriber(url, { chunk_length_s: 30, stride_length_s: 5 });\n * // { text: \" So in college, I was a government major, which means [...] So I'd start off light and I'd bump it up\" }\n * ```\n */\nexport class AutomaticSpeechRecognitionPipeline extends (/** @type {new (options: TextAudioPipelineConstructorArgs) => AutomaticSpeechRecognitionPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new AutomaticSpeechRecognitionPipeline.\n * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {AutomaticSpeechRecognitionPipelineCallback} */\n async _call(audio, kwargs = {}) {\n switch (this.model.config.model_type) {\n case 'whisper':\n return this._call_whisper(audio, kwargs)\n case 'wav2vec2':\n case 'wav2vec2-bert':\n case 'unispeech':\n case 'unispeech-sat':\n case 'hubert':\n return this._call_wav2vec2(audio, kwargs)\n default:\n throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)\n }\n }\n\n /**\n * @type {AutomaticSpeechRecognitionPipelineCallback}\n * @private\n */\n async _call_wav2vec2(audio, kwargs) {\n // TODO use kwargs\n\n if (kwargs.language) {\n console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to \"English\".');\n }\n if (kwargs.task) {\n console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to \"transcribe\".');\n }\n\n const single = !Array.isArray(audio);\n if (single) {\n audio = [/** @type {AudioInput} */ (audio)];\n }\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n const preparedAudios = await prepareAudios(audio, sampling_rate);\n\n const toReturn = [];\n for (const aud of preparedAudios) {\n const inputs = await this.processor(aud);\n const output = await this.model(inputs);\n const logits = output.logits[0];\n\n const predicted_ids = [];\n for (const item of logits) {\n predicted_ids.push(max(item.data)[1])\n }\n const predicted_sentences = this.tokenizer.decode(predicted_ids)\n toReturn.push({ text: predicted_sentences })\n }\n return single ? toReturn[0] : toReturn;\n }\n\n /**\n * @type {AutomaticSpeechRecognitionPipelineCallback}\n * @private\n */\n async _call_whisper(audio, kwargs) {\n const return_timestamps = kwargs.return_timestamps ?? false;\n const chunk_length_s = kwargs.chunk_length_s ?? 0;\n const force_full_sequences = kwargs.force_full_sequences ?? false;\n let stride_length_s = kwargs.stride_length_s ?? null;\n\n const generation_config = { ...kwargs }\n\n if (return_timestamps === 'word') {\n generation_config['return_token_timestamps'] = true;\n generation_config['return_timestamps'] = false; // Do not predict timestamp tokens\n }\n\n const single = !Array.isArray(audio);\n if (single) {\n audio = [/** @type {AudioInput} */ (audio)];\n }\n\n const time_precision = this.processor.feature_extractor.config.chunk_length / this.model.config.max_source_positions;\n const hop_length = this.processor.feature_extractor.config.hop_length;\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n const preparedAudios = await prepareAudios(audio, sampling_rate);\n\n const toReturn = [];\n for (const aud of preparedAudios) {\n /** @type {{stride: number[], input_features: Tensor, is_last: boolean, tokens?: bigint[], token_timestamps?: number[]}[]} */\n let chunks = [];\n if (chunk_length_s > 0) {\n if (stride_length_s === null) {\n stride_length_s = chunk_length_s / 6;\n } else if (chunk_length_s <= stride_length_s) {\n throw Error(\"`chunk_length_s` must be larger than `stride_length_s`.\")\n }\n\n // TODO support different stride_length_s (for left and right)\n\n const window = sampling_rate * chunk_length_s;\n const stride = sampling_rate * stride_length_s;\n const jump = window - 2 * stride;\n let offset = 0;\n\n // Create subarrays of audio with overlaps\n while (true) {\n const offset_end = offset + window;\n const subarr = aud.subarray(offset, offset_end);\n const feature = await this.processor(subarr);\n\n const is_first = offset === 0;\n const is_last = offset_end >= aud.length;\n chunks.push({\n stride: [\n subarr.length,\n is_first ? 0 : stride,\n is_last ? 0 : stride\n ],\n input_features: feature.input_features,\n is_last,\n })\n if (is_last) break;\n offset += jump;\n }\n\n } else {\n chunks = [{\n stride: [aud.length, 0, 0],\n input_features: (await this.processor(aud)).input_features,\n is_last: true\n }]\n }\n\n // Generate for each set of input features\n for (const chunk of chunks) {\n generation_config.num_frames = Math.floor(chunk.stride[0] / hop_length);\n\n // NOTE: doing sequentially for now\n const data = await this.model.generate({\n inputs: chunk.input_features,\n ...generation_config\n });\n\n // TODO: Right now we only get top beam\n if (return_timestamps === 'word') {\n chunk.tokens = data.sequences.tolist()[0];\n chunk.token_timestamps = data.token_timestamps.tolist()[0].map(\n (/** @type {number} */ x) => round(x, 2)\n );\n\n } else {\n chunk.tokens = (/** @type {Tensor} */(data))[0].tolist();\n }\n\n // convert stride to seconds\n chunk.stride = chunk.stride.map(x => x / sampling_rate);\n }\n\n // Merge text chunks\n // @ts-ignore\n const [full_text, optional] = this.tokenizer._decode_asr(chunks, {\n time_precision, return_timestamps, force_full_sequences\n });\n\n toReturn.push({ text: full_text, ...optional })\n }\n return single ? toReturn[0] : toReturn;\n }\n}\n\n/**\n * @typedef {Object} ImageToTextSingle\n * @property {string} generated_text The generated text.\n * @typedef {ImageToTextSingle[]} ImageToTextOutput\n * \n * @callback ImageToTextPipelineCallback Assign labels to the image(s) passed as inputs.\n * @param {ImagePipelineInputs} texts The images to be captioned.\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise} An object (or array of objects) containing the generated text(s).\n * \n * @typedef {TextImagePipelineConstructorArgs & ImageToTextPipelineCallback & Disposable} ImageToTextPipelineType\n */\n\n/**\n * Image To Text pipeline using a `AutoModelForVision2Seq`. This pipeline predicts a caption for a given image.\n * \n * **Example:** Generate a caption for an image w/ `Xenova/vit-gpt2-image-captioning`.\n * ```javascript\n * const captioner = await pipeline('image-to-text', 'Xenova/vit-gpt2-image-captioning');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';\n * const output = await captioner(url);\n * // [{ generated_text: 'a cat laying on a couch with another cat' }]\n * ```\n * \n * **Example:** Optical Character Recognition (OCR) w/ `Xenova/trocr-small-handwritten`.\n * ```javascript\n * const captioner = await pipeline('image-to-text', 'Xenova/trocr-small-handwritten');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/handwriting.jpg';\n * const output = await captioner(url);\n * // [{ generated_text: 'Mr. Brown commented icily.' }]\n * ```\n */\nexport class ImageToTextPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ImageToTextPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ImageToTextPipeline.\n * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ImageToTextPipelineCallback} */\n async _call(images, generate_kwargs = {}) {\n\n const isBatched = Array.isArray(images);\n const preparedImages = await prepareImages(images);\n\n const { pixel_values } = await this.processor(preparedImages);\n\n const toReturn = [];\n for (const batch of pixel_values) {\n batch.dims = [1, ...batch.dims]\n const output = await this.model.generate({ inputs: batch, ...generate_kwargs });\n const decoded = this.tokenizer.batch_decode(/** @type {Tensor} */(output), {\n skip_special_tokens: true,\n }).map(x => ({ generated_text: x.trim() }))\n toReturn.push(decoded);\n }\n\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} ImageClassificationSingle\n * @property {string} label The label identified by the model.\n * @property {number} score The score attributed by the model for that label.\n * @typedef {ImageClassificationSingle[]} ImageClassificationOutput\n * \n * @typedef {Object} ImageClassificationPipelineOptions Parameters specific to image classification pipelines.\n * @property {number} [top_k=1] The number of top labels that will be returned by the pipeline. \n * \n * @callback ImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The input images(s) to be classified.\n * @param {ImageClassificationPipelineOptions} [options] The options to use for image classification.\n * @returns {Promise} An array or object containing the predicted labels and scores.\n * \n * @typedef {ImagePipelineConstructorArgs & ImageClassificationPipelineCallback & Disposable} ImageClassificationPipelineType\n */\n\n/**\n * Image classification pipeline using any `AutoModelForImageClassification`.\n * This pipeline predicts the class of an image.\n * \n * **Example:** Classify an image.\n * ```javascript\n * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';\n * const output = await classifier(url);\n * // [\n * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 },\n * // ]\n * ```\n * \n * **Example:** Classify an image and return top `n` classes.\n * ```javascript\n * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';\n * const output = await classifier(url, { top_k: 3 });\n * // [\n * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 },\n * // { label: 'tiger cat', score: 0.3634825646877289 },\n * // { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 },\n * // ]\n * ```\n * \n * **Example:** Classify an image and return all classes.\n * ```javascript\n * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';\n * const output = await classifier(url, { top_k: 0 });\n * // [\n * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 },\n * // { label: 'tiger cat', score: 0.3634825646877289 },\n * // { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 },\n * // { label: 'jaguar, panther, Panthera onca, Felis onca', score: 0.00035465499968267977 },\n * // ...\n * // ]\n * ```\n */\nexport class ImageClassificationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ImageClassificationPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ImageClassificationPipelineCallback} */\n async _call(images, {\n top_k = 5\n } = {}) {\n\n const preparedImages = await prepareImages(images);\n\n const { pixel_values } = await this.processor(preparedImages);\n const output = await this.model({ pixel_values });\n\n const id2label = this.model.config.id2label;\n\n /** @type {ImageClassificationOutput[]} */\n const toReturn = [];\n for (const batch of output.logits) {\n const scores = await topk(new Tensor(\n 'float32',\n softmax(batch.data),\n batch.dims,\n ), top_k);\n\n const values = scores[0].tolist();\n const indices = scores[1].tolist();\n\n const vals = indices.map((x, i) => ({\n label: /** @type {string} */ (id2label ? id2label[x] : `LABEL_${x}`),\n score: /** @type {number} */ (values[i]),\n }));\n toReturn.push(vals);\n }\n\n return Array.isArray(images) ? toReturn : toReturn[0];\n }\n\n}\n\n/**\n * @typedef {Object} ImageSegmentationPipelineOutput\n * @property {string} label The label of the segment.\n * @property {number|null} score The score of the segment.\n * @property {RawImage} mask The mask of the segment.\n * \n * @typedef {Object} ImageSegmentationPipelineOptions Parameters specific to image segmentation pipelines.\n * @property {number} [threshold=0.5] Probability threshold to filter out predicted masks.\n * @property {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values.\n * @property {number} [overlap_mask_area_threshold=0.8] Mask overlap threshold to eliminate small, disconnected segments.\n * @property {null|string} [subtask=null] Segmentation task to be performed. One of [`panoptic`, `instance`, and `semantic`],\n * depending on model capabilities. If not set, the pipeline will attempt to resolve (in that order).\n * @property {number[]} [label_ids_to_fuse=null] List of label ids to fuse. If not set, do not fuse any labels.\n * @property {number[][]} [target_sizes=null] List of target sizes for the input images. If not set, use the original image sizes.\n * \n * @callback ImageSegmentationPipelineCallback Segment the input images.\n * @param {ImagePipelineInputs} images The input images.\n * @param {ImageSegmentationPipelineOptions} [options] The options to use for image segmentation.\n * @returns {Promise} The annotated segments.\n * \n * @typedef {ImagePipelineConstructorArgs & ImageSegmentationPipelineCallback & Disposable} ImageSegmentationPipelineType\n */\n\n/**\n * Image segmentation pipeline using any `AutoModelForXXXSegmentation`.\n * This pipeline predicts masks of objects and their classes.\n * \n * **Example:** Perform image segmentation with `Xenova/detr-resnet-50-panoptic`.\n * ```javascript\n * const segmenter = await pipeline('image-segmentation', 'Xenova/detr-resnet-50-panoptic');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';\n * const output = await segmenter(url);\n * // [\n * // { label: 'remote', score: 0.9984649419784546, mask: RawImage { ... } },\n * // { label: 'cat', score: 0.9994316101074219, mask: RawImage { ... } }\n * // ]\n * ```\n */\nexport class ImageSegmentationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageSegmentationPipelineType} */ (Pipeline)) {\n /**\n * Create a new ImageSegmentationPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n\n this.subtasks_mapping = {\n // Mapping of subtasks to their corresponding post-processing function names.\n panoptic: 'post_process_panoptic_segmentation',\n instance: 'post_process_instance_segmentation',\n semantic: 'post_process_semantic_segmentation'\n }\n }\n\n /** @type {ImageSegmentationPipelineCallback} */\n async _call(images, {\n threshold = 0.5,\n mask_threshold = 0.5,\n overlap_mask_area_threshold = 0.8,\n label_ids_to_fuse = null,\n target_sizes = null,\n subtask = null,\n } = {}) {\n const isBatched = Array.isArray(images);\n\n if (isBatched && images.length !== 1) {\n throw Error(\"Image segmentation pipeline currently only supports a batch size of 1.\");\n }\n\n const preparedImages = await prepareImages(images);\n const imageSizes = preparedImages.map(x => [x.height, x.width]);\n\n const { pixel_values, pixel_mask } = await this.processor(preparedImages);\n const output = await this.model({ pixel_values, pixel_mask });\n\n let fn = null;\n if (subtask !== null) {\n fn = this.subtasks_mapping[subtask];\n } else {\n for (let [task, func] of Object.entries(this.subtasks_mapping)) {\n if (func in this.processor.feature_extractor) {\n fn = this.processor.feature_extractor[func].bind(this.processor.feature_extractor);\n subtask = task;\n break;\n }\n }\n }\n\n const id2label = this.model.config.id2label;\n\n /** @type {ImageSegmentationPipelineOutput[]} */\n const annotation = [];\n if (subtask === 'panoptic' || subtask === 'instance') {\n const processed = fn(\n output,\n threshold,\n mask_threshold,\n overlap_mask_area_threshold,\n label_ids_to_fuse,\n target_sizes ?? imageSizes, // TODO FIX?\n )[0];\n\n const segmentation = processed.segmentation;\n\n for (const segment of processed.segments_info) {\n const maskData = new Uint8ClampedArray(segmentation.data.length);\n for (let i = 0; i < segmentation.data.length; ++i) {\n if (segmentation.data[i] === segment.id) {\n maskData[i] = 255;\n }\n }\n\n const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1)\n\n annotation.push({\n score: segment.score,\n label: id2label[segment.label_id],\n mask: mask\n })\n }\n\n } else if (subtask === 'semantic') {\n const { segmentation, labels } = fn(output, target_sizes ?? imageSizes)[0];\n\n for (const label of labels) {\n const maskData = new Uint8ClampedArray(segmentation.data.length);\n for (let i = 0; i < segmentation.data.length; ++i) {\n if (segmentation.data[i] === label) {\n maskData[i] = 255;\n }\n }\n\n const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1);\n\n annotation.push({\n score: null,\n label: id2label[label],\n mask: mask\n });\n }\n } else {\n throw Error(`Subtask ${subtask} not supported.`);\n }\n\n return annotation;\n }\n}\n\n/**\n * @typedef {Object} ZeroShotImageClassificationOutput\n * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`.\n * @property {number} score The score attributed by the model for that label (between 0 and 1).\n * \n * @typedef {Object} ZeroShotImageClassificationPipelineOptions Parameters specific to zero-shot image classification pipelines.\n * @property {string} [hypothesis_template=\"This is a photo of {}\"] The sentence used in conjunction with `candidate_labels`\n * to attempt the image classification by replacing the placeholder with the candidate_labels.\n * Then likelihood is estimated by using `logits_per_image`.\n * \n * @callback ZeroShotImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The input images.\n * @param {string[]} candidate_labels The candidate labels for this image.\n * @param {ZeroShotImageClassificationPipelineOptions} [options] The options to use for zero-shot image classification.\n * @returns {Promise} An array of objects containing the predicted labels and scores.\n * \n * @typedef {TextImagePipelineConstructorArgs & ZeroShotImageClassificationPipelineCallback & Disposable} ZeroShotImageClassificationPipelineType\n */\n\n/**\n * Zero shot image classification pipeline. This pipeline predicts the class of\n * an image when you provide an image and a set of `candidate_labels`.\n * \n * **Example:** Zero shot image classification w/ `Xenova/clip-vit-base-patch32`.\n * ```javascript\n * const classifier = await pipeline('zero-shot-image-classification', 'Xenova/clip-vit-base-patch32');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';\n * const output = await classifier(url, ['tiger', 'horse', 'dog']);\n * // [\n * // { score: 0.9993917942047119, label: 'tiger' },\n * // { score: 0.0003519294841680676, label: 'horse' },\n * // { score: 0.0002562698791734874, label: 'dog' }\n * // ]\n * ```\n */\nexport class ZeroShotImageClassificationPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotImageClassificationPipelineType} */ (Pipeline)) {\n /**\n * Create a new ZeroShotImageClassificationPipeline.\n * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ZeroShotImageClassificationPipelineCallback} */\n async _call(images, candidate_labels, {\n hypothesis_template = \"This is a photo of {}\"\n } = {}) {\n\n const isBatched = Array.isArray(images);\n const preparedImages = await prepareImages(images);\n\n // Insert label into hypothesis template \n const texts = candidate_labels.map(\n x => hypothesis_template.replace('{}', x)\n );\n\n // Run tokenization\n const text_inputs = this.tokenizer(texts, {\n padding: this.model.config.model_type === 'siglip' ? 'max_length' : true,\n truncation: true,\n });\n\n // Run processor\n const { pixel_values } = await this.processor(preparedImages);\n\n // Run model with both text and pixel inputs\n const output = await this.model({ ...text_inputs, pixel_values });\n\n const function_to_apply =\n this.model.config.model_type === 'siglip'\n ? batch => batch.sigmoid().data\n : batch => softmax(batch.data);\n\n // Compare each image with each candidate label\n const toReturn = [];\n for (const batch of output.logits_per_image) {\n // Compute softmax per image\n const probs = function_to_apply(batch);\n\n const result = [...probs].map((x, i) => ({\n score: x,\n label: candidate_labels[i]\n }));\n result.sort((a, b) => b.score - a.score); // sort by score in descending order\n toReturn.push(result);\n }\n\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n\n/**\n * @typedef {Object} ObjectDetectionPipelineSingle\n * @property {string} label The class label identified by the model.\n * @property {number} score The score attributed by the model for that label.\n * @property {BoundingBox} box The bounding box of detected object in image's original size, or as a percentage if `percentage` is set to true.\n * @typedef {ObjectDetectionPipelineSingle[]} ObjectDetectionPipelineOutput\n * \n * @typedef {Object} ObjectDetectionPipelineOptions Parameters specific to object detection pipelines.\n * @property {number} [threshold=0.9] The threshold used to filter boxes by score.\n * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false).\n * \n * @callback ObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The input images.\n * @param {ObjectDetectionPipelineOptions} [options] The options to use for object detection.\n * @returns {Promise} A list of objects or a list of list of objects. \n * \n * @typedef {ImagePipelineConstructorArgs & ObjectDetectionPipelineCallback & Disposable} ObjectDetectionPipelineType\n */\n\n/**\n * Object detection pipeline using any `AutoModelForObjectDetection`.\n * This pipeline predicts bounding boxes of objects and their classes.\n * \n * **Example:** Run object-detection with `Xenova/detr-resnet-50`.\n * ```javascript\n * const detector = await pipeline('object-detection', 'Xenova/detr-resnet-50');\n * const img = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';\n * const output = await detector(img, { threshold: 0.9 });\n * // [{\n * // score: 0.9976370930671692,\n * // label: \"remote\",\n * // box: { xmin: 31, ymin: 68, xmax: 190, ymax: 118 }\n * // },\n * // ...\n * // {\n * // score: 0.9984092116355896,\n * // label: \"cat\",\n * // box: { xmin: 331, ymin: 19, xmax: 649, ymax: 371 }\n * // }]\n * ```\n */\nexport class ObjectDetectionPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ObjectDetectionPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ObjectDetectionPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ObjectDetectionPipelineCallback} */\n async _call(images, {\n threshold = 0.9,\n percentage = false,\n } = {}) {\n\n const isBatched = Array.isArray(images);\n\n if (isBatched && images.length !== 1) {\n throw Error(\"Object detection pipeline currently only supports a batch size of 1.\");\n }\n const preparedImages = await prepareImages(images);\n\n const imageSizes = percentage ? null : preparedImages.map(x => [x.height, x.width]);\n\n const { pixel_values, pixel_mask } = await this.processor(preparedImages);\n const output = await this.model({ pixel_values, pixel_mask });\n\n // @ts-ignore\n const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSizes);\n\n // Add labels\n const id2label = this.model.config.id2label;\n\n // Format output\n /** @type {ObjectDetectionPipelineOutput[]} */\n const result = processed.map(batch => (\n batch.boxes.map((box, i) => ({\n score: batch.scores[i],\n label: id2label[batch.classes[i]],\n box: get_bounding_box(box, !percentage),\n }))\n ))\n\n return isBatched ? result : result[0];\n }\n}\n\n\n/**\n * @typedef {Object} ZeroShotObjectDetectionOutput\n * @property {string} label Text query corresponding to the found object.\n * @property {number} score Score corresponding to the object (between 0 and 1).\n * @property {BoundingBox} box Bounding box of the detected object in image's original size, or as a percentage if `percentage` is set to true.\n * \n * @typedef {Object} ZeroShotObjectDetectionPipelineOptions Parameters specific to zero-shot object detection pipelines.\n * @property {number} [threshold=0.1] The probability necessary to make a prediction.\n * @property {number} [top_k=null] The number of top predictions that will be returned by the pipeline.\n * If the provided number is `null` or higher than the number of predictions available, it will default\n * to the number of predictions.\n * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false).\n * \n * @callback ZeroShotObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The input images.\n * @param {string[]} candidate_labels What the model should recognize in the image.\n * @param {ZeroShotObjectDetectionPipelineOptions} [options] The options to use for zero-shot object detection.\n * @returns {Promise} An array of objects containing the predicted labels, scores, and bounding boxes.\n * \n * @typedef {TextImagePipelineConstructorArgs & ZeroShotObjectDetectionPipelineCallback & Disposable} ZeroShotObjectDetectionPipelineType\n */\n\n/**\n * Zero-shot object detection pipeline. This pipeline predicts bounding boxes of\n * objects when you provide an image and a set of `candidate_labels`.\n * \n * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32`.\n * ```javascript\n * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/astronaut.png';\n * const candidate_labels = ['human face', 'rocket', 'helmet', 'american flag'];\n * const output = await detector(url, candidate_labels);\n * // [\n * // {\n * // score: 0.24392342567443848,\n * // label: 'human face',\n * // box: { xmin: 180, ymin: 67, xmax: 274, ymax: 175 }\n * // },\n * // {\n * // score: 0.15129457414150238,\n * // label: 'american flag',\n * // box: { xmin: 0, ymin: 4, xmax: 106, ymax: 513 }\n * // },\n * // {\n * // score: 0.13649864494800568,\n * // label: 'helmet',\n * // box: { xmin: 277, ymin: 337, xmax: 511, ymax: 511 }\n * // },\n * // {\n * // score: 0.10262022167444229,\n * // label: 'rocket',\n * // box: { xmin: 352, ymin: -1, xmax: 463, ymax: 287 }\n * // }\n * // ]\n * ```\n * \n * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32` (returning top 4 matches and setting a threshold).\n * ```javascript\n * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/beach.png';\n * const candidate_labels = ['hat', 'book', 'sunglasses', 'camera'];\n * const output = await detector(url, candidate_labels, { top_k: 4, threshold: 0.05 });\n * // [\n * // {\n * // score: 0.1606510728597641,\n * // label: 'sunglasses',\n * // box: { xmin: 347, ymin: 229, xmax: 429, ymax: 264 }\n * // },\n * // {\n * // score: 0.08935828506946564,\n * // label: 'hat',\n * // box: { xmin: 38, ymin: 174, xmax: 258, ymax: 364 }\n * // },\n * // {\n * // score: 0.08530698716640472,\n * // label: 'camera',\n * // box: { xmin: 187, ymin: 350, xmax: 260, ymax: 411 }\n * // },\n * // {\n * // score: 0.08349756896495819,\n * // label: 'book',\n * // box: { xmin: 261, ymin: 280, xmax: 494, ymax: 425 }\n * // }\n * // ]\n * ```\n */\nexport class ZeroShotObjectDetectionPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotObjectDetectionPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ZeroShotObjectDetectionPipeline.\n * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ZeroShotObjectDetectionPipelineCallback} */\n async _call(images, candidate_labels, {\n threshold = 0.1,\n top_k = null,\n percentage = false,\n } = {}) {\n\n const isBatched = Array.isArray(images);\n const preparedImages = await prepareImages(images);\n\n // Run tokenization\n const text_inputs = this.tokenizer(candidate_labels, {\n padding: true,\n truncation: true,\n });\n\n // Run processor\n const model_inputs = await this.processor(preparedImages);\n\n // Since non-maximum suppression is performed for exporting, we need to\n // process each image separately. For more information, see:\n // https://github.com/huggingface/optimum/blob/e3b7efb1257c011db907ef40ab340e795cc5684c/optimum/exporters/onnx/model_configs.py#L1028-L1032\n const toReturn = [];\n for (let i = 0; i < preparedImages.length; ++i) {\n const image = preparedImages[i];\n const imageSize = percentage ? null : [[image.height, image.width]];\n const pixel_values = model_inputs.pixel_values[i].unsqueeze_(0);\n\n // Run model with both text and pixel inputs\n const output = await this.model({ ...text_inputs, pixel_values });\n\n // @ts-ignore\n const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSize, true)[0];\n let result = processed.boxes.map((box, i) => ({\n score: processed.scores[i],\n label: candidate_labels[processed.classes[i]],\n box: get_bounding_box(box, !percentage),\n })).sort((a, b) => b.score - a.score);\n if (top_k !== null) {\n result = result.slice(0, top_k);\n }\n toReturn.push(result)\n }\n\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} DocumentQuestionAnsweringSingle\n * @property {string} answer The generated text.\n * @typedef {DocumentQuestionAnsweringSingle[]} DocumentQuestionAnsweringOutput\n * \n * @callback DocumentQuestionAnsweringPipelineCallback Answer the question given as input by using the document.\n * @param {ImageInput} image The image of the document to use.\n * @param {string} question A question to ask of the document.\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise} An object (or array of objects) containing the answer(s).\n * \n * @typedef {TextImagePipelineConstructorArgs & DocumentQuestionAnsweringPipelineCallback & Disposable} DocumentQuestionAnsweringPipelineType\n */\n\n/**\n * Document Question Answering pipeline using any `AutoModelForDocumentQuestionAnswering`.\n * The inputs/outputs are similar to the (extractive) question answering pipeline; however,\n * the pipeline takes an image (and optional OCR'd words/boxes) as input instead of text context.\n * \n * **Example:** Answer questions about a document with `Xenova/donut-base-finetuned-docvqa`.\n * ```javascript\n * const qa_pipeline = await pipeline('document-question-answering', 'Xenova/donut-base-finetuned-docvqa');\n * const image = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/invoice.png';\n * const question = 'What is the invoice number?';\n * const output = await qa_pipeline(image, question);\n * // [{ answer: 'us-001' }]\n * ```\n */\nexport class DocumentQuestionAnsweringPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => DocumentQuestionAnsweringPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new DocumentQuestionAnsweringPipeline.\n * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {DocumentQuestionAnsweringPipelineCallback} */\n async _call(image, question, generate_kwargs = {}) {\n throw new Error('This pipeline is not yet supported in Transformers.js v3.'); // TODO: Remove when implemented\n\n // NOTE: For now, we only support a batch size of 1\n\n // Preprocess image\n const preparedImage = (await prepareImages(image))[0];\n const { pixel_values } = await this.processor(preparedImage);\n\n // Run tokenization\n const task_prompt = `${question}`;\n const decoder_input_ids = this.tokenizer(task_prompt, {\n add_special_tokens: false,\n padding: true,\n truncation: true,\n }).input_ids;\n\n // Run model\n const output = await this.model.generate({\n inputs: pixel_values,\n max_length: this.model.config.decoder.max_position_embeddings,\n decoder_input_ids,\n ...generate_kwargs,\n });\n\n // Decode output\n const decoded = this.tokenizer.batch_decode(/** @type {Tensor} */(output))[0];\n\n // Parse answer\n const match = decoded.match(/(.*?)<\\/s_answer>/);\n let answer = null;\n if (match && match.length >= 2) {\n answer = match[1].trim();\n }\n return [{ answer }];\n }\n}\n\n\n/**\n * @typedef {Object} VocoderOptions\n * @property {PreTrainedModel} [vocoder] The vocoder used by the pipeline (if the model uses one). If not provided, use the default HifiGan vocoder.\n * @typedef {TextAudioPipelineConstructorArgs & VocoderOptions} TextToAudioPipelineConstructorArgs\n */\n\n/**\n * @typedef {Object} TextToAudioOutput\n * @property {Float32Array} audio The generated audio waveform.\n * @property {number} sampling_rate The sampling rate of the generated audio waveform.\n * \n * @typedef {Object} TextToAudioPipelineOptions Parameters specific to text-to-audio pipelines.\n * @property {Tensor|Float32Array|string|URL} [speaker_embeddings=null] The speaker embeddings (if the model requires it).\n * \n * @callback TextToAudioPipelineCallback Generates speech/audio from the inputs.\n * @param {string|string[]} texts The text(s) to generate.\n * @param {TextToAudioPipelineOptions} options Parameters passed to the model generation/forward method.\n * @returns {Promise} An object containing the generated audio and sampling rate.\n * \n * @typedef {TextToAudioPipelineConstructorArgs & TextToAudioPipelineCallback & Disposable} TextToAudioPipelineType\n */\n\n/**\n * Text-to-audio generation pipeline using any `AutoModelForTextToWaveform` or `AutoModelForTextToSpectrogram`.\n * This pipeline generates an audio file from an input text and optional other conditional inputs.\n * \n * **Example:** Generate audio from text with `Xenova/speecht5_tts`.\n * ```javascript\n * const synthesizer = await pipeline('text-to-speech', 'Xenova/speecht5_tts', { quantized: false });\n * const speaker_embeddings = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin';\n * const out = await synthesizer('Hello, my dog is cute', { speaker_embeddings });\n * // {\n * // audio: Float32Array(26112) [-0.00005657337896991521, 0.00020583874720614403, ...],\n * // sampling_rate: 16000\n * // }\n * ```\n * \n * You can then save the audio to a .wav file with the `wavefile` package:\n * ```javascript\n * import wavefile from 'wavefile';\n * import fs from 'fs';\n * \n * const wav = new wavefile.WaveFile();\n * wav.fromScratch(1, out.sampling_rate, '32f', out.audio);\n * fs.writeFileSync('out.wav', wav.toBuffer());\n * ```\n * \n * **Example:** Multilingual speech generation with `Xenova/mms-tts-fra`. See [here](https://huggingface.co/models?pipeline_tag=text-to-speech&other=vits&sort=trending) for the full list of available languages (1107).\n * ```javascript\n * const synthesizer = await pipeline('text-to-speech', 'Xenova/mms-tts-fra');\n * const out = await synthesizer('Bonjour');\n * // {\n * // audio: Float32Array(23808) [-0.00037693005288019776, 0.0003325853613205254, ...],\n * // sampling_rate: 16000\n * // }\n * ```\n */\nexport class TextToAudioPipeline extends (/** @type {new (options: TextToAudioPipelineConstructorArgs) => TextToAudioPipelineType} */ (Pipeline)) {\n DEFAULT_VOCODER_ID = \"Xenova/speecht5_hifigan\"\n\n /**\n * Create a new TextToAudioPipeline.\n * @param {TextToAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n\n // TODO: Find a better way for `pipeline` to set the default vocoder\n this.vocoder = options.vocoder ?? null;\n }\n\n\n /** @type {TextToAudioPipelineCallback} */\n async _call(text_inputs, {\n speaker_embeddings = null,\n } = {}) {\n\n // If this.processor is not set, we are using a `AutoModelForTextToWaveform` model\n if (this.processor) {\n return this._call_text_to_spectrogram(text_inputs, { speaker_embeddings });\n } else {\n return this._call_text_to_waveform(text_inputs);\n }\n }\n\n async _call_text_to_waveform(text_inputs) {\n\n // Run tokenization\n const inputs = this.tokenizer(text_inputs, {\n padding: true,\n truncation: true,\n });\n\n // Generate waveform\n const { waveform } = await this.model(inputs);\n\n const sampling_rate = this.model.config.sampling_rate;\n return {\n audio: waveform.data,\n sampling_rate,\n }\n }\n\n async _call_text_to_spectrogram(text_inputs, { speaker_embeddings }) {\n\n // Load vocoder, if not provided\n if (!this.vocoder) {\n console.log('No vocoder specified, using default HifiGan vocoder.');\n this.vocoder = await AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID, { dtype: 'fp32' });\n }\n\n // Load speaker embeddings as Float32Array from path/URL\n if (typeof speaker_embeddings === 'string' || speaker_embeddings instanceof URL) {\n // Load from URL with fetch\n speaker_embeddings = new Float32Array(\n await (await fetch(speaker_embeddings)).arrayBuffer()\n );\n }\n\n if (speaker_embeddings instanceof Float32Array) {\n speaker_embeddings = new Tensor(\n 'float32',\n speaker_embeddings,\n [1, speaker_embeddings.length]\n )\n } else if (!(speaker_embeddings instanceof Tensor)) {\n throw new Error(\"Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.\")\n }\n\n // Run tokenization\n const { input_ids } = this.tokenizer(text_inputs, {\n padding: true,\n truncation: true,\n });\n\n // NOTE: At this point, we are guaranteed that `speaker_embeddings` is a `Tensor`\n // @ts-ignore\n const { waveform } = await this.model.generate_speech(input_ids, speaker_embeddings, { vocoder: this.vocoder });\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n return {\n audio: waveform.data,\n sampling_rate,\n }\n }\n}\n\n/**\n * @callback ImageToImagePipelineCallback Transform the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The images to transform.\n * @returns {Promise} The transformed image or list of images.\n * \n * @typedef {ImagePipelineConstructorArgs & ImageToImagePipelineCallback & Disposable} ImageToImagePipelineType\n */\n\n/**\n * Image to Image pipeline using any `AutoModelForImageToImage`. This pipeline generates an image based on a previous image input.\n * \n * **Example:** Super-resolution w/ `Xenova/swin2SR-classical-sr-x2-64`\n * ```javascript\n * const upscaler = await pipeline('image-to-image', 'Xenova/swin2SR-classical-sr-x2-64');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg';\n * const output = await upscaler(url);\n * // RawImage {\n * // data: Uint8Array(786432) [ 41, 31, 24, 43, ... ],\n * // width: 512,\n * // height: 512,\n * // channels: 3\n * // }\n * ```\n */\nexport class ImageToImagePipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageToImagePipelineType} */ (Pipeline)) {\n /**\n * Create a new ImageToImagePipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ImageToImagePipelineCallback} */\n async _call(images) {\n\n const preparedImages = await prepareImages(images);\n const inputs = await this.processor(preparedImages);\n const outputs = await this.model(inputs);\n\n /** @type {RawImage[]} */\n const toReturn = [];\n for (const batch of outputs.reconstruction) {\n const output = batch.squeeze().clamp_(0, 1).mul_(255).round_().to('uint8');\n toReturn.push(RawImage.fromTensor(output));\n }\n\n return toReturn.length > 1 ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} DepthEstimationPipelineOutput\n * @property {Tensor} predicted_depth The raw depth map predicted by the model.\n * @property {RawImage} depth The processed depth map as an image (with the same size as the input image).\n * \n * @callback DepthEstimationPipelineCallback Predicts the depth for the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The images to compute depth for.\n * @returns {Promise} An image or a list of images containing result(s).\n * \n * @typedef {ImagePipelineConstructorArgs & DepthEstimationPipelineCallback & Disposable} DepthEstimationPipelineType\n */\n\n/**\n * Depth estimation pipeline using any `AutoModelForDepthEstimation`. This pipeline predicts the depth of an image.\n * \n * **Example:** Depth estimation w/ `Xenova/dpt-hybrid-midas`\n * ```javascript\n * const depth_estimator = await pipeline('depth-estimation', 'Xenova/dpt-hybrid-midas');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';\n * const out = await depth_estimator(url);\n * // {\n * // predicted_depth: Tensor {\n * // dims: [ 384, 384 ],\n * // type: 'float32',\n * // data: Float32Array(147456) [ 542.859130859375, 545.2833862304688, 546.1649169921875, ... ],\n * // size: 147456\n * // },\n * // depth: RawImage {\n * // data: Uint8Array(307200) [ 86, 86, 86, ... ],\n * // width: 640,\n * // height: 480,\n * // channels: 1\n * // }\n * // }\n * ```\n */\nexport class DepthEstimationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => DepthEstimationPipelineType} */ (Pipeline)) {\n /**\n * Create a new DepthEstimationPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {DepthEstimationPipelineCallback} */\n async _call(images) {\n\n const preparedImages = await prepareImages(images);\n\n const inputs = await this.processor(preparedImages);\n const { predicted_depth } = await this.model(inputs);\n\n const toReturn = [];\n for (let i = 0; i < preparedImages.length; ++i) {\n const prediction = interpolate(predicted_depth[i], preparedImages[i].size.reverse(), 'bilinear', false);\n const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8');\n toReturn.push({\n predicted_depth: predicted_depth[i],\n depth: RawImage.fromTensor(formatted),\n });\n }\n\n return toReturn.length > 1 ? toReturn : toReturn[0];\n }\n}\n\nconst SUPPORTED_TASKS = Object.freeze({\n \"text-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TextClassificationPipeline,\n \"model\": AutoModelForSequenceClassification,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"distilbert-base-uncased-finetuned-sst-2-english\",\n \"model\": \"Xenova/distilbert-base-uncased-finetuned-sst-2-english\",\n },\n \"type\": \"text\",\n },\n \"token-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TokenClassificationPipeline,\n \"model\": AutoModelForTokenClassification,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"Davlan/bert-base-multilingual-cased-ner-hrl\",\n \"model\": \"Xenova/bert-base-multilingual-cased-ner-hrl\",\n },\n \"type\": \"text\",\n },\n \"question-answering\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": QuestionAnsweringPipeline,\n \"model\": AutoModelForQuestionAnswering,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"distilbert-base-cased-distilled-squad\",\n \"model\": \"Xenova/distilbert-base-cased-distilled-squad\",\n },\n \"type\": \"text\",\n },\n\n \"fill-mask\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": FillMaskPipeline,\n \"model\": AutoModelForMaskedLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"bert-base-uncased\",\n \"model\": \"Xenova/bert-base-uncased\",\n },\n \"type\": \"text\",\n },\n \"summarization\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": SummarizationPipeline,\n \"model\": AutoModelForSeq2SeqLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"sshleifer/distilbart-cnn-6-6\",\n \"model\": \"Xenova/distilbart-cnn-6-6\",\n },\n \"type\": \"text\",\n },\n \"translation\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TranslationPipeline,\n \"model\": AutoModelForSeq2SeqLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"t5-small\",\n \"model\": \"Xenova/t5-small\",\n },\n \"type\": \"text\",\n },\n \"text2text-generation\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": Text2TextGenerationPipeline,\n \"model\": AutoModelForSeq2SeqLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"google/flan-t5-small\",\n \"model\": \"Xenova/flan-t5-small\",\n },\n \"type\": \"text\",\n },\n \"text-generation\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TextGenerationPipeline,\n \"model\": AutoModelForCausalLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"gpt2\",\n \"model\": \"Xenova/gpt2\",\n },\n \"type\": \"text\",\n },\n \"zero-shot-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ZeroShotClassificationPipeline,\n \"model\": AutoModelForSequenceClassification,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"typeform/distilbert-base-uncased-mnli\",\n \"model\": \"Xenova/distilbert-base-uncased-mnli\",\n },\n \"type\": \"text\",\n },\n \"audio-classification\": {\n \"pipeline\": AudioClassificationPipeline,\n \"model\": AutoModelForAudioClassification,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"superb/wav2vec2-base-superb-ks\",\n \"model\": \"Xenova/wav2vec2-base-superb-ks\",\n },\n \"type\": \"audio\",\n },\n \"zero-shot-audio-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ZeroShotAudioClassificationPipeline,\n \"model\": AutoModel,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"laion/clap-htsat-fused\",\n \"model\": \"Xenova/clap-htsat-unfused\",\n },\n \"type\": \"multimodal\",\n },\n \"automatic-speech-recognition\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": AutomaticSpeechRecognitionPipeline,\n \"model\": [AutoModelForSpeechSeq2Seq, AutoModelForCTC],\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"openai/whisper-tiny.en\",\n \"model\": \"Xenova/whisper-tiny.en\",\n },\n \"type\": \"multimodal\",\n },\n \"text-to-audio\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TextToAudioPipeline,\n \"model\": [AutoModelForTextToWaveform, AutoModelForTextToSpectrogram],\n \"processor\": [AutoProcessor, /* Some don't use a processor */ null],\n \"default\": {\n // TODO: replace with original\n // \"model\": \"microsoft/speecht5_tts\",\n \"model\": \"Xenova/speecht5_tts\",\n },\n \"type\": \"text\",\n },\n \"image-to-text\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ImageToTextPipeline,\n \"model\": AutoModelForVision2Seq,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"nlpconnect/vit-gpt2-image-captioning\",\n \"model\": \"Xenova/vit-gpt2-image-captioning\",\n },\n \"type\": \"multimodal\",\n },\n\n \"image-classification\": {\n // no tokenizer\n \"pipeline\": ImageClassificationPipeline,\n \"model\": AutoModelForImageClassification,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"google/vit-base-patch16-224\",\n \"model\": \"Xenova/vit-base-patch16-224\",\n },\n \"type\": \"multimodal\",\n },\n\n \"image-segmentation\": {\n // no tokenizer\n \"pipeline\": ImageSegmentationPipeline,\n \"model\": [AutoModelForImageSegmentation, AutoModelForSemanticSegmentation, AutoModelForUniversalSegmentation],\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"facebook/detr-resnet-50-panoptic\",\n \"model\": \"Xenova/detr-resnet-50-panoptic\",\n },\n \"type\": \"multimodal\",\n },\n\n \"zero-shot-image-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ZeroShotImageClassificationPipeline,\n \"model\": AutoModel,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"openai/clip-vit-base-patch32\",\n \"model\": \"Xenova/clip-vit-base-patch32\",\n },\n \"type\": \"multimodal\",\n },\n\n \"object-detection\": {\n // no tokenizer\n \"pipeline\": ObjectDetectionPipeline,\n \"model\": AutoModelForObjectDetection,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"facebook/detr-resnet-50\",\n \"model\": \"Xenova/detr-resnet-50\",\n },\n \"type\": \"multimodal\",\n },\n \"zero-shot-object-detection\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ZeroShotObjectDetectionPipeline,\n \"model\": AutoModelForZeroShotObjectDetection,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"google/owlvit-base-patch32\",\n \"model\": \"Xenova/owlvit-base-patch32\",\n },\n \"type\": \"multimodal\",\n },\n \"document-question-answering\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": DocumentQuestionAnsweringPipeline,\n \"model\": AutoModelForDocumentQuestionAnswering,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"naver-clova-ix/donut-base-finetuned-docvqa\",\n \"model\": \"Xenova/donut-base-finetuned-docvqa\",\n },\n \"type\": \"multimodal\",\n },\n \"image-to-image\": {\n // no tokenizer\n \"pipeline\": ImageToImagePipeline,\n \"model\": AutoModelForImageToImage,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"caidas/swin2SR-classical-sr-x2-64\",\n \"model\": \"Xenova/swin2SR-classical-sr-x2-64\",\n },\n \"type\": \"image\",\n },\n \"depth-estimation\": {\n // no tokenizer\n \"pipeline\": DepthEstimationPipeline,\n \"model\": AutoModelForDepthEstimation,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"Intel/dpt-large\",\n \"model\": \"Xenova/dpt-large\",\n },\n \"type\": \"image\",\n },\n\n // This task serves as a useful interface for dealing with sentence-transformers (https://huggingface.co/sentence-transformers).\n \"feature-extraction\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": FeatureExtractionPipeline,\n \"model\": AutoModel,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"sentence-transformers/all-MiniLM-L6-v2\",\n \"model\": \"Xenova/all-MiniLM-L6-v2\",\n },\n \"type\": \"text\",\n },\n \"image-feature-extraction\": {\n \"processor\": AutoProcessor,\n \"pipeline\": ImageFeatureExtractionPipeline,\n \"model\": [AutoModelForImageFeatureExtraction, AutoModel],\n \"default\": {\n // TODO: replace with original\n // \"model\": \"google/vit-base-patch16-224\",\n \"model\": \"Xenova/vit-base-patch16-224-in21k\",\n },\n \"type\": \"image\",\n },\n})\n\n\n// TODO: Add types for TASK_ALIASES\nconst TASK_ALIASES = Object.freeze({\n \"sentiment-analysis\": \"text-classification\",\n \"ner\": \"token-classification\",\n // \"vqa\": \"visual-question-answering\", // TODO: Add\n \"asr\": \"automatic-speech-recognition\",\n \"text-to-speech\": \"text-to-audio\",\n\n // Add for backwards compatibility\n \"embeddings\": \"feature-extraction\",\n});\n\n/**\n * @typedef {keyof typeof SUPPORTED_TASKS} TaskType\n * @typedef {keyof typeof TASK_ALIASES} AliasType\n * @typedef {TaskType | AliasType} PipelineType All possible pipeline types.\n * @typedef {{[K in TaskType]: InstanceType}} SupportedTasks A mapping of pipeline names to their corresponding pipeline classes.\n * @typedef {{[K in AliasType]: InstanceType}} AliasTasks A mapping from pipeline aliases to their corresponding pipeline classes.\n * @typedef {SupportedTasks & AliasTasks} AllTasks A mapping from all pipeline names and aliases to their corresponding pipeline classes.\n */\n\n/**\n * Utility factory method to build a `Pipeline` object.\n * \n * @template {PipelineType} T The type of pipeline to return.\n * @param {T} task The task defining which pipeline will be returned. Currently accepted tasks are:\n * - `\"audio-classification\"`: will return a `AudioClassificationPipeline`.\n * - `\"automatic-speech-recognition\"`: will return a `AutomaticSpeechRecognitionPipeline`.\n * - `\"depth-estimation\"`: will return a `DepthEstimationPipeline`.\n * - `\"document-question-answering\"`: will return a `DocumentQuestionAnsweringPipeline`.\n * - `\"feature-extraction\"`: will return a `FeatureExtractionPipeline`.\n * - `\"fill-mask\"`: will return a `FillMaskPipeline`.\n * - `\"image-classification\"`: will return a `ImageClassificationPipeline`.\n * - `\"image-segmentation\"`: will return a `ImageSegmentationPipeline`.\n * - `\"image-to-text\"`: will return a `ImageToTextPipeline`.\n * - `\"object-detection\"`: will return a `ObjectDetectionPipeline`.\n * - `\"question-answering\"`: will return a `QuestionAnsweringPipeline`.\n * - `\"summarization\"`: will return a `SummarizationPipeline`.\n * - `\"text2text-generation\"`: will return a `Text2TextGenerationPipeline`.\n * - `\"text-classification\"` (alias \"sentiment-analysis\" available): will return a `TextClassificationPipeline`.\n * - `\"text-generation\"`: will return a `TextGenerationPipeline`.\n * - `\"token-classification\"` (alias \"ner\" available): will return a `TokenClassificationPipeline`.\n * - `\"translation\"`: will return a `TranslationPipeline`.\n * - `\"translation_xx_to_yy\"`: will return a `TranslationPipeline`.\n * - `\"zero-shot-classification\"`: will return a `ZeroShotClassificationPipeline`.\n * - `\"zero-shot-audio-classification\"`: will return a `ZeroShotAudioClassificationPipeline`.\n * - `\"zero-shot-image-classification\"`: will return a `ZeroShotImageClassificationPipeline`.\n * - `\"zero-shot-object-detection\"`: will return a `ZeroShotObjectDetectionPipeline`.\n * @param {string} [model=null] The name of the pre-trained model to use. If not specified, the default model for the task will be used.\n * @param {import('./utils/hub.js').PretrainedModelOptions} [options] Optional parameters for the pipeline.\n * @returns {Promise} A Pipeline object for the specified task.\n * @throws {Error} If an unsupported pipeline is requested.\n */\nexport async function pipeline(\n task,\n model = null,\n {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n device = null,\n dtype = null,\n model_file_name = null,\n session_options = {},\n } = {}\n) {\n // Helper method to construct pipeline\n\n // Apply aliases\n // @ts-ignore\n task = TASK_ALIASES[task] ?? task;\n\n // Get pipeline info\n const pipelineInfo = SUPPORTED_TASKS[task.split('_', 1)[0]];\n if (!pipelineInfo) {\n throw Error(`Unsupported pipeline: ${task}. Must be one of [${Object.keys(SUPPORTED_TASKS)}]`)\n }\n\n // Use model if specified, otherwise, use default\n if (!model) {\n model = pipelineInfo.default.model\n console.log(`No model specified. Using default model: \"${model}\".`);\n }\n\n const pretrainedOptions = {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n device,\n dtype,\n model_file_name,\n session_options,\n }\n\n const classes = new Map([\n ['tokenizer', pipelineInfo.tokenizer],\n ['model', pipelineInfo.model],\n ['processor', pipelineInfo.processor],\n ]);\n\n // Load model, tokenizer, and processor (if they exist)\n const results = await loadItems(classes, model, pretrainedOptions);\n results.task = task;\n\n dispatchCallback(progress_callback, {\n 'status': 'ready',\n 'task': task,\n 'model': model,\n });\n\n const pipelineClass = pipelineInfo.pipeline;\n return new pipelineClass(results);\n}\n\n\n/**\n * Helper function to get applicable model, tokenizer, or processor classes for a given model.\n * @param {Map} mapping The mapping of names to classes, arrays of classes, or null.\n * @param {string} model The name of the model to load.\n * @param {import('./utils/hub.js').PretrainedOptions} pretrainedOptions The options to pass to the `from_pretrained` method.\n * @private\n */\nasync function loadItems(mapping, model, pretrainedOptions) {\n\n const result = Object.create(null);\n\n /**@type {Promise[]} */\n const promises = [];\n for (const [name, cls] of mapping.entries()) {\n if (!cls) continue;\n\n /**@type {Promise} */\n let promise;\n if (Array.isArray(cls)) {\n promise = new Promise(async (resolve, reject) => {\n let e;\n for (const c of cls) {\n if (c === null) {\n // If null, we resolve it immediately, meaning the relevant\n // class was not found, but it is optional.\n resolve(null);\n return;\n }\n try {\n resolve(await c.from_pretrained(model, pretrainedOptions));\n return;\n } catch (err) {\n if (err.message?.includes('Unsupported model type')) {\n // If the error is due to an unsupported model type, we\n // save the error and try the next class.\n e = err;\n } else if (err.message?.includes('Could not locate file')) {\n e = err;\n } else {\n reject(err);\n return;\n }\n\n }\n }\n reject(e);\n })\n } else {\n promise = cls.from_pretrained(model, pretrainedOptions);\n }\n\n result[name] = promise;\n promises.push(promise);\n }\n\n // Wait for all promises to resolve (in parallel)\n await Promise.all(promises);\n\n // Then assign to result\n for (const [name, promise] of Object.entries(result)) {\n result[name] = await promise;\n }\n\n return result;\n}","\n/**\n * @file Processors are used to prepare non-textual inputs (e.g., image or audio) for a model.\n * \n * **Example:** Using a `WhisperProcessor` to prepare an audio input for a model.\n * ```javascript\n * import { AutoProcessor, read_audio } from '@huggingface/transformers';\n *\n * let processor = await AutoProcessor.from_pretrained('openai/whisper-tiny.en');\n * let audio = await read_audio('https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac', 16000);\n * let { input_features } = await processor(audio);\n * // Tensor {\n * // data: Float32Array(240000) [0.4752984642982483, 0.5597258806228638, 0.56434166431427, ...],\n * // dims: [1, 80, 3000],\n * // type: 'float32',\n * // size: 240000,\n * // }\n * ```\n * \n * @module processors\n */\nimport {\n Callable,\n} from './utils/generic.js';\n\nimport {\n calculateDimensions,\n calculateReflectOffset,\n} from './utils/core.js';\n\nimport {\n getModelJSON,\n} from './utils/hub.js';\n\nimport {\n min,\n max,\n softmax,\n bankers_round,\n} from './utils/maths.js';\n\n\nimport { Tensor, cat, interpolate, stack, interpolate_4d, full } from './utils/tensor.js';\n\nimport { RawImage } from './utils/image.js';\nimport {\n window_function,\n spectrogram,\n mel_filter_bank,\n} from './utils/audio.js';\n\n\n// Helper functions\n\n/**\n * Converts bounding boxes from center format to corners format.\n * \n * @param {number[]} arr The coordinate for the center of the box and its width, height dimensions (center_x, center_y, width, height)\n * @returns {number[]} The coodinates for the top-left and bottom-right corners of the box (top_left_x, top_left_y, bottom_right_x, bottom_right_y)\n */\nfunction center_to_corners_format([centerX, centerY, width, height]) {\n return [\n centerX - width / 2,\n centerY - height / 2,\n centerX + width / 2,\n centerY + height / 2\n ];\n}\n\n/**\n * Post-processes the outputs of the model (for object detection).\n * @param {Object} outputs The outputs of the model that must be post-processed\n * @param {Tensor} outputs.logits The logits\n * @param {Tensor} outputs.pred_boxes The predicted boxes.\n * @param {number} [threshold=0.5] The threshold to use for the scores.\n * @param {[number, number][]} [target_sizes=null] The sizes of the original images.\n * @param {boolean} [is_zero_shot=false] Whether zero-shot object detection was performed.\n * @return {Object[]} An array of objects containing the post-processed outputs.\n * @private\n */\nfunction post_process_object_detection(outputs, threshold = 0.5, target_sizes = null, is_zero_shot = false) {\n const out_logits = outputs.logits;\n const out_bbox = outputs.pred_boxes;\n const [batch_size, num_boxes, num_classes] = out_logits.dims;\n\n if (target_sizes !== null && target_sizes.length !== batch_size) {\n throw Error(\"Make sure that you pass in as many target sizes as the batch dimension of the logits\")\n }\n let toReturn = [];\n for (let i = 0; i < batch_size; ++i) {\n let target_size = target_sizes !== null ? target_sizes[i] : null;\n let info = {\n boxes: [],\n classes: [],\n scores: []\n }\n let logits = out_logits[i];\n let bbox = out_bbox[i];\n\n for (let j = 0; j < num_boxes; ++j) {\n let logit = logits[j];\n\n let indices = [];\n let probs;\n if (is_zero_shot) {\n // Get indices of classes with high enough probability\n probs = logit.sigmoid().data;\n for (let k = 0; k < probs.length; ++k) {\n if (probs[k] > threshold) {\n indices.push(k);\n }\n }\n\n } else {\n // Get most probable class\n let maxIndex = max(logit.data)[1];\n\n if (maxIndex === num_classes - 1) {\n // This is the background class, skip it\n continue;\n }\n // Compute softmax over classes\n probs = softmax(logit.data);\n\n if (probs[maxIndex] < threshold) {\n continue;\n }\n indices.push(maxIndex);\n }\n\n for (const index of indices) {\n\n // Some class has a high enough probability\n /** @type {number[]} */\n let box = bbox[j].data;\n\n // convert to [x0, y0, x1, y1] format\n box = center_to_corners_format(box)\n if (target_size !== null) {\n box = box.map((x, i) => x * target_size[(i + 1) % 2])\n }\n\n info.boxes.push(box);\n info.classes.push(index);\n info.scores.push(probs[index]);\n }\n }\n toReturn.push(info);\n }\n return toReturn;\n}\n\n\n/**\n * Post-processes the outputs of the model (for semantic segmentation).\n * @param {*} outputs Raw outputs of the model.\n * @param {[number, number][]} [target_sizes=null] List of tuples corresponding to the requested final size\n * (height, width) of each prediction. If unset, predictions will not be resized.\n * @returns {{segmentation: Tensor; labels: number[]}[]} The semantic segmentation maps.\n */\nfunction post_process_semantic_segmentation(outputs, target_sizes = null) {\n\n const logits = outputs.logits;\n const batch_size = logits.dims[0];\n\n if (target_sizes !== null && target_sizes.length !== batch_size) {\n throw Error(\"Make sure that you pass in as many target sizes as the batch dimension of the logits\")\n }\n\n const toReturn = [];\n for (let i = 0; i < batch_size; ++i) {\n const target_size = target_sizes !== null ? target_sizes[i] : null;\n\n let data = logits[i];\n\n // 1. If target_size is not null, we need to resize the masks to the target size\n if (target_size !== null) {\n // resize the masks to the target size\n data = interpolate(data, target_size, 'bilinear', false);\n }\n const [height, width] = target_size ?? data.dims.slice(-2);\n\n const segmentation = new Tensor(\n 'int32',\n new Int32Array(height * width),\n [height, width]\n );\n\n // Buffer to store current largest value\n const buffer = data[0].data;\n const segmentation_data = segmentation.data;\n for (let j = 1; j < data.dims[0]; ++j) {\n const row = data[j].data;\n for (let k = 0; k < row.length; ++k) {\n if (row[k] > buffer[k]) {\n buffer[k] = row[k];\n segmentation_data[k] = j;\n }\n }\n }\n\n // Store which objects have labels\n // This is much more efficient that creating a set of the final values\n const hasLabel = new Array(data.dims[0]);\n for (let j = 0; j < segmentation_data.length; ++j) {\n const index = segmentation_data[j];\n hasLabel[index] = index;\n }\n /** @type {number[]} The unique list of labels that were detected */\n const labels = hasLabel.filter(x => x !== undefined);\n\n toReturn.push({ segmentation, labels });\n }\n return toReturn;\n}\n\n\n/**\n * Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and `labels`.\n * @param {Tensor} class_logits The class logits.\n * @param {Tensor} mask_logits The mask logits.\n * @param {number} object_mask_threshold A number between 0 and 1 used to binarize the masks.\n * @param {number} num_labels The number of labels.\n * @returns {[Tensor[], number[], number[]]} The binarized masks, the scores, and the labels.\n * @private\n */\nfunction remove_low_and_no_objects(class_logits, mask_logits, object_mask_threshold, num_labels) {\n\n const mask_probs_item = [];\n const pred_scores_item = [];\n const pred_labels_item = [];\n\n for (let j = 0; j < class_logits.dims[0]; ++j) {\n const cls = class_logits[j];\n const mask = mask_logits[j];\n\n const pred_label = max(cls.data)[1];\n if (pred_label === num_labels) {\n // Is the background, so we ignore it\n continue;\n }\n\n const scores = softmax(cls.data);\n const pred_score = scores[pred_label];\n if (pred_score > object_mask_threshold) {\n mask_probs_item.push(mask);\n pred_scores_item.push(pred_score);\n pred_labels_item.push(pred_label);\n }\n }\n\n return [mask_probs_item, pred_scores_item, pred_labels_item];\n}\n\n/**\n * Checks whether the segment is valid or not.\n * @param {Int32Array} mask_labels Labels for each pixel in the mask.\n * @param {Tensor[]} mask_probs Probabilities for each pixel in the masks.\n * @param {number} k The class id of the segment.\n * @param {number} mask_threshold The mask threshold.\n * @param {number} overlap_mask_area_threshold The overlap mask area threshold.\n * @returns {[boolean, number[]]} Whether the segment is valid or not, and the indices of the valid labels.\n * @private\n */\nfunction check_segment_validity(\n mask_labels,\n mask_probs,\n k,\n mask_threshold = 0.5,\n overlap_mask_area_threshold = 0.8\n) {\n // mask_k is a 1D array of indices, indicating where the mask is equal to k\n const mask_k = [];\n let mask_k_area = 0;\n let original_area = 0;\n\n const mask_probs_k_data = mask_probs[k].data;\n\n // Compute the area of all the stuff in query k\n for (let i = 0; i < mask_labels.length; ++i) {\n if (mask_labels[i] === k) {\n mask_k.push(i);\n ++mask_k_area;\n }\n\n if (mask_probs_k_data[i] >= mask_threshold) {\n ++original_area;\n }\n }\n let mask_exists = mask_k_area > 0 && original_area > 0;\n\n // Eliminate disconnected tiny segments\n if (mask_exists) {\n // Perform additional check\n let area_ratio = mask_k_area / original_area;\n mask_exists = area_ratio > overlap_mask_area_threshold;\n }\n\n return [mask_exists, mask_k]\n}\n\n/**\n * Computes the segments.\n * @param {Tensor[]} mask_probs The mask probabilities.\n * @param {number[]} pred_scores The predicted scores.\n * @param {number[]} pred_labels The predicted labels.\n * @param {number} mask_threshold The mask threshold.\n * @param {number} overlap_mask_area_threshold The overlap mask area threshold.\n * @param {Set} label_ids_to_fuse The label ids to fuse.\n * @param {number[]} target_size The target size of the image.\n * @returns {[Tensor, Array<{id: number, label_id: number, score: number}>]} The computed segments.\n * @private\n */\nfunction compute_segments(\n mask_probs,\n pred_scores,\n pred_labels,\n mask_threshold,\n overlap_mask_area_threshold,\n label_ids_to_fuse = null,\n target_size = null,\n) {\n const [height, width] = target_size ?? mask_probs[0].dims;\n\n const segmentation = new Tensor(\n 'int32',\n new Int32Array(height * width),\n [height, width]\n );\n const segments = [];\n\n // 1. If target_size is not null, we need to resize the masks to the target size\n if (target_size !== null) {\n // resize the masks to the target size\n for (let i = 0; i < mask_probs.length; ++i) {\n mask_probs[i] = interpolate(mask_probs[i], target_size, 'bilinear', false);\n }\n }\n\n // 2. Weigh each mask by its prediction score\n // NOTE: `mask_probs` is updated in-place\n // \n // Temporary storage for the best label/scores for each pixel ([height, width]):\n const mask_labels = new Int32Array(mask_probs[0].data.length);\n const bestScores = new Float32Array(mask_probs[0].data.length);\n\n for (let i = 0; i < mask_probs.length; ++i) {\n let score = pred_scores[i];\n\n const mask_probs_i_data = mask_probs[i].data;\n\n for (let j = 0; j < mask_probs_i_data.length; ++j) {\n mask_probs_i_data[j] *= score\n if (mask_probs_i_data[j] > bestScores[j]) {\n mask_labels[j] = i;\n bestScores[j] = mask_probs_i_data[j];\n }\n }\n }\n\n let current_segment_id = 0;\n\n // let stuff_memory_list = {}\n const segmentation_data = segmentation.data;\n for (let k = 0; k < pred_labels.length; ++k) {\n const pred_class = pred_labels[k];\n\n // TODO add `should_fuse`\n // let should_fuse = pred_class in label_ids_to_fuse\n\n // Check if mask exists and large enough to be a segment\n const [mask_exists, mask_k] = check_segment_validity(\n mask_labels,\n mask_probs,\n k,\n mask_threshold,\n overlap_mask_area_threshold\n )\n\n if (!mask_exists) {\n // Nothing to see here\n continue;\n }\n\n // TODO\n // if (pred_class in stuff_memory_list) {\n // current_segment_id = stuff_memory_list[pred_class]\n // } else {\n // current_segment_id += 1;\n // }\n ++current_segment_id;\n\n\n // Add current object segment to final segmentation map\n for (const index of mask_k) {\n segmentation_data[index] = current_segment_id;\n }\n\n segments.push({\n id: current_segment_id,\n label_id: pred_class,\n // was_fused: should_fuse, TODO\n score: pred_scores[k],\n })\n\n // TODO\n // if(should_fuse){\n // stuff_memory_list[pred_class] = current_segment_id\n // }\n }\n\n return [segmentation, segments];\n}\n\n\n/**\n * Post-process the model output to generate the final panoptic segmentation.\n * @param {*} outputs The model output to post process\n * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks.\n * @param {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values.\n * @param {number} [overlap_mask_area_threshold=0.8] The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask.\n * @param {Set} [label_ids_to_fuse=null] The labels in this state will have all their instances be fused together.\n * @param {[number, number][]} [target_sizes=null] The target sizes to resize the masks to.\n * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>}\n */\nfunction post_process_panoptic_segmentation(\n outputs,\n threshold = 0.5,\n mask_threshold = 0.5,\n overlap_mask_area_threshold = 0.8,\n label_ids_to_fuse = null,\n target_sizes = null,\n) {\n if (label_ids_to_fuse === null) {\n console.warn(\"`label_ids_to_fuse` unset. No instance will be fused.\")\n label_ids_to_fuse = new Set();\n }\n\n const class_queries_logits = outputs.class_queries_logits ?? outputs.logits; // [batch_size, num_queries, num_classes+1]\n const masks_queries_logits = outputs.masks_queries_logits ?? outputs.pred_masks; // [batch_size, num_queries, height, width]\n\n const mask_probs = masks_queries_logits.sigmoid() // [batch_size, num_queries, height, width]\n\n let [batch_size, num_queries, num_labels] = class_queries_logits.dims;\n num_labels -= 1; // Remove last class (background)\n\n if (target_sizes !== null && target_sizes.length !== batch_size) {\n throw Error(\"Make sure that you pass in as many target sizes as the batch dimension of the logits\")\n }\n\n let toReturn = [];\n for (let i = 0; i < batch_size; ++i) {\n let target_size = target_sizes !== null ? target_sizes[i] : null;\n\n let class_logits = class_queries_logits[i];\n let mask_logits = mask_probs[i];\n\n let [mask_probs_item, pred_scores_item, pred_labels_item] = remove_low_and_no_objects(class_logits, mask_logits, threshold, num_labels);\n\n if (pred_labels_item.length === 0) {\n // No mask found\n let [height, width] = target_size ?? mask_logits.dims.slice(-2);\n\n let segmentation = new Tensor(\n 'int32',\n new Int32Array(height * width).fill(-1),\n [height, width]\n )\n toReturn.push({\n segmentation: segmentation,\n segments_info: []\n });\n continue;\n }\n\n\n // Get segmentation map and segment information of batch item\n let [segmentation, segments] = compute_segments(\n mask_probs_item,\n pred_scores_item,\n pred_labels_item,\n mask_threshold,\n overlap_mask_area_threshold,\n label_ids_to_fuse,\n target_size,\n )\n\n toReturn.push({\n segmentation: segmentation,\n segments_info: segments\n })\n }\n\n return toReturn;\n}\n\n\n/**\n * Post-processes the outputs of the model (for instance segmentation).\n * @param {*} outputs Raw outputs of the model.\n * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks.\n * @param {[number, number][]} [target_sizes=null] List of tuples corresponding to the requested final size\n * (height, width) of each prediction. If unset, predictions will not be resized.\n * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>}\n */\nfunction post_process_instance_segmentation(outputs, threshold = 0.5, target_sizes = null) {\n throw new Error('Not implemented yet');\n return [];\n}\n\n/**\n * Named tuple to indicate the order we are using is (height x width), even though\n * the Graphics’ industry standard is (width x height).\n * @typedef {[height: number, width: number]} HeightWidth\n */\n\n/**\n * Helper function to validate audio inputs.\n * @param {any} audio The audio data.\n * @param {string} feature_extractor The name of the feature extractor.\n * @private\n */\nfunction validate_audio_inputs(audio, feature_extractor) {\n if (!(audio instanceof Float32Array || audio instanceof Float64Array)) {\n throw new Error(\n `${feature_extractor} expects input to be a Float32Array or a Float64Array, but got ${audio?.constructor?.name ?? typeof audio} instead. ` +\n `If using the feature extractor directly, remember to use \\`read_audio(url, sampling_rate)\\` to obtain the raw audio data of the file/url.`\n )\n }\n}\n\n/**\n * Helper function to constrain a value to be a multiple of a number.\n * @param {number} val The value to constrain.\n * @param {number} multiple The number to constrain to.\n * @param {number} [minVal=0] The minimum value to constrain to.\n * @param {number} [maxVal=null] The maximum value to constrain to.\n * @returns {number} The constrained value.\n * @private\n */\nfunction constraint_to_multiple_of(val, multiple, minVal = 0, maxVal = null) {\n const a = val / multiple;\n let x = bankers_round(a) * multiple;\n\n if (maxVal !== null && x > maxVal) {\n x = Math.floor(a) * multiple;\n }\n\n if (x < minVal) {\n x = Math.ceil(a) * multiple;\n }\n\n return x;\n}\n\n/**\n * Rounds the height and width down to the closest multiple of size_divisibility\n * @param {[number, number]} size The size of the image\n * @param {number} divisor The divisor to use.\n * @returns {[number, number]} The rounded size.\n */\nfunction enforce_size_divisibility([width, height], divisor) {\n return [\n Math.max(Math.floor(width / divisor), 1) * divisor,\n Math.max(Math.floor(height / divisor), 1) * divisor\n ];\n}\n\n\n/**\n * Base class for feature extractors.\n *\n * @extends Callable\n */\nexport class FeatureExtractor extends Callable {\n /**\n * Constructs a new FeatureExtractor instance.\n *\n * @param {Object} config The configuration for the feature extractor.\n */\n constructor(config) {\n super();\n this.config = config\n }\n}\n\n/**\n * @typedef {object} ImageFeatureExtractorResult\n * @property {Tensor} pixel_values The pixel values of the batched preprocessed images.\n * @property {HeightWidth[]} original_sizes Array of two-dimensional tuples like [[480, 640]].\n * @property {HeightWidth[]} reshaped_input_sizes Array of two-dimensional tuples like [[1000, 1330]].\n */\n\n/**\n * Feature extractor for image models.\n *\n * @extends FeatureExtractor\n */\nexport class ImageFeatureExtractor extends FeatureExtractor {\n\n /**\n * Constructs a new ImageFeatureExtractor instance.\n *\n * @param {Object} config The configuration for the feature extractor.\n * @param {number[]} config.image_mean The mean values for image normalization.\n * @param {number[]} config.image_std The standard deviation values for image normalization.\n * @param {boolean} config.do_rescale Whether to rescale the image pixel values to the [0,1] range.\n * @param {number} config.rescale_factor The factor to use for rescaling the image pixel values.\n * @param {boolean} config.do_normalize Whether to normalize the image pixel values.\n * @param {boolean} config.do_resize Whether to resize the image.\n * @param {number} config.resample What method to use for resampling.\n * @param {number|Object} config.size The size to resize the image to.\n * @param {boolean} [config.do_flip_channel_order=false] Whether to flip the color channels from RGB to BGR.\n * Can be overridden by the `do_flip_channel_order` parameter in the `preprocess` method.\n */\n constructor(config) {\n super(config);\n\n this.image_mean = this.config.image_mean ?? this.config.mean;\n this.image_std = this.config.image_std ?? this.config.std;\n\n this.resample = this.config.resample ?? 2; // 2 => bilinear\n this.do_rescale = this.config.do_rescale ?? true;\n this.rescale_factor = this.config.rescale_factor ?? (1 / 255);\n this.do_normalize = this.config.do_normalize;\n\n this.do_resize = this.config.do_resize;\n this.do_thumbnail = this.config.do_thumbnail;\n this.size = this.config.size;\n this.size_divisibility = this.config.size_divisibility ?? this.config.size_divisor;\n\n this.do_center_crop = this.config.do_center_crop;\n this.crop_size = this.config.crop_size;\n this.do_convert_rgb = this.config.do_convert_rgb ?? true;\n this.do_crop_margin = this.config.do_crop_margin;\n\n this.pad_size = this.config.pad_size;\n this.do_pad = this.config.do_pad;\n\n if (this.do_pad && !this.pad_size && this.size && this.size.width !== undefined && this.size.height !== undefined) {\n // Should pad, but no pad size specified\n // We infer the pad size from the resize size\n this.pad_size = this.size\n }\n\n this.do_flip_channel_order = this.config.do_flip_channel_order ?? false;\n }\n\n /**\n * Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any\n * corresponding dimension of the specified size.\n * @param {RawImage} image The image to be resized.\n * @param {{height:number, width:number}} size The size `{\"height\": h, \"width\": w}` to resize the image to.\n * @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use.\n * @returns {Promise} The resized image.\n */\n async thumbnail(image, size, resample = 2) {\n const input_height = image.height;\n const input_width = image.width;\n\n const output_height = size.height;\n const output_width = size.width;\n\n // We always resize to the smallest of either the input or output size.\n let height = Math.min(input_height, output_height)\n let width = Math.min(input_width, output_width)\n\n if (height === input_height && width === input_width) {\n return image;\n }\n if (input_height > input_width) {\n width = Math.floor(input_width * height / input_height);\n } else if (input_width > input_height) {\n height = Math.floor(input_height * width / input_width);\n }\n return await image.resize(width, height, { resample });\n }\n\n\n /**\n * Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold).\n * @param {RawImage} image The image to be cropped.\n * @param {number} gray_threshold Value below which pixels are considered to be gray.\n * @returns {Promise} The cropped image.\n */\n async crop_margin(image, gray_threshold = 200) {\n\n const gray_image = image.clone().grayscale();\n\n const minValue = min(gray_image.data)[0];\n const maxValue = max(gray_image.data)[0];\n const diff = maxValue - minValue;\n\n if (diff === 0) {\n return image;\n }\n\n const threshold = gray_threshold / 255;\n\n let x_min = gray_image.width, y_min = gray_image.height, x_max = 0, y_max = 0;\n const gray_image_data = gray_image.data;\n for (let j = 0; j < gray_image.height; ++j) {\n const row = j * gray_image.width;\n for (let i = 0; i < gray_image.width; ++i) {\n if ((gray_image_data[row + i] - minValue) / diff < threshold) {\n // We have a non-zero pixel, so we update the min/max values accordingly\n x_min = Math.min(x_min, i);\n y_min = Math.min(y_min, j);\n x_max = Math.max(x_max, i);\n y_max = Math.max(y_max, j);\n }\n }\n }\n\n image = await image.crop([x_min, y_min, x_max, y_max]);\n return image;\n }\n\n /**\n * Pad the image by a certain amount.\n * @param {Float32Array} pixelData The pixel data to pad.\n * @param {number[]} imgDims The dimensions of the image (height, width, channels).\n * @param {{width:number; height:number}|number} padSize The dimensions of the padded image.\n * @param {Object} options The options for padding.\n * @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add.\n * @param {boolean} [options.center=false] Whether to center the image.\n * @param {number} [options.constant_values=0] The constant value to use for padding.\n * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions.\n */\n pad_image(pixelData, imgDims, padSize, {\n mode = 'constant',\n center = false,\n constant_values = 0,\n } = {}) {\n const [imageHeight, imageWidth, imageChannels] = imgDims;\n\n let paddedImageWidth, paddedImageHeight;\n if (typeof padSize === 'number') {\n paddedImageWidth = padSize;\n paddedImageHeight = padSize;\n } else {\n paddedImageWidth = padSize.width;\n paddedImageHeight = padSize.height;\n }\n\n // Only add padding if there is a difference in size\n if (paddedImageWidth !== imageWidth || paddedImageHeight !== imageHeight) {\n const paddedPixelData = new Float32Array(paddedImageWidth * paddedImageHeight * imageChannels);\n if (Array.isArray(constant_values)) {\n // Fill with constant values, cycling through the array\n for (let i = 0; i < paddedPixelData.length; ++i) {\n paddedPixelData[i] = constant_values[i % imageChannels];\n }\n } else if (constant_values !== 0) {\n paddedPixelData.fill(constant_values);\n }\n\n const [left, top] = center\n ? [Math.floor((paddedImageWidth - imageWidth) / 2), Math.floor((paddedImageHeight - imageHeight) / 2)]\n : [0, 0];\n\n // Copy the original image into the padded image\n for (let i = 0; i < imageHeight; ++i) {\n const a = (i + top) * paddedImageWidth;\n const b = i * imageWidth;\n for (let j = 0; j < imageWidth; ++j) {\n const c = (a + j + left) * imageChannels;\n const d = (b + j) * imageChannels;\n for (let k = 0; k < imageChannels; ++k) {\n paddedPixelData[c + k] = pixelData[d + k];\n }\n }\n }\n\n if (mode === 'symmetric') {\n if (center) {\n throw new Error('`center` padding is not supported when `mode` is set to `symmetric`.');\n // TODO: Implement this\n }\n const h1 = imageHeight - 1;\n const w1 = imageWidth - 1;\n for (let i = 0; i < paddedImageHeight; ++i) {\n const a = i * paddedImageWidth;\n const b = calculateReflectOffset(i, h1) * imageWidth;\n\n for (let j = 0; j < paddedImageWidth; ++j) {\n if (i < imageHeight && j < imageWidth) continue; // Do not overwrite original image\n const c = (a + j) * imageChannels;\n const d = (b + calculateReflectOffset(j, w1)) * imageChannels;\n\n // Copy channel-wise\n for (let k = 0; k < imageChannels; ++k) {\n paddedPixelData[c + k] = pixelData[d + k];\n }\n }\n }\n }\n\n\n // Update pixel data and image dimensions\n pixelData = paddedPixelData;\n imgDims = [paddedImageHeight, paddedImageWidth, imageChannels]\n }\n return [pixelData, imgDims];\n }\n\n /**\n * Rescale the image' pixel values by `this.rescale_factor`.\n * @param {Float32Array} pixelData The pixel data to rescale.\n * @returns {void}\n */\n rescale(pixelData) {\n for (let i = 0; i < pixelData.length; ++i) {\n pixelData[i] = this.rescale_factor * pixelData[i];\n }\n }\n\n /**\n * Find the target (width, height) dimension of the output image after\n * resizing given the input image and the desired size.\n * @param {RawImage} image The image to resize.\n * @param {any} size The size to use for resizing the image. \n * @returns {[number, number]} The target (width, height) dimension of the output image after resizing.\n */\n get_resize_output_image_size(image, size) {\n // `size` comes in many forms, so we need to handle them all here:\n // 1. `size` is an integer, in which case we resize the image to be a square \n\n const [srcWidth, srcHeight] = image.size;\n\n let shortest_edge;\n let longest_edge;\n\n if (this.do_thumbnail) {\n // NOTE: custom logic for `Donut` models\n const { height, width } = size;\n shortest_edge = Math.min(height, width)\n }\n // Support both formats for backwards compatibility\n else if (Number.isInteger(size)) {\n shortest_edge = size;\n longest_edge = this.config.max_size ?? shortest_edge;\n\n } else if (size !== undefined) {\n // Extract known properties from `size`\n shortest_edge = size.shortest_edge;\n longest_edge = size.longest_edge;\n }\n\n // If `longest_edge` and `shortest_edge` are set, maintain aspect ratio and resize to `shortest_edge`\n // while keeping the largest dimension <= `longest_edge`\n if (shortest_edge !== undefined || longest_edge !== undefined) {\n // http://opensourcehacker.com/2011/12/01/calculate-aspect-ratio-conserving-resize-for-images-in-javascript/\n // Try resize so that shortest edge is `shortest_edge` (target)\n const shortResizeFactor = shortest_edge === undefined\n ? 1 // If `shortest_edge` is not set, don't upscale\n : Math.max(shortest_edge / srcWidth, shortest_edge / srcHeight);\n\n const newWidth = srcWidth * shortResizeFactor;\n const newHeight = srcHeight * shortResizeFactor;\n\n // The new width and height might be greater than `longest_edge`, so\n // we downscale again to ensure the largest dimension is `longest_edge` \n const longResizeFactor = longest_edge === undefined\n ? 1 // If `longest_edge` is not set, don't downscale\n : Math.min(longest_edge / newWidth, longest_edge / newHeight);\n\n // To avoid certain floating point precision issues, we round to 2 decimal places\n let finalWidth = Math.floor(Number((newWidth * longResizeFactor).toFixed(2)));\n let finalHeight = Math.floor(Number((newHeight * longResizeFactor).toFixed(2)));\n\n if (this.size_divisibility !== undefined) {\n [finalWidth, finalHeight] = enforce_size_divisibility([finalWidth, finalHeight], this.size_divisibility)\n }\n return [finalWidth, finalHeight];\n\n } else if (size !== undefined && size.width !== undefined && size.height !== undefined) {\n // If `width` and `height` are set, resize to those dimensions\n\n let newWidth = size.width;\n let newHeight = size.height;\n\n // Custom for DPT models\n if (this.config.keep_aspect_ratio && this.config.ensure_multiple_of) {\n\n // determine new height and width\n let scale_height = newHeight / srcHeight;\n let scale_width = newWidth / srcWidth;\n\n // scale as little as possible\n if (Math.abs(1 - scale_width) < Math.abs(1 - scale_height)) {\n // fit width\n scale_height = scale_width;\n } else {\n // fit height\n scale_width = scale_height;\n }\n\n newHeight = constraint_to_multiple_of(scale_height * srcHeight, this.config.ensure_multiple_of);\n newWidth = constraint_to_multiple_of(scale_width * srcWidth, this.config.ensure_multiple_of);\n }\n\n return [newWidth, newHeight];\n\n } else if (this.size_divisibility !== undefined) {\n return enforce_size_divisibility([srcWidth, srcHeight], this.size_divisibility);\n } else {\n throw new Error(`Could not resize image due to unsupported \\`this.size\\` option in config: ${JSON.stringify(size)}`);\n }\n }\n\n /**\n * Resizes the image.\n * @param {RawImage} image The image to resize.\n * @returns {Promise} The resized image.\n */\n async resize(image) {\n const [newWidth, newHeight] = this.get_resize_output_image_size(image, this.size);\n return await image.resize(newWidth, newHeight, {\n resample: this.resample,\n });\n }\n\n /**\n * @typedef {object} PreprocessedImage\n * @property {HeightWidth} original_size The original size of the image.\n * @property {HeightWidth} reshaped_input_size The reshaped input size of the image.\n * @property {Tensor} pixel_values The pixel values of the preprocessed image.\n */\n\n /**\n * Preprocesses the given image.\n *\n * @param {RawImage} image The image to preprocess.\n * @param {Object} overrides The overrides for the preprocessing options.\n * @returns {Promise} The preprocessed image.\n */\n async preprocess(image, {\n do_normalize = null,\n do_pad = null,\n do_convert_rgb = null,\n do_convert_grayscale = null,\n do_flip_channel_order = null,\n } = {}) {\n if (this.do_crop_margin) {\n // NOTE: Specific to nougat processors. This is done before resizing,\n // and can be interpreted as a pre-preprocessing step.\n image = await this.crop_margin(image);\n }\n\n const [srcWidth, srcHeight] = image.size; // original image size\n\n // Convert image to RGB if specified in config.\n if (do_convert_rgb ?? this.do_convert_rgb) {\n image = image.rgb();\n } else if (do_convert_grayscale) {\n image = image.grayscale();\n }\n\n // TODO:\n // For efficiency reasons, it might be best to merge the resize and center crop operations into one.\n\n // Resize all images\n if (this.do_resize) {\n image = await this.resize(image);\n }\n\n // Resize the image using thumbnail method.\n if (this.do_thumbnail) {\n image = await this.thumbnail(image, this.size, this.resample);\n }\n\n if (this.do_center_crop) {\n\n let crop_width;\n let crop_height;\n if (Number.isInteger(this.crop_size)) {\n crop_width = this.crop_size;\n crop_height = this.crop_size;\n } else {\n crop_width = this.crop_size.width;\n crop_height = this.crop_size.height;\n }\n\n image = await image.center_crop(crop_width, crop_height);\n }\n\n /** @type {HeightWidth} */\n const reshaped_input_size = [image.height, image.width];\n\n // NOTE: All pixel-level manipulation (i.e., modifying `pixelData`)\n // occurs with data in the hwc format (height, width, channels), \n // to emulate the behavior of the original Python code (w/ numpy).\n let pixelData = Float32Array.from(image.data);\n let imgDims = [image.height, image.width, image.channels];\n\n if (this.do_rescale) {\n this.rescale(pixelData);\n }\n\n if (do_normalize ?? this.do_normalize) {\n let image_mean = this.image_mean;\n if (!Array.isArray(this.image_mean)) {\n image_mean = new Array(image.channels).fill(image_mean);\n }\n\n let image_std = this.image_std;\n if (!Array.isArray(this.image_std)) {\n image_std = new Array(image.channels).fill(image_mean);\n }\n\n if (image_mean.length !== image.channels || image_std.length !== image.channels) {\n throw new Error(`When set to arrays, the length of \\`image_mean\\` (${image_mean.length}) and \\`image_std\\` (${image_std.length}) must match the number of channels in the image (${image.channels}).`);\n }\n\n for (let i = 0; i < pixelData.length; i += image.channels) {\n for (let j = 0; j < image.channels; ++j) {\n pixelData[i + j] = (pixelData[i + j] - image_mean[j]) / image_std[j];\n }\n }\n }\n\n // do padding after rescaling/normalizing\n if (do_pad ?? this.do_pad) {\n if (this.pad_size) {\n const padded = this.pad_image(pixelData, [image.height, image.width, image.channels], this.pad_size);\n [pixelData, imgDims] = padded; // Update pixel data and image dimensions\n } else if (this.size_divisibility) {\n const [paddedWidth, paddedHeight] = enforce_size_divisibility([imgDims[1], imgDims[0]], this.size_divisibility);\n [pixelData, imgDims] = this.pad_image(pixelData, imgDims, { width: paddedWidth, height: paddedHeight });\n }\n }\n\n if (do_flip_channel_order ?? this.do_flip_channel_order) {\n if (imgDims[2] !== 3) {\n throw new Error('Flipping channel order is only supported for RGB images.');\n }\n // Convert RGB to BGR\n for (let i = 0; i < pixelData.length; i += 3) {\n const temp = pixelData[i];\n pixelData[i] = pixelData[i + 2];\n pixelData[i + 2] = temp;\n }\n }\n\n const pixel_values = new Tensor('float32', pixelData, imgDims)\n .permute(2, 0, 1); // convert to channel dimension format (hwc -> chw)\n\n return {\n original_size: [srcHeight, srcWidth],\n reshaped_input_size: reshaped_input_size,\n pixel_values,\n }\n }\n\n /**\n * Calls the feature extraction process on an array of images,\n * preprocesses each image, and concatenates the resulting\n * features into a single Tensor.\n * @param {RawImage[]} images The image(s) to extract features from.\n * @param {...any} args Additional arguments.\n * @returns {Promise} An object containing the concatenated pixel values (and other metadata) of the preprocessed images.\n */\n async _call(images, ...args) {\n if (!Array.isArray(images)) {\n images = [images];\n }\n /** @type {PreprocessedImage[]} */\n const imageData = await Promise.all(images.map(x => this.preprocess(x)));\n\n // Stack pixel values\n const pixel_values = stack(imageData.map(x => x.pixel_values), 0);\n\n return {\n pixel_values,\n\n // Original sizes of images\n original_sizes: imageData.map(x => x.original_size),\n\n // Reshaped sizes of images, before padding or cropping\n reshaped_input_sizes: imageData.map(x => x.reshaped_input_size),\n }\n }\n\n}\n\nexport class SapiensFeatureExtractor extends ImageFeatureExtractor {\n /** @type {typeof post_process_semantic_segmentation} */\n post_process_semantic_segmentation(...args) {\n return post_process_semantic_segmentation(...args);\n }\n}\nexport class SegformerFeatureExtractor extends ImageFeatureExtractor {\n /** @type {typeof post_process_semantic_segmentation} */\n post_process_semantic_segmentation(...args) {\n return post_process_semantic_segmentation(...args);\n }\n}\nexport class PvtImageProcessor extends ImageFeatureExtractor { }\nexport class DPTFeatureExtractor extends ImageFeatureExtractor { }\nexport class DPTImageProcessor extends DPTFeatureExtractor { } // NOTE: extends DPTFeatureExtractor\nexport class BitImageProcessor extends ImageFeatureExtractor { }\nexport class GLPNFeatureExtractor extends ImageFeatureExtractor { }\nexport class CLIPFeatureExtractor extends ImageFeatureExtractor { }\nexport class CLIPImageProcessor extends CLIPFeatureExtractor { } // NOTE: extends CLIPFeatureExtractor\nexport class ChineseCLIPFeatureExtractor extends ImageFeatureExtractor { }\nexport class SiglipImageProcessor extends ImageFeatureExtractor { }\nexport class ConvNextFeatureExtractor extends ImageFeatureExtractor {\n constructor(config) {\n super(config);\n\n /**\n * Percentage of the image to crop. Only has an effect if this.size < 384.\n */\n this.crop_pct = this.config.crop_pct ?? (224 / 256);\n }\n\n async resize(image) {\n const shortest_edge = this.size?.shortest_edge;\n if (shortest_edge === undefined) {\n throw new Error(`Size dictionary must contain 'shortest_edge' key.`);\n }\n\n if (shortest_edge < 384) {\n // maintain same ratio, resizing shortest edge to shortest_edge/crop_pct\n const resize_shortest_edge = Math.floor(shortest_edge / this.crop_pct);\n\n const [newWidth, newHeight] = this.get_resize_output_image_size(image, {\n shortest_edge: resize_shortest_edge,\n });\n\n image = await image.resize(newWidth, newHeight, {\n resample: this.resample,\n });\n\n // then crop to (shortest_edge, shortest_edge)\n image = await image.center_crop(shortest_edge, shortest_edge);\n } else {\n // warping (no cropping) when evaluated at 384 or larger\n image = await image.resize(shortest_edge, shortest_edge, {\n resample: this.resample,\n });\n }\n\n return image;\n }\n}\nexport class ConvNextImageProcessor extends ConvNextFeatureExtractor { } // NOTE extends ConvNextFeatureExtractor\nexport class ViTFeatureExtractor extends ImageFeatureExtractor { }\nexport class ViTImageProcessor extends ImageFeatureExtractor { }\n\nexport class EfficientNetImageProcessor extends ImageFeatureExtractor {\n constructor(config) {\n super(config);\n this.include_top = this.config.include_top ?? true;\n if (this.include_top) {\n this.image_std = this.image_std.map(x => x * x);\n }\n }\n}\n\nexport class MobileNetV1FeatureExtractor extends ImageFeatureExtractor { }\nexport class MobileNetV2FeatureExtractor extends ImageFeatureExtractor { }\nexport class MobileNetV3FeatureExtractor extends ImageFeatureExtractor { }\nexport class MobileNetV4FeatureExtractor extends ImageFeatureExtractor { }\n\nexport class MobileViTFeatureExtractor extends ImageFeatureExtractor { }\nexport class MobileViTImageProcessor extends MobileViTFeatureExtractor { } // NOTE extends MobileViTFeatureExtractor\nexport class OwlViTFeatureExtractor extends ImageFeatureExtractor {\n /** @type {typeof post_process_object_detection} */\n post_process_object_detection(...args) {\n return post_process_object_detection(...args);\n }\n}\nexport class Owlv2ImageProcessor extends OwlViTFeatureExtractor { } // NOTE extends OwlViTFeatureExtractor\n\nexport class RTDetrImageProcessor extends ImageFeatureExtractor {\n /** @type {typeof post_process_object_detection} */\n post_process_object_detection(...args) {\n return post_process_object_detection(...args);\n }\n}\n\nexport class DeiTFeatureExtractor extends ImageFeatureExtractor { }\nexport class BeitFeatureExtractor extends ImageFeatureExtractor { }\nexport class DonutFeatureExtractor extends ImageFeatureExtractor {\n pad_image(pixelData, imgDims, padSize, options = {}) {\n const [imageHeight, imageWidth, imageChannels] = imgDims;\n\n let image_mean = this.image_mean;\n if (!Array.isArray(this.image_mean)) {\n image_mean = new Array(imageChannels).fill(image_mean);\n }\n\n let image_std = this.image_std;\n if (!Array.isArray(image_std)) {\n image_std = new Array(imageChannels).fill(image_mean);\n }\n\n const constant_values = image_mean.map((x, i) => - x / image_std[i]);\n\n return super.pad_image(pixelData, imgDims, padSize, {\n center: true,\n\n // Since normalization is done after padding, we need to use certain constant values to ensure the same behaviour is observed.\n // For more information, see https://github.com/huggingface/transformers/blob/main/src/transformers/models/donut/image_processing_donut.py#L433-L451\n constant_values: constant_values,\n ...options,\n });\n }\n}\nexport class NougatImageProcessor extends DonutFeatureExtractor { } // NOTE extends DonutFeatureExtractor\n\n/**\n * @typedef {object} DetrFeatureExtractorResultProps\n * @property {Tensor} pixel_mask\n * @typedef {ImageFeatureExtractorResult & DetrFeatureExtractorResultProps} DetrFeatureExtractorResult\n */\n\n/**\n * Detr Feature Extractor.\n *\n * @extends ImageFeatureExtractor\n */\nexport class DetrFeatureExtractor extends ImageFeatureExtractor {\n /**\n * Calls the feature extraction process on an array of images, preprocesses\n * each image, and concatenates the resulting features into a single Tensor.\n * @param {RawImage[]} images The image(s) to extract features from.\n * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images.\n */\n async _call(images) {\n const result = await super._call(images);\n\n // TODO support differently-sized images, for now assume all images are the same size.\n // TODO support different mask sizes (not just 64x64)\n // Currently, just fill pixel mask with 1s\n const maskSize = [result.pixel_values.dims[0], 64, 64];\n const pixel_mask = full(maskSize, 1n);\n\n return { ...result, pixel_mask };\n }\n\n /** @type {typeof post_process_object_detection} */\n post_process_object_detection(...args) {\n return post_process_object_detection(...args);\n }\n\n /** @type {typeof post_process_panoptic_segmentation} */\n post_process_panoptic_segmentation(...args) {\n return post_process_panoptic_segmentation(...args);\n }\n\n post_process_instance_segmentation() {\n // TODO\n throw Error(\"Not implemented yet\");\n }\n}\n\nexport class MaskFormerFeatureExtractor extends ImageFeatureExtractor {\n\n /** @type {typeof post_process_panoptic_segmentation} */\n post_process_panoptic_segmentation(...args) {\n return post_process_panoptic_segmentation(...args);\n }\n\n post_process_instance_segmentation() {\n // TODO\n throw Error(\"Not implemented yet\");\n }\n}\n\n\nexport class YolosFeatureExtractor extends ImageFeatureExtractor {\n /** @type {typeof post_process_object_detection} */\n post_process_object_detection(...args) {\n return post_process_object_detection(...args);\n }\n}\n\n/**\n * @typedef {object} SamImageProcessorResult\n * @property {Tensor} pixel_values\n * @property {HeightWidth[]} original_sizes\n * @property {HeightWidth[]} reshaped_input_sizes\n * @property {Tensor} [input_points]\n * @property {Tensor} [input_labels]\n * @property {Tensor} [input_boxes]\n */\n\nexport class SamImageProcessor extends ImageFeatureExtractor {\n\n /**\n * \n * @param {any} input_points \n * @param {HeightWidth[]} original_sizes \n * @param {HeightWidth[]} reshaped_input_sizes \n * @returns {Tensor}\n */\n reshape_input_points(input_points, original_sizes, reshaped_input_sizes, is_bounding_box = false) {\n\n // Make deep copy to avoid altering user's input\n input_points = structuredClone(input_points);\n let shape = calculateDimensions(input_points);\n\n // TODO: add support for 2D input_points\n if (shape.length === 3) {\n // Correct user's input\n if (!is_bounding_box) {\n shape = [1, ...shape];\n }\n input_points = [input_points];\n } else if (shape.length !== 4) {\n throw Error(\"The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.\")\n }\n\n // Reshape input points\n for (let i = 0; i < input_points.length; ++i) { // batch_size\n let originalImageSize = original_sizes[i];\n let reshapedImageSize = reshaped_input_sizes[i];\n\n let resizeFactors = [\n reshapedImageSize[0] / originalImageSize[0],\n reshapedImageSize[1] / originalImageSize[1]\n ]\n\n for (let j = 0; j < input_points[i].length; ++j) { // point_batch_size\n for (let k = 0; k < input_points[i][j].length; ++k) { // nb_points_per_image\n for (let w = 0; w < input_points[i][j][k].length; ++w) { // 2 or 4\n input_points[i][j][k][w] *= resizeFactors[w % 2];\n }\n }\n }\n }\n\n return new Tensor(\n 'float32',\n Float32Array.from(input_points.flat(Infinity)),\n shape\n )\n\n }\n\n /**\n * \n * @param {any} input_labels \n * @param {Tensor} input_points \n * @returns {Tensor}\n */\n add_input_labels(input_labels, input_points) {\n let shape = calculateDimensions(input_labels);\n if (shape.length === 2) {\n // Correct user's input\n shape = [1, ...shape];\n input_labels = [input_labels];\n } else if (shape.length !== 3) {\n throw Error(\"The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.\")\n }\n\n if (shape.some((x, i) => x !== input_points.dims[i])) {\n throw Error(`The first ${shape.length} dimensions of 'input_points' and 'input_labels' must be the same.`)\n }\n return new Tensor(\n 'int64',\n input_labels.flat(Infinity).map(BigInt),\n shape,\n )\n }\n /**\n * @param {any[]} images The URL(s) of the image(s) to extract features from.\n * @param {Object} [options] Additional options for the processor.\n * @param {any} [options.input_points=null] A 3D or 4D array, representing the input points provided by the user.\n * - 3D: `[point_batch_size, nb_points_per_image, 2]`. In this case, `batch_size` is assumed to be 1.\n * - 4D: `[batch_size, point_batch_size, nb_points_per_image, 2]`.\n * @param {any} [options.input_labels=null] A 2D or 3D array, representing the input labels for the points, used by the prompt encoder to encode the prompt.\n * - 2D: `[point_batch_size, nb_points_per_image]`. In this case, `batch_size` is assumed to be 1.\n * - 3D: `[batch_size, point_batch_size, nb_points_per_image]`.\n * @param {number[][][]} [options.input_boxes=null] A 3D array of shape `(batch_size, num_boxes, 4)`, representing the input boxes provided by the user.\n * This is used by the prompt encoder to encode the prompt. Generally yields to much better generated masks.\n * The processor will generate a tensor, with each dimension corresponding respectively to the image batch size,\n * the number of boxes per image and the coordinates of the top left and botton right point of the box.\n * In the order (`x1`, `y1`, `x2`, `y2`):\n * - `x1`: the x coordinate of the top left point of the input box\n * - `y1`: the y coordinate of the top left point of the input box\n * - `x2`: the x coordinate of the bottom right point of the input box\n * - `y2`: the y coordinate of the bottom right point of the input box\n * @returns {Promise}\n */\n async _call(images, {\n input_points = null,\n input_labels = null,\n input_boxes = null\n } = {}) {\n // TODO allow user to use preprocessed images\n /** @type {SamImageProcessorResult} */\n const processed = await super._call(images);\n\n if (input_points) {\n processed.input_points = this.reshape_input_points(\n input_points, processed.original_sizes, processed.reshaped_input_sizes\n );\n }\n\n if (input_labels) {\n if (!processed.input_points) {\n throw Error(\"`input_points` must be provided if `input_labels` are provided.\")\n }\n processed.input_labels = this.add_input_labels(input_labels, processed.input_points);\n }\n\n if (input_boxes) {\n processed.input_boxes = this.reshape_input_points(\n input_boxes, processed.original_sizes, processed.reshaped_input_sizes, true,\n );\n }\n\n return processed;\n }\n\n /**\n * Remove padding and upscale masks to the original image size.\n * @param {Tensor} masks Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.\n * @param {[number, number][]} original_sizes The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format.\n * @param {[number, number][]} reshaped_input_sizes The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.\n * @param {Object} options Optional parameters for post-processing.\n * @param {number} [options.mask_threshold] The threshold to use for binarizing the masks.\n * @param {boolean} [options.binarize] Whether to binarize the masks.\n * @param {Object} [options.pad_size] The target size the images were padded to before being passed to the model. If `null`, the target size is assumed to be the processor's `pad_size`.\n * @param {number} [options.pad_size.height] The height the images were padded to.\n * @param {number} [options.pad_size.width] The width the images were padded to.\n * @returns {Promise} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size.\n */\n async post_process_masks(masks, original_sizes, reshaped_input_sizes, {\n mask_threshold = 0.0,\n binarize = true,\n pad_size = null,\n } = {}) {\n // masks: [1, 1, 3, 256, 256]\n\n const output_masks = [];\n\n pad_size = pad_size ?? this.pad_size;\n\n /** @type {[number, number]} */\n const target_image_size = [pad_size.height, pad_size.width];\n\n for (let i = 0; i < original_sizes.length; ++i) {\n const original_size = original_sizes[i];\n const reshaped_input_size = reshaped_input_sizes[i];\n\n // Upscale mask to padded size\n let interpolated_mask = (await interpolate_4d(\n masks[i],\n { mode: 'bilinear', size: target_image_size }\n ));\n\n // Crop mask\n interpolated_mask = interpolated_mask.slice(null, null, [0, reshaped_input_size[0]], [0, reshaped_input_size[1]]);\n\n // Downscale mask\n interpolated_mask = (await interpolate_4d(\n interpolated_mask,\n { mode: 'bilinear', size: original_size }\n ));\n\n if (binarize) {\n const data = interpolated_mask.data;\n const binarizedMaskData = new Uint8Array(data.length);\n for (let i = 0; i < data.length; ++i) {\n if (data[i] > mask_threshold) {\n binarizedMaskData[i] = 1;\n }\n }\n interpolated_mask = new Tensor(\n 'bool',\n binarizedMaskData,\n interpolated_mask.dims\n )\n }\n\n output_masks.push(interpolated_mask);\n }\n\n return output_masks;\n }\n\n /**\n * Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.\n * @param {RawImage} image Input original image\n * @param {number} target_size Target size of the resized image\n * @param {Object} options Options for generating crop boxes \n * @param {number} [options.crop_n_layers] If >0, mask prediction will be run again on crops of the image.\n * Sets the number of layers to run, where each layer has 2**i_layer number of image crops.\n * @param {number} [options.overlap_ratio] Sets the degree to which crops overlap. In the first crop layer,\n * crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap.\n * @param {number} [options.points_per_crop] Number of points to sample from each crop.\n * @param {number} [options.crop_n_points_downscale_factor] The number of points-per-side sampled in layer n is\n * scaled down by crop_n_points_downscale_factor**n.\n * @returns {Object} An object containing the crop boxes, number of points per crop, cropped images, and input labels.\n */\n generate_crop_boxes(image, target_size, {\n crop_n_layers = 0,\n overlap_ratio = 512 / 1500,\n points_per_crop = 32,\n crop_n_points_downscale_factor = 1,\n } = {}) {\n // TODO: Implement\n // return { crop_boxes, points_per_crop, cropped_images, input_labels }\n }\n}\n\nexport class Swin2SRImageProcessor extends ImageFeatureExtractor {\n pad_image(pixelData, imgDims, padSize, options = {}) {\n // NOTE: In this case, `padSize` represents the size of the sliding window for the local attention.\n // In other words, the image is padded so that its width and height are multiples of `padSize`.\n const [imageHeight, imageWidth, imageChannels] = imgDims;\n\n return super.pad_image(pixelData, imgDims, {\n // NOTE: For Swin2SR models, the original python implementation adds padding even when the image's width/height is already\n // a multiple of `pad_size`. However, this is most likely a bug (PR: https://github.com/mv-lab/swin2sr/pull/19).\n // For this reason, we only add padding when the image's width/height is not a multiple of `pad_size`.\n width: imageWidth + (padSize - imageWidth % padSize) % padSize,\n height: imageHeight + (padSize - imageHeight % padSize) % padSize,\n }, {\n mode: 'symmetric',\n center: false,\n constant_values: -1,\n ...options,\n })\n }\n}\n\nexport class VitMatteImageProcessor extends ImageFeatureExtractor {\n /**\n * Calls the feature extraction process on an array of images, preprocesses\n * each image, and concatenates the resulting features into a single Tensor.\n * @param {RawImage[]} images The image(s) to extract features from.\n * @param {RawImage[]} trimaps The trimaps(s) to extract features from.\n * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images.\n */\n async _call(images, trimaps) {\n if (!Array.isArray(images)) {\n images = [images];\n }\n if (!Array.isArray(trimaps)) {\n trimaps = [trimaps];\n }\n\n const imageData = await Promise.all(images.map(x => this.preprocess(x)));\n const trimapData = await Promise.all(trimaps.map(x => this.preprocess(x, {\n do_normalize: false,\n do_convert_rgb: false,\n do_convert_grayscale: true,\n })));\n\n\n // Stack pixel values\n const pixel_values = stack(imageData.map(\n // Concatenate images and trimaps\n (x, i) => cat([x.pixel_values, trimapData[i].pixel_values], 0)\n ), 0);\n\n return {\n pixel_values,\n\n // Original sizes of images\n original_sizes: imageData.map(x => x.original_size),\n\n // Reshaped sizes of images, before padding or cropping\n reshaped_input_sizes: imageData.map(x => x.reshaped_input_size),\n }\n }\n}\n\nexport class WhisperFeatureExtractor extends FeatureExtractor {\n\n constructor(config) {\n super(config);\n\n // Prefer given `mel_filters` from preprocessor_config.json, or calculate them if they don't exist.\n this.config.mel_filters ??= mel_filter_bank(\n Math.floor(1 + this.config.n_fft / 2), // num_frequency_bins\n this.config.feature_size, // num_mel_filters\n 0.0, // min_frequency\n 8000.0, // max_frequency\n this.config.sampling_rate, // sampling_rate\n \"slaney\", // norm\n \"slaney\", // mel_scale\n );\n\n this.window = window_function(this.config.n_fft, 'hann');\n }\n\n /**\n * Computes the log-Mel spectrogram of the provided audio waveform.\n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform) {\n const features = await spectrogram(\n waveform,\n this.window, // window\n this.config.n_fft, // frame_length\n this.config.hop_length, // hop_length\n {\n power: 2.0,\n mel_filters: this.config.mel_filters,\n log_mel: 'log10',\n\n // Custom\n max_num_frames: this.config.nb_max_frames, // 3000\n }\n )\n\n const data = features.data;\n const maxValue = max(data)[0];\n\n for (let i = 0; i < data.length; ++i) {\n data[i] = (Math.max(data[i], maxValue - 8.0) + 4.0) / 4.0;\n }\n\n return features;\n }\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'WhisperFeatureExtractor');\n\n let waveform;\n if (audio.length > this.config.n_samples) {\n console.warn(\n \"Attempting to extract features for audio longer than 30 seconds. \" +\n \"If using a pipeline to extract transcript from a long audio clip, \" +\n \"remember to specify `chunk_length_s` and/or `stride_length_s`.\"\n );\n waveform = audio.slice(0, this.config.n_samples);\n } else {\n // pad with zeros\n waveform = new Float32Array(this.config.n_samples);\n waveform.set(audio);\n }\n\n const features = await this._extract_fbank_features(waveform);\n\n return {\n input_features: features.unsqueeze_(0)\n };\n }\n}\n\nexport class Wav2Vec2FeatureExtractor extends FeatureExtractor {\n\n /**\n * @param {Float32Array} input_values \n * @returns {Float32Array} \n */\n _zero_mean_unit_var_norm(input_values) {\n // TODO support batch?\n const sum = input_values.reduce((a, b) => a + b, 0);\n const mean = sum / input_values.length;\n const variance = input_values.reduce((a, b) => a + (b - mean) ** 2, 0) / input_values.length;\n return input_values.map(x => (x - mean) / Math.sqrt(variance + 1e-7));\n }\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_values: Tensor; attention_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention mask as Tensors.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'Wav2Vec2FeatureExtractor');\n\n if (audio instanceof Float64Array) {\n audio = new Float32Array(audio);\n }\n\n let input_values = audio;\n\n // zero-mean and unit-variance normalization\n if (this.config.do_normalize) {\n input_values = this._zero_mean_unit_var_norm(input_values);\n }\n\n // TODO: allow user to pass in attention mask\n const shape = [1, input_values.length];\n return {\n input_values: new Tensor('float32', input_values, shape),\n attention_mask: new Tensor('int64', new BigInt64Array(input_values.length).fill(1n), shape)\n };\n }\n}\n\nexport class SeamlessM4TFeatureExtractor extends FeatureExtractor {\n\n constructor(config) {\n super(config);\n\n const sampling_rate = this.config.sampling_rate;\n const mel_filters = mel_filter_bank(\n 256, // num_frequency_bins\n this.config.num_mel_bins, // num_mel_filters\n 20, // min_frequency\n Math.floor(sampling_rate / 2), // max_frequency\n sampling_rate, // sampling_rate\n null, // norm\n \"kaldi\", // mel_scale\n true, // triangularize_in_mel_space\n );\n\n // Do padding:\n for (let i = 0; i < mel_filters.length; ++i) {\n mel_filters[i].push(0);\n }\n this.mel_filters = mel_filters;\n\n this.window = window_function(400, 'povey', {\n periodic: false,\n })\n }\n\n /**\n * Computes the log-Mel spectrogram of the provided audio waveform.\n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @param {number} max_length The maximum number of frames to return.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform, max_length) {\n // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`\n\n // Kaldi compliance: 16-bit signed integers\n // 32768 == 2 ** 15\n waveform = waveform.map((/** @type {number} */ x) => x * 32768)\n\n return spectrogram(\n waveform,\n this.window, // window\n 400, // frame_length\n 160, // hop_length\n {\n fft_length: 512,\n power: 2.0,\n center: false,\n preemphasis: 0.97,\n mel_filters: this.mel_filters,\n log_mel: 'log',\n mel_floor: 1.192092955078125e-07,\n remove_dc_offset: true,\n\n // Custom\n max_num_frames: max_length,\n transpose: true,\n }\n )\n }\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @param {Object} options Optional parameters for feature extraction.\n * @param {boolean} [options.padding=true] Whether to pad the sequence to a multiple of `pad_to_multiple_of`.\n * @param {number} [options.pad_to_multiple_of=2] The number to pad the sequence to a multiple of.\n * @param {boolean} [options.do_normalize_per_mel_bins=true] Whether or not to zero-mean unit-variance normalize the input per mel-channel.\n * @param {boolean} [options.return_attention_mask=true] Whether to return the attention mask.\n * @returns {Promise<{ input_features: Tensor, attention_mask?: Tensor }>} A Promise resolving to an object containing the extracted input features and attention masks as Tensors.\n */\n async _call(audio, {\n padding = true,\n pad_to_multiple_of = 2,\n do_normalize_per_mel_bins = true,\n return_attention_mask = true,\n } = {}) {\n validate_audio_inputs(audio, 'SeamlessM4TFeatureExtractor');\n\n let features = await this._extract_fbank_features(audio, this.config.max_length);\n\n if (do_normalize_per_mel_bins) {\n const [num_features, feature_size] = features.dims;\n const data = features.data;\n for (let i = 0; i < feature_size; ++i) {\n let sum = 0;\n for (let j = 0; j < num_features; ++j) {\n sum += data[j * feature_size + i];\n }\n\n const mean = sum / num_features;\n\n let variance = 0;\n for (let j = 0; j < num_features; ++j) {\n variance += (data[j * feature_size + i] - mean) ** 2;\n }\n variance /= num_features - 1; // NOTE: We use ddof=1\n\n const std = Math.sqrt(variance + 1e-7);\n for (let j = 0; j < num_features; ++j) {\n const index = j * feature_size + i;\n data[index] = (data[index] - mean) / std;\n }\n }\n }\n\n let padded_attention_mask;\n if (padding) {\n const [num_frames, num_channels] = features.dims;\n const data = /** @type {Float32Array} */(features.data);\n\n const pad_size = num_frames % pad_to_multiple_of;\n if (pad_size > 0) {\n const padded_data = new Float32Array(num_channels * (num_frames + pad_size));\n padded_data.set(data)\n padded_data.fill(this.config.padding_value, data.length)\n\n const numPaddedFrames = num_frames + pad_size;\n features = new Tensor(\n features.type,\n padded_data,\n [numPaddedFrames, num_channels],\n )\n\n if (return_attention_mask) {\n padded_attention_mask = new Tensor(\n 'int64',\n new BigInt64Array(numPaddedFrames),\n [1, numPaddedFrames],\n )\n padded_attention_mask.data.fill(1n, 0, num_frames);\n }\n }\n }\n\n const [num_frames, num_channels] = features.dims;\n\n const stride = this.config.stride;\n const remainder = num_frames % stride;\n if (remainder !== 0) {\n throw new Error(`The number of frames (${num_frames}) must be a multiple of the stride (${stride}).`)\n }\n\n const input_features = features.view(\n 1,\n Math.floor(num_frames / stride),\n num_channels * stride,\n );\n\n const result = { input_features }\n\n if (return_attention_mask) {\n const reshapedNumFrames = input_features.dims[1];\n\n const attention_mask_data = new BigInt64Array(reshapedNumFrames);\n\n if (padded_attention_mask) {\n const padded_attention_mask_data = padded_attention_mask.data;\n for (let i = 1, j = 0; i < num_frames; i += stride, ++j) {\n attention_mask_data[j] = padded_attention_mask_data[i];\n }\n } else {\n attention_mask_data.fill(1n);\n }\n result.attention_mask = new Tensor(\n 'int64',\n attention_mask_data,\n [1, reshapedNumFrames],\n );\n }\n\n return result;\n }\n}\n\nexport class ASTFeatureExtractor extends FeatureExtractor {\n\n\n constructor(config) {\n super(config);\n\n const sampling_rate = this.config.sampling_rate;\n const mel_filters = mel_filter_bank(\n 256, // num_frequency_bins\n this.config.num_mel_bins, // num_mel_filters\n 20, // min_frequency\n Math.floor(sampling_rate / 2), // max_frequency\n sampling_rate, // sampling_rate\n null, // norm\n \"kaldi\", // mel_scale\n true, // triangularize_in_mel_space\n );\n\n // Do padding:\n for (let i = 0; i < mel_filters.length; ++i) {\n mel_filters[i].push(0);\n }\n this.mel_filters = mel_filters;\n\n this.window = window_function(400, 'hann', {\n periodic: false,\n })\n\n this.mean = this.config.mean;\n this.std = this.config.std;\n }\n\n /**\n * Computes the log-Mel spectrogram of the provided audio waveform.\n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @param {number} max_length The maximum number of frames to return.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform, max_length) {\n // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`\n return spectrogram(\n waveform,\n this.window, // window\n 400, // frame_length\n 160, // hop_length\n {\n fft_length: 512,\n power: 2.0,\n center: false,\n preemphasis: 0.97,\n mel_filters: this.mel_filters,\n log_mel: 'log',\n mel_floor: 1.192092955078125e-07,\n remove_dc_offset: true,\n\n // Custom\n max_num_frames: max_length,\n transpose: true,\n }\n )\n }\n\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_values: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'ASTFeatureExtractor');\n\n const features = await this._extract_fbank_features(audio, this.config.max_length);\n if (this.config.do_normalize) {\n // Normalize the input audio spectrogram to have mean=0, std=0.5\n const denom = this.std * 2;\n const features_data = features.data;\n for (let i = 0; i < features_data.length; ++i) {\n features_data[i] = (features_data[i] - this.mean) / denom;\n }\n }\n\n return {\n input_values: features.unsqueeze_(0)\n };\n }\n}\n\nexport class ClapFeatureExtractor extends FeatureExtractor {\n\n constructor(config) {\n super(config);\n\n this.mel_filters = mel_filter_bank(\n this.config.nb_frequency_bins, // num_frequency_bins\n this.config.feature_size, // num_mel_filters\n this.config.frequency_min, // min_frequency\n this.config.frequency_max, // max_frequency\n this.config.sampling_rate, // sampling_rate\n null, // norm\n \"htk\", // mel_scale\n );\n\n this.mel_filters_slaney = mel_filter_bank(\n this.config.nb_frequency_bins, // num_frequency_bins\n this.config.feature_size, // num_mel_filters\n this.config.frequency_min, // min_frequency\n this.config.frequency_max, // max_frequency\n this.config.sampling_rate, // sampling_rate\n \"slaney\", // norm\n \"slaney\", // mel_scale\n );\n\n this.window = window_function(this.config.fft_window_size, 'hann')\n\n }\n\n\n /**\n * Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments.\n * \n * Four different path are possible:\n * - `truncation=\"fusion\"` and the length of the waveform is greater than the max length: the mel spectrogram\n * will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram\n * are then stacked together. They will later be used for `feature_fusion`.\n * - `truncation=\"rand_trunc\"` and the length of the waveform is smaller than the max length: the audio is\n * padded based on `padding`.\n * - `truncation=\"fusion\"` and the length of the waveform is smaller than the max length: the audio is padded\n * based on `padding`, and is repeated `4` times.\n * - `truncation=\"rand_trunc\"` and the length of the waveform is greater than the max length: the mel\n * spectrogram will be computed on a random crop of the waveform.\n * \n * @param {Float32Array|Float64Array} waveform The input waveform.\n * @param {number} max_length The maximum length of the waveform.\n * @param {string} truncation The truncation strategy to use.\n * @param {string} padding The padding strategy to use.\n * @returns {Promise} An object containing the mel spectrogram data as a Float32Array, its dimensions as an array of numbers, and a boolean indicating whether the waveform was longer than the max length.\n * @private\n */\n async _get_input_mel(waveform, max_length, truncation, padding) {\n\n /** @type {Tensor} */\n let input_mel;\n let longer = false;\n const diff = waveform.length - max_length;\n if (diff > 0) {\n if (truncation === 'rand_trunc') {\n longer = true;\n const idx = Math.floor(Math.random() * (diff + 1));\n waveform = waveform.subarray(idx, idx + max_length);\n\n input_mel = await this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples);\n } else {\n // TODO implement fusion strategy\n throw new Error(`Truncation strategy \"${truncation}\" not implemented`)\n }\n } else {\n if (diff < 0) {\n let padded = new Float64Array(max_length); // already padded with zeros\n padded.set(waveform);\n\n if (padding === 'repeat') {\n for (let i = waveform.length; i < max_length; i += waveform.length) {\n padded.set(waveform.subarray(0, Math.min(waveform.length, max_length - i)), i);\n }\n } else if (padding === 'repeatpad') {\n for (let i = waveform.length; i < -diff; i += waveform.length) {\n padded.set(waveform, i);\n }\n }\n waveform = padded;\n }\n\n if (truncation === 'fusion') {\n throw new Error(`Truncation strategy \"${truncation}\" not implemented`)\n }\n\n input_mel = await this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples);\n }\n\n return input_mel.unsqueeze_(0);\n }\n\n /**\n * Compute the log-mel spectrogram of the provided `waveform` using the Hann window.\n * In CLAP, two different filter banks are used depending on the truncation pattern:\n * - `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from\n * calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation`\n * is set to `\"fusion\"`.\n * - `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used\n * `librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original\n * implementation when the truncation mode is not `\"fusion\"`.\n * \n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @param {number[][]} mel_filters The mel filters to use.\n * @param {number} [max_length=null] The maximum number of frames to return.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform, mel_filters, max_length = null) {\n // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`\n return spectrogram(\n waveform,\n this.window, // window\n this.config.fft_window_size, // frame_length\n this.config.hop_length, // hop_length\n {\n power: 2.0,\n mel_filters,\n log_mel: 'dB',\n\n // Custom\n max_num_frames: max_length,\n do_pad: false,\n transpose: true,\n }\n )\n }\n\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.\n */\n async _call(audio, {\n max_length = null,\n } = {}) {\n validate_audio_inputs(audio, 'ClapFeatureExtractor');\n\n // convert to mel spectrogram, truncate and pad if needed.\n const padded_inputs = await this._get_input_mel(\n audio,\n max_length ?? this.config.nb_max_samples,\n this.config.truncation,\n this.config.padding,\n );\n\n return {\n input_features: padded_inputs.unsqueeze_(0),\n }\n }\n}\n\n\nexport class PyAnnoteFeatureExtractor extends FeatureExtractor {\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_values: Tensor; }>} The extracted input features.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'PyAnnoteFeatureExtractor');\n\n if (audio instanceof Float64Array) {\n audio = new Float32Array(audio);\n }\n\n const shape = [\n 1, /* batch_size */\n 1, /* num_channels */\n audio.length, /* num_samples */\n ];\n return {\n input_values: new Tensor('float32', audio, shape),\n };\n }\n\n /**\n * NOTE: Can return fractional values. `Math.ceil` will ensure correct value.\n * @param {number} samples The number of frames in the audio.\n * @returns {number} The number of frames in the audio.\n */\n samples_to_frames(samples) {\n return ((samples - this.config.offset) / this.config.step);\n }\n\n /**\n * Post-processes the speaker diarization logits output by the model.\n * @param {Tensor} logits The speaker diarization logits output by the model.\n * @param {number} num_samples Number of samples in the input audio.\n * @returns {Array>} The post-processed speaker diarization results.\n */\n post_process_speaker_diarization(logits, num_samples) {\n const ratio = (\n num_samples / this.samples_to_frames(num_samples)\n ) / this.config.sampling_rate;\n\n const results = [];\n for (const scores of logits.tolist()) {\n const accumulated_segments = [];\n\n let current_speaker = -1;\n for (let i = 0; i < scores.length; ++i) {\n const probabilities = softmax(scores[i]);\n const [score, id] = max(probabilities);\n const [start, end] = [i, i + 1];\n\n if (id !== current_speaker) {\n // Speaker has changed\n current_speaker = id;\n accumulated_segments.push({ id, start, end, score });\n } else {\n // Continue the current segment\n accumulated_segments.at(-1).end = end;\n accumulated_segments.at(-1).score += score;\n }\n }\n\n results.push(accumulated_segments.map(\n // Convert frame-space to time-space\n // and compute the confidence\n ({ id, start, end, score }) => ({\n id,\n start: start * ratio,\n end: end * ratio,\n confidence: score / (end - start),\n })\n ));\n }\n return results;\n }\n\n}\n\nexport class WeSpeakerFeatureExtractor extends FeatureExtractor {\n\n constructor(config) {\n super(config);\n\n const sampling_rate = this.config.sampling_rate;\n const mel_filters = mel_filter_bank(\n 256, // num_frequency_bins\n this.config.num_mel_bins, // num_mel_filters\n 20, // min_frequency\n Math.floor(sampling_rate / 2), // max_frequency\n sampling_rate, // sampling_rate\n null, // norm\n \"kaldi\", // mel_scale\n true, // triangularize_in_mel_space\n );\n\n // Do padding:\n for (let i = 0; i < mel_filters.length; ++i) {\n mel_filters[i].push(0);\n }\n this.mel_filters = mel_filters;\n\n this.window = window_function(400, 'hamming', {\n periodic: false,\n })\n this.min_num_frames = this.config.min_num_frames;\n }\n\n /**\n * Computes the log-Mel spectrogram of the provided audio waveform.\n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform) {\n // Kaldi compliance: 16-bit signed integers\n // 32768 == 2 ** 15\n waveform = waveform.map((/** @type {number} */ x) => x * 32768)\n\n return spectrogram(\n waveform,\n this.window, // window\n 400, // frame_length\n 160, // hop_length\n {\n fft_length: 512,\n power: 2.0,\n center: false,\n preemphasis: 0.97,\n mel_filters: this.mel_filters,\n log_mel: 'log',\n mel_floor: 1.192092955078125e-07,\n remove_dc_offset: true,\n\n // Custom\n transpose: true,\n min_num_frames: this.min_num_frames,\n }\n )\n }\n\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'WeSpeakerFeatureExtractor');\n\n const features = (await this._extract_fbank_features(audio)).unsqueeze_(0);\n\n if (this.config.fbank_centering_span === null) {\n // center features with global average\n const meanData = /** @type {Float32Array} */ (features.mean(1).data);\n const featuresData = /** @type {Float32Array} */(features.data);\n const [batch_size, num_frames, feature_size] = features.dims;\n\n for (let i = 0; i < batch_size; ++i) {\n const offset1 = i * num_frames * feature_size;\n const offset2 = i * feature_size;\n for (let j = 0; j < num_frames; ++j) {\n const offset3 = offset1 + j * feature_size;\n for (let k = 0; k < feature_size; ++k) {\n featuresData[offset3 + k] -= meanData[offset2 + k];\n }\n }\n }\n }\n\n return {\n input_features: features\n };\n }\n}\n\nexport class SpeechT5FeatureExtractor extends FeatureExtractor { }\n\n/**\n * Represents a Processor that extracts features from an input.\n * @extends Callable\n */\nexport class Processor extends Callable {\n /**\n * Creates a new Processor with the given feature extractor.\n * @param {FeatureExtractor} feature_extractor The function used to extract features from the input.\n */\n constructor(feature_extractor) {\n super();\n this.feature_extractor = feature_extractor;\n // TODO use tokenizer here?\n }\n\n /**\n * Calls the feature_extractor function with the given input.\n * @param {any} input The input to extract features from.\n * @param {...any} args Additional arguments.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(input, ...args) {\n return await this.feature_extractor(input, ...args);\n }\n}\n\nexport class SamProcessor extends Processor {\n /**\n * @borrows SamImageProcessor#_call as _call\n */\n async _call(...args) {\n return await this.feature_extractor(...args);\n }\n\n /**\n * @borrows SamImageProcessor#post_process_masks as post_process_masks\n */\n post_process_masks(...args) {\n // @ts-ignore\n return this.feature_extractor.post_process_masks(...args);\n }\n /**\n * @borrows SamImageProcessor#reshape_input_points as reshape_input_points\n */\n reshape_input_points(...args) {\n // @ts-ignore\n return this.feature_extractor.reshape_input_points(...args);\n }\n}\n\n/**\n * Represents a WhisperProcessor that extracts features from an audio input.\n * @extends Processor\n */\nexport class WhisperProcessor extends Processor {\n /**\n * Calls the feature_extractor function with the given audio input.\n * @param {any} audio The audio input to extract features from.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(audio) {\n return await this.feature_extractor(audio)\n }\n}\n\n\nexport class Wav2Vec2ProcessorWithLM extends Processor {\n /**\n * Calls the feature_extractor function with the given audio input.\n * @param {any} audio The audio input to extract features from.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(audio) {\n return await this.feature_extractor(audio)\n }\n}\n\nexport class PyAnnoteProcessor extends Processor {\n /**\n * Calls the feature_extractor function with the given audio input.\n * @param {any} audio The audio input to extract features from.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(audio) {\n return await this.feature_extractor(audio)\n }\n\n post_process_speaker_diarization(...args) {\n // @ts-ignore\n return this.feature_extractor.post_process_speaker_diarization(...args);\n }\n\n}\n\nexport class SpeechT5Processor extends Processor {\n /**\n * Calls the feature_extractor function with the given input.\n * @param {any} input The input to extract features from.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(input) {\n return await this.feature_extractor(input)\n }\n}\n\nexport class OwlViTProcessor extends Processor { }\n\nexport class Florence2Processor extends Processor {\n constructor(feature_extractor) {\n super(feature_extractor);\n\n const {\n tasks_answer_post_processing_type,\n task_prompts_without_inputs,\n task_prompts_with_input,\n } = feature_extractor.config;\n\n /** @type {Map} */\n this.tasks_answer_post_processing_type = new Map(Object.entries(tasks_answer_post_processing_type ?? {}));\n\n /** @type {Map} */\n this.task_prompts_without_inputs = new Map(Object.entries(task_prompts_without_inputs ?? {}));\n\n /** @type {Map} */\n this.task_prompts_with_input = new Map(Object.entries(task_prompts_with_input ?? {}));\n\n this.regexes = {\n quad_boxes: /(.+?)/gm,\n bboxes: /([^<]+)?/gm,\n }\n this.size_per_bin = 1000;\n }\n\n /**\n * Helper function to construct prompts from input texts\n * @param {string|string[]} text\n * @returns {string[]}\n */\n construct_prompts(text) {\n if (typeof text === 'string') {\n text = [text];\n }\n\n const prompts = [];\n for (const t of text) {\n // 1. fixed task prompts without additional inputs\n if (this.task_prompts_without_inputs.has(t)) {\n prompts.push(this.task_prompts_without_inputs.get(t));\n }\n // 2. task prompts with additional inputs \n else {\n for (const [task, prompt] of this.task_prompts_with_input) {\n if (t.includes(task)) {\n prompts.push(prompt.replaceAll('{input}', t).replaceAll(task, ''));\n break;\n }\n }\n\n // 3. default prompt\n if (prompts.length !== text.length) {\n prompts.push(t);\n }\n }\n }\n return prompts;\n }\n\n /**\n * Post-process the output of the model to each of the task outputs.\n * @param {string} text The text to post-process.\n * @param {string} task The task to post-process the text for.\n * @param {[number, number]} image_size The size of the image. height x width.\n */\n post_process_generation(text, task, image_size) {\n const task_answer_post_processing_type = this.tasks_answer_post_processing_type.get(task) ?? 'pure_text';\n\n // remove the special tokens\n text = text.replaceAll('', '').replaceAll('', '');\n\n let final_answer;\n switch (task_answer_post_processing_type) {\n case 'pure_text':\n final_answer = text;\n break;\n\n case 'description_with_bboxes':\n case 'bboxes':\n case 'phrase_grounding':\n case 'ocr':\n const key = task_answer_post_processing_type === 'ocr' ? 'quad_boxes' : 'bboxes';\n const matches = text.matchAll(this.regexes[key]);\n const labels = [];\n const items = [];\n for (const [_, label, ...locations] of matches) {\n // Push new label, or duplicate the last label\n labels.push(label ? label.trim() : labels.at(-1) ?? '');\n items.push(locations.map((x, i) =>\n // NOTE: Add 0.5 to use the center position of the bin as the coordinate.\n (Number(x) + 0.5) / this.size_per_bin * image_size[i % 2])\n );\n }\n final_answer = { labels, [key]: items };\n break;\n\n default:\n throw new Error(`Task \"${task}\" (of type \"${task_answer_post_processing_type}\") not yet implemented.`);\n }\n\n return { [task]: final_answer }\n }\n}\n\n//////////////////////////////////////////////////\n/**\n * Helper class which is used to instantiate pretrained processors with the `from_pretrained` function.\n * The chosen processor class is determined by the type specified in the processor config.\n * \n * **Example:** Load a processor using `from_pretrained`.\n * ```javascript\n * let processor = await AutoProcessor.from_pretrained('openai/whisper-tiny.en');\n * ```\n * \n * **Example:** Run an image through a processor.\n * ```javascript\n * let processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16');\n * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * let image_inputs = await processor(image);\n * // {\n * // \"pixel_values\": {\n * // \"dims\": [ 1, 3, 224, 224 ],\n * // \"type\": \"float32\",\n * // \"data\": Float32Array [ -1.558687686920166, -1.558687686920166, -1.5440893173217773, ... ],\n * // \"size\": 150528\n * // },\n * // \"original_sizes\": [\n * // [ 533, 800 ]\n * // ],\n * // \"reshaped_input_sizes\": [\n * // [ 224, 224 ]\n * // ]\n * // }\n * ```\n */\nexport class AutoProcessor {\n static FEATURE_EXTRACTOR_CLASS_MAPPING = {\n ImageFeatureExtractor,\n WhisperFeatureExtractor,\n ViTFeatureExtractor,\n MobileViTFeatureExtractor,\n MobileViTImageProcessor,\n MobileNetV1FeatureExtractor,\n MobileNetV2FeatureExtractor,\n MobileNetV3FeatureExtractor,\n MobileNetV4FeatureExtractor,\n OwlViTFeatureExtractor,\n Owlv2ImageProcessor,\n CLIPFeatureExtractor,\n CLIPImageProcessor,\n Florence2Processor,\n ChineseCLIPFeatureExtractor,\n SiglipImageProcessor,\n ConvNextFeatureExtractor,\n ConvNextImageProcessor,\n SegformerFeatureExtractor,\n SapiensFeatureExtractor,\n BitImageProcessor,\n DPTImageProcessor,\n DPTFeatureExtractor,\n PvtImageProcessor,\n GLPNFeatureExtractor,\n BeitFeatureExtractor,\n DeiTFeatureExtractor,\n DetrFeatureExtractor,\n RTDetrImageProcessor,\n MaskFormerFeatureExtractor,\n YolosFeatureExtractor,\n DonutFeatureExtractor,\n NougatImageProcessor,\n EfficientNetImageProcessor,\n\n ViTImageProcessor,\n VitMatteImageProcessor,\n SamImageProcessor,\n Swin2SRImageProcessor,\n Wav2Vec2FeatureExtractor,\n SeamlessM4TFeatureExtractor,\n SpeechT5FeatureExtractor,\n ASTFeatureExtractor,\n ClapFeatureExtractor,\n PyAnnoteFeatureExtractor,\n WeSpeakerFeatureExtractor,\n }\n\n static PROCESSOR_CLASS_MAPPING = {\n WhisperProcessor,\n Wav2Vec2ProcessorWithLM,\n PyAnnoteProcessor,\n SamProcessor,\n SpeechT5Processor,\n OwlViTProcessor,\n Florence2Processor,\n }\n\n /**\n * Instantiate one of the processor classes of the library from a pretrained model.\n * \n * The processor class to instantiate is selected based on the `feature_extractor_type` property of the config object\n * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)\n * \n * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:\n * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co.\n * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a\n * user or organization name, like `dbmdz/bert-base-german-cased`.\n * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`.\n * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the processor.\n * \n * @returns {Promise} A new instance of the Processor class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n } = {}) {\n\n let preprocessorConfig = config ?? await getModelJSON(pretrained_model_name_or_path, 'preprocessor_config.json', true, {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n })\n\n // Determine feature extractor class\n // TODO: Ensure backwards compatibility with old configs\n let key = preprocessorConfig.feature_extractor_type ?? preprocessorConfig.image_processor_type;\n let feature_extractor_class = this.FEATURE_EXTRACTOR_CLASS_MAPPING[key];\n\n if (!feature_extractor_class) {\n if (preprocessorConfig.size !== undefined) {\n // Assume ImageFeatureExtractor\n console.warn(`Feature extractor type \"${key}\" not found, assuming ImageFeatureExtractor due to size parameter in config.`);\n feature_extractor_class = ImageFeatureExtractor;\n } else {\n throw new Error(`Unknown Feature Extractor type: ${key}`);\n }\n }\n\n // If no associated processor class, use default\n let processor_class = this.PROCESSOR_CLASS_MAPPING[preprocessorConfig.processor_class] ?? Processor;\n\n // Instantiate processor and feature extractor\n let feature_extractor = new feature_extractor_class(preprocessorConfig);\n return new processor_class(feature_extractor);\n }\n}\n//////////////////////////////////////////////////\n\n","\n/**\n * @file Tokenizers are used to prepare textual inputs for a model.\n * \n * **Example:** Create an `AutoTokenizer` and use it to tokenize a sentence.\n * This will automatically detect the tokenizer type based on the tokenizer class defined in `tokenizer.json`.\n * ```javascript\n * import { AutoTokenizer } from '@huggingface/transformers';\n * \n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');\n * const { input_ids } = await tokenizer('I love transformers!');\n * // Tensor {\n * // data: BigInt64Array(6) [101n, 1045n, 2293n, 19081n, 999n, 102n],\n * // dims: [1, 6],\n * // type: 'int64',\n * // size: 6,\n * // }\n * ```\n * \n * @module tokenizers\n */\nimport {\n Callable,\n} from './utils/generic.js';\n\nimport {\n reverseDictionary,\n escapeRegExp,\n isIntegralNumber,\n mergeArrays,\n len,\n} from './utils/core.js';\n\nimport {\n getModelJSON,\n} from './utils/hub.js';\n\nimport { max, min, round } from './utils/maths.js';\nimport { Tensor } from './utils/tensor.js';\n\nimport {\n PriorityQueue,\n TokenLattice,\n CharTrie,\n} from './utils/data-structures.js';\n\nimport { Template } from '@huggingface/jinja';\n\nimport {\n WHISPER_LANGUAGE_MAPPING,\n whisper_language_to_code,\n} from './models/whisper/common_whisper.js';\nimport { GITHUB_ISSUE_URL } from './utils/constants.js';\n\n/**\n * @typedef {Object} TokenizerProperties Additional tokenizer-specific properties.\n * @property {boolean} [legacy=false] Whether or not the `legacy` behavior of the tokenizer should be used.\n * @typedef {import('./utils/hub.js').PretrainedOptions & TokenizerProperties} PretrainedTokenizerOptions\n */\n\n/**\n * Loads a tokenizer from the specified path.\n * @param {string} pretrained_model_name_or_path The path to the tokenizer directory.\n * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.\n * @returns {Promise} A promise that resolves with information about the loaded tokenizer.\n */\nasync function loadTokenizer(pretrained_model_name_or_path, options) {\n\n const info = await Promise.all([\n getModelJSON(pretrained_model_name_or_path, 'tokenizer.json', true, options),\n getModelJSON(pretrained_model_name_or_path, 'tokenizer_config.json', true, options),\n ])\n\n // Override legacy option if `options.legacy` is not null\n if (options.legacy !== null) {\n info[1].legacy = options.legacy;\n }\n return info;\n}\n\n\n/**\n * Helper function to split a string on a regex, but keep the delimiters.\n * This is required, because the JavaScript `.split()` method does not keep the delimiters,\n * and wrapping in a capturing group causes issues with existing capturing groups (due to nesting).\n * @param {string} text The text to split.\n * @param {RegExp} regex The regex to split on.\n * @returns {string[]} The split string.\n */\nfunction regexSplit(text, regex) {\n const result = [];\n let prev = 0;\n for (const match of text.matchAll(regex)) {\n const fullMatch = match[0];\n if (prev < match.index) {\n result.push(text.slice(prev, match.index));\n }\n if (fullMatch.length > 0) {\n result.push(fullMatch);\n }\n prev = match.index + fullMatch.length;\n }\n if (prev < text.length) {\n result.push(text.slice(prev));\n }\n return result;\n}\n\n\n/**\n * Helper method to construct a pattern from a config object.\n * @param {Object} pattern The pattern object.\n * @param {boolean} invert Whether to invert the pattern.\n * @returns {RegExp|null} The compiled pattern.\n */\nfunction createPattern(pattern, invert = true) {\n\n if (pattern.Regex !== undefined) {\n // In certain cases, the pattern may contain unnecessary escape sequences (e.g., \\# or \\& or \\~).\n // i.e., valid in Python (where the patterns are exported from) but invalid in JavaScript (where the patterns are parsed).\n // This isn't an issue when creating the regex w/o the 'u' flag, but it is when the 'u' flag is used.\n // For this reason, it is necessary to remove these backslashes before creating the regex.\n // See https://stackoverflow.com/a/63007777/13989043 for more information\n let regex = pattern.Regex.replace(/\\\\([#&~])/g, '$1'); // TODO: add more characters to this list if necessary\n\n // We also handle special cases where the regex contains invalid (non-JS compatible) syntax.\n for (const [key, value] of PROBLEMATIC_REGEX_MAP) {\n regex = regex.replaceAll(key, value);\n }\n\n return new RegExp(regex, 'gu');\n\n } else if (pattern.String !== undefined) {\n const escaped = escapeRegExp(pattern.String);\n // NOTE: if invert is true, we wrap the pattern in a group so that it is kept when performing .split()\n return new RegExp(invert ? escaped : `(${escaped})`, 'gu');\n\n } else {\n console.warn('Unknown pattern type:', pattern)\n return null;\n }\n}\n\n/**\n * Helper function to convert an Object to a Map\n * @param {Object} obj The object to convert.\n * @returns {Map} The map.\n */\nfunction objectToMap(obj) {\n return new Map(Object.entries(obj));\n}\n\n/**\n * Helper function to convert a tensor to a list before decoding.\n * @param {Tensor} tensor The tensor to convert.\n * @returns {number[]} The tensor as a list.\n */\nfunction prepareTensorForDecode(tensor) {\n const dims = tensor.dims;\n switch (dims.length) {\n case 1:\n return tensor.tolist();\n case 2:\n if (dims[0] !== 1) {\n throw new Error('Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.');\n }\n return tensor.tolist()[0];\n default:\n throw new Error(`Expected tensor to have 1-2 dimensions, got ${dims.length}.`)\n }\n}\n\n/**\n * Clean up a list of simple English tokenization artifacts like spaces before punctuations and abbreviated forms\n * @param {string} text The text to clean up.\n * @returns {string} The cleaned up text.\n */\nfunction clean_up_tokenization(text) {\n // Clean up a list of simple English tokenization artifacts\n // like spaces before punctuations and abbreviated forms\n return text.replace(/ \\./g, '.')\n .replace(/ \\?/g, '?')\n .replace(/ \\!/g, '!')\n .replace(/ ,/g, ',')\n .replace(/ \\' /g, \"'\")\n .replace(/ n\\'t/g, \"n't\")\n .replace(/ \\'m/g, \"'m\")\n .replace(/ \\'s/g, \"'s\")\n .replace(/ \\'ve/g, \"'ve\")\n .replace(/ \\'re/g, \"'re\");\n}\n\n/**\n * Helper function to remove accents from a string.\n * @param {string} text The text to remove accents from.\n * @returns {string} The text with accents removed.\n */\nfunction remove_accents(text) {\n return text.replace(/\\p{M}/gu, '');\n}\n\n/**\n * Helper function to lowercase a string and remove accents.\n * @param {string} text The text to lowercase and remove accents from.\n * @returns {string} The lowercased text with accents removed.\n */\nfunction lowercase_and_remove_accent(text) {\n return remove_accents(text.toLowerCase());\n}\n\n\n/**\n * Checks whether the given Unicode codepoint represents a CJK (Chinese, Japanese, or Korean) character.\n *\n * A \"chinese character\" is defined as anything in the CJK Unicode block:\n * https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)\n *\n * Note that the CJK Unicode block is NOT all Japanese and Korean characters, despite its name.\n * The modern Korean Hangul alphabet is a different block, as is Japanese Hiragana and Katakana.\n * Those alphabets are used to write space-separated words, so they are not treated specially\n * and are handled like all other languages.\n *\n * @param {number|bigint} cp The Unicode codepoint to check.\n * @returns {boolean} True if the codepoint represents a CJK character, false otherwise.\n */\nexport function is_chinese_char(cp) {\n return (\n (cp >= 0x4E00 && cp <= 0x9FFF)\n || (cp >= 0x3400 && cp <= 0x4DBF)\n || (cp >= 0x20000 && cp <= 0x2A6DF)\n || (cp >= 0x2A700 && cp <= 0x2B73F)\n || (cp >= 0x2B740 && cp <= 0x2B81F)\n || (cp >= 0x2B820 && cp <= 0x2CEAF)\n || (cp >= 0xF900 && cp <= 0xFAFF)\n || (cp >= 0x2F800 && cp <= 0x2FA1F)\n )\n}\n\n/**\n * Helper function to fuse consecutive unknown tokens.\n * @param {string[]} arr The list of input tokens\n * @param {Map} tokens_to_ids The mapping from tokens to token ids.\n * @param {number} unk_token_id The value to fuse on.\n * @private\n */\nfunction fuse_unk(arr, tokens_to_ids, unk_token_id) {\n const fused = [];\n let i = 0;\n while (i < arr.length) {\n fused.push(arr[i])\n if ((tokens_to_ids.get(arr[i]) ?? unk_token_id) !== unk_token_id) {\n ++i;\n continue;\n }\n\n while (++i < arr.length && (tokens_to_ids.get(arr[i]) ?? unk_token_id) === unk_token_id) {\n if (tokens_to_ids.get(fused.at(-1)) !== unk_token_id) {\n fused[fused.length - 1] += arr[i];\n }\n }\n }\n\n return fused;\n}\n\n/**\n * Split a string on whitespace.\n * @param {string} text The text to split.\n * @returns {string[]} The split string.\n */\nfunction whitespace_split(text) {\n return text.match(/\\S+/g) || [];\n}\n\nconst PUNCTUATION_REGEX = '\\\\p{P}\\\\u0021-\\\\u002F\\\\u003A-\\\\u0040\\\\u005B-\\\\u0060\\\\u007B-\\\\u007E';\nconst PUNCTUATION_ONLY_REGEX = new RegExp(`^[${PUNCTUATION_REGEX}]+$`, 'gu');\nconst BLOOM_SPLIT_CHARS = '.,!?\\u2026\\u3002\\uff0c\\u3001\\u0964\\u06d4\\u060c';\n\n// A mapping of regex patterns to their equivalent (but possibly longer) JS-compatible versions.\nconst PROBLEMATIC_REGEX_MAP = new Map([\n // This uses the case insensitive group modifier, which is not supported in JavaScript.\n // When parsing the regex, an \"Invalid group\" error is thrown.\n [\"(?i:'s|'t|'re|'ve|'m|'ll|'d)\", \"(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))\"],\n\n // Used to override the default (invalid) regex of the bloom pretokenizer.\n // For more information, see https://github.com/huggingface/transformers.js/issues/94\n [` ?[^(\\\\s|[${BLOOM_SPLIT_CHARS}])]+`, ` ?[^\\\\s${BLOOM_SPLIT_CHARS}]+`],\n])\n\n\n/**\n * Represent a token added by the user on top of the existing Model vocabulary.\n * AddedToken can be configured to specify the behavior they should have in various situations like:\n * - Whether they should only match single words\n * - Whether to include any whitespace on its left or right\n */\nclass AddedToken {\n /**\n * Creates a new instance of AddedToken.\n * @param {Object} config Added token configuration object.\n * @param {string} config.content The content of the added token.\n * @param {number} config.id The id of the added token.\n * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words.\n * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left.\n * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right.\n * @param {boolean} [config.normalized=false] Whether this token should be normalized.\n * @param {boolean} [config.special=false] Whether this token is special.\n */\n constructor(config) {\n this.content = config.content;\n this.id = config.id;\n this.single_word = config.single_word ?? false;\n this.lstrip = config.lstrip ?? false;\n this.rstrip = config.rstrip ?? false;\n this.special = config.special ?? false;\n this.normalized = config.normalized ?? null;\n }\n}\n\n/**\n * Abstract base class for tokenizer models.\n *\n * @extends Callable\n */\nexport class TokenizerModel extends Callable {\n /**\n * Creates a new instance of TokenizerModel.\n * @param {Object} config The configuration object for the TokenizerModel.\n */\n constructor(config) {\n super();\n this.config = config;\n\n /** @type {string[]} */\n this.vocab = [];\n\n /**\n * A mapping of tokens to ids.\n * @type {Map}\n */\n this.tokens_to_ids = new Map();\n\n this.unk_token_id = undefined;\n this.unk_token = undefined;\n this.end_of_word_suffix = undefined;\n\n /** @type {boolean} Whether to fuse unknown tokens when encoding. Defaults to false. */\n this.fuse_unk = this.config.fuse_unk ?? false;\n }\n\n /**\n * Instantiates a new TokenizerModel instance based on the configuration object provided.\n * @param {Object} config The configuration object for the TokenizerModel.\n * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor.\n * @returns {TokenizerModel} A new instance of a TokenizerModel.\n * @throws Will throw an error if the TokenizerModel type in the config is not recognized.\n */\n static fromConfig(config, ...args) {\n switch (config.type) {\n case 'WordPiece':\n return new WordPieceTokenizer(config);\n case 'Unigram':\n // @ts-ignore\n return new Unigram(config, ...args);\n case 'BPE':\n return new BPE(config);\n\n default:\n // Some tokenizers, like for google-t5/t5-small, do not have a `type` field.\n // In this case, we can infer the tokenizer type based on the structure of the `vocab` field.\n if (config.vocab) {\n if (Array.isArray(config.vocab)) {\n // config.vocab is of type `[string, number][]`\n // @ts-ignore\n return new Unigram(config, ...args);\n } else {\n // @ts-ignore\n return new LegacyTokenizerModel(config, ...args);\n }\n }\n throw new Error(`Unknown TokenizerModel type: ${config.type}`);\n }\n }\n\n /**\n * Internal function to call the TokenizerModel instance.\n * @param {string[]} tokens The tokens to encode.\n * @returns {string[]} The encoded tokens.\n */\n _call(tokens) {\n tokens = this.encode(tokens);\n if (this.fuse_unk) {\n // Fuse unknown tokens\n tokens = fuse_unk(tokens, this.tokens_to_ids, this.unk_token_id);\n }\n return tokens;\n }\n\n /**\n * Encodes a list of tokens into a list of token IDs.\n * @param {string[]} tokens The tokens to encode.\n * @returns {string[]} The encoded tokens.\n * @throws Will throw an error if not implemented in a subclass.\n */\n encode(tokens) {\n throw Error(\"encode should be implemented in subclass.\")\n }\n\n /**\n * Converts a list of tokens into a list of token IDs.\n * @param {string[]} tokens The tokens to convert.\n * @returns {number[]} The converted token IDs.\n */\n convert_tokens_to_ids(tokens) {\n return tokens.map(t => this.tokens_to_ids.get(t) ?? this.unk_token_id);\n }\n\n /**\n * Converts a list of token IDs into a list of tokens.\n * @param {number[]|bigint[]} ids The token IDs to convert.\n * @returns {string[]} The converted tokens.\n */\n convert_ids_to_tokens(ids) {\n return ids.map(i => this.vocab[i] ?? this.unk_token);\n }\n}\n\n/**\n * A subclass of TokenizerModel that uses WordPiece encoding to encode tokens.\n * @extends TokenizerModel\n */\nclass WordPieceTokenizer extends TokenizerModel {\n /**\n * @param {Object} config The configuration object.\n * @param {Object} config.vocab A mapping of tokens to ids.\n * @param {string} config.unk_token The unknown token string.\n * @param {string} config.continuing_subword_prefix The prefix to use for continuing subwords.\n * @param {number} [config.max_input_chars_per_word=100] The maximum number of characters per word.\n */\n constructor(config) {\n super(config);\n /**\n * A mapping of tokens to ids.\n * @type {Map}\n */\n this.tokens_to_ids = objectToMap(config.vocab);\n\n /**\n * The id of the unknown token.\n * @type {number}\n */\n this.unk_token_id = this.tokens_to_ids.get(config.unk_token);\n\n /**\n * The unknown token string.\n * @type {string}\n */\n this.unk_token = config.unk_token;\n\n /**\n * The maximum number of characters allowed per word.\n * @type {number}\n */\n this.max_input_chars_per_word = config.max_input_chars_per_word ?? 100;\n\n /**\n * An array of tokens.\n * @type {string[]}\n */\n this.vocab = new Array(this.tokens_to_ids.size);\n for (const [key, value] of this.tokens_to_ids) {\n this.vocab[value] = key;\n }\n }\n\n /**\n * Encodes an array of tokens using WordPiece encoding.\n * @param {string[]} tokens The tokens to encode.\n * @returns {string[]} An array of encoded tokens.\n */\n encode(tokens) {\n const outputTokens = [];\n for (const token of tokens) {\n const chars = [...token];\n if (chars.length > this.max_input_chars_per_word) {\n outputTokens.push(this.unk_token);\n continue;\n }\n\n let isUnknown = false;\n let start = 0;\n const subTokens = [];\n\n while (start < chars.length) {\n let end = chars.length;\n let currentSubstring = null;\n while (start < end) {\n let substr = chars.slice(start, end).join('');\n\n if (start > 0) {\n substr = this.config.continuing_subword_prefix + substr;\n }\n if (this.tokens_to_ids.has(substr)) {\n currentSubstring = substr;\n break;\n }\n\n --end;\n }\n if (currentSubstring === null) {\n isUnknown = true;\n break;\n }\n subTokens.push(currentSubstring);\n start = end;\n }\n if (isUnknown) {\n outputTokens.push(this.unk_token);\n } else {\n outputTokens.push(...subTokens);\n }\n }\n\n return outputTokens;\n }\n\n}\n\n/**\n * Class representing a Unigram tokenizer model.\n * @extends TokenizerModel\n */\nclass Unigram extends TokenizerModel {\n /**\n * Create a new Unigram tokenizer model.\n * @param {Object} config The configuration object for the Unigram model.\n * @param {number} config.unk_id The ID of the unknown token\n * @param {any[][]} config.vocab A 2D array representing a mapping of tokens to scores.\n * @param {Object} moreConfig Additional configuration object for the Unigram model.\n */\n constructor(config, moreConfig) {\n super(config);\n\n const vocabSize = config.vocab.length;\n this.vocab = new Array(vocabSize);\n this.scores = new Array(vocabSize);\n for (let i = 0; i < vocabSize; ++i) {\n const piece = config.vocab[i];\n this.vocab[i] = piece[0];\n this.scores[i] = piece[1];\n }\n\n this.unk_token_id = config.unk_id;\n this.unk_token = this.vocab[config.unk_id];\n\n this.tokens_to_ids = new Map(this.vocab.map((x, i) => [x, i]));\n this.bos_token = ' '; // beginning of a sentence token\n\n this.bos_token_id = this.tokens_to_ids.get(this.bos_token); // NOTE: may be undefined\n this.eos_token = moreConfig.eos_token;\n\n this.eos_token_id = this.tokens_to_ids.get(this.eos_token);\n this.unk_token = this.vocab[this.unk_token_id];\n\n this.minScore = min(this.scores)[0];\n\n this.unk_score = this.minScore - 10.0;\n this.scores[this.unk_token_id] = this.unk_score;\n\n this.trie = new CharTrie();\n this.trie.extend(this.vocab);\n\n // NOTE: `fuse_unk` is hardcoded to true for Unigram models\n // See: https://github.com/huggingface/tokenizers/blob/b58227c7f1ccf8b73ee2268354336da56d91e492/tokenizers/src/models/unigram/model.rs#L119\n this.fuse_unk = true;\n }\n\n /**\n * Populates lattice nodes.\n * @param {TokenLattice} lattice The token lattice to populate with nodes.\n */\n populateNodes(lattice) {\n const chars = lattice.chars;\n const mblen = 1;\n let beginPos = 0;\n while (beginPos < chars.length) {\n let hasSingleNode = false;\n\n const tokens = [];\n const sliced = chars.slice(beginPos).join('');\n const prefixedTokens = this.trie.commonPrefixSearch(sliced);\n for (const token of prefixedTokens) {\n tokens.push(token);\n const tokenId = this.tokens_to_ids.get(token);\n const tokenScore = this.scores[tokenId];\n const n = len(token);\n lattice.insert(beginPos, n, tokenScore, tokenId);\n if (!hasSingleNode && n === mblen) {\n hasSingleNode = true;\n }\n }\n if (!hasSingleNode) {\n lattice.insert(beginPos, mblen, this.unk_score, this.unk_token_id);\n }\n beginPos += mblen;\n }\n }\n\n /**\n * Encodes an array of tokens into an array of subtokens using the unigram model.\n *\n * @param {string} normalized The normalized string.\n * @returns {string[]} An array of subtokens obtained by encoding the input tokens using the unigram model.\n */\n tokenize(normalized) {\n const lattice = new TokenLattice(normalized, this.bos_token_id, this.eos_token_id);\n this.populateNodes(lattice);\n return lattice.tokens();\n }\n\n /**\n * Encodes an array of tokens using Unigram encoding.\n * @param {string[]} tokens The tokens to encode.\n * @returns {string[]} An array of encoded tokens.\n */\n encode(tokens) {\n const toReturn = [];\n for (const token of tokens) {\n const tokenized = this.tokenize(token);\n toReturn.push(...tokenized);\n }\n return toReturn;\n }\n\n}\n\n/**\n * Returns list of utf-8 byte and a mapping to unicode strings.\n * Specifically avoids mapping to whitespace/control characters the BPE code barfs on.\n * @returns {Object} Object with utf-8 byte keys and unicode string values.\n */\nconst BYTES_TO_UNICODE = (() => {\n // Returns list of utf-8 byte and a mapping to unicode strings.\n // We specifically avoids mapping to whitespace/control characters\n // the bpe code barfs on.\n\n const bs = [\n ...Array.from({ length: \"~\".charCodeAt(0) - \"!\".charCodeAt(0) + 1 }, (_, i) => i + \"!\".charCodeAt(0)),\n ...Array.from({ length: \"¬\".charCodeAt(0) - \"¡\".charCodeAt(0) + 1 }, (_, i) => i + \"¡\".charCodeAt(0)),\n ...Array.from({ length: \"ÿ\".charCodeAt(0) - \"®\".charCodeAt(0) + 1 }, (_, i) => i + \"®\".charCodeAt(0)),\n ];\n const cs = bs.slice();\n let n = 0;\n for (let b = 0; b < 256; ++b) {\n if (!bs.includes(b)) {\n bs.push(b);\n cs.push(256 + n);\n n += 1;\n }\n }\n const ccs = cs.map(n => String.fromCharCode(n));\n return Object.fromEntries(bs.map((b, i) => [b, ccs[i]]));\n})();\n\nconst UNICODE_TO_BYTES = reverseDictionary(BYTES_TO_UNICODE);\n\n\n/**\n * @typedef {Object} BPENode\n * @property {string} token The token associated with the node\n * @property {number} bias A positional bias for the node.\n * @property {number} [score] The score of the node.\n * @property {BPENode} [prev] The previous node in the linked list.\n * @property {BPENode} [next] The next node in the linked list.\n */\n\n/**\n * BPE class for encoding text into Byte-Pair-Encoding (BPE) tokens.\n * @extends TokenizerModel\n */\nclass BPE extends TokenizerModel {\n /**\n * Create a BPE instance.\n * @param {Object} config The configuration object for BPE.\n * @param {Object} config.vocab A mapping of tokens to ids.\n * @param {string[]|[string, string][]} config.merges An array of BPE merges as strings.\n * @param {string} config.unk_token The unknown token used for out of vocabulary words.\n * @param {string} config.end_of_word_suffix The suffix to place at the end of each word.\n * @param {string} [config.continuing_subword_suffix] The suffix to insert between words.\n * @param {boolean} [config.byte_fallback=false] Whether to use spm byte-fallback trick (defaults to False)\n * @param {boolean} [config.ignore_merges=false] Whether or not to match tokens with the vocab before using merges.\n */\n constructor(config) {\n super(config);\n\n /** @type {Map} */\n this.tokens_to_ids = objectToMap(config.vocab);\n\n this.unk_token_id = this.tokens_to_ids.get(config.unk_token);\n this.unk_token = config.unk_token;\n\n this.vocab = new Array(this.tokens_to_ids.size);\n for (const [key, value] of this.tokens_to_ids) {\n this.vocab[value] = key;\n }\n\n // Tokenizers >= 0.20.0 serializes BPE merges as a [string, string][] instead of a string[],\n // which resolves the ambiguity for merges containing spaces.\n const use_new_merge_format = Array.isArray(config.merges[0]);\n\n /** @type {[string, string][]} */\n this.merges = use_new_merge_format\n ? /** @type {[string, string][]} */(config.merges)\n : (/** @type {string[]} */(config.merges)).map(x => /** @type {[string, string]} */(x.split(' ', 2)));\n this.bpe_ranks = new Map(this.merges.map((x, i) => [JSON.stringify(x), i]));\n\n this.end_of_word_suffix = config.end_of_word_suffix;\n\n // NOTE: `continuing_subword_suffix` is custom (to support `BlenderbotSmallTokenizer`)\n this.continuing_subword_suffix = config.continuing_subword_suffix ?? null;\n\n this.byte_fallback = this.config.byte_fallback ?? false;\n\n if (this.byte_fallback) {\n this.text_encoder = new TextEncoder();\n }\n\n this.ignore_merges = this.config.ignore_merges ?? false;\n\n /** @type {Map} */\n this.cache = new Map();\n }\n\n /**\n * Apply Byte-Pair-Encoding (BPE) to a given token. Efficient heap-based priority\n * queue implementation adapted from https://github.com/belladoreai/llama-tokenizer-js.\n * @param {string} token The token to encode.\n * @returns {string[]} The BPE encoded tokens.\n */\n bpe(token) {\n if (token.length === 0) {\n return [];\n }\n\n const cached = this.cache.get(token);\n if (cached !== undefined) {\n return cached;\n }\n\n const word = Array.from(token);\n if (this.end_of_word_suffix) {\n word[word.length - 1] += this.end_of_word_suffix;\n }\n\n let result = [];\n if (word.length > 1) {\n // Create a priority queue to store the nodes that will be merged.\n // The comparator function compares the scores of the nodes.\n const queue = new PriorityQueue((a, b) => a.score < b.score);\n\n // Construct a doubly-linked list of nodes that will be inserted into the priority queue,\n // starting with the individual characters. We also populate each node with a positional\n // bias to break ties in the priority queue.\n let startingNode = {\n token: word[0],\n bias: 0,\n prev: null,\n next: null,\n }\n\n let previousNode = startingNode\n for (let i = 1; i < word.length; ++i) {\n const currentNode = {\n bias: i / word.length, // Add fractional component to break ties\n token: word[i],\n prev: previousNode,\n next: null,\n }\n previousNode.next = currentNode\n this._add_node(queue, previousNode)\n previousNode = currentNode\n }\n\n while (!queue.isEmpty()) {\n // Get the next node with the highest priority\n const node = queue.pop();\n\n // Check that this merge is still possible\n if (node.deleted || !node.next || node.next.deleted) continue;\n\n // Here, we mark the current node (left side of the merge) and the next node (right side of the merge) as deleted.\n // This is because they will both be replaced by a new node representing the merge result.\n node.deleted = true;\n node.next.deleted = true;\n\n // Next, we fix the node that comes before the current node (i.e., left side of the merge).\n if (node.prev) {\n\n // Make a shallow copy of the previous node\n const newPreviousNode = { ...node.prev };\n\n // Mark the old previous node as deleted. This avoids erroneous merges later,\n // because there may still be references to this node in the priority queue.\n node.prev.deleted = true;\n node.prev = newPreviousNode;\n\n // Update the reference of the previous node, by pointing its previous node to this new previous node.\n if (newPreviousNode.prev) {\n newPreviousNode.prev.next = newPreviousNode;\n } else {\n // If the previous of the previous node does not exist, it means that\n // `newPreviousNode` must be the new `startingNode`.\n startingNode = newPreviousNode;\n }\n }\n\n // Create a new node which represents the result of the merge.\n const merged = {\n token: node.token + node.next.token,\n bias: node.bias,\n prev: node.prev,\n next: node.next.next,\n }\n\n // We now consider where we can add the new merged node to the priority queue:\n // 1. prev <-> merged\n if (merged.prev) {\n merged.prev.next = merged;\n this._add_node(queue, merged.prev);\n } else {\n // If `merged.prev` does not exist, then `merged` must be the new `startingNode`.\n startingNode = merged;\n }\n\n // 2. merged <-> next\n if (merged.next) {\n merged.next.prev = merged;\n this._add_node(queue, merged);\n }\n }\n\n // Traverse the linked list, starting from the `startingNode`, and collect the tokens.\n for (let currentNode = startingNode; currentNode !== null; currentNode = currentNode.next) {\n result.push(currentNode.token);\n }\n } else {\n result = word;\n }\n\n // Possibly append suffix\n if (this.continuing_subword_suffix) {\n // Do not append suffix to the last token\n for (let i = 0; i < result.length - 1; ++i) {\n result[i] += this.continuing_subword_suffix;\n }\n }\n\n // Save the result to the cache\n this.cache.set(token, result);\n\n return result;\n }\n\n\n /**\n * Helper function to add a node to the priority queue.\n * @param {PriorityQueue} queue \n * @param {BPENode} node\n * @private\n */\n _add_node(queue, node) {\n // `score` is a measure of the merge priority: lower means higher priority\n // We use the BPE rank as a measure of priority (i.e., the local of the merge in the merges list)\n // We also add a fractional component to the score to break ties (with the earlier character having higher priority)\n const rank = this.bpe_ranks.get(JSON.stringify([node.token, node.next.token]));\n if (rank !== undefined) {\n node.score = rank + node.bias;\n queue.push(node);\n }\n }\n\n /**\n * Encodes the input sequence of tokens using the BPE algorithm and returns the resulting subword tokens.\n * @param {string[]} tokens The input sequence of tokens to encode.\n * @returns {string[]} The resulting subword tokens after applying the BPE algorithm to the input sequence of tokens.\n */\n encode(tokens) {\n const outputTokens = [];\n\n for (const token of tokens) {\n if (this.ignore_merges && this.tokens_to_ids.has(token)) {\n outputTokens.push(token);\n continue;\n }\n const bpe_token_list = this.bpe(token);\n\n for (const t of bpe_token_list) {\n if (this.tokens_to_ids.has(t)) {\n outputTokens.push(t);\n } else if (this.byte_fallback) {\n const byteTokens = Array.from(this.text_encoder.encode(t))\n .map(x => `<0x${x.toString(16).toUpperCase().padStart(2, '0')}>`);\n if (byteTokens.every(x => this.tokens_to_ids.has(x))) {\n // Ensure the byte tokens are actually in the vocabulary, otherwise\n // we fall back to the unknown token. For more information, see\n // https://github.com/huggingface/transformers/issues/28096.\n outputTokens.push(...byteTokens);\n } else {\n outputTokens.push(this.unk_token);\n }\n } else {\n outputTokens.push(this.unk_token);\n }\n }\n }\n\n return outputTokens;\n }\n\n}\n\n/**\n * Legacy tokenizer class for tokenizers with only a vocabulary.\n */\nclass LegacyTokenizerModel extends TokenizerModel {\n /**\n * Create a LegacyTokenizerModel instance.\n * @param {Object} config The configuration object for LegacyTokenizerModel.\n * @param {Object} config.vocab A (possibly nested) mapping of tokens to ids.\n * @param {Object} moreConfig Additional configuration object for the LegacyTokenizerModel model.\n */\n constructor(config, moreConfig) {\n super(config);\n\n /**@type {Map} */\n this.tokens_to_ids = objectToMap(\n moreConfig.target_lang\n ? config.vocab[moreConfig.target_lang]\n : config.vocab\n );\n\n this.bos_token = moreConfig.bos_token;\n this.bos_token_id = this.tokens_to_ids.get(this.bos_token);\n\n this.eos_token = moreConfig.eos_token;\n this.eos_token_id = this.tokens_to_ids.get(this.eos_token);\n\n this.pad_token = moreConfig.pad_token;\n this.pad_token_id = this.tokens_to_ids.get(this.pad_token);\n\n this.unk_token = moreConfig.unk_token;\n this.unk_token_id = this.tokens_to_ids.get(this.unk_token);\n\n this.vocab = new Array(this.tokens_to_ids.size);\n for (const [key, value] of this.tokens_to_ids) {\n this.vocab[value] = key;\n }\n }\n\n encode(tokens) {\n return tokens;\n }\n}\n\n\n/**\n * A base class for text normalization.\n * @abstract\n */\nclass Normalizer extends Callable {\n /**\n * @param {Object} config The configuration object for the normalizer.\n */\n constructor(config) {\n super();\n this.config = config;\n }\n\n /**\n * Factory method for creating normalizers from config objects.\n * @static\n * @param {Object} config The configuration object for the normalizer.\n * @returns {Normalizer} A Normalizer object.\n * @throws {Error} If an unknown Normalizer type is specified in the config.\n */\n static fromConfig(config) {\n if (config === null) return null;\n switch (config.type) {\n case 'BertNormalizer':\n return new BertNormalizer(config);\n case 'Precompiled':\n return new Precompiled(config);\n case 'Sequence':\n return new NormalizerSequence(config);\n case 'Replace':\n return new Replace(config);\n case 'NFC':\n return new NFC(config);\n case 'NFKC':\n return new NFKC(config);\n case 'NFKD':\n return new NFKD(config);\n case 'Strip':\n return new StripNormalizer(config);\n case 'StripAccents':\n return new StripAccents(config);\n case 'Lowercase':\n return new Lowercase(config);\n case 'Prepend':\n return new Prepend(config);\n default:\n throw new Error(`Unknown Normalizer type: ${config.type}`);\n }\n }\n\n /**\n * Normalize the input text.\n * @abstract\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n * @throws {Error} If this method is not implemented in a subclass.\n */\n normalize(text) {\n throw Error(\"normalize should be implemented in subclass.\")\n }\n\n /**\n * Alias for {@link Normalizer#normalize}.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n _call(text) {\n return this.normalize(text);\n }\n\n}\n\n/**\n * Replace normalizer that replaces occurrences of a pattern with a given string or regular expression.\n * @extends Normalizer\n */\nclass Replace extends Normalizer {\n /**\n * Normalize the input text by replacing the pattern with the content.\n * @param {string} text The input text to be normalized.\n * @returns {string} The normalized text after replacing the pattern with the content.\n */\n normalize(text) {\n const pattern = createPattern(this.config.pattern);\n return pattern === null\n ? text\n : text.replaceAll(pattern, this.config.content);\n }\n}\n\n/**\n * A normalizer that applies Unicode normalization form C (NFC) to the input text.\n * @extends Normalizer\n */\nclass NFC extends Normalizer {\n /**\n * Normalize the input text by applying Unicode normalization form C (NFC).\n * @param {string} text The input text to be normalized.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = text.normalize('NFC')\n return text;\n }\n}\n\n/**\n * NFKC Normalizer.\n * @extends Normalizer\n */\nclass NFKC extends Normalizer {\n /**\n * Normalize text using NFKC normalization.\n * @param {string} text The text to be normalized.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = text.normalize('NFKC')\n return text;\n }\n}\n/**\n * NFKD Normalizer.\n * @extends Normalizer\n */\nclass NFKD extends Normalizer {\n /**\n * Normalize text using NFKD normalization.\n * @param {string} text The text to be normalized.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = text.normalize('NFKD')\n return text;\n }\n}\n\n/**\n * A normalizer that strips leading and/or trailing whitespace from the input text.\n */\nclass StripNormalizer extends Normalizer {\n /**\n * Strip leading and/or trailing whitespace from the input text.\n * @param {string} text The input text.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n if (this.config.strip_left && this.config.strip_right) {\n // Fast path to avoid an extra trim call\n text = text.trim();\n } else {\n if (this.config.strip_left) {\n text = text.trimStart();\n }\n if (this.config.strip_right) {\n text = text.trimEnd();\n }\n }\n return text;\n }\n}\n\n/**\n * StripAccents normalizer removes all accents from the text.\n * @extends Normalizer\n */\nclass StripAccents extends Normalizer {\n /**\n * Remove all accents from the text.\n * @param {string} text The input text.\n * @returns {string} The normalized text without accents.\n */\n normalize(text) {\n text = remove_accents(text);\n return text;\n }\n}\n\n/**\n * A Normalizer that lowercases the input string.\n * @extends Normalizer\n */\nclass Lowercase extends Normalizer {\n /**\n * Lowercases the input string.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = text.toLowerCase();\n return text;\n }\n}\n\n/**\n * A Normalizer that prepends a string to the input string.\n * @extends Normalizer\n */\nclass Prepend extends Normalizer {\n /**\n * Prepends the input string.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = this.config.prepend + text;\n return text;\n }\n}\n\n/**\n * A Normalizer that applies a sequence of Normalizers.\n * @extends Normalizer\n */\nclass NormalizerSequence extends Normalizer {\n /**\n * Create a new instance of NormalizerSequence.\n * @param {Object} config The configuration object.\n * @param {Object[]} config.normalizers An array of Normalizer configuration objects.\n */\n constructor(config) {\n super(config);\n this.normalizers = config.normalizers.map(x => Normalizer.fromConfig(x));\n }\n /**\n * Apply a sequence of Normalizers to the input text.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n return this.normalizers.reduce((t, normalizer) => {\n return normalizer.normalize(t);\n }, text);\n }\n}\n\n/**\n * A class representing a normalizer used in BERT tokenization.\n * @extends Normalizer\n */\nclass BertNormalizer extends Normalizer {\n /**\n * Adds whitespace around any CJK (Chinese, Japanese, or Korean) character in the input text.\n *\n * @param {string} text The input text to tokenize.\n * @returns {string} The tokenized text with whitespace added around CJK characters.\n */\n _tokenize_chinese_chars(text) {\n /* Adds whitespace around any CJK character. */\n const output = [];\n for (let i = 0; i < text.length; ++i) {\n const char = text[i];\n const cp = char.charCodeAt(0);\n if (is_chinese_char(cp)) {\n output.push(\" \");\n output.push(char);\n output.push(\" \");\n } else {\n output.push(char);\n }\n }\n return output.join(\"\");\n }\n\n /**\n * Strips accents from the given text.\n * @param {string} text The text to strip accents from.\n * @returns {string} The text with accents removed.\n */\n stripAccents(text) {\n // \"Mark, Nonspacing\" (Mn)\n return text.normalize('NFD').replace(/\\p{Mn}/gu, '');\n }\n\n\n /**\n * Checks whether `char` is a control character.\n * @param {string} char The character to check.\n * @returns {boolean} Whether `char` is a control character.\n * @private\n */\n _is_control(char) {\n switch (char) {\n case '\\t':\n case '\\n':\n case '\\r':\n // These are technically control characters but we count them as whitespace characters.\n return false;\n\n default:\n // Check if unicode category starts with C:\n // Cc - Control\n // Cf - Format\n // Co - Private Use\n // Cs - Surrogate\n return /^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$/u.test(char);\n }\n }\n\n /**\n * Performs invalid character removal and whitespace cleanup on text.\n * @param {string} text The text to clean.\n * @returns {string} The cleaned text.\n * @private\n */\n _clean_text(text) {\n const output = [];\n for (const char of text) {\n const cp = char.charCodeAt(0);\n if (cp === 0 || cp === 0xFFFD || this._is_control(char)) {\n continue;\n }\n if (/^\\s$/.test(char)) { // is whitespace\n output.push(\" \");\n } else {\n output.push(char);\n }\n }\n return output.join(\"\");\n }\n /**\n * Normalizes the given text based on the configuration.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n if (this.config.clean_text) {\n text = this._clean_text(text);\n }\n\n if (this.config.handle_chinese_chars) {\n text = this._tokenize_chinese_chars(text);\n }\n\n if (this.config.lowercase) {\n text = text.toLowerCase();\n\n if (this.config.strip_accents !== false) {\n text = this.stripAccents(text);\n }\n } else if (this.config.strip_accents) {\n text = this.stripAccents(text);\n }\n\n return text;\n }\n}\n\n/**\n * A callable class representing a pre-tokenizer used in tokenization. Subclasses\n * should implement the `pre_tokenize_text` method to define the specific pre-tokenization logic.\n * @extends Callable\n */\nclass PreTokenizer extends Callable {\n /**\n * Factory method that returns an instance of a subclass of `PreTokenizer` based on the provided configuration.\n *\n * @static\n * @param {Object} config A configuration object for the pre-tokenizer.\n * @returns {PreTokenizer} An instance of a subclass of `PreTokenizer`.\n * @throws {Error} If the provided configuration object does not correspond to any known pre-tokenizer.\n */\n static fromConfig(config) {\n if (config === null) return null;\n\n switch (config.type) {\n case 'BertPreTokenizer':\n return new BertPreTokenizer(config);\n case 'Sequence':\n return new PreTokenizerSequence(config);\n case 'Whitespace':\n return new WhitespacePreTokenizer(config);\n case 'WhitespaceSplit':\n return new WhitespaceSplit(config);\n case 'Metaspace':\n return new MetaspacePreTokenizer(config);\n\n case 'ByteLevel':\n return new ByteLevelPreTokenizer(config);\n case 'Split':\n return new SplitPreTokenizer(config);\n case 'Punctuation':\n return new PunctuationPreTokenizer(config);\n case 'Digits':\n return new DigitsPreTokenizer(config);\n case 'Replace':\n return new ReplacePreTokenizer(config);\n default:\n throw new Error(`Unknown PreTokenizer type: ${config.type}`);\n }\n }\n\n /**\n * Method that should be implemented by subclasses to define the specific pre-tokenization logic.\n *\n * @abstract\n * @param {string} text The text to pre-tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} The pre-tokenized text.\n * @throws {Error} If the method is not implemented in the subclass.\n */\n pre_tokenize_text(text, options) {\n throw Error(\"pre_tokenize_text should be implemented in subclass.\")\n }\n\n /**\n * Tokenizes the given text into pre-tokens.\n * @param {string|string[]} text The text or array of texts to pre-tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of pre-tokens.\n */\n pre_tokenize(text, options) {\n return (Array.isArray(text)\n ? text.map(x => this.pre_tokenize_text(x, options))\n : this.pre_tokenize_text(text, options)\n ).flat();\n }\n\n /**\n * Alias for {@link PreTokenizer#pre_tokenize}.\n * @param {string|string[]} text The text or array of texts to pre-tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of pre-tokens.\n */\n _call(text, options) {\n return this.pre_tokenize(text, options);\n }\n}\n\n/**\n * @extends PreTokenizer\n */\nclass BertPreTokenizer extends PreTokenizer {\n /**\n * A PreTokenizer that splits text into wordpieces using a basic tokenization scheme\n * similar to that used in the original implementation of BERT.\n * \n * @param {Object} config The configuration object.\n */\n constructor(config) {\n super();\n // Construct a pattern which matches the rust implementation:\n // https://github.com/huggingface/tokenizers/blob/b4fcc9ce6e4ad5806e82826f816acfdfdc4fcc67/tokenizers/src/pre_tokenizers/bert.rs#L11\n // Equivalent to removing whitespace and splitting on punctuation (both \\p{P} and other ascii characters)\n this.pattern = new RegExp(`[^\\\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`, 'gu');\n }\n /**\n * Tokenizes a single text using the BERT pre-tokenization scheme.\n * \n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n return text.trim().match(this.pattern) || [];\n }\n}\n\n/**\n * A pre-tokenizer that splits text into Byte-Pair-Encoding (BPE) subwords.\n * @extends PreTokenizer\n */\nclass ByteLevelPreTokenizer extends PreTokenizer {\n /**\n * Creates a new instance of the `ByteLevelPreTokenizer` class.\n * @param {Object} config The configuration object.\n */\n constructor(config) {\n super();\n this.config = config;\n\n /**\n * @type {boolean} Whether to add a leading space to the first word.\n * This allows to treat the leading word just as any other word.\n */\n this.add_prefix_space = this.config.add_prefix_space;\n\n /**\n * @type {boolean} Whether the post processing step should trim offsets\n * to avoid including whitespaces.\n * @todo Use this in the pretokenization step.\n */\n this.trim_offsets = this.config.trim_offsets;\n\n /**\n * @type {boolean} Whether to use the standard GPT2 regex for whitespace splitting.\n * Set it to False if you want to use your own splitting. Defaults to true.\n */\n this.use_regex = this.config.use_regex ?? true;\n this.pattern = /'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+/gu;\n\n this.byte_encoder = BYTES_TO_UNICODE;\n this.text_encoder = new TextEncoder();\n }\n\n /**\n * Tokenizes a single piece of text using byte-level tokenization.\n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n // Add a leading space if the option is enabled\n if (this.add_prefix_space && !text.startsWith(' ')) {\n text = ' ' + text;\n }\n\n // Split on whitespace and punctuation\n const tokens = this.use_regex ? (text.match(this.pattern) || []) : [text];\n\n // Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)\n return tokens.map(\n token => Array.from(this.text_encoder.encode(token), byte => this.byte_encoder[byte]).join('')\n );\n }\n}\n\n/**\n * @typedef {'removed'|'isolated'|'mergedWithPrevious'|'mergedWithNext'|'contiguous'} SplitDelimiterBehavior\n */\n\n/**\n * Splits text using a given pattern.\n * @extends PreTokenizer\n */\nclass SplitPreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration options for the pre-tokenizer.\n * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.\n * @param {string|undefined} config.pattern.String The string to use for splitting. Only defined if the pattern is a string.\n * @param {string|undefined} config.pattern.Regex The regex to use for splitting. Only defined if the pattern is a regex.\n * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.\n * @param {boolean} config.invert Whether to split (invert=false) or match (invert=true) the pattern.\n */\n constructor(config) {\n super();\n this.config = config;\n // TODO support all behaviours (config.behavior)\n\n this.pattern = createPattern(this.config.pattern, this.config.invert);\n }\n\n /**\n * Tokenizes text by splitting it using the given pattern.\n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n if (this.pattern === null) {\n return [];\n }\n\n if (this.config.invert) {\n return text.match(this.pattern) || [];\n } else {\n return regexSplit(text, this.pattern);\n }\n }\n}\n\n/**\n * Splits text based on punctuation.\n * @extends PreTokenizer\n */\nclass PunctuationPreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration options for the pre-tokenizer.\n * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.\n */\n constructor(config) {\n super();\n this.config = config;\n this.pattern = new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`, 'gu');\n }\n\n /**\n * Tokenizes text by splitting it using the given pattern.\n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n return text.match(this.pattern) || [];\n }\n}\n\n\n/**\n * Splits text based on digits.\n * @extends PreTokenizer\n */\nclass DigitsPreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration options for the pre-tokenizer.\n * @param {boolean} config.individual_digits Whether to split on individual digits.\n */\n constructor(config) {\n super();\n this.config = config;\n\n // Construct a pattern which matches the rust implementation:\n const digit_pattern = `[^\\\\d]+|\\\\d${this.config.individual_digits ? '' : '+'}`;\n this.pattern = new RegExp(digit_pattern, 'gu');\n }\n\n /**\n * Tokenizes text by splitting it using the given pattern.\n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n return text.match(this.pattern) || [];\n }\n}\n\n/**\n * @typedef {Object} PostProcessedOutput\n * @property {string[]} tokens List of token produced by the post-processor.\n * @property {number[]} [token_type_ids] List of token type ids produced by the post-processor.\n */\n\n\n/**\n * @typedef {Object} EncodingSingle\n * @property {number[]} input_ids List of token ids to be fed to a model.\n * @property {number[]} attention_mask List of token type ids to be fed to a model\n * @property {number[]} [token_type_ids] List of indices specifying which tokens should be attended to by the model\n */\n\n\n/**\n * @extends Callable\n */\nclass PostProcessor extends Callable {\n\n /**\n * @param {Object} config The configuration for the post-processor.\n */\n constructor(config) {\n super();\n this.config = config;\n }\n\n /**\n * Factory method to create a PostProcessor object from a configuration object.\n *\n * @param {Object} config Configuration object representing a PostProcessor.\n * @returns {PostProcessor} A PostProcessor object created from the given configuration.\n * @throws {Error} If an unknown PostProcessor type is encountered.\n */\n static fromConfig(config) {\n if (config === null) return null;\n switch (config.type) {\n case 'TemplateProcessing':\n return new TemplateProcessing(config);\n\n case 'ByteLevel':\n return new ByteLevelPostProcessor(config);\n\n case 'RobertaProcessing':\n return new RobertaProcessing(config);\n case 'BertProcessing':\n return new BertProcessing(config);\n\n case 'Sequence':\n return new PostProcessorSequence(config);\n default:\n throw new Error(`Unknown PostProcessor type: ${config.type}`);\n }\n }\n\n /**\n * Method to be implemented in subclass to apply post-processing on the given tokens.\n *\n * @param {Array} tokens The input tokens to be post-processed.\n * @param {...*} args Additional arguments required by the post-processing logic.\n * @returns {PostProcessedOutput} The post-processed tokens.\n * @throws {Error} If the method is not implemented in subclass.\n */\n post_process(tokens, ...args) {\n throw Error(\"post_process should be implemented in subclass.\")\n }\n\n /**\n * Alias for {@link PostProcessor#post_process}.\n * @param {Array} tokens The text or array of texts to post-process.\n * @param {...*} args Additional arguments required by the post-processing logic.\n * @returns {PostProcessedOutput} The post-processed tokens.\n */\n _call(tokens, ...args) {\n return this.post_process(tokens, ...args);\n }\n}\n\n/**\n * A post-processor that adds special tokens to the beginning and end of the input.\n */\nclass BertProcessing extends PostProcessor {\n /**\n * @param {Object} config The configuration for the post-processor.\n * @param {string[]} config.cls The special tokens to add to the beginning of the input.\n * @param {string[]} config.sep The special tokens to add to the end of the input.\n */\n constructor(config) {\n super(config);\n // TODO use all of config: add_prefix_space, trim_offsets\n\n this.cls = config.cls[0];\n this.sep = config.sep[0];\n }\n\n /**\n * Adds the special tokens to the beginning and end of the input.\n * @param {string[]} tokens The input tokens.\n * @param {string[]} [tokens_pair=null] An optional second set of input tokens.\n * @returns {PostProcessedOutput} The post-processed tokens with the special tokens added to the beginning and end.\n */\n post_process(tokens, tokens_pair = null, {\n add_special_tokens = true,\n } = {}) {\n if (add_special_tokens) {\n tokens = mergeArrays([this.cls], tokens, [this.sep]);\n }\n\n let token_type_ids = new Array(tokens.length).fill(0);\n if (tokens_pair !== null) {\n // NOTE: It is intended to add 2 EOS tokens after the first set of tokens\n // https://github.com/huggingface/tokenizers/issues/983\n const middle = (add_special_tokens && this instanceof RobertaProcessing)\n ? [this.sep]\n : [];\n const after = add_special_tokens ? [this.sep] : [];\n\n tokens = mergeArrays(tokens, middle, tokens_pair, after);\n token_type_ids = mergeArrays(token_type_ids, new Array(tokens_pair.length + middle.length + after.length).fill(1));\n }\n return { tokens, token_type_ids };\n }\n}\nclass RobertaProcessing extends BertProcessing { } // NOTE: extends BertProcessing\n\n/**\n * Post processor that replaces special tokens in a template with actual tokens.\n * @extends PostProcessor\n */\nclass TemplateProcessing extends PostProcessor {\n /**\n * Creates a new instance of `TemplateProcessing`.\n * @param {Object} config The configuration options for the post processor.\n * @param {Array} config.single The template for a single sequence of tokens.\n * @param {Array} config.pair The template for a pair of sequences of tokens.\n */\n constructor(config) {\n super(config);\n\n this.single = config.single;\n this.pair = config.pair;\n }\n\n /**\n * Replaces special tokens in the template with actual tokens.\n * @param {string[]} tokens The list of tokens for the first sequence.\n * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).\n * @returns {PostProcessedOutput} An object containing the list of tokens with the special tokens replaced with actual tokens.\n */\n post_process(tokens, tokens_pair = null, {\n add_special_tokens = true,\n } = {}) {\n const type = tokens_pair === null ? this.single : this.pair\n\n let processedTokens = [];\n let types = [];\n for (const item of type) {\n if ('SpecialToken' in item) {\n if (add_special_tokens) {\n processedTokens.push(item.SpecialToken.id);\n types.push(item.SpecialToken.type_id);\n }\n } else if ('Sequence' in item) {\n if (item.Sequence.id === 'A') {\n processedTokens = mergeArrays(processedTokens, tokens);\n types = mergeArrays(types, new Array(tokens.length).fill(item.Sequence.type_id));\n\n } else if (item.Sequence.id === 'B') {\n processedTokens = mergeArrays(processedTokens, tokens_pair);\n types = mergeArrays(types, new Array(tokens_pair.length).fill(item.Sequence.type_id));\n }\n }\n }\n return { tokens: processedTokens, token_type_ids: types };\n }\n}\n\n/**\n * A PostProcessor that returns the given tokens as is.\n * @extends PostProcessor\n */\nclass ByteLevelPostProcessor extends PostProcessor {\n /**\n * Post process the given tokens.\n * @param {string[]} tokens The list of tokens for the first sequence.\n * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).\n * @returns {PostProcessedOutput} An object containing the post-processed tokens.\n */\n post_process(tokens, tokens_pair = null) {\n if (tokens_pair) {\n tokens = mergeArrays(tokens, tokens_pair);\n }\n return { tokens };\n }\n}\n\n\n/**\n * A post-processor that applies multiple post-processors in sequence.\n */\nclass PostProcessorSequence extends PostProcessor {\n\n /**\n * Creates a new instance of PostProcessorSequence.\n * @param {Object} config The configuration object.\n * @param {Object[]} config.processors The list of post-processors to apply.\n */\n constructor(config) {\n super(config);\n\n this.processors = config.processors.map(x => PostProcessor.fromConfig(x));\n }\n\n /**\n * Post process the given tokens.\n * @param {string[]} tokens The list of tokens for the first sequence.\n * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).\n * @returns {PostProcessedOutput} An object containing the post-processed tokens.\n */\n post_process(tokens, tokens_pair = null, options = {}) {\n let token_type_ids;\n for (const processor of this.processors) {\n if (processor instanceof ByteLevelPostProcessor) {\n // Special case where we need to pass the tokens_pair to the post-processor\n const output = processor.post_process(tokens);\n tokens = output.tokens;\n if (tokens_pair) {\n const pair_output = processor.post_process(tokens_pair);\n tokens_pair = pair_output.tokens;\n }\n } else {\n const output = processor.post_process(tokens, tokens_pair, options);\n tokens = output.tokens;\n token_type_ids = output.token_type_ids;\n }\n }\n return { tokens, token_type_ids };\n }\n}\n\n/**\n * The base class for token decoders.\n * @extends Callable\n */\nclass Decoder extends Callable {\n\n /**\n * Creates an instance of `Decoder`.\n *\n * @param {Object} config The configuration object.\n */\n constructor(config) {\n super();\n this.config = config;\n\n /** @type {AddedToken[]} */\n this.added_tokens = [];\n this.end_of_word_suffix = null;\n this.trim_offsets = config.trim_offsets;\n }\n\n /**\n * Creates a decoder instance based on the provided configuration.\n *\n * @param {Object} config The configuration object.\n * @returns {Decoder} A decoder instance.\n * @throws {Error} If an unknown decoder type is provided.\n */\n static fromConfig(config) {\n if (config === null) return null;\n switch (config.type) {\n case 'WordPiece':\n return new WordPieceDecoder(config);\n case 'Metaspace':\n return new MetaspaceDecoder(config);\n case 'ByteLevel':\n return new ByteLevelDecoder(config);\n\n case 'Replace':\n return new ReplaceDecoder(config);\n case 'ByteFallback':\n return new ByteFallback(config);\n case 'Fuse':\n return new FuseDecoder(config);\n case 'Strip':\n return new StripDecoder(config);\n\n case 'Sequence':\n return new DecoderSequence(config);\n\n case 'CTC':\n return new CTCDecoder(config);\n case 'BPEDecoder':\n return new BPEDecoder(config);\n default:\n throw new Error(`Unknown Decoder type: ${config.type}`);\n }\n }\n\n /**\n * Calls the `decode` method.\n *\n * @param {string[]} tokens The list of tokens.\n * @returns {string} The decoded string.\n */\n _call(tokens) {\n return this.decode(tokens);\n }\n\n /**\n * Decodes a list of tokens.\n * @param {string[]} tokens The list of tokens.\n * @returns {string} The decoded string.\n */\n decode(tokens) {\n return this.decode_chain(tokens).join('');\n }\n\n /**\n * Apply the decoder to a list of tokens.\n * \n * @param {string[]} tokens The list of tokens.\n * @returns {string[]} The decoded list of tokens.\n * @throws {Error} If the `decode_chain` method is not implemented in the subclass.\n */\n decode_chain(tokens) {\n throw Error(\"`decode_chain` should be implemented in subclass.\")\n }\n\n}\n\nclass ReplaceDecoder extends Decoder {\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n const pattern = createPattern(this.config.pattern);\n return pattern === null\n ? tokens\n : tokens.map(token => token.replaceAll(pattern, this.config.content))\n }\n}\n\n\nclass ByteFallback extends Decoder {\n constructor(config) {\n super(config);\n\n this.text_decoder = new TextDecoder();\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n\n const new_tokens = [];\n let previous_byte_tokens = [];\n\n for (const token of tokens) {\n let bytes = null;\n if (token.length === 6 && token.startsWith('<0x') && token.endsWith('>')) {\n const byte = parseInt(token.slice(3, 5), 16);\n if (!isNaN(byte)) {\n bytes = byte;\n }\n }\n if (bytes !== null) {\n previous_byte_tokens.push(bytes);\n } else {\n if (previous_byte_tokens.length > 0) {\n const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));\n new_tokens.push(string);\n previous_byte_tokens = [];\n }\n new_tokens.push(token);\n }\n }\n if (previous_byte_tokens.length > 0) {\n const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));\n new_tokens.push(string);\n previous_byte_tokens = [];\n }\n\n return new_tokens;\n }\n}\n\n/**\n * Fuse simply fuses all tokens into one big string.\n * It's usually the last decoding step anyway, but this decoder\n * exists incase some decoders need to happen after that step\n */\nclass FuseDecoder extends Decoder {\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return [tokens.join('')];\n }\n}\n\n\nclass StripDecoder extends Decoder {\n constructor(config) {\n super(config);\n\n this.content = this.config.content;\n this.start = this.config.start;\n this.stop = this.config.stop;\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return tokens.map(token => {\n let start_cut = 0;\n for (let i = 0; i < this.start; ++i) {\n if (token[i] === this.content) {\n start_cut = i + 1;\n continue;\n } else {\n break;\n }\n }\n\n let stop_cut = token.length;\n for (let i = 0; i < this.stop; ++i) {\n const index = token.length - i - 1;\n if (token[index] === this.content) {\n stop_cut = index;\n continue;\n } else {\n break;\n }\n }\n\n return token.slice(start_cut, stop_cut)\n });\n }\n}\n\n/**\n * A decoder that decodes a list of WordPiece tokens into a single string.\n * @extends Decoder\n */\nclass WordPieceDecoder extends Decoder {\n\n /**\n * Creates a new instance of WordPieceDecoder.\n * @param {Object} config The configuration object.\n * @param {string} config.prefix The prefix used for WordPiece encoding.\n * @param {boolean} config.cleanup Whether to cleanup the decoded string.\n */\n constructor(config) {\n super(config);\n this.cleanup = config.cleanup;\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return tokens.map((token, i) => {\n if (i !== 0) {\n if (token.startsWith(this.config.prefix)) {\n // NOTE: .replace() is intended; only replace first occurrence\n token = token.replace(this.config.prefix, '');\n } else {\n token = ' ' + token;\n }\n }\n if (this.cleanup) {\n token = clean_up_tokenization(token)\n }\n\n return token;\n });\n }\n}\n\n/**\n * Byte-level decoder for tokenization output. Inherits from the `Decoder` class.\n * @extends Decoder\n */\nclass ByteLevelDecoder extends Decoder {\n\n /**\n * Create a `ByteLevelDecoder` object.\n * @param {Object} config Configuration object.\n */\n constructor(config) {\n super(config);\n\n this.byte_decoder = UNICODE_TO_BYTES;\n this.text_decoder = new TextDecoder(\"utf-8\", {\n fatal: false,\n ignoreBOM: true,\n });\n\n this.end_of_word_suffix = null;\n }\n\n /**\n * Convert an array of tokens to string by decoding each byte.\n * @param {string[]} tokens Array of tokens to be decoded.\n * @returns {string} The decoded string.\n */\n convert_tokens_to_string(tokens) {\n const text = tokens.join('');\n const byteArray = new Uint8Array([...text].map(c => this.byte_decoder[c]));\n const decoded_text = this.text_decoder.decode(byteArray);\n return decoded_text;\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n // TODO move to base class (like HF)\n // tokens === filtered_tokens\n\n // To avoid mixing byte-level and unicode for byte-level BPT\n // we need to build string separately for added tokens and byte-level tokens\n // cf. https://github.com/huggingface/transformers/issues/1133\n const sub_texts = [];\n let current_sub_text = [];\n for (const token of tokens) {\n // tokens sent here are already filtered, so we don't need to do this\n // if (skip_special_tokens && this.all_special_ids.includes(token)) {\n // continue;\n // }\n\n if (this.added_tokens.find(x => x.content === token) !== undefined) {\n if (current_sub_text.length > 0) {\n sub_texts.push(this.convert_tokens_to_string(current_sub_text));\n current_sub_text = [];\n }\n sub_texts.push(token);\n } else {\n current_sub_text.push(token);\n }\n }\n if (current_sub_text.length > 0) {\n sub_texts.push(this.convert_tokens_to_string(current_sub_text));\n }\n\n // TODO add spaces_between_special_tokens and clean_up_tokenization_spaces options\n\n return sub_texts;\n }\n}\n\n/**\n * The CTC (Connectionist Temporal Classification) decoder.\n * See https://github.com/huggingface/tokenizers/blob/bb38f390a61883fc2f29d659af696f428d1cda6b/tokenizers/src/decoders/ctc.rs\n */\nclass CTCDecoder extends Decoder {\n\n constructor(config) {\n super(config);\n\n this.pad_token = this.config.pad_token;\n this.word_delimiter_token = this.config.word_delimiter_token;\n this.cleanup = this.config.cleanup;\n }\n /**\n * Converts a connectionist-temporal-classification (CTC) output tokens into a single string.\n * @param {string[]} tokens Array of tokens to be decoded.\n * @returns {string} The decoded string.\n */\n convert_tokens_to_string(tokens) {\n if (tokens.length === 0) return '';\n\n // group same tokens into non-repeating tokens in CTC style decoding\n const grouped_tokens = [tokens[0]];\n for (let i = 1; i < tokens.length; ++i) {\n if (tokens[i] !== grouped_tokens.at(-1)) {\n grouped_tokens.push(tokens[i]);\n }\n }\n\n // filter self.pad_token which is used as CTC-blank token\n const filtered_tokens = grouped_tokens.filter(token => token !== this.pad_token);\n\n let text = filtered_tokens.join('');\n if (this.cleanup) {\n // cleanup and replace delimiter token\n text = clean_up_tokenization(text)\n .replaceAll(this.word_delimiter_token, ' ')\n .trim();\n }\n return text;\n }\n\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return [this.convert_tokens_to_string(tokens)];\n }\n}\n\n/**\n * Apply a sequence of decoders.\n * @extends Decoder\n */\nclass DecoderSequence extends Decoder {\n\n /**\n * Creates a new instance of DecoderSequence.\n * @param {Object} config The configuration object.\n * @param {Object[]} config.decoders The list of decoders to apply.\n */\n constructor(config) {\n super(config);\n this.decoders = config.decoders.map(x => Decoder.fromConfig(x));\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n // Use reduce to apply each decoder to the tokens\n return this.decoders.reduce((toks, decoder) => {\n return decoder.decode_chain(toks);\n }, tokens);\n }\n\n}\n\nclass BPEDecoder extends Decoder {\n constructor(config) {\n super(config);\n\n this.suffix = this.config.suffix;\n }\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return tokens.map((token, i) => {\n return token.replaceAll(this.suffix, (i === tokens.length - 1) ? '' : ' ')\n });\n }\n}\n\n// Custom decoder for VITS\nclass VitsDecoder extends Decoder {\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n let decoded = '';\n for (let i = 1; i < tokens.length; i += 2) {\n decoded += tokens[i];\n }\n return [decoded];\n }\n}\n\n\n/**\n * This PreTokenizer replaces spaces with the given replacement character, adds a prefix space if requested,\n * and returns a list of tokens.\n * @extends PreTokenizer\n */\nclass MetaspacePreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration object for the MetaspacePreTokenizer.\n * @param {boolean} config.add_prefix_space Whether to add a prefix space to the first token.\n * @param {string} config.replacement The character to replace spaces with.\n * @param {string} [config.str_rep=config.replacement] An optional string representation of the replacement character.\n * @param {'first'|'never'|'always'} [config.prepend_scheme='always'] The metaspace prepending scheme.\n */\n constructor(config) {\n super();\n\n this.addPrefixSpace = config.add_prefix_space;\n this.replacement = config.replacement;\n this.strRep = config.str_rep || this.replacement;\n this.prepend_scheme = config.prepend_scheme ?? 'always';\n }\n\n /**\n * This method takes a string, replaces spaces with the replacement character,\n * adds a prefix space if requested, and returns a new list of tokens.\n * @param {string} text The text to pre-tokenize.\n * @param {Object} [options] The options for the pre-tokenization.\n * @param {number} [options.section_index] The index of the section to pre-tokenize.\n * @returns {string[]} A new list of pre-tokenized tokens.\n */\n pre_tokenize_text(text, {\n section_index = undefined,\n } = {}) {\n\n let normalized = text.replaceAll(' ', this.strRep);\n\n if (\n // We add a prefix space if:\n // (1) The addPrefixSpace option is enabled and the normalized\n // token does not already start with the replacement character.\n (this.addPrefixSpace && !normalized.startsWith(this.replacement))\n\n // and (2) either:\n // (a) prepend_scheme is 'always'\n // (b) prepend_scheme is 'first' and this is the first section\n && (\n this.prepend_scheme === 'always' ||\n (this.prepend_scheme === 'first' && section_index === 0)\n )\n ) {\n normalized = this.strRep + normalized;\n }\n return [normalized];\n }\n}\n\n/**\n * MetaspaceDecoder class extends the Decoder class and decodes Metaspace tokenization.\n * @extends Decoder\n */\nclass MetaspaceDecoder extends Decoder {\n /**\n * Constructs a new MetaspaceDecoder object.\n * @param {Object} config The configuration object for the MetaspaceDecoder.\n * @param {boolean} config.add_prefix_space Whether to add a prefix space to the decoded string.\n * @param {string} config.replacement The string to replace spaces with.\n */\n constructor(config) {\n super(config);\n\n this.addPrefixSpace = config.add_prefix_space;\n this.replacement = config.replacement;\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n const result = [];\n for (let i = 0; i < tokens.length; ++i) {\n let normalized = tokens[i].replaceAll(this.replacement, ' ');\n if (this.addPrefixSpace && i == 0 && normalized.startsWith(' ')) {\n normalized = normalized.substring(1);\n }\n result.push(normalized);\n }\n return result;\n }\n}\n\n/**\n * A normalizer that applies a precompiled charsmap.\n * This is useful for applying complex normalizations in C++ and exposing them to JavaScript.\n * @extends Normalizer\n * @param {Object} config The configuration object for the Precompiled normalizer.\n * @param {Object} config.precompiled_charsmap The precompiled charsmap object.\n */\nclass Precompiled extends Normalizer {\n /**\n * Create a new instance of Precompiled normalizer.\n * @param {Object} config The configuration object.\n * @param {any} config.precompiled_charsmap Precompiled chars mapping.\n */\n constructor(config) {\n super(config);\n this.charsmap = config.precompiled_charsmap;\n }\n\n /**\n * Normalizes the given text by applying the precompiled charsmap.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n // As stated in the sentencepiece normalization docs (https://github.com/google/sentencepiece/blob/master/doc/normalization.md#use-pre-defined-normalization-rule),\n // there are 5 pre-defined normalization rules:\n // 1. nmt_nfkc: NFKC normalization with some additional normalization around spaces. (default)\n // 2. nfkc: original NFKC normalization.\n // 3. nmt_nfkc_cf: nmt_nfkc + Unicode case folding (mostly lower casing)\n // 4. nfkc_cf: nfkc + Unicode case folding.\n // 5. identity: no normalization\n // \n // For now, we only implement the default (nmt_nfkc).\n // See https://raw.githubusercontent.com/google/sentencepiece/master/data/nmt_nfkc.tsv for the full list of rules.\n // TODO: detect when a different `this.charsmap` is used.\n\n text = text.replace(/[\\u0001-\\u0008\\u000B\\u000E-\\u001F\\u007F\\u008F\\u009F]/gm, ''); // Remove control characters\n text = text.replace(/[\\u0009\\u000A\\u000C\\u000D\\u00A0\\u1680\\u2000-\\u200F\\u2028\\u2029\\u202F\\u205F\\u2581\\u3000\\uFEFF\\uFFFD]/gm, '\\u0020'); // Replace certain characters with a space\n\n if (text.includes('\\uFF5E')) {\n // To match the sentencepiece implementation 100%, we must handle a very strange edge-case.\n // For some reason, the \"Fullwidth Tilde\" character (\\uFF5E) should not be converted to the standard Tilde character (\\u007E).\n // However, NFKC normalization does do this conversion. As a result, we split the string on the Fullwidth Tilde character,\n // perform NFKC normalization on each substring, and then join them back together with the Fullwidth Tilde character.\n const parts = text.split('\\uFF5E');\n text = parts.map(part => part.normalize('NFKC')).join('\\uFF5E');\n } else {\n text = text.normalize('NFKC');\n }\n\n return text;\n }\n}\n\n/**\n * A pre-tokenizer that applies a sequence of pre-tokenizers to the input text.\n * @extends PreTokenizer\n */\nclass PreTokenizerSequence extends PreTokenizer {\n /**\n * Creates an instance of PreTokenizerSequence.\n * @param {Object} config The configuration object for the pre-tokenizer sequence.\n * @param {Object[]} config.pretokenizers An array of pre-tokenizer configurations.\n */\n constructor(config) {\n super();\n this.tokenizers = config.pretokenizers.map(x => PreTokenizer.fromConfig(x));\n }\n\n /**\n * Applies each pre-tokenizer in the sequence to the input text in turn.\n * @param {string} text The text to pre-tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} The pre-tokenized text.\n */\n pre_tokenize_text(text, options) {\n // Use reduce to apply each tokenizer to the text\n return this.tokenizers.reduce((preTokenizedText, tokenizer) => {\n return tokenizer.pre_tokenize(preTokenizedText, options);\n }, [text]);\n }\n}\n\n/**\n * Splits on word boundaries (using the following regular expression: `\\w+|[^\\w\\s]+`).\n */\nclass WhitespacePreTokenizer extends PreTokenizer {\n /**\n * Creates an instance of WhitespacePreTokenizer.\n * @param {Object} config The configuration object for the pre-tokenizer.\n */\n constructor(config) {\n super();\n }\n /**\n * Pre-tokenizes the input text by splitting it on word boundaries.\n * @param {string} text The text to be pre-tokenized.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.\n */\n pre_tokenize_text(text, options) {\n return text.match(/\\w+|[^\\w\\s]+/g) || [];\n }\n}\n\n/**\n * Splits a string of text by whitespace characters into individual tokens.\n * @extends PreTokenizer\n */\nclass WhitespaceSplit extends PreTokenizer {\n /**\n * Creates an instance of WhitespaceSplit.\n * @param {Object} config The configuration object for the pre-tokenizer.\n */\n constructor(config) {\n super();\n }\n /**\n * Pre-tokenizes the input text by splitting it on whitespace characters.\n * @param {string} text The text to be pre-tokenized.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.\n */\n pre_tokenize_text(text, options) {\n return whitespace_split(text);\n }\n}\n\n// NOTE: `ReplacePreTokenizer` is custom (to support `BlenderbotSmallTokenizer`)\nclass ReplacePreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration options for the pre-tokenizer.\n * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.\n * @param {string} config.content What to replace the pattern with.\n */\n constructor(config) {\n super();\n this.config = config;\n this.pattern = createPattern(this.config.pattern);\n this.content = this.config.content;\n }\n\n /**\n * Pre-tokenizes the input text by replacing certain characters.\n * @param {string} text The text to be pre-tokenized.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens produced by replacing certain characters.\n */\n pre_tokenize_text(text, options) {\n if (this.pattern === null) {\n return [text];\n }\n return [text.replaceAll(this.pattern, this.config.content)];\n }\n}\n\nconst SPECIAL_TOKEN_ATTRIBUTES = [\n 'bos_token',\n 'eos_token',\n 'unk_token',\n 'sep_token',\n 'pad_token',\n 'cls_token',\n 'mask_token',\n // additional_special_tokens (TODO)\n]\n\n/**\n * \n * Helper function for padding values of an object, which are each arrays.\n * NOTE: No additional checks are made here for validity of arguments.\n * @param {Record} item The input object.\n * @param {number} length The length to pad to.\n * @param {(key: string) => any} value_fn Determine the value to fill the array, based on its key.\n * @param {string} side Which side to pad the array.\n * @private\n */\nfunction padHelper(item, length, value_fn, side) {\n for (const key of Object.keys(item)) {\n const diff = length - item[key].length;\n const value = value_fn(key);\n\n const padData = new Array(diff).fill(value);\n item[key] = side === 'right'\n ? mergeArrays(item[key], padData)\n : mergeArrays(padData, item[key]);\n }\n}\n\n/**\n * Helper function for truncating values of an object, which are each arrays.\n * NOTE: No additional checks are made here for validity of arguments.\n * @param {Record} item The input object.\n * @param {number} length The length to truncate to.\n * @private\n */\nfunction truncateHelper(item, length) {\n // Setting .length to a lower value truncates the array in-place:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length\n for (const key of Object.keys(item)) {\n item[key].length = length;\n }\n}\n\n\n/**\n * @typedef {Object} Message\n * @property {string} role The role of the message (e.g., \"user\" or \"assistant\" or \"system\").\n * @property {string} content The content of the message.\n */\n\nexport class PreTrainedTokenizer extends Callable {\n return_token_type_ids = false;\n\n padding_side = 'right';\n /**\n * Create a new PreTrainedTokenizer instance.\n * @param {Object} tokenizerJSON The JSON of the tokenizer.\n * @param {Object} tokenizerConfig The config of the tokenizer.\n */\n constructor(tokenizerJSON, tokenizerConfig) {\n super();\n\n this._tokenizer_config = tokenizerConfig;\n\n // Construct parts of the tokenizer from the JSON\n this.normalizer = Normalizer.fromConfig(tokenizerJSON.normalizer);\n this.pre_tokenizer = PreTokenizer.fromConfig(tokenizerJSON.pre_tokenizer);\n this.model = TokenizerModel.fromConfig(tokenizerJSON.model, tokenizerConfig);\n this.post_processor = PostProcessor.fromConfig(tokenizerJSON.post_processor);\n this.decoder = Decoder.fromConfig(tokenizerJSON.decoder);\n\n // Add added_tokens to model\n this.special_tokens = [];\n this.all_special_ids = [];\n\n /** @type {AddedToken[]} */\n this.added_tokens = [];\n for (const addedToken of tokenizerJSON.added_tokens) {\n const token = new AddedToken(addedToken);\n this.added_tokens.push(token);\n\n this.model.tokens_to_ids.set(token.content, token.id);\n this.model.vocab[token.id] = token.content;\n\n if (token.special) {\n this.special_tokens.push(token.content);\n this.all_special_ids.push(token.id);\n }\n }\n\n // Update additional_special_tokens\n this.additional_special_tokens = tokenizerConfig.additional_special_tokens ?? [];\n this.special_tokens.push(...this.additional_special_tokens);\n this.special_tokens = [...new Set(this.special_tokens)]; // Remove duplicates\n\n if (this.decoder) {\n // Slight hack, but it prevents code duplication:\n this.decoder.added_tokens = this.added_tokens;\n\n // Another slight hack to add `end_of_word_suffix` (if present) to the decoder\n // This is needed for cases where BPE model and ByteLevel decoder are used\n // For more information, see https://github.com/huggingface/transformers.js/issues/74\n // TODO: save this to the decoder when exporting?\n this.decoder.end_of_word_suffix = this.model.end_of_word_suffix;\n }\n\n this.added_tokens_regex = this.added_tokens.length > 0 ? new RegExp(\n this.added_tokens.slice()\n // Sort by length (desc) to avoid early partial matches\n .sort((a, b) => b.content.length - a.content.length)\n .map(x => `${x.lstrip ? '\\\\s*' : ''}(${escapeRegExp(x.content)})${x.rstrip ? '\\\\s*' : ''}`)\n .join('|')\n ) : null;\n\n // Set mask token if present (otherwise will be undefined, which is fine)\n this.mask_token = this.getToken('mask_token');\n this.mask_token_id = this.model.tokens_to_ids.get(this.mask_token);\n\n this.pad_token = this.getToken('pad_token', 'eos_token');\n this.pad_token_id = this.model.tokens_to_ids.get(this.pad_token);\n\n this.sep_token = this.getToken('sep_token');\n this.sep_token_id = this.model.tokens_to_ids.get(this.sep_token);\n\n this.unk_token = this.getToken('unk_token');\n this.unk_token_id = this.model.tokens_to_ids.get(this.unk_token);\n\n this.model_max_length = tokenizerConfig.model_max_length;\n\n /** @type {boolean} Whether or not to strip the text when tokenizing (removing excess spaces before and after the string). */\n this.remove_space = tokenizerConfig.remove_space;\n\n this.clean_up_tokenization_spaces = tokenizerConfig.clean_up_tokenization_spaces ?? true;\n this.do_lowercase_and_remove_accent = tokenizerConfig.do_lowercase_and_remove_accent ?? false;\n\n if (tokenizerConfig.padding_side) {\n this.padding_side = tokenizerConfig.padding_side;\n }\n\n this.legacy = false;\n\n this.chat_template = tokenizerConfig.chat_template ?? null;\n if (Array.isArray(this.chat_template)) {\n // Chat templates are stored as lists of dicts with fixed key names,\n // we reconstruct that into a single dict while loading them.\n const chat_template = Object.create(null);\n for (const { name, template } of this.chat_template) {\n if (typeof name !== 'string' || typeof template !== 'string') {\n throw new Error('Chat template must be a list of objects with \"name\" and \"template\" properties');\n }\n chat_template[name] = template;\n }\n this.chat_template = chat_template;\n }\n this._compiled_template_cache = new Map();\n }\n\n /**\n * Returns the value of the first matching key in the tokenizer config object.\n * @param {...string} keys One or more keys to search for in the tokenizer config object.\n * @returns {string|null} The value associated with the first matching key, or null if no match is found.\n * @throws {Error} If an object is found for a matching key and its __type property is not \"AddedToken\".\n * @private\n */\n getToken(...keys) {\n for (const key of keys) {\n const item = this._tokenizer_config[key];\n\n if (!item) continue;\n\n if (typeof item === 'object') {\n if (item.__type === 'AddedToken') {\n return item.content;\n } else {\n throw Error(`Unknown token: ${item}`);\n }\n } else {\n return item;\n }\n }\n return null;\n }\n\n /**\n * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`. \n * \n * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer.\n * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.\n * \n * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`.\n * @returns {Promise} A new instance of the `PreTrainedTokenizer` class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n legacy = null,\n } = {}) {\n\n const info = await loadTokenizer(pretrained_model_name_or_path, {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n legacy,\n })\n\n // @ts-ignore\n return new this(...info);\n }\n\n /**\n * @typedef {number[]|number[][]|Tensor} BatchEncodingItem\n * \n * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function.\n * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model.\n * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model.\n * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model.\n */\n\n /**\n * Encode/tokenize the given text(s).\n * @param {string|string[]} text The text to tokenize.\n * @param {Object} options An optional object containing the following properties:\n * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text.\n * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences.\n * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.\n * @param {boolean} [options.truncation=null] Whether to truncate the input sequences.\n * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length.\n * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays.\n * @param {boolean} [options.return_token_type_ids=null] Whether to return the token type ids.\n * @returns {BatchEncoding} Object to be passed to the model.\n */\n _call(\n // Required positional arguments\n text,\n\n // Optional keyword arguments\n {\n text_pair = null,\n add_special_tokens = true,\n padding = false,\n truncation = null,\n max_length = null,\n return_tensor = true, // Different to HF\n return_token_type_ids = null,\n } = {},\n ) {\n\n const isBatched = Array.isArray(text);\n\n /** @type {EncodingSingle[]} */\n let encodedTokens;\n\n if (isBatched) {\n if (text.length === 0) {\n throw Error('text array must be non-empty')\n }\n\n if (text_pair !== null) {\n if (!Array.isArray(text_pair)) {\n throw Error('text_pair must also be an array')\n\n } else if (text.length !== text_pair.length) {\n throw Error('text and text_pair must have the same length')\n }\n\n encodedTokens = text.map(\n (t, i) => this._encode_plus(t, { text_pair: text_pair[i], add_special_tokens, return_token_type_ids })\n )\n\n } else {\n encodedTokens = text.map(x => this._encode_plus(x, { add_special_tokens, return_token_type_ids }));\n }\n\n } else {\n if (text === null || text === undefined) {\n throw Error('text may not be null or undefined')\n }\n\n if (Array.isArray(text_pair)) {\n throw Error('When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).')\n }\n\n // For single input, we just wrap in an array, and then unwrap later.\n encodedTokens = [this._encode_plus(text, { text_pair, add_special_tokens, return_token_type_ids })];\n }\n // At this point, tokens is batched: [batch_size, tokens]\n // However, array may be jagged. So, we pad to max_length\n\n if (max_length === null) {\n if (padding === 'max_length') {\n max_length = this.model_max_length;\n } else {\n // Calculate max length from sequences\n max_length = max(encodedTokens.map(x => x.input_ids.length))[0];\n }\n } else {\n if (!truncation) {\n console.warn(`Truncation was not explicitly activated but \\`max_length\\` is provided a specific value, please use \\`truncation=true\\` to explicitly truncate examples to max length.`)\n }\n }\n\n // Ensure it is less than model max length\n max_length = Math.min(max_length, this.model_max_length ?? Infinity);\n\n if (padding || truncation) {\n\n // Perform padding and/or truncation\n for (let i = 0; i < encodedTokens.length; ++i) {\n if (encodedTokens[i].input_ids.length === max_length) {\n continue;\n\n } else if (encodedTokens[i].input_ids.length > max_length) {\n // possibly truncate\n if (truncation) {\n truncateHelper(encodedTokens[i], max_length);\n }\n\n } else { // t.length < max_length\n // possibly pad\n if (padding) {\n padHelper(\n encodedTokens[i],\n max_length,\n key => key === 'input_ids' ? this.pad_token_id : 0,\n this.padding_side\n );\n }\n }\n }\n }\n\n const result = {};\n\n if (return_tensor) {\n if (!(padding && truncation)) {\n // Not, guaranteed that all items have same length, so\n // we perform additional check\n\n if (\n encodedTokens.some(x => {\n for (const key of Object.keys(x)) {\n if (x[key].length !== encodedTokens[0][key]?.length) {\n return true;\n }\n }\n return false;\n })\n ) {\n throw Error(\n \"Unable to create tensor, you should probably activate truncation and/or padding \" +\n \"with 'padding=true' and 'truncation=true' to have batched tensors with the same length.\"\n )\n }\n }\n\n // Now we actually convert to tensor\n // NOTE: In the same way as the python library, we return a batched tensor, regardless of\n // whether we have a single input or multiple inputs.\n const dims = [encodedTokens.length, encodedTokens[0].input_ids.length];\n\n for (const key of Object.keys(encodedTokens[0])) {\n result[key] = new Tensor('int64',\n BigInt64Array.from(encodedTokens.flatMap(x => x[key]).map(BigInt)),\n dims\n );\n }\n\n } else {\n for (const key of Object.keys(encodedTokens[0])) {\n result[key] = encodedTokens.map(x => x[key]);\n }\n\n // If not returning a tensor, we match the input type\n if (!isBatched) {\n // Input was not batched, so we unwrap\n for (const key of Object.keys(result)) {\n result[key] = result[key][0];\n }\n }\n }\n\n return /** @type {BatchEncoding} */(result);\n }\n\n /**\n * Encodes a single text using the preprocessor pipeline of the tokenizer.\n *\n * @param {string|null} text The text to encode.\n * @returns {string[]|null} The encoded tokens.\n */\n _encode_text(text) {\n if (text === null) return null;\n\n // Actual function which does encoding, for a single text\n // First, we take care of special tokens. Needed to avoid issues arising from\n // normalization and/or pretokenization (which may not preserve special tokens)\n const sections = this.added_tokens_regex ? text.split(this.added_tokens_regex).filter(x => x) : [text];\n\n const tokens = sections.map((x, section_index) => {\n const addedToken = this.added_tokens.find(t => t.content === x);\n if (addedToken !== undefined) {\n // Ignore added tokens\n return x\n } else {\n if (this.remove_space === true) {\n x = x.trim().split(/\\s+/).join(' ');\n }\n if (this.do_lowercase_and_remove_accent) {\n x = lowercase_and_remove_accent(x);\n }\n\n if (this.normalizer !== null) {\n x = this.normalizer(x);\n }\n\n // If, after normalization, this section is empty (e.g., trimming whitespace),\n // we return an empty array\n if (x.length === 0) {\n return [];\n }\n\n const sectionTokens = (this.pre_tokenizer !== null) ? this.pre_tokenizer(x, {\n section_index,\n }) : [x];\n\n const tokens = this.model(sectionTokens);\n\n return tokens;\n }\n }).flat();\n\n return tokens;\n }\n\n /**\n * Encodes a single text or a pair of texts using the model's tokenizer.\n *\n * @param {string} text The text to encode.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.text_pair=null] The optional second text to encode.\n * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.\n * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids.\n * @returns {EncodingSingle} An object containing the encoded text.\n * @private\n */\n _encode_plus(text, {\n text_pair = null,\n add_special_tokens = true,\n return_token_type_ids = null,\n } = {}) {\n\n const { tokens, token_type_ids } = this._tokenize_helper(text, { pair: text_pair, add_special_tokens });\n\n const input_ids = this.model.convert_tokens_to_ids(tokens);\n\n const result = {\n input_ids,\n attention_mask: new Array(input_ids.length).fill(1),\n }\n if ((return_token_type_ids ?? this.return_token_type_ids) && token_type_ids) {\n result.token_type_ids = token_type_ids;\n }\n return result;\n }\n\n /**\n * Internal helper function to tokenize a text, and optionally a pair of texts.\n * @param {string} text The text to tokenize.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.pair=null] The optional second text to tokenize.\n * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model.\n * @returns {{tokens: string[], token_type_ids?: number[]}} An object containing the tokens and optionally the token type IDs.\n */\n _tokenize_helper(text, {\n pair = null,\n add_special_tokens = false,\n } = {}) {\n const tokens = this._encode_text(text);\n const tokens2 = this._encode_text(pair);\n\n return this.post_processor\n ? this.post_processor(tokens, tokens2, { add_special_tokens })\n : { tokens: mergeArrays(tokens ?? [], tokens2 ?? []) };\n }\n\n /**\n * Converts a string into a sequence of tokens.\n * @param {string} text The sequence to be encoded.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.pair] A second sequence to be encoded with the first.\n * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model.\n * @returns {string[]} The list of tokens.\n */\n tokenize(text, {\n pair = null,\n add_special_tokens = false,\n } = {}) {\n return this._tokenize_helper(text, { pair, add_special_tokens }).tokens;\n }\n\n /**\n * Encodes a single text or a pair of texts using the model's tokenizer.\n *\n * @param {string} text The text to encode.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.text_pair=null] The optional second text to encode.\n * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.\n * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids.\n * @returns {number[]} An array of token IDs representing the encoded text(s).\n */\n encode(text, {\n text_pair = null,\n add_special_tokens = true,\n return_token_type_ids = null,\n } = {}) {\n return this._encode_plus(text, {\n text_pair,\n add_special_tokens,\n return_token_type_ids,\n }).input_ids;\n }\n\n /**\n * Decode a batch of tokenized sequences.\n * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences.\n * @param {Object} decode_args (Optional) Object with decoding arguments.\n * @returns {string[]} List of decoded sequences.\n */\n batch_decode(batch, decode_args = {}) {\n if (batch instanceof Tensor) {\n batch = batch.tolist();\n }\n return batch.map(x => this.decode(x, decode_args));\n }\n\n /**\n * Decodes a sequence of token IDs back to a string.\n *\n * @param {number[]|bigint[]|Tensor} token_ids List/Tensor of token IDs to decode.\n * @param {Object} [decode_args={}]\n * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string.\n * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuations and abbreviated forms are removed.\n *\n * @returns {string} The decoded string.\n * @throws {Error} If `token_ids` is not a non-empty array of integers.\n */\n decode(\n token_ids,\n decode_args = {},\n ) {\n if (token_ids instanceof Tensor) {\n token_ids = prepareTensorForDecode(token_ids);\n }\n\n if (!Array.isArray(token_ids) || token_ids.length === 0 || !isIntegralNumber(token_ids[0])) {\n throw Error(\"token_ids must be a non-empty array of integers.\");\n }\n\n return this.decode_single(token_ids, decode_args)\n }\n\n /**\n * Decode a single list of token ids to a string.\n * @param {number[]|bigint[]} token_ids List of token ids to decode\n * @param {Object} decode_args Optional arguments for decoding\n * @param {boolean} [decode_args.skip_special_tokens=false] Whether to skip special tokens during decoding\n * @param {boolean} [decode_args.clean_up_tokenization_spaces=null] Whether to clean up tokenization spaces during decoding.\n * If null, the value is set to `this.decoder.cleanup` if it exists, falling back to `this.clean_up_tokenization_spaces` if it exists, falling back to `true`.\n * @returns {string} The decoded string\n */\n decode_single(\n token_ids,\n {\n skip_special_tokens = false,\n clean_up_tokenization_spaces = null,\n }\n ) {\n let tokens = this.model.convert_ids_to_tokens(token_ids);\n if (skip_special_tokens) {\n tokens = tokens.filter(x => !this.special_tokens.includes(x));\n }\n\n // If `this.decoder` is null, we just join tokens with a space:\n // https://github.com/huggingface/tokenizers/blob/8edec536a737cb04494b454805be16c020abb14f/tokenizers/src/tokenizer/mod.rs#L835\n /** @type {string} */\n let decoded = this.decoder ? this.decoder(tokens) : tokens.join(' ');\n\n // Slight hack, but prevents having to pass `skip_special_tokens` to\n // each call to `decode`, which would lead to code duplication.\n if (this.decoder && this.decoder.end_of_word_suffix) {\n decoded = decoded.replaceAll(this.decoder.end_of_word_suffix, ' ');\n if (skip_special_tokens) {\n decoded = decoded.trim();\n }\n }\n\n if (clean_up_tokenization_spaces ?? this.clean_up_tokenization_spaces) {\n decoded = clean_up_tokenization(decoded);\n }\n\n return decoded;\n }\n\n /**\n * Retrieve the chat template string used for tokenizing chat messages. This template is used\n * internally by the `apply_chat_template` method and can also be used externally to retrieve the model's chat\n * template for better generation tracking.\n * \n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.chat_template=null]\n * A Jinja template or the name of a template to use for this conversion.\n * It is usually not necessary to pass anything to this argument,\n * as the model's template will be used by default.\n * @param {Object[]} [options.tools=null]\n * A list of tools (callable functions) that will be accessible to the model. If the template does not\n * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema,\n * giving the name, description and argument types for the tool. See our\n * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use)\n * for more information.\n * @returns {string} The chat template string.\n */\n get_chat_template({\n chat_template = null,\n tools = null,\n } = {}) {\n\n // First, handle the cases when the model has a dict of multiple templates\n if (this.chat_template && typeof this.chat_template === 'object') {\n const template_dict = this.chat_template;\n\n if (chat_template !== null && Object.hasOwn(template_dict, chat_template)) {\n // The user can pass the name of a template to the chat template argument instead of an entire template\n chat_template = template_dict[chat_template];\n } else if (chat_template === null) {\n if (tools !== null && 'tool_use' in template_dict) {\n chat_template = template_dict['tool_use'];\n } else if ('default' in template_dict) {\n chat_template = template_dict['default'];\n } else {\n throw Error(\n `This model has multiple chat templates with no default specified! Please either pass a chat ` +\n `template or the name of the template you wish to use to the 'chat_template' argument. Available ` +\n `template names are ${Object.keys(template_dict).sort()}.`\n )\n }\n }\n } else if (chat_template === null) {\n // These are the cases when the model has a single template\n // priority: `chat_template` argument > `tokenizer.chat_template`\n if (this.chat_template) {\n chat_template = this.chat_template;\n } else {\n throw Error(\n \"Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template \" +\n \"argument was passed! For information about writing templates and setting the \" +\n \"tokenizer.chat_template attribute, please see the documentation at \" +\n \"https://huggingface.co/docs/transformers/main/en/chat_templating\"\n )\n }\n }\n return chat_template;\n }\n\n /**\n * Converts a list of message objects with `\"role\"` and `\"content\"` keys to a list of token\n * ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to\n * determine the format and control tokens to use when converting.\n * \n * See [here](https://huggingface.co/docs/transformers/chat_templating) for more information.\n * \n * **Example:** Applying a chat template to a conversation.\n * \n * ```javascript\n * import { AutoTokenizer } from \"@huggingface/transformers\";\n * \n * const tokenizer = await AutoTokenizer.from_pretrained(\"Xenova/mistral-tokenizer-v1\");\n * \n * const chat = [\n * { \"role\": \"user\", \"content\": \"Hello, how are you?\" },\n * { \"role\": \"assistant\", \"content\": \"I'm doing great. How can I help you today?\" },\n * { \"role\": \"user\", \"content\": \"I'd like to show off how chat templating works!\" },\n * ]\n * \n * const text = tokenizer.apply_chat_template(chat, { tokenize: false });\n * // \"[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today? [INST] I'd like to show off how chat templating works! [/INST]\"\n * \n * const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false });\n * // [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793]\n * ```\n * \n * @param {Message[]} conversation A list of message objects with `\"role\"` and `\"content\"` keys,\n * representing the chat history so far.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.chat_template=null] A Jinja template to use for this conversion. If\n * this is not passed, the model's chat template will be used instead.\n * @param {Object[]} [options.tools=null]\n * A list of tools (callable functions) that will be accessible to the model. If the template does not\n * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema,\n * giving the name, description and argument types for the tool. See our\n * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use)\n * for more information.\n * @param {Record[]} [options.documents=null]\n * A list of dicts representing documents that will be accessible to the model if it is performing RAG\n * (retrieval-augmented generation). If the template does not support RAG, this argument will have no\n * effect. We recommend that each document should be a dict containing \"title\" and \"text\" keys. Please\n * see the RAG section of the [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#arguments-for-RAG)\n * for examples of passing documents with chat templates.\n * @param {boolean} [options.add_generation_prompt=false] Whether to end the prompt with the token(s) that indicate\n * the start of an assistant message. This is useful when you want to generate a response from the model.\n * Note that this argument will be passed to the chat template, and so it must be supported in the\n * template for this argument to have any effect.\n * @param {boolean} [options.tokenize=true] Whether to tokenize the output. If false, the output will be a string.\n * @param {boolean} [options.padding=false] Whether to pad sequences to the maximum length. Has no effect if tokenize is false.\n * @param {boolean} [options.truncation=false] Whether to truncate sequences to the maximum length. Has no effect if tokenize is false.\n * @param {number} [options.max_length=null] Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is false.\n * If not specified, the tokenizer's `max_length` attribute will be used as a default.\n * @param {boolean} [options.return_tensor=true] Whether to return the output as a Tensor or an Array. Has no effect if tokenize is false.\n * @param {boolean} [options.return_dict=true] Whether to return a dictionary with named outputs. Has no effect if tokenize is false.\n * @param {Object} [options.tokenizer_kwargs={}] Additional options to pass to the tokenizer.\n * @returns {string | Tensor | number[]| number[][]|BatchEncoding} The tokenized output.\n */\n apply_chat_template(conversation, {\n tools = null,\n documents = null,\n chat_template = null,\n add_generation_prompt = false,\n tokenize = true,\n padding = false,\n truncation = false,\n max_length = null,\n return_tensor = true,\n return_dict = false,\n tokenizer_kwargs = {},\n ...kwargs\n } = {}) {\n\n chat_template = this.get_chat_template({ chat_template, tools });\n\n if (typeof chat_template !== 'string') {\n throw Error(`chat_template must be a string, but got ${typeof chat_template}`);\n }\n\n // Compilation function uses a cache to avoid recompiling the same template\n let compiledTemplate = this._compiled_template_cache.get(chat_template);\n if (compiledTemplate === undefined) {\n compiledTemplate = new Template(chat_template);\n this._compiled_template_cache.set(chat_template, compiledTemplate);\n }\n\n const special_tokens_map = Object.create(null);\n for (const key of SPECIAL_TOKEN_ATTRIBUTES) {\n const value = this.getToken(key);\n if (value) {\n special_tokens_map[key] = value;\n }\n }\n\n const rendered = compiledTemplate.render({\n messages: conversation,\n add_generation_prompt,\n tools,\n documents,\n ...special_tokens_map,\n ...kwargs,\n });\n\n if (tokenize) {\n const out = this._call(rendered, {\n add_special_tokens: false,\n padding,\n truncation,\n max_length,\n return_tensor,\n ...tokenizer_kwargs,\n });\n return return_dict ? out : out.input_ids;\n }\n\n return rendered;\n }\n}\n\n/**\n * BertTokenizer is a class used to tokenize text for BERT models.\n * @extends PreTrainedTokenizer\n */\nexport class BertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\n/**\n * Albert tokenizer\n * @extends PreTrainedTokenizer\n */\nexport class AlbertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class MobileBertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class SqueezeBertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class DebertaTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class DebertaV2Tokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class HerbertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class ConvBertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class RoFormerTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class DistilBertTokenizer extends PreTrainedTokenizer { }\nexport class CamembertTokenizer extends PreTrainedTokenizer { }\nexport class XLMTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\\'s \"fast\" tokenizers library. Therefore, you may experience slightly inaccurate results.')\n }\n}\nexport class ElectraTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\n\nexport class T5Tokenizer extends PreTrainedTokenizer { }\nexport class GPT2Tokenizer extends PreTrainedTokenizer { }\nexport class BartTokenizer extends PreTrainedTokenizer { }\nexport class MBartTokenizer extends PreTrainedTokenizer {\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.languageRegex = /^[a-z]{2}_[A-Z]{2}$/;\n this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x));\n this.lang_to_token = x => x; // Identity function\n }\n\n /**\n * Helper function to build translation inputs for an `MBartTokenizer`.\n * @param {string|string[]} raw_inputs The text to tokenize.\n * @param {Object} tokenizer_options Options to be sent to the tokenizer\n * @param {Object} generate_kwargs Generation options.\n * @returns {Object} Object to be passed to the model.\n */\n _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {\n return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);\n }\n}\nexport class MBart50Tokenizer extends MBartTokenizer { } // NOTE: extends MBartTokenizer\n\nexport class RobertaTokenizer extends PreTrainedTokenizer { }\n\nexport class BloomTokenizer extends PreTrainedTokenizer { }\n\nconst SPIECE_UNDERLINE = \"▁\";\n\nexport class LlamaTokenizer extends PreTrainedTokenizer {\n\n padding_side = 'left';\n\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.legacy = tokenizerConfig.legacy ?? true;\n if (!this.legacy) {\n // See https://github.com/huggingface/transformers/pull/24565 for more information\n this.normalizer = null;\n this.pre_tokenizer = new MetaspacePreTokenizer({\n replacement: SPIECE_UNDERLINE,\n add_prefix_space: true,\n prepend_scheme: \"first\",\n });\n }\n }\n\n /**\n * Helper function to handle legacy encoding of SPM tokenizers.\n * Adapted from https://github.com/huggingface/transformers/blob/e6dcf8abd6f65bb4b6dfc1831b20d9ba49ce00e2/src/transformers/models/t5/tokenization_t5.py#L374-L387\n * @param {string} text The text to encode.\n * @returns {string[]} The encoded tokens.\n */\n _encode_text(text) {\n if (text === null) return null;\n\n if (this.legacy || text.length === 0) {\n return super._encode_text(text);\n }\n\n let tokens = super._encode_text(SPIECE_UNDERLINE + text.replaceAll(SPIECE_UNDERLINE, \" \"));\n if (tokens.length > 1 && tokens[0] === SPIECE_UNDERLINE && this.special_tokens.includes(tokens[1])) {\n tokens = tokens.slice(1);\n }\n return tokens;\n }\n}\nexport class CodeLlamaTokenizer extends PreTrainedTokenizer { }\n\nexport class XLMRobertaTokenizer extends PreTrainedTokenizer { }\nexport class MPNetTokenizer extends PreTrainedTokenizer { }\n\nexport class FalconTokenizer extends PreTrainedTokenizer { }\n\nexport class GPTNeoXTokenizer extends PreTrainedTokenizer { }\n\nexport class EsmTokenizer extends PreTrainedTokenizer { }\n\nexport class Qwen2Tokenizer extends PreTrainedTokenizer { }\n\nexport class GemmaTokenizer extends PreTrainedTokenizer { }\n\nexport class Grok1Tokenizer extends PreTrainedTokenizer { }\n\n/**\n * Helper function to build translation inputs for an `NllbTokenizer` or `M2M100Tokenizer`.\n * @param {PreTrainedTokenizer} self The tokenizer instance.\n * @param {string|string[]} raw_inputs The text to tokenize.\n * @param {Object} tokenizer_options Options to be sent to the tokenizer\n * @param {Object} generate_kwargs Generation options.\n * @returns {Object} Object to be passed to the model.\n * @private\n */\nfunction _build_translation_inputs(self, raw_inputs, tokenizer_options, generate_kwargs) {\n if (!('language_codes' in self) || !Array.isArray(self.language_codes)) {\n throw new Error('Tokenizer must have `language_codes` attribute set and it should be an array of language ids.')\n }\n if (!('languageRegex' in self) || !(self.languageRegex instanceof RegExp)) {\n throw new Error('Tokenizer must have `languageRegex` attribute set and it should be a regular expression.')\n }\n if (!('lang_to_token' in self) || typeof self.lang_to_token !== 'function') {\n throw new Error('Tokenizer must have `lang_to_token` attribute set and it should be a function.')\n }\n const src_lang_token = generate_kwargs.src_lang;\n const tgt_lang_token = generate_kwargs.tgt_lang;\n\n // Check that the target language is valid:\n if (!self.language_codes.includes(tgt_lang_token)) {\n throw new Error(`Target language code \"${tgt_lang_token}\" is not valid. Must be one of: {${self.language_codes.join(', ')}}`);\n }\n\n // Allow `src_lang` to be optional. If not set, we'll use the tokenizer's default.\n if (src_lang_token !== undefined) {\n // Check that the source language is valid:\n if (!self.language_codes.includes(src_lang_token)) {\n throw new Error(`Source language code \"${src_lang_token}\" is not valid. Must be one of: {${self.language_codes.join(', ')}}`);\n }\n\n // In the same way as the Python library, we override the post-processor\n // to force the source language to be first:\n for (const item of self.post_processor.config.single) {\n if ('SpecialToken' in item && self.languageRegex.test(item.SpecialToken.id)) {\n item.SpecialToken.id = self.lang_to_token(src_lang_token);\n break;\n }\n }\n // TODO: Do the same for pair?\n }\n\n // Override the `forced_bos_token_id` to force the correct language\n generate_kwargs.forced_bos_token_id = self.model.convert_tokens_to_ids([self.lang_to_token(tgt_lang_token)])[0];\n\n return self._call(raw_inputs, tokenizer_options);\n}\n\n/**\n * The NllbTokenizer class is used to tokenize text for NLLB (\"No Language Left Behind\") models.\n * \n * No Language Left Behind (NLLB) is a first-of-its-kind, AI breakthrough project\n * that open-sources models capable of delivering high-quality translations directly\n * between any pair of 200+ languages — including low-resource languages like Asturian,\n * Luganda, Urdu and more. It aims to help people communicate with anyone, anywhere,\n * regardless of their language preferences. For more information, check out their\n * [paper](https://arxiv.org/abs/2207.04672).\n * \n * For a list of supported languages (along with their language codes),\n * @see {@link https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200}\n */\nexport class NllbTokenizer extends PreTrainedTokenizer {\n\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.languageRegex = /^[a-z]{3}_[A-Z][a-z]{3}$/;\n this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x));\n this.lang_to_token = x => x; // Identity function\n }\n\n /**\n * Helper function to build translation inputs for an `NllbTokenizer`.\n * @param {string|string[]} raw_inputs The text to tokenize.\n * @param {Object} tokenizer_options Options to be sent to the tokenizer\n * @param {Object} generate_kwargs Generation options.\n * @returns {Object} Object to be passed to the model.\n */\n _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {\n return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);\n }\n}\n\n/**\n * The M2M100Tokenizer class is used to tokenize text for M2M100 (\"Many-to-Many\") models.\n * \n * M2M100 is a multilingual encoder-decoder (seq-to-seq) model trained for Many-to-Many\n * multilingual translation. It was introduced in this [paper](https://arxiv.org/abs/2010.11125)\n * and first released in [this](https://github.com/pytorch/fairseq/tree/master/examples/m2m_100) repository.\n * \n * For a list of supported languages (along with their language codes),\n * @see {@link https://huggingface.co/facebook/m2m100_418M#languages-covered}\n */\nexport class M2M100Tokenizer extends PreTrainedTokenizer {\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.languageRegex = /^__[a-z]{2,3}__$/;\n this.language_codes = this.special_tokens\n .filter(x => this.languageRegex.test(x))\n .map(x => x.slice(2, -2));\n this.lang_to_token = x => `__${x}__`;\n }\n\n /**\n * Helper function to build translation inputs for an `M2M100Tokenizer`.\n * @param {string|string[]} raw_inputs The text to tokenize.\n * @param {Object} tokenizer_options Options to be sent to the tokenizer\n * @param {Object} generate_kwargs Generation options.\n * @returns {Object} Object to be passed to the model.\n */\n _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {\n return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);\n }\n}\n\n/**\n * WhisperTokenizer tokenizer\n * @extends PreTrainedTokenizer\n */\nexport class WhisperTokenizer extends PreTrainedTokenizer {\n\n get timestamp_begin() {\n return this.model.convert_tokens_to_ids([\"<|notimestamps|>\"])[0] + 1;\n }\n\n /**\n * Decodes automatic speech recognition (ASR) sequences.\n * @param {Array<{tokens: bigint[], token_timestamps?: number[], stride: number[]}>} sequences The sequences to decode.\n * @param {Object} options The options to use for decoding.\n * @returns {Array, text: string}>}>} The decoded sequences.\n */\n _decode_asr(sequences, {\n return_timestamps = false,\n return_language = false,\n time_precision = null,\n force_full_sequences = true\n } = {}) {\n // Set force_full_sequences=false if you want streaming\n // TODO add support for `return_language`\n\n // Internal method meant to only be used by asr pipeline.\n // Handles all the little quirks specific to whisper to handle\n // the various options not allowed in other seq2seq models\n\n // =========== Overview ============\n // - iterate over all outputs\n // - all tokens within output\n // - Each token can be\n // - language token\n // - special token\n // - timestamp token\n // - text token\n // - We accumulate the text tokens.\n // - We split on end timestamps\n // - Lots of complexity comes from stride and timestamps\n\n if (time_precision === null) {\n throw Error(\"Must specify time_precision\")\n }\n let last_language = null;\n\n const returnWordTimestamps = return_timestamps === \"word\";\n\n function new_chunk() {\n return { \"language\": last_language, \"timestamp\": [null, null], \"text\": \"\" };\n }\n\n // Welcome to the state machine!\n const chunks = [];\n let chunk = new_chunk();\n let time_offset = 0.0;\n const timestamp_begin = this.timestamp_begin;\n\n let previous_tokens = [];\n let previous_token_timestamps = [];\n\n let skip = false;\n let right_stride_start = null;\n\n\n const all_special_ids = new Set(this.all_special_ids);\n\n for (const output of sequences) {\n // NOTE: python version has batches, so it uses [0]\n const token_ids = output.tokens;\n const token_timestamps = returnWordTimestamps ? output.token_timestamps : null;\n\n // These keep track of timestamps within strides, which need\n // to be skipped and resolve all tokens in a single chunk.\n let last_timestamp = null;\n let first_timestamp = timestamp_begin;\n\n if (\"stride\" in output) {\n const [chunk_len, stride_left, stride_right] = output.stride;\n\n // Offset the timings to account for the other `model_outputs`.\n time_offset -= stride_left;\n right_stride_start = chunk_len - stride_right;\n\n // Keeping track of timestamps within strides\n // We're going to NOT split on those, and delay until we're\n // out of BOTH stride. Otherwise lots of issues occur and\n // corner cases\n if (stride_left) {\n first_timestamp = stride_left / time_precision + timestamp_begin;\n }\n\n if (stride_right) {\n for (let i = token_ids.length - 1; i >= 0; --i) {\n const token = Number(token_ids[i]);\n if (token >= timestamp_begin) {\n // There can be several token in the right stride\n // But the last one is ALWAYS going to be skipped\n if (last_timestamp !== null && (token - timestamp_begin) * time_precision < right_stride_start) {\n break;\n }\n last_timestamp = token;\n }\n }\n }\n }\n\n let current_tokens = [];\n let current_token_timestamps = [];\n\n // - all tokens within output\n for (let i = 0; i < token_ids.length; ++i) {\n const token = Number(token_ids[i]);\n // 4 possible states for each token\n // - 1/ Language code\n // - 2/ all other special tokens (which we ignore)\n // - 3/ Timestamp\n // - 4/ Regular text\n\n if (all_special_ids.has(token)) {\n const text = this.decode([token]);\n const language = WHISPER_LANGUAGE_MAPPING.get(text.slice(2, -2));\n\n if (language !== undefined) {\n // 1/ Indeed some language\n // TODO Handle when language is different from the previous\n // one, and we cannot use timestamped tokens to create chunks\n if (last_language !== null && language !== last_language && !return_timestamps) {\n previous_tokens.push(current_tokens);\n const resolved_tokens = this.findLongestCommonSequence(previous_tokens)[0];\n const resolved_text = this.decode(resolved_tokens);\n chunk.text = resolved_text;\n chunks.push(chunk);\n\n // Flush all our temporary context\n previous_tokens = [];\n current_tokens = [];\n chunk = new_chunk();\n }\n\n last_language = chunk.language = language;\n } else {\n // 2/ This is a regular special token, ignoring it\n }\n } else if (token >= timestamp_begin) {\n // 3/ Timestamp token\n const time = (token - timestamp_begin) * time_precision + time_offset;\n const rounded_time = round(time, 2);\n\n if (last_timestamp !== null && token >= last_timestamp) {\n // Whisper outputted a timestamp token, but it falls within\n // our stride, so we're going to skip it for the time being\n // and resolve this later\n // Skip is necessary because timestamp tokens always come\n // by pair, so we need to skip the next one too (which would mark the start of another chunk).\n skip = true;\n } else if (skip || (previous_tokens.length > 0 && token < first_timestamp)) {\n skip = false;\n } else if (chunk.timestamp[0] === null) {\n chunk.timestamp[0] = rounded_time;\n } else {\n // This is the end of the timestamp chunk\n if (rounded_time === chunk.timestamp[0]) {\n // This is a bug in timestamp token output\n // where we're taking the duplicate token\n // as a stop where it should be a start.\n // This is an issue in the underlying model output\n // Let's just skip it so it becomes de-factor a start agin\n } else {\n chunk.timestamp[1] = rounded_time;\n\n // Handling merges\n previous_tokens.push(current_tokens)\n\n if (returnWordTimestamps) {\n previous_token_timestamps.push(current_token_timestamps);\n }\n const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(\n previous_tokens, previous_token_timestamps\n )\n\n const resolved_text = this.decode(resolved_tokens)\n chunk.text = resolved_text\n\n if (returnWordTimestamps) {\n chunk.words = this.collateWordTimestamps(\n resolved_tokens, resolved_token_timestamps, last_language,\n )\n }\n\n chunks.push(chunk)\n\n // Flush all our temporary context\n previous_tokens = []\n current_tokens = []\n previous_token_timestamps = []\n current_token_timestamps = []\n chunk = new_chunk()\n }\n }\n\n } else {\n // 4/ Regular token\n // We just append to the list of all tokens so we can handle\n // merges later and decode into text.\n current_tokens.push(token)\n\n if (returnWordTimestamps) {\n let start_time = round(token_timestamps[i] + time_offset, 2);\n\n let end_time;\n if (i + 1 < token_timestamps.length) {\n end_time = round(token_timestamps[i + 1] + time_offset, 2);\n\n // Do not allow punctuation-only tokens to have a duration.\n // This prevents long pauses from messing up the timestamps.\n const decoded_text = this.decode([token]);\n if (PUNCTUATION_ONLY_REGEX.test(decoded_text)) {\n // Add `time_precision` to avoid overlapping timestamps\n end_time = round(Math.min(start_time + time_precision, end_time), 2);\n }\n } else {\n // should never happen\n end_time = null;\n }\n current_token_timestamps.push([start_time, end_time]);\n }\n\n }\n }\n\n if ('stride' in output) {\n const [chunk_len, stride_left, stride_right] = output.stride;\n time_offset += chunk_len - stride_right\n }\n\n // Leftover tokens\n if (current_tokens.length > 0) {\n previous_tokens.push(current_tokens)\n if (returnWordTimestamps) {\n previous_token_timestamps.push(current_token_timestamps);\n }\n } else if (previous_tokens.every(p => p.length === 0)) {\n // Flushing previous tokens (END)\"\n chunk = new_chunk()\n previous_tokens = []\n current_tokens = []\n previous_token_timestamps = [];\n current_token_timestamps = [];\n }\n\n }\n\n if (previous_tokens.length > 0) {\n if (force_full_sequences && return_timestamps) {\n // Last token should always be timestamps, so there shouldn't be\n // leftover\n throw new Error(\n \"Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. \" +\n \"Also make sure WhisperTimeStampLogitsProcessor was used during generation.\"\n );\n }\n\n // Happens when we don't use timestamps\n const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(previous_tokens, previous_token_timestamps);\n\n // Flushing previous tokens (FINAL)\n const resolved_text = this.decode(resolved_tokens);\n chunk.text = resolved_text;\n if (returnWordTimestamps) {\n chunk.words = this.collateWordTimestamps(\n resolved_tokens, resolved_token_timestamps, last_language,\n )\n }\n chunks.push(chunk);\n }\n\n let optional = Object.create(null);\n\n // Preparing and cleaning up the pipeline output\n const full_text = chunks.map(chunk => chunk.text).join('');\n if (return_timestamps || return_language) {\n for (let i = 0; i < chunks.length; ++i) {\n const chunk = chunks[i];\n if (!return_timestamps) {\n delete chunk[\"timestamp\"];\n }\n\n if (!return_language) {\n delete chunk[\"language\"];\n }\n }\n if (returnWordTimestamps) {\n const new_chunks = [];\n for (const chunk of chunks) {\n for (const word of chunk.words) {\n new_chunks.push(word);\n }\n }\n optional = { \"chunks\": new_chunks };\n } else {\n optional = { \"chunks\": chunks };\n }\n }\n return [full_text, optional];\n\n }\n\n /**\n * Finds the longest common sequence among the provided sequences.\n * @param {number[][]} sequences An array of sequences of token ids to compare.\n * @returns {number[][]} The longest common sequence found.\n * @throws {Error} If there is a bug within the function.\n * @private\n */\n findLongestCommonSequence(sequences, token_timestamp_sequences = null) {\n // It would be much harder to do O(n) because of fault tolerance.\n // We actually have a really good property which is that the total sequence\n // MUST be those subsequences in order.\n // If token_timestamp_sequences is provided, will split those sequences in\n // exactly the same way.\n let leftSequence = sequences[0];\n let leftLength = leftSequence.length;\n let totalSequence = [];\n\n const use_token_timestamp_sequences = Array.isArray(token_timestamp_sequences) && token_timestamp_sequences.length > 0;\n let total_token_timestamp_sequence = use_token_timestamp_sequences ? [] : null;\n let left_token_timestamp_sequence = use_token_timestamp_sequences ? token_timestamp_sequences[0] : null;\n for (let i = 1; i < sequences.length; ++i) {\n const rightSequence = sequences[i];\n let max = 0.0;\n let maxIndices = [leftLength, leftLength, 0, 0];\n // Here we're sliding matches\n // [a, b, c, d]\n // [c, d, f]\n // = [c] == [d]\n\n // [a, b, c, d]\n // [c, d, f]\n // = [c, d] == [c, d]\n\n\n // [a, b, c, d]\n // [c, d, f]\n\n // = [b, c, d] == [c, d, f]\n\n // [a, b, c, d]\n // [c, d, f]\n\n // [a, b, c] == [c, d, f]\n\n // [a, b, c, d]\n // [d, f]\n\n // [a, b] == [d, f]\n\n // [a, b, c, d]\n // [f]\n\n // [a] == [f]\n\n const rightLength = rightSequence.length;\n for (let j = 1; j < leftLength + rightLength; ++j) {\n // Slightly convoluted because we don't want out of bound indices\n // This will be necessary for a small conflict resolution optimization\n // later\n const leftStart = Math.max(0, leftLength - j);\n const leftStop = Math.min(leftLength, leftLength + rightLength - j);\n const left = leftSequence.slice(leftStart, leftStop);\n const rightStart = Math.max(0, j - leftLength);\n const rightStop = Math.min(rightLength, j);\n const right = rightSequence.slice(rightStart, rightStop);\n if (left.length !== right.length) {\n throw new Error(\"There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.\");\n }\n\n let matches;\n if (use_token_timestamp_sequences) {\n // Get length of longest subsequence of tokens that match\n // and have timestamps that are in order\n matches = left.filter((elem, idx) => (\n elem === right[idx]\n && left_token_timestamp_sequence[leftStart + idx] <= token_timestamp_sequences[i][rightStart + idx]\n )).length;\n } else {\n matches = left.filter((elem, idx) => elem === right[idx]).length;\n }\n\n // epsilon to favor long perfect matches\n const eps = j / 10000.0;\n const matching = matches / j + eps;\n if (matches > 1 && matching > max) {\n max = matching;\n maxIndices = [leftStart, leftStop, rightStart, rightStop];\n }\n }\n const [leftStart, leftStop, rightStart, rightStop] = maxIndices;\n const leftMid = Math.floor((leftStop + leftStart) / 2);\n const rightMid = Math.floor((rightStop + rightStart) / 2);\n totalSequence.push(...leftSequence.slice(0, leftMid));\n leftSequence = rightSequence.slice(rightMid);\n leftLength = leftSequence.length;\n\n if (use_token_timestamp_sequences) {\n total_token_timestamp_sequence.push(...left_token_timestamp_sequence.slice(0, leftMid));\n left_token_timestamp_sequence = token_timestamp_sequences[i].slice(rightMid);\n }\n }\n totalSequence.push(...leftSequence);\n\n if (use_token_timestamp_sequences) {\n total_token_timestamp_sequence.push(...left_token_timestamp_sequence);\n return [totalSequence, total_token_timestamp_sequence];\n } else {\n return [totalSequence, []];\n }\n }\n\n /** @private */\n collateWordTimestamps(tokens, token_timestamps, language) {\n\n const [words, _, token_indices] = this.combineTokensIntoWords(tokens, language);\n\n const timings = [];\n for (let i = 0; i < words.length; ++i) {\n const indices = token_indices[i];\n timings.push({\n text: words[i],\n timestamp: [\n token_timestamps[indices.at(0)][0],\n token_timestamps[indices.at(-1)][1],\n ],\n });\n }\n return timings;\n }\n\n /**\n * Groups tokens by word. Returns a tuple containing a list of strings with the words,\n * and a list of `token_id` sequences with the tokens making up each word.\n * @param {number[]} tokens \n * @param {string} [language] \n * @param {string} prepend_punctionations \n * @param {string} append_punctuations \n * \n * @private\n */\n combineTokensIntoWords(tokens, language, prepend_punctionations = \"\\\"'“¡¿([{-\", append_punctuations = \"\\\"'.。,,!!??::”)]}、\") {\n language = language ?? 'english';\n\n let words, word_tokens, token_indices;\n\n if ([\"chinese\", \"japanese\", \"thai\", \"lao\", \"myanmar\"].includes(language)) {\n // These languages don't typically use spaces.\n [words, word_tokens, token_indices] = this.splitTokensOnUnicode(tokens)\n } else {\n [words, word_tokens, token_indices] = this.splitTokensOnSpaces(tokens)\n }\n\n return this.mergePunctuations(words, word_tokens, token_indices, prepend_punctionations, append_punctuations);\n }\n\n /** @type {PreTrainedTokenizer['decode']} */\n decode(\n token_ids,\n decode_args,\n ) {\n let text;\n // @ts-ignore\n if (decode_args?.decode_with_timestamps) {\n if (token_ids instanceof Tensor) {\n token_ids = prepareTensorForDecode(token_ids);\n }\n text = this.decodeWithTimestamps(token_ids, decode_args);\n } else {\n text = super.decode(token_ids, decode_args);\n }\n // TODO: implement offsets\n // if (decode_args.output_offsets) {\n // let offsets = this.computeOffsets\n // }\n return text;\n }\n\n /**\n * @param {number[]|bigint[]} token_ids List of token IDs to decode.\n * @param {Object} decode_args Optional arguments for decoding\n * @private\n */\n decodeWithTimestamps(token_ids, decode_args) {\n const time_precision = decode_args?.time_precision ?? 0.02;\n\n const timestamp_begin = Array.from(this.all_special_ids).at(-1) + 1;\n /**@type {Array} */\n let outputs = [[]];\n for (let token of token_ids) {\n token = Number(token);\n if (token >= timestamp_begin) {\n const timestamp = ((token - timestamp_begin) * time_precision).toFixed(2);\n outputs.push(`<|${timestamp}|>`);\n outputs.push([]);\n } else {\n outputs[outputs.length - 1].push(token);\n }\n }\n outputs = outputs.map(\n s => typeof s === 'string' ? s : super.decode(s, decode_args)\n )\n\n return outputs.join('');\n }\n\n /**\n * Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points.\n * @param {number[]} tokens \n * @returns {*}\n * @private\n */\n splitTokensOnUnicode(tokens) {\n const decoded_full = this.decode(tokens, {\n // @ts-ignore\n decode_with_timestamps: true,\n });\n const replacement_char = '\\uFFFD';\n\n const words = []\n const word_tokens = []\n const token_indices = []\n let current_tokens = []\n let current_indices = []\n let unicode_offset = 0\n\n for (let token_idx = 0; token_idx < tokens.length; ++token_idx) {\n const token = tokens[token_idx];\n\n current_tokens.push(token);\n current_indices.push(token_idx);\n\n const decoded = this.decode(current_tokens, {\n // @ts-ignore\n decode_with_timestamps: true,\n });\n\n if (!decoded.includes(replacement_char) || decoded_full[unicode_offset + decoded.indexOf(replacement_char)] === replacement_char) {\n words.push(decoded)\n word_tokens.push(current_tokens)\n token_indices.push(current_indices)\n current_tokens = []\n current_indices = []\n unicode_offset += decoded.length;\n }\n\n }\n\n return [words, word_tokens, token_indices]\n }\n\n /**\n * Combine tokens into words by splitting at whitespace and punctuation tokens.\n * @param {number[]} tokens \n * @private\n */\n splitTokensOnSpaces(tokens) {\n\n const [subwords, subword_tokens_list, subword_indices_list] = this.splitTokensOnUnicode(tokens);\n\n const words = []\n const word_tokens = []\n const token_indices = []\n\n const punctuationRegex = new RegExp(`^[${PUNCTUATION_REGEX}]$`, 'gu');\n\n for (let i = 0; i < subwords.length; ++i) {\n\n const subword = subwords[i];\n const subword_tokens = subword_tokens_list[i];\n const subword_indices = subword_indices_list[i];\n\n // @ts-ignore\n const special = subword_tokens[0] >= this.model.tokens_to_ids.get('<|endoftext|>');\n const with_space = subword.startsWith(' ');\n const trimmed = subword.trim();\n const punctuation = punctuationRegex.test(trimmed);\n\n if (special || with_space || punctuation || words.length === 0) {\n words.push(subword);\n word_tokens.push(subword_tokens);\n token_indices.push(subword_indices);\n } else {\n const ix = words.length - 1;\n words[ix] += subword;\n word_tokens[ix].push(...subword_tokens);\n token_indices[ix].push(...subword_indices);\n }\n }\n\n return [words, word_tokens, token_indices];\n\n }\n\n /**\n * Merges punctuation tokens with neighboring words.\n * @param {string[]} words \n * @param {number[][]} tokens \n * @param {number[][]} indices \n * @param {string} prepended \n * @param {string} appended \n * @private\n */\n mergePunctuations(words, tokens, indices, prepended, appended) {\n\n const newWords = structuredClone(words);\n const newTokens = structuredClone(tokens);\n const newIndices = structuredClone(indices);\n\n\n // prepend punctuations\n let i = newWords.length - 2;\n let j = newWords.length - 1;\n\n while (i >= 0) {\n if (newWords[i].startsWith(' ') && prepended.includes(newWords[i].trim())) {\n newWords[j] = newWords[i] + newWords[j];\n newTokens[j] = mergeArrays(newTokens[i], newTokens[j]);\n newIndices[j] = mergeArrays(newIndices[i], newIndices[j]);\n newWords[i] = '';\n newTokens[i] = [];\n newIndices[i] = [];\n } else {\n j = i;\n }\n --i;\n }\n\n // append punctuations\n i = 0;\n j = 1;\n while (j < newWords.length) {\n if (!newWords[i].endsWith(' ') && appended.includes(newWords[j])) {\n newWords[i] += newWords[j];\n newTokens[i] = mergeArrays(newTokens[i], newTokens[j]);\n newIndices[i] = mergeArrays(newIndices[i], newIndices[j]);\n newWords[j] = '';\n newTokens[j] = [];\n newIndices[j] = [];\n } else {\n i = j;\n }\n ++j;\n }\n\n return [\n newWords.filter(x => x),\n newTokens.filter(x => x.length > 0),\n newIndices.filter(x => x.length > 0),\n ]\n }\n}\nexport class CodeGenTokenizer extends PreTrainedTokenizer { }\nexport class CLIPTokenizer extends PreTrainedTokenizer { }\nexport class SiglipTokenizer extends PreTrainedTokenizer { }\n\n/**\n * @todo This model is not yet supported by Hugging Face's \"fast\" tokenizers library (https://github.com/huggingface/tokenizers).\n * Therefore, this implementation (which is based on fast tokenizers) may produce slightly inaccurate results.\n */\nexport class MarianTokenizer extends PreTrainedTokenizer {\n /**\n * Create a new MarianTokenizer instance.\n * @param {Object} tokenizerJSON The JSON of the tokenizer.\n * @param {Object} tokenizerConfig The config of the tokenizer.\n */\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.languageRegex = /^(>>\\w+<<)\\s*/g;\n\n this.supported_language_codes = this.model.vocab.filter(\n x => this.languageRegex.test(x)\n );\n\n console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\\'s \"fast\" tokenizers library. Therefore, you may experience slightly inaccurate results.')\n }\n\n /**\n * Encodes a single text. Overriding this method is necessary since the language codes\n * must be removed before encoding with sentencepiece model.\n * @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213\n *\n * @param {string|null} text The text to encode.\n * @returns {Array} The encoded tokens.\n */\n _encode_text(text) {\n if (text === null) return null;\n\n // Check if text starts with language code:\n const [matchInfo, ...remainder] = text.trim().split(this.languageRegex);\n\n if (remainder.length === 0) {\n // No language code, encode normally\n return super._encode_text(matchInfo);\n\n } else if (remainder.length === 2) {\n // Text starts with language code, so we do not encode it with sentencepiece.\n const [language, text] = remainder;\n\n if (!this.supported_language_codes.includes(language)) {\n console.warn(`Unsupported language code \"${language}\" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`)\n }\n return mergeArrays([language], super._encode_text(text));\n }\n }\n\n}\n\nexport class Wav2Vec2CTCTokenizer extends PreTrainedTokenizer { }\n\nexport class BlenderbotTokenizer extends PreTrainedTokenizer { }\nexport class BlenderbotSmallTokenizer extends PreTrainedTokenizer { }\n\nexport class SpeechT5Tokenizer extends PreTrainedTokenizer { }\n\nexport class NougatTokenizer extends PreTrainedTokenizer { }\n\nexport class VitsTokenizer extends PreTrainedTokenizer {\n\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n // Custom decoder function\n this.decoder = new VitsDecoder({});\n }\n}\n\nexport class CohereTokenizer extends PreTrainedTokenizer { }\n\n/**\n * Helper class which is used to instantiate pretrained tokenizers with the `from_pretrained` function.\n * The chosen tokenizer class is determined by the type specified in the tokenizer config.\n * \n * @example\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');\n */\nexport class AutoTokenizer {\n static TOKENIZER_CLASS_MAPPING = {\n T5Tokenizer,\n DistilBertTokenizer,\n CamembertTokenizer,\n DebertaTokenizer,\n DebertaV2Tokenizer,\n BertTokenizer,\n HerbertTokenizer,\n ConvBertTokenizer,\n RoFormerTokenizer,\n XLMTokenizer,\n ElectraTokenizer,\n MobileBertTokenizer,\n SqueezeBertTokenizer,\n AlbertTokenizer,\n GPT2Tokenizer,\n BartTokenizer,\n MBartTokenizer,\n MBart50Tokenizer,\n RobertaTokenizer,\n WhisperTokenizer,\n CodeGenTokenizer,\n CLIPTokenizer,\n SiglipTokenizer,\n MarianTokenizer,\n BloomTokenizer,\n NllbTokenizer,\n M2M100Tokenizer,\n LlamaTokenizer,\n CodeLlamaTokenizer,\n XLMRobertaTokenizer,\n MPNetTokenizer,\n FalconTokenizer,\n GPTNeoXTokenizer,\n EsmTokenizer,\n Wav2Vec2CTCTokenizer,\n BlenderbotTokenizer,\n BlenderbotSmallTokenizer,\n SpeechT5Tokenizer,\n NougatTokenizer,\n VitsTokenizer,\n Qwen2Tokenizer,\n GemmaTokenizer,\n Grok1Tokenizer,\n CohereTokenizer,\n\n // Base case:\n PreTrainedTokenizer,\n }\n\n\n /**\n * Instantiate one of the tokenizer classes of the library from a pretrained model.\n * \n * The tokenizer class to instantiate is selected based on the `tokenizer_class` property of the config object\n * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)\n * \n * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:\n * - A string, the *model id* of a pretrained tokenizer hosted inside a model repo on huggingface.co.\n * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a\n * user or organization name, like `dbmdz/bert-base-german-cased`.\n * - A path to a *directory* containing tokenizer files, e.g., `./my_model_directory/`.\n * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.\n * \n * @returns {Promise} A new instance of the PreTrainedTokenizer class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n legacy = null,\n } = {}) {\n\n const [tokenizerJSON, tokenizerConfig] = await loadTokenizer(pretrained_model_name_or_path, {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n legacy,\n })\n\n // Some tokenizers are saved with the \"Fast\" suffix, so we remove that if present.\n const tokenizerName = tokenizerConfig.tokenizer_class?.replace(/Fast$/, '') ?? 'PreTrainedTokenizer';\n\n let cls = this.TOKENIZER_CLASS_MAPPING[tokenizerName];\n if (!cls) {\n console.warn(`Unknown tokenizer class \"${tokenizerName}\", attempting to construct from base class.`);\n cls = PreTrainedTokenizer;\n }\n return new cls(tokenizerJSON, tokenizerConfig);\n }\n}\n","/**\n * @file Helper module for audio processing. \n * \n * These functions and classes are only used internally, \n * meaning an end-user shouldn't need to access anything here.\n * \n * @module utils/audio\n */\n\nimport {\n getFile,\n} from './hub.js';\nimport { FFT, max } from './maths.js';\nimport {\n calculateReflectOffset,\n} from './core.js';\nimport { Tensor, matmul } from './tensor.js';\n\n\n/**\n * Helper function to read audio from a path/URL.\n * @param {string|URL} url The path/URL to load the audio from.\n * @param {number} sampling_rate The sampling rate to use when decoding the audio.\n * @returns {Promise} The decoded audio as a `Float32Array`.\n */\nexport async function read_audio(url, sampling_rate) {\n if (typeof AudioContext === 'undefined') {\n // Running in node or an environment without AudioContext\n throw Error(\n \"Unable to load audio from path/URL since `AudioContext` is not available in your environment. \" +\n \"Instead, audio data should be passed directly to the pipeline/processor. \" +\n \"For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.\"\n )\n }\n\n const response = await (await getFile(url)).arrayBuffer();\n const audioCTX = new AudioContext({ sampleRate: sampling_rate });\n if (typeof sampling_rate === 'undefined') {\n console.warn(`No sampling rate provided, using default of ${audioCTX.sampleRate}Hz.`)\n }\n const decoded = await audioCTX.decodeAudioData(response);\n\n /** @type {Float32Array} */\n let audio;\n\n // We now replicate HuggingFace's `ffmpeg_read` method:\n if (decoded.numberOfChannels === 2) {\n // When downmixing a stereo audio file to mono using the -ac 1 option in FFmpeg,\n // the audio signal is summed across both channels to create a single mono channel.\n // However, if the audio is at full scale (i.e. the highest possible volume level),\n // the summing of the two channels can cause the audio signal to clip or distort.\n\n // To prevent this clipping, FFmpeg applies a scaling factor of 1/sqrt(2) (~ 0.707)\n // to the audio signal before summing the two channels. This scaling factor ensures\n // that the combined audio signal will not exceed the maximum possible level, even\n // if both channels are at full scale.\n\n // After applying this scaling factor, the audio signal from both channels is summed\n // to create a single mono channel. It's worth noting that this scaling factor is\n // only applied when downmixing stereo audio to mono using the -ac 1 option in FFmpeg.\n // If you're using a different downmixing method, or if you're not downmixing the\n // audio at all, this scaling factor may not be needed.\n const SCALING_FACTOR = Math.sqrt(2);\n\n const left = decoded.getChannelData(0);\n const right = decoded.getChannelData(1);\n\n audio = new Float32Array(left.length);\n for (let i = 0; i < decoded.length; ++i) {\n audio[i] = SCALING_FACTOR * (left[i] + right[i]) / 2;\n }\n\n } else {\n // If the audio is not stereo, we can just use the first channel:\n audio = decoded.getChannelData(0);\n }\n\n return audio;\n}\n\n/**\n * Helper function to generate windows that are special cases of the generalized cosine window.\n * See https://www.mathworks.com/help/signal/ug/generalized-cosine-windows.html for more information.\n * @param {number} M Number of points in the output window. If zero or less, an empty array is returned.\n * @param {number} a_0 Offset for the generalized cosine window.\n * @returns {Float64Array} The generated window.\n */\nfunction generalized_cosine_window(M, a_0) {\n if (M < 1) {\n return new Float64Array();\n }\n if (M === 1) {\n return new Float64Array([1]);\n }\n\n const a_1 = 1 - a_0;\n const factor = 2 * Math.PI / (M - 1);\n\n const cos_vals = new Float64Array(M);\n for (let i = 0; i < M; ++i) {\n cos_vals[i] = a_0 - a_1 * Math.cos(i * factor);\n }\n return cos_vals;\n}\n\n/**\n * Generates a Hanning window of length M.\n * See https://numpy.org/doc/stable/reference/generated/numpy.hanning.html for more information.\n *\n * @param {number} M The length of the Hanning window to generate.\n * @returns {Float64Array} The generated Hanning window.\n */\nexport function hanning(M) {\n return generalized_cosine_window(M, 0.5);\n}\n\n\n/**\n * Generates a Hamming window of length M.\n * See https://numpy.org/doc/stable/reference/generated/numpy.hamming.html for more information.\n *\n * @param {number} M The length of the Hamming window to generate.\n * @returns {Float64Array} The generated Hamming window.\n */\nexport function hamming(M) {\n return generalized_cosine_window(M, 0.54);\n}\n\n\nconst HERTZ_TO_MEL_MAPPING = {\n \"htk\": (/** @type {number} */ freq) => 2595.0 * Math.log10(1.0 + (freq / 700.0)),\n \"kaldi\": (/** @type {number} */ freq) => 1127.0 * Math.log(1.0 + (freq / 700.0)),\n \"slaney\": (/** @type {number} */ freq, min_log_hertz = 1000.0, min_log_mel = 15.0, logstep = 27.0 / Math.log(6.4)) =>\n freq >= min_log_hertz\n ? min_log_mel + Math.log(freq / min_log_hertz) * logstep\n : 3.0 * freq / 200.0,\n}\n\n/**\n * @template {Float32Array|Float64Array|number} T \n * @param {T} freq \n * @param {string} [mel_scale]\n * @returns {T}\n */\nfunction hertz_to_mel(freq, mel_scale = \"htk\") {\n const fn = HERTZ_TO_MEL_MAPPING[mel_scale];\n if (!fn) {\n throw new Error('mel_scale should be one of \"htk\", \"slaney\" or \"kaldi\".');\n }\n\n return typeof freq === 'number' ? fn(freq) : freq.map(x => fn(x));\n}\n\nconst MEL_TO_HERTZ_MAPPING = {\n \"htk\": (/** @type {number} */ mels) => 700.0 * (10.0 ** (mels / 2595.0) - 1.0),\n \"kaldi\": (/** @type {number} */ mels) => 700.0 * (Math.exp(mels / 1127.0) - 1.0),\n \"slaney\": (/** @type {number} */ mels, min_log_hertz = 1000.0, min_log_mel = 15.0, logstep = Math.log(6.4) / 27.0) => mels >= min_log_mel\n ? min_log_hertz * Math.exp(logstep * (mels - min_log_mel))\n : 200.0 * mels / 3.0,\n}\n\n/**\n * @template {Float32Array|Float64Array|number} T \n * @param {T} mels \n * @param {string} [mel_scale]\n * @returns {T}\n */\nfunction mel_to_hertz(mels, mel_scale = \"htk\") {\n const fn = MEL_TO_HERTZ_MAPPING[mel_scale];\n if (!fn) {\n throw new Error('mel_scale should be one of \"htk\", \"slaney\" or \"kaldi\".');\n }\n\n return typeof mels === 'number' ? fn(mels) : mels.map(x => fn(x));\n}\n\n/**\n* Creates a triangular filter bank.\n*\n* Adapted from torchaudio and librosa.\n*\n* @param {Float64Array} fft_freqs Discrete frequencies of the FFT bins in Hz, of shape `(num_frequency_bins,)`.\n* @param {Float64Array} filter_freqs Center frequencies of the triangular filters to create, in Hz, of shape `(num_mel_filters,)`.\n* @returns {number[][]} of shape `(num_frequency_bins, num_mel_filters)`.\n*/\nfunction _create_triangular_filter_bank(fft_freqs, filter_freqs) {\n const filter_diff = Float64Array.from(\n { length: filter_freqs.length - 1 },\n (_, i) => filter_freqs[i + 1] - filter_freqs[i]\n );\n\n const slopes = Array.from({\n length: fft_freqs.length\n }, () => new Array(filter_freqs.length));\n\n for (let j = 0; j < fft_freqs.length; ++j) {\n const slope = slopes[j];\n for (let i = 0; i < filter_freqs.length; ++i) {\n slope[i] = filter_freqs[i] - fft_freqs[j];\n }\n }\n\n const numFreqs = filter_freqs.length - 2;\n const ret = Array.from({ length: numFreqs }, () => new Array(fft_freqs.length));\n\n for (let j = 0; j < fft_freqs.length; ++j) { // 201\n const slope = slopes[j];\n for (let i = 0; i < numFreqs; ++i) { // 80\n const down = -slope[i] / filter_diff[i];\n const up = slope[i + 2] / filter_diff[i + 1];\n ret[i][j] = Math.max(0, Math.min(down, up));\n }\n }\n return ret;\n}\n\n/**\n * Return evenly spaced numbers over a specified interval.\n * @param {number} start The starting value of the sequence.\n * @param {number} end The end value of the sequence.\n * @param {number} num Number of samples to generate.\n * @returns `num` evenly spaced samples, calculated over the interval `[start, stop]`.\n */\nfunction linspace(start, end, num) {\n const step = (end - start) / (num - 1);\n return Float64Array.from({ length: num }, (_, i) => start + step * i);\n}\n\n/**\n * Creates a frequency bin conversion matrix used to obtain a mel spectrogram. This is called a *mel filter bank*, and\n * various implementation exist, which differ in the number of filters, the shape of the filters, the way the filters\n * are spaced, the bandwidth of the filters, and the manner in which the spectrum is warped. The goal of these\n * features is to approximate the non-linear human perception of the variation in pitch with respect to the frequency.\n * @param {number} num_frequency_bins Number of frequencies used to compute the spectrogram (should be the same as in `stft`).\n * @param {number} num_mel_filters Number of mel filters to generate.\n * @param {number} min_frequency Lowest frequency of interest in Hz.\n * @param {number} max_frequency Highest frequency of interest in Hz. This should not exceed `sampling_rate / 2`.\n * @param {number} sampling_rate Sample rate of the audio waveform.\n * @param {string} [norm] If `\"slaney\"`, divide the triangular mel weights by the width of the mel band (area normalization).\n * @param {string} [mel_scale] The mel frequency scale to use, `\"htk\"` or `\"slaney\"`.\n * @param {boolean} [triangularize_in_mel_space] If this option is enabled, the triangular filter is applied in mel space rather than frequency space.\n * This should be set to `true` in order to get the same results as `torchaudio` when computing mel filters.\n * @returns {number[][]} Triangular filter bank matrix, which is a 2D array of shape (`num_frequency_bins`, `num_mel_filters`).\n * This is a projection matrix to go from a spectrogram to a mel spectrogram.\n */\nexport function mel_filter_bank(\n num_frequency_bins,\n num_mel_filters,\n min_frequency,\n max_frequency,\n sampling_rate,\n norm = null,\n mel_scale = \"htk\",\n triangularize_in_mel_space = false,\n) {\n if (norm !== null && norm !== \"slaney\") {\n throw new Error('norm must be one of null or \"slaney\"');\n }\n\n const mel_min = hertz_to_mel(min_frequency, mel_scale);\n const mel_max = hertz_to_mel(max_frequency, mel_scale);\n const mel_freqs = linspace(mel_min, mel_max, num_mel_filters + 2);\n\n let filter_freqs = mel_to_hertz(mel_freqs, mel_scale);\n let fft_freqs; // frequencies of FFT bins in Hz\n\n if (triangularize_in_mel_space) {\n const fft_bin_width = sampling_rate / (num_frequency_bins * 2);\n fft_freqs = hertz_to_mel(Float64Array.from({ length: num_frequency_bins }, (_, i) => i * fft_bin_width), mel_scale);\n filter_freqs = mel_freqs;\n } else {\n fft_freqs = linspace(0, Math.floor(sampling_rate / 2), num_frequency_bins);\n }\n\n const mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs);\n\n if (norm !== null && norm === \"slaney\") {\n // Slaney-style mel is scaled to be approx constant energy per channel\n for (let i = 0; i < num_mel_filters; ++i) {\n const filter = mel_filters[i];\n const enorm = 2.0 / (filter_freqs[i + 2] - filter_freqs[i]);\n for (let j = 0; j < num_frequency_bins; ++j) {\n // Apply this enorm to all frequency bins\n filter[j] *= enorm;\n }\n }\n }\n\n // TODO warn if there is a zero row\n\n return mel_filters;\n\n}\n\n/**\n * @template {Float32Array|Float64Array} T\n * Pads an array with a reflected version of itself on both ends.\n * @param {T} array The array to pad.\n * @param {number} left The amount of padding to add to the left.\n * @param {number} right The amount of padding to add to the right.\n * @returns {T} The padded array.\n */\nfunction padReflect(array, left, right) {\n // @ts-ignore\n const padded = new array.constructor(array.length + left + right);\n const w = array.length - 1;\n\n for (let i = 0; i < array.length; ++i) {\n padded[left + i] = array[i];\n }\n\n for (let i = 1; i <= left; ++i) {\n padded[left - i] = array[calculateReflectOffset(i, w)];\n }\n\n for (let i = 1; i <= right; ++i) {\n padded[w + left + i] = array[calculateReflectOffset(w - i, w)];\n }\n\n return padded;\n}\n\n/**\n * Helper function to compute `amplitude_to_db` and `power_to_db`.\n * @template {Float32Array|Float64Array} T\n * @param {T} spectrogram \n * @param {number} factor \n * @param {number} reference \n * @param {number} min_value \n * @param {number} db_range \n * @returns {T}\n */\nfunction _db_conversion_helper(spectrogram, factor, reference, min_value, db_range) {\n if (reference <= 0) {\n throw new Error('reference must be greater than zero');\n }\n\n if (min_value <= 0) {\n throw new Error('min_value must be greater than zero');\n }\n\n reference = Math.max(min_value, reference);\n\n const logReference = Math.log10(reference);\n for (let i = 0; i < spectrogram.length; ++i) {\n spectrogram[i] = factor * Math.log10(Math.max(min_value, spectrogram[i]) - logReference)\n }\n\n if (db_range !== null) {\n if (db_range <= 0) {\n throw new Error('db_range must be greater than zero');\n }\n const maxValue = max(spectrogram)[0] - db_range;\n for (let i = 0; i < spectrogram.length; ++i) {\n spectrogram[i] = Math.max(spectrogram[i], maxValue);\n }\n }\n\n return spectrogram;\n}\n\n/**\n * Converts an amplitude spectrogram to the decibel scale. This computes `20 * log10(spectrogram / reference)`,\n * using basic logarithm properties for numerical stability. NOTE: Operates in-place.\n * \n * The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a\n * linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.\n * This means that large variations in energy may not sound all that different if the sound is loud to begin with.\n * This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.\n * \n * @template {Float32Array|Float64Array} T\n * @param {T} spectrogram The input amplitude (mel) spectrogram.\n * @param {number} [reference=1.0] Sets the input spectrogram value that corresponds to 0 dB.\n * For example, use `np.max(spectrogram)` to set the loudest part to 0 dB. Must be greater than zero.\n * @param {number} [min_value=1e-5] The spectrogram will be clipped to this minimum value before conversion to decibels,\n * to avoid taking `log(0)`. The default of `1e-5` corresponds to a minimum of -100 dB. Must be greater than zero.\n * @param {number} [db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the\n * difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero.\n * @returns {T} The modified spectrogram in decibels.\n */\nfunction amplitude_to_db(spectrogram, reference = 1.0, min_value = 1e-5, db_range = null) {\n return _db_conversion_helper(spectrogram, 20.0, reference, min_value, db_range);\n}\n\n/**\n * Converts a power spectrogram to the decibel scale. This computes `10 * log10(spectrogram / reference)`,\n * using basic logarithm properties for numerical stability. NOTE: Operates in-place.\n * \n * The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a\n * linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.\n * This means that large variations in energy may not sound all that different if the sound is loud to begin with.\n * This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.\n * \n * Based on the implementation of `librosa.power_to_db`.\n * \n * @template {Float32Array|Float64Array} T\n * @param {T} spectrogram The input power (mel) spectrogram. Note that a power spectrogram has the amplitudes squared!\n * @param {number} [reference=1.0] Sets the input spectrogram value that corresponds to 0 dB.\n * For example, use `np.max(spectrogram)` to set the loudest part to 0 dB. Must be greater than zero.\n * @param {number} [min_value=1e-10] The spectrogram will be clipped to this minimum value before conversion to decibels,\n * to avoid taking `log(0)`. The default of `1e-10` corresponds to a minimum of -100 dB. Must be greater than zero.\n * @param {number} [db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the\n * difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero.\n * @returns {T} The modified spectrogram in decibels.\n */\nfunction power_to_db(spectrogram, reference = 1.0, min_value = 1e-10, db_range = null) {\n return _db_conversion_helper(spectrogram, 10.0, reference, min_value, db_range);\n}\n\n/**\n * Calculates a spectrogram over one waveform using the Short-Time Fourier Transform.\n * \n * This function can create the following kinds of spectrograms:\n * - amplitude spectrogram (`power = 1.0`)\n * - power spectrogram (`power = 2.0`)\n * - complex-valued spectrogram (`power = None`)\n * - log spectrogram (use `log_mel` argument)\n * - mel spectrogram (provide `mel_filters`)\n * - log-mel spectrogram (provide `mel_filters` and `log_mel`)\n *\n * In this implementation, the window is assumed to be zero-padded to have the same size as the analysis frame.\n * A padded window can be obtained from `window_function()`. The FFT input buffer may be larger than the analysis frame, \n * typically the next power of two.\n * \n * @param {Float32Array|Float64Array} waveform The input waveform of shape `(length,)`. This must be a single real-valued, mono waveform.\n * @param {Float32Array|Float64Array} window The windowing function to apply of shape `(frame_length,)`, including zero-padding if necessary. The actual window length may be\n * shorter than `frame_length`, but we're assuming the array has already been zero-padded.\n * @param {number} frame_length The length of the analysis frames in samples (a.k.a., `fft_length`).\n * @param {number} hop_length The stride between successive analysis frames in samples.\n * @param {Object} options\n * @param {number} [options.fft_length=null] The size of the FFT buffer in samples. This determines how many frequency bins the spectrogram will have.\n * For optimal speed, this should be a power of two. If `null`, uses `frame_length`.\n * @param {number} [options.power=1.0] If 1.0, returns the amplitude spectrogram. If 2.0, returns the power spectrogram. If `null`, returns complex numbers.\n * @param {boolean} [options.center=true] Whether to pad the waveform so that frame `t` is centered around time `t * hop_length`. If `false`, frame\n * `t` will start at time `t * hop_length`.\n * @param {string} [options.pad_mode=\"reflect\"] Padding mode used when `center` is `true`. Possible values are: `\"constant\"` (pad with zeros),\n * `\"edge\"` (pad with edge values), `\"reflect\"` (pads with mirrored values).\n * @param {boolean} [options.onesided=true] If `true`, only computes the positive frequencies and returns a spectrogram containing `fft_length // 2 + 1`\n * frequency bins. If `false`, also computes the negative frequencies and returns `fft_length` frequency bins.\n * @param {number} [options.preemphasis=null] Coefficient for a low-pass filter that applies pre-emphasis before the DFT.\n * @param {number[][]} [options.mel_filters=null] The mel filter bank of shape `(num_freq_bins, num_mel_filters)`.\n * If supplied, applies this filter bank to create a mel spectrogram.\n * @param {number} [options.mel_floor=1e-10] Minimum value of mel frequency banks.\n * @param {string} [options.log_mel=null] How to convert the spectrogram to log scale. Possible options are:\n * `null` (don't convert), `\"log\"` (take the natural logarithm) `\"log10\"` (take the base-10 logarithm), `\"dB\"` (convert to decibels).\n * Can only be used when `power` is not `null`.\n * @param {number} [options.reference=1.0] Sets the input spectrogram value that corresponds to 0 dB. For example, use `max(spectrogram)[0]` to set\n * the loudest part to 0 dB. Must be greater than zero.\n * @param {number} [options.min_value=1e-10] The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking `log(0)`.\n * For a power spectrogram, the default of `1e-10` corresponds to a minimum of -100 dB. For an amplitude spectrogram, the value `1e-5` corresponds to -100 dB.\n * Must be greater than zero.\n * @param {number} [options.db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the\n * peak value and the smallest value will never be more than 80 dB. Must be greater than zero.\n * @param {boolean} [options.remove_dc_offset=null] Subtract mean from waveform on each frame, applied before pre-emphasis. This should be set to `true` in\n * order to get the same results as `torchaudio.compliance.kaldi.fbank` when computing mel filters.\n * @param {number} [options.max_num_frames=null] If provided, limits the number of frames to compute to this value.\n * @param {number} [options.min_num_frames=null] If provided, ensures the number of frames to compute is at least this value.\n * @param {boolean} [options.do_pad=true] If `true`, pads the output spectrogram to have `max_num_frames` frames.\n * @param {boolean} [options.transpose=false] If `true`, the returned spectrogram will have shape `(num_frames, num_frequency_bins/num_mel_filters)`. If `false`, the returned spectrogram will have shape `(num_frequency_bins/num_mel_filters, num_frames)`.\n * @returns {Promise} Spectrogram of shape `(num_frequency_bins, length)` (regular spectrogram) or shape `(num_mel_filters, length)` (mel spectrogram).\n */\nexport async function spectrogram(\n waveform,\n window,\n frame_length,\n hop_length,\n {\n fft_length = null,\n power = 1.0,\n center = true,\n pad_mode = \"reflect\",\n onesided = true,\n preemphasis = null,\n mel_filters = null,\n mel_floor = 1e-10,\n log_mel = null,\n reference = 1.0,\n min_value = 1e-10,\n db_range = null,\n remove_dc_offset = null,\n\n // Custom parameters for efficiency reasons\n min_num_frames = null,\n max_num_frames = null,\n do_pad = true,\n transpose = false,\n } = {}\n) {\n const window_length = window.length;\n if (fft_length === null) {\n fft_length = frame_length;\n }\n if (frame_length > fft_length) {\n throw Error(`frame_length (${frame_length}) may not be larger than fft_length (${fft_length})`)\n }\n\n if (window_length !== frame_length) {\n throw new Error(`Length of the window (${window_length}) must equal frame_length (${frame_length})`);\n }\n\n if (hop_length <= 0) {\n throw new Error(\"hop_length must be greater than zero\");\n }\n\n if (power === null && mel_filters !== null) {\n throw new Error(\n \"You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. \" +\n \"Specify `power` to fix this issue.\"\n );\n }\n\n if (center) {\n if (pad_mode !== 'reflect') {\n throw new Error(`pad_mode=\"${pad_mode}\" not implemented yet.`)\n }\n const half_window = Math.floor((fft_length - 1) / 2) + 1;\n waveform = padReflect(waveform, half_window, half_window);\n }\n\n // split waveform into frames of frame_length size\n let num_frames = Math.floor(1 + Math.floor((waveform.length - frame_length) / hop_length))\n if (min_num_frames !== null && num_frames < min_num_frames) {\n num_frames = min_num_frames\n }\n const num_frequency_bins = onesided ? Math.floor(fft_length / 2) + 1 : fft_length\n\n let d1 = num_frames;\n let d1Max = num_frames;\n\n // If maximum number of frames is provided, we must either pad or truncate\n if (max_num_frames !== null) {\n if (max_num_frames > num_frames) { // input is too short, so we pad\n if (do_pad) {\n d1Max = max_num_frames;\n }\n } else { // input is too long, so we truncate\n d1Max = d1 = max_num_frames;\n }\n }\n\n // Preallocate arrays to store output.\n const fft = new FFT(fft_length);\n const inputBuffer = new Float64Array(fft_length);\n const outputBuffer = new Float64Array(fft.outputBufferSize);\n const transposedMagnitudeData = new Float32Array(num_frequency_bins * d1Max);\n\n for (let i = 0; i < d1; ++i) {\n // Populate buffer with waveform data\n const offset = i * hop_length;\n const buffer_size = Math.min(waveform.length - offset, frame_length);\n if (buffer_size !== frame_length) {\n // The full buffer is not needed, so we need to reset it (avoid overflow from previous iterations)\n // NOTE: We don't need to reset the buffer if it's full since we overwrite the first\n // `frame_length` values and the rest (`fft_length - frame_length`) remains zero.\n inputBuffer.fill(0, 0, frame_length);\n }\n\n for (let j = 0; j < buffer_size; ++j) {\n inputBuffer[j] = waveform[offset + j];\n }\n\n if (remove_dc_offset) {\n let sum = 0;\n for (let j = 0; j < buffer_size; ++j) {\n sum += inputBuffer[j];\n }\n const mean = sum / buffer_size;\n for (let j = 0; j < buffer_size; ++j) {\n inputBuffer[j] -= mean;\n }\n }\n\n if (preemphasis !== null) {\n // Done in reverse to avoid copies and distructive modification\n for (let j = buffer_size - 1; j >= 1; --j) {\n inputBuffer[j] -= preemphasis * inputBuffer[j - 1];\n }\n inputBuffer[0] *= 1 - preemphasis;\n }\n\n // Apply window function\n for (let j = 0; j < window.length; ++j) {\n inputBuffer[j] *= window[j];\n }\n\n fft.realTransform(outputBuffer, inputBuffer);\n\n // compute magnitudes\n for (let j = 0; j < num_frequency_bins; ++j) {\n const j2 = j << 1;\n\n // NOTE: We transpose the data here to avoid doing it later\n transposedMagnitudeData[j * d1Max + i] = outputBuffer[j2] ** 2 + outputBuffer[j2 + 1] ** 2;\n }\n }\n\n if (power !== null && power !== 2) {\n // slight optimization to not sqrt\n const pow = 2 / power; // we use 2 since we already squared\n for (let i = 0; i < transposedMagnitudeData.length; ++i) {\n transposedMagnitudeData[i] **= pow;\n }\n }\n\n // TODO: What if `mel_filters` is null?\n const num_mel_filters = mel_filters.length;\n\n // Perform matrix muliplication:\n // mel_spec = mel_filters @ magnitudes.T\n // - mel_filters.shape=(80, 201)\n // - magnitudes.shape=(3000, 201) => magnitudes.T.shape=(201, 3000)\n // - mel_spec.shape=(80, 3000)\n let mel_spec = await matmul(\n // TODO: Make `mel_filters` a Tensor during initialization\n new Tensor('float32', mel_filters.flat(), [num_mel_filters, num_frequency_bins]),\n new Tensor('float32', transposedMagnitudeData, [num_frequency_bins, d1Max]),\n );\n if (transpose) {\n mel_spec = mel_spec.transpose(1, 0);\n }\n\n const mel_spec_data = /** @type {Float32Array} */(mel_spec.data);\n for (let i = 0; i < mel_spec_data.length; ++i) {\n mel_spec_data[i] = Math.max(mel_floor, mel_spec_data[i]);\n }\n\n if (power !== null && log_mel !== null) {\n const o = Math.min(mel_spec_data.length, d1 * num_mel_filters);\n // NOTE: operates in-place\n switch (log_mel) {\n case 'log':\n for (let i = 0; i < o; ++i) {\n mel_spec_data[i] = Math.log(mel_spec_data[i]);\n }\n break;\n case 'log10':\n for (let i = 0; i < o; ++i) {\n mel_spec_data[i] = Math.log10(mel_spec_data[i]);\n }\n break;\n case 'dB':\n if (power === 1.0) {\n amplitude_to_db(mel_spec_data, reference, min_value, db_range);\n } else if (power === 2.0) {\n power_to_db(mel_spec_data, reference, min_value, db_range);\n } else {\n throw new Error(`Cannot use log_mel option '${log_mel}' with power ${power}`)\n }\n break;\n default:\n throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${log_mel}'`);\n }\n }\n\n return mel_spec;\n}\n\n/**\n * Returns an array containing the specified window.\n * @param {number} window_length The length of the window in samples.\n * @param {string} name The name of the window function.\n * @param {Object} options Additional options.\n * @param {boolean} [options.periodic=true] Whether the window is periodic or symmetric.\n * @param {number} [options.frame_length=null] The length of the analysis frames in samples.\n * Provide a value for `frame_length` if the window is smaller than the frame length, so that it will be zero-padded.\n * @param {boolean} [options.center=true] Whether to center the window inside the FFT buffer. Only used when `frame_length` is provided.\n * @returns {Float64Array} The window of shape `(window_length,)` or `(frame_length,)`.\n */\nexport function window_function(window_length, name, {\n periodic = true,\n frame_length = null,\n center = true,\n} = {}) {\n const length = periodic ? window_length + 1 : window_length;\n let window;\n switch (name) {\n case 'boxcar':\n window = new Float64Array(length).fill(1.0);\n break;\n case 'hann':\n case 'hann_window':\n window = hanning(length);\n break;\n case 'hamming':\n window = hamming(length);\n break;\n case 'povey':\n window = hanning(length).map(x => Math.pow(x, 0.85));\n break;\n default:\n throw new Error(`Unknown window type ${name}.`);\n }\n if (periodic) {\n window = window.subarray(0, window_length);\n }\n if (frame_length === null) {\n return window;\n }\n if (window_length > frame_length) {\n throw new Error(`Length of the window (${window_length}) may not be larger than frame_length (${frame_length})`);\n }\n\n return window;\n}\n","\nexport const GITHUB_ISSUE_URL = 'https://github.com/huggingface/transformers.js/issues/new/choose';","\n/**\n * @file Core utility functions/classes for Transformers.js.\n * \n * These are only used internally, meaning an end-user shouldn't\n * need to access anything here.\n * \n * @module utils/core\n */\n\n/**\n * Helper function to dispatch progress callbacks.\n *\n * @param {Function} progress_callback The progress callback function to dispatch.\n * @param {any} data The data to pass to the progress callback function.\n * @returns {void}\n * @private\n */\nexport function dispatchCallback(progress_callback, data) {\n if (progress_callback) progress_callback(data);\n}\n\n/**\n * Reverses the keys and values of an object.\n *\n * @param {Object} data The object to reverse.\n * @returns {Object} The reversed object.\n * @see https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript\n */\nexport function reverseDictionary(data) {\n // https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript\n return Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key]));\n}\n\n/**\n * Escapes regular expression special characters from a string by replacing them with their escaped counterparts.\n *\n * @param {string} string The string to escape.\n * @returns {string} The escaped string.\n */\nexport function escapeRegExp(string) {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); // $& means the whole matched string\n}\n\n/**\n * Check if a value is a typed array.\n * @param {*} val The value to check.\n * @returns {boolean} True if the value is a `TypedArray`, false otherwise.\n * \n * Adapted from https://stackoverflow.com/a/71091338/13989043\n */\nexport function isTypedArray(val) {\n return val?.prototype?.__proto__?.constructor?.name === 'TypedArray';\n}\n\n\n/**\n * Check if a value is an integer.\n * @param {*} x The value to check.\n * @returns {boolean} True if the value is a string, false otherwise.\n */\nexport function isIntegralNumber(x) {\n return Number.isInteger(x) || typeof x === 'bigint'\n}\n\n/**\n * Calculates the dimensions of a nested array.\n *\n * @param {any[]} arr The nested array to calculate dimensions for.\n * @returns {number[]} An array containing the dimensions of the input array.\n */\nexport function calculateDimensions(arr) {\n const dimensions = [];\n let current = arr;\n while (Array.isArray(current)) {\n dimensions.push(current.length);\n current = current[0];\n }\n return dimensions;\n}\n\n/**\n * Replicate python's .pop() method for objects.\n * @param {Object} obj The object to pop from.\n * @param {string} key The key to pop.\n * @param {*} defaultValue The default value to return if the key does not exist.\n * @returns {*} The value of the popped key.\n * @throws {Error} If the key does not exist and no default value is provided.\n */\nexport function pop(obj, key, defaultValue = undefined) {\n const value = obj[key];\n if (value !== undefined) {\n delete obj[key];\n return value;\n }\n if (defaultValue === undefined) {\n throw Error(`Key ${key} does not exist in object.`)\n }\n return defaultValue;\n}\n\n/**\n * Efficiently merge arrays, creating a new copy.\n * Adapted from https://stackoverflow.com/a/6768642/13989043\n * @param {Array[]} arrs Arrays to merge.\n * @returns {Array} The merged array.\n */\nexport function mergeArrays(...arrs) {\n return Array.prototype.concat.apply([], arrs);\n}\n\n/**\n * Compute the Cartesian product of given arrays\n * @param {...Array} a Arrays to compute the product\n * @returns {Array} Returns the computed Cartesian product as an array\n * @private\n */\nexport function product(...a) {\n // Cartesian product of items\n // Adapted from https://stackoverflow.com/a/43053803\n return a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e])));\n}\n\n/**\n * Calculates the index offset for a given index and window size.\n * @param {number} i The index.\n * @param {number} w The window size.\n * @returns {number} The index offset.\n */\nexport function calculateReflectOffset(i, w) {\n return Math.abs((i + w) % (2 * w) - w);\n}\n\n/**\n * \n * @param {Object} o \n * @param {string[]} props \n * @returns {Object}\n */\nexport function pick(o, props) {\n return Object.assign(\n {},\n ...props.map((prop) => {\n if (o[prop] !== undefined) {\n return { [prop]: o[prop] };\n }\n })\n );\n}\n\n/**\n * Calculate the length of a string, taking multi-byte characters into account.\n * This mimics the behavior of Python's `len` function.\n * @param {string} s The string to calculate the length of. \n * @returns {number} The length of the string.\n */\nexport function len(s) {\n let length = 0;\n for (const c of s) ++length;\n return length;\n}\n","\n/**\n * @file Custom data structures.\n * \n * These are only used internally, meaning an end-user shouldn't\n * need to access anything here.\n * \n * @module utils/data-structures\n */\n\n\n/**\n * Efficient Heap-based Implementation of a Priority Queue.\n * It uses an array-based binary heap, where the root is at index `0`, and the\n * children of node `i` are located at indices `2i + 1` and `2i + 2`, respectively.\n * \n * Adapted from the following sources:\n * - https://stackoverflow.com/a/42919752/13989043 (original)\n * - https://github.com/belladoreai/llama-tokenizer-js (minor improvements)\n */\nexport class PriorityQueue {\n\n /**\n * Create a new PriorityQueue.\n * @param {function(any, any): boolean} comparator Comparator function to determine priority. Defaults to a MaxHeap.\n */\n constructor(comparator = (a, b) => a > b, maxSize = Infinity) {\n this._heap = [];\n this._comparator = comparator;\n this._maxSize = maxSize;\n }\n\n /**\n * The size of the queue\n */\n get size() {\n return this._heap.length;\n }\n\n /**\n * Check if the queue is empty.\n * @returns {boolean} `true` if the queue is empty, `false` otherwise.\n */\n isEmpty() {\n return this.size === 0;\n }\n\n /**\n * Return the element with the highest priority in the queue.\n * @returns {any} The highest priority element in the queue.\n */\n peek() {\n return this._heap[0];\n }\n\n /**\n * Add one or more elements to the queue.\n * @param {...any} values The values to push into the queue.\n * @returns {number} The new size of the queue.\n */\n push(...values) {\n return this.extend(values);\n }\n\n /**\n * Add multiple elements to the queue.\n * @param {any[]} values The values to push into the queue.\n * @returns {number} The new size of the queue.\n */\n extend(values) {\n for (const value of values) {\n if (this.size < this._maxSize) {\n this._heap.push(value);\n this._siftUp();\n } else {\n // Get index of value with the lowest priority\n const smallest = this._smallest();\n\n // If the new value has higher priority than the smallest value in the heap\n // then replace the smallest value with the new value and update the heap\n if (this._comparator(value, this._heap[smallest])) {\n this._heap[smallest] = value;\n this._siftUpFrom(smallest);\n }\n }\n }\n return this.size;\n }\n\n /**\n * Remove and return the element with the highest priority in the queue.\n * @returns {any} The element with the highest priority in the queue.\n */\n pop() {\n const poppedValue = this.peek();\n const bottom = this.size - 1;\n if (bottom > 0) {\n this._swap(0, bottom);\n }\n this._heap.pop();\n this._siftDown();\n return poppedValue;\n }\n\n /**\n * Replace the element with the highest priority in the queue with a new value.\n * @param {*} value The new value.\n * @returns {*} The replaced value.\n */\n replace(value) {\n const replacedValue = this.peek();\n this._heap[0] = value;\n this._siftDown();\n return replacedValue;\n }\n\n /**\n * Compute the index for the parent of the node at index `i`.\n * @param {number} i The index of the node to get the parent of.\n * @returns {number} The index of the parent node.\n * @private\n */\n _parent(i) {\n return ((i + 1) >>> 1) - 1;\n }\n\n /**\n * Compute the index for the left child of the node at index `i`.\n * @param {number} i The index of the node to get the left child of.\n * @returns {number} The index of the left child.\n * @private\n */\n _left(i) {\n return (i << 1) + 1;\n }\n\n /**\n * Compute the index for the right child of the node at index `i`.\n * @param {number} i The index of the node to get the right child of.\n * @returns {number} The index of the right child.\n * @private\n */\n _right(i) {\n return (i + 1) << 1;\n }\n\n /**\n * Check if the element at index `i` is greater than the element at index `j`.\n * @param {number} i The index of the first element to compare.\n * @param {number} j The index of the second element to compare.\n * @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.\n * @private\n */\n _greater(i, j) {\n return this._comparator(this._heap[i], this._heap[j]);\n }\n\n /**\n * Swap the elements at indices `i` and `j`.\n * @param {number} i The index of the first element to swap.\n * @param {number} j The index of the second element to swap.\n * @private\n */\n _swap(i, j) {\n const temp = this._heap[i];\n this._heap[i] = this._heap[j];\n this._heap[j] = temp;\n }\n\n /**\n * Maintain the heap property by updating positions in the heap,\n * starting at the last element and moving up the heap.\n * @private\n */\n _siftUp() {\n this._siftUpFrom(this.size - 1);\n }\n\n /**\n * Helper function to sift up from a given node.\n * @param {number} node The index of the node to start sifting up from.\n */\n _siftUpFrom(node) {\n while (node > 0 && this._greater(node, this._parent(node))) {\n this._swap(node, this._parent(node));\n node = this._parent(node);\n }\n }\n\n /**\n * Maintain the heap property by updating positions in the heap,\n * starting at the first element and moving down the heap.\n * @private\n */\n _siftDown() {\n let node = 0;\n while (\n (this._left(node) < this.size && this._greater(this._left(node), node)) ||\n (this._right(node) < this.size && this._greater(this._right(node), node))\n ) {\n const maxChild = (this._right(node) < this.size && this._greater(this._right(node), this._left(node)))\n ? this._right(node)\n : this._left(node);\n this._swap(node, maxChild);\n node = maxChild;\n }\n }\n\n /**\n * Get the index of the smallest element in the heap. Since we use an array-based heap,\n * the index can be computed without needing to traverse the heap.\n * @private\n */\n _smallest() {\n return (2 ** (Math.floor(Math.log2(this.size))) - 1);\n }\n}\n\n/**\n * A trie structure to efficiently store and search for strings.\n */\nexport class CharTrie {\n constructor() {\n this.root = CharTrieNode.default();\n }\n\n /**\n * Adds one or more `texts` to the trie.\n * @param {string[]} texts The strings to add to the trie.\n */\n extend(texts) {\n for (const text of texts) {\n this.push(text);\n }\n }\n\n /**\n * Adds text to the trie.\n * @param {string} text The string to add to the trie.\n */\n push(text) {\n let node = this.root;\n for (const ch of text) {\n let child = node.children.get(ch);\n if (child === undefined) {\n child = CharTrieNode.default();\n node.children.set(ch, child);\n }\n node = child;\n }\n node.isLeaf = true;\n }\n\n /**\n * Searches the trie for all strings with a common prefix of `text`.\n * @param {string} text The common prefix to search for.\n * @yields {string} Each string in the trie that has `text` as a prefix.\n */\n *commonPrefixSearch(text) {\n let node = this.root;\n if (node === undefined) return;\n\n let prefix = \"\";\n for (const ch of text) {\n prefix += ch;\n node = node.children.get(ch);\n if (node === undefined) return;\n if (node.isLeaf) {\n yield prefix;\n }\n }\n }\n}\n\n/**\n * Represents a node in a character trie.\n */\nclass CharTrieNode {\n /**\n * Create a new CharTrieNode.\n * @param {boolean} isLeaf Whether the node is a leaf node or not.\n * @param {Map} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.\n */\n constructor(isLeaf, children) {\n this.isLeaf = isLeaf;\n this.children = children;\n }\n\n /**\n * Returns a new `CharTrieNode` instance with default values.\n * @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map.\n */\n static default() {\n return new CharTrieNode(false, new Map());\n }\n}\n\n/**\n * A lattice data structure to be used for tokenization.\n */\nexport class TokenLattice {\n /**\n * Creates a new TokenLattice instance.\n *\n * @param {string} sentence The input sentence to be tokenized.\n * @param {number} bosTokenId The beginning-of-sequence token ID.\n * @param {number} eosTokenId The end-of-sequence token ID.\n */\n constructor(sentence, bosTokenId, eosTokenId) {\n this.chars = Array.from(sentence);\n this.len = this.chars.length;\n this.bosTokenId = bosTokenId;\n this.eosTokenId = eosTokenId;\n this.nodes = [];\n this.beginNodes = Array.from({ length: this.len + 1 }, () => []);\n this.endNodes = Array.from({ length: this.len + 1 }, () => []);\n\n const bos = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0.0);\n const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0.0);\n this.nodes.push(bos.clone());\n this.nodes.push(eos.clone());\n this.beginNodes[this.len].push(eos);\n this.endNodes[0].push(bos);\n }\n\n /**\n * Inserts a new token node into the token lattice.\n *\n * @param {number} pos The starting position of the token.\n * @param {number} length The length of the token.\n * @param {number} score The score of the token.\n * @param {number} tokenId The token ID of the token.\n */\n insert(pos, length, score, tokenId) {\n const nodeId = this.nodes.length;\n const node = new TokenLatticeNode(tokenId, nodeId, pos, length, score);\n this.beginNodes[pos].push(node);\n this.endNodes[pos + length].push(node);\n this.nodes.push(node);\n }\n\n /**\n * Implements the Viterbi algorithm to compute the most likely sequence of tokens.\n *\n * @returns {TokenLatticeNode[]} The most likely sequence of tokens.\n */\n viterbi() {\n const len = this.len;\n let pos = 0;\n while (pos <= len) {\n if (this.beginNodes[pos].length == 0) {\n return [];\n }\n for (let rnode of this.beginNodes[pos]) {\n rnode.prev = null;\n let bestScore = 0.0;\n let bestNode = null;\n for (let lnode of this.endNodes[pos]) {\n const score = lnode.backtraceScore + rnode.score;\n if (bestNode === null || score > bestScore) {\n bestNode = lnode.clone();\n bestScore = score;\n }\n }\n\n if (bestNode !== null) {\n rnode.prev = bestNode;\n rnode.backtraceScore = bestScore;\n } else {\n return [];\n }\n }\n ++pos;\n }\n\n const results = [];\n const root = this.beginNodes[len][0];\n const prev = root.prev;\n if (prev === null) {\n return [];\n }\n\n let node = prev.clone();\n while (node.prev !== null) {\n results.push(node.clone());\n const n = node.clone();\n node = n.prev.clone();\n }\n\n results.reverse();\n return results;\n }\n\n /**\n * @param {TokenLatticeNode} node\n * @returns {string} The array of nodes representing the most likely sequence of tokens.\n */\n piece(node) {\n return this.chars.slice(node.pos, node.pos + node.length).join('');\n }\n\n /**\n * @returns {string[]} The most likely sequence of tokens.\n */\n tokens() {\n const nodes = this.viterbi();\n return nodes.map(x => this.piece(x));\n }\n\n /**\n * @returns {number[]} The most likely sequence of token ids.\n */\n tokenIds() {\n const nodes = this.viterbi();\n return nodes.map(x => x.tokenId);\n }\n}\nclass TokenLatticeNode {\n /**\n * Represents a node in a token lattice for a given sentence.\n * @param {number} tokenId The ID of the token associated with this node.\n * @param {number} nodeId The ID of this node.\n * @param {number} pos The starting position of the token in the sentence.\n * @param {number} length The length of the token.\n * @param {number} score The score associated with the token.\n */\n constructor(tokenId, nodeId, pos, length, score) {\n this.tokenId = tokenId;\n this.nodeId = nodeId;\n this.pos = pos;\n this.length = length;\n this.score = score;\n this.prev = null;\n this.backtraceScore = 0.0;\n }\n\n /**\n * Returns a clone of this node.\n * @returns {TokenLatticeNode} A clone of this node.\n */\n clone() {\n const n = new TokenLatticeNode(this.tokenId, this.nodeId, this.pos, this.length, this.score);\n n.prev = this.prev;\n n.backtraceScore = this.backtraceScore;\n return n;\n }\n}\n","\n/**\n * The list of devices supported by Transformers.js\n */\nexport const DEVICE_TYPES = Object.freeze({\n auto: 'auto', // Auto-detect based on device and environment\n gpu: 'gpu', // Auto-detect GPU\n cpu: 'cpu', // CPU\n wasm: 'wasm', // WebAssembly\n webgpu: 'webgpu', // WebGPU\n cuda: 'cuda', // CUDA\n dml: 'dml', // DirectML\n\n webnn: 'webnn', // WebNN (default)\n 'webnn-npu': 'webnn-npu', // WebNN NPU\n 'webnn-gpu': 'webnn-gpu', // WebNN GPU\n 'webnn-cpu': 'webnn-cpu', // WebNN CPU\n});\n\n/**\n * @typedef {keyof typeof DEVICE_TYPES} DeviceType\n */\n","import { apis } from \"../env.js\";\n\nimport { DEVICE_TYPES } from \"./devices.js\";\n\n// TODO: Use the adapter from `env.backends.onnx.webgpu.adapter` to check for `shader-f16` support,\n// when available in https://github.com/microsoft/onnxruntime/pull/19940.\n// For more information, see https://github.com/microsoft/onnxruntime/pull/19857#issuecomment-1999984753\n\n/**\n * Checks if WebGPU fp16 support is available in the current environment.\n */\nexport const isWebGpuFp16Supported = (function () {\n /** @type {boolean} */\n let cachedResult;\n\n return async function () {\n if (cachedResult === undefined) {\n if (!apis.IS_WEBGPU_AVAILABLE) {\n cachedResult = false;\n } else {\n try {\n const adapter = await navigator.gpu.requestAdapter();\n cachedResult = adapter.features.has('shader-f16');\n } catch (e) {\n cachedResult = false;\n }\n }\n }\n return cachedResult;\n };\n})();\n\nexport const DATA_TYPES = Object.freeze({\n fp32: 'fp32',\n fp16: 'fp16',\n q8: 'q8',\n int8: 'int8',\n uint8: 'uint8',\n q4: 'q4',\n bnb4: 'bnb4',\n q4f16: 'q4f16', // fp16 model with int4 block weight quantization\n});\n/** @typedef {keyof typeof DATA_TYPES} DataType */\n\nexport const DEFAULT_DEVICE_DTYPE_MAPPING = Object.freeze({\n // NOTE: If not specified, will default to fp32\n [DEVICE_TYPES.wasm]: DATA_TYPES.q8,\n});\n\n/** @type {Record} */\nexport const DEFAULT_DTYPE_SUFFIX_MAPPING = Object.freeze({\n [DATA_TYPES.fp32]: '',\n [DATA_TYPES.fp16]: '_fp16',\n [DATA_TYPES.int8]: '_int8',\n [DATA_TYPES.uint8]: '_uint8',\n [DATA_TYPES.q8]: '_quantized',\n [DATA_TYPES.q4]: '_q4',\n [DATA_TYPES.q4f16]: '_q4f16',\n [DATA_TYPES.bnb4]: '_bnb4',\n});\n","\n/**\n * A base class for creating callable objects.\n * See [here](https://stackoverflow.com/q/76073890) for more information.\n * \n * @type {new () => {(...args: any[]): any, _call(...args: any[]): any}}\n */\nexport const Callable = /** @type {any} */ (class {\n /**\n * Creates a new instance of the Callable class.\n */\n constructor() {\n /**\n * Creates a closure that delegates to a private method '_call' with the given arguments.\n * @type {any}\n * @param {...any} args Zero or more arguments to pass to the '_call' method.\n * @returns {*} The result of calling the '_call' method.\n */\n let closure = function (...args) {\n return closure._call(...args)\n }\n return Object.setPrototypeOf(closure, new.target.prototype)\n }\n\n /**\n * This method should be implemented in subclasses to provide the\n * functionality of the callable object.\n *\n * @param {any[]} args\n * @throws {Error} If the subclass does not implement the `_call` method.\n */\n _call(...args) {\n throw Error('Must implement _call method in subclass')\n }\n});\n","\n/**\n * @file Utility functions to interact with the Hugging Face Hub (https://huggingface.co/models)\n * \n * @module utils/hub\n */\n\nimport fs from 'fs';\nimport path from 'path';\n\nimport { env } from '../env.js';\nimport { dispatchCallback } from './core.js';\n\n/**\n * @typedef {Object} PretrainedOptions Options for loading a pretrained model. \n * @property {function} [progress_callback=null] If specified, this function will be called during model construction, to provide the user with progress updates.\n * @property {import('../configs.js').PretrainedConfig} [config=null] Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when:\n * - The model is a model provided by the library (loaded with the *model id* string of a pretrained model).\n * - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a configuration JSON file named *config.json* is found in the directory.\n * @property {string} [cache_dir=null] Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.\n * @property {boolean} [local_files_only=false] Whether or not to only look at local files (e.g., not try downloading the model).\n * @property {string} [revision='main'] The specific model version to use. It can be a branch name, a tag name, or a commit id,\n * since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git.\n * NOTE: This setting is ignored for local requests.\n */\n\n/**\n * @typedef {Object} ModelSpecificPretrainedOptions Options for loading a pretrained model.\n * @property {string} [subfolder='onnx'] In case the relevant files are located inside a subfolder of the model repo on huggingface.co,\n * you can specify the folder name here.\n * @property {string} [model_file_name=null] If specified, load the model with this name (excluding the .onnx suffix). Currently only valid for encoder- or decoder-only models.\n * @property {import(\"./devices.js\").DeviceType|Record} [device=null] The device to run the model on. If not specified, the device will be chosen from the environment settings.\n * @property {import(\"./dtypes.js\").DataType|Record} [dtype=null] The data type to use for the model. If not specified, the data type will be chosen from the environment settings.\n * @property {boolean|Record} [use_external_data_format=false] Whether to load the model using the external data format (used for models >= 2GB in size).\n * @property {import('onnxruntime-common').InferenceSession.SessionOptions} [session_options] (Optional) User-specified session options passed to the runtime. If not provided, suitable defaults will be chosen.\n */\n\n/**\n * @typedef {PretrainedOptions & ModelSpecificPretrainedOptions} PretrainedModelOptions Options for loading a pretrained model.\n */\n\n/**\n * Mapping from file extensions to MIME types.\n */\nconst CONTENT_TYPE_MAP = {\n 'txt': 'text/plain',\n 'html': 'text/html',\n 'css': 'text/css',\n 'js': 'text/javascript',\n 'json': 'application/json',\n 'png': 'image/png',\n 'jpg': 'image/jpeg',\n 'jpeg': 'image/jpeg',\n 'gif': 'image/gif',\n}\nclass FileResponse {\n\n /**\n * Creates a new `FileResponse` object.\n * @param {string|URL} filePath\n */\n constructor(filePath) {\n this.filePath = filePath;\n this.headers = new Headers();\n\n this.exists = fs.existsSync(filePath);\n if (this.exists) {\n this.status = 200;\n this.statusText = 'OK';\n\n let stats = fs.statSync(filePath);\n this.headers.set('content-length', stats.size.toString());\n\n this.updateContentType();\n\n let self = this;\n this.body = new ReadableStream({\n start(controller) {\n self.arrayBuffer().then(buffer => {\n controller.enqueue(new Uint8Array(buffer));\n controller.close();\n })\n }\n });\n } else {\n this.status = 404;\n this.statusText = 'Not Found';\n this.body = null;\n }\n }\n\n /**\n * Updates the 'content-type' header property of the response based on the extension of\n * the file specified by the filePath property of the current object.\n * @returns {void}\n */\n updateContentType() {\n // Set content-type header based on file extension\n const extension = this.filePath.toString().split('.').pop().toLowerCase();\n this.headers.set('content-type', CONTENT_TYPE_MAP[extension] ?? 'application/octet-stream');\n }\n\n /**\n * Clone the current FileResponse object.\n * @returns {FileResponse} A new FileResponse object with the same properties as the current object.\n */\n clone() {\n let response = new FileResponse(this.filePath);\n response.exists = this.exists;\n response.status = this.status;\n response.statusText = this.statusText;\n response.headers = new Headers(this.headers);\n return response;\n }\n\n /**\n * Reads the contents of the file specified by the filePath property and returns a Promise that\n * resolves with an ArrayBuffer containing the file's contents.\n * @returns {Promise} A Promise that resolves with an ArrayBuffer containing the file's contents.\n * @throws {Error} If the file cannot be read.\n */\n async arrayBuffer() {\n const data = await fs.promises.readFile(this.filePath);\n return data.buffer;\n }\n\n /**\n * Reads the contents of the file specified by the filePath property and returns a Promise that\n * resolves with a Blob containing the file's contents.\n * @returns {Promise} A Promise that resolves with a Blob containing the file's contents.\n * @throws {Error} If the file cannot be read.\n */\n async blob() {\n const data = await fs.promises.readFile(this.filePath);\n return new Blob([data], { type: this.headers.get('content-type') });\n }\n\n /**\n * Reads the contents of the file specified by the filePath property and returns a Promise that\n * resolves with a string containing the file's contents.\n * @returns {Promise} A Promise that resolves with a string containing the file's contents.\n * @throws {Error} If the file cannot be read.\n */\n async text() {\n const data = await fs.promises.readFile(this.filePath, 'utf8');\n return data;\n }\n\n /**\n * Reads the contents of the file specified by the filePath property and returns a Promise that\n * resolves with a parsed JavaScript object containing the file's contents.\n * \n * @returns {Promise} A Promise that resolves with a parsed JavaScript object containing the file's contents.\n * @throws {Error} If the file cannot be read.\n */\n async json() {\n return JSON.parse(await this.text());\n }\n}\n\n/**\n * Determines whether the given string is a valid URL.\n * @param {string|URL} string The string to test for validity as an URL.\n * @param {string[]} [protocols=null] A list of valid protocols. If specified, the protocol must be in this list.\n * @param {string[]} [validHosts=null] A list of valid hostnames. If specified, the URL's hostname must be in this list.\n * @returns {boolean} True if the string is a valid URL, false otherwise.\n */\nfunction isValidUrl(string, protocols = null, validHosts = null) {\n let url;\n try {\n url = new URL(string);\n } catch (_) {\n return false;\n }\n if (protocols && !protocols.includes(url.protocol)) {\n return false;\n }\n if (validHosts && !validHosts.includes(url.hostname)) {\n return false;\n }\n return true;\n}\n\n/**\n * Helper function to get a file, using either the Fetch API or FileSystem API.\n *\n * @param {URL|string} urlOrPath The URL/path of the file to get.\n * @returns {Promise} A promise that resolves to a FileResponse object (if the file is retrieved using the FileSystem API), or a Response object (if the file is retrieved using the Fetch API).\n */\nexport async function getFile(urlOrPath) {\n\n if (env.useFS && !isValidUrl(urlOrPath, ['http:', 'https:', 'blob:'])) {\n return new FileResponse(urlOrPath);\n\n } else if (typeof process !== 'undefined' && process?.release?.name === 'node') {\n const IS_CI = !!process.env?.TESTING_REMOTELY;\n const version = env.version;\n\n const headers = new Headers();\n headers.set('User-Agent', `transformers.js/${version}; is_ci/${IS_CI};`);\n\n // Check whether we are making a request to the Hugging Face Hub.\n const isHFURL = isValidUrl(urlOrPath, ['http:', 'https:'], ['huggingface.co', 'hf.co']);\n if (isHFURL) {\n // If an access token is present in the environment variables,\n // we add it to the request headers.\n // NOTE: We keep `HF_ACCESS_TOKEN` for backwards compatibility (as a fallback).\n const token = process.env?.HF_TOKEN ?? process.env?.HF_ACCESS_TOKEN;\n if (token) {\n headers.set('Authorization', `Bearer ${token}`);\n }\n }\n return fetch(urlOrPath, { headers });\n } else {\n // Running in a browser-environment, so we use default headers\n // NOTE: We do not allow passing authorization headers in the browser,\n // since this would require exposing the token to the client.\n return fetch(urlOrPath);\n }\n}\n\nconst ERROR_MAPPING = {\n // 4xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses)\n 400: 'Bad request error occurred while trying to load file',\n 401: 'Unauthorized access to file',\n 403: 'Forbidden access to file',\n 404: 'Could not locate file',\n 408: 'Request timeout error occurred while trying to load file',\n\n // 5xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses)\n 500: 'Internal server error error occurred while trying to load file',\n 502: 'Bad gateway error occurred while trying to load file',\n 503: 'Service unavailable error occurred while trying to load file',\n 504: 'Gateway timeout error occurred while trying to load file',\n}\n/**\n * Helper method to handle fatal errors that occur while trying to load a file from the Hugging Face Hub.\n * @param {number} status The HTTP status code of the error.\n * @param {string} remoteURL The URL of the file that could not be loaded.\n * @param {boolean} fatal Whether to raise an error if the file could not be loaded.\n * @returns {null} Returns `null` if `fatal = true`.\n * @throws {Error} If `fatal = false`.\n */\nfunction handleError(status, remoteURL, fatal) {\n if (!fatal) {\n // File was not loaded correctly, but it is optional.\n // TODO in future, cache the response?\n return null;\n }\n\n const message = ERROR_MAPPING[status] ?? `Error (${status}) occurred while trying to load file`;\n throw Error(`${message}: \"${remoteURL}\".`);\n}\n\nclass FileCache {\n /**\n * Instantiate a `FileCache` object.\n * @param {string} path \n */\n constructor(path) {\n this.path = path;\n }\n\n /**\n * Checks whether the given request is in the cache.\n * @param {string} request \n * @returns {Promise}\n */\n async match(request) {\n\n let filePath = path.join(this.path, request);\n let file = new FileResponse(filePath);\n\n if (file.exists) {\n return file;\n } else {\n return undefined;\n }\n }\n\n /**\n * Adds the given response to the cache.\n * @param {string} request \n * @param {Response|FileResponse} response \n * @returns {Promise}\n */\n async put(request, response) {\n const buffer = Buffer.from(await response.arrayBuffer());\n\n let outputPath = path.join(this.path, request);\n\n try {\n await fs.promises.mkdir(path.dirname(outputPath), { recursive: true });\n await fs.promises.writeFile(outputPath, buffer);\n\n } catch (err) {\n console.warn('An error occurred while writing the file to cache:', err)\n }\n }\n\n // TODO add the rest?\n // addAll(requests: RequestInfo[]): Promise;\n // delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise;\n // keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>;\n // match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise;\n // matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>;\n}\n\n/**\n * \n * @param {FileCache|Cache} cache The cache to search\n * @param {string[]} names The names of the item to search for\n * @returns {Promise} The item from the cache, or undefined if not found.\n */\nasync function tryCache(cache, ...names) {\n for (let name of names) {\n try {\n let result = await cache.match(name);\n if (result) return result;\n } catch (e) {\n continue;\n }\n }\n return undefined;\n}\n\n/**\n * \n * Retrieves a file from either a remote URL using the Fetch API or from the local file system using the FileSystem API.\n * If the filesystem is available and `env.useCache = true`, the file will be downloaded and cached.\n * \n * @param {string} path_or_repo_id This can be either:\n * - a string, the *model id* of a model repo on huggingface.co.\n * - a path to a *directory* potentially containing the file.\n * @param {string} filename The name of the file to locate in `path_or_repo`.\n * @param {boolean} [fatal=true] Whether to throw an error if the file is not found.\n * @param {PretrainedOptions} [options] An object containing optional parameters.\n * \n * @throws Will throw an error if the file is not found and `fatal` is true.\n * @returns {Promise} A Promise that resolves with the file content as a buffer.\n */\nexport async function getModelFile(path_or_repo_id, filename, fatal = true, options = {}) {\n\n if (!env.allowLocalModels) {\n // User has disabled local models, so we just make sure other settings are correct.\n\n if (options.local_files_only) {\n throw Error(\"Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).\")\n } else if (!env.allowRemoteModels) {\n throw Error(\"Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.\")\n }\n }\n\n // Initiate file retrieval\n dispatchCallback(options.progress_callback, {\n status: 'initiate',\n name: path_or_repo_id,\n file: filename\n })\n\n // First, check if the a caching backend is available\n // If no caching mechanism available, will download the file every time\n let cache;\n if (!cache && env.useBrowserCache) {\n if (typeof caches === 'undefined') {\n throw Error('Browser cache is not available in this environment.')\n }\n try {\n // In some cases, the browser cache may be visible, but not accessible due to security restrictions.\n // For example, when running an application in an iframe, if a user attempts to load the page in\n // incognito mode, the following error is thrown: `DOMException: Failed to execute 'open' on 'CacheStorage':\n // An attempt was made to break through the security policy of the user agent.`\n // So, instead of crashing, we just ignore the error and continue without using the cache.\n cache = await caches.open('transformers-cache');\n } catch (e) {\n console.warn('An error occurred while opening the browser cache:', e);\n }\n }\n\n if (!cache && env.useFSCache) {\n // TODO throw error if not available\n\n // If `cache_dir` is not specified, use the default cache directory\n cache = new FileCache(options.cache_dir ?? env.cacheDir);\n }\n\n if (!cache && env.useCustomCache) {\n // Allow the user to specify a custom cache system.\n if (!env.customCache) {\n throw Error('`env.useCustomCache=true`, but `env.customCache` is not defined.')\n }\n\n // Check that the required methods are defined:\n if (!env.customCache.match || !env.customCache.put) {\n throw new Error(\n \"`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. \" +\n \"For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache\"\n )\n }\n cache = env.customCache;\n }\n\n const revision = options.revision ?? 'main';\n\n let requestURL = pathJoin(path_or_repo_id, filename);\n let localPath = pathJoin(env.localModelPath, requestURL);\n\n let remoteURL = pathJoin(\n env.remoteHost,\n env.remotePathTemplate\n .replaceAll('{model}', path_or_repo_id)\n .replaceAll('{revision}', encodeURIComponent(revision)),\n filename\n );\n\n // Choose cache key for filesystem cache\n // When using the main revision (default), we use the request URL as the cache key.\n // If a specific revision is requested, we account for this in the cache key.\n let fsCacheKey = revision === 'main' ? requestURL : pathJoin(path_or_repo_id, revision, filename);\n\n /** @type {string} */\n let cacheKey;\n let proposedCacheKey = cache instanceof FileCache ? fsCacheKey : remoteURL;\n\n // Whether to cache the final response in the end.\n let toCacheResponse = false;\n\n /** @type {Response|FileResponse|undefined} */\n let response;\n\n if (cache) {\n // A caching system is available, so we try to get the file from it.\n // 1. We first try to get from cache using the local path. In some environments (like deno),\n // non-URL cache keys are not allowed. In these cases, `response` will be undefined.\n // 2. If no response is found, we try to get from cache using the remote URL or file system cache.\n response = await tryCache(cache, localPath, proposedCacheKey);\n }\n\n const cacheHit = response !== undefined;\n\n if (response === undefined) {\n // Caching not available, or file is not cached, so we perform the request\n\n if (env.allowLocalModels) {\n // Accessing local models is enabled, so we try to get the file locally.\n // If request is a valid HTTP URL, we skip the local file check. Otherwise, we try to get the file locally.\n const isURL = isValidUrl(requestURL, ['http:', 'https:']);\n if (!isURL) {\n try {\n response = await getFile(localPath);\n cacheKey = localPath; // Update the cache key to be the local path\n } catch (e) {\n // Something went wrong while trying to get the file locally.\n // NOTE: error handling is done in the next step (since `response` will be undefined)\n console.warn(`Unable to load from local path \"${localPath}\": \"${e}\"`);\n }\n } else if (options.local_files_only) {\n throw new Error(`\\`local_files_only=true\\`, but attempted to load a remote file from: ${requestURL}.`);\n } else if (!env.allowRemoteModels) {\n throw new Error(`\\`env.allowRemoteModels=false\\`, but attempted to load a remote file from: ${requestURL}.`);\n }\n }\n\n if (response === undefined || response.status === 404) {\n // File not found locally. This means either:\n // - The user has disabled local file access (`env.allowLocalModels=false`)\n // - the path is a valid HTTP url (`response === undefined`)\n // - the path is not a valid HTTP url and the file is not present on the file system or local server (`response.status === 404`)\n\n if (options.local_files_only || !env.allowRemoteModels) {\n // User requested local files only, but the file is not found locally.\n if (fatal) {\n throw Error(`\\`local_files_only=true\\` or \\`env.allowRemoteModels=false\\` and file was not found locally at \"${localPath}\".`);\n } else {\n // File not found, but this file is optional.\n // TODO in future, cache the response?\n return null;\n }\n }\n\n // File not found locally, so we try to download it from the remote server\n response = await getFile(remoteURL);\n\n if (response.status !== 200) {\n return handleError(response.status, remoteURL, fatal);\n }\n\n // Success! We use the proposed cache key from earlier\n cacheKey = proposedCacheKey;\n }\n\n // Only cache the response if:\n toCacheResponse =\n cache // 1. A caching system is available\n && typeof Response !== 'undefined' // 2. `Response` is defined (i.e., we are in a browser-like environment)\n && response instanceof Response // 3. result is a `Response` object (i.e., not a `FileResponse`)\n && response.status === 200 // 4. request was successful (status code 200)\n }\n\n // Start downloading\n dispatchCallback(options.progress_callback, {\n status: 'download',\n name: path_or_repo_id,\n file: filename\n })\n\n const progressInfo = {\n status: 'progress',\n name: path_or_repo_id,\n file: filename\n }\n\n /** @type {Uint8Array} */\n let buffer;\n\n if (!options.progress_callback) {\n // If no progress callback is specified, we can use the `.arrayBuffer()`\n // method to read the response.\n buffer = new Uint8Array(await response.arrayBuffer());\n\n } else if (\n cacheHit // The item is being read from the cache\n &&\n typeof navigator !== 'undefined' && /firefox/i.test(navigator.userAgent) // We are in Firefox\n ) {\n // Due to bug in Firefox, we cannot display progress when loading from cache.\n // Fortunately, since this should be instantaneous, this should not impact users too much.\n buffer = new Uint8Array(await response.arrayBuffer());\n\n // For completeness, we still fire the final progress callback\n dispatchCallback(options.progress_callback, {\n ...progressInfo,\n progress: 100,\n loaded: buffer.length,\n total: buffer.length,\n })\n } else {\n buffer = await readResponse(response, data => {\n dispatchCallback(options.progress_callback, {\n ...progressInfo,\n ...data,\n })\n })\n }\n\n if (\n // Only cache web responses\n // i.e., do not cache FileResponses (prevents duplication)\n toCacheResponse && cacheKey\n &&\n // Check again whether request is in cache. If not, we add the response to the cache\n (await cache.match(cacheKey) === undefined)\n ) {\n // NOTE: We use `new Response(buffer, ...)` instead of `response.clone()` to handle LFS files\n await cache.put(cacheKey, new Response(buffer, {\n headers: response.headers\n }))\n .catch(err => {\n // Do not crash if unable to add to cache (e.g., QuotaExceededError).\n // Rather, log a warning and proceed with execution.\n console.warn(`Unable to add response to browser cache: ${err}.`);\n });\n\n }\n\n dispatchCallback(options.progress_callback, {\n status: 'done',\n name: path_or_repo_id,\n file: filename\n });\n\n return buffer;\n}\n\n/**\n * Fetches a JSON file from a given path and file name.\n *\n * @param {string} modelPath The path to the directory containing the file.\n * @param {string} fileName The name of the file to fetch.\n * @param {boolean} [fatal=true] Whether to throw an error if the file is not found.\n * @param {PretrainedOptions} [options] An object containing optional parameters.\n * @returns {Promise} The JSON data parsed into a JavaScript object.\n * @throws Will throw an error if the file is not found and `fatal` is true.\n */\nexport async function getModelJSON(modelPath, fileName, fatal = true, options = {}) {\n let buffer = await getModelFile(modelPath, fileName, fatal, options);\n if (buffer === null) {\n // Return empty object\n return {}\n }\n\n let decoder = new TextDecoder('utf-8');\n let jsonData = decoder.decode(buffer);\n\n return JSON.parse(jsonData);\n}\n\n/**\n * Read and track progress when reading a Response object\n *\n * @param {any} response The Response object to read\n * @param {function} progress_callback The function to call with progress updates\n * @returns {Promise} A Promise that resolves with the Uint8Array buffer\n */\nasync function readResponse(response, progress_callback) {\n\n const contentLength = response.headers.get('Content-Length');\n if (contentLength === null) {\n console.warn('Unable to determine content-length from response headers. Will expand buffer when needed.')\n }\n let total = parseInt(contentLength ?? '0');\n let buffer = new Uint8Array(total);\n let loaded = 0;\n\n const reader = response.body.getReader();\n async function read() {\n const { done, value } = await reader.read();\n if (done) return;\n\n let newLoaded = loaded + value.length;\n if (newLoaded > total) {\n total = newLoaded;\n\n // Adding the new data will overflow buffer.\n // In this case, we extend the buffer\n let newBuffer = new Uint8Array(total);\n\n // copy contents\n newBuffer.set(buffer);\n\n buffer = newBuffer;\n }\n buffer.set(value, loaded)\n loaded = newLoaded;\n\n const progress = (loaded / total) * 100;\n\n // Call your function here\n progress_callback({\n progress: progress,\n loaded: loaded,\n total: total,\n })\n\n return read();\n }\n\n // Actually read\n await read();\n\n return buffer;\n}\n\n/**\n * Joins multiple parts of a path into a single path, while handling leading and trailing slashes.\n *\n * @param {...string} parts Multiple parts of a path.\n * @returns {string} A string representing the joined path.\n */\nfunction pathJoin(...parts) {\n // https://stackoverflow.com/a/55142565\n parts = parts.map((part, index) => {\n if (index) {\n part = part.replace(new RegExp('^/'), '');\n }\n if (index !== parts.length - 1) {\n part = part.replace(new RegExp('/$'), '');\n }\n return part;\n })\n return parts.join('/');\n}\n","\n/**\n * @file Helper module for image processing. \n * \n * These functions and classes are only used internally, \n * meaning an end-user shouldn't need to access anything here.\n * \n * @module utils/image\n */\n\nimport { getFile } from './hub.js';\nimport { env } from '../env.js';\nimport { Tensor } from './tensor.js';\n\n// Will be empty (or not used) if running in browser or web-worker\nimport sharp from 'sharp';\n\nconst BROWSER_ENV = typeof self !== 'undefined';\nconst WEBWORKER_ENV = BROWSER_ENV && self.constructor.name === 'DedicatedWorkerGlobalScope';\n\nlet createCanvasFunction;\nlet ImageDataClass;\nlet loadImageFunction;\nif (BROWSER_ENV) {\n // Running in browser or web-worker\n createCanvasFunction = (/** @type {number} */ width, /** @type {number} */ height) => {\n if (!self.OffscreenCanvas) {\n throw new Error('OffscreenCanvas not supported by this browser.');\n }\n return new self.OffscreenCanvas(width, height)\n };\n loadImageFunction = self.createImageBitmap;\n ImageDataClass = self.ImageData;\n\n} else if (sharp) {\n // Running in Node.js, electron, or other non-browser environment\n\n loadImageFunction = async (/**@type {sharp.Sharp}*/img) => {\n const metadata = await img.metadata();\n const rawChannels = metadata.channels;\n\n const { data, info } = await img.rotate().raw().toBuffer({ resolveWithObject: true });\n\n const newImage = new RawImage(new Uint8ClampedArray(data), info.width, info.height, info.channels);\n if (rawChannels !== undefined && rawChannels !== info.channels) {\n // Make sure the new image has the same number of channels as the input image.\n // This is necessary for grayscale images.\n newImage.convert(rawChannels);\n }\n return newImage;\n }\n\n} else {\n throw new Error('Unable to load image processing library.');\n}\n\n\n// Defined here: https://github.com/python-pillow/Pillow/blob/a405e8406b83f8bfb8916e93971edc7407b8b1ff/src/libImaging/Imaging.h#L262-L268\nconst RESAMPLING_MAPPING = {\n 0: 'nearest',\n 1: 'lanczos',\n 2: 'bilinear',\n 3: 'bicubic',\n 4: 'box',\n 5: 'hamming',\n}\n\n/**\n * Mapping from file extensions to MIME types.\n */\nconst CONTENT_TYPE_MAP = new Map([\n ['png', 'image/png'],\n ['jpg', 'image/jpeg'],\n ['jpeg', 'image/jpeg'],\n ['gif', 'image/gif'],\n]);\n\nexport class RawImage {\n\n /**\n * Create a new `RawImage` object.\n * @param {Uint8ClampedArray|Uint8Array} data The pixel data.\n * @param {number} width The width of the image.\n * @param {number} height The height of the image.\n * @param {1|2|3|4} channels The number of channels.\n */\n constructor(data, width, height, channels) {\n this.data = data;\n this.width = width;\n this.height = height;\n this.channels = channels;\n }\n\n /** \n * Returns the size of the image (width, height).\n * @returns {[number, number]} The size of the image (width, height).\n */\n get size() {\n return [this.width, this.height];\n }\n\n /**\n * Helper method for reading an image from a variety of input types.\n * @param {RawImage|string|URL} input \n * @returns The image object.\n * \n * **Example:** Read image from a URL.\n * ```javascript\n * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * // RawImage {\n * // \"data\": Uint8ClampedArray [ 25, 25, 25, 19, 19, 19, ... ],\n * // \"width\": 800,\n * // \"height\": 533,\n * // \"channels\": 3\n * // }\n * ```\n */\n static async read(input) {\n if (input instanceof RawImage) {\n return input;\n } else if (typeof input === 'string' || input instanceof URL) {\n return await this.fromURL(input);\n } else {\n throw new Error(`Unsupported input type: ${typeof input}`);\n }\n }\n\n /**\n * Read an image from a canvas.\n * @param {HTMLCanvasElement|OffscreenCanvas} canvas The canvas to read the image from.\n * @returns {RawImage} The image object.\n */\n static fromCanvas(canvas) {\n if (!BROWSER_ENV) {\n throw new Error('fromCanvas() is only supported in browser environments.')\n }\n\n const ctx = canvas.getContext('2d');\n const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;\n return new RawImage(data, canvas.width, canvas.height, 4);\n }\n\n /**\n * Read an image from a URL or file path.\n * @param {string|URL} url The URL or file path to read the image from.\n * @returns {Promise} The image object.\n */\n static async fromURL(url) {\n const response = await getFile(url);\n if (response.status !== 200) {\n throw new Error(`Unable to read image from \"${url}\" (${response.status} ${response.statusText})`);\n }\n const blob = await response.blob();\n return this.fromBlob(blob);\n }\n\n /**\n * Helper method to create a new Image from a blob.\n * @param {Blob} blob The blob to read the image from.\n * @returns {Promise} The image object.\n */\n static async fromBlob(blob) {\n if (BROWSER_ENV) {\n // Running in environment with canvas\n const img = await loadImageFunction(blob);\n\n const ctx = createCanvasFunction(img.width, img.height).getContext('2d');\n\n // Draw image to context\n ctx.drawImage(img, 0, 0);\n\n return new this(ctx.getImageData(0, 0, img.width, img.height).data, img.width, img.height, 4);\n\n } else {\n // Use sharp.js to read (and possible resize) the image.\n const img = sharp(await blob.arrayBuffer());\n\n return await loadImageFunction(img);\n }\n }\n\n /**\n * Helper method to create a new Image from a tensor\n * @param {Tensor} tensor \n */\n static fromTensor(tensor, channel_format = 'CHW') {\n if (tensor.dims.length !== 3) {\n throw new Error(`Tensor should have 3 dimensions, but has ${tensor.dims.length} dimensions.`);\n }\n\n if (channel_format === 'CHW') {\n tensor = tensor.transpose(1, 2, 0);\n } else if (channel_format === 'HWC') {\n // Do nothing\n } else {\n throw new Error(`Unsupported channel format: ${channel_format}`);\n }\n if (!(tensor.data instanceof Uint8ClampedArray || tensor.data instanceof Uint8Array)) {\n throw new Error(`Unsupported tensor type: ${tensor.type}`);\n }\n switch (tensor.dims[2]) {\n case 1:\n case 2:\n case 3:\n case 4:\n return new RawImage(tensor.data, tensor.dims[1], tensor.dims[0], tensor.dims[2]);\n default:\n throw new Error(`Unsupported number of channels: ${tensor.dims[2]}`);\n }\n }\n\n /**\n * Convert the image to grayscale format.\n * @returns {RawImage} `this` to support chaining.\n */\n grayscale() {\n if (this.channels === 1) {\n return this;\n }\n\n const newData = new Uint8ClampedArray(this.width * this.height * 1);\n switch (this.channels) {\n case 3: // rgb to grayscale\n case 4: // rgba to grayscale\n for (let i = 0, offset = 0; i < this.data.length; i += this.channels) {\n const red = this.data[i];\n const green = this.data[i + 1];\n const blue = this.data[i + 2];\n\n newData[offset++] = Math.round(0.2989 * red + 0.5870 * green + 0.1140 * blue);\n }\n break;\n default:\n throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);\n }\n return this._update(newData, this.width, this.height, 1);\n }\n\n /**\n * Convert the image to RGB format.\n * @returns {RawImage} `this` to support chaining.\n */\n rgb() {\n if (this.channels === 3) {\n return this;\n }\n\n const newData = new Uint8ClampedArray(this.width * this.height * 3);\n\n switch (this.channels) {\n case 1: // grayscale to rgb\n for (let i = 0, offset = 0; i < this.data.length; ++i) {\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i];\n }\n break;\n case 4: // rgba to rgb\n for (let i = 0, offset = 0; i < this.data.length; i += 4) {\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i + 1];\n newData[offset++] = this.data[i + 2];\n }\n break;\n default:\n throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);\n }\n return this._update(newData, this.width, this.height, 3);\n\n }\n\n /**\n * Convert the image to RGBA format.\n * @returns {RawImage} `this` to support chaining.\n */\n rgba() {\n if (this.channels === 4) {\n return this;\n }\n\n const newData = new Uint8ClampedArray(this.width * this.height * 4);\n\n switch (this.channels) {\n case 1: // grayscale to rgba\n for (let i = 0, offset = 0; i < this.data.length; ++i) {\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i];\n newData[offset++] = 255;\n }\n break;\n case 3: // rgb to rgba\n for (let i = 0, offset = 0; i < this.data.length; i += 3) {\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i + 1];\n newData[offset++] = this.data[i + 2];\n newData[offset++] = 255;\n }\n break;\n default:\n throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);\n }\n\n return this._update(newData, this.width, this.height, 4);\n }\n\n /**\n * Resize the image to the given dimensions. This method uses the canvas API to perform the resizing.\n * @param {number} width The width of the new image.\n * @param {number} height The height of the new image.\n * @param {Object} options Additional options for resizing.\n * @param {0|1|2|3|4|5|string} [options.resample] The resampling method to use.\n * @returns {Promise} `this` to support chaining.\n */\n async resize(width, height, {\n resample = 2,\n } = {}) {\n\n // Ensure resample method is a string\n let resampleMethod = RESAMPLING_MAPPING[resample] ?? resample;\n\n if (BROWSER_ENV) {\n // TODO use `resample` in browser environment\n\n // Store number of channels before resizing\n const numChannels = this.channels;\n\n // Create canvas object for this image\n const canvas = this.toCanvas();\n\n // Actually perform resizing using the canvas API\n const ctx = createCanvasFunction(width, height).getContext('2d');\n\n // Draw image to context, resizing in the process\n ctx.drawImage(canvas, 0, 0, width, height);\n\n // Create image from the resized data\n const resizedImage = new RawImage(ctx.getImageData(0, 0, width, height).data, width, height, 4);\n\n // Convert back so that image has the same number of channels as before\n return resizedImage.convert(numChannels);\n\n } else {\n // Create sharp image from raw data, and resize\n let img = this.toSharp();\n\n switch (resampleMethod) {\n case 'box':\n case 'hamming':\n if (resampleMethod === 'box' || resampleMethod === 'hamming') {\n console.warn(`Resampling method ${resampleMethod} is not yet supported. Using bilinear instead.`);\n resampleMethod = 'bilinear';\n }\n\n case 'nearest':\n case 'bilinear':\n case 'bicubic':\n // Perform resizing using affine transform. \n // This matches how the python Pillow library does it.\n img = img.affine([width / this.width, 0, 0, height / this.height], {\n interpolator: resampleMethod\n });\n break;\n\n case 'lanczos':\n // https://github.com/python-pillow/Pillow/discussions/5519\n // https://github.com/lovell/sharp/blob/main/docs/api-resize.md\n img = img.resize({\n width, height,\n fit: 'fill',\n kernel: 'lanczos3', // PIL Lanczos uses a kernel size of 3 \n });\n break;\n\n default:\n throw new Error(`Resampling method ${resampleMethod} is not supported.`);\n }\n\n return await loadImageFunction(img);\n }\n\n }\n\n async pad([left, right, top, bottom]) {\n left = Math.max(left, 0);\n right = Math.max(right, 0);\n top = Math.max(top, 0);\n bottom = Math.max(bottom, 0);\n\n if (left === 0 && right === 0 && top === 0 && bottom === 0) {\n // No padding needed\n return this;\n }\n\n if (BROWSER_ENV) {\n // Store number of channels before padding\n const numChannels = this.channels;\n\n // Create canvas object for this image\n const canvas = this.toCanvas();\n\n const newWidth = this.width + left + right;\n const newHeight = this.height + top + bottom;\n\n // Create a new canvas of the desired size.\n const ctx = createCanvasFunction(newWidth, newHeight).getContext('2d');\n\n // Draw image to context, padding in the process\n ctx.drawImage(canvas,\n 0, 0, this.width, this.height,\n left, top, newWidth, newHeight\n );\n\n // Create image from the padded data\n const paddedImage = new RawImage(\n ctx.getImageData(0, 0, newWidth, newHeight).data,\n newWidth, newHeight, 4);\n\n // Convert back so that image has the same number of channels as before\n return paddedImage.convert(numChannels);\n\n } else {\n const img = this.toSharp().extend({ left, right, top, bottom });\n return await loadImageFunction(img);\n }\n }\n\n async crop([x_min, y_min, x_max, y_max]) {\n // Ensure crop bounds are within the image\n x_min = Math.max(x_min, 0);\n y_min = Math.max(y_min, 0);\n x_max = Math.min(x_max, this.width - 1);\n y_max = Math.min(y_max, this.height - 1);\n\n // Do nothing if the crop is the entire image\n if (x_min === 0 && y_min === 0 && x_max === this.width - 1 && y_max === this.height - 1) {\n return this;\n }\n\n const crop_width = x_max - x_min + 1;\n const crop_height = y_max - y_min + 1;\n\n if (BROWSER_ENV) {\n // Store number of channels before resizing\n const numChannels = this.channels;\n\n // Create canvas object for this image\n const canvas = this.toCanvas();\n\n // Create a new canvas of the desired size. This is needed since if the \n // image is too small, we need to pad it with black pixels.\n const ctx = createCanvasFunction(crop_width, crop_height).getContext('2d');\n\n // Draw image to context, cropping in the process\n ctx.drawImage(canvas,\n x_min, y_min, crop_width, crop_height,\n 0, 0, crop_width, crop_height\n );\n\n // Create image from the resized data\n const resizedImage = new RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4);\n\n // Convert back so that image has the same number of channels as before\n return resizedImage.convert(numChannels);\n\n } else {\n // Create sharp image from raw data\n const img = this.toSharp().extract({\n left: x_min,\n top: y_min,\n width: crop_width,\n height: crop_height,\n });\n\n return await loadImageFunction(img);\n }\n\n }\n\n async center_crop(crop_width, crop_height) {\n // If the image is already the desired size, return it\n if (this.width === crop_width && this.height === crop_height) {\n return this;\n }\n\n // Determine bounds of the image in the new canvas\n const width_offset = (this.width - crop_width) / 2;\n const height_offset = (this.height - crop_height) / 2;\n\n\n if (BROWSER_ENV) {\n // Store number of channels before resizing\n const numChannels = this.channels;\n\n // Create canvas object for this image\n const canvas = this.toCanvas();\n\n // Create a new canvas of the desired size. This is needed since if the \n // image is too small, we need to pad it with black pixels.\n const ctx = createCanvasFunction(crop_width, crop_height).getContext('2d');\n\n let sourceX = 0;\n let sourceY = 0;\n let destX = 0;\n let destY = 0;\n\n if (width_offset >= 0) {\n sourceX = width_offset;\n } else {\n destX = -width_offset;\n }\n\n if (height_offset >= 0) {\n sourceY = height_offset;\n } else {\n destY = -height_offset;\n }\n\n // Draw image to context, cropping in the process\n ctx.drawImage(canvas,\n sourceX, sourceY, crop_width, crop_height,\n destX, destY, crop_width, crop_height\n );\n\n // Create image from the resized data\n const resizedImage = new RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4);\n\n // Convert back so that image has the same number of channels as before\n return resizedImage.convert(numChannels);\n\n } else {\n // Create sharp image from raw data\n let img = this.toSharp();\n\n if (width_offset >= 0 && height_offset >= 0) {\n // Cropped image lies entirely within the original image\n img = img.extract({\n left: Math.floor(width_offset),\n top: Math.floor(height_offset),\n width: crop_width,\n height: crop_height,\n })\n } else if (width_offset <= 0 && height_offset <= 0) {\n // Cropped image lies entirely outside the original image,\n // so we add padding\n const top = Math.floor(-height_offset);\n const left = Math.floor(-width_offset);\n img = img.extend({\n top: top,\n left: left,\n\n // Ensures the resulting image has the desired dimensions\n right: crop_width - this.width - left,\n bottom: crop_height - this.height - top,\n });\n } else {\n // Cropped image lies partially outside the original image.\n // We first pad, then crop.\n\n let y_padding = [0, 0];\n let y_extract = 0;\n if (height_offset < 0) {\n y_padding[0] = Math.floor(-height_offset);\n y_padding[1] = crop_height - this.height - y_padding[0];\n } else {\n y_extract = Math.floor(height_offset);\n }\n\n let x_padding = [0, 0];\n let x_extract = 0;\n if (width_offset < 0) {\n x_padding[0] = Math.floor(-width_offset);\n x_padding[1] = crop_width - this.width - x_padding[0];\n } else {\n x_extract = Math.floor(width_offset);\n }\n\n img = img.extend({\n top: y_padding[0],\n bottom: y_padding[1],\n left: x_padding[0],\n right: x_padding[1],\n }).extract({\n left: x_extract,\n top: y_extract,\n width: crop_width,\n height: crop_height,\n })\n }\n\n return await loadImageFunction(img);\n }\n }\n\n async toBlob(type = 'image/png', quality = 1) {\n if (!BROWSER_ENV) {\n throw new Error('toBlob() is only supported in browser environments.')\n }\n\n const canvas = this.toCanvas();\n return await canvas.convertToBlob({ type, quality });\n }\n\n toTensor(channel_format = 'CHW') {\n let tensor = new Tensor(\n 'uint8',\n new Uint8Array(this.data),\n [this.height, this.width, this.channels]\n );\n\n if (channel_format === 'HWC') {\n // Do nothing\n } else if (channel_format === 'CHW') { // hwc -> chw\n tensor = tensor.permute(2, 0, 1);\n } else {\n throw new Error(`Unsupported channel format: ${channel_format}`);\n }\n return tensor;\n }\n\n toCanvas() {\n if (!BROWSER_ENV) {\n throw new Error('toCanvas() is only supported in browser environments.')\n }\n\n // Clone, and convert data to RGBA before drawing to canvas.\n // This is because the canvas API only supports RGBA\n const cloned = this.clone().rgba();\n\n // Create canvas object for the cloned image\n const clonedCanvas = createCanvasFunction(cloned.width, cloned.height);\n\n // Draw image to context\n const data = new ImageDataClass(cloned.data, cloned.width, cloned.height);\n clonedCanvas.getContext('2d').putImageData(data, 0, 0);\n\n return clonedCanvas;\n }\n\n /**\n * Helper method to update the image data.\n * @param {Uint8ClampedArray} data The new image data.\n * @param {number} width The new width of the image.\n * @param {number} height The new height of the image.\n * @param {1|2|3|4|null} [channels] The new number of channels of the image.\n * @private\n */\n _update(data, width, height, channels = null) {\n this.data = data;\n this.width = width;\n this.height = height;\n if (channels !== null) {\n this.channels = channels;\n }\n return this;\n }\n\n /**\n * Clone the image\n * @returns {RawImage} The cloned image\n */\n clone() {\n return new RawImage(this.data.slice(), this.width, this.height, this.channels);\n }\n\n /**\n * Helper method for converting image to have a certain number of channels\n * @param {number} numChannels The number of channels. Must be 1, 3, or 4.\n * @returns {RawImage} `this` to support chaining.\n */\n convert(numChannels) {\n if (this.channels === numChannels) return this; // Already correct number of channels\n\n switch (numChannels) {\n case 1:\n this.grayscale();\n break;\n case 3:\n this.rgb();\n break;\n case 4:\n this.rgba();\n break;\n default:\n throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);\n }\n return this;\n }\n\n /**\n * Save the image to the given path.\n * @param {string} path The path to save the image to.\n */\n async save(path) {\n\n if (BROWSER_ENV) {\n if (WEBWORKER_ENV) {\n throw new Error('Unable to save an image from a Web Worker.')\n }\n\n const extension = path.split('.').pop().toLowerCase();\n const mime = CONTENT_TYPE_MAP.get(extension) ?? 'image/png';\n\n // Convert image to Blob\n const blob = await this.toBlob(mime);\n\n // Convert the canvas content to a data URL\n const dataURL = URL.createObjectURL(blob);\n\n // Create an anchor element with the data URL as the href attribute\n const downloadLink = document.createElement('a');\n downloadLink.href = dataURL;\n\n // Set the download attribute to specify the desired filename for the downloaded image\n downloadLink.download = path;\n\n // Trigger the download\n downloadLink.click();\n\n // Clean up: remove the anchor element from the DOM\n downloadLink.remove();\n\n } else if (!env.useFS) {\n throw new Error('Unable to save the image because filesystem is disabled in this environment.')\n\n } else {\n const img = this.toSharp();\n return await img.toFile(path);\n }\n }\n\n toSharp() {\n if (BROWSER_ENV) {\n throw new Error('toSharp() is only supported in server-side environments.')\n }\n\n return sharp(this.data, {\n raw: {\n width: this.width,\n height: this.height,\n channels: this.channels\n }\n });\n }\n}","\n/**\n * @file Helper module for mathematical processing. \n * \n * These functions and classes are only used internally, \n * meaning an end-user shouldn't need to access anything here.\n * \n * @module utils/maths\n */\n\n/**\n * @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array} TypedArray\n * @typedef {BigInt64Array | BigUint64Array} BigTypedArray\n * @typedef {TypedArray | BigTypedArray} AnyTypedArray\n */\n\n/**\n * @param {TypedArray} input\n */\nexport function interpolate_data(input, [in_channels, in_height, in_width], [out_height, out_width], mode = 'bilinear', align_corners = false) {\n // TODO use mode and align_corners\n\n // Output image dimensions\n const x_scale = out_width / in_width;\n const y_scale = out_height / in_height;\n\n // Output image\n // @ts-ignore\n const out_img = new input.constructor(out_height * out_width * in_channels);\n\n // Pre-calculate strides\n const inStride = in_height * in_width;\n const outStride = out_height * out_width;\n\n for (let i = 0; i < out_height; ++i) {\n for (let j = 0; j < out_width; ++j) {\n // Calculate output offset\n const outOffset = i * out_width + j;\n\n // Calculate input pixel coordinates\n const x = (j + 0.5) / x_scale - 0.5;\n const y = (i + 0.5) / y_scale - 0.5;\n\n // Calculate the four nearest input pixels\n // We also check if the input pixel coordinates are within the image bounds\n let x1 = Math.floor(x);\n let y1 = Math.floor(y);\n const x2 = Math.min(x1 + 1, in_width - 1);\n const y2 = Math.min(y1 + 1, in_height - 1);\n\n x1 = Math.max(x1, 0);\n y1 = Math.max(y1, 0);\n\n\n // Calculate the fractional distances between the input pixel and the four nearest pixels\n const s = x - x1;\n const t = y - y1;\n\n // Perform bilinear interpolation\n const w1 = (1 - s) * (1 - t);\n const w2 = s * (1 - t);\n const w3 = (1 - s) * t;\n const w4 = s * t;\n\n // Calculate the four nearest input pixel indices\n const yStride = y1 * in_width;\n const xStride = y2 * in_width;\n const idx1 = yStride + x1;\n const idx2 = yStride + x2;\n const idx3 = xStride + x1;\n const idx4 = xStride + x2;\n\n for (let k = 0; k < in_channels; ++k) {\n // Calculate channel offset\n const cOffset = k * inStride;\n\n out_img[k * outStride + outOffset] =\n w1 * input[cOffset + idx1] +\n w2 * input[cOffset + idx2] +\n w3 * input[cOffset + idx3] +\n w4 * input[cOffset + idx4];\n }\n }\n }\n\n return out_img;\n}\n\n\n/**\n * Helper method to permute a `AnyTypedArray` directly\n * @template {AnyTypedArray} T \n * @param {T} array \n * @param {number[]} dims \n * @param {number[]} axes \n * @returns {[T, number[]]} The permuted array and the new shape.\n */\nexport function permute_data(array, dims, axes) {\n // Calculate the new shape of the permuted array\n // and the stride of the original array\n const shape = new Array(axes.length);\n const stride = new Array(axes.length);\n\n for (let i = axes.length - 1, s = 1; i >= 0; --i) {\n stride[i] = s;\n shape[i] = dims[axes[i]];\n s *= shape[i];\n }\n\n // Precompute inverse mapping of stride\n const invStride = axes.map((_, i) => stride[axes.indexOf(i)]);\n\n // Create the permuted array with the new shape\n // @ts-ignore\n const permutedData = new array.constructor(array.length);\n\n // Permute the original array to the new array\n for (let i = 0; i < array.length; ++i) {\n let newIndex = 0;\n for (let j = dims.length - 1, k = i; j >= 0; --j) {\n newIndex += (k % dims[j]) * invStride[j];\n k = Math.floor(k / dims[j]);\n }\n permutedData[newIndex] = array[i];\n }\n\n return [permutedData, shape];\n}\n\n\n/**\n * Compute the softmax of an array of numbers.\n * @template {TypedArray|number[]} T\n * @param {T} arr The array of numbers to compute the softmax of.\n * @returns {T} The softmax array.\n */\nexport function softmax(arr) {\n // Compute the maximum value in the array\n const maxVal = max(arr)[0];\n\n // Compute the exponentials of the array values\n const exps = arr.map(x => Math.exp(x - maxVal));\n\n // Compute the sum of the exponentials\n // @ts-ignore\n const sumExps = exps.reduce((acc, val) => acc + val, 0);\n\n // Compute the softmax values\n const softmaxArr = exps.map(x => x / sumExps);\n\n return /** @type {T} */(softmaxArr);\n}\n\n/**\n * Calculates the logarithm of the softmax function for the input array.\n * @template {TypedArray|number[]} T\n * @param {T} arr The input array to calculate the log_softmax function for.\n * @returns {T} The resulting log_softmax array.\n */\nexport function log_softmax(arr) {\n // Compute the maximum value in the array\n const maxVal = max(arr)[0];\n\n // Compute the sum of the exponentials\n let sumExps = 0;\n for(let i = 0; i < arr.length; ++i) {\n sumExps += Math.exp(arr[i] - maxVal);\n }\n\n // Compute the log of the sum\n const logSum = Math.log(sumExps);\n\n // Compute the softmax values\n const logSoftmaxArr = arr.map(x => x - maxVal - logSum);\n\n return /** @type {T} */(logSoftmaxArr);\n}\n\n/**\n * Calculates the dot product of two arrays.\n * @param {number[]} arr1 The first array.\n * @param {number[]} arr2 The second array.\n * @returns {number} The dot product of arr1 and arr2.\n */\nexport function dot(arr1, arr2) {\n let result = 0;\n for (let i = 0; i < arr1.length; ++i) {\n result += arr1[i] * arr2[i];\n }\n return result;\n}\n\n/**\n * Computes the cosine similarity between two arrays.\n *\n * @param {number[]} arr1 The first array.\n * @param {number[]} arr2 The second array.\n * @returns {number} The cosine similarity between the two arrays.\n */\nexport function cos_sim(arr1, arr2) {\n // Calculate dot product of the two arrays\n const dotProduct = dot(arr1, arr2);\n\n // Calculate the magnitude of the first array\n const magnitudeA = magnitude(arr1);\n\n // Calculate the magnitude of the second array\n const magnitudeB = magnitude(arr2);\n\n // Calculate the cosine similarity\n const cosineSimilarity = dotProduct / (magnitudeA * magnitudeB);\n\n return cosineSimilarity;\n}\n\n/**\n * Calculates the magnitude of a given array.\n * @param {number[]} arr The array to calculate the magnitude of.\n * @returns {number} The magnitude of the array.\n */\nexport function magnitude(arr) {\n return Math.sqrt(arr.reduce((acc, val) => acc + val * val, 0));\n}\n\n\n/**\n * Returns the value and index of the minimum element in an array.\n * @param {number[]|TypedArray} arr array of numbers.\n * @returns {[number, number]} the value and index of the minimum element, of the form: [valueOfMin, indexOfMin]\n * @throws {Error} If array is empty.\n */\nexport function min(arr) {\n if (arr.length === 0) throw Error('Array must not be empty');\n let min = arr[0];\n let indexOfMin = 0;\n for (let i = 1; i < arr.length; ++i) {\n if (arr[i] < min) {\n min = arr[i];\n indexOfMin = i;\n }\n }\n return [min, indexOfMin];\n}\n\n\n/**\n * Returns the value and index of the maximum element in an array.\n * @param {number[]|AnyTypedArray} arr array of numbers.\n * @returns {[number, number]} the value and index of the maximum element, of the form: [valueOfMax, indexOfMax]\n * @throws {Error} If array is empty.\n */\nexport function max(arr) {\n if (arr.length === 0) throw Error('Array must not be empty');\n let max = arr[0];\n let indexOfMax = 0;\n for (let i = 1; i < arr.length; ++i) {\n if (arr[i] > max) {\n max = arr[i];\n indexOfMax = i;\n }\n }\n return [Number(max), indexOfMax];\n}\n\nfunction isPowerOfTwo(number) {\n // Check if the number is greater than 0 and has only one bit set to 1\n return (number > 0) && ((number & (number - 1)) === 0);\n}\n\n/**\n * Implementation of Radix-4 FFT.\n * \n * P2FFT class provides functionality for performing Fast Fourier Transform on arrays\n * which are a power of two in length.\n * Code adapted from https://www.npmjs.com/package/fft.js\n */\nclass P2FFT {\n /**\n * @param {number} size The size of the input array. Must be a power of two larger than 1.\n * @throws {Error} FFT size must be a power of two larger than 1.\n */\n constructor(size) {\n this.size = size | 0; // convert to a 32-bit signed integer\n if (this.size <= 1 || !isPowerOfTwo(this.size))\n throw new Error('FFT size must be a power of two larger than 1');\n\n this._csize = size << 1;\n\n this.table = new Float64Array(this.size * 2);\n for (let i = 0; i < this.table.length; i += 2) {\n const angle = Math.PI * i / this.size;\n this.table[i] = Math.cos(angle);\n this.table[i + 1] = -Math.sin(angle);\n }\n\n // Find size's power of two\n let power = 0;\n for (let t = 1; this.size > t; t <<= 1)\n ++power;\n\n // Calculate initial step's width:\n // * If we are full radix-4, it is 2x smaller to give inital len=8\n // * Otherwise it is the same as `power` to give len=4\n this._width = power % 2 === 0 ? power - 1 : power;\n\n // Pre-compute bit-reversal patterns\n this._bitrev = new Int32Array(1 << this._width);\n for (let j = 0; j < this._bitrev.length; ++j) {\n this._bitrev[j] = 0;\n for (let shift = 0; shift < this._width; shift += 2) {\n const revShift = this._width - shift - 2;\n this._bitrev[j] |= ((j >>> shift) & 3) << revShift;\n }\n }\n }\n\n /**\n * Create a complex number array with size `2 * size`\n *\n * @returns {Float64Array} A complex number array with size `2 * size`\n */\n createComplexArray() {\n return new Float64Array(this._csize);\n }\n\n /**\n * Converts a complex number representation stored in a Float64Array to an array of real numbers.\n * \n * @param {Float64Array} complex The complex number representation to be converted.\n * @param {number[]} [storage] An optional array to store the result in.\n * @returns {number[]} An array of real numbers representing the input complex number representation.\n */\n fromComplexArray(complex, storage) {\n const res = storage || new Array(complex.length >>> 1);\n for (let i = 0; i < complex.length; i += 2)\n res[i >>> 1] = complex[i];\n return res;\n }\n\n /**\n * Convert a real-valued input array to a complex-valued output array.\n * @param {Float64Array} input The real-valued input array.\n * @param {Float64Array} [storage] Optional buffer to store the output array.\n * @returns {Float64Array} The complex-valued output array.\n */\n toComplexArray(input, storage) {\n const res = storage || this.createComplexArray();\n for (let i = 0; i < res.length; i += 2) {\n res[i] = input[i >>> 1];\n res[i + 1] = 0;\n }\n return res;\n }\n\n /**\n * Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer.\n * \n * @param {Float64Array} out The output buffer to store the result.\n * @param {Float64Array} data The input data to transform.\n * \n * @throws {Error} Input and output buffers must be different.\n * \n * @returns {void}\n */\n transform(out, data) {\n if (out === data)\n throw new Error('Input and output buffers must be different');\n\n this._transform4(out, data, 1 /* DONE */);\n }\n\n /**\n * Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer.\n * The input buffer must contain real values only, while the output buffer will contain complex values. The input and\n * output buffers must be different.\n *\n * @param {Float64Array} out The output buffer.\n * @param {Float64Array} data The input buffer containing real values.\n *\n * @throws {Error} If the input and output buffers are the same.\n */\n realTransform(out, data) {\n if (out === data)\n throw new Error('Input and output buffers must be different');\n\n this._realTransform4(out, data, 1 /* DONE */);\n }\n\n /**\n * Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`.\n * The `out` array must be a different buffer than the `data` array. The `out` array will contain the\n * result of the transformation. The `data` array will not be modified.\n * \n * @param {Float64Array} out The output buffer for the transformed data.\n * @param {Float64Array} data The input data to transform.\n * @throws {Error} If `out` and `data` refer to the same buffer.\n * @returns {void}\n */\n inverseTransform(out, data) {\n if (out === data)\n throw new Error('Input and output buffers must be different');\n\n this._transform4(out, data, -1 /* DONE */);\n for (let i = 0; i < out.length; ++i)\n out[i] /= this.size;\n }\n\n /**\n * Performs a radix-4 implementation of a discrete Fourier transform on a given set of data.\n *\n * @param {Float64Array} out The output buffer for the transformed data.\n * @param {Float64Array} data The input buffer of data to be transformed.\n * @param {number} inv A scaling factor to apply to the transform.\n * @returns {void}\n */\n _transform4(out, data, inv) {\n // radix-4 implementation\n\n const size = this._csize;\n\n // Initial step (permute and transform)\n const width = this._width;\n let step = 1 << width;\n let len = (size / step) << 1;\n\n let outOff;\n let t;\n const bitrev = this._bitrev;\n if (len === 4) {\n for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n const off = bitrev[t];\n this._singleTransform2(data, out, outOff, off, step);\n }\n } else {\n // len === 8\n for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n const off = bitrev[t];\n this._singleTransform4(data, out, outOff, off, step, inv);\n }\n }\n\n // Loop through steps in decreasing order\n const table = this.table;\n for (step >>= 2; step >= 2; step >>= 2) {\n len = (size / step) << 1;\n const quarterLen = len >>> 2;\n\n // Loop through offsets in the data\n for (outOff = 0; outOff < size; outOff += len) {\n // Full case\n const limit = outOff + quarterLen - 1;\n for (let i = outOff, k = 0; i < limit; i += 2, k += step) {\n const A = i;\n const B = A + quarterLen;\n const C = B + quarterLen;\n const D = C + quarterLen;\n\n // Original values\n const Ar = out[A];\n const Ai = out[A + 1];\n const Br = out[B];\n const Bi = out[B + 1];\n const Cr = out[C];\n const Ci = out[C + 1];\n const Dr = out[D];\n const Di = out[D + 1];\n\n const tableBr = table[k];\n const tableBi = inv * table[k + 1];\n const MBr = Br * tableBr - Bi * tableBi;\n const MBi = Br * tableBi + Bi * tableBr;\n\n const tableCr = table[2 * k];\n const tableCi = inv * table[2 * k + 1];\n const MCr = Cr * tableCr - Ci * tableCi;\n const MCi = Cr * tableCi + Ci * tableCr;\n\n const tableDr = table[3 * k];\n const tableDi = inv * table[3 * k + 1];\n const MDr = Dr * tableDr - Di * tableDi;\n const MDi = Dr * tableDi + Di * tableDr;\n\n // Pre-Final values\n const T0r = Ar + MCr;\n const T0i = Ai + MCi;\n const T1r = Ar - MCr;\n const T1i = Ai - MCi;\n const T2r = MBr + MDr;\n const T2i = MBi + MDi;\n const T3r = inv * (MBr - MDr);\n const T3i = inv * (MBi - MDi);\n\n // Final values\n out[A] = T0r + T2r;\n out[A + 1] = T0i + T2i;\n out[B] = T1r + T3i;\n out[B + 1] = T1i - T3r;\n out[C] = T0r - T2r;\n out[C + 1] = T0i - T2i;\n out[D] = T1r - T3i;\n out[D + 1] = T1i + T3r;\n }\n }\n }\n }\n\n /**\n * Performs a radix-2 implementation of a discrete Fourier transform on a given set of data.\n *\n * @param {Float64Array} data The input buffer of data to be transformed.\n * @param {Float64Array} out The output buffer for the transformed data.\n * @param {number} outOff The offset at which to write the output data.\n * @param {number} off The offset at which to begin reading the input data.\n * @param {number} step The step size for indexing the input data.\n * @returns {void}\n */\n _singleTransform2(data, out, outOff, off, step) {\n // radix-2 implementation\n // NOTE: Only called for len=4\n\n const evenR = data[off];\n const evenI = data[off + 1];\n const oddR = data[off + step];\n const oddI = data[off + step + 1];\n\n out[outOff] = evenR + oddR;\n out[outOff + 1] = evenI + oddI;\n out[outOff + 2] = evenR - oddR;\n out[outOff + 3] = evenI - oddI;\n }\n\n /**\n * Performs radix-4 transformation on input data of length 8\n *\n * @param {Float64Array} data Input data array of length 8\n * @param {Float64Array} out Output data array of length 8\n * @param {number} outOff Index of output array to start writing from\n * @param {number} off Index of input array to start reading from\n * @param {number} step Step size between elements in input array\n * @param {number} inv Scaling factor for inverse transform\n * \n * @returns {void}\n */\n _singleTransform4(data, out, outOff, off, step, inv) {\n // radix-4\n // NOTE: Only called for len=8\n const step2 = step * 2;\n const step3 = step * 3;\n\n // Original values\n const Ar = data[off];\n const Ai = data[off + 1];\n const Br = data[off + step];\n const Bi = data[off + step + 1];\n const Cr = data[off + step2];\n const Ci = data[off + step2 + 1];\n const Dr = data[off + step3];\n const Di = data[off + step3 + 1];\n\n // Pre-Final values\n const T0r = Ar + Cr;\n const T0i = Ai + Ci;\n const T1r = Ar - Cr;\n const T1i = Ai - Ci;\n const T2r = Br + Dr;\n const T2i = Bi + Di;\n const T3r = inv * (Br - Dr);\n const T3i = inv * (Bi - Di);\n\n // Final values\n out[outOff] = T0r + T2r;\n out[outOff + 1] = T0i + T2i;\n out[outOff + 2] = T1r + T3i;\n out[outOff + 3] = T1i - T3r;\n out[outOff + 4] = T0r - T2r;\n out[outOff + 5] = T0i - T2i;\n out[outOff + 6] = T1r - T3i;\n out[outOff + 7] = T1i + T3r;\n }\n\n /**\n * Real input radix-4 implementation\n * @param {Float64Array} out Output array for the transformed data\n * @param {Float64Array} data Input array of real data to be transformed\n * @param {number} inv The scale factor used to normalize the inverse transform\n */\n _realTransform4(out, data, inv) {\n // Real input radix-4 implementation\n const size = this._csize;\n\n // Initial step (permute and transform)\n const width = this._width;\n let step = 1 << width;\n let len = (size / step) << 1;\n\n let outOff;\n let t;\n const bitrev = this._bitrev;\n if (len === 4) {\n for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n const off = bitrev[t];\n this._singleRealTransform2(data, out, outOff, off >>> 1, step >>> 1);\n }\n } else {\n // len === 8\n for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n const off = bitrev[t];\n this._singleRealTransform4(data, out, outOff, off >>> 1, step >>> 1, inv);\n }\n }\n\n // Loop through steps in decreasing order\n const table = this.table;\n for (step >>= 2; step >= 2; step >>= 2) {\n len = (size / step) << 1;\n const halfLen = len >>> 1;\n const quarterLen = halfLen >>> 1;\n const hquarterLen = quarterLen >>> 1;\n\n // Loop through offsets in the data\n for (outOff = 0; outOff < size; outOff += len) {\n for (let i = 0, k = 0; i <= hquarterLen; i += 2, k += step) {\n const A = outOff + i;\n const B = A + quarterLen;\n const C = B + quarterLen;\n const D = C + quarterLen;\n\n // Original values\n const Ar = out[A];\n const Ai = out[A + 1];\n const Br = out[B];\n const Bi = out[B + 1];\n const Cr = out[C];\n const Ci = out[C + 1];\n const Dr = out[D];\n const Di = out[D + 1];\n\n // Middle values\n const MAr = Ar;\n const MAi = Ai;\n\n const tableBr = table[k];\n const tableBi = inv * table[k + 1];\n const MBr = Br * tableBr - Bi * tableBi;\n const MBi = Br * tableBi + Bi * tableBr;\n\n const tableCr = table[2 * k];\n const tableCi = inv * table[2 * k + 1];\n const MCr = Cr * tableCr - Ci * tableCi;\n const MCi = Cr * tableCi + Ci * tableCr;\n\n const tableDr = table[3 * k];\n const tableDi = inv * table[3 * k + 1];\n const MDr = Dr * tableDr - Di * tableDi;\n const MDi = Dr * tableDi + Di * tableDr;\n\n // Pre-Final values\n const T0r = MAr + MCr;\n const T0i = MAi + MCi;\n const T1r = MAr - MCr;\n const T1i = MAi - MCi;\n const T2r = MBr + MDr;\n const T2i = MBi + MDi;\n const T3r = inv * (MBr - MDr);\n const T3i = inv * (MBi - MDi);\n\n // Final values\n out[A] = T0r + T2r;\n out[A + 1] = T0i + T2i;\n out[B] = T1r + T3i;\n out[B + 1] = T1i - T3r;\n\n // Output final middle point\n if (i === 0) {\n out[C] = T0r - T2r;\n out[C + 1] = T0i - T2i;\n continue;\n }\n\n // Do not overwrite ourselves\n if (i === hquarterLen)\n continue;\n\n const SA = outOff + quarterLen - i;\n const SB = outOff + halfLen - i;\n\n out[SA] = T1r - inv * T3i;\n out[SA + 1] = -T1i - inv * T3r;\n out[SB] = T0r - inv * T2r;\n out[SB + 1] = -T0i + inv * T2i;\n }\n }\n }\n\n // Complete the spectrum by adding its mirrored negative frequency components.\n const half = size >>> 1;\n for (let i = 2; i < half; i += 2) {\n out[size - i] = out[i];\n out[size - i + 1] = -out[i + 1];\n }\n }\n\n /**\n * Performs a single real input radix-2 transformation on the provided data\n * \n * @param {Float64Array} data The input data array\n * @param {Float64Array} out The output data array\n * @param {number} outOff The output offset\n * @param {number} off The input offset\n * @param {number} step The step\n * \n * @returns {void}\n */\n _singleRealTransform2(data, out, outOff, off, step) {\n // radix-2 implementation\n // NOTE: Only called for len=4\n\n const evenR = data[off];\n const oddR = data[off + step];\n\n out[outOff] = evenR + oddR;\n out[outOff + 1] = 0;\n out[outOff + 2] = evenR - oddR;\n out[outOff + 3] = 0;\n }\n\n /**\n * Computes a single real-valued transform using radix-4 algorithm.\n * This method is only called for len=8.\n *\n * @param {Float64Array} data The input data array.\n * @param {Float64Array} out The output data array.\n * @param {number} outOff The offset into the output array.\n * @param {number} off The offset into the input array.\n * @param {number} step The step size for the input array.\n * @param {number} inv The value of inverse.\n */\n _singleRealTransform4(data, out, outOff, off, step, inv) {\n // radix-4\n // NOTE: Only called for len=8\n const step2 = step * 2;\n const step3 = step * 3;\n\n // Original values\n const Ar = data[off];\n const Br = data[off + step];\n const Cr = data[off + step2];\n const Dr = data[off + step3];\n\n // Pre-Final values\n const T0r = Ar + Cr;\n const T1r = Ar - Cr;\n const T2r = Br + Dr;\n const T3r = inv * (Br - Dr);\n\n // Final values\n out[outOff] = T0r + T2r;\n out[outOff + 1] = 0;\n out[outOff + 2] = T1r;\n out[outOff + 3] = -T3r;\n out[outOff + 4] = T0r - T2r;\n out[outOff + 5] = 0;\n out[outOff + 6] = T1r;\n out[outOff + 7] = T3r;\n }\n}\n\n/**\n * NP2FFT class provides functionality for performing Fast Fourier Transform on arrays\n * which are not a power of two in length. In such cases, the chirp-z transform is used.\n * \n * For more information, see: https://math.stackexchange.com/questions/77118/non-power-of-2-ffts/77156#77156\n */\nclass NP2FFT {\n\n /**\n * Constructs a new NP2FFT object.\n * @param {number} fft_length The length of the FFT\n */\n constructor(fft_length) {\n // Helper variables\n const a = 2 * (fft_length - 1);\n const b = 2 * (2 * fft_length - 1);\n const nextP2 = 2 ** (Math.ceil(Math.log2(b)))\n this.bufferSize = nextP2;\n this._a = a;\n\n // Define buffers\n // Compute chirp for transform\n const chirp = new Float64Array(b);\n const ichirp = new Float64Array(nextP2);\n this._chirpBuffer = new Float64Array(nextP2);\n this._buffer1 = new Float64Array(nextP2);\n this._buffer2 = new Float64Array(nextP2);\n this._outBuffer1 = new Float64Array(nextP2);\n this._outBuffer2 = new Float64Array(nextP2);\n\n // Compute complex exponentiation\n const theta = -2 * Math.PI / fft_length;\n const baseR = Math.cos(theta);\n const baseI = Math.sin(theta);\n\n // Precompute helper for chirp-z transform\n for (let i = 0; i < b >> 1; ++i) {\n // Compute complex power:\n const e = (i + 1 - fft_length) ** 2 / 2.0;\n\n // Compute the modulus and argument of the result\n const result_mod = Math.sqrt(baseR ** 2 + baseI ** 2) ** e;\n const result_arg = e * Math.atan2(baseI, baseR);\n\n // Convert the result back to rectangular form\n // and assign to chirp and ichirp\n const i2 = 2 * i;\n chirp[i2] = result_mod * Math.cos(result_arg);\n chirp[i2 + 1] = result_mod * Math.sin(result_arg);\n\n // conjugate\n ichirp[i2] = chirp[i2];\n ichirp[i2 + 1] = - chirp[i2 + 1];\n }\n this._slicedChirpBuffer = chirp.subarray(a, b);\n\n // create object to perform Fast Fourier Transforms\n // with `nextP2` complex numbers\n this._f = new P2FFT(nextP2 >> 1);\n this._f.transform(this._chirpBuffer, ichirp);\n }\n\n _transform(output, input, real) {\n const ib1 = this._buffer1;\n const ib2 = this._buffer2;\n const ob2 = this._outBuffer1;\n const ob3 = this._outBuffer2;\n const cb = this._chirpBuffer;\n const sb = this._slicedChirpBuffer;\n const a = this._a;\n\n if (real) {\n // Real multiplication\n for (let j = 0; j < sb.length; j += 2) {\n const j2 = j + 1\n const j3 = j >> 1;\n\n const a_real = input[j3];\n ib1[j] = a_real * sb[j];\n ib1[j2] = a_real * sb[j2];\n }\n } else {\n // Complex multiplication\n for (let j = 0; j < sb.length; j += 2) {\n const j2 = j + 1\n ib1[j] = input[j] * sb[j] - input[j2] * sb[j2];\n ib1[j2] = input[j] * sb[j2] + input[j2] * sb[j];\n }\n }\n this._f.transform(ob2, ib1);\n\n for (let j = 0; j < cb.length; j += 2) {\n const j2 = j + 1;\n\n ib2[j] = ob2[j] * cb[j] - ob2[j2] * cb[j2];\n ib2[j2] = ob2[j] * cb[j2] + ob2[j2] * cb[j];\n }\n this._f.inverseTransform(ob3, ib2);\n\n for (let j = 0; j < ob3.length; j += 2) {\n const a_real = ob3[j + a];\n const a_imag = ob3[j + a + 1];\n const b_real = sb[j];\n const b_imag = sb[j + 1];\n\n output[j] = a_real * b_real - a_imag * b_imag;\n output[j + 1] = a_real * b_imag + a_imag * b_real;\n }\n }\n\n transform(output, input) {\n this._transform(output, input, false);\n }\n\n realTransform(output, input) {\n this._transform(output, input, true);\n }\n}\n\nexport class FFT {\n constructor(fft_length) {\n this.fft_length = fft_length;\n this.isPowerOfTwo = isPowerOfTwo(fft_length);\n if (this.isPowerOfTwo) {\n this.fft = new P2FFT(fft_length);\n this.outputBufferSize = 2 * fft_length;\n } else {\n this.fft = new NP2FFT(fft_length);\n this.outputBufferSize = this.fft.bufferSize;\n }\n }\n\n realTransform(out, input) {\n this.fft.realTransform(out, input);\n }\n\n transform(out, input) {\n this.fft.transform(out, input);\n }\n}\n\n\n/**\n * Performs median filter on the provided data. Padding is done by mirroring the data.\n * @param {AnyTypedArray} data The input array\n * @param {number} windowSize The window size\n */\nexport function medianFilter(data, windowSize) {\n\n if (windowSize % 2 === 0 || windowSize <= 0) {\n throw new Error('Window size must be a positive odd number');\n }\n\n // @ts-ignore\n const outputArray = new data.constructor(data.length);\n\n // @ts-ignore\n const buffer = new data.constructor(windowSize); // Reusable array for storing values\n\n const halfWindowSize = Math.floor(windowSize / 2);\n\n for (let i = 0; i < data.length; ++i) {\n let valuesIndex = 0;\n\n for (let j = -halfWindowSize; j <= halfWindowSize; ++j) {\n let index = i + j;\n if (index < 0) {\n index = Math.abs(index);\n } else if (index >= data.length) {\n index = 2 * (data.length - 1) - index;\n }\n\n buffer[valuesIndex++] = data[index];\n }\n\n buffer.sort();\n outputArray[i] = buffer[halfWindowSize];\n }\n\n return outputArray;\n}\n\n/**\n * Helper function to round a number to a given number of decimals\n * @param {number} num The number to round\n * @param {number} decimals The number of decimals\n * @returns {number} The rounded number\n */\nexport function round(num, decimals) {\n const pow = Math.pow(10, decimals);\n return Math.round(num * pow) / pow;\n}\n\n/**\n * Helper function to round a number to the nearest integer, with ties rounded to the nearest even number.\n * Also known as \"bankers' rounding\". This is the default rounding mode in python. For example:\n * 1.5 rounds to 2 and 2.5 rounds to 2.\n * \n * @param {number} x The number to round\n * @returns {number} The rounded number\n */\nexport function bankers_round(x) {\n const r = Math.round(x);\n const br = Math.abs(x) % 1 === 0.5 ? (r % 2 === 0 ? r : r - 1) : r;\n return br;\n}\n\n\n/**\n * Measures similarity between two temporal sequences (e.g., input audio and output tokens\n * to generate token-level timestamps).\n * @param {number[][]} matrix \n * @returns {number[][]}\n */\nexport function dynamic_time_warping(matrix) {\n const output_length = matrix.length;\n const input_length = matrix[0].length;\n\n const outputShape = [output_length + 1, input_length + 1];\n\n const cost = Array.from(\n { length: outputShape[0] },\n () => Array(outputShape[1]).fill(Infinity)\n );\n cost[0][0] = 0;\n\n const trace = Array.from(\n { length: outputShape[0] },\n () => Array(outputShape[1]).fill(-1)\n );\n\n for (let j = 1; j < outputShape[1]; ++j) {\n for (let i = 1; i < outputShape[0]; ++i) {\n const c0 = cost[i - 1][j - 1];\n const c1 = cost[i - 1][j];\n const c2 = cost[i][j - 1];\n\n let c, t;\n if (c0 < c1 && c0 < c2) {\n c = c0;\n t = 0;\n } else if (c1 < c0 && c1 < c2) {\n c = c1;\n t = 1;\n } else {\n c = c2;\n t = 2;\n }\n cost[i][j] = matrix[i - 1][j - 1] + c;\n trace[i][j] = t;\n }\n }\n\n for (let i = 0; i < outputShape[1]; ++i) { // trace[0, :] = 2\n trace[0][i] = 2;\n }\n for (let i = 0; i < outputShape[0]; ++i) { // trace[:, 0] = 1\n trace[i][0] = 1;\n }\n\n // backtrace\n let i = output_length;\n let j = input_length;\n let text_indices = [];\n let time_indices = [];\n while (i > 0 || j > 0) {\n text_indices.push(i - 1);\n time_indices.push(j - 1);\n\n switch (trace[i][j]) {\n case 0:\n --i; --j;\n break;\n case 1:\n --i;\n break;\n case 2:\n --j;\n break;\n default:\n throw new Error(\n `Internal error in dynamic time warping. Unexpected trace[${i}, ${j}]. Please file a bug report.`\n )\n }\n }\n\n text_indices.reverse();\n time_indices.reverse();\n\n return [text_indices, time_indices];\n\n}\n","/**\n * @file Helper module for `Tensor` processing.\n *\n * These functions and classes are only used internally,\n * meaning an end-user shouldn't need to access anything here.\n *\n * @module utils/tensor\n */\n\nimport {\n interpolate_data,\n permute_data\n} from './maths.js';\n\nimport {\n Tensor as ONNXTensor, isONNXTensor,\n} from '../backends/onnx.js';\n\nimport { TensorOpRegistry } from '../ops/registry.js';\n\nconst DataTypeMap = Object.freeze({\n float32: Float32Array,\n float16: Uint16Array,\n float64: Float64Array,\n string: Array, // string[]\n int8: Int8Array,\n uint8: Uint8Array,\n int16: Int16Array,\n uint16: Uint16Array,\n int32: Int32Array,\n uint32: Uint32Array,\n int64: BigInt64Array,\n uint64: BigUint64Array,\n bool: Uint8Array,\n});\n\n/**\n * @typedef {keyof typeof DataTypeMap} DataType\n * @typedef {import('./maths.js').AnyTypedArray | any[]} DataArray\n */\n\n\nexport class Tensor {\n /** @type {number[]} Dimensions of the tensor. */\n get dims() {\n // @ts-ignore\n return this.ort_tensor.dims;\n }\n set dims(value) {\n // FIXME: ONNXTensor declares dims as readonly so one needs to use the constructor() if dims change.\n // @ts-ignore\n this.ort_tensor.dims = value;\n }\n\n /** @type {DataType} Type of the tensor. */\n get type() {\n return this.ort_tensor.type;\n };\n\n /** @type {DataArray} The data stored in the tensor. */\n get data() {\n return this.ort_tensor.data;\n }\n\n /** @type {number} The number of elements in the tensor. */\n get size() {\n return this.ort_tensor.size;\n };\n\n /** @type {string} The location of the tensor data. */\n get location() {\n return this.ort_tensor.location;\n };\n\n ort_tensor;\n\n /**\n * Create a new Tensor or copy an existing Tensor.\n * @param {[DataType, DataArray, number[]]|[ONNXTensor]} args\n */\n constructor(...args) {\n if (isONNXTensor(args[0])) {\n this.ort_tensor = /** @type {ONNXTensor} */ (args[0]);\n } else {\n // Create new tensor\n this.ort_tensor = new ONNXTensor(\n /** @type {DataType} */(args[0]),\n /** @type {Exclude} */(args[1]),\n args[2]\n );\n }\n\n return new Proxy(this, {\n get: (obj, key) => {\n if (typeof key === 'string') {\n let index = Number(key);\n if (Number.isInteger(index)) {\n // key is an integer (i.e., index)\n return obj._getitem(index);\n }\n }\n // @ts-ignore\n return obj[key];\n },\n set: (obj, key, value) => {\n // TODO allow setting of data\n\n // @ts-ignore\n return obj[key] = value;\n }\n });\n }\n\n dispose() {\n this.ort_tensor.dispose();\n // this.ort_tensor = undefined;\n }\n\n /**\n * Returns an iterator object for iterating over the tensor data in row-major order.\n * If the tensor has more than one dimension, the iterator will yield subarrays.\n * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order.\n */\n *[Symbol.iterator]() {\n const [iterLength, ...iterDims] = this.dims;\n\n if (iterDims.length > 0) {\n const iterSize = iterDims.reduce((a, b) => a * b);\n for (let i = 0; i < iterLength; ++i) {\n yield this._subarray(i, iterSize, iterDims);\n }\n } else {\n yield* this.data\n }\n\n }\n\n /**\n * Index into a Tensor object.\n * @param {number} index The index to access.\n * @returns {Tensor} The data at the specified index.\n */\n _getitem(index) {\n const [iterLength, ...iterDims] = this.dims;\n\n index = safeIndex(index, iterLength);\n\n if (iterDims.length > 0) {\n const iterSize = iterDims.reduce((a, b) => a * b);\n return this._subarray(index, iterSize, iterDims);\n } else {\n return new Tensor(this.type, [this.data[index]], iterDims);\n }\n }\n\n /**\n * @param {number|bigint} item The item to search for in the tensor\n * @returns {number} The index of the first occurrence of item in the tensor data.\n */\n indexOf(item) {\n const this_data = this.data;\n for (let index = 0; index < this_data.length; ++index) {\n // Note: == instead of === so we can match Ints with BigInts\n if (this_data[index] == item) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * @param {number} index\n * @param {number} iterSize\n * @param {any} iterDims\n * @returns {Tensor}\n */\n _subarray(index, iterSize, iterDims) {\n const o1 = index * iterSize;\n const o2 = (index + 1) * iterSize;\n\n // We use subarray if available (typed array), otherwise we use slice (normal array)\n const data =\n ('subarray' in this.data)\n ? this.data.subarray(o1, o2)\n : this.data.slice(o1, o2);\n return new Tensor(this.type, data, iterDims);\n }\n\n /**\n * Returns the value of this tensor as a standard JavaScript Number. This only works\n * for tensors with one element. For other cases, see `Tensor.tolist()`.\n * @returns {number|bigint} The value of this tensor as a standard JavaScript Number.\n * @throws {Error} If the tensor has more than one element.\n */\n item() {\n const this_data = this.data;\n if (this_data.length !== 1) {\n throw new Error(`a Tensor with ${this_data.length} elements cannot be converted to Scalar`);\n }\n return this_data[0];\n }\n\n /**\n * Convert tensor data to a n-dimensional JS list\n * @returns {Array}\n */\n tolist() {\n return reshape(this.data, this.dims)\n }\n\n /**\n * Return a new Tensor with the sigmoid function applied to each element.\n * @returns {Tensor} The tensor with the sigmoid function applied.\n */\n sigmoid() {\n return this.clone().sigmoid_();\n }\n\n /**\n * Applies the sigmoid function to the tensor in place.\n * @returns {Tensor} Returns `this`.\n */\n sigmoid_() {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = 1 / (1 + Math.exp(-this_data[i]));\n }\n return this;\n }\n\n /**\n * Return a new Tensor with a callback function applied to each element.\n * @param {Function} callback - The function to apply to each element. It should take three arguments:\n * the current element, its index, and the tensor's data array.\n * @returns {Tensor} A new Tensor with the callback function applied to each element.\n */\n map(callback) {\n return this.clone().map_(callback);\n }\n\n /**\n * Apply a callback function to each element of the tensor in place.\n * @param {Function} callback - The function to apply to each element. It should take three arguments:\n * the current element, its index, and the tensor's data array.\n * @returns {Tensor} Returns `this`.\n */\n map_(callback) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = callback(this_data[i], i, this_data);\n }\n return this;\n }\n\n /**\n * Return a new Tensor with every element multiplied by a constant.\n * @param {number} val The value to multiply by.\n * @returns {Tensor} The new tensor.\n */\n mul(val) {\n return this.clone().mul_(val);\n }\n\n /**\n * Multiply the tensor by a constant in place.\n * @param {number} val The value to multiply by.\n * @returns {Tensor} Returns `this`.\n */\n mul_(val) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] *= val;\n }\n return this;\n }\n\n /**\n * Return a new Tensor with every element divided by a constant.\n * @param {number} val The value to divide by.\n * @returns {Tensor} The new tensor.\n */\n div(val) {\n return this.clone().div_(val);\n }\n\n /**\n * Divide the tensor by a constant in place.\n * @param {number} val The value to divide by.\n * @returns {Tensor} Returns `this`.\n */\n div_(val) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] /= val;\n }\n return this;\n }\n\n /**\n * Return a new Tensor with every element added by a constant.\n * @param {number} val The value to add by.\n * @returns {Tensor} The new tensor.\n */\n add(val) {\n return this.clone().add_(val);\n }\n\n /**\n * Add the tensor by a constant in place.\n * @param {number} val The value to add by.\n * @returns {Tensor} Returns `this`.\n */\n add_(val) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] += val;\n }\n return this;\n }\n\n /**\n * Return a new Tensor with every element subtracted by a constant.\n * @param {number} val The value to subtract by.\n * @returns {Tensor} The new tensor.\n */\n sub(val) {\n return this.clone().sub_(val);\n }\n\n /**\n * Subtract the tensor by a constant in place.\n * @param {number} val The value to subtract by.\n * @returns {Tensor} Returns `this`.\n */\n sub_(val) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] -= val;\n }\n return this;\n }\n\n clone() {\n return new Tensor(this.type, this.data.slice(), this.dims.slice());\n }\n\n slice(...slices) {\n // This allows for slicing with ranges and numbers\n const newTensorDims = [];\n const newOffsets = [];\n\n // slices is an array of numbers or arrays of numbers\n // e.g., slices = [0, [1, 3], null, [0, 3]]\n for (let sliceIndex = 0; sliceIndex < this.dims.length; ++sliceIndex) {\n let slice = slices[sliceIndex];\n\n if (slice === null || slice === undefined) {\n // null or undefined means take the whole dimension\n newOffsets.push([0, this.dims[sliceIndex]]);\n newTensorDims.push(this.dims[sliceIndex]);\n\n } else if (typeof slice === 'number') {\n slice = safeIndex(slice, this.dims[sliceIndex], sliceIndex);\n\n // A number means take a single element\n newOffsets.push([slice, slice + 1]);\n\n } else if (Array.isArray(slice) && slice.length === 2) {\n // An array of length 2 means take a range of elements\n let [start, end] = slice;\n start = start === null\n ? 0\n : safeIndex(start, this.dims[sliceIndex], sliceIndex, false);\n end = end === null\n ? this.dims[sliceIndex]\n : safeIndex(end, this.dims[sliceIndex], sliceIndex, false);\n\n if (start > end) {\n throw new Error(`Invalid slice: ${slice}`);\n }\n\n const offsets = [\n Math.max(start, 0),\n Math.min(end, this.dims[sliceIndex])\n ];\n\n newOffsets.push(offsets);\n newTensorDims.push(offsets[1] - offsets[0]);\n\n } else {\n throw new Error(`Invalid slice: ${slice}`);\n }\n }\n\n const newDims = newOffsets.map(([start, end]) => end - start);\n const newBufferSize = newDims.reduce((a, b) => a * b);\n\n const this_data = this.data;\n // Allocate memory\n // @ts-ignore\n const data = new this_data.constructor(newBufferSize);\n\n // Precompute strides\n const stride = this.stride();\n\n for (let i = 0; i < newBufferSize; ++i) {\n let originalIndex = 0;\n for (let j = newDims.length - 1, num = i; j >= 0; --j) {\n const size = newDims[j];\n originalIndex += ((num % size) + newOffsets[j][0]) * stride[j];\n num = Math.floor(num / size);\n }\n data[i] = this_data[originalIndex];\n }\n return new Tensor(this.type, data, newTensorDims);\n\n }\n\n /**\n * Return a permuted version of this Tensor, according to the provided dimensions.\n * @param {...number} dims Dimensions to permute.\n * @returns {Tensor} The permuted tensor.\n */\n permute(...dims) {\n return permute(this, dims);\n }\n\n // TODO: implement transpose. For now (backwards compatibility), it's just an alias for permute()\n transpose(...dims) {\n return this.permute(...dims);\n }\n\n // TODO add .max() and .min() methods\n\n /**\n * Returns the sum of each row of the input tensor in the given dimension dim.\n *\n * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced.\n * @param {boolean} keepdim Whether the output tensor has `dim` retained or not.\n * @returns The summed tensor\n */\n sum(dim = null, keepdim = false) {\n return this.norm(1, dim, keepdim);\n }\n\n /**\n * Returns the matrix norm or vector norm of a given tensor.\n * @param {number|string} [p='fro'] The order of norm\n * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across.\n * If dim is None, the norm will be calculated across all dimensions of input.\n * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not.\n * @returns {Tensor} The norm of the tensor.\n */\n norm(p = 'fro', dim = null, keepdim = false) {\n if (p === 'fro') {\n // NOTE: Since we only support integer dims, Frobenius norm produces the same result as p=2.\n p = 2;\n } else if (typeof p === 'string') {\n throw Error(`Unsupported norm: ${p}`);\n }\n\n const this_data = this.data;\n\n if (dim === null) {\n // @ts-ignore\n let val = this_data.reduce((a, b) => a + (b ** p), 0) ** (1 / p);\n return new Tensor(this.type, [val], []);\n }\n\n // Negative indexing\n dim = safeIndex(dim, this.dims.length);\n\n // Calculate the shape of the resulting array after summation\n const resultDims = this.dims.slice(); // Copy the original dimensions\n resultDims[dim] = 1; // Remove the specified axis\n\n // Create a new array to store the accumulated values\n // @ts-ignore\n const result = new this_data.constructor(this_data.length / this.dims[dim]);\n\n // Iterate over the data array\n for (let i = 0; i < this_data.length; ++i) {\n\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = this.dims[j];\n if (j !== dim) {\n const index = num % size;\n resultIndex += index * resultMultiplier;\n resultMultiplier *= resultDims[j];\n }\n num = Math.floor(num / size);\n }\n\n // Accumulate the value at the current index\n result[resultIndex] += (this_data[i]) ** p;\n }\n\n if (p !== 1) {\n for (let i = 0; i < result.length; ++i) {\n result[i] = result[i] ** (1 / p);\n }\n }\n\n if (!keepdim) {\n resultDims.splice(dim, 1);\n }\n\n return new Tensor(this.type, result, resultDims);\n }\n\n /**\n * Performs `L_p` normalization of inputs over specified dimension. Operates in place.\n * @param {number} [p=2] The exponent value in the norm formulation\n * @param {number} [dim=1] The dimension to reduce\n * @returns {Tensor} `this` for operation chaining.\n */\n normalize_(p = 2.0, dim = 1) {\n dim = safeIndex(dim, this.dims.length);\n\n const norm = this.norm(p, dim, true);\n\n const this_data = this.data;\n const norm_data = norm.data;\n for (let i = 0; i < this_data.length; ++i) {\n\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = this.dims[j];\n if (j !== dim) {\n const index = num % size;\n resultIndex += index * resultMultiplier;\n resultMultiplier *= this.dims[j];\n }\n num = Math.floor(num / size);\n }\n\n // Divide by normalized value\n this_data[i] /= norm_data[resultIndex];\n }\n\n return this;\n }\n\n /**\n * Performs `L_p` normalization of inputs over specified dimension.\n * @param {number} [p=2] The exponent value in the norm formulation\n * @param {number} [dim=1] The dimension to reduce\n * @returns {Tensor} The normalized tensor.\n */\n normalize(p = 2.0, dim = 1) {\n return this.clone().normalize_(p, dim);\n }\n\n /**\n * Compute and return the stride of this tensor.\n * Stride is the jump necessary to go from one element to the next one in the specified dimension dim.\n * @returns {number[]} The stride of this tensor.\n */\n stride() {\n return dimsToStride(this.dims);\n }\n\n /**\n * Returns a tensor with all specified dimensions of input of size 1 removed.\n *\n * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other.\n * If you would like a copy, use `tensor.clone()` before squeezing.\n *\n * @param {number} [dim=null] If given, the input will be squeezed only in the specified dimensions.\n * @returns {Tensor} The squeezed tensor\n */\n squeeze(dim = null) {\n return new Tensor(\n this.type,\n this.data,\n calc_squeeze_dims(this.dims, dim)\n )\n }\n\n /**\n * In-place version of @see {@link Tensor.squeeze}\n */\n squeeze_(dim = null) {\n this.dims = calc_squeeze_dims(this.dims, dim);\n return this;\n }\n\n /**\n * Returns a new tensor with a dimension of size one inserted at the specified position.\n *\n * NOTE: The returned tensor shares the same underlying data with this tensor.\n *\n * @param {number} dim The index at which to insert the singleton dimension\n * @returns {Tensor} The unsqueezed tensor\n */\n unsqueeze(dim = null) {\n return new Tensor(\n this.type,\n this.data,\n calc_unsqueeze_dims(this.dims, dim)\n );\n }\n\n /**\n * In-place version of @see {@link Tensor.unsqueeze}\n */\n unsqueeze_(dim = null) {\n this.dims = calc_unsqueeze_dims(this.dims, dim);\n return this;\n }\n\n /**\n * In-place version of @see {@link Tensor.flatten}\n */\n flatten_(start_dim = 0, end_dim = -1) {\n // TODO validate inputs\n end_dim = (end_dim + this.dims.length) % this.dims.length;\n\n let dimsToKeepBefore = this.dims.slice(0, start_dim);\n let dimsToFlatten = this.dims.slice(start_dim, end_dim + 1);\n let dimsToKeepAfter = this.dims.slice(end_dim + 1);\n\n this.dims = [...dimsToKeepBefore, dimsToFlatten.reduce((a, b) => a * b, 1), ...dimsToKeepAfter]\n return this;\n }\n\n /**\n * Flattens input by reshaping it into a one-dimensional tensor.\n * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim`\n * and ending with `end_dim` are flattened. The order of elements in input is unchanged.\n * @param {number} start_dim the first dim to flatten\n * @param {number} end_dim the last dim to flatten\n * @returns {Tensor} The flattened tensor.\n */\n flatten(start_dim = 0, end_dim = -1) {\n return this.clone().flatten_(start_dim, end_dim);\n }\n\n /**\n * Returns a new tensor with the same data as the `self` tensor but of a different `shape`.\n * @param {...number} dims the desired size\n * @returns {Tensor} The tensor with the same data but different shape\n */\n view(...dims) {\n // TODO: validate dims\n let inferredIndex = -1;\n for (let i = 0; i < dims.length; ++i) {\n if (dims[i] === -1) {\n if (inferredIndex !== -1) {\n throw new Error(\"Only one dimension can be inferred\");\n }\n inferredIndex = i;\n }\n }\n\n const this_data = this.data;\n if (inferredIndex !== -1) {\n // Some dimension must be inferred\n const productOther = dims.reduce((product, curr, index) => {\n return index !== inferredIndex ? product * curr : product\n }, 1);\n\n dims[inferredIndex] = this_data.length / productOther;\n }\n return new Tensor(this.type, this_data, dims); // NOTE: uses same underlying storage\n }\n\n neg_() {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = -this_data[i];\n }\n return this;\n }\n neg() {\n return this.clone().neg_();\n }\n\n /**\n * In-place version of @see {@link Tensor.clamp}\n */\n clamp_(min, max) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = Math.min(Math.max(this_data[i], min), max);\n }\n return this;\n }\n\n /**\n * Clamps all elements in input into the range [ min, max ]\n * @param {number} min lower-bound of the range to be clamped to\n * @param {number} max upper-bound of the range to be clamped to\n * @returns {Tensor} the output tensor.\n */\n clamp(min, max) {\n return this.clone().clamp_(min, max);\n }\n\n /**\n * In-place version of @see {@link Tensor.round}\n */\n round_() {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = Math.round(this_data[i]);\n }\n return this;\n }\n\n /**\n * Rounds elements of input to the nearest integer.\n * @returns {Tensor} the output tensor.\n */\n round() {\n return this.clone().round_();\n }\n\n mean(dim = null, keepdim = false) {\n return mean(this, dim, keepdim);\n }\n\n /**\n * Performs Tensor dtype conversion.\n * @param {DataType} type The desired data type.\n * @returns {Tensor} The converted tensor.\n */\n to(type) {\n // If the self Tensor already has the correct dtype, then self is returned.\n if (this.type === type) return this;\n\n // Otherwise, the returned tensor is a copy of self with the desired dtype.\n if (!DataTypeMap.hasOwnProperty(type)) {\n throw new Error(`Unsupported type: ${type}`);\n }\n // @ts-ignore\n return new Tensor(type, DataTypeMap[type].from(this.data), this.dims);\n }\n}\n\n/**\n * This creates a nested array of a given type and depth (see examples).\n *\n * @example\n * NestArray; // string[]\n * @example\n * NestArray; // number[][]\n * @example\n * NestArray; // string[][][] etc.\n * @template T\n * @template {number} Depth\n * @template {never[]} [Acc=[]]\n * @typedef {Acc['length'] extends Depth ? T : NestArray} NestArray\n */\n\n/**\n * Reshapes a 1-dimensional array into an n-dimensional array, according to the provided dimensions.\n *\n * @example\n * reshape([10 ], [1 ]); // Type: number[] Value: [10]\n * reshape([1, 2, 3, 4 ], [2, 2 ]); // Type: number[][] Value: [[1, 2], [3, 4]]\n * reshape([1, 2, 3, 4, 5, 6, 7, 8], [2, 2, 2]); // Type: number[][][] Value: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]\n * reshape([1, 2, 3, 4, 5, 6, 7, 8], [4, 2 ]); // Type: number[][] Value: [[1, 2], [3, 4], [5, 6], [7, 8]]\n * @param {T[]|DataArray} data The input array to reshape.\n * @param {DIM} dimensions The target shape/dimensions.\n * @template T\n * @template {[number]|number[]} DIM\n * @returns {NestArray} The reshaped array.\n */\nfunction reshape(data, dimensions) {\n\n const totalElements = data.length;\n const dimensionSize = dimensions.reduce((a, b) => a * b);\n\n if (totalElements !== dimensionSize) {\n throw Error(`cannot reshape array of size ${totalElements} into shape (${dimensions})`);\n }\n\n /** @type {any} */\n let reshapedArray = data;\n\n for (let i = dimensions.length - 1; i >= 0; i--) {\n reshapedArray = reshapedArray.reduce((acc, val) => {\n let lastArray = acc[acc.length - 1];\n\n if (lastArray.length < dimensions[i]) {\n lastArray.push(val);\n } else {\n acc.push([val]);\n }\n\n return acc;\n }, [[]]);\n }\n\n return reshapedArray[0];\n}\n\n/**\n * Permutes a tensor according to the provided axes.\n * @param {any} tensor The input tensor to permute.\n * @param {Array} axes The axes to permute the tensor along.\n * @returns {Tensor} The permuted tensor.\n */\nexport function permute(tensor, axes) {\n const [permutedData, shape] = permute_data(tensor.data, tensor.dims, axes);\n return new Tensor(tensor.type, permutedData, shape);\n}\n\n\n/**\n * Interpolates an Tensor to the given size.\n * @param {Tensor} input The input tensor to interpolate. Data must be channel-first (i.e., [c, h, w])\n * @param {number[]} size The output size of the image\n * @param {string} mode The interpolation mode\n * @param {boolean} align_corners Whether to align corners.\n * @returns {Tensor} The interpolated tensor.\n */\nexport function interpolate(input, [out_height, out_width], mode = 'bilinear', align_corners = false) {\n\n // Input image dimensions\n const in_channels = input.dims.at(-3) ?? 1;\n const in_height = input.dims.at(-2);\n const in_width = input.dims.at(-1);\n\n let output = interpolate_data(\n /** @type {import('./maths.js').TypedArray}*/(input.data),\n [in_channels, in_height, in_width],\n [out_height, out_width],\n mode,\n align_corners\n );\n return new Tensor(input.type, output, [in_channels, out_height, out_width]);\n}\n\n\n/**\n * Down/up samples the input.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html.\n * @param {Tensor} input the input tensor\n * @param {Object} options the options for the interpolation\n * @param {[number, number]|[number, number, number]|[number, number, number, number]} [options.size=null] output spatial size.\n * @param {\"bilinear\"|\"bicubic\"} [options.mode='bilinear'] algorithm used for upsampling\n * @returns {Promise} The interpolated tensor.\n */\nexport async function interpolate_4d(input, {\n size = null,\n mode = 'bilinear',\n} = {}) {\n\n // Error checking\n if (input.dims.length !== 4) {\n throw new Error('`interpolate_4d` currently only supports 4D input.');\n }\n if (!size) {\n // TODO: support scale_factor\n throw new Error('`interpolate_4d` requires a `size` argument.');\n }\n\n // Fill in missing dimensions\n let targetDims;\n if (size.length === 2) {\n targetDims = [...input.dims.slice(0, 2), ...size];\n } else if (size.length === 3) {\n targetDims = [input.dims[0], ...size];\n } else if (size.length === 4) {\n targetDims = size;\n } else {\n throw new Error('`size` must be of length 2, 3, or 4.');\n }\n\n let op;\n if (mode === 'bilinear') {\n op = await TensorOpRegistry.bilinear_interpolate_4d;\n } else if (mode === 'bicubic') {\n op = await TensorOpRegistry.bicubic_interpolate_4d;\n } else {\n throw new Error(`Unsupported mode: ${mode}`);\n }\n\n const sizeTensor = new Tensor('int64', new BigInt64Array(targetDims.map(BigInt)), [targetDims.length]);\n return await op({ x: input, s: sizeTensor });\n}\n\n/**\n * Matrix product of two tensors.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.matmul.html\n * @param {Tensor} a the first tensor to be multiplied\n * @param {Tensor} b the second tensor to be multiplied\n * @returns {Promise} The matrix product of the two tensors.\n */\nexport async function matmul(a, b) {\n const op = await TensorOpRegistry.matmul;\n return await op({ a, b });\n}\n\n/**\n * Computes the one dimensional Fourier transform of real-valued input.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.fft.rfft.html\n * @param {Tensor} x the real input tensor\n * @param {Tensor} a The dimension along which to take the one dimensional real FFT.\n * @returns {Promise} the output tensor.\n */\nexport async function rfft(x, a) {\n const op = await TensorOpRegistry.rfft;\n return await op({ x, a });\n}\n\n\n/**\n * Returns the k largest elements of the given input tensor.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.topk.html\n * @param {Tensor} x the input tensor\n * @param {number} k the k in \"top-k\"\n * @returns {Promise<[Tensor, Tensor]>} the output tuple of (Tensor, LongTensor) of top-k elements and their indices.\n */\nexport async function topk(x, k) {\n const op = await TensorOpRegistry.top_k;\n\n if (k === null) {\n k = x.dims.at(-1);\n } else {\n k = Math.min(k, x.dims.at(-1));\n }\n return await op({\n x,\n k: new Tensor(\n 'int64',\n [BigInt(k)],\n [1]\n )\n });\n}\n\n/**\n * Perform mean pooling of the last hidden state followed by a normalization step.\n * @param {Tensor} last_hidden_state Tensor of shape [batchSize, seqLength, embedDim]\n * @param {Tensor} attention_mask Tensor of shape [batchSize, seqLength]\n * @returns {Tensor} Returns a new Tensor of shape [batchSize, embedDim].\n */\nexport function mean_pooling(last_hidden_state, attention_mask) {\n // last_hidden_state: [batchSize, seqLength, embedDim]\n // attention_mask: [batchSize, seqLength]\n const lastHiddenStateData = last_hidden_state.data;\n const attentionMaskData = attention_mask.data;\n\n const shape = [last_hidden_state.dims[0], last_hidden_state.dims[2]];\n\n // @ts-ignore\n const returnedData = new lastHiddenStateData.constructor(shape[0] * shape[1]);\n const [batchSize, seqLength, embedDim] = last_hidden_state.dims;\n\n let outIndex = 0;\n for (let i = 0; i < batchSize; ++i) {\n const offset = i * embedDim * seqLength;\n\n for (let k = 0; k < embedDim; ++k) {\n let sum = 0;\n let count = 0;\n\n const attnMaskOffset = i * seqLength;\n const offset2 = offset + k;\n // Pool over all words in sequence\n for (let j = 0; j < seqLength; ++j) {\n // index into attention mask\n const attn = Number(attentionMaskData[attnMaskOffset + j]);\n\n count += attn;\n sum += lastHiddenStateData[offset2 + j * embedDim] * attn;\n }\n\n const avg = sum / count;\n returnedData[outIndex++] = avg;\n }\n }\n\n return new Tensor(\n last_hidden_state.type,\n returnedData,\n shape\n )\n}\n\n/**\n * Apply Layer Normalization for last certain number of dimensions.\n * @param {Tensor} input The input tensor\n * @param {number[]} normalized_shape input shape from an expected input of size\n * @param {Object} options The options for the layer normalization\n * @param {number} [options.eps=1e-5] A value added to the denominator for numerical stability.\n * @returns {Tensor} The normalized tensor.\n */\nexport function layer_norm(input, normalized_shape, {\n eps = 1e-5,\n} = {}) {\n if (input.dims.length !== 2) {\n throw new Error('`layer_norm` currently only supports 2D input.');\n }\n\n const [batchSize, featureDim] = input.dims;\n\n if (normalized_shape.length !== 1 && normalized_shape[0] !== featureDim) {\n throw new Error('`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.');\n }\n\n const [std, mean] = std_mean(input, 1, 0, true);\n const stdData = /** @type {Float32Array} */(std.data);\n const meanData = /** @type {Float32Array} */(mean.data);\n\n const inputData = /** @type {Float32Array} */(input.data);\n\n // @ts-ignore\n const returnedData = new inputData.constructor(inputData.length);\n\n for (let i = 0; i < batchSize; ++i) {\n const offset = i * featureDim;\n for (let j = 0; j < featureDim; ++j) {\n const offset2 = offset + j;\n returnedData[offset2] = (inputData[offset2] - meanData[i]) / (stdData[i] + eps);\n }\n }\n return new Tensor(input.type, returnedData, input.dims);\n}\n\n/**\n * Helper function to calculate new dimensions when performing a squeeze operation.\n * @param {number[]} dims The dimensions of the tensor.\n * @param {number|number[]|null} dim The dimension(s) to squeeze.\n * @returns {number[]} The new dimensions.\n * @private\n */\nfunction calc_squeeze_dims(dims, dim) {\n dims = dims.slice();\n if (dim === null) {\n dims = dims.filter((d) => d !== 1);\n } else if (typeof dim === 'number') {\n if (dims[dim] === 1) {\n dims.splice(dim, 1);\n }\n } else if (Array.isArray(dim)) {\n dims = dims.filter((x, i) => {\n return x !== 1 || !dim.includes(i);\n });\n }\n return dims;\n}\n\n/**\n * Helper function to calculate new dimensions when performing an unsqueeze operation.\n * @param {number[]} dims The dimensions of the tensor.\n * @param {number} dim The dimension to unsqueeze.\n * @returns {number[]} The new dimensions.\n * @private\n */\nfunction calc_unsqueeze_dims(dims, dim) {\n // Dimension out of range (e.g., \"expected to be in range of [-4, 3], but got 4\")\n // + 1 since we allow inserting at the end (i.e. dim = -1)\n dim = safeIndex(dim, dims.length + 1);\n dims = dims.slice();\n // Insert 1 into specified dimension\n dims.splice(dim, 0, 1);\n return dims;\n}\n\n/**\n * Safely calculate the index for an array of a given size, allowing negative indexing.\n * @param {number} index The index that will be used.\n * @param {number} size The size of the array.\n * @param {number} [dimension=null] The dimension that the index is for (optional).\n * @returns {number} The index, guaranteed to be non-negative and less than `arrayLength`.\n *\n * @throws {Error} If the index is out of range.\n * @private\n */\nfunction safeIndex(index, size, dimension = null, boundsCheck = true) {\n if (boundsCheck && (index < -size || index >= size)) {\n throw new Error(`IndexError: index ${index} is out of bounds for dimension${dimension === null ? '' : ' ' + dimension} with size ${size}`);\n }\n\n if (index < 0) {\n // Negative indexing, ensuring positive index\n index = ((index % size) + size) % size;\n }\n return index;\n}\n\n/**\n * Concatenates an array of tensors along a specified dimension.\n * @param {Tensor[]} tensors The array of tensors to concatenate.\n * @param {number} dim The dimension to concatenate along.\n * @returns {Tensor} The concatenated tensor.\n */\nexport function cat(tensors, dim = 0) {\n dim = safeIndex(dim, tensors[0].dims.length);\n\n // TODO do validation of shapes\n\n const resultDims = tensors[0].dims.slice();\n resultDims[dim] = tensors.reduce((a, b) => a + b.dims[dim], 0);\n\n // Create a new array to store the accumulated values\n const resultSize = resultDims.reduce((a, b) => a * b, 1);\n // @ts-ignore\n const result = new tensors[0].data.constructor(resultSize);\n\n // Create output tensor of same type as first\n const resultType = tensors[0].type;\n\n if (dim === 0) {\n // Handle special case for performance reasons\n\n let offset = 0;\n for (const tensor of tensors) {\n const tensorData = tensor.data;\n result.set(tensorData, offset);\n offset += tensorData.length;\n }\n\n } else {\n\n let currentDim = 0;\n\n for (let t = 0; t < tensors.length; ++t) {\n const { data, dims } = tensors[t];\n\n // Iterate over the data array\n for (let i = 0; i < data.length; ++i) {\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = dims[j];\n let index = num % size;\n if (j === dim) {\n index += currentDim;\n }\n resultIndex += index * resultMultiplier;\n resultMultiplier *= resultDims[j];\n num = Math.floor(num / size);\n }\n // Accumulate the value at the current index\n result[resultIndex] = data[i];\n }\n\n currentDim += dims[dim];\n }\n }\n return new Tensor(resultType, result, resultDims);\n}\n\n/**\n * Stack an array of tensors along a specified dimension.\n * @param {Tensor[]} tensors The array of tensors to stack.\n * @param {number} dim The dimension to stack along.\n * @returns {Tensor} The stacked tensor.\n */\nexport function stack(tensors, dim = 0) {\n // TODO do validation of shapes\n // NOTE: stack expects each tensor to be equal size\n return cat(tensors.map(t => t.unsqueeze(dim)), dim);\n}\n\n\n/**\n * Calculates the standard deviation and mean over the dimensions specified by dim. dim can be a single dimension or `null` to reduce over all dimensions.\n * @param {Tensor} input the input tenso\n * @param {number|null} dim the dimension to reduce. If None, all dimensions are reduced.\n * @param {number} correction difference between the sample size and sample degrees of freedom. Defaults to Bessel's correction, correction=1.\n * @param {boolean} keepdim whether the output tensor has dim retained or not.\n * @returns {Tensor[]} A tuple of (std, mean) tensors.\n */\nexport function std_mean(input, dim = null, correction = 1, keepdim = false) {\n const inputData = /** @type {Float32Array} */(input.data);\n const inputDims = input.dims;\n\n if (dim === null) {\n // None to reduce over all dimensions.\n const sum = inputData.reduce((a, b) => a + b, 0);\n const mean = sum / inputData.length;\n const std = Math.sqrt(inputData.reduce((a, b) => a + (b - mean) ** 2, 0) / (inputData.length - correction));\n\n const meanTensor = new Tensor(input.type, [mean], [/* scalar */]);\n const stdTensor = new Tensor(input.type, [std], [/* scalar */]);\n\n return [stdTensor, meanTensor];\n }\n\n // Negative indexing\n dim = safeIndex(dim, inputDims.length);\n\n const meanTensor = mean(input, dim, keepdim);\n const meanTensorData = meanTensor.data;\n\n // Calculate the shape of the resulting array after summation\n const resultDims = inputDims.slice(); // Copy the original dimensions\n resultDims[dim] = 1; // Remove the specified axis\n\n // Create a new array to store the accumulated values\n // @ts-ignore\n const result = new inputData.constructor(inputData.length / inputDims[dim]);\n\n // Iterate over the data array\n for (let i = 0; i < inputData.length; ++i) {\n\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = inputDims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = inputDims[j];\n if (j !== dim) {\n const index = num % size;\n resultIndex += index * resultMultiplier;\n resultMultiplier *= resultDims[j];\n }\n num = Math.floor(num / size);\n }\n\n // Accumulate the value at the current index\n result[resultIndex] += (inputData[i] - meanTensorData[resultIndex]) ** 2;\n }\n\n for (let i = 0; i < result.length; ++i) {\n result[i] = Math.sqrt(result[i] / (inputDims[dim] - correction));\n }\n\n if (!keepdim) {\n resultDims.splice(dim, 1);\n }\n\n const stdTensor = new Tensor(input.type, result, resultDims);\n\n return [stdTensor, meanTensor];\n}\n\n\n/**\n * Returns the mean value of each row of the input tensor in the given dimension dim.\n * @param {Tensor} input the input tensor.\n * @param {number|null} dim the dimension to reduce.\n * @param {boolean} keepdim whether the output tensor has dim retained or not.\n * @returns {Tensor} A new tensor with means taken along the specified dimension.\n */\nexport function mean(input, dim = null, keepdim = false) {\n const inputData = /** @type {Float32Array} */(input.data);\n\n if (dim === null) {\n // None to reduce over all dimensions.\n // @ts-ignore\n const val = inputData.reduce((a, b) => a + b, 0);\n return new Tensor(input.type, [val / inputData.length], [/* scalar */]);\n }\n const inputDims = input.dims;\n\n // Negative indexing\n dim = safeIndex(dim, inputDims.length);\n\n // Calculate the shape of the resulting array after summation\n const resultDims = inputDims.slice(); // Copy the original dimensions\n resultDims[dim] = 1; // Remove the specified axis\n\n // Create a new array to store the accumulated values\n // @ts-ignore\n const result = new inputData.constructor(inputData.length / inputDims[dim]);\n\n // Iterate over the data array\n for (let i = 0; i < inputData.length; ++i) {\n\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = inputDims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = inputDims[j];\n if (j !== dim) {\n const index = num % size;\n resultIndex += index * resultMultiplier;\n resultMultiplier *= resultDims[j];\n }\n num = Math.floor(num / size);\n }\n\n // Accumulate the value at the current index\n result[resultIndex] += inputData[i];\n }\n\n if (inputDims[dim] !== 1) {\n for (let i = 0; i < result.length; ++i) {\n result[i] = result[i] / inputDims[dim];\n }\n }\n\n if (!keepdim) {\n resultDims.splice(dim, 1);\n }\n\n return new Tensor(input.type, result, resultDims);\n}\n\n\nfunction dimsToStride(dims) {\n const stride = new Array(dims.length);\n for (let i = dims.length - 1, s2 = 1; i >= 0; --i) {\n stride[i] = s2;\n s2 *= dims[i];\n }\n return stride;\n}\n\nfunction fullHelper(size, fill_value, dtype, cls) {\n const numElements = size.reduce((a, b) => a * b, 1);\n return new Tensor(\n dtype,\n new cls(numElements).fill(fill_value),\n size\n )\n}\n\n/**\n * Creates a tensor of size size filled with fill_value. The tensor's dtype is inferred from fill_value.\n * @param {number[]} size A sequence of integers defining the shape of the output tensor.\n * @param {number|bigint} fill_value The value to fill the output tensor with.\n * @returns {Tensor} The filled tensor.\n */\nexport function full(size, fill_value) {\n let dtype;\n let typedArrayCls;\n if (typeof fill_value === 'number') {\n dtype = 'float32';\n typedArrayCls = Float32Array;\n } else if (typeof fill_value === 'bigint') {\n dtype = 'int64';\n typedArrayCls = BigInt64Array;\n } else {\n // TODO: support other dtypes\n throw new Error(`Unsupported data type: ${typeof fill_value}`);\n }\n return fullHelper(size, fill_value, dtype, typedArrayCls);\n}\n\nexport function full_like(tensor, fill_value) {\n return full(tensor.dims, fill_value);\n}\n\n/**\n * Returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size.\n * @param {number[]} size A sequence of integers defining the shape of the output tensor.\n * @returns {Tensor} The ones tensor.\n */\nexport function ones(size) {\n return fullHelper(size, 1n, 'int64', BigInt64Array);\n}\n\n/**\n * Returns a tensor filled with the scalar value 1, with the same size as input.\n * @param {Tensor} tensor The size of input will determine size of the output tensor.\n * @returns {Tensor} The ones tensor.\n */\nexport function ones_like(tensor) {\n return ones(tensor.dims);\n}\n\n/**\n * Returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size.\n * @param {number[]} size A sequence of integers defining the shape of the output tensor.\n * @returns {Tensor} The zeros tensor.\n */\nexport function zeros(size) {\n return fullHelper(size, 0n, 'int64', BigInt64Array);\n}\n\n/**\n * Returns a tensor filled with the scalar value 0, with the same size as input.\n * @param {Tensor} tensor The size of input will determine size of the output tensor.\n * @returns {Tensor} The zeros tensor.\n */\nexport function zeros_like(tensor) {\n return zeros(tensor.dims);\n}\n\n/**\n * Quantizes the embeddings tensor to binary or unsigned binary precision.\n * @param {Tensor} tensor The tensor to quantize.\n * @param {'binary'|'ubinary'} precision The precision to use for quantization.\n * @returns {Tensor} The quantized tensor.\n */\nexport function quantize_embeddings(tensor, precision) {\n if (tensor.dims.length !== 2) {\n throw new Error(\"The tensor must have 2 dimensions\");\n }\n if (tensor.dims.at(-1) % 8 !== 0) {\n throw new Error(\"The last dimension of the tensor must be a multiple of 8\");\n }\n if (!['binary', 'ubinary'].includes(precision)) {\n throw new Error(\"The precision must be either 'binary' or 'ubinary'\");\n }\n\n const signed = precision === 'binary';\n const dtype = signed ? 'int8' : 'uint8';\n\n // Create a typed array to store the packed bits\n const cls = signed ? Int8Array : Uint8Array;\n const inputData = tensor.data;\n const outputData = new cls(inputData.length / 8);\n\n // Iterate over each number in the array\n for (let i = 0; i < inputData.length; ++i) {\n // Determine if the number is greater than 0\n const bit = inputData[i] > 0 ? 1 : 0;\n\n // Calculate the index in the typed array and the position within the byte\n const arrayIndex = Math.floor(i / 8);\n const bitPosition = i % 8;\n\n // Pack the bit into the typed array\n outputData[arrayIndex] |= bit << (7 - bitPosition);\n if (signed && bitPosition === 0) {\n outputData[arrayIndex] -= 128;\n }\n };\n\n return new Tensor(dtype, outputData, [tensor.dims[0], tensor.dims[1] / 8]);\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","var scriptUrl;\nif (typeof import.meta.url === \"string\") scriptUrl = import.meta.url\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl;","__webpack_require__.b = new URL(\"./\", import.meta.url);\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t\"transformers\": 0\n};\n\n// no install chunk\n\n// no chunk on demand loading\n\n// no prefetching\n\n// no preloaded\n\n// no external install chunk\n\n// no on chunks loaded","/**\n * @file Entry point for the Transformers.js library. Only the exports from this file\n * are available to the end user, and are grouped as follows:\n * \n * 1. [Pipelines](./pipelines)\n * 2. [Environment variables](./env)\n * 3. [Models](./models)\n * 4. [Tokenizers](./tokenizers)\n * 5. [Processors](./processors)\n * \n * @module transformers\n */\n\nexport { env } from './env.js';\nexport * from './pipelines.js';\nexport * from './models.js';\nexport * from './tokenizers.js';\nexport * from './processors.js';\nexport * from './configs.js';\n\nexport * from './utils/audio.js';\nexport * from './utils/image.js';\nexport * from './utils/tensor.js';\nexport * from './utils/maths.js';\n\nexport * from './generation/streamers.js';\nexport * from './generation/stopping_criteria.js';\n\n"],"names":[],"sourceRoot":""} \ No newline at end of file diff --git a/assets/dist_transformers/1.21.0-dev.20241109/transformers.min.js.map b/assets/dist_transformers/1.21.0-dev.20241109/transformers.min.js.map deleted file mode 100644 index f6be1ac..0000000 --- a/assets/dist_transformers/1.21.0-dev.20241109/transformers.min.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transformers.min.js","mappings":"IACIA,EADAC,E;;;;;;;;;;;;;;;;;;;;;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AI/E,OAFA05I,EAAa,QAAI,IAAM,EACvBN,EAAoB37H,EAAEoI,EAAI6zH,GACnB7zH,CACR,E6CxBAuzH,EAAoB37H,EAAI,CAAC+gC,EAASm7F,KACjC,IAAI,IAAI35I,KAAO25I,EACXP,EAAoB97H,EAAEq8H,EAAY35I,KAASo5I,EAAoB97H,EAAEkhC,EAASx+C,IAC5EnJ,OAAOyX,eAAekwC,EAASx+C,EAAK,CAAEuO,YAAY,EAAM7R,IAAKi9I,EAAW35I,IAE1E,ECNDo5I,EAAoB97H,EAAI,CAAC6qD,EAAKv6D,IAAU/W,OAAO+lB,UAAUnN,eAAeC,KAAKy4D,EAAKv6D,GCClFwrI,EAAoBl8H,EAAKshC,IACH,oBAAXskB,QAA0BA,OAAO82E,aAC1C/iJ,OAAOyX,eAAekwC,EAASskB,OAAO82E,YAAa,CAAEh/I,MAAO,WAE7D/D,OAAOyX,eAAekwC,EAAS,aAAc,CAAE5jD,OAAO,GAAO,E,MCL9D,IAAIi/I,EAIJ,GAH+B,6BAAR17G,MAAkB07G,cAAwB17G,MAG5D07G,EAAW,MAAM,IAAIt5I,MAAM,yDAChCs5I,EAAYA,EAAU/9I,QAAQ,OAAQ,IAAIA,QAAQ,QAAS,IAAIA,QAAQ,YAAa,KACpFs9I,EAAoBp6G,EAAI66G,C,KCNxBT,EAAoBp3I,EAAI,IAAI0yC,IAAI,iBAAkBvW,K","sources":["webpack://@huggingface/transformers/webpack/runtime/create fake namespace object","webpack://@huggingface/transformers/./node_modules/@huggingface/jinja/dist/index.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/backend-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/env-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/env.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/inference-session.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/trace.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/training-session-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/training-session.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/version.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs","webpack://@huggingface/transformers/./src/backends/onnx.js","webpack://@huggingface/transformers/./src/configs.js","webpack://@huggingface/transformers/./src/env.js","webpack://@huggingface/transformers/./src/generation/configuration_utils.js","webpack://@huggingface/transformers/./src/generation/logits_process.js","webpack://@huggingface/transformers/./src/generation/logits_sampler.js","webpack://@huggingface/transformers/./src/generation/stopping_criteria.js","webpack://@huggingface/transformers/./src/generation/streamers.js","webpack://@huggingface/transformers/./src/models.js","webpack://@huggingface/transformers/./src/models/whisper/common_whisper.js","webpack://@huggingface/transformers/./src/models/whisper/generation_whisper.js","webpack://@huggingface/transformers/./src/ops/registry.js","webpack://@huggingface/transformers/./src/pipelines.js","webpack://@huggingface/transformers/./src/processors.js","webpack://@huggingface/transformers/./src/tokenizers.js","webpack://@huggingface/transformers/./src/utils/audio.js","webpack://@huggingface/transformers/./src/utils/constants.js","webpack://@huggingface/transformers/./src/utils/core.js","webpack://@huggingface/transformers/./src/utils/data-structures.js","webpack://@huggingface/transformers/./src/utils/devices.js","webpack://@huggingface/transformers/./src/utils/dtypes.js","webpack://@huggingface/transformers/./src/utils/generic.js","webpack://@huggingface/transformers/./src/utils/hub.js","webpack://@huggingface/transformers/./src/utils/image.js","webpack://@huggingface/transformers/./src/utils/maths.js","webpack://@huggingface/transformers/./src/utils/tensor.js","webpack://@huggingface/transformers/webpack/bootstrap","webpack://@huggingface/transformers/webpack/runtime/define property getters","webpack://@huggingface/transformers/webpack/runtime/hasOwnProperty shorthand","webpack://@huggingface/transformers/webpack/runtime/make namespace object","webpack://@huggingface/transformers/webpack/runtime/publicPath","webpack://@huggingface/transformers/webpack/runtime/import chunk loading"],"sourcesContent":["var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","// src/lexer.ts\nvar TOKEN_TYPES = Object.freeze({\n Text: \"Text\",\n // The text between Jinja statements or expressions\n NumericLiteral: \"NumericLiteral\",\n // e.g., 123\n BooleanLiteral: \"BooleanLiteral\",\n // true or false\n StringLiteral: \"StringLiteral\",\n // 'string'\n Identifier: \"Identifier\",\n // Variables, functions, etc.\n Equals: \"Equals\",\n // =\n OpenParen: \"OpenParen\",\n // (\n CloseParen: \"CloseParen\",\n // )\n OpenStatement: \"OpenStatement\",\n // {%\n CloseStatement: \"CloseStatement\",\n // %}\n OpenExpression: \"OpenExpression\",\n // {{\n CloseExpression: \"CloseExpression\",\n // }}\n OpenSquareBracket: \"OpenSquareBracket\",\n // [\n CloseSquareBracket: \"CloseSquareBracket\",\n // ]\n OpenCurlyBracket: \"OpenCurlyBracket\",\n // {\n CloseCurlyBracket: \"CloseCurlyBracket\",\n // }\n Comma: \"Comma\",\n // ,\n Dot: \"Dot\",\n // .\n Colon: \"Colon\",\n // :\n Pipe: \"Pipe\",\n // |\n CallOperator: \"CallOperator\",\n // ()\n AdditiveBinaryOperator: \"AdditiveBinaryOperator\",\n // + -\n MultiplicativeBinaryOperator: \"MultiplicativeBinaryOperator\",\n // * / %\n ComparisonBinaryOperator: \"ComparisonBinaryOperator\",\n // < > <= >= == !=\n UnaryOperator: \"UnaryOperator\",\n // ! - +\n // Keywords\n Set: \"Set\",\n If: \"If\",\n For: \"For\",\n In: \"In\",\n Is: \"Is\",\n NotIn: \"NotIn\",\n Else: \"Else\",\n EndIf: \"EndIf\",\n ElseIf: \"ElseIf\",\n EndFor: \"EndFor\",\n And: \"And\",\n Or: \"Or\",\n Not: \"UnaryOperator\",\n Macro: \"Macro\",\n EndMacro: \"EndMacro\"\n});\nvar KEYWORDS = Object.freeze({\n set: TOKEN_TYPES.Set,\n for: TOKEN_TYPES.For,\n in: TOKEN_TYPES.In,\n is: TOKEN_TYPES.Is,\n if: TOKEN_TYPES.If,\n else: TOKEN_TYPES.Else,\n endif: TOKEN_TYPES.EndIf,\n elif: TOKEN_TYPES.ElseIf,\n endfor: TOKEN_TYPES.EndFor,\n and: TOKEN_TYPES.And,\n or: TOKEN_TYPES.Or,\n not: TOKEN_TYPES.Not,\n \"not in\": TOKEN_TYPES.NotIn,\n macro: TOKEN_TYPES.Macro,\n endmacro: TOKEN_TYPES.EndMacro,\n // Literals\n true: TOKEN_TYPES.BooleanLiteral,\n false: TOKEN_TYPES.BooleanLiteral,\n // NOTE: According to the Jinja docs: The special constants true, false, and none are indeed lowercase.\n // Because that caused confusion in the past, (True used to expand to an undefined variable that was considered false),\n // all three can now also be written in title case (True, False, and None). However, for consistency, (all Jinja identifiers are lowercase)\n // you should use the lowercase versions.\n True: TOKEN_TYPES.BooleanLiteral,\n False: TOKEN_TYPES.BooleanLiteral\n});\nvar Token = class {\n /**\n * Constructs a new Token.\n * @param {string} value The raw value as seen inside the source code.\n * @param {TokenType} type The type of token.\n */\n constructor(value, type) {\n this.value = value;\n this.type = type;\n }\n};\nfunction isWord(char) {\n return /\\w/.test(char);\n}\nfunction isInteger(char) {\n return /[0-9]/.test(char);\n}\nvar ORDERED_MAPPING_TABLE = [\n // Control sequences\n [\"{%\", TOKEN_TYPES.OpenStatement],\n [\"%}\", TOKEN_TYPES.CloseStatement],\n [\"{{\", TOKEN_TYPES.OpenExpression],\n [\"}}\", TOKEN_TYPES.CloseExpression],\n // Single character tokens\n [\"(\", TOKEN_TYPES.OpenParen],\n [\")\", TOKEN_TYPES.CloseParen],\n [\"{\", TOKEN_TYPES.OpenCurlyBracket],\n [\"}\", TOKEN_TYPES.CloseCurlyBracket],\n [\"[\", TOKEN_TYPES.OpenSquareBracket],\n [\"]\", TOKEN_TYPES.CloseSquareBracket],\n [\",\", TOKEN_TYPES.Comma],\n [\".\", TOKEN_TYPES.Dot],\n [\":\", TOKEN_TYPES.Colon],\n [\"|\", TOKEN_TYPES.Pipe],\n // Comparison operators\n [\"<=\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\">=\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\"==\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\"!=\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\"<\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\">\", TOKEN_TYPES.ComparisonBinaryOperator],\n // Arithmetic operators\n [\"+\", TOKEN_TYPES.AdditiveBinaryOperator],\n [\"-\", TOKEN_TYPES.AdditiveBinaryOperator],\n [\"*\", TOKEN_TYPES.MultiplicativeBinaryOperator],\n [\"/\", TOKEN_TYPES.MultiplicativeBinaryOperator],\n [\"%\", TOKEN_TYPES.MultiplicativeBinaryOperator],\n // Assignment operator\n [\"=\", TOKEN_TYPES.Equals]\n];\nvar ESCAPE_CHARACTERS = /* @__PURE__ */ new Map([\n [\"n\", \"\\n\"],\n // New line\n [\"t\", \"\t\"],\n // Horizontal tab\n [\"r\", \"\\r\"],\n // Carriage return\n [\"b\", \"\\b\"],\n // Backspace\n [\"f\", \"\\f\"],\n // Form feed\n [\"v\", \"\\v\"],\n // Vertical tab\n [\"'\", \"'\"],\n // Single quote\n ['\"', '\"'],\n // Double quote\n [\"\\\\\", \"\\\\\"]\n // Backslash\n]);\nfunction preprocess(template, options = {}) {\n if (template.endsWith(\"\\n\")) {\n template = template.slice(0, -1);\n }\n template = template.replace(/{#.*?#}/gs, \"{##}\");\n if (options.lstrip_blocks) {\n template = template.replace(/^[ \\t]*({[#%])/gm, \"$1\");\n }\n if (options.trim_blocks) {\n template = template.replace(/([#%]})\\n/g, \"$1\");\n }\n return template.replace(/{##}/g, \"\").replace(/-%}\\s*/g, \"%}\").replace(/\\s*{%-/g, \"{%\").replace(/-}}\\s*/g, \"}}\").replace(/\\s*{{-/g, \"{{\");\n}\nfunction tokenize(source, options = {}) {\n const tokens = [];\n const src = preprocess(source, options);\n let cursorPosition = 0;\n const consumeWhile = (predicate) => {\n let str = \"\";\n while (predicate(src[cursorPosition])) {\n if (src[cursorPosition] === \"\\\\\") {\n ++cursorPosition;\n if (cursorPosition >= src.length)\n throw new SyntaxError(\"Unexpected end of input\");\n const escaped = src[cursorPosition++];\n const unescaped = ESCAPE_CHARACTERS.get(escaped);\n if (unescaped === void 0) {\n throw new SyntaxError(`Unexpected escaped character: ${escaped}`);\n }\n str += unescaped;\n continue;\n }\n str += src[cursorPosition++];\n if (cursorPosition >= src.length)\n throw new SyntaxError(\"Unexpected end of input\");\n }\n return str;\n };\n main:\n while (cursorPosition < src.length) {\n const lastTokenType = tokens.at(-1)?.type;\n if (lastTokenType === void 0 || lastTokenType === TOKEN_TYPES.CloseStatement || lastTokenType === TOKEN_TYPES.CloseExpression) {\n let text = \"\";\n while (cursorPosition < src.length && // Keep going until we hit the next Jinja statement or expression\n !(src[cursorPosition] === \"{\" && (src[cursorPosition + 1] === \"%\" || src[cursorPosition + 1] === \"{\"))) {\n text += src[cursorPosition++];\n }\n if (text.length > 0) {\n tokens.push(new Token(text, TOKEN_TYPES.Text));\n continue;\n }\n }\n consumeWhile((char2) => /\\s/.test(char2));\n const char = src[cursorPosition];\n if (char === \"-\" || char === \"+\") {\n const lastTokenType2 = tokens.at(-1)?.type;\n if (lastTokenType2 === TOKEN_TYPES.Text || lastTokenType2 === void 0) {\n throw new SyntaxError(`Unexpected character: ${char}`);\n }\n switch (lastTokenType2) {\n case TOKEN_TYPES.Identifier:\n case TOKEN_TYPES.NumericLiteral:\n case TOKEN_TYPES.BooleanLiteral:\n case TOKEN_TYPES.StringLiteral:\n case TOKEN_TYPES.CloseParen:\n case TOKEN_TYPES.CloseSquareBracket:\n break;\n default: {\n ++cursorPosition;\n const num = consumeWhile(isInteger);\n tokens.push(\n new Token(`${char}${num}`, num.length > 0 ? TOKEN_TYPES.NumericLiteral : TOKEN_TYPES.UnaryOperator)\n );\n continue;\n }\n }\n }\n for (const [char2, token] of ORDERED_MAPPING_TABLE) {\n const slice2 = src.slice(cursorPosition, cursorPosition + char2.length);\n if (slice2 === char2) {\n tokens.push(new Token(char2, token));\n cursorPosition += char2.length;\n continue main;\n }\n }\n if (char === \"'\" || char === '\"') {\n ++cursorPosition;\n const str = consumeWhile((c) => c !== char);\n tokens.push(new Token(str, TOKEN_TYPES.StringLiteral));\n ++cursorPosition;\n continue;\n }\n if (isInteger(char)) {\n const num = consumeWhile(isInteger);\n tokens.push(new Token(num, TOKEN_TYPES.NumericLiteral));\n continue;\n }\n if (isWord(char)) {\n const word = consumeWhile(isWord);\n const type = Object.hasOwn(KEYWORDS, word) ? KEYWORDS[word] : TOKEN_TYPES.Identifier;\n if (type === TOKEN_TYPES.In && tokens.at(-1)?.type === TOKEN_TYPES.Not) {\n tokens.pop();\n tokens.push(new Token(\"not in\", TOKEN_TYPES.NotIn));\n } else {\n tokens.push(new Token(word, type));\n }\n continue;\n }\n throw new SyntaxError(`Unexpected character: ${char}`);\n }\n return tokens;\n}\n\n// src/ast.ts\nvar Statement = class {\n type = \"Statement\";\n};\nvar Program = class extends Statement {\n constructor(body) {\n super();\n this.body = body;\n }\n type = \"Program\";\n};\nvar If = class extends Statement {\n constructor(test, body, alternate) {\n super();\n this.test = test;\n this.body = body;\n this.alternate = alternate;\n }\n type = \"If\";\n};\nvar For = class extends Statement {\n constructor(loopvar, iterable, body, defaultBlock) {\n super();\n this.loopvar = loopvar;\n this.iterable = iterable;\n this.body = body;\n this.defaultBlock = defaultBlock;\n }\n type = \"For\";\n};\nvar SetStatement = class extends Statement {\n constructor(assignee, value) {\n super();\n this.assignee = assignee;\n this.value = value;\n }\n type = \"Set\";\n};\nvar Macro = class extends Statement {\n constructor(name, args, body) {\n super();\n this.name = name;\n this.args = args;\n this.body = body;\n }\n type = \"Macro\";\n};\nvar Expression = class extends Statement {\n type = \"Expression\";\n};\nvar MemberExpression = class extends Expression {\n constructor(object, property, computed) {\n super();\n this.object = object;\n this.property = property;\n this.computed = computed;\n }\n type = \"MemberExpression\";\n};\nvar CallExpression = class extends Expression {\n constructor(callee, args) {\n super();\n this.callee = callee;\n this.args = args;\n }\n type = \"CallExpression\";\n};\nvar Identifier = class extends Expression {\n /**\n * @param {string} value The name of the identifier\n */\n constructor(value) {\n super();\n this.value = value;\n }\n type = \"Identifier\";\n};\nvar Literal = class extends Expression {\n constructor(value) {\n super();\n this.value = value;\n }\n type = \"Literal\";\n};\nvar NumericLiteral = class extends Literal {\n type = \"NumericLiteral\";\n};\nvar StringLiteral = class extends Literal {\n type = \"StringLiteral\";\n};\nvar BooleanLiteral = class extends Literal {\n type = \"BooleanLiteral\";\n};\nvar ArrayLiteral = class extends Literal {\n type = \"ArrayLiteral\";\n};\nvar TupleLiteral = class extends Literal {\n type = \"TupleLiteral\";\n};\nvar ObjectLiteral = class extends Literal {\n type = \"ObjectLiteral\";\n};\nvar BinaryExpression = class extends Expression {\n constructor(operator, left, right) {\n super();\n this.operator = operator;\n this.left = left;\n this.right = right;\n }\n type = \"BinaryExpression\";\n};\nvar FilterExpression = class extends Expression {\n constructor(operand, filter) {\n super();\n this.operand = operand;\n this.filter = filter;\n }\n type = \"FilterExpression\";\n};\nvar SelectExpression = class extends Expression {\n constructor(iterable, test) {\n super();\n this.iterable = iterable;\n this.test = test;\n }\n type = \"SelectExpression\";\n};\nvar TestExpression = class extends Expression {\n constructor(operand, negate, test) {\n super();\n this.operand = operand;\n this.negate = negate;\n this.test = test;\n }\n type = \"TestExpression\";\n};\nvar UnaryExpression = class extends Expression {\n constructor(operator, argument) {\n super();\n this.operator = operator;\n this.argument = argument;\n }\n type = \"UnaryExpression\";\n};\nvar SliceExpression = class extends Expression {\n constructor(start = void 0, stop = void 0, step = void 0) {\n super();\n this.start = start;\n this.stop = stop;\n this.step = step;\n }\n type = \"SliceExpression\";\n};\nvar KeywordArgumentExpression = class extends Expression {\n constructor(key, value) {\n super();\n this.key = key;\n this.value = value;\n }\n type = \"KeywordArgumentExpression\";\n};\n\n// src/parser.ts\nfunction parse(tokens) {\n const program = new Program([]);\n let current = 0;\n function expect(type, error) {\n const prev = tokens[current++];\n if (!prev || prev.type !== type) {\n throw new Error(`Parser Error: ${error}. ${prev.type} !== ${type}.`);\n }\n return prev;\n }\n function parseAny() {\n switch (tokens[current].type) {\n case TOKEN_TYPES.Text:\n return parseText();\n case TOKEN_TYPES.OpenStatement:\n return parseJinjaStatement();\n case TOKEN_TYPES.OpenExpression:\n return parseJinjaExpression();\n default:\n throw new SyntaxError(`Unexpected token type: ${tokens[current].type}`);\n }\n }\n function not(...types) {\n return current + types.length <= tokens.length && types.some((type, i) => type !== tokens[current + i].type);\n }\n function is(...types) {\n return current + types.length <= tokens.length && types.every((type, i) => type === tokens[current + i].type);\n }\n function parseText() {\n return new StringLiteral(expect(TOKEN_TYPES.Text, \"Expected text token\").value);\n }\n function parseJinjaStatement() {\n expect(TOKEN_TYPES.OpenStatement, \"Expected opening statement token\");\n let result;\n switch (tokens[current].type) {\n case TOKEN_TYPES.Set:\n ++current;\n result = parseSetStatement();\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n break;\n case TOKEN_TYPES.If:\n ++current;\n result = parseIfStatement();\n expect(TOKEN_TYPES.OpenStatement, \"Expected {% token\");\n expect(TOKEN_TYPES.EndIf, \"Expected endif token\");\n expect(TOKEN_TYPES.CloseStatement, \"Expected %} token\");\n break;\n case TOKEN_TYPES.Macro:\n ++current;\n result = parseMacroStatement();\n expect(TOKEN_TYPES.OpenStatement, \"Expected {% token\");\n expect(TOKEN_TYPES.EndMacro, \"Expected endmacro token\");\n expect(TOKEN_TYPES.CloseStatement, \"Expected %} token\");\n break;\n case TOKEN_TYPES.For:\n ++current;\n result = parseForStatement();\n expect(TOKEN_TYPES.OpenStatement, \"Expected {% token\");\n expect(TOKEN_TYPES.EndFor, \"Expected endfor token\");\n expect(TOKEN_TYPES.CloseStatement, \"Expected %} token\");\n break;\n default:\n throw new SyntaxError(`Unknown statement type: ${tokens[current].type}`);\n }\n return result;\n }\n function parseJinjaExpression() {\n expect(TOKEN_TYPES.OpenExpression, \"Expected opening expression token\");\n const result = parseExpression();\n expect(TOKEN_TYPES.CloseExpression, \"Expected closing expression token\");\n return result;\n }\n function parseSetStatement() {\n const left = parseExpression();\n if (is(TOKEN_TYPES.Equals)) {\n ++current;\n const value = parseSetStatement();\n return new SetStatement(left, value);\n }\n return left;\n }\n function parseIfStatement() {\n const test = parseExpression();\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n const body = [];\n const alternate = [];\n while (!(tokens[current]?.type === TOKEN_TYPES.OpenStatement && (tokens[current + 1]?.type === TOKEN_TYPES.ElseIf || tokens[current + 1]?.type === TOKEN_TYPES.Else || tokens[current + 1]?.type === TOKEN_TYPES.EndIf))) {\n body.push(parseAny());\n }\n if (tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type !== TOKEN_TYPES.EndIf) {\n ++current;\n if (is(TOKEN_TYPES.ElseIf)) {\n expect(TOKEN_TYPES.ElseIf, \"Expected elseif token\");\n alternate.push(parseIfStatement());\n } else {\n expect(TOKEN_TYPES.Else, \"Expected else token\");\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n while (!(tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type === TOKEN_TYPES.EndIf)) {\n alternate.push(parseAny());\n }\n }\n }\n return new If(test, body, alternate);\n }\n function parseMacroStatement() {\n const name = parsePrimaryExpression();\n if (name.type !== \"Identifier\") {\n throw new SyntaxError(`Expected identifier following macro statement`);\n }\n const args = parseArgs();\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n const body = [];\n while (not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.EndMacro)) {\n body.push(parseAny());\n }\n return new Macro(name, args, body);\n }\n function parseExpressionSequence(primary = false) {\n const fn = primary ? parsePrimaryExpression : parseExpression;\n const expressions = [fn()];\n const isTuple = is(TOKEN_TYPES.Comma);\n while (isTuple) {\n ++current;\n expressions.push(fn());\n if (!is(TOKEN_TYPES.Comma)) {\n break;\n }\n }\n return isTuple ? new TupleLiteral(expressions) : expressions[0];\n }\n function parseForStatement() {\n const loopVariable = parseExpressionSequence(true);\n if (!(loopVariable instanceof Identifier || loopVariable instanceof TupleLiteral)) {\n throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${loopVariable.type} instead`);\n }\n expect(TOKEN_TYPES.In, \"Expected `in` keyword following loop variable\");\n const iterable = parseExpression();\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n const body = [];\n while (not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.EndFor) && not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.Else)) {\n body.push(parseAny());\n }\n const alternative = [];\n if (is(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.Else)) {\n ++current;\n ++current;\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n while (not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.EndFor)) {\n alternative.push(parseAny());\n }\n }\n return new For(loopVariable, iterable, body, alternative);\n }\n function parseExpression() {\n return parseIfExpression();\n }\n function parseIfExpression() {\n const a = parseLogicalOrExpression();\n if (is(TOKEN_TYPES.If)) {\n ++current;\n const predicate = parseLogicalOrExpression();\n if (is(TOKEN_TYPES.Else)) {\n ++current;\n const b = parseLogicalOrExpression();\n return new If(predicate, [a], [b]);\n } else {\n return new SelectExpression(a, predicate);\n }\n }\n return a;\n }\n function parseLogicalOrExpression() {\n let left = parseLogicalAndExpression();\n while (is(TOKEN_TYPES.Or)) {\n const operator = tokens[current];\n ++current;\n const right = parseLogicalAndExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseLogicalAndExpression() {\n let left = parseLogicalNegationExpression();\n while (is(TOKEN_TYPES.And)) {\n const operator = tokens[current];\n ++current;\n const right = parseLogicalNegationExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseLogicalNegationExpression() {\n let right;\n while (is(TOKEN_TYPES.Not)) {\n const operator = tokens[current];\n ++current;\n const arg = parseLogicalNegationExpression();\n right = new UnaryExpression(operator, arg);\n }\n return right ?? parseComparisonExpression();\n }\n function parseComparisonExpression() {\n let left = parseAdditiveExpression();\n while (is(TOKEN_TYPES.ComparisonBinaryOperator) || is(TOKEN_TYPES.In) || is(TOKEN_TYPES.NotIn)) {\n const operator = tokens[current];\n ++current;\n const right = parseAdditiveExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseAdditiveExpression() {\n let left = parseMultiplicativeExpression();\n while (is(TOKEN_TYPES.AdditiveBinaryOperator)) {\n const operator = tokens[current];\n ++current;\n const right = parseMultiplicativeExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseCallMemberExpression() {\n const member = parseMemberExpression();\n if (is(TOKEN_TYPES.OpenParen)) {\n return parseCallExpression(member);\n }\n return member;\n }\n function parseCallExpression(callee) {\n let callExpression = new CallExpression(callee, parseArgs());\n if (is(TOKEN_TYPES.OpenParen)) {\n callExpression = parseCallExpression(callExpression);\n }\n return callExpression;\n }\n function parseArgs() {\n expect(TOKEN_TYPES.OpenParen, \"Expected opening parenthesis for arguments list\");\n const args = parseArgumentsList();\n expect(TOKEN_TYPES.CloseParen, \"Expected closing parenthesis for arguments list\");\n return args;\n }\n function parseArgumentsList() {\n const args = [];\n while (!is(TOKEN_TYPES.CloseParen)) {\n let argument = parseExpression();\n if (is(TOKEN_TYPES.Equals)) {\n ++current;\n if (!(argument instanceof Identifier)) {\n throw new SyntaxError(`Expected identifier for keyword argument`);\n }\n const value = parseExpression();\n argument = new KeywordArgumentExpression(argument, value);\n }\n args.push(argument);\n if (is(TOKEN_TYPES.Comma)) {\n ++current;\n }\n }\n return args;\n }\n function parseMemberExpressionArgumentsList() {\n const slices = [];\n let isSlice = false;\n while (!is(TOKEN_TYPES.CloseSquareBracket)) {\n if (is(TOKEN_TYPES.Colon)) {\n slices.push(void 0);\n ++current;\n isSlice = true;\n } else {\n slices.push(parseExpression());\n if (is(TOKEN_TYPES.Colon)) {\n ++current;\n isSlice = true;\n }\n }\n }\n if (slices.length === 0) {\n throw new SyntaxError(`Expected at least one argument for member/slice expression`);\n }\n if (isSlice) {\n if (slices.length > 3) {\n throw new SyntaxError(`Expected 0-3 arguments for slice expression`);\n }\n return new SliceExpression(...slices);\n }\n return slices[0];\n }\n function parseMemberExpression() {\n let object = parsePrimaryExpression();\n while (is(TOKEN_TYPES.Dot) || is(TOKEN_TYPES.OpenSquareBracket)) {\n const operator = tokens[current];\n ++current;\n let property;\n const computed = operator.type !== TOKEN_TYPES.Dot;\n if (computed) {\n property = parseMemberExpressionArgumentsList();\n expect(TOKEN_TYPES.CloseSquareBracket, \"Expected closing square bracket\");\n } else {\n property = parsePrimaryExpression();\n if (property.type !== \"Identifier\") {\n throw new SyntaxError(`Expected identifier following dot operator`);\n }\n }\n object = new MemberExpression(object, property, computed);\n }\n return object;\n }\n function parseMultiplicativeExpression() {\n let left = parseTestExpression();\n while (is(TOKEN_TYPES.MultiplicativeBinaryOperator)) {\n const operator = tokens[current];\n ++current;\n const right = parseTestExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseTestExpression() {\n let operand = parseFilterExpression();\n while (is(TOKEN_TYPES.Is)) {\n ++current;\n const negate = is(TOKEN_TYPES.Not);\n if (negate) {\n ++current;\n }\n let filter = parsePrimaryExpression();\n if (filter instanceof BooleanLiteral) {\n filter = new Identifier(filter.value.toString());\n }\n if (!(filter instanceof Identifier)) {\n throw new SyntaxError(`Expected identifier for the test`);\n }\n operand = new TestExpression(operand, negate, filter);\n }\n return operand;\n }\n function parseFilterExpression() {\n let operand = parseCallMemberExpression();\n while (is(TOKEN_TYPES.Pipe)) {\n ++current;\n let filter = parsePrimaryExpression();\n if (!(filter instanceof Identifier)) {\n throw new SyntaxError(`Expected identifier for the filter`);\n }\n if (is(TOKEN_TYPES.OpenParen)) {\n filter = parseCallExpression(filter);\n }\n operand = new FilterExpression(operand, filter);\n }\n return operand;\n }\n function parsePrimaryExpression() {\n const token = tokens[current];\n switch (token.type) {\n case TOKEN_TYPES.NumericLiteral:\n ++current;\n return new NumericLiteral(Number(token.value));\n case TOKEN_TYPES.StringLiteral:\n ++current;\n return new StringLiteral(token.value);\n case TOKEN_TYPES.BooleanLiteral:\n ++current;\n return new BooleanLiteral(token.value.toLowerCase() === \"true\");\n case TOKEN_TYPES.Identifier:\n ++current;\n return new Identifier(token.value);\n case TOKEN_TYPES.OpenParen: {\n ++current;\n const expression = parseExpressionSequence();\n if (tokens[current].type !== TOKEN_TYPES.CloseParen) {\n throw new SyntaxError(`Expected closing parenthesis, got ${tokens[current].type} instead`);\n }\n ++current;\n return expression;\n }\n case TOKEN_TYPES.OpenSquareBracket: {\n ++current;\n const values = [];\n while (!is(TOKEN_TYPES.CloseSquareBracket)) {\n values.push(parseExpression());\n if (is(TOKEN_TYPES.Comma)) {\n ++current;\n }\n }\n ++current;\n return new ArrayLiteral(values);\n }\n case TOKEN_TYPES.OpenCurlyBracket: {\n ++current;\n const values = /* @__PURE__ */ new Map();\n while (!is(TOKEN_TYPES.CloseCurlyBracket)) {\n const key = parseExpression();\n expect(TOKEN_TYPES.Colon, \"Expected colon between key and value in object literal\");\n const value = parseExpression();\n values.set(key, value);\n if (is(TOKEN_TYPES.Comma)) {\n ++current;\n }\n }\n ++current;\n return new ObjectLiteral(values);\n }\n default:\n throw new SyntaxError(`Unexpected token: ${token.type}`);\n }\n }\n while (current < tokens.length) {\n program.body.push(parseAny());\n }\n return program;\n}\n\n// src/utils.ts\nfunction range(start, stop, step = 1) {\n if (stop === void 0) {\n stop = start;\n start = 0;\n }\n const result = [];\n for (let i = start; i < stop; i += step) {\n result.push(i);\n }\n return result;\n}\nfunction slice(array, start, stop, step = 1) {\n const direction = Math.sign(step);\n if (direction >= 0) {\n start = (start ??= 0) < 0 ? Math.max(array.length + start, 0) : Math.min(start, array.length);\n stop = (stop ??= array.length) < 0 ? Math.max(array.length + stop, 0) : Math.min(stop, array.length);\n } else {\n start = (start ??= array.length - 1) < 0 ? Math.max(array.length + start, -1) : Math.min(start, array.length - 1);\n stop = (stop ??= -1) < -1 ? Math.max(array.length + stop, -1) : Math.min(stop, array.length - 1);\n }\n const result = [];\n for (let i = start; direction * i < direction * stop; i += step) {\n result.push(array[i]);\n }\n return result;\n}\nfunction titleCase(value) {\n return value.replace(/\\b\\w/g, (c) => c.toUpperCase());\n}\n\n// src/runtime.ts\nvar RuntimeValue = class {\n type = \"RuntimeValue\";\n value;\n /**\n * A collection of built-in functions for this type.\n */\n builtins = /* @__PURE__ */ new Map();\n /**\n * Creates a new RuntimeValue.\n */\n constructor(value = void 0) {\n this.value = value;\n }\n /**\n * Determines truthiness or falsiness of the runtime value.\n * This function should be overridden by subclasses if it has custom truthiness criteria.\n * @returns {BooleanValue} BooleanValue(true) if the value is truthy, BooleanValue(false) otherwise.\n */\n __bool__() {\n return new BooleanValue(!!this.value);\n }\n};\nvar NumericValue = class extends RuntimeValue {\n type = \"NumericValue\";\n};\nvar StringValue = class extends RuntimeValue {\n type = \"StringValue\";\n builtins = /* @__PURE__ */ new Map([\n [\n \"upper\",\n new FunctionValue(() => {\n return new StringValue(this.value.toUpperCase());\n })\n ],\n [\n \"lower\",\n new FunctionValue(() => {\n return new StringValue(this.value.toLowerCase());\n })\n ],\n [\n \"strip\",\n new FunctionValue(() => {\n return new StringValue(this.value.trim());\n })\n ],\n [\n \"title\",\n new FunctionValue(() => {\n return new StringValue(titleCase(this.value));\n })\n ],\n [\"length\", new NumericValue(this.value.length)]\n ]);\n};\nvar BooleanValue = class extends RuntimeValue {\n type = \"BooleanValue\";\n};\nvar ObjectValue = class extends RuntimeValue {\n type = \"ObjectValue\";\n /**\n * NOTE: necessary to override since all JavaScript arrays are considered truthy,\n * while only non-empty Python arrays are consider truthy.\n *\n * e.g.,\n * - JavaScript: {} && 5 -> 5\n * - Python: {} and 5 -> {}\n */\n __bool__() {\n return new BooleanValue(this.value.size > 0);\n }\n builtins = /* @__PURE__ */ new Map([\n [\n \"get\",\n new FunctionValue(([key, defaultValue]) => {\n if (!(key instanceof StringValue)) {\n throw new Error(`Object key must be a string: got ${key.type}`);\n }\n return this.value.get(key.value) ?? defaultValue ?? new NullValue();\n })\n ],\n [\n \"items\",\n new FunctionValue(() => {\n return new ArrayValue(\n Array.from(this.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value]))\n );\n })\n ]\n ]);\n};\nvar KeywordArgumentsValue = class extends ObjectValue {\n type = \"KeywordArgumentsValue\";\n};\nvar ArrayValue = class extends RuntimeValue {\n type = \"ArrayValue\";\n builtins = /* @__PURE__ */ new Map([[\"length\", new NumericValue(this.value.length)]]);\n /**\n * NOTE: necessary to override since all JavaScript arrays are considered truthy,\n * while only non-empty Python arrays are consider truthy.\n *\n * e.g.,\n * - JavaScript: [] && 5 -> 5\n * - Python: [] and 5 -> []\n */\n __bool__() {\n return new BooleanValue(this.value.length > 0);\n }\n};\nvar TupleValue = class extends ArrayValue {\n type = \"TupleValue\";\n};\nvar FunctionValue = class extends RuntimeValue {\n type = \"FunctionValue\";\n};\nvar NullValue = class extends RuntimeValue {\n type = \"NullValue\";\n};\nvar UndefinedValue = class extends RuntimeValue {\n type = \"UndefinedValue\";\n};\nvar Environment = class {\n constructor(parent) {\n this.parent = parent;\n }\n /**\n * The variables declared in this environment.\n */\n variables = /* @__PURE__ */ new Map([\n [\n \"namespace\",\n new FunctionValue((args) => {\n if (args.length === 0) {\n return new ObjectValue(/* @__PURE__ */ new Map());\n }\n if (args.length !== 1 || !(args[0] instanceof ObjectValue)) {\n throw new Error(\"`namespace` expects either zero arguments or a single object argument\");\n }\n return args[0];\n })\n ]\n ]);\n /**\n * The tests available in this environment.\n */\n tests = /* @__PURE__ */ new Map([\n [\"boolean\", (operand) => operand.type === \"BooleanValue\"],\n [\"callable\", (operand) => operand instanceof FunctionValue],\n [\n \"odd\",\n (operand) => {\n if (operand.type !== \"NumericValue\") {\n throw new Error(`Cannot apply test \"odd\" to type: ${operand.type}`);\n }\n return operand.value % 2 !== 0;\n }\n ],\n [\n \"even\",\n (operand) => {\n if (operand.type !== \"NumericValue\") {\n throw new Error(`Cannot apply test \"even\" to type: ${operand.type}`);\n }\n return operand.value % 2 === 0;\n }\n ],\n [\"false\", (operand) => operand.type === \"BooleanValue\" && !operand.value],\n [\"true\", (operand) => operand.type === \"BooleanValue\" && operand.value],\n [\"string\", (operand) => operand.type === \"StringValue\"],\n [\"number\", (operand) => operand.type === \"NumericValue\"],\n [\"integer\", (operand) => operand.type === \"NumericValue\" && Number.isInteger(operand.value)],\n [\"iterable\", (operand) => operand instanceof ArrayValue || operand instanceof StringValue],\n [\n \"lower\",\n (operand) => {\n const str = operand.value;\n return operand.type === \"StringValue\" && str === str.toLowerCase();\n }\n ],\n [\n \"upper\",\n (operand) => {\n const str = operand.value;\n return operand.type === \"StringValue\" && str === str.toUpperCase();\n }\n ],\n [\"none\", (operand) => operand.type === \"NullValue\"],\n [\"defined\", (operand) => operand.type !== \"UndefinedValue\"],\n [\"undefined\", (operand) => operand.type === \"UndefinedValue\"],\n [\"equalto\", (a, b) => a.value === b.value],\n [\"eq\", (a, b) => a.value === b.value]\n ]);\n /**\n * Set the value of a variable in the current environment.\n */\n set(name, value) {\n return this.declareVariable(name, convertToRuntimeValues(value));\n }\n declareVariable(name, value) {\n if (this.variables.has(name)) {\n throw new SyntaxError(`Variable already declared: ${name}`);\n }\n this.variables.set(name, value);\n return value;\n }\n // private assignVariable(name: string, value: AnyRuntimeValue): AnyRuntimeValue {\n // \tconst env = this.resolve(name);\n // \tenv.variables.set(name, value);\n // \treturn value;\n // }\n /**\n * Set variable in the current scope.\n * See https://jinja.palletsprojects.com/en/3.0.x/templates/#assignments for more information.\n */\n setVariable(name, value) {\n this.variables.set(name, value);\n return value;\n }\n /**\n * Resolve the environment in which the variable is declared.\n * @param {string} name The name of the variable.\n * @returns {Environment} The environment in which the variable is declared.\n */\n resolve(name) {\n if (this.variables.has(name)) {\n return this;\n }\n if (this.parent) {\n return this.parent.resolve(name);\n }\n throw new Error(`Unknown variable: ${name}`);\n }\n lookupVariable(name) {\n try {\n return this.resolve(name).variables.get(name) ?? new UndefinedValue();\n } catch {\n return new UndefinedValue();\n }\n }\n};\nvar Interpreter = class {\n global;\n constructor(env) {\n this.global = env ?? new Environment();\n }\n /**\n * Run the program.\n */\n run(program) {\n return this.evaluate(program, this.global);\n }\n /**\n * Evaluates expressions following the binary operation type.\n */\n evaluateBinaryExpression(node, environment) {\n const left = this.evaluate(node.left, environment);\n switch (node.operator.value) {\n case \"and\":\n return left.__bool__().value ? this.evaluate(node.right, environment) : left;\n case \"or\":\n return left.__bool__().value ? left : this.evaluate(node.right, environment);\n }\n const right = this.evaluate(node.right, environment);\n switch (node.operator.value) {\n case \"==\":\n return new BooleanValue(left.value == right.value);\n case \"!=\":\n return new BooleanValue(left.value != right.value);\n }\n if (left instanceof UndefinedValue || right instanceof UndefinedValue) {\n throw new Error(\"Cannot perform operation on undefined values\");\n } else if (left instanceof NullValue || right instanceof NullValue) {\n throw new Error(\"Cannot perform operation on null values\");\n } else if (left instanceof NumericValue && right instanceof NumericValue) {\n switch (node.operator.value) {\n case \"+\":\n return new NumericValue(left.value + right.value);\n case \"-\":\n return new NumericValue(left.value - right.value);\n case \"*\":\n return new NumericValue(left.value * right.value);\n case \"/\":\n return new NumericValue(left.value / right.value);\n case \"%\":\n return new NumericValue(left.value % right.value);\n case \"<\":\n return new BooleanValue(left.value < right.value);\n case \">\":\n return new BooleanValue(left.value > right.value);\n case \">=\":\n return new BooleanValue(left.value >= right.value);\n case \"<=\":\n return new BooleanValue(left.value <= right.value);\n }\n } else if (left instanceof ArrayValue && right instanceof ArrayValue) {\n switch (node.operator.value) {\n case \"+\":\n return new ArrayValue(left.value.concat(right.value));\n }\n } else if (right instanceof ArrayValue) {\n const member = right.value.find((x) => x.value === left.value) !== void 0;\n switch (node.operator.value) {\n case \"in\":\n return new BooleanValue(member);\n case \"not in\":\n return new BooleanValue(!member);\n }\n }\n if (left instanceof StringValue || right instanceof StringValue) {\n switch (node.operator.value) {\n case \"+\":\n return new StringValue(left.value.toString() + right.value.toString());\n }\n }\n if (left instanceof StringValue && right instanceof StringValue) {\n switch (node.operator.value) {\n case \"in\":\n return new BooleanValue(right.value.includes(left.value));\n case \"not in\":\n return new BooleanValue(!right.value.includes(left.value));\n }\n }\n if (left instanceof StringValue && right instanceof ObjectValue) {\n switch (node.operator.value) {\n case \"in\":\n return new BooleanValue(right.value.has(left.value));\n case \"not in\":\n return new BooleanValue(!right.value.has(left.value));\n }\n }\n throw new SyntaxError(`Unknown operator \"${node.operator.value}\" between ${left.type} and ${right.type}`);\n }\n evaluateArguments(args, environment) {\n const positionalArguments = [];\n const keywordArguments = /* @__PURE__ */ new Map();\n for (const argument of args) {\n if (argument.type === \"KeywordArgumentExpression\") {\n const kwarg = argument;\n keywordArguments.set(kwarg.key.value, this.evaluate(kwarg.value, environment));\n } else {\n if (keywordArguments.size > 0) {\n throw new Error(\"Positional arguments must come before keyword arguments\");\n }\n positionalArguments.push(this.evaluate(argument, environment));\n }\n }\n return [positionalArguments, keywordArguments];\n }\n /**\n * Evaluates expressions following the filter operation type.\n */\n evaluateFilterExpression(node, environment) {\n const operand = this.evaluate(node.operand, environment);\n if (node.filter.type === \"Identifier\") {\n const filter = node.filter;\n if (filter.value === \"tojson\") {\n return new StringValue(toJSON(operand));\n }\n if (operand instanceof ArrayValue) {\n switch (filter.value) {\n case \"list\":\n return operand;\n case \"first\":\n return operand.value[0];\n case \"last\":\n return operand.value[operand.value.length - 1];\n case \"length\":\n return new NumericValue(operand.value.length);\n case \"reverse\":\n return new ArrayValue(operand.value.reverse());\n case \"sort\":\n return new ArrayValue(\n operand.value.sort((a, b) => {\n if (a.type !== b.type) {\n throw new Error(`Cannot compare different types: ${a.type} and ${b.type}`);\n }\n switch (a.type) {\n case \"NumericValue\":\n return a.value - b.value;\n case \"StringValue\":\n return a.value.localeCompare(b.value);\n default:\n throw new Error(`Cannot compare type: ${a.type}`);\n }\n })\n );\n default:\n throw new Error(`Unknown ArrayValue filter: ${filter.value}`);\n }\n } else if (operand instanceof StringValue) {\n switch (filter.value) {\n case \"length\":\n return new NumericValue(operand.value.length);\n case \"upper\":\n return new StringValue(operand.value.toUpperCase());\n case \"lower\":\n return new StringValue(operand.value.toLowerCase());\n case \"title\":\n return new StringValue(titleCase(operand.value));\n case \"capitalize\":\n return new StringValue(operand.value.charAt(0).toUpperCase() + operand.value.slice(1));\n case \"trim\":\n return new StringValue(operand.value.trim());\n case \"indent\":\n return new StringValue(\n operand.value.split(\"\\n\").map(\n (x, i) => (\n // By default, don't indent the first line or empty lines\n i === 0 || x.length === 0 ? x : \" \" + x\n )\n ).join(\"\\n\")\n );\n case \"string\":\n return operand;\n default:\n throw new Error(`Unknown StringValue filter: ${filter.value}`);\n }\n } else if (operand instanceof NumericValue) {\n switch (filter.value) {\n case \"abs\":\n return new NumericValue(Math.abs(operand.value));\n default:\n throw new Error(`Unknown NumericValue filter: ${filter.value}`);\n }\n } else if (operand instanceof ObjectValue) {\n switch (filter.value) {\n case \"items\":\n return new ArrayValue(\n Array.from(operand.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value]))\n );\n case \"length\":\n return new NumericValue(operand.value.size);\n default:\n throw new Error(`Unknown ObjectValue filter: ${filter.value}`);\n }\n }\n throw new Error(`Cannot apply filter \"${filter.value}\" to type: ${operand.type}`);\n } else if (node.filter.type === \"CallExpression\") {\n const filter = node.filter;\n if (filter.callee.type !== \"Identifier\") {\n throw new Error(`Unknown filter: ${filter.callee.type}`);\n }\n const filterName = filter.callee.value;\n if (filterName === \"tojson\") {\n const [, kwargs] = this.evaluateArguments(filter.args, environment);\n const indent = kwargs.get(\"indent\") ?? new NullValue();\n if (!(indent instanceof NumericValue || indent instanceof NullValue)) {\n throw new Error(\"If set, indent must be a number\");\n }\n return new StringValue(toJSON(operand, indent.value));\n }\n if (operand instanceof ArrayValue) {\n switch (filterName) {\n case \"selectattr\": {\n if (operand.value.some((x) => !(x instanceof ObjectValue))) {\n throw new Error(\"`selectattr` can only be applied to array of objects\");\n }\n if (filter.args.some((x) => x.type !== \"StringLiteral\")) {\n throw new Error(\"arguments of `selectattr` must be strings\");\n }\n const [attr, testName, value] = filter.args.map((x) => this.evaluate(x, environment));\n let testFunction;\n if (testName) {\n const test = environment.tests.get(testName.value);\n if (!test) {\n throw new Error(`Unknown test: ${testName.value}`);\n }\n testFunction = test;\n } else {\n testFunction = (...x) => x[0].__bool__().value;\n }\n const filtered = operand.value.filter((item) => {\n const a = item.value.get(attr.value);\n if (a) {\n return testFunction(a, value);\n }\n return false;\n });\n return new ArrayValue(filtered);\n }\n case \"map\": {\n const [, kwargs] = this.evaluateArguments(filter.args, environment);\n if (kwargs.has(\"attribute\")) {\n const attr = kwargs.get(\"attribute\");\n if (!(attr instanceof StringValue)) {\n throw new Error(\"attribute must be a string\");\n }\n const defaultValue = kwargs.get(\"default\");\n const mapped = operand.value.map((item) => {\n if (!(item instanceof ObjectValue)) {\n throw new Error(\"items in map must be an object\");\n }\n return item.value.get(attr.value) ?? defaultValue ?? new UndefinedValue();\n });\n return new ArrayValue(mapped);\n } else {\n throw new Error(\"`map` expressions without `attribute` set are not currently supported.\");\n }\n }\n }\n throw new Error(`Unknown ArrayValue filter: ${filterName}`);\n } else if (operand instanceof StringValue) {\n switch (filterName) {\n case \"indent\": {\n const [args, kwargs] = this.evaluateArguments(filter.args, environment);\n const width = args.at(0) ?? kwargs.get(\"width\") ?? new NumericValue(4);\n if (!(width instanceof NumericValue)) {\n throw new Error(\"width must be a number\");\n }\n const first = args.at(1) ?? kwargs.get(\"first\") ?? new BooleanValue(false);\n const blank = args.at(2) ?? kwargs.get(\"blank\") ?? new BooleanValue(false);\n const lines = operand.value.split(\"\\n\");\n const indent = \" \".repeat(width.value);\n const indented = lines.map(\n (x, i) => !first.value && i === 0 || !blank.value && x.length === 0 ? x : indent + x\n );\n return new StringValue(indented.join(\"\\n\"));\n }\n }\n throw new Error(`Unknown StringValue filter: ${filterName}`);\n } else {\n throw new Error(`Cannot apply filter \"${filterName}\" to type: ${operand.type}`);\n }\n }\n throw new Error(`Unknown filter: ${node.filter.type}`);\n }\n /**\n * Evaluates expressions following the test operation type.\n */\n evaluateTestExpression(node, environment) {\n const operand = this.evaluate(node.operand, environment);\n const test = environment.tests.get(node.test.value);\n if (!test) {\n throw new Error(`Unknown test: ${node.test.value}`);\n }\n const result = test(operand);\n return new BooleanValue(node.negate ? !result : result);\n }\n /**\n * Evaluates expressions following the unary operation type.\n */\n evaluateUnaryExpression(node, environment) {\n const argument = this.evaluate(node.argument, environment);\n switch (node.operator.value) {\n case \"not\":\n return new BooleanValue(!argument.value);\n default:\n throw new SyntaxError(`Unknown operator: ${node.operator.value}`);\n }\n }\n evalProgram(program, environment) {\n return this.evaluateBlock(program.body, environment);\n }\n evaluateBlock(statements, environment) {\n let result = \"\";\n for (const statement of statements) {\n const lastEvaluated = this.evaluate(statement, environment);\n if (lastEvaluated.type !== \"NullValue\" && lastEvaluated.type !== \"UndefinedValue\") {\n result += lastEvaluated.value;\n }\n }\n return new StringValue(result);\n }\n evaluateIdentifier(node, environment) {\n return environment.lookupVariable(node.value);\n }\n evaluateCallExpression(expr, environment) {\n const [args, kwargs] = this.evaluateArguments(expr.args, environment);\n if (kwargs.size > 0) {\n args.push(new KeywordArgumentsValue(kwargs));\n }\n const fn = this.evaluate(expr.callee, environment);\n if (fn.type !== \"FunctionValue\") {\n throw new Error(`Cannot call something that is not a function: got ${fn.type}`);\n }\n return fn.value(args, environment);\n }\n evaluateSliceExpression(object, expr, environment) {\n if (!(object instanceof ArrayValue || object instanceof StringValue)) {\n throw new Error(\"Slice object must be an array or string\");\n }\n const start = this.evaluate(expr.start, environment);\n const stop = this.evaluate(expr.stop, environment);\n const step = this.evaluate(expr.step, environment);\n if (!(start instanceof NumericValue || start instanceof UndefinedValue)) {\n throw new Error(\"Slice start must be numeric or undefined\");\n }\n if (!(stop instanceof NumericValue || stop instanceof UndefinedValue)) {\n throw new Error(\"Slice stop must be numeric or undefined\");\n }\n if (!(step instanceof NumericValue || step instanceof UndefinedValue)) {\n throw new Error(\"Slice step must be numeric or undefined\");\n }\n if (object instanceof ArrayValue) {\n return new ArrayValue(slice(object.value, start.value, stop.value, step.value));\n } else {\n return new StringValue(slice(Array.from(object.value), start.value, stop.value, step.value).join(\"\"));\n }\n }\n evaluateMemberExpression(expr, environment) {\n const object = this.evaluate(expr.object, environment);\n let property;\n if (expr.computed) {\n if (expr.property.type === \"SliceExpression\") {\n return this.evaluateSliceExpression(object, expr.property, environment);\n } else {\n property = this.evaluate(expr.property, environment);\n }\n } else {\n property = new StringValue(expr.property.value);\n }\n let value;\n if (object instanceof ObjectValue) {\n if (!(property instanceof StringValue)) {\n throw new Error(`Cannot access property with non-string: got ${property.type}`);\n }\n value = object.value.get(property.value) ?? object.builtins.get(property.value);\n } else if (object instanceof ArrayValue || object instanceof StringValue) {\n if (property instanceof NumericValue) {\n value = object.value.at(property.value);\n if (object instanceof StringValue) {\n value = new StringValue(object.value.at(property.value));\n }\n } else if (property instanceof StringValue) {\n value = object.builtins.get(property.value);\n } else {\n throw new Error(`Cannot access property with non-string/non-number: got ${property.type}`);\n }\n } else {\n if (!(property instanceof StringValue)) {\n throw new Error(`Cannot access property with non-string: got ${property.type}`);\n }\n value = object.builtins.get(property.value);\n }\n return value instanceof RuntimeValue ? value : new UndefinedValue();\n }\n evaluateSet(node, environment) {\n const rhs = this.evaluate(node.value, environment);\n if (node.assignee.type === \"Identifier\") {\n const variableName = node.assignee.value;\n environment.setVariable(variableName, rhs);\n } else if (node.assignee.type === \"MemberExpression\") {\n const member = node.assignee;\n const object = this.evaluate(member.object, environment);\n if (!(object instanceof ObjectValue)) {\n throw new Error(\"Cannot assign to member of non-object\");\n }\n if (member.property.type !== \"Identifier\") {\n throw new Error(\"Cannot assign to member with non-identifier property\");\n }\n object.value.set(member.property.value, rhs);\n } else {\n throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(node.assignee)}`);\n }\n return new NullValue();\n }\n evaluateIf(node, environment) {\n const test = this.evaluate(node.test, environment);\n return this.evaluateBlock(test.__bool__().value ? node.body : node.alternate, environment);\n }\n evaluateFor(node, environment) {\n const scope = new Environment(environment);\n let test, iterable;\n if (node.iterable.type === \"SelectExpression\") {\n const select = node.iterable;\n iterable = this.evaluate(select.iterable, scope);\n test = select.test;\n } else {\n iterable = this.evaluate(node.iterable, scope);\n }\n if (!(iterable instanceof ArrayValue)) {\n throw new Error(`Expected iterable type in for loop: got ${iterable.type}`);\n }\n const items = [];\n const scopeUpdateFunctions = [];\n for (let i = 0; i < iterable.value.length; ++i) {\n const loopScope = new Environment(scope);\n const current = iterable.value[i];\n let scopeUpdateFunction;\n if (node.loopvar.type === \"Identifier\") {\n scopeUpdateFunction = (scope2) => scope2.setVariable(node.loopvar.value, current);\n } else if (node.loopvar.type === \"TupleLiteral\") {\n const loopvar = node.loopvar;\n if (current.type !== \"ArrayValue\") {\n throw new Error(`Cannot unpack non-iterable type: ${current.type}`);\n }\n const c = current;\n if (loopvar.value.length !== c.value.length) {\n throw new Error(`Too ${loopvar.value.length > c.value.length ? \"few\" : \"many\"} items to unpack`);\n }\n scopeUpdateFunction = (scope2) => {\n for (let j = 0; j < loopvar.value.length; ++j) {\n if (loopvar.value[j].type !== \"Identifier\") {\n throw new Error(`Cannot unpack non-identifier type: ${loopvar.value[j].type}`);\n }\n scope2.setVariable(loopvar.value[j].value, c.value[j]);\n }\n };\n } else {\n throw new Error(`Invalid loop variable(s): ${node.loopvar.type}`);\n }\n if (test) {\n scopeUpdateFunction(loopScope);\n const testValue = this.evaluate(test, loopScope);\n if (!testValue.__bool__().value) {\n continue;\n }\n }\n items.push(current);\n scopeUpdateFunctions.push(scopeUpdateFunction);\n }\n let result = \"\";\n let noIteration = true;\n for (let i = 0; i < items.length; ++i) {\n const loop = /* @__PURE__ */ new Map([\n [\"index\", new NumericValue(i + 1)],\n [\"index0\", new NumericValue(i)],\n [\"revindex\", new NumericValue(items.length - i)],\n [\"revindex0\", new NumericValue(items.length - i - 1)],\n [\"first\", new BooleanValue(i === 0)],\n [\"last\", new BooleanValue(i === items.length - 1)],\n [\"length\", new NumericValue(items.length)],\n [\"previtem\", i > 0 ? items[i - 1] : new UndefinedValue()],\n [\"nextitem\", i < items.length - 1 ? items[i + 1] : new UndefinedValue()]\n ]);\n scope.setVariable(\"loop\", new ObjectValue(loop));\n scopeUpdateFunctions[i](scope);\n const evaluated = this.evaluateBlock(node.body, scope);\n result += evaluated.value;\n noIteration = false;\n }\n if (noIteration) {\n const defaultEvaluated = this.evaluateBlock(node.defaultBlock, scope);\n result += defaultEvaluated.value;\n }\n return new StringValue(result);\n }\n /**\n * See https://jinja.palletsprojects.com/en/3.1.x/templates/#macros for more information.\n */\n evaluateMacro(node, environment) {\n environment.setVariable(\n node.name.value,\n new FunctionValue((args, scope) => {\n const macroScope = new Environment(scope);\n args = args.slice();\n let kwargs;\n if (args.at(-1)?.type === \"KeywordArgumentsValue\") {\n kwargs = args.pop();\n }\n for (let i = 0; i < node.args.length; ++i) {\n const nodeArg = node.args[i];\n const passedArg = args[i];\n if (nodeArg.type === \"Identifier\") {\n const identifier = nodeArg;\n if (!passedArg) {\n throw new Error(`Missing positional argument: ${identifier.value}`);\n }\n macroScope.setVariable(identifier.value, passedArg);\n } else if (nodeArg.type === \"KeywordArgumentExpression\") {\n const kwarg = nodeArg;\n const value = passedArg ?? // Try positional arguments first\n kwargs?.value.get(kwarg.key.value) ?? // Look in user-passed kwargs\n this.evaluate(kwarg.value, macroScope);\n macroScope.setVariable(kwarg.key.value, value);\n } else {\n throw new Error(`Unknown argument type: ${nodeArg.type}`);\n }\n }\n return this.evaluateBlock(node.body, macroScope);\n })\n );\n return new NullValue();\n }\n evaluate(statement, environment) {\n if (statement === void 0)\n return new UndefinedValue();\n switch (statement.type) {\n case \"Program\":\n return this.evalProgram(statement, environment);\n case \"Set\":\n return this.evaluateSet(statement, environment);\n case \"If\":\n return this.evaluateIf(statement, environment);\n case \"For\":\n return this.evaluateFor(statement, environment);\n case \"Macro\":\n return this.evaluateMacro(statement, environment);\n case \"NumericLiteral\":\n return new NumericValue(Number(statement.value));\n case \"StringLiteral\":\n return new StringValue(statement.value);\n case \"BooleanLiteral\":\n return new BooleanValue(statement.value);\n case \"ArrayLiteral\":\n return new ArrayValue(statement.value.map((x) => this.evaluate(x, environment)));\n case \"TupleLiteral\":\n return new TupleValue(statement.value.map((x) => this.evaluate(x, environment)));\n case \"ObjectLiteral\": {\n const mapping = /* @__PURE__ */ new Map();\n for (const [key, value] of statement.value) {\n const evaluatedKey = this.evaluate(key, environment);\n if (!(evaluatedKey instanceof StringValue)) {\n throw new Error(`Object keys must be strings: got ${evaluatedKey.type}`);\n }\n mapping.set(evaluatedKey.value, this.evaluate(value, environment));\n }\n return new ObjectValue(mapping);\n }\n case \"Identifier\":\n return this.evaluateIdentifier(statement, environment);\n case \"CallExpression\":\n return this.evaluateCallExpression(statement, environment);\n case \"MemberExpression\":\n return this.evaluateMemberExpression(statement, environment);\n case \"UnaryExpression\":\n return this.evaluateUnaryExpression(statement, environment);\n case \"BinaryExpression\":\n return this.evaluateBinaryExpression(statement, environment);\n case \"FilterExpression\":\n return this.evaluateFilterExpression(statement, environment);\n case \"TestExpression\":\n return this.evaluateTestExpression(statement, environment);\n default:\n throw new SyntaxError(`Unknown node type: ${statement.type}`);\n }\n }\n};\nfunction convertToRuntimeValues(input) {\n switch (typeof input) {\n case \"number\":\n return new NumericValue(input);\n case \"string\":\n return new StringValue(input);\n case \"boolean\":\n return new BooleanValue(input);\n case \"undefined\":\n return new UndefinedValue();\n case \"object\":\n if (input === null) {\n return new NullValue();\n } else if (Array.isArray(input)) {\n return new ArrayValue(input.map(convertToRuntimeValues));\n } else {\n return new ObjectValue(\n new Map(Object.entries(input).map(([key, value]) => [key, convertToRuntimeValues(value)]))\n );\n }\n case \"function\":\n return new FunctionValue((args, _scope) => {\n const result = input(...args.map((x) => x.value)) ?? null;\n return convertToRuntimeValues(result);\n });\n default:\n throw new Error(`Cannot convert to runtime value: ${input}`);\n }\n}\nfunction toJSON(input, indent, depth) {\n const currentDepth = depth ?? 0;\n switch (input.type) {\n case \"NullValue\":\n case \"UndefinedValue\":\n return \"null\";\n case \"NumericValue\":\n case \"StringValue\":\n case \"BooleanValue\":\n return JSON.stringify(input.value);\n case \"ArrayValue\":\n case \"ObjectValue\": {\n const indentValue = indent ? \" \".repeat(indent) : \"\";\n const basePadding = \"\\n\" + indentValue.repeat(currentDepth);\n const childrenPadding = basePadding + indentValue;\n if (input.type === \"ArrayValue\") {\n const core = input.value.map((x) => toJSON(x, indent, currentDepth + 1));\n return indent ? `[${childrenPadding}${core.join(`,${childrenPadding}`)}${basePadding}]` : `[${core.join(\", \")}]`;\n } else {\n const core = Array.from(input.value.entries()).map(([key, value]) => {\n const v = `\"${key}\": ${toJSON(value, indent, currentDepth + 1)}`;\n return indent ? `${childrenPadding}${v}` : v;\n });\n return indent ? `{${core.join(\",\")}${basePadding}}` : `{${core.join(\", \")}}`;\n }\n }\n default:\n throw new Error(`Cannot convert to JSON: ${input.type}`);\n }\n}\n\n// src/index.ts\nvar Template = class {\n parsed;\n /**\n * @param {string} template The template string\n */\n constructor(template) {\n const tokens = tokenize(template, {\n lstrip_blocks: true,\n trim_blocks: true\n });\n this.parsed = parse(tokens);\n }\n render(items) {\n const env = new Environment();\n env.set(\"false\", false);\n env.set(\"true\", true);\n env.set(\"raise_exception\", (args) => {\n throw new Error(args);\n });\n env.set(\"range\", range);\n for (const [key, value] of Object.entries(items)) {\n env.set(key, value);\n }\n const interpreter = new Interpreter(env);\n const result = interpreter.run(this.parsed);\n return result.value;\n }\n};\nexport {\n Environment,\n Interpreter,\n Template,\n parse,\n tokenize\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nconst backends = new Map();\nconst backendsSortedByPriority = [];\n/**\n * Register a backend.\n *\n * @param name - the name as a key to lookup as an execution provider.\n * @param backend - the backend object.\n * @param priority - an integer indicating the priority of the backend. Higher number means higher priority. if priority\n * < 0, it will be considered as a 'beta' version and will not be used as a fallback backend by default.\n *\n * @ignore\n */\nexport const registerBackend = (name, backend, priority) => {\n if (backend && typeof backend.init === 'function' && typeof backend.createInferenceSessionHandler === 'function') {\n const currentBackend = backends.get(name);\n if (currentBackend === undefined) {\n backends.set(name, { backend, priority });\n }\n else if (currentBackend.priority > priority) {\n // same name is already registered with a higher priority. skip registeration.\n return;\n }\n else if (currentBackend.priority === priority) {\n if (currentBackend.backend !== backend) {\n throw new Error(`cannot register backend \"${name}\" using priority ${priority}`);\n }\n }\n if (priority >= 0) {\n const i = backendsSortedByPriority.indexOf(name);\n if (i !== -1) {\n backendsSortedByPriority.splice(i, 1);\n }\n for (let i = 0; i < backendsSortedByPriority.length; i++) {\n if (backends.get(backendsSortedByPriority[i]).priority <= priority) {\n backendsSortedByPriority.splice(i, 0, name);\n return;\n }\n }\n backendsSortedByPriority.push(name);\n }\n return;\n }\n throw new TypeError('not a valid backend');\n};\n/**\n * Try to resolve and initialize a backend.\n *\n * @param backendName - the name of the backend.\n * @returns the backend instance if resolved and initialized successfully, or an error message if failed.\n */\nconst tryResolveAndInitializeBackend = async (backendName) => {\n const backendInfo = backends.get(backendName);\n if (!backendInfo) {\n return 'backend not found.';\n }\n if (backendInfo.initialized) {\n return backendInfo.backend;\n }\n else if (backendInfo.aborted) {\n return backendInfo.error;\n }\n else {\n const isInitializing = !!backendInfo.initPromise;\n try {\n if (!isInitializing) {\n backendInfo.initPromise = backendInfo.backend.init(backendName);\n }\n await backendInfo.initPromise;\n backendInfo.initialized = true;\n return backendInfo.backend;\n }\n catch (e) {\n if (!isInitializing) {\n backendInfo.error = `${e}`;\n backendInfo.aborted = true;\n }\n return backendInfo.error;\n }\n finally {\n delete backendInfo.initPromise;\n }\n }\n};\n/**\n * Resolve execution providers from the specific session options.\n *\n * @param options - the session options object.\n * @returns a promise that resolves to a tuple of an initialized backend instance and a session options object with\n * filtered EP list.\n *\n * @ignore\n */\nexport const resolveBackendAndExecutionProviders = async (options) => {\n // extract backend hints from session options\n const eps = options.executionProviders || [];\n const backendHints = eps.map(i => typeof i === 'string' ? i : i.name);\n const backendNames = backendHints.length === 0 ? backendsSortedByPriority : backendHints;\n // try to resolve and initialize all requested backends\n let backend;\n const errors = [];\n const availableBackendNames = new Set();\n for (const backendName of backendNames) {\n const resolveResult = await tryResolveAndInitializeBackend(backendName);\n if (typeof resolveResult === 'string') {\n errors.push({ name: backendName, err: resolveResult });\n }\n else {\n if (!backend) {\n backend = resolveResult;\n }\n if (backend === resolveResult) {\n availableBackendNames.add(backendName);\n }\n }\n }\n // if no backend is available, throw error.\n if (!backend) {\n throw new Error(`no available backend found. ERR: ${errors.map(e => `[${e.name}] ${e.err}`).join(', ')}`);\n }\n // for each explicitly requested backend, if it's not available, output warning message.\n for (const { name, err } of errors) {\n if (backendHints.includes(name)) {\n // eslint-disable-next-line no-console\n console.warn(`removing requested execution provider \"${name}\" from session options because it is not available: ${err}`);\n }\n }\n const filteredEps = eps.filter(i => availableBackendNames.has(typeof i === 'string' ? i : i.name));\n return [\n backend, new Proxy(options, {\n get: (target, prop) => {\n if (prop === 'executionProviders') {\n return filteredEps;\n }\n return Reflect.get(target, prop);\n }\n })\n ];\n};\n//# sourceMappingURL=backend-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { version } from './version.js';\nlet logLevelValue = 'warning';\nexport const env = {\n wasm: {},\n webgl: {},\n webgpu: {},\n versions: { common: version },\n set logLevel(value) {\n if (value === undefined) {\n return;\n }\n if (typeof value !== 'string' || ['verbose', 'info', 'warning', 'error', 'fatal'].indexOf(value) === -1) {\n throw new Error(`Unsupported logging level: ${value}`);\n }\n logLevelValue = value;\n },\n get logLevel() {\n return logLevelValue;\n },\n};\n// set property 'logLevel' so that they can be correctly transferred to worker by `postMessage()`.\nObject.defineProperty(env, 'logLevel', { enumerable: true });\n//# sourceMappingURL=env-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { env as envImpl } from './env-impl.js';\n/**\n * Represent a set of flags as a global singleton.\n */\nexport const env = envImpl;\n//# sourceMappingURL=env.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { resolveBackendAndExecutionProviders } from './backend-impl.js';\nimport { Tensor } from './tensor.js';\nimport { TRACE_FUNC_BEGIN, TRACE_FUNC_END } from './trace.js';\nexport class InferenceSession {\n constructor(handler) {\n this.handler = handler;\n }\n async run(feeds, arg1, arg2) {\n TRACE_FUNC_BEGIN();\n const fetches = {};\n let options = {};\n // check inputs\n if (typeof feeds !== 'object' || feeds === null || feeds instanceof Tensor || Array.isArray(feeds)) {\n throw new TypeError('\\'feeds\\' must be an object that use input names as keys and OnnxValue as corresponding values.');\n }\n let isFetchesEmpty = true;\n // determine which override is being used\n if (typeof arg1 === 'object') {\n if (arg1 === null) {\n throw new TypeError('Unexpected argument[1]: cannot be null.');\n }\n if (arg1 instanceof Tensor) {\n throw new TypeError('\\'fetches\\' cannot be a Tensor');\n }\n if (Array.isArray(arg1)) {\n if (arg1.length === 0) {\n throw new TypeError('\\'fetches\\' cannot be an empty array.');\n }\n isFetchesEmpty = false;\n // output names\n for (const name of arg1) {\n if (typeof name !== 'string') {\n throw new TypeError('\\'fetches\\' must be a string array or an object.');\n }\n if (this.outputNames.indexOf(name) === -1) {\n throw new RangeError(`'fetches' contains invalid output name: ${name}.`);\n }\n fetches[name] = null;\n }\n if (typeof arg2 === 'object' && arg2 !== null) {\n options = arg2;\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else {\n // decide whether arg1 is fetches or options\n // if any output name is present and its value is valid OnnxValue, we consider it fetches\n let isFetches = false;\n const arg1Keys = Object.getOwnPropertyNames(arg1);\n for (const name of this.outputNames) {\n if (arg1Keys.indexOf(name) !== -1) {\n const v = arg1[name];\n if (v === null || v instanceof Tensor) {\n isFetches = true;\n isFetchesEmpty = false;\n fetches[name] = v;\n }\n }\n }\n if (isFetches) {\n if (typeof arg2 === 'object' && arg2 !== null) {\n options = arg2;\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else {\n options = arg1;\n }\n }\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('Unexpected argument[1]: must be \\'fetches\\' or \\'options\\'.');\n }\n // check if all inputs are in feed\n for (const name of this.inputNames) {\n if (typeof feeds[name] === 'undefined') {\n throw new Error(`input '${name}' is missing in 'feeds'.`);\n }\n }\n // if no fetches is specified, we use the full output names list\n if (isFetchesEmpty) {\n for (const name of this.outputNames) {\n fetches[name] = null;\n }\n }\n // feeds, fetches and options are prepared\n const results = await this.handler.run(feeds, fetches, options);\n const returnValue = {};\n for (const key in results) {\n if (Object.hasOwnProperty.call(results, key)) {\n const result = results[key];\n if (result instanceof Tensor) {\n returnValue[key] = result;\n }\n else {\n returnValue[key] = new Tensor(result.type, result.data, result.dims);\n }\n }\n }\n TRACE_FUNC_END();\n return returnValue;\n }\n async release() {\n return this.handler.dispose();\n }\n static async create(arg0, arg1, arg2, arg3) {\n TRACE_FUNC_BEGIN();\n // either load from a file or buffer\n let filePathOrUint8Array;\n let options = {};\n if (typeof arg0 === 'string') {\n filePathOrUint8Array = arg0;\n if (typeof arg1 === 'object' && arg1 !== null) {\n options = arg1;\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else if (arg0 instanceof Uint8Array) {\n filePathOrUint8Array = arg0;\n if (typeof arg1 === 'object' && arg1 !== null) {\n options = arg1;\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else if (arg0 instanceof ArrayBuffer ||\n (typeof SharedArrayBuffer !== 'undefined' && arg0 instanceof SharedArrayBuffer)) {\n const buffer = arg0;\n let byteOffset = 0;\n let byteLength = arg0.byteLength;\n if (typeof arg1 === 'object' && arg1 !== null) {\n options = arg1;\n }\n else if (typeof arg1 === 'number') {\n byteOffset = arg1;\n if (!Number.isSafeInteger(byteOffset)) {\n throw new RangeError('\\'byteOffset\\' must be an integer.');\n }\n if (byteOffset < 0 || byteOffset >= buffer.byteLength) {\n throw new RangeError(`'byteOffset' is out of range [0, ${buffer.byteLength}).`);\n }\n byteLength = arg0.byteLength - byteOffset;\n if (typeof arg2 === 'number') {\n byteLength = arg2;\n if (!Number.isSafeInteger(byteLength)) {\n throw new RangeError('\\'byteLength\\' must be an integer.');\n }\n if (byteLength <= 0 || byteOffset + byteLength > buffer.byteLength) {\n throw new RangeError(`'byteLength' is out of range (0, ${buffer.byteLength - byteOffset}].`);\n }\n if (typeof arg3 === 'object' && arg3 !== null) {\n options = arg3;\n }\n else if (typeof arg3 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'byteLength\\' must be a number.');\n }\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n filePathOrUint8Array = new Uint8Array(buffer, byteOffset, byteLength);\n }\n else {\n throw new TypeError('Unexpected argument[0]: must be \\'path\\' or \\'buffer\\'.');\n }\n // resolve backend, update session options with validated EPs, and create session handler\n const [backend, optionsWithValidatedEPs] = await resolveBackendAndExecutionProviders(options);\n const handler = await backend.createInferenceSessionHandler(filePathOrUint8Array, optionsWithValidatedEPs);\n TRACE_FUNC_END();\n return new InferenceSession(handler);\n }\n startProfiling() {\n this.handler.startProfiling();\n }\n endProfiling() {\n this.handler.endProfiling();\n }\n get inputNames() {\n return this.handler.inputNames;\n }\n get outputNames() {\n return this.handler.outputNames;\n }\n}\n//# sourceMappingURL=inference-session-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { InferenceSession as InferenceSessionImpl } from './inference-session-impl.js';\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const InferenceSession = InferenceSessionImpl;\n//# sourceMappingURL=inference-session.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n/**\n * implementation of Tensor.toDataURL()\n */\nexport const tensorToDataURL = (tensor, options) => {\n const canvas = typeof document !== 'undefined' ? document.createElement('canvas') : (new OffscreenCanvas(1, 1));\n canvas.width = tensor.dims[3];\n canvas.height = tensor.dims[2];\n const pixels2DContext = canvas.getContext('2d');\n if (pixels2DContext != null) {\n // Default values for height and width & format\n let width;\n let height;\n if (options?.tensorLayout !== undefined && options.tensorLayout === 'NHWC') {\n width = tensor.dims[2];\n height = tensor.dims[3];\n }\n else { // Default layout is NCWH\n width = tensor.dims[3];\n height = tensor.dims[2];\n }\n const inputformat = options?.format !== undefined ? options.format : 'RGB';\n const norm = options?.norm;\n let normMean;\n let normBias;\n if (norm === undefined || norm.mean === undefined) {\n normMean = [255, 255, 255, 255];\n }\n else {\n if (typeof (norm.mean) === 'number') {\n normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n }\n else {\n normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 0];\n if (norm.mean[3] !== undefined) {\n normMean[3] = norm.mean[3];\n }\n }\n }\n if (norm === undefined || norm.bias === undefined) {\n normBias = [0, 0, 0, 0];\n }\n else {\n if (typeof (norm.bias) === 'number') {\n normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n }\n else {\n normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];\n if (norm.bias[3] !== undefined) {\n normBias[3] = norm.bias[3];\n }\n }\n }\n const stride = height * width;\n // Default pointer assignments\n let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;\n // Updating the pointer assignments based on the input image format\n if (inputformat === 'RGBA') {\n rTensorPointer = 0;\n gTensorPointer = stride;\n bTensorPointer = stride * 2;\n aTensorPointer = stride * 3;\n }\n else if (inputformat === 'RGB') {\n rTensorPointer = 0;\n gTensorPointer = stride;\n bTensorPointer = stride * 2;\n }\n else if (inputformat === 'RBG') {\n rTensorPointer = 0;\n bTensorPointer = stride;\n gTensorPointer = stride * 2;\n }\n for (let i = 0; i < height; i++) {\n for (let j = 0; j < width; j++) {\n const R = (tensor.data[rTensorPointer++] - normBias[0]) * normMean[0]; // R value\n const G = (tensor.data[gTensorPointer++] - normBias[1]) * normMean[1]; // G value\n const B = (tensor.data[bTensorPointer++] - normBias[2]) * normMean[2]; // B value\n const A = aTensorPointer === -1 ?\n 255 :\n (tensor.data[aTensorPointer++] - normBias[3]) * normMean[3]; // A value\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n pixels2DContext.fillStyle = 'rgba(' + R + ',' + G + ',' + B + ',' + A + ')';\n pixels2DContext.fillRect(j, i, 1, 1);\n }\n }\n if ('toDataURL' in canvas) {\n return canvas.toDataURL();\n }\n else {\n throw new Error('toDataURL is not supported');\n }\n }\n else {\n throw new Error('Can not access image data');\n }\n};\n/**\n * implementation of Tensor.toImageData()\n */\nexport const tensorToImageData = (tensor, options) => {\n const pixels2DContext = typeof document !== 'undefined' ?\n document.createElement('canvas').getContext('2d') :\n new OffscreenCanvas(1, 1).getContext('2d');\n let image;\n if (pixels2DContext != null) {\n // Default values for height and width & format\n let width;\n let height;\n let channels;\n if (options?.tensorLayout !== undefined && options.tensorLayout === 'NHWC') {\n width = tensor.dims[2];\n height = tensor.dims[1];\n channels = tensor.dims[3];\n }\n else { // Default layout is NCWH\n width = tensor.dims[3];\n height = tensor.dims[2];\n channels = tensor.dims[1];\n }\n const inputformat = options !== undefined ? (options.format !== undefined ? options.format : 'RGB') : 'RGB';\n const norm = options?.norm;\n let normMean;\n let normBias;\n if (norm === undefined || norm.mean === undefined) {\n normMean = [255, 255, 255, 255];\n }\n else {\n if (typeof (norm.mean) === 'number') {\n normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n }\n else {\n normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 255];\n if (norm.mean[3] !== undefined) {\n normMean[3] = norm.mean[3];\n }\n }\n }\n if (norm === undefined || norm.bias === undefined) {\n normBias = [0, 0, 0, 0];\n }\n else {\n if (typeof (norm.bias) === 'number') {\n normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n }\n else {\n normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];\n if (norm.bias[3] !== undefined) {\n normBias[3] = norm.bias[3];\n }\n }\n }\n const stride = height * width;\n if (options !== undefined) {\n if (options.format !== undefined && (channels === 4 && options.format !== 'RGBA') ||\n (channels === 3 && (options.format !== 'RGB' && options.format !== 'BGR'))) {\n throw new Error('Tensor format doesn\\'t match input tensor dims');\n }\n }\n // Default pointer assignments\n const step = 4;\n let rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;\n let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;\n // Updating the pointer assignments based on the input image format\n if (inputformat === 'RGBA') {\n rTensorPointer = 0;\n gTensorPointer = stride;\n bTensorPointer = stride * 2;\n aTensorPointer = stride * 3;\n }\n else if (inputformat === 'RGB') {\n rTensorPointer = 0;\n gTensorPointer = stride;\n bTensorPointer = stride * 2;\n }\n else if (inputformat === 'RBG') {\n rTensorPointer = 0;\n bTensorPointer = stride;\n gTensorPointer = stride * 2;\n }\n image = pixels2DContext.createImageData(width, height);\n for (let i = 0; i < height * width; rImagePointer += step, gImagePointer += step, bImagePointer += step, aImagePointer += step, i++) {\n image.data[rImagePointer] = (tensor.data[rTensorPointer++] - normBias[0]) * normMean[0]; // R value\n image.data[gImagePointer] = (tensor.data[gTensorPointer++] - normBias[1]) * normMean[1]; // G value\n image.data[bImagePointer] = (tensor.data[bTensorPointer++] - normBias[2]) * normMean[2]; // B value\n image.data[aImagePointer] = aTensorPointer === -1 ?\n 255 :\n (tensor.data[aTensorPointer++] - normBias[3]) * normMean[3]; // A value\n }\n }\n else {\n throw new Error('Can not access image data');\n }\n return image;\n};\n//# sourceMappingURL=tensor-conversion-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { Tensor } from './tensor-impl.js';\n/**\n * Create a new tensor object from image object\n *\n * @param buffer - Extracted image buffer data - assuming RGBA format\n * @param imageFormat - input image configuration - required configurations height, width, format\n * @param tensorFormat - output tensor configuration - Default is RGB format\n */\nexport const bufferToTensor = (buffer, options) => {\n if (buffer === undefined) {\n throw new Error('Image buffer must be defined');\n }\n if (options.height === undefined || options.width === undefined) {\n throw new Error('Image height and width must be defined');\n }\n if (options.tensorLayout === 'NHWC') {\n throw new Error('NHWC Tensor layout is not supported yet');\n }\n const { height, width } = options;\n const norm = options.norm ?? { mean: 255, bias: 0 };\n let normMean;\n let normBias;\n if (typeof (norm.mean) === 'number') {\n normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n }\n else {\n normMean = [norm.mean[0], norm.mean[1], norm.mean[2], norm.mean[3] ?? 255];\n }\n if (typeof (norm.bias) === 'number') {\n normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n }\n else {\n normBias = [norm.bias[0], norm.bias[1], norm.bias[2], norm.bias[3] ?? 0];\n }\n const inputformat = options.format !== undefined ? options.format : 'RGBA';\n // default value is RGBA since imagedata and HTMLImageElement uses it\n const outputformat = options.tensorFormat !== undefined ? (options.tensorFormat !== undefined ? options.tensorFormat : 'RGB') : 'RGB';\n const stride = height * width;\n const float32Data = outputformat === 'RGBA' ? new Float32Array(stride * 4) : new Float32Array(stride * 3);\n // Default pointer assignments\n let step = 4, rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;\n let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;\n // Updating the pointer assignments based on the input image format\n if (inputformat === 'RGB') {\n step = 3;\n rImagePointer = 0;\n gImagePointer = 1;\n bImagePointer = 2;\n aImagePointer = -1;\n }\n // Updating the pointer assignments based on the output tensor format\n if (outputformat === 'RGBA') {\n aTensorPointer = stride * 3;\n }\n else if (outputformat === 'RBG') {\n rTensorPointer = 0;\n bTensorPointer = stride;\n gTensorPointer = stride * 2;\n }\n else if (outputformat === 'BGR') {\n bTensorPointer = 0;\n gTensorPointer = stride;\n rTensorPointer = stride * 2;\n }\n for (let i = 0; i < stride; i++, rImagePointer += step, bImagePointer += step, gImagePointer += step, aImagePointer += step) {\n float32Data[rTensorPointer++] = (buffer[rImagePointer] + normBias[0]) / normMean[0];\n float32Data[gTensorPointer++] = (buffer[gImagePointer] + normBias[1]) / normMean[1];\n float32Data[bTensorPointer++] = (buffer[bImagePointer] + normBias[2]) / normMean[2];\n if (aTensorPointer !== -1 && aImagePointer !== -1) {\n float32Data[aTensorPointer++] = (buffer[aImagePointer] + normBias[3]) / normMean[3];\n }\n }\n // Float32Array -> ort.Tensor\n const outputTensor = outputformat === 'RGBA' ? new Tensor('float32', float32Data, [1, 4, height, width]) :\n new Tensor('float32', float32Data, [1, 3, height, width]);\n return outputTensor;\n};\n/**\n * implementation of Tensor.fromImage().\n */\nexport const tensorFromImage = async (image, options) => {\n // checking the type of image object\n const isHTMLImageEle = typeof (HTMLImageElement) !== 'undefined' && image instanceof HTMLImageElement;\n const isImageDataEle = typeof (ImageData) !== 'undefined' && image instanceof ImageData;\n const isImageBitmap = typeof (ImageBitmap) !== 'undefined' && image instanceof ImageBitmap;\n const isString = typeof image === 'string';\n let data;\n let bufferToTensorOptions = options ?? {};\n const createCanvas = () => {\n if (typeof document !== 'undefined') {\n return document.createElement('canvas');\n }\n else if (typeof OffscreenCanvas !== 'undefined') {\n return new OffscreenCanvas(1, 1);\n }\n else {\n throw new Error('Canvas is not supported');\n }\n };\n const createCanvasContext = (canvas) => {\n if (canvas instanceof HTMLCanvasElement) {\n return canvas.getContext('2d');\n }\n else if (canvas instanceof OffscreenCanvas) {\n return canvas.getContext('2d');\n }\n else {\n return null;\n }\n };\n // filling and checking image configuration options\n if (isHTMLImageEle) {\n // HTMLImageElement - image object - format is RGBA by default\n const canvas = createCanvas();\n canvas.width = image.width;\n canvas.height = image.height;\n const pixels2DContext = createCanvasContext(canvas);\n if (pixels2DContext != null) {\n let height = image.height;\n let width = image.width;\n if (options !== undefined && options.resizedHeight !== undefined && options.resizedWidth !== undefined) {\n height = options.resizedHeight;\n width = options.resizedWidth;\n }\n if (options !== undefined) {\n bufferToTensorOptions = options;\n if (options.tensorFormat !== undefined) {\n throw new Error('Image input config format must be RGBA for HTMLImageElement');\n }\n else {\n bufferToTensorOptions.tensorFormat = 'RGBA';\n }\n bufferToTensorOptions.height = height;\n bufferToTensorOptions.width = width;\n }\n else {\n bufferToTensorOptions.tensorFormat = 'RGBA';\n bufferToTensorOptions.height = height;\n bufferToTensorOptions.width = width;\n }\n pixels2DContext.drawImage(image, 0, 0);\n data = pixels2DContext.getImageData(0, 0, width, height).data;\n }\n else {\n throw new Error('Can not access image data');\n }\n }\n else if (isImageDataEle) {\n let height;\n let width;\n if (options !== undefined && options.resizedWidth !== undefined && options.resizedHeight !== undefined) {\n height = options.resizedHeight;\n width = options.resizedWidth;\n }\n else {\n height = image.height;\n width = image.width;\n }\n if (options !== undefined) {\n bufferToTensorOptions = options;\n }\n bufferToTensorOptions.format = 'RGBA';\n bufferToTensorOptions.height = height;\n bufferToTensorOptions.width = width;\n if (options !== undefined) {\n const tempCanvas = createCanvas();\n tempCanvas.width = width;\n tempCanvas.height = height;\n const pixels2DContext = createCanvasContext(tempCanvas);\n if (pixels2DContext != null) {\n pixels2DContext.putImageData(image, 0, 0);\n data = pixels2DContext.getImageData(0, 0, width, height).data;\n }\n else {\n throw new Error('Can not access image data');\n }\n }\n else {\n data = image.data;\n }\n }\n else if (isImageBitmap) {\n // ImageBitmap - image object - format must be provided by user\n if (options === undefined) {\n throw new Error('Please provide image config with format for Imagebitmap');\n }\n const canvas = createCanvas();\n canvas.width = image.width;\n canvas.height = image.height;\n const pixels2DContext = createCanvasContext(canvas);\n if (pixels2DContext != null) {\n const height = image.height;\n const width = image.width;\n pixels2DContext.drawImage(image, 0, 0, width, height);\n data = pixels2DContext.getImageData(0, 0, width, height).data;\n bufferToTensorOptions.height = height;\n bufferToTensorOptions.width = width;\n return bufferToTensor(data, bufferToTensorOptions);\n }\n else {\n throw new Error('Can not access image data');\n }\n }\n else if (isString) {\n return new Promise((resolve, reject) => {\n const canvas = createCanvas();\n const context = createCanvasContext(canvas);\n if (!image || !context) {\n return reject();\n }\n const newImage = new Image();\n newImage.crossOrigin = 'Anonymous';\n newImage.src = image;\n newImage.onload = () => {\n canvas.width = newImage.width;\n canvas.height = newImage.height;\n context.drawImage(newImage, 0, 0, canvas.width, canvas.height);\n const img = context.getImageData(0, 0, canvas.width, canvas.height);\n bufferToTensorOptions.height = canvas.height;\n bufferToTensorOptions.width = canvas.width;\n resolve(bufferToTensor(img.data, bufferToTensorOptions));\n };\n });\n }\n else {\n throw new Error('Input data provided is not supported - aborted tensor creation');\n }\n if (data !== undefined) {\n return bufferToTensor(data, bufferToTensorOptions);\n }\n else {\n throw new Error('Input data provided is not supported - aborted tensor creation');\n }\n};\n/**\n * implementation of Tensor.fromTexture().\n */\nexport const tensorFromTexture = (texture, options) => {\n const { width, height, download, dispose } = options;\n // Always assume RGBAF32. TODO: support different texture format\n const dims = [1, height, width, 4];\n return new Tensor({ location: 'texture', type: 'float32', texture, dims, download, dispose });\n};\n/**\n * implementation of Tensor.fromGpuBuffer().\n */\nexport const tensorFromGpuBuffer = (gpuBuffer, options) => {\n const { dataType, dims, download, dispose } = options;\n return new Tensor({ location: 'gpu-buffer', type: dataType ?? 'float32', gpuBuffer, dims, download, dispose });\n};\n/**\n * implementation of Tensor.fromPinnedBuffer().\n */\nexport const tensorFromPinnedBuffer = (type, buffer, dims) => new Tensor({ location: 'cpu-pinned', type, data: buffer, dims: dims ?? [buffer.length] });\n//# sourceMappingURL=tensor-factory-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.\nexport const NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = new Map([\n ['float32', Float32Array],\n ['uint8', Uint8Array],\n ['int8', Int8Array],\n ['uint16', Uint16Array],\n ['int16', Int16Array],\n ['int32', Int32Array],\n ['bool', Uint8Array],\n ['float64', Float64Array],\n ['uint32', Uint32Array],\n]);\n// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.\nexport const NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = new Map([\n [Float32Array, 'float32'],\n [Uint8Array, 'uint8'],\n [Int8Array, 'int8'],\n [Uint16Array, 'uint16'],\n [Int16Array, 'int16'],\n [Int32Array, 'int32'],\n [Float64Array, 'float64'],\n [Uint32Array, 'uint32'],\n]);\n// the following code allows delaying execution of BigInt/Float16Array checking. This allows lazy initialization for\n// NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP and NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP, which allows BigInt/Float16Array\n// polyfill if available.\nlet isTypedArrayChecked = false;\nexport const checkTypedArray = () => {\n if (!isTypedArrayChecked) {\n isTypedArrayChecked = true;\n const isBigInt64ArrayAvailable = typeof BigInt64Array !== 'undefined' && BigInt64Array.from;\n const isBigUint64ArrayAvailable = typeof BigUint64Array !== 'undefined' && BigUint64Array.from;\n const isFloat16ArrayAvailable = typeof Float16Array !== 'undefined' && Float16Array.from;\n if (isBigInt64ArrayAvailable) {\n NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('int64', BigInt64Array);\n NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, 'int64');\n }\n if (isBigUint64ArrayAvailable) {\n NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('uint64', BigUint64Array);\n NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, 'uint64');\n }\n if (isFloat16ArrayAvailable) {\n NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('float16', Float16Array);\n NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(Float16Array, 'float16');\n }\n else {\n // if Float16Array is not available, use 'Uint16Array' to store the data.\n NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('float16', Uint16Array);\n }\n }\n};\n//# sourceMappingURL=tensor-impl-type-mapping.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { tensorToDataURL, tensorToImageData } from './tensor-conversion-impl.js';\nimport { tensorFromGpuBuffer, tensorFromImage, tensorFromPinnedBuffer, tensorFromTexture } from './tensor-factory-impl.js';\nimport { checkTypedArray, NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP, NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP } from './tensor-impl-type-mapping.js';\nimport { calculateSize, tensorReshape } from './tensor-utils-impl.js';\n/**\n * the implementation of Tensor interface.\n *\n * @ignore\n */\nexport class Tensor {\n /**\n * implementation.\n */\n constructor(arg0, arg1, arg2) {\n // perform one-time check for BigInt/Float16Array support\n checkTypedArray();\n let type;\n let dims;\n if (typeof arg0 === 'object' && 'location' in arg0) {\n //\n // constructing tensor from specific location\n //\n this.dataLocation = arg0.location;\n type = arg0.type;\n dims = arg0.dims;\n switch (arg0.location) {\n case 'cpu-pinned': {\n const expectedTypedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(type);\n if (!expectedTypedArrayConstructor) {\n throw new TypeError(`unsupported type \"${type}\" to create tensor from pinned buffer`);\n }\n if (!(arg0.data instanceof expectedTypedArrayConstructor)) {\n throw new TypeError(`buffer should be of type ${expectedTypedArrayConstructor.name}`);\n }\n this.cpuData = arg0.data;\n break;\n }\n case 'texture': {\n if (type !== 'float32') {\n throw new TypeError(`unsupported type \"${type}\" to create tensor from texture`);\n }\n this.gpuTextureData = arg0.texture;\n this.downloader = arg0.download;\n this.disposer = arg0.dispose;\n break;\n }\n case 'gpu-buffer': {\n if ((type !== 'float32' && type !== 'float16' && type !== 'int32' && type !== 'int64' && type !== 'uint32' &&\n type !== 'uint8' && type !== 'bool')) {\n throw new TypeError(`unsupported type \"${type}\" to create tensor from gpu buffer`);\n }\n this.gpuBufferData = arg0.gpuBuffer;\n this.downloader = arg0.download;\n this.disposer = arg0.dispose;\n break;\n }\n default:\n throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`);\n }\n }\n else {\n //\n // constructing tensor of location 'cpu'\n //\n let data;\n let maybeDims;\n // check whether arg0 is type or data\n if (typeof arg0 === 'string') {\n //\n // Override: constructor(type, data, ...)\n //\n type = arg0;\n maybeDims = arg2;\n if (arg0 === 'string') {\n // string tensor\n if (!Array.isArray(arg1)) {\n throw new TypeError('A string tensor\\'s data must be a string array.');\n }\n // we don't check whether every element in the array is string; this is too slow. we assume it's correct and\n // error will be populated at inference\n data = arg1;\n }\n else {\n // numeric tensor\n const typedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(arg0);\n if (typedArrayConstructor === undefined) {\n throw new TypeError(`Unsupported tensor type: ${arg0}.`);\n }\n if (Array.isArray(arg1)) {\n if (arg0 === 'float16' && typedArrayConstructor === Uint16Array) {\n // When no Float16Array polyfill is used, we cannot create 'float16' tensor from number array.\n //\n // Throw error here because when user try to use number array as data,\n // e.g. new Tensor('float16', [1, 2, 3, 4], dims)), it will actually call\n // Uint16Array.from(arg1) which generates wrong data.\n throw new TypeError('Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.');\n }\n else if (arg0 === 'uint64' || arg0 === 'int64') {\n // use 'as any' here because:\n // 1. TypeScript's check on type of 'Array.isArray()' does not work with readonly arrays.\n // see https://github.com/microsoft/TypeScript/issues/17002\n // 2. TypeScript's check on union type of '(BigInt64ArrayConstructor|BigUint64ArrayConstructor).from()'\n // does not accept parameter mapFn.\n // 3. parameters of 'SupportedTypedArrayConstructors.from()' does not match the requirement of the union\n // type.\n // assume 'arg1' is of type \"readonly number[]|readonly bigint[]\" here.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data = typedArrayConstructor.from(arg1, BigInt);\n }\n else {\n // assume 'arg1' is of type \"readonly number[]\" here.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data = typedArrayConstructor.from(arg1);\n }\n }\n else if (arg1 instanceof typedArrayConstructor) {\n data = arg1;\n }\n else {\n throw new TypeError(`A ${type} tensor's data must be type of ${typedArrayConstructor}`);\n }\n }\n }\n else {\n //\n // Override: constructor(data, ...)\n //\n maybeDims = arg1;\n if (Array.isArray(arg0)) {\n // only boolean[] and string[] is supported\n if (arg0.length === 0) {\n throw new TypeError('Tensor type cannot be inferred from an empty array.');\n }\n const firstElementType = typeof arg0[0];\n if (firstElementType === 'string') {\n type = 'string';\n data = arg0;\n }\n else if (firstElementType === 'boolean') {\n type = 'bool';\n // 'arg0' is of type 'boolean[]'. Uint8Array.from(boolean[]) actually works, but typescript thinks this is\n // wrong type. We use 'as any' to make it happy.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data = Uint8Array.from(arg0);\n }\n else {\n throw new TypeError(`Invalid element type of data array: ${firstElementType}.`);\n }\n }\n else {\n // get tensor type from TypedArray\n const mappedType = NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(arg0.constructor);\n if (mappedType === undefined) {\n throw new TypeError(`Unsupported type for tensor data: ${arg0.constructor}.`);\n }\n type = mappedType;\n data = arg0;\n }\n }\n // type and data is processed, now processing dims\n if (maybeDims === undefined) {\n // assume 1-D tensor if dims omitted\n maybeDims = [data.length];\n }\n else if (!Array.isArray(maybeDims)) {\n throw new TypeError('A tensor\\'s dims must be a number array');\n }\n dims = maybeDims;\n this.cpuData = data;\n this.dataLocation = 'cpu';\n }\n // perform check on dims\n const size = calculateSize(dims);\n // if data is on CPU, check whether data length matches tensor size\n if (this.cpuData && size !== this.cpuData.length) {\n throw new Error(`Tensor's size(${size}) does not match data length(${this.cpuData.length}).`);\n }\n this.type = type;\n this.dims = dims;\n this.size = size;\n }\n // #endregion\n // #region factory\n static async fromImage(image, options) {\n return tensorFromImage(image, options);\n }\n static fromTexture(texture, options) {\n return tensorFromTexture(texture, options);\n }\n static fromGpuBuffer(gpuBuffer, options) {\n return tensorFromGpuBuffer(gpuBuffer, options);\n }\n static fromPinnedBuffer(type, buffer, dims) {\n return tensorFromPinnedBuffer(type, buffer, dims);\n }\n // #endregion\n // #region conversions\n toDataURL(options) {\n return tensorToDataURL(this, options);\n }\n toImageData(options) {\n return tensorToImageData(this, options);\n }\n // #endregion\n // #region properties\n get data() {\n this.ensureValid();\n if (!this.cpuData) {\n throw new Error('The data is not on CPU. Use `getData()` to download GPU data to CPU, ' +\n 'or use `texture` or `gpuBuffer` property to access the GPU data directly.');\n }\n return this.cpuData;\n }\n get location() {\n return this.dataLocation;\n }\n get texture() {\n this.ensureValid();\n if (!this.gpuTextureData) {\n throw new Error('The data is not stored as a WebGL texture.');\n }\n return this.gpuTextureData;\n }\n get gpuBuffer() {\n this.ensureValid();\n if (!this.gpuBufferData) {\n throw new Error('The data is not stored as a WebGPU buffer.');\n }\n return this.gpuBufferData;\n }\n // #endregion\n // #region methods\n async getData(releaseData) {\n this.ensureValid();\n switch (this.dataLocation) {\n case 'cpu':\n case 'cpu-pinned':\n return this.data;\n case 'texture':\n case 'gpu-buffer': {\n if (!this.downloader) {\n throw new Error('The current tensor is not created with a specified data downloader.');\n }\n if (this.isDownloading) {\n throw new Error('The current tensor is being downloaded.');\n }\n try {\n this.isDownloading = true;\n const data = await this.downloader();\n this.downloader = undefined;\n this.dataLocation = 'cpu';\n this.cpuData = data;\n if (releaseData && this.disposer) {\n this.disposer();\n this.disposer = undefined;\n }\n return data;\n }\n finally {\n this.isDownloading = false;\n }\n }\n default:\n throw new Error(`cannot get data from location: ${this.dataLocation}`);\n }\n }\n dispose() {\n if (this.isDownloading) {\n throw new Error('The current tensor is being downloaded.');\n }\n if (this.disposer) {\n this.disposer();\n this.disposer = undefined;\n }\n this.cpuData = undefined;\n this.gpuTextureData = undefined;\n this.gpuBufferData = undefined;\n this.downloader = undefined;\n this.isDownloading = undefined;\n this.dataLocation = 'none';\n }\n // #endregion\n // #region tensor utilities\n ensureValid() {\n if (this.dataLocation === 'none') {\n throw new Error('The tensor is disposed.');\n }\n }\n reshape(dims) {\n this.ensureValid();\n if (this.downloader || this.disposer) {\n throw new Error('Cannot reshape a tensor that owns GPU resource.');\n }\n return tensorReshape(this, dims);\n }\n}\n//# sourceMappingURL=tensor-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { Tensor } from './tensor-impl.js';\n/**\n * calculate size from dims.\n *\n * @param dims the dims array. May be an illegal input.\n */\nexport const calculateSize = (dims) => {\n let size = 1;\n for (let i = 0; i < dims.length; i++) {\n const dim = dims[i];\n if (typeof dim !== 'number' || !Number.isSafeInteger(dim)) {\n throw new TypeError(`dims[${i}] must be an integer, got: ${dim}`);\n }\n if (dim < 0) {\n throw new RangeError(`dims[${i}] must be a non-negative integer, got: ${dim}`);\n }\n size *= dim;\n }\n return size;\n};\n/**\n * implementation of Tensor.reshape()\n */\nexport const tensorReshape = (tensor, dims) => {\n switch (tensor.location) {\n case 'cpu':\n return new Tensor(tensor.type, tensor.data, dims);\n case 'cpu-pinned':\n return new Tensor({\n location: 'cpu-pinned',\n data: tensor.data,\n type: tensor.type,\n dims,\n });\n case 'texture':\n return new Tensor({\n location: 'texture',\n texture: tensor.texture,\n type: tensor.type,\n dims,\n });\n case 'gpu-buffer':\n return new Tensor({\n location: 'gpu-buffer',\n gpuBuffer: tensor.gpuBuffer,\n type: tensor.type,\n dims,\n });\n default:\n throw new Error(`tensorReshape: tensor location ${tensor.location} is not supported`);\n }\n};\n//# sourceMappingURL=tensor-utils-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { Tensor as TensorImpl } from './tensor-impl.js';\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const Tensor = TensorImpl;\n//# sourceMappingURL=tensor.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { env } from './env-impl.js';\n/**\n * @ignore\n */\nexport const TRACE = (deviceType, label) => {\n if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n return;\n }\n // eslint-disable-next-line no-console\n console.timeStamp(`${deviceType}::ORT::${label}`);\n};\nconst TRACE_FUNC = (msg, extraMsg) => {\n const stack = new Error().stack?.split(/\\r\\n|\\r|\\n/g) || [];\n let hasTraceFunc = false;\n for (let i = 0; i < stack.length; i++) {\n if (hasTraceFunc && !stack[i].includes('TRACE_FUNC')) {\n let label = `FUNC_${msg}::${stack[i].trim().split(' ')[1]}`;\n if (extraMsg) {\n label += `::${extraMsg}`;\n }\n TRACE('CPU', label);\n return;\n }\n if (stack[i].includes('TRACE_FUNC')) {\n hasTraceFunc = true;\n }\n }\n};\n/**\n * @ignore\n */\nexport const TRACE_FUNC_BEGIN = (extraMsg) => {\n if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n return;\n }\n TRACE_FUNC('BEGIN', extraMsg);\n};\n/**\n * @ignore\n */\nexport const TRACE_FUNC_END = (extraMsg) => {\n if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n return;\n }\n TRACE_FUNC('END', extraMsg);\n};\n//# sourceMappingURL=trace.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { resolveBackendAndExecutionProviders } from './backend-impl.js';\nimport { Tensor } from './tensor.js';\nconst noBackendErrMsg = 'Training backend could not be resolved. ' +\n 'Make sure you\\'re using the correct configuration & WebAssembly files.';\nexport class TrainingSession {\n constructor(handler, hasOptimizerModel, hasEvalModel) {\n this.handler = handler;\n this.hasOptimizerModel = hasOptimizerModel;\n this.hasEvalModel = hasEvalModel;\n }\n get trainingInputNames() {\n return this.handler.inputNames;\n }\n get trainingOutputNames() {\n return this.handler.outputNames;\n }\n get evalInputNames() {\n if (this.hasEvalModel) {\n return this.handler.evalInputNames;\n }\n else {\n throw new Error('This training session has no evalModel loaded.');\n }\n }\n get evalOutputNames() {\n if (this.hasEvalModel) {\n return this.handler.evalOutputNames;\n }\n else {\n throw new Error('This training session has no evalModel loaded.');\n }\n }\n static async create(trainingOptions, sessionOptions) {\n const evalModel = trainingOptions.evalModel || '';\n const optimizerModel = trainingOptions.optimizerModel || '';\n const options = sessionOptions || {};\n // resolve backend, update session options with validated EPs, and create session handler\n const [backend, optionsWithValidatedEPs] = await resolveBackendAndExecutionProviders(options);\n if (backend.createTrainingSessionHandler) {\n const handler = await backend.createTrainingSessionHandler(trainingOptions.checkpointState, trainingOptions.trainModel, evalModel, optimizerModel, optionsWithValidatedEPs);\n return new TrainingSession(handler, !!trainingOptions.optimizerModel, !!trainingOptions.evalModel);\n }\n else {\n throw new Error(noBackendErrMsg);\n }\n }\n /**\n * Helper function for runTrainStep and future runStep methods that handles the type-narrowing conversion from\n * the given parameters to SessionHandler.FetchesType and RunOptions.\n *\n * @param inputNames the feeds object is checked that they contain all input names in the provided list of input\n * names.\n * @param outputNames the fetches object is checked that their keys match up with valid names in the list of output\n * names.\n * @param feeds the required input\n * @param arg1 narrowed & converted into the SessionHandler.FetchesType or RunOptions object\n * @param arg2 optional RunOptions object.\n * @returns\n */\n typeNarrowingForRunStep(inputNames, outputNames, feeds, arg1, arg2) {\n const fetches = {};\n let options = {};\n // check inputs\n if (typeof feeds !== 'object' || feeds === null || feeds instanceof Tensor || Array.isArray(feeds)) {\n throw new TypeError('\\'feeds\\' must be an object that use input names as keys and OnnxValue as corresponding values.');\n }\n let isFetchesEmpty = true;\n // determine which override is being used\n if (typeof arg1 === 'object') {\n if (arg1 === null) {\n throw new TypeError('Unexpected argument[1]: cannot be null.');\n }\n if (arg1 instanceof Tensor) {\n throw new TypeError('\\'fetches\\' cannot be a Tensor');\n }\n if (Array.isArray(arg1)) {\n if (arg1.length === 0) {\n throw new TypeError('\\'fetches\\' cannot be an empty array.');\n }\n isFetchesEmpty = false;\n // output names\n for (const name of arg1) {\n if (typeof name !== 'string') {\n throw new TypeError('\\'fetches\\' must be a string array or an object.');\n }\n if (outputNames.indexOf(name) === -1) {\n throw new RangeError(`'fetches' contains invalid output name: ${name}.`);\n }\n fetches[name] = null;\n }\n if (typeof arg2 === 'object' && arg2 !== null) {\n options = arg2;\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else {\n // decide whether arg1 is fetches or options\n // if any output name is present and its value is valid OnnxValue, we consider it fetches\n let isFetches = false;\n const arg1Keys = Object.getOwnPropertyNames(arg1);\n for (const name of outputNames) {\n if (arg1Keys.indexOf(name) !== -1) {\n const v = arg1[name];\n if (v === null || v instanceof Tensor) {\n isFetches = true;\n isFetchesEmpty = false;\n fetches[name] = v;\n }\n }\n }\n if (isFetches) {\n if (typeof arg2 === 'object' && arg2 !== null) {\n options = arg2;\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else {\n options = arg1;\n }\n }\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('Unexpected argument[1]: must be \\'fetches\\' or \\'options\\'.');\n }\n // check if all inputs are in feed\n for (const name of inputNames) {\n if (typeof feeds[name] === 'undefined') {\n throw new Error(`input '${name}' is missing in 'feeds'.`);\n }\n }\n // if no fetches is specified, we use the full output names list\n if (isFetchesEmpty) {\n for (const name of outputNames) {\n fetches[name] = null;\n }\n }\n return [fetches, options];\n }\n /**\n * Helper method for runTrainStep and any other runStep methods. Takes the ReturnType result from the SessionHandler\n * and changes it into a map of Tensors.\n *\n * @param results\n * @returns\n */\n convertHandlerReturnTypeToMapOfTensors(results) {\n const returnValue = {};\n for (const key in results) {\n if (Object.hasOwnProperty.call(results, key)) {\n const result = results[key];\n if (result instanceof Tensor) {\n returnValue[key] = result;\n }\n else {\n returnValue[key] = new Tensor(result.type, result.data, result.dims);\n }\n }\n }\n return returnValue;\n }\n async lazyResetGrad() {\n await this.handler.lazyResetGrad();\n }\n async runTrainStep(feeds, arg1, arg2) {\n const [fetches, options] = this.typeNarrowingForRunStep(this.trainingInputNames, this.trainingOutputNames, feeds, arg1, arg2);\n const results = await this.handler.runTrainStep(feeds, fetches, options);\n return this.convertHandlerReturnTypeToMapOfTensors(results);\n }\n async runOptimizerStep(options) {\n if (this.hasOptimizerModel) {\n await this.handler.runOptimizerStep(options || {});\n }\n else {\n throw new Error('This TrainingSession has no OptimizerModel loaded.');\n }\n }\n async runEvalStep(feeds, arg1, arg2) {\n if (this.hasEvalModel) {\n const [fetches, options] = this.typeNarrowingForRunStep(this.evalInputNames, this.evalOutputNames, feeds, arg1, arg2);\n const results = await this.handler.runEvalStep(feeds, fetches, options);\n return this.convertHandlerReturnTypeToMapOfTensors(results);\n }\n else {\n throw new Error('This TrainingSession has no EvalModel loaded.');\n }\n }\n async getParametersSize(trainableOnly = true) {\n return this.handler.getParametersSize(trainableOnly);\n }\n async loadParametersBuffer(array, trainableOnly = true) {\n const paramsSize = await this.getParametersSize(trainableOnly);\n // checking that the size of the Uint8Array is equivalent to the byte length of a Float32Array of the number\n // of parameters\n if (array.length !== 4 * paramsSize) {\n throw new Error('Size of the buffer passed into loadParametersBuffer must match the number of parameters in ' +\n 'the model. Please use getParametersSize method to check.');\n }\n return this.handler.loadParametersBuffer(array, trainableOnly);\n }\n async getContiguousParameters(trainableOnly = true) {\n return this.handler.getContiguousParameters(trainableOnly);\n }\n async release() {\n return this.handler.dispose();\n }\n}\n//# sourceMappingURL=training-session-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { TrainingSession as TrainingSessionImpl } from './training-session-impl.js';\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const TrainingSession = TrainingSessionImpl;\n//# sourceMappingURL=training-session.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n// This file is generated by /js/scripts/update-version.ts\n// Do not modify file content manually.\nexport const version = '1.19.2';\n//# sourceMappingURL=version.js.map","/*!\n * ONNX Runtime Web v1.21.0-dev.20241109-d3ad76b2cf\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\nvar Fn=Object.defineProperty;var Pp=Object.getOwnPropertyDescriptor;var zp=Object.getOwnPropertyNames;var Op=Object.prototype.hasOwnProperty;var qn=(e=>typeof require<\"u\"?require:typeof Proxy<\"u\"?new Proxy(e,{get:(t,r)=>(typeof require<\"u\"?require:t)[r]}):e)(function(e){if(typeof require<\"u\")return require.apply(this,arguments);throw Error('Dynamic require of \"'+e+'\" is not supported')});var R=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ft=(e,t)=>{for(var r in t)Fn(e,r,{get:t[r],enumerable:!0})},Dp=(e,t,r,n)=>{if(t&&typeof t==\"object\"||typeof t==\"function\")for(let o of zp(t))!Op.call(e,o)&&o!==r&&Fn(e,o,{get:()=>t[o],enumerable:!(n=Pp(t,o))||n.enumerable});return e};var vr=e=>Dp(Fn({},\"__esModule\",{value:!0}),e);var $r,$t,xt,Bp,xr,Sr=R(()=>{\"use strict\";$r=new Map,$t=[],xt=(e,t,r)=>{if(t&&typeof t.init==\"function\"&&typeof t.createInferenceSessionHandler==\"function\"){let n=$r.get(e);if(n===void 0)$r.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend \"${e}\" using priority ${r}`)}if(r>=0){let o=$t.indexOf(e);o!==-1&&$t.splice(o,1);for(let i=0;i<$t.length;i++)if($r.get($t[i]).priority<=r){$t.splice(i,0,e);return}$t.push(e)}return}throw new TypeError(\"not a valid backend\")},Bp=async e=>{let t=$r.get(e);if(!t)return\"backend not found.\";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},xr=async e=>{let t=e.executionProviders||[],r=t.map(d=>typeof d==\"string\"?d:d.name),n=r.length===0?$t:r,o,i=[],a=new Set;for(let d of n){let c=await Bp(d);typeof c==\"string\"?i.push({name:d,err:c}):(o||(o=c),o===c&&a.add(d))}if(!o)throw new Error(`no available backend found. ERR: ${i.map(d=>`[${d.name}] ${d.err}`).join(\", \")}`);for(let{name:d,err:c}of i)r.includes(d)&&console.warn(`removing requested execution provider \"${d}\" from session options because it is not available: ${c}`);let l=t.filter(d=>a.has(typeof d==\"string\"?d:d.name));return[o,new Proxy(e,{get:(d,c)=>c===\"executionProviders\"?l:Reflect.get(d,c)})]}});var oa=R(()=>{\"use strict\";Sr()});var ia,aa=R(()=>{\"use strict\";ia=\"1.21.0-dev.20241026-05fbb43b34\"});var sa,Re,jn=R(()=>{\"use strict\";aa();sa=\"warning\",Re={wasm:{},webgl:{},webgpu:{},versions:{common:ia},set logLevel(e){if(e!==void 0){if(typeof e!=\"string\"||[\"verbose\",\"info\",\"warning\",\"error\",\"fatal\"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);sa=e}},get logLevel(){return sa}};Object.defineProperty(Re,\"logLevel\",{enumerable:!0})});var ve,ua=R(()=>{\"use strict\";jn();ve=Re});var la,da,ca=R(()=>{\"use strict\";la=(e,t)=>{let r=typeof document<\"u\"?document.createElement(\"canvas\"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext(\"2d\");if(n!=null){let o,i;t?.tensorLayout!==void 0&&t.tensorLayout===\"NHWC\"?(o=e.dims[2],i=e.dims[3]):(o=e.dims[3],i=e.dims[2]);let a=t?.format!==void 0?t.format:\"RGB\",l=t?.norm,d,c;l===void 0||l.mean===void 0?d=[255,255,255,255]:typeof l.mean==\"number\"?d=[l.mean,l.mean,l.mean,l.mean]:(d=[l.mean[0],l.mean[1],l.mean[2],0],l.mean[3]!==void 0&&(d[3]=l.mean[3])),l===void 0||l.bias===void 0?c=[0,0,0,0]:typeof l.bias==\"number\"?c=[l.bias,l.bias,l.bias,l.bias]:(c=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(c[3]=l.bias[3]));let m=i*o,u=0,h=m,w=m*2,y=-1;a===\"RGBA\"?(u=0,h=m,w=m*2,y=m*3):a===\"RGB\"?(u=0,h=m,w=m*2):a===\"RBG\"&&(u=0,w=m,h=m*2);for(let g=0;g{let r=typeof document<\"u\"?document.createElement(\"canvas\").getContext(\"2d\"):new OffscreenCanvas(1,1).getContext(\"2d\"),n;if(r!=null){let o,i,a;t?.tensorLayout!==void 0&&t.tensorLayout===\"NHWC\"?(o=e.dims[2],i=e.dims[1],a=e.dims[3]):(o=e.dims[3],i=e.dims[2],a=e.dims[1]);let l=t!==void 0&&t.format!==void 0?t.format:\"RGB\",d=t?.norm,c,m;d===void 0||d.mean===void 0?c=[255,255,255,255]:typeof d.mean==\"number\"?c=[d.mean,d.mean,d.mean,d.mean]:(c=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(c[3]=d.mean[3])),d===void 0||d.bias===void 0?m=[0,0,0,0]:typeof d.bias==\"number\"?m=[d.bias,d.bias,d.bias,d.bias]:(m=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(m[3]=d.bias[3]));let u=i*o;if(t!==void 0&&(t.format!==void 0&&a===4&&t.format!==\"RGBA\"||a===3&&t.format!==\"RGB\"&&t.format!==\"BGR\"))throw new Error(\"Tensor format doesn't match input tensor dims\");let h=4,w=0,y=1,g=2,x=3,$=0,v=u,S=u*2,T=-1;l===\"RGBA\"?($=0,v=u,S=u*2,T=u*3):l===\"RGB\"?($=0,v=u,S=u*2):l===\"RBG\"&&($=0,S=u,v=u*2),n=r.createImageData(o,i);for(let C=0;C{\"use strict\";Tr();Kn=(e,t)=>{if(e===void 0)throw new Error(\"Image buffer must be defined\");if(t.height===void 0||t.width===void 0)throw new Error(\"Image height and width must be defined\");if(t.tensorLayout===\"NHWC\")throw new Error(\"NHWC Tensor layout is not supported yet\");let{height:r,width:n}=t,o=t.norm??{mean:255,bias:0},i,a;typeof o.mean==\"number\"?i=[o.mean,o.mean,o.mean,o.mean]:i=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias==\"number\"?a=[o.bias,o.bias,o.bias,o.bias]:a=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let l=t.format!==void 0?t.format:\"RGBA\",d=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:\"RGB\",c=r*n,m=d===\"RGBA\"?new Float32Array(c*4):new Float32Array(c*3),u=4,h=0,w=1,y=2,g=3,x=0,$=c,v=c*2,S=-1;l===\"RGB\"&&(u=3,h=0,w=1,y=2,g=-1),d===\"RGBA\"?S=c*3:d===\"RBG\"?(x=0,v=c,$=c*2):d===\"BGR\"&&(v=0,$=c,x=c*2);for(let C=0;C{let r=typeof HTMLImageElement<\"u\"&&e instanceof HTMLImageElement,n=typeof ImageData<\"u\"&&e instanceof ImageData,o=typeof ImageBitmap<\"u\"&&e instanceof ImageBitmap,i=typeof e==\"string\",a,l=t??{},d=()=>{if(typeof document<\"u\")return document.createElement(\"canvas\");if(typeof OffscreenCanvas<\"u\")return new OffscreenCanvas(1,1);throw new Error(\"Canvas is not supported\")},c=m=>typeof HTMLCanvasElement<\"u\"&&m instanceof HTMLCanvasElement||m instanceof OffscreenCanvas?m.getContext(\"2d\"):null;if(r){let m=d();m.width=e.width,m.height=e.height;let u=c(m);if(u!=null){let h=e.height,w=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(h=t.resizedHeight,w=t.resizedWidth),t!==void 0){if(l=t,t.tensorFormat!==void 0)throw new Error(\"Image input config format must be RGBA for HTMLImageElement\");l.tensorFormat=\"RGBA\",l.height=h,l.width=w}else l.tensorFormat=\"RGBA\",l.height=h,l.width=w;u.drawImage(e,0,0),a=u.getImageData(0,0,w,h).data}else throw new Error(\"Can not access image data\")}else if(n){let m,u;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(m=t.resizedHeight,u=t.resizedWidth):(m=e.height,u=e.width),t!==void 0&&(l=t),l.format=\"RGBA\",l.height=m,l.width=u,t!==void 0){let h=d();h.width=u,h.height=m;let w=c(h);if(w!=null)w.putImageData(e,0,0),a=w.getImageData(0,0,u,m).data;else throw new Error(\"Can not access image data\")}else a=e.data}else if(o){if(t===void 0)throw new Error(\"Please provide image config with format for Imagebitmap\");let m=d();m.width=e.width,m.height=e.height;let u=c(m);if(u!=null){let h=e.height,w=e.width;return u.drawImage(e,0,0,w,h),a=u.getImageData(0,0,w,h).data,l.height=h,l.width=w,Kn(a,l)}else throw new Error(\"Can not access image data\")}else{if(i)return new Promise((m,u)=>{let h=d(),w=c(h);if(!e||!w)return u();let y=new Image;y.crossOrigin=\"Anonymous\",y.src=e,y.onload=()=>{h.width=y.width,h.height=y.height,w.drawImage(y,0,0,h.width,h.height);let g=w.getImageData(0,0,h.width,h.height);l.height=h.height,l.width=h.width,m(Kn(g.data,l))}});throw new Error(\"Input data provided is not supported - aborted tensor creation\")}if(a!==void 0)return Kn(a,l);throw new Error(\"Input data provided is not supported - aborted tensor creation\")},ma=(e,t)=>{let{width:r,height:n,download:o,dispose:i}=t,a=[1,n,r,4];return new Oe({location:\"texture\",type:\"float32\",texture:e,dims:a,download:o,dispose:i})},fa=(e,t)=>{let{dataType:r,dims:n,download:o,dispose:i}=t;return new Oe({location:\"gpu-buffer\",type:r??\"float32\",gpuBuffer:e,dims:n,download:o,dispose:i})},ha=(e,t)=>{let{dataType:r,dims:n,download:o,dispose:i}=t;return new Oe({location:\"ml-tensor\",type:r??\"float32\",mlTensor:e,dims:n,download:o,dispose:i})},ga=(e,t,r)=>new Oe({location:\"cpu-pinned\",type:e,data:t,dims:r??[t.length]})});var St,qt,ya,wa,_a=R(()=>{\"use strict\";St=new Map([[\"float32\",Float32Array],[\"uint8\",Uint8Array],[\"int8\",Int8Array],[\"uint16\",Uint16Array],[\"int16\",Int16Array],[\"int32\",Int32Array],[\"bool\",Uint8Array],[\"float64\",Float64Array],[\"uint32\",Uint32Array],[\"int4\",Uint8Array],[\"uint4\",Uint8Array]]),qt=new Map([[Float32Array,\"float32\"],[Uint8Array,\"uint8\"],[Int8Array,\"int8\"],[Uint16Array,\"uint16\"],[Int16Array,\"int16\"],[Int32Array,\"int32\"],[Float64Array,\"float64\"],[Uint32Array,\"uint32\"]]),ya=!1,wa=()=>{if(!ya){ya=!0;let e=typeof BigInt64Array<\"u\"&&BigInt64Array.from,t=typeof BigUint64Array<\"u\"&&BigUint64Array.from,r=typeof Float16Array<\"u\"&&Float16Array.from;e&&(St.set(\"int64\",BigInt64Array),qt.set(BigInt64Array,\"int64\")),t&&(St.set(\"uint64\",BigUint64Array),qt.set(BigUint64Array,\"uint64\")),r?(St.set(\"float16\",Float16Array),qt.set(Float16Array,\"float16\")):St.set(\"float16\",Uint16Array)}}});var va,$a,xa=R(()=>{\"use strict\";Tr();va=e=>{let t=1;for(let r=0;r{switch(e.location){case\"cpu\":return new Oe(e.type,e.data,t);case\"cpu-pinned\":return new Oe({location:\"cpu-pinned\",data:e.data,type:e.type,dims:t});case\"texture\":return new Oe({location:\"texture\",texture:e.texture,type:e.type,dims:t});case\"gpu-buffer\":return new Oe({location:\"gpu-buffer\",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case\"ml-tensor\":return new Oe({location:\"ml-tensor\",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}});var Oe,Tr=R(()=>{\"use strict\";ca();ba();_a();xa();Oe=class{constructor(t,r,n){wa();let o,i;if(typeof t==\"object\"&&\"location\"in t)switch(this.dataLocation=t.location,o=t.type,i=t.dims,t.location){case\"cpu-pinned\":{let l=St.get(o);if(!l)throw new TypeError(`unsupported type \"${o}\" to create tensor from pinned buffer`);if(!(t.data instanceof l))throw new TypeError(`buffer should be of type ${l.name}`);this.cpuData=t.data;break}case\"texture\":{if(o!==\"float32\")throw new TypeError(`unsupported type \"${o}\" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case\"gpu-buffer\":{if(o!==\"float32\"&&o!==\"float16\"&&o!==\"int32\"&&o!==\"int64\"&&o!==\"uint32\"&&o!==\"uint8\"&&o!==\"bool\"&&o!==\"uint4\"&&o!==\"int4\")throw new TypeError(`unsupported type \"${o}\" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case\"ml-tensor\":{if(o!==\"float32\"&&o!==\"float16\"&&o!==\"int32\"&&o!==\"int64\"&&o!==\"uint32\"&&o!==\"uint64\"&&o!==\"int8\"&&o!==\"uint8\"&&o!==\"bool\"&&o!==\"uint4\"&&o!==\"int4\")throw new TypeError(`unsupported type \"${o}\" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let l,d;if(typeof t==\"string\")if(o=t,d=n,t===\"string\"){if(!Array.isArray(r))throw new TypeError(\"A string tensor's data must be a string array.\");l=r}else{let c=St.get(t);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t===\"float16\"&&c===Uint16Array||t===\"uint4\"||t===\"int4\")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${c.name} as data.`);t===\"uint64\"||t===\"int64\"?l=c.from(r,BigInt):l=c.from(r)}else if(r instanceof c)l=r;else if(r instanceof Uint8ClampedArray)if(t===\"uint8\")l=Uint8Array.from(r);else throw new TypeError(\"A Uint8ClampedArray tensor's data must be type of uint8\");else throw new TypeError(`A ${o} tensor's data must be type of ${c}`)}else if(d=r,Array.isArray(t)){if(t.length===0)throw new TypeError(\"Tensor type cannot be inferred from an empty array.\");let c=typeof t[0];if(c===\"string\")o=\"string\",l=t;else if(c===\"boolean\")o=\"bool\",l=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(t instanceof Uint8ClampedArray)o=\"uint8\",l=Uint8Array.from(t);else{let c=qt.get(t.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);o=c,l=t}if(d===void 0)d=[l.length];else if(!Array.isArray(d))throw new TypeError(\"A tensor's dims must be a number array\");i=d,this.cpuData=l,this.dataLocation=\"cpu\"}let a=va(i);if(this.cpuData&&a!==this.cpuData.length&&!((o===\"uint4\"||o===\"int4\")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=i,this.size=a}static async fromImage(t,r){return pa(t,r)}static fromTexture(t,r){return ma(t,r)}static fromGpuBuffer(t,r){return fa(t,r)}static fromMLTensor(t,r){return ha(t,r)}static fromPinnedBuffer(t,r,n){return ga(t,r,n)}toDataURL(t){return la(this,t)}toImageData(t){return da(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error(\"The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.\");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error(\"The data is not stored as a WebGL texture.\");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error(\"The data is not stored as a WebGPU buffer.\");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error(\"The data is not stored as a WebNN MLTensor.\");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case\"cpu\":case\"cpu-pinned\":return this.data;case\"texture\":case\"gpu-buffer\":case\"ml-tensor\":{if(!this.downloader)throw new Error(\"The current tensor is not created with a specified data downloader.\");if(this.isDownloading)throw new Error(\"The current tensor is being downloaded.\");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation=\"cpu\",this.cpuData=r,t&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error(\"The current tensor is being downloaded.\");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=\"none\"}ensureValid(){if(this.dataLocation===\"none\")throw new Error(\"The tensor is disposed.\")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error(\"Cannot reshape a tensor that owns GPU resource.\");return $a(this,t)}}});var De,Ir=R(()=>{\"use strict\";Tr();De=Oe});var Cr,Sa,Ue,Be,Yn=R(()=>{\"use strict\";jn();Cr=(e,t)=>{(typeof Re.trace>\"u\"?!Re.wasm.trace:!Re.trace)||console.timeStamp(`${e}::ORT::${t}`)},Sa=(e,t)=>{let r=new Error().stack?.split(/\\r\\n|\\r|\\n/g)||[],n=!1;for(let o=0;o{(typeof Re.trace>\"u\"?!Re.wasm.trace:!Re.trace)||Sa(\"BEGIN\",e)},Be=e=>{(typeof Re.trace>\"u\"?!Re.wasm.trace:!Re.trace)||Sa(\"END\",e)}});var Ar,Ta=R(()=>{\"use strict\";Sr();Ir();Yn();Ar=class e{constructor(t){this.handler=t}async run(t,r,n){Ue();let o={},i={};if(typeof t!=\"object\"||t===null||t instanceof De||Array.isArray(t))throw new TypeError(\"'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.\");let a=!0;if(typeof r==\"object\"){if(r===null)throw new TypeError(\"Unexpected argument[1]: cannot be null.\");if(r instanceof De)throw new TypeError(\"'fetches' cannot be a Tensor\");if(Array.isArray(r)){if(r.length===0)throw new TypeError(\"'fetches' cannot be an empty array.\");a=!1;for(let c of r){if(typeof c!=\"string\")throw new TypeError(\"'fetches' must be a string array or an object.\");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);o[c]=null}if(typeof n==\"object\"&&n!==null)i=n;else if(typeof n<\"u\")throw new TypeError(\"'options' must be an object.\")}else{let c=!1,m=Object.getOwnPropertyNames(r);for(let u of this.outputNames)if(m.indexOf(u)!==-1){let h=r[u];(h===null||h instanceof De)&&(c=!0,a=!1,o[u]=h)}if(c){if(typeof n==\"object\"&&n!==null)i=n;else if(typeof n<\"u\")throw new TypeError(\"'options' must be an object.\")}else i=r}}else if(typeof r<\"u\")throw new TypeError(\"Unexpected argument[1]: must be 'fetches' or 'options'.\");for(let c of this.inputNames)if(typeof t[c]>\"u\")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)o[c]=null;let l=await this.handler.run(t,o,i),d={};for(let c in l)if(Object.hasOwnProperty.call(l,c)){let m=l[c];m instanceof De?d[c]=m:d[c]=new De(m.type,m.data,m.dims)}return Be(),d}async release(){return this.handler.dispose()}static async create(t,r,n,o){Ue();let i,a={};if(typeof t==\"string\"){if(i=t,typeof r==\"object\"&&r!==null)a=r;else if(typeof r<\"u\")throw new TypeError(\"'options' must be an object.\")}else if(t instanceof Uint8Array){if(i=t,typeof r==\"object\"&&r!==null)a=r;else if(typeof r<\"u\")throw new TypeError(\"'options' must be an object.\")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<\"u\"&&t instanceof SharedArrayBuffer){let m=t,u=0,h=t.byteLength;if(typeof r==\"object\"&&r!==null)a=r;else if(typeof r==\"number\"){if(u=r,!Number.isSafeInteger(u))throw new RangeError(\"'byteOffset' must be an integer.\");if(u<0||u>=m.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${m.byteLength}).`);if(h=t.byteLength-u,typeof n==\"number\"){if(h=n,!Number.isSafeInteger(h))throw new RangeError(\"'byteLength' must be an integer.\");if(h<=0||u+h>m.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${m.byteLength-u}].`);if(typeof o==\"object\"&&o!==null)a=o;else if(typeof o<\"u\")throw new TypeError(\"'options' must be an object.\")}else if(typeof n<\"u\")throw new TypeError(\"'byteLength' must be a number.\")}else if(typeof r<\"u\")throw new TypeError(\"'options' must be an object.\");i=new Uint8Array(m,u,h)}else throw new TypeError(\"Unexpected argument[0]: must be 'path' or 'buffer'.\");let[l,d]=await xr(a),c=await l.createInferenceSessionHandler(i,d);return Be(),new e(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}});var Mp,Ia=R(()=>{\"use strict\";Ta();Mp=Ar});var Ca=R(()=>{\"use strict\"});var Aa=R(()=>{\"use strict\"});var ka=R(()=>{\"use strict\"});var Ea=R(()=>{\"use strict\"});var Rp,kr,Pa=R(()=>{\"use strict\";Sr();Ir();Rp=\"Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.\",kr=class e{constructor(t,r,n){this.handler=t,this.hasOptimizerModel=r,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error(\"This training session has no evalModel loaded.\")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error(\"This training session has no evalModel loaded.\")}static async create(t,r){let n=t.evalModel||\"\",o=t.optimizerModel||\"\",i=r||{},[a,l]=await xr(i);if(a.createTrainingSessionHandler){let d=await a.createTrainingSessionHandler(t.checkpointState,t.trainModel,n,o,l);return new e(d,!!t.optimizerModel,!!t.evalModel)}else throw new Error(Rp)}typeNarrowingForRunStep(t,r,n,o,i){let a={},l={};if(typeof n!=\"object\"||n===null||n instanceof De||Array.isArray(n))throw new TypeError(\"'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.\");let d=!0;if(typeof o==\"object\"){if(o===null)throw new TypeError(\"Unexpected argument[1]: cannot be null.\");if(o instanceof De)throw new TypeError(\"'fetches' cannot be a Tensor\");if(Array.isArray(o)){if(o.length===0)throw new TypeError(\"'fetches' cannot be an empty array.\");d=!1;for(let c of o){if(typeof c!=\"string\")throw new TypeError(\"'fetches' must be a string array or an object.\");if(r.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);a[c]=null}if(typeof i==\"object\"&&i!==null)l=i;else if(typeof i<\"u\")throw new TypeError(\"'options' must be an object.\")}else{let c=!1,m=Object.getOwnPropertyNames(o);for(let u of r)if(m.indexOf(u)!==-1){let h=o[u];(h===null||h instanceof De)&&(c=!0,d=!1,a[u]=h)}if(c){if(typeof i==\"object\"&&i!==null)l=i;else if(typeof i<\"u\")throw new TypeError(\"'options' must be an object.\")}else l=o}}else if(typeof o<\"u\")throw new TypeError(\"Unexpected argument[1]: must be 'fetches' or 'options'.\");for(let c of t)if(typeof n[c]>\"u\")throw new Error(`input '${c}' is missing in 'feeds'.`);if(d)for(let c of r)a[c]=null;return[a,l]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let n in t)if(Object.hasOwnProperty.call(t,n)){let o=t[n];o instanceof De?r[n]=o:r[n]=new De(o.type,o.data,o.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,n){let[o,i]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,n),a=await this.handler.runTrainStep(t,o,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}async runOptimizerStep(t){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(t||{});else throw new Error(\"This TrainingSession has no OptimizerModel loaded.\")}async runEvalStep(t,r,n){if(this.hasEvalModel){let[o,i]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,n),a=await this.handler.runEvalStep(t,o,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}else throw new Error(\"This TrainingSession has no EvalModel loaded.\")}async getParametersSize(t=!0){return this.handler.getParametersSize(t)}async loadParametersBuffer(t,r=!0){let n=await this.getParametersSize(r);if(t.length!==4*n)throw new Error(\"Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.\");return this.handler.loadParametersBuffer(t,r)}async getContiguousParameters(t=!0){return this.handler.getContiguousParameters(t)}async release(){return this.handler.dispose()}}});var Up,za=R(()=>{\"use strict\";Pa();Up=kr});var Zn={};Ft(Zn,{InferenceSession:()=>Mp,TRACE:()=>Cr,TRACE_FUNC_BEGIN:()=>Ue,TRACE_FUNC_END:()=>Be,Tensor:()=>De,TrainingSession:()=>Up,env:()=>ve,registerBackend:()=>xt});var He=R(()=>{\"use strict\";oa();ua();Ia();Ir();Ca();Aa();Yn();ka();Ea();za()});var Er=R(()=>{\"use strict\"});var Ma={};Ft(Ma,{default:()=>Vp});var Da,Ba,Vp,Ra=R(()=>{\"use strict\";Xn();gt();jt();Da=\"ort-wasm-proxy-worker\",Ba=globalThis.self?.name===Da;Ba&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case\"init-wasm\":Pr(r.wasm).then(()=>{zr(r).then(()=>{postMessage({type:t})},n=>{postMessage({type:t,err:n})})},n=>{postMessage({type:t,err:n})});break;case\"init-ep\":{let{epName:n,env:o}=r;Or(o,n).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case\"copy-from\":{let{buffer:n}=r,o=Kt(n);postMessage({type:t,out:o});break}case\"create\":{let{model:n,options:o}=r;Dr(n,o).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case\"release\":Br(r),postMessage({type:t});break;case\"run\":{let{sessionId:n,inputIndices:o,inputs:i,outputIndices:a,options:l}=r;Mr(n,o,i,a,new Array(a.length).fill(null),l).then(d=>{d.some(c=>c[3]!==\"cpu\")?postMessage({type:t,err:\"Proxy does not support non-cpu tensor location.\"}):postMessage({type:t,out:d},Ur([...i,...d]))},d=>{postMessage({type:t,err:d})});break}case\"end-profiling\":Rr(r),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}});Vp=Ba?null:e=>new Worker(e??Bt,{type:\"module\",name:Da})});var Va={};Ft(Va,{default:()=>Np});var Qn,Ua,Np,Na=R(()=>{\"use strict\";Ua=(Qn=import.meta.url,async function(e={}){function t(){return ue.buffer!=Q.buffer&&be(),Q}function r(){return ue.buffer!=Q.buffer&&be(),ne}function n(){return ue.buffer!=Q.buffer&&be(),we}function o(){return ue.buffer!=Q.buffer&&be(),Ae}function i(){return ue.buffer!=Q.buffer&&be(),$e}function a(){return ue.buffer!=Q.buffer&&be(),de}function l(){return ue.buffer!=Q.buffer&&be(),N}function d(){return ue.buffer!=Q.buffer&&be(),qe}var c,m,u=Object.assign({},e),h=new Promise((s,p)=>{c=s,m=p}),w=typeof window==\"object\",y=typeof importScripts==\"function\",g=y&&self.name==\"em-pthread\";u.mountExternalData=(s,p)=>{s.startsWith(\"./\")&&(s=s.substring(2)),(u.Eb||(u.Eb=new Map)).set(s,p)},u.unmountExternalData=()=>{delete u.Eb};var x=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let $=()=>{let s=(f,b,_)=>(...I)=>{let D=Qe,B=b?.();I=f(...I);let G=b?.();return B!==G&&(f=G,_(B),b=_=null),Qe!=D?new Promise((H,X)=>{Rn={resolve:H,reject:X}}):I},p=f=>async(...b)=>{try{if(u.Fb)throw Error(\"Session already started\");let _=u.Fb={fc:b[0],errors:[]},I=await f(...b);if(u.Fb!==_)throw Error(\"Session mismatch\");u.Gb?.flush();let D=_.errors;if(0G),0u._OrtCreateSession,f=>u._OrtCreateSession=f),u._OrtRun=p(s(u._OrtRun,()=>u._OrtRun,f=>u._OrtRun=f)),u._OrtRunWithBinding=p(s(u._OrtRunWithBinding,()=>u._OrtRunWithBinding,f=>u._OrtRunWithBinding=f)),u._OrtBindInput=s(u._OrtBindInput,()=>u._OrtBindInput,f=>u._OrtBindInput=f),$=void 0};u.jsepInit=(s,p)=>{if($?.(),s===\"webgpu\"){[u.Gb,u.Ub,u.Yb,u.Nb,u.Xb,u.jb,u.Zb,u.bc,u.Vb,u.Wb,u.$b]=p;let f=u.Gb;u.jsepRegisterBuffer=(b,_,I,D)=>f.registerBuffer(b,_,I,D),u.jsepGetBuffer=b=>f.getBuffer(b),u.jsepCreateDownloader=(b,_,I)=>f.createDownloader(b,_,I),u.jsepOnCreateSession=b=>{f.onCreateSession(b)},u.jsepOnReleaseSession=b=>{f.onReleaseSession(b)},u.jsepOnRunStart=b=>f.onRunStart(b),u.cc=(b,_)=>{f.upload(b,_)}}else if(s===\"webnn\"){[u.Gb,u.ac,u.Ob,u.jsepEnsureTensor,u.dc,u.jsepDownloadTensor]=p,u.jsepReleaseTensorId=u.Ob;let f=u.Gb;u.jsepOnRunStart=b=>f.onRunStart(b),u.jsepRegisterMLContext=(b,_)=>{f.registerMLContext(b,_)},u.jsepOnReleaseSession=b=>{f.onReleaseSession(b)},u.jsepCreateMLTensorDownloader=(b,_)=>f.createMLTensorDownloader(b,_),u.jsepRegisterMLTensor=(b,_,I)=>f.registerMLTensor(b,_,I),u.jsepCreateMLContext=b=>f.createMLContext(b),u.qc=(b,_,I,D,B)=>f.registerMLConstant(b,_,I,D,B,u.Eb)}};var v,S,T=Object.assign({},u),C=\"./this.program\",A=(s,p)=>{throw p},P=\"\";(w||y)&&(y?P=self.location.href:typeof document<\"u\"&&document.currentScript&&(P=document.currentScript.src),Qn&&(P=Qn),P=P.startsWith(\"blob:\")?\"\":P.substr(0,P.replace(/[?#].*/,\"\").lastIndexOf(\"/\")+1),y&&(S=s=>{var p=new XMLHttpRequest;return p.open(\"GET\",s,!1),p.responseType=\"arraybuffer\",p.send(null),new Uint8Array(p.response)}),v=(s,p,f)=>{var b=new XMLHttpRequest;b.open(\"GET\",s,!0),b.responseType=\"arraybuffer\",b.onload=()=>{b.status==200||b.status==0&&b.response?p(b.response):f()},b.onerror=f,b.send(null)});var O,U=console.log.bind(console),L=console.error.bind(console),j=U,K=L;if(Object.assign(u,T),T=null,g){let s=function(p){try{var f=p.data,b=f.cmd;if(b===\"load\"){let _=[];self.onmessage=I=>_.push(I),self.startWorker=()=>{postMessage({cmd:\"loaded\"});for(let I of _)s(I);self.onmessage=s};for(let I of f.handlers)u[I]&&!u[I].proxy||(u[I]=(...D)=>{postMessage({Mb:\"callHandler\",oc:I,args:D})},I==\"print\"&&(j=u[I]),I==\"printErr\"&&(K=u[I]));ue=f.wasmMemory,be(),W(f.wasmModule)}else if(b===\"run\"){Wn(f.pthread_ptr,0,0,1,0,0),Dn(f.pthread_ptr),hc(),Yo(),ee||(qi(),ee=!0);try{gc(f.start_routine,f.arg)}catch(_){if(_!=\"unwind\")throw _}}else b===\"cancel\"?Dt()&&wr(-1):f.target!==\"setimmediate\"&&(b===\"checkMailbox\"?ee&&dr():b&&(K(`worker: received unknown command ${b}`),K(f)))}catch(_){throw ji(),_}};var mg=s,W,ee=!1;K=function(...p){p=p.join(\" \"),console.error(p)},self.alert=function(...p){postMessage({Mb:\"alert\",text:p.join(\" \"),rc:Dt()})},u.instantiateWasm=(p,f)=>new Promise(b=>{W=_=>{_=new WebAssembly.Instance(_,Ho()),f(_),b()}}),self.onunhandledrejection=p=>{throw p.reason||p},self.onmessage=s}u.wasmBinary&&(O=u.wasmBinary);var ue,Z,J,Q,ne,we,Ae,$e,de,N,q,he,qe,_e=!1;function be(){var s=ue.buffer;u.HEAP8=Q=new Int8Array(s),u.HEAP16=we=new Int16Array(s),u.HEAPU8=ne=new Uint8Array(s),u.HEAPU16=Ae=new Uint16Array(s),u.HEAP32=$e=new Int32Array(s),u.HEAPU32=de=new Uint32Array(s),u.HEAPF32=N=new Float32Array(s),u.HEAPF64=qe=new Float64Array(s),u.HEAP64=q=new BigInt64Array(s),u.HEAPU64=he=new BigUint64Array(s)}if(!g){if(!((ue=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof x))throw K(\"requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag\"),Error(\"bad memory\");be()}var Ye=[],Lt=[],_n=[],Gt=0,vn=null,Ht=null;function Vo(){if(--Gt==0&&(vn!==null&&(clearInterval(vn),vn=null),Ht)){var s=Ht;Ht=null,s()}}function ct(s){throw K(s=\"Aborted(\"+s+\")\"),_e=!0,J=1,s=new WebAssembly.RuntimeError(s+\". Build with -sASSERTIONS for more info.\"),m(s),s}var $n,No=s=>s.startsWith(\"data:application/octet-stream;base64,\"),Wo=s=>s.startsWith(\"file://\");function Lo(s){if(s==$n&&O)return new Uint8Array(O);if(S)return S(s);throw\"both async and sync fetching of the wasm failed\"}function Go(s,p,f){return function(b){if(!O&&(w||y)){if(typeof fetch==\"function\"&&!Wo(b))return fetch(b,{credentials:\"same-origin\"}).then(_=>{if(!_.ok)throw`failed to load wasm binary file at '${b}'`;return _.arrayBuffer()}).catch(()=>Lo(b));if(v)return new Promise((_,I)=>{v(b,D=>_(new Uint8Array(D)),I)})}return Promise.resolve().then(()=>Lo(b))}(s).then(b=>WebAssembly.instantiate(b,p)).then(f,b=>{K(`failed to asynchronously prepare wasm: ${b}`),ct(b)})}function Ho(){return{a:{O:fc,Aa:mc,b:yc,aa:Jo,B:ri,qa:ni,Y:ii,_:ai,ra:si,oa:ui,ha:li,na:di,L:ci,Z:pi,W:mi,pa:fi,X:hi,wa:wc,F:vc,Q:$c,P:Sc,E:Ic,u:Cc,q:Ac,G:kc,A:Mc,R:Rc,ua:Uc,ka:Vc,U:Nc,ba:Wc,H:Lc,ja:Dn,ta:Gc,t:Hc,x:jc,o:Kc,l:Zc,c:zn,n:Xc,j:ep,w:tp,p:rp,g:np,s:op,m:ip,e:ap,k:sp,i:up,h:lp,d:dp,ea:cp,fa:pp,ga:mp,ca:ki,da:Ei,T:fp,f:hp,D:gp,I:bp,M:yp,y:wp,sa:_p,V:vp,v:zi,z:$p,N:xp,S:Sp,za:Tp,ya:Ip,la:Bi,ma:Mi,$:Cn,C:Ri,K:Ui,ia:Vi,J:Ni,a:ue,xa:In,va:Gi,r:kp}}}var xn={874964:(s,p,f,b,_)=>{if(u===void 0||!u.Eb)return 1;if((s=Ce(Number(s>>>0))).startsWith(\"./\")&&(s=s.substring(2)),!(s=u.Eb.get(s)))return 2;if(p=Number(p>>>0),f=Number(f>>>0),b=Number(b>>>0),p+f>s.byteLength)return 3;try{let I=s.subarray(p,p+f);switch(_){case 0:r().set(I,b>>>0);break;case 1:u.cc(b,I);break;default:return 4}return 0}catch{return 4}},875679:(s,p,f)=>{u.dc(s,r().subarray(p>>>0,p+f>>>0))},875742:()=>u.ac(),875783:s=>{u.Ob(s)},875819:()=>{u.Vb()},875850:()=>{u.Wb()},875879:()=>{u.$b()},875904:s=>u.Ub(s),875937:s=>u.Yb(s),875969:(s,p,f)=>{u.Nb(Number(s),Number(p),Number(f),!0)},876032:(s,p,f)=>{u.Nb(Number(s),Number(p),Number(f))},876089:()=>typeof wasmOffsetConverter<\"u\",876146:s=>{u.jb(\"Abs\",s,void 0)},876197:s=>{u.jb(\"Neg\",s,void 0)},876248:s=>{u.jb(\"Floor\",s,void 0)},876301:s=>{u.jb(\"Ceil\",s,void 0)},876353:s=>{u.jb(\"Reciprocal\",s,void 0)},876411:s=>{u.jb(\"Sqrt\",s,void 0)},876463:s=>{u.jb(\"Exp\",s,void 0)},876514:s=>{u.jb(\"Erf\",s,void 0)},876565:s=>{u.jb(\"Sigmoid\",s,void 0)},876620:(s,p,f)=>{u.jb(\"HardSigmoid\",s,{alpha:p,beta:f})},876699:s=>{u.jb(\"Log\",s,void 0)},876750:s=>{u.jb(\"Sin\",s,void 0)},876801:s=>{u.jb(\"Cos\",s,void 0)},876852:s=>{u.jb(\"Tan\",s,void 0)},876903:s=>{u.jb(\"Asin\",s,void 0)},876955:s=>{u.jb(\"Acos\",s,void 0)},877007:s=>{u.jb(\"Atan\",s,void 0)},877059:s=>{u.jb(\"Sinh\",s,void 0)},877111:s=>{u.jb(\"Cosh\",s,void 0)},877163:s=>{u.jb(\"Asinh\",s,void 0)},877216:s=>{u.jb(\"Acosh\",s,void 0)},877269:s=>{u.jb(\"Atanh\",s,void 0)},877322:s=>{u.jb(\"Tanh\",s,void 0)},877374:s=>{u.jb(\"Not\",s,void 0)},877425:(s,p,f)=>{u.jb(\"Clip\",s,{min:p,max:f})},877494:s=>{u.jb(\"Clip\",s,void 0)},877546:(s,p)=>{u.jb(\"Elu\",s,{alpha:p})},877604:s=>{u.jb(\"Gelu\",s,void 0)},877656:s=>{u.jb(\"Relu\",s,void 0)},877708:(s,p)=>{u.jb(\"LeakyRelu\",s,{alpha:p})},877772:(s,p)=>{u.jb(\"ThresholdedRelu\",s,{alpha:p})},877842:(s,p)=>{u.jb(\"Cast\",s,{to:p})},877900:s=>{u.jb(\"Add\",s,void 0)},877951:s=>{u.jb(\"Sub\",s,void 0)},878002:s=>{u.jb(\"Mul\",s,void 0)},878053:s=>{u.jb(\"Div\",s,void 0)},878104:s=>{u.jb(\"Pow\",s,void 0)},878155:s=>{u.jb(\"Equal\",s,void 0)},878208:s=>{u.jb(\"Greater\",s,void 0)},878263:s=>{u.jb(\"GreaterOrEqual\",s,void 0)},878325:s=>{u.jb(\"Less\",s,void 0)},878377:s=>{u.jb(\"LessOrEqual\",s,void 0)},878436:(s,p,f,b,_)=>{u.jb(\"ReduceMean\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},878611:(s,p,f,b,_)=>{u.jb(\"ReduceMax\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},878785:(s,p,f,b,_)=>{u.jb(\"ReduceMin\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},878959:(s,p,f,b,_)=>{u.jb(\"ReduceProd\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},879134:(s,p,f,b,_)=>{u.jb(\"ReduceSum\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},879308:(s,p,f,b,_)=>{u.jb(\"ReduceL1\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},879481:(s,p,f,b,_)=>{u.jb(\"ReduceL2\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},879654:(s,p,f,b,_)=>{u.jb(\"ReduceLogSum\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},879831:(s,p,f,b,_)=>{u.jb(\"ReduceSumSquare\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},880011:(s,p,f,b,_)=>{u.jb(\"ReduceLogSumExp\",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},880191:s=>{u.jb(\"Where\",s,void 0)},880244:(s,p,f)=>{u.jb(\"Transpose\",s,{perm:p?Array.from(i().subarray(Number(p)>>>0,Number(f)>>>0)):[]})},880368:(s,p,f,b)=>{u.jb(\"DepthToSpace\",s,{blocksize:p,mode:Ce(f),format:b?\"NHWC\":\"NCHW\"})},880501:(s,p,f,b)=>{u.jb(\"DepthToSpace\",s,{blocksize:p,mode:Ce(f),format:b?\"NHWC\":\"NCHW\"})},880634:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z,le)=>{u.jb(\"ConvTranspose\",s,{format:G?\"NHWC\":\"NCHW\",autoPad:p,dilations:[f],group:b,kernelShape:[_],pads:[I,D],strides:[B],wIsConst:()=>!!t()[H>>>0],outputPadding:X?Array.from(i().subarray(Number(X)>>>0,Number(ce)>>>0)):[],outputShape:ge?Array.from(i().subarray(Number(ge)>>>0,Number(z)>>>0)):[],activation:Ce(le)})},881067:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z)=>{u.jb(\"ConvTranspose\",s,{format:B?\"NHWC\":\"NCHW\",autoPad:p,dilations:Array.from(i().subarray(Number(f)>>>0,2+(Number(f)>>>0)>>>0)),group:b,kernelShape:Array.from(i().subarray(Number(_)>>>0,2+(Number(_)>>>0)>>>0)),pads:Array.from(i().subarray(Number(I)>>>0,4+(Number(I)>>>0)>>>0)),strides:Array.from(i().subarray(Number(D)>>>0,2+(Number(D)>>>0)>>>0)),wIsConst:()=>!!t()[G>>>0],outputPadding:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],outputShape:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[],activation:Ce(z)})},881728:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z,le)=>{u.jb(\"ConvTranspose\",s,{format:G?\"NHWC\":\"NCHW\",autoPad:p,dilations:[f],group:b,kernelShape:[_],pads:[I,D],strides:[B],wIsConst:()=>!!t()[H>>>0],outputPadding:X?Array.from(i().subarray(Number(X)>>>0,Number(ce)>>>0)):[],outputShape:ge?Array.from(i().subarray(Number(ge)>>>0,Number(z)>>>0)):[],activation:Ce(le)})},882161:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z)=>{u.jb(\"ConvTranspose\",s,{format:B?\"NHWC\":\"NCHW\",autoPad:p,dilations:Array.from(i().subarray(Number(f)>>>0,2+(Number(f)>>>0)>>>0)),group:b,kernelShape:Array.from(i().subarray(Number(_)>>>0,2+(Number(_)>>>0)>>>0)),pads:Array.from(i().subarray(Number(I)>>>0,4+(Number(I)>>>0)>>>0)),strides:Array.from(i().subarray(Number(D)>>>0,2+(Number(D)>>>0)>>>0)),wIsConst:()=>!!t()[G>>>0],outputPadding:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],outputShape:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[],activation:Ce(z)})},882822:(s,p)=>{u.jb(\"GlobalAveragePool\",s,{format:p?\"NHWC\":\"NCHW\"})},882913:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z)=>{u.jb(\"AveragePool\",s,{format:z?\"NHWC\":\"NCHW\",auto_pad:p,ceil_mode:f,count_include_pad:b,storage_order:_,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(D)>>>0)):[],kernel_shape:B?Array.from(i().subarray(Number(B)>>>0,Number(G)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},883392:(s,p)=>{u.jb(\"GlobalAveragePool\",s,{format:p?\"NHWC\":\"NCHW\"})},883483:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z)=>{u.jb(\"AveragePool\",s,{format:z?\"NHWC\":\"NCHW\",auto_pad:p,ceil_mode:f,count_include_pad:b,storage_order:_,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(D)>>>0)):[],kernel_shape:B?Array.from(i().subarray(Number(B)>>>0,Number(G)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},883962:(s,p)=>{u.jb(\"GlobalMaxPool\",s,{format:p?\"NHWC\":\"NCHW\"})},884049:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z)=>{u.jb(\"MaxPool\",s,{format:z?\"NHWC\":\"NCHW\",auto_pad:p,ceil_mode:f,count_include_pad:b,storage_order:_,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(D)>>>0)):[],kernel_shape:B?Array.from(i().subarray(Number(B)>>>0,Number(G)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},884524:(s,p)=>{u.jb(\"GlobalMaxPool\",s,{format:p?\"NHWC\":\"NCHW\"})},884611:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z)=>{u.jb(\"MaxPool\",s,{format:z?\"NHWC\":\"NCHW\",auto_pad:p,ceil_mode:f,count_include_pad:b,storage_order:_,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(D)>>>0)):[],kernel_shape:B?Array.from(i().subarray(Number(B)>>>0,Number(G)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},885086:(s,p,f,b,_)=>{u.jb(\"Gemm\",s,{alpha:p,beta:f,transA:b,transB:_})},885190:s=>{u.jb(\"MatMul\",s,void 0)},885244:(s,p,f,b)=>{u.jb(\"ArgMax\",s,{keepDims:!!p,selectLastIndex:!!f,axis:b})},885352:(s,p,f,b)=>{u.jb(\"ArgMin\",s,{keepDims:!!p,selectLastIndex:!!f,axis:b})},885460:(s,p)=>{u.jb(\"Softmax\",s,{axis:p})},885523:(s,p)=>{u.jb(\"Concat\",s,{axis:p})},885583:(s,p,f,b,_)=>{u.jb(\"Split\",s,{axis:p,numOutputs:f,splitSizes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},885739:s=>{u.jb(\"Expand\",s,void 0)},885793:(s,p)=>{u.jb(\"Gather\",s,{axis:Number(p)})},885864:(s,p)=>{u.jb(\"GatherElements\",s,{axis:Number(p)})},885943:(s,p,f,b,_,I,D,B,G,H,X)=>{u.jb(\"Resize\",s,{antialias:p,axes:f?Array.from(i().subarray(Number(f)>>>0,Number(b)>>>0)):[],coordinateTransformMode:Ce(_),cubicCoeffA:I,excludeOutside:D,extrapolationValue:B,keepAspectRatioPolicy:Ce(G),mode:Ce(H),nearestMode:Ce(X)})},886305:(s,p,f,b,_,I,D)=>{u.jb(\"Slice\",s,{starts:p?Array.from(i().subarray(Number(p)>>>0,Number(f)>>>0)):[],ends:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[],axes:I?Array.from(i().subarray(Number(I)>>>0,Number(D)>>>0)):[]})},886569:s=>{u.jb(\"Tile\",s,void 0)},886621:(s,p,f)=>{u.jb(\"InstanceNormalization\",s,{epsilon:p,format:f?\"NHWC\":\"NCHW\"})},886735:(s,p,f)=>{u.jb(\"InstanceNormalization\",s,{epsilon:p,format:f?\"NHWC\":\"NCHW\"})},886849:s=>{u.jb(\"Range\",s,void 0)},886902:(s,p)=>{u.jb(\"Einsum\",s,{equation:Ce(p)})},886983:(s,p,f,b,_)=>{u.jb(\"Pad\",s,{mode:p,value:f,pads:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},887126:(s,p,f,b,_,I)=>{u.jb(\"BatchNormalization\",s,{epsilon:p,momentum:f,spatial:!!_,trainingMode:!!b,format:I?\"NHWC\":\"NCHW\"})},887295:(s,p,f,b,_,I)=>{u.jb(\"BatchNormalization\",s,{epsilon:p,momentum:f,spatial:!!_,trainingMode:!!b,format:I?\"NHWC\":\"NCHW\"})},887464:(s,p,f)=>{u.jb(\"CumSum\",s,{exclusive:Number(p),reverse:Number(f)})},887561:(s,p,f)=>{u.jb(\"DequantizeLinear\",s,{axis:p,blockSize:f})},887651:(s,p,f,b,_)=>{u.jb(\"GridSample\",s,{align_corners:p,mode:Ce(f),padding_mode:Ce(b),format:_?\"NHWC\":\"NCHW\"})},887821:(s,p,f,b,_)=>{u.jb(\"GridSample\",s,{align_corners:p,mode:Ce(f),padding_mode:Ce(b),format:_?\"NHWC\":\"NCHW\"})},887991:(s,p,f,b,_,I,D,B,G)=>{u.jb(\"Attention\",s,{numHeads:p,isUnidirectional:f,maskFilterValue:b,scale:_,doRotary:I,qkvHiddenSizes:D?Array.from(i().subarray(Number(B)>>>0,Number(B)+D>>>0)):[],pastPresentShareBuffer:!!G})},888263:s=>{u.jb(\"BiasAdd\",s,void 0)},888318:s=>{u.jb(\"BiasSplitGelu\",s,void 0)},888379:s=>{u.jb(\"FastGelu\",s,void 0)},888435:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z,le,Se)=>{u.jb(\"Conv\",s,{format:ce?\"NHWC\":\"NCHW\",auto_pad:p,dilations:f?Array.from(i().subarray(Number(f)>>>0,Number(b)>>>0)):[],group:_,kernel_shape:I?Array.from(i().subarray(Number(I)>>>0,Number(D)>>>0)):[],pads:B?Array.from(i().subarray(Number(B)>>>0,Number(G)>>>0)):[],strides:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],w_is_const:()=>!!t()[Number(ge)>>>0],activation:Ce(z),activation_params:le?Array.from(l().subarray(Number(le)>>>0,Number(Se)>>>0)):[]})},889019:s=>{u.jb(\"Gelu\",s,void 0)},889071:(s,p,f,b,_,I,D,B,G)=>{u.jb(\"GroupQueryAttention\",s,{numHeads:p,kvNumHeads:f,scale:b,softcap:_,doRotary:I,rotaryInterleaved:D,smoothSoftmax:B,localWindowSize:G})},889288:(s,p,f,b)=>{u.jb(\"LayerNormalization\",s,{axis:p,epsilon:f,simplified:!!b})},889399:(s,p,f,b)=>{u.jb(\"LayerNormalization\",s,{axis:p,epsilon:f,simplified:!!b})},889510:(s,p,f,b,_,I)=>{u.jb(\"MatMulNBits\",s,{k:p,n:f,accuracyLevel:b,bits:_,blockSize:I})},889637:(s,p,f,b,_,I)=>{u.jb(\"MultiHeadAttention\",s,{numHeads:p,isUnidirectional:f,maskFilterValue:b,scale:_,doRotary:I})},889796:(s,p)=>{u.jb(\"QuickGelu\",s,{alpha:p})},889860:(s,p,f,b,_)=>{u.jb(\"RotaryEmbedding\",s,{interleaved:!!p,numHeads:f,rotaryEmbeddingDim:b,scale:_})},889999:(s,p,f)=>{u.jb(\"SkipLayerNormalization\",s,{epsilon:p,simplified:!!f})},890101:(s,p,f)=>{u.jb(\"SkipLayerNormalization\",s,{epsilon:p,simplified:!!f})},890203:(s,p,f,b)=>{u.jb(\"GatherBlockQuantized\",s,{gatherAxis:p,quantizeAxis:f,blockSize:b})},890324:s=>{u.Zb(s)},890358:(s,p)=>u.bc(Number(s),Number(p),u.Fb.fc,u.Fb.errors)};function mc(s,p,f){return Si(async()=>{await u.Xb(Number(s),Number(p),Number(f))})}function fc(){return typeof wasmOffsetConverter<\"u\"}function Sn(s){this.name=\"ExitStatus\",this.message=`Program terminated with exit(${s})`,this.status=s}var Tn=s=>{s.terminate(),s.onmessage=()=>{}},Fo=s=>{pt.length==0&&(Xo(),Zo(pt[0]));var p=pt.pop();if(!p)return 6;_t.push(p),Ze[s.Ab]=p,p.Ab=s.Ab;var f={cmd:\"run\",start_routine:s.hc,arg:s.Qb,pthread_ptr:s.Ab};return p.postMessage(f,s.mc),0},wt=0,xe=(s,p,...f)=>{for(var b=2*f.length,_=Hn(),I=Gn(8*b),D=I>>>3,B=0;B>>0]=G)}return s=Ki(s,0,b,I,p),_r(_),s};function In(s){if(g)return xe(0,1,s);if(J=s,!(0{if(J=s,g)throw qo(s),\"unwind\";In(s)},pt=[],_t=[],jo=[],Ze={},Ko=s=>{var p=s.Ab;delete Ze[p],pt.push(s),_t.splice(_t.indexOf(s),1),s.Ab=0,Ln(p)};function Yo(){jo.forEach(s=>s())}var Zo=s=>new Promise(p=>{s.onmessage=_=>{var I=(_=_.data).cmd;if(_.targetThread&&_.targetThread!=Dt()){var D=Ze[_.targetThread];D?D.postMessage(_,_.transferList):K(`Internal error! Worker sent a message \"${I}\" to target pthread ${_.targetThread}, but that thread no longer exists!`)}else I===\"checkMailbox\"?dr():I===\"spawnThread\"?Fo(_):I===\"cleanupThread\"?Ko(Ze[_.thread]):I===\"killThread\"?(_=_.thread,I=Ze[_],delete Ze[_],Tn(I),Ln(_),_t.splice(_t.indexOf(I),1),I.Ab=0):I===\"cancelThread\"?Ze[_.thread].postMessage({cmd:\"cancel\"}):I===\"loaded\"?(s.loaded=!0,p(s)):I===\"alert\"?alert(`Thread ${_.threadId}: ${_.text}`):_.target===\"setimmediate\"?s.postMessage(_):I===\"callHandler\"?u[_.handler](..._.args):I&&K(`worker sent an unknown command ${I}`)},s.onerror=_=>{throw K(`worker sent an error! ${_.filename}:${_.lineno}: ${_.message}`),_};var f,b=[];for(f of[])u.hasOwnProperty(f)&&b.push(f);s.postMessage({cmd:\"load\",handlers:b,wasmMemory:ue,wasmModule:Z})});function Xo(){var s=new Worker(new URL(import.meta.url),{type:\"module\",workerData:\"em-pthread\",name:\"em-pthread\"});pt.push(s)}var lr=s=>{for(;0{var s=Dt(),p=a()[s+52>>>2>>>0];s=a()[s+56>>>2>>>0],Zi(p,p-s),_r(p)},gc=(s,p)=>{wt=0,s=Xi(s,p),0>>=0);throw p>>>=0,f>>>=0,a()[b.Jb+16>>>2>>>0]=0,a()[b.Jb+4>>>2>>>0]=p,a()[b.Jb+8>>>2>>>0]=f,s}function Qo(s,p,f,b){return g?xe(2,1,s,p,f,b):Jo(s,p,f,b)}function Jo(s,p,f,b){if(s>>>=0,p>>>=0,f>>>=0,b>>>=0,x===void 0)return K(\"Current environment does not support SharedArrayBuffer, pthreads are not available!\"),6;var _=[];return g&&_.length===0?Qo(s,p,f,b):(s={hc:f,Ab:s,Qb:b,mc:_},g?(s.Mb=\"spawnThread\",postMessage(s,_),0):Fo(s))}var ei=typeof TextDecoder<\"u\"?new TextDecoder(\"utf8\"):void 0,ti=(s,p,f)=>{var b=(p>>>=0)+f;for(f=p;s[f]&&!(f>=b);)++f;if(16(_=(240&_)==224?(15&_)<<12|I<<6|D:(7&_)<<18|I<<12|D<<6|63&s[p++])?b+=String.fromCharCode(_):(_-=65536,b+=String.fromCharCode(55296|_>>10,56320|1023&_))}}else b+=String.fromCharCode(_)}return b},Ce=(s,p)=>(s>>>=0)?ti(r(),s,p):\"\";function ri(s,p,f){return g?xe(3,1,s,p,f):0}function ni(s,p){if(g)return xe(4,1,s,p)}var An=s=>{for(var p=0,f=0;f=b?p++:2047>=b?p+=2:55296<=b&&57343>=b?(p+=4,++f):p+=3}return p},oi=(s,p,f,b)=>{if(!(0>>=0;b=f+b-1;for(var I=0;I=D&&(D=65536+((1023&D)<<10)|1023&s.charCodeAt(++I)),127>=D){if(f>=b)break;p[f++>>>0]=D}else{if(2047>=D){if(f+1>=b)break;p[f++>>>0]=192|D>>6}else{if(65535>=D){if(f+2>=b)break;p[f++>>>0]=224|D>>12}else{if(f+3>=b)break;p[f++>>>0]=240|D>>18,p[f++>>>0]=128|D>>12&63}p[f++>>>0]=128|D>>6&63}p[f++>>>0]=128|63&D}}return p[f>>>0]=0,f-_},Pt=(s,p,f)=>oi(s,r(),p,f);function ii(s,p){if(g)return xe(5,1,s,p)}function ai(s,p,f){if(g)return xe(6,1,s,p,f)}function si(s,p,f){return g?xe(7,1,s,p,f):0}function ui(s,p){if(g)return xe(8,1,s,p)}function li(s,p,f){if(g)return xe(9,1,s,p,f)}function di(s,p,f,b){if(g)return xe(10,1,s,p,f,b)}function ci(s,p,f,b){if(g)return xe(11,1,s,p,f,b)}function pi(s,p,f,b){if(g)return xe(12,1,s,p,f,b)}function mi(s){if(g)return xe(13,1,s)}function fi(s,p){if(g)return xe(14,1,s,p)}function hi(s,p,f){if(g)return xe(15,1,s,p,f)}var gi,mt,wc=()=>{ct(\"\")},Xe=s=>{for(var p=\"\";r()[s>>>0];)p+=gi[r()[s++>>>0]];return p},kn={},En={},_c={};function at(s,p,f={}){if(!(\"argPackAdvance\"in p))throw new TypeError(\"registerType registeredInstance requires argPackAdvance\");return function(b,_,I={}){var D=_.name;if(!b)throw new mt(`type \"${D}\" must have a positive integer typeid pointer`);if(En.hasOwnProperty(b)){if(I.Sb)return;throw new mt(`Cannot register type '${D}' twice`)}En[b]=_,delete _c[b],kn.hasOwnProperty(b)&&(_=kn[b],delete kn[b],_.forEach(B=>B()))}(s,p,f)}var bi=(s,p,f)=>{switch(p){case 1:return f?b=>t()[b>>>0]:b=>r()[b>>>0];case 2:return f?b=>n()[b>>>1>>>0]:b=>o()[b>>>1>>>0];case 4:return f?b=>i()[b>>>2>>>0]:b=>a()[b>>>2>>>0];case 8:return f?b=>q[b>>>3]:b=>he[b>>>3];default:throw new TypeError(`invalid integer width (${p}): ${s}`)}};function vc(s,p,f){f>>>=0,at(s>>>=0,{name:p=Xe(p>>>0),fromWireType:b=>b,toWireType:function(b,_){if(typeof _!=\"bigint\"&&typeof _!=\"number\")throw _=_===null?\"null\":(b=typeof _)==\"object\"||b===\"array\"||b===\"function\"?_.toString():\"\"+_,new TypeError(`Cannot convert \"${_}\" to ${this.name}`);return typeof _==\"number\"&&(_=BigInt(_)),_},argPackAdvance:ft,readValueFromPointer:bi(p,f,p.indexOf(\"u\")==-1),Db:null})}var ft=8;function $c(s,p,f,b){at(s>>>=0,{name:p=Xe(p>>>0),fromWireType:function(_){return!!_},toWireType:function(_,I){return I?f:b},argPackAdvance:ft,readValueFromPointer:function(_){return this.fromWireType(r()[_>>>0])},Db:null})}var Pn=[],st=[];function zn(s){9<(s>>>=0)&&--st[s+1]==0&&(st[s]=void 0,Pn.push(s))}var Le=s=>{if(!s)throw new mt(\"Cannot use deleted val. handle = \"+s);return st[s]},Ge=s=>{switch(s){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let p=Pn.pop()||st.length;return st[p]=s,st[p+1]=1,p}};function On(s){return this.fromWireType(a()[s>>>2>>>0])}var xc={name:\"emscripten::val\",fromWireType:s=>{var p=Le(s);return zn(s),p},toWireType:(s,p)=>Ge(p),argPackAdvance:ft,readValueFromPointer:On,Db:null};function Sc(s){return at(s>>>0,xc)}var Tc=(s,p)=>{switch(p){case 4:return function(f){return this.fromWireType(l()[f>>>2>>>0])};case 8:return function(f){return this.fromWireType(d()[f>>>3>>>0])};default:throw new TypeError(`invalid float width (${p}): ${s}`)}};function Ic(s,p,f){f>>>=0,at(s>>>=0,{name:p=Xe(p>>>0),fromWireType:b=>b,toWireType:(b,_)=>_,argPackAdvance:ft,readValueFromPointer:Tc(p,f),Db:null})}function Cc(s,p,f,b,_){if(s>>>=0,f>>>=0,p=Xe(p>>>0),_===-1&&(_=4294967295),_=B=>B,b===0){var I=32-8*f;_=B=>B<>>I}var D=p.includes(\"unsigned\")?function(B,G){return G>>>0}:function(B,G){return G};at(s,{name:p,fromWireType:_,toWireType:D,argPackAdvance:ft,readValueFromPointer:bi(p,f,b!==0),Db:null})}function Ac(s,p,f){function b(I){var D=a()[I>>>2>>>0];return I=a()[I+4>>>2>>>0],new _(t().buffer,I,D)}var _=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][p];at(s>>>=0,{name:f=Xe(f>>>0),fromWireType:b,argPackAdvance:ft,readValueFromPointer:b},{Sb:!0})}function kc(s,p){s>>>=0;var f=(p=Xe(p>>>0))===\"std::string\";at(s,{name:p,fromWireType:function(b){var _=a()[b>>>2>>>0],I=b+4;if(f)for(var D=I,B=0;B<=_;++B){var G=I+B;if(B==_||r()[G>>>0]==0){if(D=Ce(D,G-D),H===void 0)var H=D;else H+=String.fromCharCode(0),H+=D;D=G+1}}else{for(H=Array(_),B=0;B<_;++B)H[B]=String.fromCharCode(r()[I+B>>>0]);H=H.join(\"\")}return Je(b),H},toWireType:function(b,_){_ instanceof ArrayBuffer&&(_=new Uint8Array(_));var I=typeof _==\"string\";if(!(I||_ instanceof Uint8Array||_ instanceof Uint8ClampedArray||_ instanceof Int8Array))throw new mt(\"Cannot pass non-string to std::string\");var D=f&&I?An(_):_.length,B=yr(4+D+1),G=B+4;if(a()[B>>>2>>>0]=D,f&&I)Pt(_,G,D+1);else if(I)for(I=0;I>>0]=H}else for(I=0;I>>0]=_[I];return b!==null&&b.push(Je,B),B},argPackAdvance:ft,readValueFromPointer:On,Db(b){Je(b)}})}var yi=typeof TextDecoder<\"u\"?new TextDecoder(\"utf-16le\"):void 0,Ec=(s,p)=>{for(var f=s>>1,b=f+p/2;!(f>=b)&&o()[f>>>0];)++f;if(32<(f<<=1)-s&&yi)return yi.decode(r().slice(s,f));for(f=\"\",b=0;!(b>=p/2);++b){var _=n()[s+2*b>>>1>>>0];if(_==0)break;f+=String.fromCharCode(_)}return f},Pc=(s,p,f)=>{if(f??=2147483647,2>f)return 0;var b=p;f=(f-=2)<2*s.length?f/2:s.length;for(var _=0;_>>1>>>0]=I,p+=2}return n()[p>>>1>>>0]=0,p-b},zc=s=>2*s.length,Oc=(s,p)=>{for(var f=0,b=\"\";!(f>=p/4);){var _=i()[s+4*f>>>2>>>0];if(_==0)break;++f,65536<=_?(_-=65536,b+=String.fromCharCode(55296|_>>10,56320|1023&_)):b+=String.fromCharCode(_)}return b},Dc=(s,p,f)=>{if(p>>>=0,f??=2147483647,4>f)return 0;var b=p;f=b+f-4;for(var _=0;_=I&&(I=65536+((1023&I)<<10)|1023&s.charCodeAt(++_)),i()[p>>>2>>>0]=I,(p+=4)+4>f)break}return i()[p>>>2>>>0]=0,p-b},Bc=s=>{for(var p=0,f=0;f=b&&++f,p+=4}return p};function Mc(s,p,f){if(s>>>=0,p>>>=0,f=Xe(f>>>=0),p===2)var b=Ec,_=Pc,I=zc,D=B=>o()[B>>>1>>>0];else p===4&&(b=Oc,_=Dc,I=Bc,D=B=>a()[B>>>2>>>0]);at(s,{name:f,fromWireType:B=>{for(var G,H=a()[B>>>2>>>0],X=B+4,ce=0;ce<=H;++ce){var ge=B+4+ce*p;ce!=H&&D(ge)!=0||(X=b(X,ge-X),G===void 0?G=X:(G+=String.fromCharCode(0),G+=X),X=ge+p)}return Je(B),G},toWireType:(B,G)=>{if(typeof G!=\"string\")throw new mt(`Cannot pass non-string to C++ string type ${f}`);var H=I(G),X=yr(4+H+p);return a()[X>>>2>>>0]=H/p,_(G,X+4,H+p),B!==null&&B.push(Je,X),X},argPackAdvance:ft,readValueFromPointer:On,Db(B){Je(B)}})}function Rc(s,p){at(s>>>=0,{Tb:!0,name:p=Xe(p>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Uc=()=>1;function Vc(s){Wn(s>>>0,!y,1,!w,131072,!1),Yo()}var wi=s=>{if(!_e)try{if(s(),!(0>>=0,typeof Atomics.nc==\"function\"&&(Atomics.nc(i(),s>>>2,s).value.then(dr),s+=128,Atomics.store(i(),s>>>2,1))}var dr=()=>{var s=Dt();s&&(Dn(s),wi(Yi))};function Nc(s,p){(s>>>=0)==p>>>0?setTimeout(dr):g?postMessage({targetThread:s,cmd:\"checkMailbox\"}):(s=Ze[s])&&s.postMessage({cmd:\"checkMailbox\"})}var Bn=[];function Wc(s,p,f,b,_){for(p>>>=0,b/=2,Bn.length=b,f=_>>>0>>>3,_=0;_>>0];return(p?xn[p]:Ep[s])(...Bn)}function Lc(s){s>>>=0,g?postMessage({cmd:\"cleanupThread\",thread:s}):Ko(Ze[s])}function Gc(s){}var Mn=(s,p)=>{var f=En[s];if(f===void 0)throw s=Fi(s),f=Xe(s),Je(s),new mt(`${p} has unknown type ${f}`);return f},_i=(s,p,f)=>{var b=[];return s=s.toWireType(b,f),b.length&&(a()[p>>>2>>>0]=Ge(b)),s};function Hc(s,p,f){return p>>>=0,f>>>=0,s=Le(s>>>0),p=Mn(p,\"emval::as\"),_i(p,f,s)}var cr=s=>{try{s()}catch(p){ct(p)}},ht=0,Qe=null,vi=0,pr=[],$i={},xi={},Fc=0,Rn=null,qc=[];function Si(s){return function(p){if(!_e){if(ht===0){var f=!1,b=!1;p((_=0)=>{if(!_e&&(vi=_,f=!0,b)){ht=2,cr(()=>ea(Qe)),typeof Browser<\"u\"&&Browser.Kb.Rb&&Browser.Kb.resume(),_=!1;try{var I=function(){var G=i()[Qe+8>>>2>>>0];return G=Y[xi[G]],--wt,G()}()}catch(G){I=G,_=!0}var D=!1;if(!Qe){var B=Rn;B&&(Rn=null,(_?B.reject:B.resolve)(I),D=!0)}if(_&&!D)throw I}}),b=!0,f||(ht=1,Qe=function(){var _=yr(65548),I=_+12;a()[_>>>2>>>0]=I,a()[_+4>>>2>>>0]=I+65536,I=pr[0];var D=$i[I];return D===void 0&&(D=Fc++,$i[I]=D,xi[D]=I),I=D,i()[_+8>>>2>>>0]=I,_}(),typeof Browser<\"u\"&&Browser.Kb.Rb&&Browser.Kb.pause(),cr(()=>Qi(Qe)))}else ht===2?(ht=0,cr(ta),Je(Qe),Qe=null,qc.forEach(wi)):ct(`invalid state: ${ht}`);return vi}}(p=>{s().then(p)})}function jc(s){return s>>>=0,Si(()=>(s=Le(s)).then(Ge))}var mr=[];function Kc(s,p,f,b){return f>>>=0,b>>>=0,(s=mr[s>>>0])(null,p=Le(p>>>0),f,b)}var Yc={},fr=s=>{var p=Yc[s];return p===void 0?Xe(s):p};function Zc(s,p,f,b,_){return f>>>=0,b>>>=0,_>>>=0,(s=mr[s>>>0])(p=Le(p>>>0),p[f=fr(f)],b,_)}var Ti=()=>typeof globalThis==\"object\"?globalThis:Function(\"return this\")();function Xc(s){return(s>>>=0)==0?Ge(Ti()):(s=fr(s),Ge(Ti()[s]))}var Qc=s=>{var p=mr.length;return mr.push(s),p},Jc=(s,p)=>{for(var f=Array(s),b=0;b>>2>>>0],\"parameter \"+b);return f},Ii=(s,p)=>Object.defineProperty(p,\"name\",{value:s});function ep(s,p,f){var b=(p=Jc(s,p>>>0)).shift();s--;var _=`return function (obj, func, destructorsRef, args) {\n`,I=0,D=[];f===0&&D.push(\"obj\");for(var B=[\"retType\"],G=[b],H=0;HX.name).join(\", \")}) => ${b.name}>`,Qc(Ii(f,s))}function tp(s){return s=fr(s>>>0),Ge(u[s])}function rp(s,p){return p>>>=0,s=Le(s>>>0),p=Le(p),Ge(s[p])}function np(s){9<(s>>>=0)&&(st[s+1]+=1)}function op(){return Ge([])}function ip(s){s=Le(s>>>0);for(var p=Array(s.length),f=0;f>>0))}function sp(){return Ge({})}function up(s){for(var p=Le(s>>>=0);p.length;){var f=p.pop();p.pop()(f)}zn(s)}function lp(s,p,f){p>>>=0,f>>>=0,s=Le(s>>>0),p=Le(p),f=Le(f),s[p]=f}function dp(s,p){return p>>>=0,s=(s=Mn(s>>>0,\"_emval_take_value\")).readValueFromPointer(p),Ge(s)}function cp(s,p){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),i()[p>>>2>>>0]=s.getUTCSeconds(),i()[p+4>>>2>>>0]=s.getUTCMinutes(),i()[p+8>>>2>>>0]=s.getUTCHours(),i()[p+12>>>2>>>0]=s.getUTCDate(),i()[p+16>>>2>>>0]=s.getUTCMonth(),i()[p+20>>>2>>>0]=s.getUTCFullYear()-1900,i()[p+24>>>2>>>0]=s.getUTCDay(),s=(s.getTime()-Date.UTC(s.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[p+28>>>2>>>0]=s}var zt=s=>s%4==0&&(s%100!=0||s%400==0),Ci=[0,31,60,91,121,152,182,213,244,274,305,335],Ai=[0,31,59,90,120,151,181,212,243,273,304,334];function pp(s,p){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),i()[p>>>2>>>0]=s.getSeconds(),i()[p+4>>>2>>>0]=s.getMinutes(),i()[p+8>>>2>>>0]=s.getHours(),i()[p+12>>>2>>>0]=s.getDate(),i()[p+16>>>2>>>0]=s.getMonth(),i()[p+20>>>2>>>0]=s.getFullYear()-1900,i()[p+24>>>2>>>0]=s.getDay();var f=(zt(s.getFullYear())?Ci:Ai)[s.getMonth()]+s.getDate()-1|0;i()[p+28>>>2>>>0]=f,i()[p+36>>>2>>>0]=-60*s.getTimezoneOffset(),f=new Date(s.getFullYear(),6,1).getTimezoneOffset();var b=new Date(s.getFullYear(),0,1).getTimezoneOffset();s=0|(f!=b&&s.getTimezoneOffset()==Math.min(b,f)),i()[p+32>>>2>>>0]=s}function mp(s){s>>>=0;var p=new Date(i()[s+20>>>2>>>0]+1900,i()[s+16>>>2>>>0],i()[s+12>>>2>>>0],i()[s+8>>>2>>>0],i()[s+4>>>2>>>0],i()[s>>>2>>>0],0),f=i()[s+32>>>2>>>0],b=p.getTimezoneOffset(),_=new Date(p.getFullYear(),6,1).getTimezoneOffset(),I=new Date(p.getFullYear(),0,1).getTimezoneOffset(),D=Math.min(I,_);return 0>f?i()[s+32>>>2>>>0]=+(_!=I&&D==b):0>>2>>>0]=p.getDay(),f=(zt(p.getFullYear())?Ci:Ai)[p.getMonth()]+p.getDate()-1|0,i()[s+28>>>2>>>0]=f,i()[s>>>2>>>0]=p.getSeconds(),i()[s+4>>>2>>>0]=p.getMinutes(),i()[s+8>>>2>>>0]=p.getHours(),i()[s+12>>>2>>>0]=p.getDate(),i()[s+16>>>2>>>0]=p.getMonth(),i()[s+20>>>2>>>0]=p.getYear(),s=p.getTime(),BigInt(isNaN(s)?-1:s/1e3)}function ki(s,p,f,b,_,I,D){return g?xe(16,1,s,p,f,b,_,I,D):-52}function Ei(s,p,f,b,_,I){if(g)return xe(17,1,s,p,f,b,_,I)}function fp(s,p,f,b){s>>>=0,p>>>=0,f>>>=0,b>>>=0;var _=new Date().getFullYear(),I=new Date(_,0,1),D=new Date(_,6,1);_=I.getTimezoneOffset();var B=D.getTimezoneOffset(),G=Math.max(_,B);a()[s>>>2>>>0]=60*G,i()[p>>>2>>>0]=+(_!=B),I=(s=H=>H.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:\"short\"}).split(\" \")[1])(I),D=s(D),B<_?(Pt(I,f,17),Pt(D,b,17)):(Pt(I,b,17),Pt(D,f,17))}var Un=[],Pi=(s,p)=>{Un.length=0;for(var f;f=r()[s++>>>0];){var b=f!=105;p+=(b&=f!=112)&&p%8?4:0,Un.push(f==112?a()[p>>>2>>>0]:f==106?q[p>>>3]:f==105?i()[p>>>2>>>0]:d()[p>>>3>>>0]),p+=b?8:4}return Un};function hp(s,p,f){return s>>>=0,p=Pi(p>>>0,f>>>0),xn[s](...p)}function gp(s,p,f){return s>>>=0,p=Pi(p>>>0,f>>>0),xn[s](...p)}var bp=()=>{},yp=()=>Date.now();function wp(s,p){return K(Ce(s>>>0,p>>>0))}var zi,_p=()=>{throw wt+=1,\"unwind\"};function vp(){return 4294901760}zi=()=>performance.timeOrigin+performance.now();var $p=()=>navigator.hardwareConcurrency;function xp(){return ct(\"Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER\"),0}function Sp(s){s>>>=0;var p=r().length;if(s<=p||4294901760=f;f*=2){var b=p*(1+.2/f);b=Math.min(b,s+100663296);var _=Math;b=Math.max(s,b);e:{_=(_.min.call(_,4294901760,b+(65536-b%65536)%65536)-ue.buffer.byteLength+65535)/65536;try{ue.grow(_),be();var I=1;break e}catch{}I=void 0}if(I)return!0}return!1}var hr=()=>(ct(\"Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER\"),0),Ot={},Oi=s=>{s.forEach(p=>{var f=hr();f&&(Ot[f]=p)})};function Tp(){var s=Error().stack.toString().split(`\n`);return s[0]==\"Error\"&&s.shift(),Oi(s),Ot.Pb=hr(),Ot.ec=s,Ot.Pb}function Ip(s,p,f){if(s>>>=0,p>>>=0,Ot.Pb==s)var b=Ot.ec;else(b=Error().stack.toString().split(`\n`))[0]==\"Error\"&&b.shift(),Oi(b);for(var _=3;b[_]&&hr()!=s;)++_;for(s=0;s>>2>>>0]=hr();return s}var Vn,Nn={},Di=()=>{if(!Vn){var s,p={USER:\"web_user\",LOGNAME:\"web_user\",PATH:\"/\",PWD:\"/\",HOME:\"/home/web_user\",LANG:(typeof navigator==\"object\"&&navigator.languages&&navigator.languages[0]||\"C\").replace(\"-\",\"_\")+\".UTF-8\",_:C||\"./this.program\"};for(s in Nn)Nn[s]===void 0?delete p[s]:p[s]=Nn[s];var f=[];for(s in p)f.push(`${s}=${p[s]}`);Vn=f}return Vn};function Bi(s,p){if(g)return xe(18,1,s,p);s>>>=0,p>>>=0;var f=0;return Di().forEach((b,_)=>{var I=p+f;for(_=a()[s+4*_>>>2>>>0]=I,I=0;I>>0]=b.charCodeAt(I);t()[_>>>0]=0,f+=b.length+1}),0}function Mi(s,p){if(g)return xe(19,1,s,p);s>>>=0,p>>>=0;var f=Di();a()[s>>>2>>>0]=f.length;var b=0;return f.forEach(_=>b+=_.length+1),a()[p>>>2>>>0]=b,0}function Ri(s){return g?xe(20,1,s):52}function Ui(s,p,f,b){return g?xe(21,1,s,p,f,b):52}function Vi(s,p,f,b){return g?xe(22,1,s,p,f,b):70}var Cp=[null,[],[]];function Ni(s,p,f,b){if(g)return xe(23,1,s,p,f,b);p>>>=0,f>>>=0,b>>>=0;for(var _=0,I=0;I>>2>>>0],B=a()[p+4>>>2>>>0];p+=8;for(var G=0;G>>0],X=Cp[s];H===0||H===10?((s===1?j:K)(ti(X,0)),X.length=0):X.push(H)}_+=B}return a()[b>>>2>>>0]=_,0}var Wi=[31,29,31,30,31,30,31,31,30,31,30,31],Li=[31,28,31,30,31,30,31,31,30,31,30,31],Ap=(s,p)=>{t().set(s,p>>>0)};function Gi(s,p,f,b){function _(z,le,Se){for(z=typeof z==\"number\"?z.toString():z||\"\";z.lengthna?-1:0vt-z.getDate())){z.setDate(z.getDate()+le);break}le-=vt-z.getDate()+1,z.setDate(1),11>Se?z.setMonth(Se+1):(z.setMonth(0),z.setFullYear(z.getFullYear()+1))}return Se=new Date(z.getFullYear()+1,0,4),le=B(new Date(z.getFullYear(),0,4)),Se=B(Se),0>=D(le,z)?0>=D(Se,z)?z.getFullYear()+1:z.getFullYear():z.getFullYear()-1}s>>>=0,p>>>=0,f>>>=0,b>>>=0;var H=a()[b+40>>>2>>>0];for(var X in b={kc:i()[b>>>2>>>0],jc:i()[b+4>>>2>>>0],Hb:i()[b+8>>>2>>>0],Lb:i()[b+12>>>2>>>0],Ib:i()[b+16>>>2>>>0],Cb:i()[b+20>>>2>>>0],ub:i()[b+24>>>2>>>0],Bb:i()[b+28>>>2>>>0],sc:i()[b+32>>>2>>>0],ic:i()[b+36>>>2>>>0],lc:H?Ce(H):\"\"},f=Ce(f),H={\"%c\":\"%a %b %d %H:%M:%S %Y\",\"%D\":\"%m/%d/%y\",\"%F\":\"%Y-%m-%d\",\"%h\":\"%b\",\"%r\":\"%I:%M:%S %p\",\"%R\":\"%H:%M\",\"%T\":\"%H:%M:%S\",\"%x\":\"%m/%d/%y\",\"%X\":\"%H:%M:%S\",\"%Ec\":\"%c\",\"%EC\":\"%C\",\"%Ex\":\"%m/%d/%y\",\"%EX\":\"%H:%M:%S\",\"%Ey\":\"%y\",\"%EY\":\"%Y\",\"%Od\":\"%d\",\"%Oe\":\"%e\",\"%OH\":\"%H\",\"%OI\":\"%I\",\"%Om\":\"%m\",\"%OM\":\"%M\",\"%OS\":\"%S\",\"%Ou\":\"%u\",\"%OU\":\"%U\",\"%OV\":\"%V\",\"%Ow\":\"%w\",\"%OW\":\"%W\",\"%Oy\":\"%y\"})f=f.replace(new RegExp(X,\"g\"),H[X]);var ce=\"Sunday Monday Tuesday Wednesday Thursday Friday Saturday\".split(\" \"),ge=\"January February March April May June July August September October November December\".split(\" \");for(X in H={\"%a\":z=>ce[z.ub].substring(0,3),\"%A\":z=>ce[z.ub],\"%b\":z=>ge[z.Ib].substring(0,3),\"%B\":z=>ge[z.Ib],\"%C\":z=>I((z.Cb+1900)/100|0,2),\"%d\":z=>I(z.Lb,2),\"%e\":z=>_(z.Lb,2,\" \"),\"%g\":z=>G(z).toString().substring(2),\"%G\":G,\"%H\":z=>I(z.Hb,2),\"%I\":z=>((z=z.Hb)==0?z=12:12{for(var le=0,Se=0;Se<=z.Ib-1;le+=(zt(z.Cb+1900)?Wi:Li)[Se++]);return I(z.Lb+le,3)},\"%m\":z=>I(z.Ib+1,2),\"%M\":z=>I(z.jc,2),\"%n\":()=>`\n`,\"%p\":z=>0<=z.Hb&&12>z.Hb?\"AM\":\"PM\",\"%S\":z=>I(z.kc,2),\"%t\":()=>\"\t\",\"%u\":z=>z.ub||7,\"%U\":z=>I(Math.floor((z.Bb+7-z.ub)/7),2),\"%V\":z=>{var le=Math.floor((z.Bb+7-(z.ub+6)%7)/7);if(2>=(z.ub+371-z.Bb-2)%7&&le++,le)le==53&&((Se=(z.ub+371-z.Bb)%7)==4||Se==3&&zt(z.Cb)||(le=1));else{le=52;var Se=(z.ub+7-z.Bb-1)%7;(Se==4||Se==5&&zt(z.Cb%400-1))&&le++}return I(le,2)},\"%w\":z=>z.ub,\"%W\":z=>I(Math.floor((z.Bb+7-(z.ub+6)%7)/7),2),\"%y\":z=>(z.Cb+1900).toString().substring(2),\"%Y\":z=>z.Cb+1900,\"%z\":z=>{var le=0<=(z=z.ic);return z=Math.abs(z)/60,(le?\"+\":\"-\")+(\"0000\"+(z/60*100+z%60)).slice(-4)},\"%Z\":z=>z.lc,\"%%\":()=>\"%\"},f=f.replace(/%%/g,\"\\0\\0\"),H)f.includes(X)&&(f=f.replace(new RegExp(X,\"g\"),H[X](b)));return X=function(z){var le=Array(An(z)+1);return oi(z,le,0,le.length),le}(f=f.replace(/\\0\\0/g,\"%\")),X.length>p?0:(Ap(X,s),X.length-1)}function kp(s,p,f,b){return Gi(s>>>0,p>>>0,f>>>0,b>>>0)}g||function(){for(var s=u.numThreads-1;s--;)Xo();Ye.unshift(()=>{Gt++,function(p){g?p():Promise.all(pt.map(Zo)).then(p)}(()=>Vo())})}();for(var Hi=Array(256),gr=0;256>gr;++gr)Hi[gr]=String.fromCharCode(gr);gi=Hi,mt=u.BindingError=class extends Error{constructor(s){super(s),this.name=\"BindingError\"}},u.InternalError=class extends Error{constructor(s){super(s),this.name=\"InternalError\"}},st.push(0,1,void 0,1,null,1,!0,1,!1,1),u.count_emval_handles=()=>st.length/2-5-Pn.length;var Ep=[In,qo,Qo,ri,ni,ii,ai,si,ui,li,di,ci,pi,mi,fi,hi,ki,Ei,Bi,Mi,Ri,Ui,Vi,Ni],Y=function(){function s(f,b){return Y=f.exports,Y=function(){var _=Y,I={};for(let[D,B]of Object.entries(_))I[D]=typeof B==\"function\"?(...G)=>{pr.push(D);try{return B(...G)}finally{_e||(pr.pop(),Qe&&ht===1&&pr.length===0&&(ht=0,wt+=1,cr(Ji),typeof Fibers<\"u\"&&Fibers.tc()))}}:B;return I}(),Y=function(){var _=Y,I=B=>G=>B(G)>>>0,D=B=>()=>B()>>>0;return(_=Object.assign({},_)).Ca=I(_.Ca),_.fb=D(_.fb),_.hb=I(_.hb),_.emscripten_main_runtime_thread_id=D(_.emscripten_main_runtime_thread_id),_.sb=I(_.sb),_.tb=D(_.tb),_}(),jo.push(Y.ib),Lt.unshift(Y.Ba),Z=b,Vo(),Y}var p=Ho();if(Gt++,u.instantiateWasm)try{return u.instantiateWasm(p,s)}catch(f){K(`Module.instantiateWasm callback failed with error: ${f}`),m(f)}return $n||=u.locateFile?No(\"ort-wasm-simd-threaded.jsep.wasm\")?\"ort-wasm-simd-threaded.jsep.wasm\":u.locateFile?u.locateFile(\"ort-wasm-simd-threaded.jsep.wasm\",P):P+\"ort-wasm-simd-threaded.jsep.wasm\":new URL(\"ort-wasm-simd-threaded.jsep.wasm\",import.meta.url).href,function(f,b){var _=$n;return O||typeof WebAssembly.instantiateStreaming!=\"function\"||No(_)||Wo(_)||typeof fetch!=\"function\"?Go(_,f,b):fetch(_,{credentials:\"same-origin\"}).then(I=>WebAssembly.instantiateStreaming(I,f).then(b,function(D){return K(`wasm streaming compile failed: ${D}`),K(\"falling back to ArrayBuffer instantiation\"),Go(_,f,b)}))}(p,function(f){s(f.instance,f.module)}).catch(m),{}}(),Fi=s=>(Fi=Y.Ca)(s),qi=()=>(qi=Y.Da)();u._OrtInit=(s,p)=>(u._OrtInit=Y.Ea)(s,p),u._OrtGetLastError=(s,p)=>(u._OrtGetLastError=Y.Fa)(s,p),u._OrtCreateSessionOptions=(s,p,f,b,_,I,D,B,G,H)=>(u._OrtCreateSessionOptions=Y.Ga)(s,p,f,b,_,I,D,B,G,H),u._OrtAppendExecutionProvider=(s,p)=>(u._OrtAppendExecutionProvider=Y.Ha)(s,p),u._OrtAddFreeDimensionOverride=(s,p,f)=>(u._OrtAddFreeDimensionOverride=Y.Ia)(s,p,f),u._OrtAddSessionConfigEntry=(s,p,f)=>(u._OrtAddSessionConfigEntry=Y.Ja)(s,p,f),u._OrtReleaseSessionOptions=s=>(u._OrtReleaseSessionOptions=Y.Ka)(s),u._OrtCreateSession=(s,p,f)=>(u._OrtCreateSession=Y.La)(s,p,f),u._OrtReleaseSession=s=>(u._OrtReleaseSession=Y.Ma)(s),u._OrtGetInputOutputCount=(s,p,f)=>(u._OrtGetInputOutputCount=Y.Na)(s,p,f),u._OrtGetInputName=(s,p)=>(u._OrtGetInputName=Y.Oa)(s,p),u._OrtGetOutputName=(s,p)=>(u._OrtGetOutputName=Y.Pa)(s,p),u._OrtFree=s=>(u._OrtFree=Y.Qa)(s),u._OrtCreateTensor=(s,p,f,b,_,I)=>(u._OrtCreateTensor=Y.Ra)(s,p,f,b,_,I),u._OrtGetTensorData=(s,p,f,b,_)=>(u._OrtGetTensorData=Y.Sa)(s,p,f,b,_),u._OrtReleaseTensor=s=>(u._OrtReleaseTensor=Y.Ta)(s),u._OrtCreateRunOptions=(s,p,f,b)=>(u._OrtCreateRunOptions=Y.Ua)(s,p,f,b),u._OrtAddRunConfigEntry=(s,p,f)=>(u._OrtAddRunConfigEntry=Y.Va)(s,p,f),u._OrtReleaseRunOptions=s=>(u._OrtReleaseRunOptions=Y.Wa)(s),u._OrtCreateBinding=s=>(u._OrtCreateBinding=Y.Xa)(s),u._OrtBindInput=(s,p,f)=>(u._OrtBindInput=Y.Ya)(s,p,f),u._OrtBindOutput=(s,p,f,b)=>(u._OrtBindOutput=Y.Za)(s,p,f,b),u._OrtClearBoundOutputs=s=>(u._OrtClearBoundOutputs=Y._a)(s),u._OrtReleaseBinding=s=>(u._OrtReleaseBinding=Y.$a)(s),u._OrtRunWithBinding=(s,p,f,b,_)=>(u._OrtRunWithBinding=Y.ab)(s,p,f,b,_),u._OrtRun=(s,p,f,b,_,I,D,B)=>(u._OrtRun=Y.bb)(s,p,f,b,_,I,D,B),u._OrtEndProfiling=s=>(u._OrtEndProfiling=Y.cb)(s),u._JsepOutput=(s,p,f)=>(u._JsepOutput=Y.db)(s,p,f),u._JsepGetNodeName=s=>(u._JsepGetNodeName=Y.eb)(s);var br,Dt=()=>(Dt=Y.fb)(),Je=u._free=s=>(Je=u._free=Y.gb)(s),yr=u._malloc=s=>(yr=u._malloc=Y.hb)(s),Wn=(s,p,f,b,_,I)=>(Wn=Y.kb)(s,p,f,b,_,I),ji=()=>(ji=Y.lb)(),Ki=(s,p,f,b,_)=>(Ki=Y.mb)(s,p,f,b,_),Ln=s=>(Ln=Y.nb)(s),wr=s=>(wr=Y.ob)(s),Yi=()=>(Yi=Y.pb)(),Zi=(s,p)=>(Zi=Y.qb)(s,p),_r=s=>(_r=Y.rb)(s),Gn=s=>(Gn=Y.sb)(s),Hn=()=>(Hn=Y.tb)(),Xi=u.dynCall_ii=(s,p)=>(Xi=u.dynCall_ii=Y.vb)(s,p),Qi=s=>(Qi=Y.wb)(s),Ji=()=>(Ji=Y.xb)(),ea=s=>(ea=Y.yb)(s),ta=()=>(ta=Y.zb)();function ra(){0Hn(),u.stackRestore=s=>_r(s),u.stackAlloc=s=>Gn(s),u.setValue=function(s,p,f=\"i8\"){switch(f.endsWith(\"*\")&&(f=\"*\"),f){case\"i1\":case\"i8\":t()[s>>>0]=p;break;case\"i16\":n()[s>>>1>>>0]=p;break;case\"i32\":i()[s>>>2>>>0]=p;break;case\"i64\":q[s>>>3]=BigInt(p);break;case\"float\":l()[s>>>2>>>0]=p;break;case\"double\":d()[s>>>3>>>0]=p;break;case\"*\":a()[s>>>2>>>0]=p;break;default:ct(`invalid type for setValue: ${f}`)}},u.getValue=function(s,p=\"i8\"){switch(p.endsWith(\"*\")&&(p=\"*\"),p){case\"i1\":case\"i8\":return t()[s>>>0];case\"i16\":return n()[s>>>1>>>0];case\"i32\":return i()[s>>>2>>>0];case\"i64\":return q[s>>>3];case\"float\":return l()[s>>>2>>>0];case\"double\":return d()[s>>>3>>>0];case\"*\":return a()[s>>>2>>>0];default:ct(`invalid type for getValue: ${p}`)}},u.UTF8ToString=Ce,u.stringToUTF8=Pt,u.lengthBytesUTF8=An,Ht=function s(){br||ra(),br||(Ht=s)},ra(),u.PTR_SIZE=4,h}),Np=Ua;globalThis.self?.name===\"em-pthread\"&&Ua()});var Bt,Wp,Lp,Gp,Wa,La,Hp,Ga,jt=R(()=>{\"use strict\";Er();Bt=!1?void 0:import.meta.url??(typeof document<\"u\"?document.currentScript?.src:typeof self<\"u\"?self.location?.href:void 0),Wp=!1||typeof location>\"u\"?void 0:location.origin,Lp=(e,t)=>{try{let r=t??Bt;return(r?new URL(e,r):new URL(e)).origin===Wp}catch{return!1}},Gp=async e=>{let r=await(await fetch(e,{credentials:\"same-origin\"})).blob();return URL.createObjectURL(r)},Wa=(Ra(),vr(Ma)).default,La=async()=>{if(!Bt)throw new Error(\"Failed to load proxy worker: cannot determine the script source URL.\");if(Lp(Bt))return[void 0,Wa()];let e=await Gp(Bt);return[e,Wa(e)]},Hp=(Na(),vr(Va)).default,Ga=async(e,t,r)=>[void 0,Hp]});var Jn,eo,Vr,Ha,Fp,qp,Pr,Te,gt=R(()=>{\"use strict\";jt();eo=!1,Vr=!1,Ha=!1,Fp=()=>{if(typeof SharedArrayBuffer>\"u\")return!1;try{return typeof MessageChannel<\"u\"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},qp=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Pr=async e=>{if(eo)return Promise.resolve();if(Vr)throw new Error(\"multiple calls to 'initializeWebAssembly()' detected.\");if(Ha)throw new Error(\"previous call to 'initializeWebAssembly()' failed.\");Vr=!0;let t=e.initTimeout,r=e.numThreads;if(!qp())throw new Error(\"WebAssembly SIMD is not supported in the current environment.\");let n=Fp();r>1&&!n&&(typeof self<\"u\"&&!self.crossOriginIsolated&&console.warn(\"env.wasm.numThreads is set to \"+r+\", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info.\"),console.warn(\"WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading.\"),e.numThreads=r=1);let o=e.wasmPaths,i=typeof o==\"string\"?o:void 0,a=o?.mjs,l=a?.href??a,d=o?.wasm,c=d?.href??d,m=e.wasmBinary,[u,h]=await Ga(l,i,r>1),w=!1,y=[];if(t>0&&y.push(new Promise(g=>{setTimeout(()=>{w=!0,g()},t)})),y.push(new Promise((g,x)=>{let $={numThreads:r};m?$.wasmBinary=m:(c||i)&&($.locateFile=(v,S)=>c??(i??S)+v),h($).then(v=>{Vr=!1,eo=!0,Jn=v,g(),u&&URL.revokeObjectURL(u)},v=>{Vr=!1,Ha=!0,x(v)})})),await Promise.race(y),w)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Te=()=>{if(eo&&Jn)return Jn;throw new Error(\"WebAssembly is not initialized yet.\")}});var ke,Yt,pe,Nr=R(()=>{\"use strict\";gt();ke=(e,t)=>{let r=Te(),n=r.lengthBytesUTF8(e)+1,o=r._malloc(n);return r.stringToUTF8(e,o,n),t.push(o),o},Yt=(e,t,r,n)=>{if(typeof e==\"object\"&&e!==null){if(r.has(e))throw new Error(\"Circular reference in options\");r.add(e)}Object.entries(e).forEach(([o,i])=>{let a=t?t+o:o;if(typeof i==\"object\")Yt(i,a+\".\",r,n);else if(typeof i==\"string\"||typeof i==\"number\")n(a,i.toString());else if(typeof i==\"boolean\")n(a,i?\"1\":\"0\");else throw new Error(`Can't handle extra config type: ${typeof i}`)})},pe=e=>{let t=Te(),r=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetLastError(o,o+n);let i=Number(t.getValue(o,n===4?\"i32\":\"i64\")),a=t.getValue(o+n,\"*\"),l=a?t.UTF8ToString(a):\"\";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${l}`)}finally{t.stackRestore(r)}}});var Fa,qa=R(()=>{\"use strict\";gt();Nr();Fa=e=>{let t=Te(),r=0,n=[],o=e||{};try{if(e?.logSeverityLevel===void 0)o.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=\"number\"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)o.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=\"number\"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(o.terminate=!1);let i=0;return e?.tag!==void 0&&(i=ke(e.tag,n)),r=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,i),r===0&&pe(\"Can't create run options.\"),e?.extra!==void 0&&Yt(e.extra,\"\",new WeakSet,(a,l)=>{let d=ke(a,n),c=ke(l,n);t._OrtAddRunConfigEntry(r,d,c)!==0&&pe(`Can't set a run config entry: ${a} - ${l}.`)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(a=>t._free(a)),i}}});var jp,Kp,Yp,Zp,ja,Ka=R(()=>{\"use strict\";gt();Nr();jp=e=>{switch(e){case\"disabled\":return 0;case\"basic\":return 1;case\"extended\":return 2;case\"all\":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},Kp=e=>{switch(e){case\"sequential\":return 0;case\"parallel\":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Yp=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly=\"1\"),e.executionProviders&&e.executionProviders.some(r=>(typeof r==\"string\"?r:r.name)===\"webgpu\")&&(e.enableMemPattern=!1)},Zp=(e,t,r)=>{for(let n of t){let o=typeof n==\"string\"?n:n.name;switch(o){case\"webnn\":if(o=\"WEBNN\",typeof n!=\"string\"){let l=n?.deviceType;if(l){let d=ke(\"deviceType\",r),c=ke(l,r);Te()._OrtAddSessionConfigEntry(e,d,c)!==0&&pe(`Can't set a session config entry: 'deviceType' - ${l}.`)}}break;case\"webgpu\":if(o=\"JS\",typeof n!=\"string\"){let a=n;if(a?.preferredLayout){if(a.preferredLayout!==\"NCHW\"&&a.preferredLayout!==\"NHWC\")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${a.preferredLayout}`);let l=ke(\"preferredLayout\",r),d=ke(a.preferredLayout,r);Te()._OrtAddSessionConfigEntry(e,l,d)!==0&&pe(`Can't set a session config entry: 'preferredLayout' - ${a.preferredLayout}.`)}}break;case\"wasm\":case\"cpu\":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=ke(o,r);Te()._OrtAppendExecutionProvider(e,i)!==0&&pe(`Can't append execution provider: ${o}.`)}},ja=e=>{let t=Te(),r=0,n=[],o=e||{};Yp(o);try{let i=jp(o.graphOptimizationLevel??\"all\"),a=Kp(o.executionMode??\"sequential\"),l=typeof o.logId==\"string\"?ke(o.logId,n):0,d=o.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let c=o.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let m=typeof o.optimizedModelFilePath==\"string\"?ke(o.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(i,!!o.enableCpuMemArena,!!o.enableMemPattern,a,!!o.enableProfiling,0,l,d,c,m),r===0&&pe(\"Can't create session options.\"),o.executionProviders&&Zp(r,o.executionProviders,n),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!=\"boolean\")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);let u=ke(\"enableGraphCapture\",n),h=ke(o.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,u,h)!==0&&pe(`Can't set a session config entry: 'enableGraphCapture' - ${o.enableGraphCapture}.`)}if(o.freeDimensionOverrides)for(let[u,h]of Object.entries(o.freeDimensionOverrides)){if(typeof u!=\"string\")throw new Error(`free dimension override name must be a string: ${u}`);if(typeof h!=\"number\"||!Number.isInteger(h)||h<0)throw new Error(`free dimension override value must be a non-negative integer: ${h}`);let w=ke(u,n);t._OrtAddFreeDimensionOverride(r,w,h)!==0&&pe(`Can't set a free dimension override: ${u} - ${h}.`)}return o.extra!==void 0&&Yt(o.extra,\"\",new WeakSet,(u,h)=>{let w=ke(u,n),y=ke(h,n);t._OrtAddSessionConfigEntry(r,w,y)!==0&&pe(`Can't set a session config entry: ${u} - ${h}.`)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&pe(\"Can't release session options.\"),n.forEach(a=>t._free(a)),i}}});var Zt,bt,Tt,Wr,Xt,Lr,Gr,to,te=R(()=>{\"use strict\";Zt=e=>{switch(e){case\"int8\":return 3;case\"uint8\":return 2;case\"bool\":return 9;case\"int16\":return 5;case\"uint16\":return 4;case\"int32\":return 6;case\"uint32\":return 12;case\"float16\":return 10;case\"float32\":return 1;case\"float64\":return 11;case\"string\":return 8;case\"int64\":return 7;case\"uint64\":return 13;case\"int4\":return 22;case\"uint4\":return 21;default:throw new Error(`unsupported data type: ${e}`)}},bt=e=>{switch(e){case 3:return\"int8\";case 2:return\"uint8\";case 9:return\"bool\";case 5:return\"int16\";case 4:return\"uint16\";case 6:return\"int32\";case 12:return\"uint32\";case 10:return\"float16\";case 1:return\"float32\";case 11:return\"float64\";case 8:return\"string\";case 7:return\"int64\";case 13:return\"uint64\";case 22:return\"int4\";case 21:return\"uint4\";default:throw new Error(`unsupported data type: ${e}`)}},Tt=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t==\"number\"?t:t.reduce((o,i)=>o*i,1);return r>0?Math.ceil(n*r):void 0},Wr=e=>{switch(e){case\"float16\":return typeof Float16Array<\"u\"&&Float16Array.from?Float16Array:Uint16Array;case\"float32\":return Float32Array;case\"uint8\":return Uint8Array;case\"int8\":return Int8Array;case\"uint16\":return Uint16Array;case\"int16\":return Int16Array;case\"int32\":return Int32Array;case\"bool\":return Uint8Array;case\"float64\":return Float64Array;case\"uint32\":return Uint32Array;case\"int64\":return BigInt64Array;case\"uint64\":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Xt=e=>{switch(e){case\"verbose\":return 0;case\"info\":return 1;case\"warning\":return 2;case\"error\":return 3;case\"fatal\":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},Lr=e=>e===\"float32\"||e===\"float16\"||e===\"int32\"||e===\"int64\"||e===\"uint32\"||e===\"uint8\"||e===\"bool\"||e===\"uint4\"||e===\"int4\",Gr=e=>e===\"float32\"||e===\"float16\"||e===\"int32\"||e===\"int64\"||e===\"uint32\"||e===\"uint64\"||e===\"int8\"||e===\"uint8\"||e===\"bool\"||e===\"uint4\"||e===\"int4\",to=e=>{switch(e){case\"none\":return 0;case\"cpu\":return 1;case\"cpu-pinned\":return 2;case\"texture\":return 3;case\"gpu-buffer\":return 4;case\"ml-tensor\":return 5;default:throw new Error(`unsupported data location: ${e}`)}}});var Qt,ro=R(()=>{\"use strict\";Er();Qt=async e=>{if(typeof e==\"string\")if(!1)try{let{readFile:t}=qn(\"node:fs/promises\");return new Uint8Array(await t(e))}catch(t){if(t.code===\"ERR_FS_FILE_TOO_LARGE\"){let{createReadStream:r}=qn(\"node:fs\"),n=r(e),o=[];for await(let i of n)o.push(i);return new Uint8Array(Buffer.concat(o))}throw t}else{let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get(\"Content-Length\"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=t.body.getReader(),i;try{i=new ArrayBuffer(n)}catch(l){if(l instanceof RangeError){let d=Math.ceil(n/65536);i=new WebAssembly.Memory({initial:d,maximum:d}).buffer}else throw l}let a=0;for(;;){let{done:l,value:d}=await o.read();if(l)break;let c=d.byteLength;new Uint8Array(i,a,c).set(d),a+=c}return new Uint8Array(i,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}});var Xp,Qp,Ya,Za,Hr,Jp,se,je=R(()=>{\"use strict\";te();Xp=[\"V\",\"I\",\"W\",\"E\",\"F\"],Qp=(e,t)=>{console.log(`[${Xp[e]},${new Date().toISOString()}]${t}`)},Hr=(e,t)=>{Ya=e,Za=t},Jp=(e,t)=>{let r=Xt(e),n=Xt(Ya);r>=n&&Qp(r,typeof t==\"function\"?t():t)},se=(...e)=>{Za&&Jp(...e)}});var Fr,no=R(()=>{\"use strict\";te();Fr=(e,t)=>new(Wr(t))(e)});var qr=R(()=>{\"use strict\"});var Xa,oo,io,em,tm,Qa,so,ao,es,ts=R(()=>{\"use strict\";je();qr();Xa=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),oo=[],io=e=>Math.ceil(Number(e)/16)*16,em=e=>{for(let t=0;ttm++,so=async(e,t,r,n)=>{let o=io(r),i=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=e.getCommandEncoder();e.endComputePass(),a.copyBufferToBuffer(t,0,i,0,o),e.flush(),await i.mapAsync(GPUMapMode.READ);let l=i.getMappedRange();if(n){let d=n();return d.set(new Uint8Array(l,0,r)),d}else return new Uint8Array(l.slice(0,r))}finally{i.destroy()}},ao=class{constructor(t){this.backend=t;this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[r]of Xa)oo.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(t,r){let n=r.buffer,o=r.byteOffset,i=r.byteLength,a=io(i),l=this.storageCache.get(t);if(!l)throw new Error(\"gpu data for uploading does not exist\");if(Number(l.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${l.originalSize}, data size=${i}`);let d=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),c=d.getMappedRange();new Uint8Array(c).set(new Uint8Array(n,o,i)),d.unmap();let m=this.backend.device.createCommandEncoder();m.copyBufferToBuffer(d,0,l.gpuData.buffer,0,a),this.backend.device.queue.submit([m.finish()]),d.destroy(),se(\"verbose\",()=>`[WebGPU] GpuDataManager.upload(id=${t})`)}memcpy(t,r){let n=this.storageCache.get(t);if(!n)throw new Error(\"source gpu data for memcpy does not exist\");let o=this.storageCache.get(r);if(!o)throw new Error(\"destination gpu data for memcpy does not exist\");if(n.originalSize!==o.originalSize)throw new Error(\"inconsistent source and destination gpu data size\");let i=io(n.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(n.gpuData.buffer,0,o.gpuData.buffer,0,i)}registerExternalBuffer(t,r,n){let o;if(n){if(o=n[0],t===n[1])return se(\"verbose\",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, buffer is the same, skip.`),o;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.\n Please use the previous external buffer!`)}else o=Qa();return this.storageCache.set(o,{gpuData:{id:o,type:0,buffer:t},originalSize:r}),se(\"verbose\",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, registered.`),o}unregisterExternalBuffer(t){t!==void 0&&(this.storageCache.delete(t),se(\"verbose\",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`))}create(t,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=em(t),o,i=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let c=(i?this.freeBuffers:this.freeUniformBuffers).get(n);c?c.length>0?o=c.pop():o=this.backend.device.createBuffer({size:n,usage:r}):o=this.backend.device.createBuffer({size:n,usage:r})}else o=this.backend.device.createBuffer({size:n,usage:r});let l={id:Qa(),type:0,buffer:o};return this.storageCache.set(l.id,{gpuData:l,originalSize:Number(t)}),se(\"verbose\",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${l.id}`),l}get(t){return this.storageCache.get(t)?.gpuData}release(t){let r=typeof t==\"bigint\"?Number(t):t,n=this.storageCache.get(r);if(!n){if(this.storageCache.size===0)return 0;throw new Error(\"releasing data does not exist\")}return se(\"verbose\",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${n.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(t,r){let n=this.storageCache.get(Number(t));if(!n)throw new Error(\"data does not exist\");await so(this.backend,n.gpuData.buffer,n.originalSize,r)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus===\"default\"){for(let t of this.buffersPending){let r=Xa.get(t.size);if((t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(t.size)||[];r===void 0||n.length>=r?t.destroy():n.push(t)}else if((t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(t.size)||[];r===void 0||n.length>=r?t.destroy():n.push(t)}else t.destroy()}this.buffersPending=[]}else{let t=this.capturedPendingBuffers.get(this.backend.currentSessionId);t||(t=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,t));for(let r of this.buffersPending)t.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(t){let r=this.capturedPendingBuffers.get(t);r&&(r.forEach(n=>{n.destroy()}),this.capturedPendingBuffers.delete(t)),this.sessionCount-=1,this.sessionCount===0&&(se(\"warning\",()=>\"[WebGPU] Clearing webgpu buffer cache\"),this.storageCache.forEach(n=>{n.gpuData.buffer.destroy()}),this.storageCache=new Map)}},es=(...e)=>new ao(...e)});var uo,re,Ie=R(()=>{\"use strict\";uo=class{constructor(t){Object.assign(this,t)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(t=>`${this[t]}`).join(\";\")),this.key}},re=e=>new uo(e)});var lo,et,k,It,jr,rs,ns,oe=R(()=>{\"use strict\";lo=class{static calcMatMulShape(t,r){return t[1]!==r[0]?void 0:[t[0],r[1]]}},et=class{static calcShape(t,r,n=!1){let o=t.length,i=r.length;if(o===0)return r;if(i===0)return t;let a=Math.max(t.length,r.length),l=new Array(a);if(n){if(o<2||i<2)return;let d=lo.calcMatMulShape([t[o-2],t[o-1]],[r[i-2],r[i-1]]);if(d===void 0)return;[l[a-2],l[a-1]]=d}for(let d=n?3:1;d<=a;d++){let c=o-d<0?1:t[o-d],m=i-d<0?1:r[i-d];if(c!==m&&c>1&&m>1)return;let u=Math.max(c,m);if(c&&m)l[a-d]=Math.max(c,m);else{if(u>1)return;l[a-d]=0}}return l}static isValidBroadcast(t,r){let n=t.length,o=r.length;if(n>o)return!1;for(let i=1;i<=n;i++)if(t[n-i]!==1&&t[n-i]!==r[o-i])return!1;return!0}},k=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let o=new Array(n),i=n-1;for(;i>=0;){if(t[i]%r===0){o[i]=t[i]/r;break}if(r%t[i]!==0)throw new Error(\"cannot convert shape\");o[i]=1,r/=t[i],i--}for(i--;i>=0;i--)o[i]=t[i];return o}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let o=1;for(let i=r;i=0;--o)n[o]=n[o+1]*t[o+1];return n}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error(\"unsupported axis for this operation.\");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(n=>this.normalizeAxis(n,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(n=>t[n]):t.slice().reverse()}static padShape(t,r){let n=t.length;return t.map((o,i)=>o+r[i]+r[i+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,o)=>n===r[o])}},It=class e{static adjustPoolAttributes(t,r,n,o,i,a){if(!t&&n.length!==r.length-2)throw new Error(\"length of specified kernel shapes should be 2 less than length of input dimensions\");if(t)for(let l=0;l=n.length?n.push(r[l+2]):n[l]=r[l+2];for(let l=0;l=n[l]||a[l+n.length]>=n[l])throw new Error(\"pads should be smaller than kernel\")}}static adjustPadsBasedOnAutoPad(t,r,n,o,i,a,l){if(l){if(i.length!==2*(t.length-2))throw new Error(\"length of pads should be twice the length of data dimensions\");if(r.length!==t.length-2)throw new Error(\"length of strides should be the length of data dimensions\");if(o.length!==t.length-2)throw new Error(\"length of kernel shapes should be the length of data dimensions\");for(let d=0;d{\"use strict\";te();oe();Ct=64,po=(e,t)=>{if(t===3)throw new Error(\"vec3 has same alignment as vec4, use vec4 instead\");switch(Number(e)){case 10:return t>1?`vec${t}`:\"f16\";case 1:return t>1?`vec${t}`:\"f32\";case 6:return t>1?`vec${t}`:\"i32\";case 12:return t>1?`vec${t}`:\"u32\";case 7:if(t>1)throw new Error(\"currently not supported vecX of uint64 yet\");return[\"vec2\",\"i32\"];case 13:if(t>1)throw new Error(\"currently not supported vecX of uint64 yet\");return[\"vec2\",\"u32\"];case 9:if(t!==4)throw new Error(\"bool must be vec4\");return[\"u32\",\"vec4\"];case 22:return\"i32\";case 21:return\"u32\";default:throw new Error(`Unknown data type: ${e}`)}},me=(e,t=1)=>{let r=po(e,t);return typeof r==\"string\"?r:r[0]},Ee=(e,t=1)=>{let r=po(e,t);return typeof r==\"string\"?r:r[1]},V=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:k.computeStrides(r)})}),t},ye=e=>e%4===0?4:e%2===0?2:1,mo=(e=\"f32\",t,r=\"0\")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,At=(e,t,r)=>e===\"f32\"?r:t===1?`f32(${r})`:`vec${t}(${r})`,Ke=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,F=(e,t,r,n)=>e.startsWith(\"uniforms.\")&&r>4?typeof t==\"string\"?n===\"f16\"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n===\"f16\"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,fo=(e,t,r,n,o)=>{let i=typeof r==\"number\",a=i?r:r.length,l=[...new Array(a).keys()],d=a<2?\"u32\":a<=4?`vec${a}`:`array`,c=po(t,o),m=typeof c==\"string\"?c:c[1],u=typeof c==\"string\"?c:c[0],h={indices:d,value:m,storage:u,tensor:t},w=N=>typeof N==\"string\"?N:`${N}u`,y={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},g=i?\"uniforms.\":\"\",x=`${g}${e}_shape`,$=`${g}${e}_strides`,v=\"\";for(let N=0;N ${h.indices} {\n var indices: ${h.indices};\n var current = offset;\n ${v}\n return indices;\n }`,T=N=>(y.offsetToIndices=!0,a<2?N:`o2i_${e}(${N})`),C=[];if(a>=2)for(let N=a-1;N>=0;N--)C.push(`${F($,N,a)} * (indices[${N}])`);let A=a<2?\"\":`\n fn i2o_${e}(indices: ${h.indices}) -> u32 {\n return ${C.join(\"+\")};\n }`,P=N=>(y.indicesToOffset=!0,a<2?N:`i2o_${e}(${N})`),O=(...N)=>a===0?\"0u\":`${h.indices}(${N.map(w).join(\",\")})`,U=(N,q)=>a<2?`${N}`:`${F(N,q,a)}`,L=(N,q,he)=>a<2?`${N}=${he};`:`${F(N,q,a)}=${he};`,j={},K=(N,q)=>{y.broadcastedIndicesToOffset=!0;let he=`${q.name}broadcastedIndicesTo${e}Offset`;if(he in j)return`${he}(${N})`;let qe=[];for(let _e=a-1;_e>=0;_e--){let be=q.indicesGet(\"outputIndices\",_e+q.rank-a);qe.push(`${U($,_e)} * (${be} % ${U(x,_e)})`)}return j[he]=`fn ${he}(outputIndices: ${q.type.indices}) -> u32 {\n return ${qe.length>0?qe.join(\"+\"):\"0u\"};\n }`,`${he}(${N})`},W=(N,q)=>(()=>{if(h.storage===h.value)return`${e}[${N}]=${q};`;if(h.storage===\"vec2\"&&h.value===\"i32\")return`${e}[${N}]=vec2(u32(${q}), select(0u, 0xFFFFFFFFu, ${q} < 0));`;if(h.storage===\"vec2\"&&h.value===\"u32\")return`${e}[${N}]=vec2(u32(${q}), 0u);`;if(h.storage===\"u32\"&&h.value===\"vec4\")return`${e}[${N}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${q}));`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),ee=N=>(()=>{if(h.storage===h.value)return`${e}[${N}]`;if(h.storage===\"vec2\"&&h.value===\"i32\")return`i32(${e}[${N}].x)`;if(h.storage===\"vec2\"&&h.value===\"u32\")return`u32(${e}[${N}].x)`;if(h.storage===\"u32\"&&h.value===\"vec4\")return`vec4(bool(${e}[${N}] & 0xFFu), bool(${e}[${N}] & 0xFF00u), bool(${e}[${N}] & 0xFF0000u), bool(${e}[${N}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),ue=a<2?\"\":`\n fn get_${e}ByIndices(indices: ${h.indices}) -> ${m} {\n return ${ee(`i2o_${e}(indices)`)};\n }`,Z=a<2?\"\":(()=>{let N=l.map(he=>`d${he}: u32`).join(\", \"),q=l.map(he=>`d${he}`).join(\", \");return`\n fn get_${e}(${N}) -> ${m} {\n return get_${e}ByIndices(${O(q)});\n }`})(),J=(...N)=>{if(N.length!==a)throw new Error(`indices length must be ${a}`);let q=N.map(w).join(\",\");return a===0?ee(\"0u\"):a===1?ee(q[0]):(y.get=!0,y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}(${q})`)},Q=N=>a<2?ee(N):(y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}ByIndices(${N})`),ne=a<2?\"\":`\n fn set_${e}ByIndices(indices: ${h.indices}, value: ${m}) {\n ${W(`i2o_${e}(indices)`,\"value\")}\n }`,we=a<2?\"\":(()=>{let N=l.map(he=>`d${he}: u32`).join(\", \"),q=l.map(he=>`d${he}`).join(\", \");return`\n fn set_${e}(${N}, value: ${m}) {\n set_${e}ByIndices(${O(q)}, value);\n }`})();return{impl:()=>{let N=[],q=!1;return y.offsetToIndices&&(N.push(S),q=!0),y.indicesToOffset&&(N.push(A),q=!0),y.broadcastedIndicesToOffset&&(Object.values(j).forEach(he=>N.push(he)),q=!0),y.set&&(N.push(we),q=!0),y.setByIndices&&(N.push(ne),q=!0),y.get&&(N.push(Z),q=!0),y.getByIndices&&(N.push(ue),q=!0),!i&&q&&N.unshift(`const ${x} = ${h.indices}(${r.join(\",\")});`,`const ${$} = ${h.indices}(${k.computeStrides(r).join(\",\")});`),N.join(`\n`)},type:h,offsetToIndices:T,indicesToOffset:P,broadcastedIndicesToOffset:K,indices:O,indicesGet:U,indicesSet:L,set:(...N)=>{if(N.length!==a+1)throw new Error(`indices length must be ${a}`);let q=N[a];if(typeof q!=\"string\")throw new Error(\"value must be string\");let he=N.slice(0,a).map(w).join(\",\");return a===0?W(\"0u\",q):a===1?W(he[0],q):(y.set=!0,y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}(${he}, ${q})`)},setByOffset:W,setByIndices:(N,q)=>a<2?W(N,q):(y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}ByIndices(${N}, ${q});`),get:J,getByOffset:ee,getByIndices:Q,usage:n,name:e,strides:$,shape:x,rank:a}},E=(e,t,r,n=1)=>fo(e,t,r,\"input\",n),M=(e,t,r,n=1)=>fo(e,t,r,\"output\",n),Kr=(e,t,r,n=1)=>fo(e,t,r,\"internal\",n),co=class{constructor(t,r){this.normalizedDispatchGroup=t;this.limits=r;this.internalVariables=[];this.variables=[];this.uniforms=[];this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t==\"number\"?`${t}u`:t}) { return; }`}mainStart(t=Ct){let r=typeof t==\"number\"?t:t[0],n=typeof t==\"number\"?1:t[1],o=typeof t==\"number\"?1:t[2];if(r>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||o>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*n*o>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=i?`@builtin(global_invocation_id) global_id : vec3,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3,\n @builtin(local_invocation_id) local_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(num_workgroups) num_workgroups : vec3`,l=i?`let global_idx = global_id.x;\n let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] +\n workgroup_id.y * num_workgroups[0] + workgroup_id.x;\n let global_idx = workgroup_index * ${r*n*o}u + local_idx;`;return`@compute @workgroup_size(${r}, ${n}, ${o})\n fn main(${a}) {\n ${l}\n `}appendVariableUniforms(t){t.rank!==0&&(t.shape.startsWith(\"uniforms.\")&&this.uniforms.push({name:t.shape.replace(\"uniforms.\",\"\"),type:\"u32\",length:t.rank}),t.strides.startsWith(\"uniforms.\")&&this.uniforms.push({name:t.strides.replace(\"uniforms.\",\"\"),type:\"u32\",length:t.rank}))}declareVariable(t,r){if(t.usage===\"internal\")throw new Error(\"cannot use internal variable with declareVariable(). use registerInternalVariables() instead.\");this.variables.push(t),this.appendVariableUniforms(t);let n=t.usage===\"input\"?\"read\":\"read_write\",o=t.type.storage;return`@group(0) @binding(${r}) var ${t.name}: array<${o}>;`}declareVariables(...t){return t.map(r=>this.declareVariable(r,this.variableIndex++)).join(`\n`)}registerInternalVariable(t){if(t.usage!==\"internal\")throw new Error(\"cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.\");this.internalVariables.push(t),this.appendVariableUniforms(t)}registerInternalVariables(...t){return t.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(t,r,n=1){return this.uniforms.push({name:t,type:r,length:n}),this}registerUniforms(t){return this.uniforms=this.uniforms.concat(t),this}uniformDeclaration(){if(this.uniforms.length===0)return\"\";let t=[];for(let{name:r,type:n,length:o}of this.uniforms)if(o&&o>4)n===\"f16\"?t.push(`@align(16) ${r}:array, ${Math.ceil(o/8)}>`):t.push(`${r}:array, ${Math.ceil(o/4)}>`);else{let i=o==null||o===1?n:`vec${o}<${n}>`;t.push(`${r}:${i}`)}return`\n struct Uniforms { ${t.join(\", \")} };\n @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(t=>t.impl()).join(`\n`)+this.internalVariables.map(t=>t.impl()).join(`\n`)}get variablesInfo(){if(this.uniforms.length===0)return;let t=r=>[12,10,1,6][[\"u32\",\"f16\",\"f32\",\"i32\"].indexOf(r)];return this.uniforms.map(r=>[t(r.type),r.length??1])}},os=(e,t)=>new co(e,t)});var rm,is,nm,om,im,Pe,as,ss,ut=R(()=>{\"use strict\";te();oe();Ie();ae();rm=e=>{if(!e||e.length!==1)throw new Error(\"Transpose requires 1 input.\")},is=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,nm=(e,t)=>k.sortBasedOnPerm(e,is(e.length,t)),om=(e,t,r,n)=>{let o=`fn perm(i: ${n.type.indices}) -> ${r.type.indices} {\n var a: ${r.type.indices};`;for(let i=0;i{let r=[],n=[];for(let o=0;o{let r=e.dataType,n=e.dims.length,o=is(n,t),i=nm(e.dims,o),{newShape:a,newPerm:l}=im(e.dims,o),d=k.areEqual(l,[2,3,1]),c=k.areEqual(l,[3,1,2]),m=a.length===2&&l[0]>l[1]||d||c,u=m?a:e.dims,h=i;m&&(u=d?[a[0],a[1]*a[2]]:c?[a[0]*a[1],a[2]]:a,h=[u[1],u[0]]);let w=E(\"a\",r,u.length),y=M(\"output\",r,h.length),g=16,x;return m?x=$=>`\n ${$.registerUniform(\"output_size\",\"u32\").declareVariables(w,y)}\n var tile : array, ${g}>;\n ${$.mainStart([g,g,1])}\n let stride = (uniforms.output_shape[1] - 1) / ${g} + 1;\n let workgroup_id_x = workgroup_index % stride;\n let workgroup_id_y = workgroup_index / stride;\n let input_col = workgroup_id_y * ${g}u + local_id.x;\n let input_row = workgroup_id_x * ${g}u + local_id.y;\n if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) {\n tile[local_id.y][local_id.x] = ${w.getByIndices(`${w.type.indices}(input_row, input_col)`)};\n }\n workgroupBarrier();\n\n let output_col = workgroup_id_x * ${g}u + local_id.x;\n let output_row = workgroup_id_y * ${g}u + local_id.y;\n if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) {\n ${y.setByIndices(`${y.type.indices}(output_row, output_col)`,\"tile[local_id.x][local_id.y]\")}\n }\n }`:x=$=>`\n ${$.registerUniform(\"output_size\",\"u32\").declareVariables(w,y)}\n\n ${om(o,n,w,y)}\n\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let indices = ${y.offsetToIndices(\"global_idx\")};\n let aIndices = perm(indices);\n\n ${y.setByOffset(\"global_idx\",w.getByIndices(\"aIndices\"))}\n }`,{name:m?\"TransposeShared\":\"Transpose\",shaderCache:{hint:`${t}`,inputDependencies:[\"rank\"]},getRunData:()=>{let $=k.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:m?{x:Math.ceil(h[1]/g),y:Math.ceil(h[0]/g)}:{x:Math.ceil($/64)},programUniforms:[{type:12,data:$},...V(u,h)]}},getShaderSource:x}},as=(e,t)=>{rm(e.inputs),e.compute(Pe(e.inputs[0],t.perm))},ss=e=>re({perm:e.perm})});var am,sm,um,lm,dm,cm,pm,mm,fm,hm,tt,us,ls,ds,cs,ps,ms,fs,hs,gs,bs,ys=R(()=>{\"use strict\";te();oe();ae();Yr();ut();am={max:\"select(bestValue, candidate, candidate > bestValue)\",min:\"select(bestValue, candidate, candidate < bestValue)\",mean:\"bestValue + candidate\",sum:\"bestValue + candidate\",prod:\"bestValue * candidate\",sumSquare:\"bestValue + candidate * candidate\",logSumExp:\"bestValue + exp(candidate)\",l1:\"bestValue + abs(candidate)\",l2:\"bestValue + candidate * candidate\",logSum:\"bestValue + candidate\"},sm={max:\"select(bestValue, candidate, candidate > bestValue)\",min:\"select(bestValue, candidate, candidate < bestValue)\",mean:\"bestValue + candidate\",sum:\"bestValue + candidate\",prod:\"bestValue * candidate\",sumSquare:\"bestValue + candidate\",logSumExp:\"bestValue + candidate\",l1:\"bestValue + candidate\",l2:\"bestValue + candidate\",logSum:\"bestValue + candidate\"},um={max:\"_A[offset]\",min:\"_A[offset]\",mean:\"0\",sum:\"0\",prod:\"1\",sumSquare:\"0\",logSumExp:\"0\",l1:\"0\",l2:\"0\",logSum:\"0\"},lm={max:\"bestValue\",min:\"bestValue\",sum:\"bestValue\",prod:\"bestValue\",sumSquare:\"bestValue\",logSumExp:\"log(bestValue)\",l1:\"bestValue\",l2:\"sqrt(bestValue)\",logSum:\"log(bestValue)\"},dm=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let i=0;ie[i]);return[r,o]},pm=(e,t)=>{let r=e.length+t.length,n=[],o=0;for(let i=0;i{for(let r=0;r{let r=[];if(!mm(e,t)){for(let n=0;nr.push(n))}return r},hm=(e,t,r,n,o,i,a)=>{let l=r[0].dims,d=k.size(i),c=k.size(a),m=E(\"_A\",r[0].dataType,l),u=M(\"output\",o,i),h=64;d===1&&(h=256);let w=`\n var aBestValues : array;\n `,y=g=>`\n ${g.registerUniform(\"reduceSize\",\"u32\").declareVariables(m,u)}\n ${w}\n fn DIV_CEIL(a : u32, b : u32) -> u32 {\n return ((a - 1u) / b + 1u);\n }\n ${g.mainStart(h)}\n\n let outputIndex = global_idx / ${h};\n let offset = outputIndex * uniforms.reduceSize;\n\n var bestValue = f32(${um[n]});\n let Length = uniforms.reduceSize;\n for (var k = local_idx; k < Length; k = k + ${h}) {\n let candidate = f32(${m.getByOffset(\"offset + k\")});\n bestValue = ${am[n]};\n }\n aBestValues[local_idx] = bestValue;\n workgroupBarrier();\n\n var reduceSize = min(Length, ${h}u);\n for (var currentSize = reduceSize / 2u; reduceSize > 1u;\n currentSize = reduceSize / 2u) {\n let interval = DIV_CEIL(reduceSize, 2u);\n if (local_idx < currentSize) {\n let candidate = aBestValues[local_idx + interval];\n bestValue = ${sm[n]};\n aBestValues[local_idx] = bestValue;\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (local_idx == 0u) {\n ${u.setByOffset(\"outputIndex\",`${n===\"mean\"?`${u.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${u.type.storage}(${lm[n]})`}`)};\n }\n }`;return{name:e,shaderCache:{hint:`${t};${h}`,inputDependencies:[\"type\"]},getShaderSource:y,getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:d},programUniforms:[{type:12,data:c}]})}},tt=(e,t,r,n)=>{let o=e.inputs.length===1?r:ho(e.inputs,r),i=o.axes;i.length===0&&!o.noopWithEmptyAxes&&(i=e.inputs[0].dims.map((w,y)=>y));let a=k.normalizeAxes(i,e.inputs[0].dims.length),l=a,d=e.inputs[0],c=fm(l,e.inputs[0].dims.length);c.length>0&&(d=e.compute(Pe(e.inputs[0],c),{inputs:[0],outputs:[-1]})[0],l=dm(l.length,d.dims.length));let[m,u]=cm(d.dims,l),h=m;o.keepDims&&(h=pm(m,a)),e.compute(hm(t,o.cacheKey,[d],n,e.inputs[0].dataType,h,u),{inputs:[d]})},us=(e,t)=>{tt(e,\"ReduceMeanShared\",t,\"mean\")},ls=(e,t)=>{tt(e,\"ReduceL1Shared\",t,\"l1\")},ds=(e,t)=>{tt(e,\"ReduceL2Shared\",t,\"l2\")},cs=(e,t)=>{tt(e,\"ReduceLogSumExpShared\",t,\"logSumExp\")},ps=(e,t)=>{tt(e,\"ReduceMaxShared\",t,\"max\")},ms=(e,t)=>{tt(e,\"ReduceMinShared\",t,\"min\")},fs=(e,t)=>{tt(e,\"ReduceProdShared\",t,\"prod\")},hs=(e,t)=>{tt(e,\"ReduceSumShared\",t,\"sum\")},gs=(e,t)=>{tt(e,\"ReduceSumSquareShared\",t,\"sumSquare\")},bs=(e,t)=>{tt(e,\"ReduceLogSumShared\",t,\"logSum\")}});var rt,gm,Zr,ho,nt,bm,ym,wm,_m,vm,$m,xm,Sm,Tm,Im,ot,ws,_s,vs,$s,xs,Ss,Ts,Is,Cs,As,Yr=R(()=>{\"use strict\";te();oe();Ie();ae();ys();rt=e=>{if(!e||e.length===0||e.length>2)throw new Error(\"Reduce op requires 1 or 2 inputs.\");if(e.length===2&&e[1].dims.length!==1)throw new Error(\"Invalid axes input dims.\")},gm=e=>[\"\",\"\",`var value = ${e.getByIndices(\"input_indices\")};`,\"\"],Zr=(e,t,r,n,o,i,a=!1,l=!1)=>{let d=[],c=r[0].dims,m=c.length,u=k.normalizeAxes(o,m),h=!l&&u.length===0;c.forEach((x,$)=>{h||u.indexOf($)>=0?a&&d.push(1):d.push(x)});let w=d.length,y=k.size(d);return{name:e,shaderCache:t,getShaderSource:x=>{let $=[],v=E(\"_A\",r[0].dataType,m),S=M(\"output\",i,w),T=n(v,S,u),C=T[2];for(let A=0,P=0;A=0?(a&&P++,C=`for(var j${A}: u32 = 0; j${A} < ${c[A]}; j${A}++) {\n ${T[2].includes(\"last_index\")?`let last_index = j${A};`:\"\"}\n ${v.indicesSet(\"input_indices\",A,`j${A}`)}\n ${C}\n }`):($.push(`${v.indicesSet(\"input_indices\",A,S.indicesGet(\"output_indices\",P))};`),P++);return`\n\n ${x.registerUniform(\"output_size\",\"u32\").declareVariables(v,S)}\n\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n var input_indices: ${v.type.indices};\n let output_indices = ${S.offsetToIndices(\"global_idx\")};\n\n ${$.join(`\n`)}\n ${T[0]} // init ops for reduce max/min\n ${T[1]}\n ${C}\n ${T[3]}\n ${T.length===4?S.setByOffset(\"global_idx\",\"value\"):T.slice(4).join(`\n`)}\n }`},getRunData:()=>({outputs:[{dims:d,dataType:i}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:[{type:12,data:y},...V(c,d)]})}},ho=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),re({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},nt=(e,t,r,n)=>{let o=e.inputs,i=o.length===1?r:ho(o,r);e.compute(Zr(t,{hint:i.cacheKey,inputDependencies:[\"rank\"]},[o[0]],i.noopWithEmptyAxes&&i.axes.length===0?gm:n,i.axes,o[0].dataType,i.keepDims,i.noopWithEmptyAxes),{inputs:[0]})},bm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceLogSum\",t,(n,o)=>[`var value = ${o.type.storage}(0);`,\"\",`value += ${n.getByIndices(\"input_indices\")};`,\"value = log(value);\"])},ym=(e,t)=>{rt(e.inputs),nt(e,\"ReduceL1\",t,(n,o)=>[`var value = ${o.type.storage}(0);`,\"\",`value += abs(${n.getByIndices(\"input_indices\")});`,\"\"])},wm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceL2\",t,(n,o)=>[`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`,\"\",`t = ${n.getByIndices(\"input_indices\")}; value += (t * t);`,\"value = sqrt(value);\"])},_m=(e,t)=>{rt(e.inputs),nt(e,\"ReduceLogSumExp\",t,(n,o)=>[`var value = ${o.type.storage}(0);`,\"\",`value += exp(${n.getByIndices(\"input_indices\")});`,\"value = log(value);\"])},vm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceMax\",t,(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(n.indicesSet(\"input_indices\",l,0));return[`${a.join(`\n`)}`,`var value = ${n.getByIndices(\"input_indices\")};`,`value = max(value, ${n.getByIndices(\"input_indices\")});`,\"\"]})},$m=(e,t)=>{rt(e.inputs),nt(e,\"ReduceMean\",t,(n,o,i)=>{let a=1;for(let l=0;l=0||i.length===0)&&(a*=e.inputs[0].dims[l]);return[\"var sum = f32(0);\",\"\",`sum += f32(${n.getByIndices(\"input_indices\")});`,`let value = ${o.type.value}(sum / ${a});`]})},xm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceMin\",t,(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(`input_indices[${l}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${n.getByIndices(\"input_indices\")};`,`value = min(value, ${n.getByIndices(\"input_indices\")});`,\"\"]})},Sm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceProd\",t,(n,o)=>[`var value = ${o.type.storage}(1);`,\"\",`value *= ${n.getByIndices(\"input_indices\")};`,\"\"])},Tm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceSum\",t,(n,o)=>[`var value = ${o.type.storage}(0);`,\"\",`value += ${n.getByIndices(\"input_indices\")};`,\"\"])},Im=(e,t)=>{rt(e.inputs),nt(e,\"ReduceSumSquare\",t,(n,o)=>[`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`,\"\",`t = ${n.getByIndices(\"input_indices\")}; value += t * t;`,\"\"])},ot=(e,t,r)=>{if(t.length===0)return r;let n=1,o=1;for(let i=0;i1024},ws=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?$m(e,t):us(e,t)},_s=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ym(e,t):ls(e,t)},vs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?wm(e,t):ds(e,t)},$s=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?_m(e,t):cs(e,t)},xs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?vm(e,t):ps(e,t)},Ss=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?xm(e,t):ms(e,t)},Ts=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Sm(e,t):fs(e,t)},Is=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Tm(e,t):hs(e,t)},Cs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Im(e,t):gs(e,t)},As=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?bm(e,t):bs(e,t)}});var ks,Es,Ps,go,zs=R(()=>{\"use strict\";te();Ie();Yr();ks=e=>{if(!e||e.length===0||e.length>2)throw new Error(\"ArgMinMaxOp op requires 1 or 2 inputs.\");if(e[0].dataType!==1)throw new Error(\"Invalid input type.\")},Es=(e,t)=>{ks(e.inputs);let r=(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(`input_indices[${l}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${n.getByIndices(\"input_indices\")};\nvar best_index : i32 = 0;`,`if (${n.getByIndices(\"input_indices\")} ${t.selectLastIndex>0?\"<=\":\"<\"} value) {\n value = ${n.getByIndices(\"input_indices\")};\n best_index = i32(last_index);\n }`,\"\",o.setByOffset(\"global_idx\",\"best_index\")]};e.compute(Zr(\"ArgMin\",{hint:t.cacheKey,inputDependencies:[\"rank\"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Ps=(e,t)=>{ks(e.inputs);let r=(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(`input_indices[${l}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${n.getByIndices(\"input_indices\")};\nvar best_index : i32 = 0;`,`if (${n.getByIndices(\"input_indices\")} ${t.selectLastIndex>0?\">=\":\">\"} value) {\n value = ${n.getByIndices(\"input_indices\")};\n best_index = i32(last_index);\n }`,\"\",o.setByOffset(\"global_idx\",\"best_index\")]};e.compute(Zr(\"argMax\",{hint:t.cacheKey,inputDependencies:[\"rank\"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},go=e=>re(e)});var Cm,bo,Am,km,Em,Rt,Pm,Os,Xr=R(()=>{\"use strict\";te();oe();qr();ae();Cm=(e,t)=>{let r=e[0],n=e[1],o=e[2],i=e[3],a=e[4],l=e[5];if(a&&l)throw new Error(\"Attention cannot have both past and attention_bias\");if(r.dims.length!==3)throw new Error('Input \"input\" must have 3 dimensions');let d=r.dims[0],c=r.dims[1],m=r.dims[2];if(o.dims.length!==1)throw new Error('Input \"bias\" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input \"weights\" is expected to have 2 dimensions');if(n.dims[0]!==m)throw new Error(\"Input 1 dimension 0 should have same length as dimension 2 of input 0\");if(o.dims[0]!==n.dims[1])throw new Error('Input \"bias\" dimension 0 should have same length as dimension 1 of input \"weights\"');let u=o.dims[0]/3,h=u,w=h;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error(\"qkv_hidden_sizes attribute should have 3 elements\");for(let S of t.qkvHiddenSizes)if(S%t.numHeads!==0)throw new Error(\"qkv_hidden_sizes should be divisible by num_heads\");u=t.qkvHiddenSizes[0],h=t.qkvHiddenSizes[1],w=t.qkvHiddenSizes[2]}let y=c;if(u!==h)throw new Error(\"qkv_hidden_sizes first element should be same as the second\");if(o.dims[0]!==u+h+w)throw new Error('Input \"bias\" dimension 0 should have same length as sum of Q/K/V hidden sizes');let g=0;if(a){if(h!==w)throw new Error('Input \"past\" expect k_hidden_size == v_hidden_size');if(a.dims.length!==5)throw new Error('Input \"past\" must have 5 dimensions');if(a.dims[0]!==2)throw new Error('Input \"past\" first dimension must be 2');if(a.dims[1]!==d)throw new Error('Input \"past\" second dimension must be batch_size');if(a.dims[2]!==t.numHeads)throw new Error('Input \"past\" third dimension must be num_heads');if(a.dims[4]!==h/t.numHeads)throw new Error('Input \"past\" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(g=a.dims[3])}let x=y+g,$=-1,v=0;if(i)throw new Error(\"Mask not supported\");if(a)throw new Error(\"past is not supported\");if(l){if(l.dims.length!==4)throw new Error('Input \"attention_bias\" must have 4 dimensions');if(l.dims[0]!==d||l.dims[1]!==t.numHeads||l.dims[2]!==c||l.dims[3]!==x)throw new Error('Expect \"attention_bias\" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:d,sequenceLength:c,pastSequenceLength:g,kvSequenceLength:y,totalSequenceLength:x,maxSequenceLength:$,inputHiddenSize:m,hiddenSize:u,vHiddenSize:w,headSize:Math.floor(u/t.numHeads),vHeadSize:Math.floor(w/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:v,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},bo=(e,t,r)=>t&&e?`\n let total_sequence_length_input = u32(${t.getByOffset(\"0\")});\n let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);\n let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;\n let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input;\n total_sequence_length = u32(${e?.getByOffset(\"batchIdx\")}) + 1;\n var past_sequence_length: u32 = 0;\n if (is_first_prompt == false) {\n past_sequence_length = total_sequence_length - sequence_length;\n }\n `:`\n ${r?\"let past_sequence_length = uniforms.past_sequence_length\":\"\"};\n let present_sequence_length = total_sequence_length;\n `,Am=(e,t,r,n,o,i,a,l)=>{let d=ye(a?1:i),c=64,m=i/d;m{let v=M(\"x\",e.dataType,e.dims,d),S=[v],T=a?E(\"seq_lens\",a.dataType,a.dims):void 0;T&&S.push(T);let C=l?E(\"total_sequence_length_input\",l.dataType,l.dims):void 0;C&&S.push(C);let A=Ee(e.dataType),P=[{name:\"batch_size\",type:\"u32\"},{name:\"num_heads\",type:\"u32\"},{name:\"past_sequence_length\",type:\"u32\"},{name:\"sequence_length\",type:\"u32\"},{name:\"total_sequence_length\",type:\"u32\"},{name:\"elements_per_thread\",type:\"u32\"}];return`\n var thread_max: array;\n var thread_sum: array;\n ${$.registerUniforms(P).declareVariables(...S)}\n ${$.mainStart([c,1,1])}\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let sequence_length = uniforms.sequence_length;\n var total_sequence_length = uniforms.total_sequence_length;\n ${bo(T,C,!1)}\n let local_offset = local_idx * uniforms.elements_per_thread;\n let offset = (global_idx / ${c}) * uniforms.total_sequence_length + local_offset;\n let seq_causal_length = ${a?\"u32(past_sequence_length + workgroup_id.y + 1)\":\"total_sequence_length\"};\n var thread_max_vector = ${y}(-3.402823e+38f);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n thread_max_vector = max(${y}(x[offset + i]), thread_max_vector);\n }\n thread_max[local_idx] = ${(()=>{switch(d){case 1:return\"thread_max_vector\";case 2:return\"max(thread_max_vector.x, thread_max_vector.y)\";case 4:return\"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))\";default:throw new Error(`Unsupported components: ${d}`)}})()};\n workgroupBarrier();\n\n var max_value = f32(-3.402823e+38f);\n for (var i = 0u; i < ${c}; i++) {\n max_value = max(thread_max[i], max_value);\n }\n\n var sum_vector = ${y}(0);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n sum_vector += exp(${y}(x[offset + i]) - max_value);\n }\n thread_sum[local_idx] = ${(()=>{switch(d){case 1:return\"sum_vector\";case 2:return\"sum_vector.x + sum_vector.y\";case 4:return\"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w\";default:throw new Error(`Unsupported components: ${d}`)}})()};\n workgroupBarrier();\n\n var sum: f32 = 0;\n for (var i = 0u; i < ${c}; i++) {\n sum += thread_sum[i];\n }\n\n if (sum == 0) {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n x[offset + i] = ${v.type.value}(${A}(1.0) / ${A}(seq_causal_length));\n }\n } else {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n var f32input = ${y}(x[offset + i]);\n x[offset + i] = ${v.type.value}(exp(f32input - max_value) / sum);\n }\n }\n ${a?`\n for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) {\n x[offset + total_seq_id] = ${v.type.value}(${A}(0));\n }`:\"\"};\n }`};return{name:\"AttentionProbsSoftmax\",shaderCache:{hint:`${c};${w};${d}`,inputDependencies:g},getShaderSource:x,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(i/c),y:o,z:t*r},programUniforms:h})}},km=(e,t,r,n,o,i,a,l,d)=>{let c=a+i.kvSequenceLength,m=[i.batchSize,i.numHeads,i.sequenceLength,c],u=e>1&&n,h=i.kvNumHeads?i.kvNumHeads:i.numHeads,w=u?[i.batchSize,h,c,i.headSize]:void 0,y=i.nReps?i.nReps:1,g=i.scale===0?1/Math.sqrt(i.headSize):i.scale,x=ye(i.headSize),$=i.headSize/x,v=12,S={x:Math.ceil(c/v),y:Math.ceil(i.sequenceLength/v),z:i.batchSize*i.numHeads},T=[{type:12,data:i.sequenceLength},{type:12,data:$},{type:12,data:c},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:1,data:g},{type:12,data:a},{type:12,data:i.kvSequenceLength},{type:12,data:y}],C=u&&n&&k.size(n.dims)>0,A=[\"type\",\"type\"];C&&A.push(\"type\"),o&&A.push(\"type\"),l&&A.push(\"type\"),d&&A.push(\"type\");let P=[{dims:m,dataType:t.dataType,gpuDataType:0}];u&&P.push({dims:w,dataType:t.dataType,gpuDataType:0});let O=U=>{let L=E(\"q\",t.dataType,t.dims,x),j=E(\"key\",r.dataType,r.dims,x),K=[L,j];if(C){let ne=E(\"past_key\",n.dataType,n.dims,x);K.push(ne)}o&&K.push(E(\"attention_bias\",o.dataType,o.dims));let W=l?E(\"seq_lens\",l.dataType,l.dims):void 0;W&&K.push(W);let ee=d?E(\"total_sequence_length_input\",d.dataType,d.dims):void 0;ee&&K.push(ee);let ue=M(\"output\",t.dataType,m),Z=[ue];u&&Z.push(M(\"present_key\",t.dataType,w,x));let J=Ee(1,x),Q=[{name:\"M\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"num_heads\",type:\"u32\"},{name:\"head_size\",type:\"u32\"},{name:\"alpha\",type:\"f32\"},{name:\"past_sequence_length\",type:\"u32\"},{name:\"kv_sequence_length\",type:\"u32\"},{name:\"n_reps\",type:\"u32\"}];return`\n const TILE_SIZE = ${v}u;\n\n var tileQ: array<${L.type.storage}, ${v*v}>;\n var tileK: array<${L.type.storage}, ${v*v}>;\n ${U.registerUniforms(Q).declareVariables(...K,...Z)}\n ${U.mainStart([v,v,1])}\n // x holds the N and y holds the M\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let kvHeadIdx = ${y===1?\"headIdx\":\"headIdx / uniforms.n_reps\"};\n let kv_num_heads = ${y===1?\"uniforms.num_heads\":\"uniforms.num_heads / uniforms.n_reps\"};\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let m = workgroup_id.y * TILE_SIZE;\n let n = workgroup_id.x * TILE_SIZE;\n let sequence_length = uniforms.M;\n var total_sequence_length = uniforms.N;\n ${bo(W,ee,!0)}\n let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx;\n let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;\n ${C&&u?\"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;\":\"\"};\n let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K;\n ${u?\"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;\":\"\"}\n var value = ${J}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {\n var idx = TILE_SIZE * local_id.y + local_id.x;\n ${(()=>C&&u?`\n if (n + local_id.y < past_sequence_length) {\n tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x];\n } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {\n tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x];\n }`:`\n if (n + local_id.y < uniforms.kv_sequence_length) {\n tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x];\n }`)()}\n ${u?`if (n + local_id.y < present_sequence_length) {\n present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];\n }`:\"\"}\n }\n workgroupBarrier();\n\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {\n value += ${J}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);\n }\n\n workgroupBarrier();\n }\n\n if (global_id.y < uniforms.M && global_id.x < total_sequence_length) {\n let headOffset = workgroup_id.z * uniforms.M * uniforms.N;\n let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;\n var sum: f32 = ${(()=>{switch(x){case 1:return\"value\";case 2:return\"value.x + value.y\";case 4:return\"value.x + value.y + value.z + value.w\";default:throw new Error(`Unsupported components: ${x}`)}})()};\n output[outputIdx] = ${ue.type.value} (sum * uniforms.alpha) + ${o?\"attention_bias[outputIdx]\":\"0.0\"};\n }\n }`};return{name:\"AttentionProbs\",shaderCache:{hint:`${x};${o!==void 0};${n!==void 0};${e}`,inputDependencies:A},getRunData:()=>({outputs:P,dispatchGroup:S,programUniforms:T}),getShaderSource:O}},Em=(e,t,r,n,o,i,a=void 0,l=void 0)=>{let d=i+o.kvSequenceLength,c=o.nReps?o.nReps:1,m=o.vHiddenSize*c,u=e>1&&n,h=o.kvNumHeads?o.kvNumHeads:o.numHeads,w=u?[o.batchSize,h,d,o.headSize]:void 0,y=[o.batchSize,o.sequenceLength,m],g=12,x={x:Math.ceil(o.vHeadSize/g),y:Math.ceil(o.sequenceLength/g),z:o.batchSize*o.numHeads},$=[{type:12,data:o.sequenceLength},{type:12,data:d},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:m},{type:12,data:i},{type:12,data:o.kvSequenceLength},{type:12,data:c}],v=u&&n&&k.size(n.dims)>0,S=[\"type\",\"type\"];v&&S.push(\"type\"),a&&S.push(\"type\"),l&&S.push(\"type\");let T=[{dims:y,dataType:t.dataType,gpuDataType:0}];u&&T.push({dims:w,dataType:t.dataType,gpuDataType:0});let C=A=>{let P=E(\"probs\",t.dataType,t.dims),O=E(\"v\",r.dataType,r.dims),U=[P,O];v&&U.push(E(\"past_value\",n.dataType,n.dims));let L=a?E(\"seq_lens\",a.dataType,a.dims):void 0;a&&U.push(L);let j=l?E(\"total_sequence_length_input\",l.dataType,l.dims):void 0;l&&U.push(j);let W=[M(\"output\",t.dataType,y)];u&&W.push(M(\"present_value\",t.dataType,w));let ee=[{name:\"M\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"num_heads\",type:\"u32\"},{name:\"head_size\",type:\"u32\"},{name:\"v_hidden_size\",type:\"u32\"},{name:\"past_sequence_length\",type:\"u32\"},{name:\"kv_sequence_length\",type:\"u32\"},{name:\"n_reps\",type:\"u32\"}];return`\n const TILE_SIZE = ${g}u;\n var tileQ: array<${P.type.value}, ${g*g}>;\n var tileV: array<${P.type.value}, ${g*g}>;\n ${A.registerUniforms(ee).declareVariables(...U,...W)}\n ${A.mainStart([g,g,1])}\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let kvHeadIdx = ${c===1?\"headIdx\":\"headIdx / uniforms.n_reps\"};\n let kv_num_heads = ${c===1?\"uniforms.num_heads\":\"uniforms.num_heads / uniforms.n_reps\"};\n let m = global_id.y;\n let n = global_id.x;\n let sequence_length = uniforms.M;\n var total_sequence_length = uniforms.K;\n ${bo(L,j,!0)}\n let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;\n let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch\n ${v&&u?\"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;\":\"\"};\n let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n;\n ${u?\"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;\":\"\"}\n var value = ${P.type.storage}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n var idx = TILE_SIZE * local_id.y + local_id.x;\n ${(()=>v&&u?`\n if (w + local_id.y < past_sequence_length) {\n tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N];\n } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {\n tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N];\n }\n `:`\n if (w + local_id.y < uniforms.kv_sequence_length) {\n tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N];\n }`)()}\n ${u?`\n if (w + local_id.y < present_sequence_length) {\n present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx];\n }`:\"\"}\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) {\n value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x];\n }\n workgroupBarrier();\n }\n\n // we need to transpose output from BNSH_v to BSND_v\n if (m < uniforms.M && n < uniforms.N) {\n let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size\n + headIdx * uniforms.N + n;\n output[outputIdx] = value;\n }\n }`};return{name:\"AttentionScore\",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:S},getRunData:()=>({outputs:T,dispatchGroup:x,programUniforms:$}),getShaderSource:C}},Rt=(e,t,r,n,o,i,a,l,d,c,m=void 0,u=void 0)=>{let h=Math.min(e.outputCount,1+(a?1:0)+(l?1:0)),w=h>1?c.pastSequenceLength:0,y=w+c.kvSequenceLength,g=d&&k.size(d.dims)>0?d:void 0,x=[t,r];h>1&&a&&k.size(a.dims)>0&&x.push(a),g&&x.push(g),m&&x.push(m),u&&x.push(u);let $=e.compute(km(h,t,r,a,g,c,w,m,u),{inputs:x,outputs:h>1?[-1,1]:[-1]})[0];e.compute(Am($,c.batchSize,c.numHeads,w,c.sequenceLength,y,m,u),{inputs:m&&u?[$,m,u]:[$],outputs:[]});let v=[$,n];h>1&&l&&k.size(l.dims)>0&&v.push(l),m&&v.push(m),u&&v.push(u),e.compute(Em(h,$,n,l,c,w,m,u),{inputs:v,outputs:h>1?[0,2]:[0]})},Pm=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,o=t.inputHiddenSize,i=t.headSize,a=12,l={x:Math.ceil(t.headSize/a),y:Math.ceil(t.sequenceLength/a),z:t.batchSize*t.numHeads},d=[e.inputs[0],e.inputs[1],e.inputs[2]],c=[{type:12,data:n},{type:12,data:o},{type:12,data:i},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],m=u=>{let h=M(\"output_q\",d[0].dataType,r),w=M(\"output_k\",d[0].dataType,r),y=M(\"output_v\",d[0].dataType,r),g=E(\"input\",d[0].dataType,d[0].dims),x=E(\"weight\",d[1].dataType,d[1].dims),$=E(\"bias\",d[2].dataType,d[2].dims),v=g.type.storage,S=[{name:\"M\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"num_heads\",type:\"u32\"},{name:\"head_size\",type:\"u32\"},{name:\"hidden_size\",type:\"u32\"},{name:\"ldb\",type:\"u32\"}];return`\n const TILE_SIZE = ${a}u;\n var tileInput: array<${v}, ${a*a}>;\n var tileWeightQ: array<${v}, ${a*a}>;\n var tileWeightK: array<${v}, ${a*a}>;\n var tileWeightV: array<${v}, ${a*a}>;\n ${u.registerUniforms(S).declareVariables(g,x,$,h,w,y)}\n ${u.mainStart([a,a,1])}\n let batchIndex = workgroup_id.z / uniforms.num_heads;\n let headNumber = workgroup_id.z % uniforms.num_heads;\n let m = global_id.y;\n let n = global_id.x;\n\n let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;\n let biasOffsetQ = headNumber * uniforms.head_size;\n let biasOffsetK = uniforms.hidden_size + biasOffsetQ;\n let biasOffsetV = uniforms.hidden_size + biasOffsetK;\n\n var valueQ = ${v}(0);\n var valueK = ${v}(0);\n var valueV = ${v}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n let offset = n + (w + local_id.y) * uniforms.ldb;\n tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];\n tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];\n tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:l,programUniforms:c}),getShaderSource:m},{inputs:d,outputs:[-1,-1,-1]})},Os=(e,t)=>{let r=Cm(e.inputs,t),[n,o,i]=Pm(e,r);return Rt(e,n,o,i,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r)}});var zm,Om,Dm,Ds,Bs=R(()=>{\"use strict\";He();te();oe();Ie();ae();zm=(e,t)=>{if(!e||e.length!==5)throw new Error(\"BatchNormalization requires 5 inputs\");let r=(n,o,i)=>{let a=o.length;if(a!==n.length)throw new Error(`${i}: num dimensions != ${a}`);o.forEach((l,d)=>{if(l!==n[d])throw new Error(`${i}: dim[${d}] do not match`)})};if(e[0].dims.length>1){let n=t.format===\"NHWC\"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,n,\"Invalid input scale\"),r(e[2].dims,n,\"Invalid input B\"),r(e[3].dims,n,\"Invalid input mean\"),r(e[4].dims,n,\"Invalid input var\")}else r(e[1].dims,[1],\"Invalid input scale\"),r(e[2].dims,[1],\"Invalid input B\"),r(e[3].dims,[1],\"Invalid input mean\"),r(e[4].dims,[1],\"Invalid input var\")},Om=(e,t)=>{let{epsilon:r,spatial:n,format:o}=t,i=e[0].dims,a=n?ye(i[i.length-1]):1,l=o===\"NHWC\"&&i.length>1?a:1,d=k.size(i)/a,c=n,m=c?i.length:i,u=E(\"x\",e[0].dataType,e[0].dims,a),h=E(\"scale\",e[1].dataType,e[1].dims,l),w=E(\"bias\",e[2].dataType,e[2].dims,l),y=E(\"inputMean\",e[3].dataType,e[3].dims,l),g=E(\"inputVar\",e[4].dataType,e[4].dims,l),x=M(\"y\",e[0].dataType,m,a),$=()=>{let S=\"\";if(n)S=`let cOffset = ${i.length===1?\"0u\":o===\"NHWC\"?`outputIndices[${i.length-1}] / ${a}`:\"outputIndices[1]\"};`;else if(o===\"NCHW\")S=`\n ${x.indicesSet(\"outputIndices\",\"0\",\"0\")}\n let cOffset = ${x.indicesToOffset(\"outputIndices\")};`;else{S=`var cIndices = ${h.type.indices}(0);\n cIndices[0] = outputIndices[${i.length-1}];`;for(let T=1;T`\n const epsilon = ${r};\n ${S.registerUniform(\"outputSize\",\"u32\").declareVariables(u,h,w,y,g,x)}\n ${S.mainStart()}\n ${S.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n var outputIndices = ${x.offsetToIndices(`global_idx * ${a}`)};\n ${$()}\n let scale = ${h.getByOffset(\"cOffset\")};\n let bias = ${w.getByOffset(\"cOffset\")};\n let inputMean = ${y.getByOffset(\"cOffset\")};\n let inputVar = ${g.getByOffset(\"cOffset\")};\n let x = ${u.getByOffset(\"global_idx\")};\n let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;\n ${x.setByOffset(\"global_idx\",\"value\")}\n }`;return{name:\"BatchNormalization\",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${a}`,inputDependencies:c?[\"rank\",\"type\",\"type\",\"type\",\"type\"]:void 0},getShaderSource:v,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c?[{type:12,data:d},...V(i)]:[{type:12,data:d}]})}},Dm=e=>re(e),Ds=(e,t)=>{let{inputs:r,outputCount:n}=e,o=Dm({...t,outputCount:n});if(ve.webgpu.validateInputContent&&zm(r,o),t.trainingMode)throw new Error(\"BatchNormalization trainingMode is not supported yet.\");e.compute(Om(r,o))}});var Bm,Mm,Ms,Rs=R(()=>{\"use strict\";oe();ae();Bm=e=>{if(e[0].dims.length!==3)throw new Error(\"input should have 3 dimensions\");if(![320,640,1280].includes(e[0].dims[2]))throw new Error(\"number of channels should be 320, 640 or 1280\");if(e[1].dims.length!==1)throw new Error(\"bias is expected to have 1 dimensions\");if(e[0].dims[2]!==e[1].dims[0])throw new Error(\"last dimension of input and bias are not the same\")},Mm=e=>{let t=e[0].dims,r=e[0].dims[2],n=k.size(t)/4,o=e[0].dataType,i=E(\"input\",o,t,4),a=E(\"bias\",o,[r],4),l=E(\"residual\",o,t,4),d=M(\"output\",o,t,4);return{name:\"BiasAdd\",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:m=>`\n const channels = ${r}u / 4;\n ${m.declareVariables(i,a,l,d)}\n\n ${m.mainStart()}\n ${m.guardAgainstOutOfBoundsWorkgroupSizes(n)}\n let value = ${i.getByOffset(\"global_idx\")}\n + ${a.getByOffset(\"global_idx % channels\")} + ${l.getByOffset(\"global_idx\")};\n ${d.setByOffset(\"global_idx\",\"value\")}\n }`}},Ms=e=>{Bm(e.inputs),e.compute(Mm(e.inputs))}});var Rm,fe,Us,Vs,Ns,Ws,Ls,Gs,Hs,Fs,qs,Um,js,Ks,Ys,Zs,Jt,Xs,Qr,Qs,Js,eu,tu,ru,nu,ou,iu,au,su,uu,lu,du,cu,pu,mu,fu,hu,yo,wo,gu,bu,yu,Vm,Nm,wu,Jr=R(()=>{\"use strict\";te();oe();Ie();ae();Rm=(e,t,r,n,o,i,a)=>{let l=Math.ceil(t/4),d=\"\";typeof o==\"string\"?d=`${o}(a)`:d=o(\"a\");let c=E(\"inputData\",r,[l],4),m=M(\"outputData\",n,[l],4),u=[{name:\"vec_size\",type:\"u32\"}];return a&&u.push(...a),`\n ${e.registerUniforms(u).declareVariables(c,m)}\n\n ${i??\"\"}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.vec_size\")}\n\n let a = ${c.getByOffset(\"global_idx\")};\n ${m.setByOffset(\"global_idx\",d)}\n }`},fe=(e,t,r,n,o,i=e.dataType,a,l)=>{let d=[{type:12,data:Math.ceil(k.size(e.dims)/4)}];return a&&d.push(...a),{name:t,shaderCache:{hint:o,inputDependencies:[\"type\"]},getShaderSource:c=>Rm(c,k.size(e.dims),e.dataType,i,r,n,l),getRunData:c=>({outputs:[{dims:e.dims,dataType:i}],dispatchGroup:{x:Math.ceil(k.size(c[0].dims)/64/4)},programUniforms:d})}},Us=e=>{e.compute(fe(e.inputs[0],\"Abs\",\"abs\"))},Vs=e=>{e.compute(fe(e.inputs[0],\"Acos\",\"acos\"))},Ns=e=>{e.compute(fe(e.inputs[0],\"Acosh\",\"acosh\"))},Ws=e=>{e.compute(fe(e.inputs[0],\"Asin\",\"asin\"))},Ls=e=>{e.compute(fe(e.inputs[0],\"Asinh\",\"asinh\"))},Gs=e=>{e.compute(fe(e.inputs[0],\"Atan\",\"atan\"))},Hs=e=>{e.compute(fe(e.inputs[0],\"Atanh\",\"atanh\"))},Fs=e=>re(e),qs=(e,t)=>{let r;switch(t.to){case 10:r=\"vec4\";break;case 1:r=\"vec4\";break;case 12:r=\"vec4\";break;case 6:r=\"vec4\";break;case 9:r=\"vec4\";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(fe(e.inputs[0],\"Cast\",r,void 0,t.cacheKey,t.to))},Um=e=>{let t,r,n=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,r=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,r=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error(\"Unsupport data type\")}return re({min:t,max:r})},js=(e,t)=>{let r=t||Um(e.inputs),n=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Clip\",o=>`clamp(${o}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,r.cacheKey,void 0,[{type:e.inputs[0].dataType,data:r.min},{type:e.inputs[0].dataType,data:r.max}],[{name:\"min\",type:n},{name:\"max\",type:n}]),{inputs:[0]})},Ks=e=>{e.compute(fe(e.inputs[0],\"Ceil\",\"ceil\"))},Ys=e=>{e.compute(fe(e.inputs[0],\"Cos\",\"cos\"))},Zs=e=>{e.compute(fe(e.inputs[0],\"Cosh\",\"cosh\"))},Jt=e=>re(e),Xs=(e,t)=>{let r=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Elu\",n=>`elu_vf32(${n})`,`\n const elu_alpha_ = ${r}(${t.alpha});\n\n fn elu_f32(a: ${r}) -> ${r} {\n return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);\n }\n\n fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> {\n return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));\n }`,t.cacheKey))},Qr=(e=\"f32\")=>`\nconst r0: ${e} = 0.3275911;\nconst r1: ${e} = 0.254829592;\nconst r2: ${e} = -0.284496736;\nconst r3: ${e} = 1.421413741;\nconst r4: ${e} = -1.453152027;\nconst r5: ${e} = 1.061405429;\n\nfn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {\n let absv = abs(v);\n let x = 1.0 / (1.0 + r0 * absv);\n return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));\n}`,Qs=e=>{let t=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Erf\",r=>`erf_vf32(${r})`,Qr(t)))},Js=e=>{e.compute(fe(e.inputs[0],\"Exp\",\"exp\"))},eu=e=>{e.compute(fe(e.inputs[0],\"Floor\",\"floor\"))},tu=e=>{let t=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Gelu\",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Qr(t)))},ru=(e,t)=>{let r=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"LeakyRelu\",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},nu=e=>{e.compute(fe(e.inputs[0],\"Not\",t=>`!${t}`))},ou=e=>{e.compute(fe(e.inputs[0],\"Neg\",t=>`-${t}`))},iu=e=>{e.compute(fe(e.inputs[0],\"Reciprocal\",t=>`1.0/${t}`))},au=e=>{let t=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Relu\",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},su=e=>{e.compute(fe(e.inputs[0],\"Sigmoid\",t=>`(1.0 / (1.0 + exp(-${t})))`))},uu=e=>re(e),lu=(e,t)=>{let r=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"HardSigmoid\",n=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${n} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},du=e=>{e.compute(fe(e.inputs[0],\"Sin\",\"sin\"))},cu=e=>{e.compute(fe(e.inputs[0],\"Sinh\",\"sinh\"))},pu=e=>{e.compute(fe(e.inputs[0],\"Sqrt\",\"sqrt\"))},mu=e=>{e.compute(fe(e.inputs[0],\"Tan\",\"tan\"))},fu=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,hu=e=>{e.compute(fe(e.inputs[0],\"Tanh\",fu))},yo=(e=\"f32\")=>`\nconst fast_gelu_a: ${e} = 0.5;\nconst fast_gelu_b: ${e} = 0.7978845608028654;\nconst fast_gelu_c: ${e} = 0.035677408136300125;\n\nfn tanh_v(v: vec4<${e}>) -> vec4<${e}> {\n return ${fu(\"v\")};\n}\n`,wo=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,gu=e=>{let t=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"FastGelu\",wo,yo(t),void 0,e.inputs[0].dataType))},bu=(e,t)=>{let r=Ee(e.inputs[0].dataType);return e.compute(fe(e.inputs[0],\"ThresholdedRelu\",n=>`select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},yu=e=>{e.compute(fe(e.inputs[0],\"Log\",\"log\"))},Vm=(e,t)=>`\nconst alpha = vec4<${e}>(${t});\nconst one = ${e}(1.0);\nconst zero = ${e}(0.0);\n\nfn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {\n let v = x *alpha;\n var x1 : vec4<${e}>;\n for (var i = 0; i < 4; i = i + 1) {\n if (v[i] >= zero) {\n x1[i] = one / (one + exp(-v[i]));\n } else {\n x1[i] = one - one / (one + exp(v[i]));\n }\n }\n return x * x1;\n}\n`,Nm=e=>`quick_gelu_impl(${e})`,wu=(e,t)=>{let r=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"QuickGelu\",Nm,Vm(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}});var Wm,Lm,vu,$u=R(()=>{\"use strict\";oe();ae();Jr();Wm=e=>{if(e[0].dims.length!==3)throw new Error(\"input should have 3 dimensions\");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error(\"hidden state should be 2560, 5120 or 10240\");if(e[1].dims.length!==1)throw new Error(\"bias is expected to have 1 dimensions\");if(e[0].dims[2]!==e[1].dims[0])throw new Error(\"last dimension of input and bias are not the same\")},Lm=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=E(\"input\",e[0].dataType,e[0].dims,4),n=E(\"bias\",e[0].dataType,[e[0].dims[2]],4),o=M(\"output\",e[0].dataType,t,4),i=k.size(t)/4,a=me(e[0].dataType);return{name:\"BiasSplitGelu\",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:d=>`\n const M_SQRT2 = sqrt(2.0);\n const halfChannels = ${e[0].dims[2]/4/2}u;\n\n ${d.declareVariables(r,n,o)}\n\n ${Qr(a)}\n\n ${d.mainStart()}\n ${d.guardAgainstOutOfBoundsWorkgroupSizes(i)}\n let biasIdx = global_idx % halfChannels;\n let batchIndex = global_idx / halfChannels;\n let inputOffset = biasIdx + batchIndex * halfChannels * 2;\n let valueLeft = input[inputOffset] + bias[biasIdx];\n let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];\n let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);\n\n ${o.setByOffset(\"global_idx\",\"valueLeft * geluRight\")}\n }`}},vu=e=>{Wm(e.inputs),e.compute(Lm(e.inputs))}});var Gm,Hm,it,xu,Su,Tu,Iu,Cu,Au,ku,Eu,Pu,zu,Ou=R(()=>{\"use strict\";te();oe();ae();Gm=(e,t,r,n,o,i,a,l,d,c,m,u)=>{let h,w;typeof l==\"string\"?h=w=(v,S)=>`${l}((${v}),(${S}))`:typeof l==\"function\"?h=w=l:(h=l.scalar,w=l.vector);let y=M(\"outputData\",m,n.length,4),g=E(\"aData\",d,t.length,4),x=E(\"bData\",c,r.length,4),$;if(o)if(i){let v=k.size(t)===1,S=k.size(r)===1,T=t.length>0&&t[t.length-1]%4===0,C=r.length>0&&r[r.length-1]%4===0;v||S?$=y.setByOffset(\"global_idx\",w(v?`${g.type.value}(${g.getByOffset(\"0\")}.x)`:g.getByOffset(\"global_idx\"),S?`${x.type.value}(${x.getByOffset(\"0\")}.x)`:x.getByOffset(\"global_idx\"))):$=`\n let outputIndices = ${y.offsetToIndices(\"global_idx * 4u\")};\n let offsetA = ${g.broadcastedIndicesToOffset(\"outputIndices\",y)};\n let offsetB = ${x.broadcastedIndicesToOffset(\"outputIndices\",y)};\n ${y.setByOffset(\"global_idx\",w(a||T?g.getByOffset(\"offsetA / 4u\"):`${g.type.value}(${g.getByOffset(\"offsetA / 4u\")}[offsetA % 4u])`,a||C?x.getByOffset(\"offsetB / 4u\"):`${x.type.value}(${x.getByOffset(\"offsetB / 4u\")}[offsetB % 4u])`))}\n `}else $=y.setByOffset(\"global_idx\",w(g.getByOffset(\"global_idx\"),x.getByOffset(\"global_idx\")));else{if(!i)throw new Error(\"no necessary to use scalar implementation for element-wise binary op implementation.\");let v=(S,T,C=\"\")=>{let A=`aData[indexA${T}][componentA${T}]`,P=`bData[indexB${T}][componentB${T}]`;return`\n let outputIndices${T} = ${y.offsetToIndices(`global_idx * 4u + ${T}u`)};\n let offsetA${T} = ${g.broadcastedIndicesToOffset(`outputIndices${T}`,y)};\n let offsetB${T} = ${x.broadcastedIndicesToOffset(`outputIndices${T}`,y)};\n let indexA${T} = offsetA${T} / 4u;\n let indexB${T} = offsetB${T} / 4u;\n let componentA${T} = offsetA${T} % 4u;\n let componentB${T} = offsetB${T} % 4u;\n ${S}[${T}] = ${C}(${h(A,P)});\n `};m===9?$=`\n var data = vec4(0);\n ${v(\"data\",0,\"u32\")}\n ${v(\"data\",1,\"u32\")}\n ${v(\"data\",2,\"u32\")}\n ${v(\"data\",3,\"u32\")}\n outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:$=`\n ${v(\"outputData[global_idx]\",0)}\n ${v(\"outputData[global_idx]\",1)}\n ${v(\"outputData[global_idx]\",2)}\n ${v(\"outputData[global_idx]\",3)}\n `}return`\n ${e.registerUniform(\"vec_size\",\"u32\").declareVariables(g,x,y)}\n\n ${u??\"\"}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.vec_size\")}\n ${$}\n }`},Hm=(e,t,r,n,o,i,a=r.dataType)=>{let l=r.dims.map(g=>Number(g)??1),d=n.dims.map(g=>Number(g)??1),c=!k.areEqual(l,d),m=l,u=k.size(l),h=!1,w=!1,y=[c];if(c){let g=et.calcShape(l,d,!1);if(!g)throw new Error(\"Can't perform binary op on the given tensors\");m=g.slice(),u=k.size(m);let x=k.size(l)===1,$=k.size(d)===1,v=l.length>0&&l[l.length-1]%4===0,S=d.length>0&&d[d.length-1]%4===0;y.push(x),y.push($),y.push(v),y.push(S);let T=1;for(let C=1;Cg.toString()).join(\"_\"),inputDependencies:[\"rank\",\"rank\"]},getShaderSource:g=>Gm(g,l,d,m,h,c,w,o,r.dataType,n.dataType,a,i),getRunData:()=>({outputs:[{dims:m,dataType:a}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:Math.ceil(k.size(m)/4)},...V(l,d,m)]})}},it=(e,t,r,n,o,i)=>{e.compute(Hm(t,o??\"\",e.inputs[0],e.inputs[1],r,n,i))},xu=e=>{it(e,\"Add\",(t,r)=>`${t}+${r}`)},Su=e=>{it(e,\"Div\",(t,r)=>`${t}/${r}`)},Tu=e=>{it(e,\"Equal\",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},Iu=e=>{it(e,\"Mul\",(t,r)=>`${t}*${r}`)},Cu=e=>{let t=E(\"input\",e.inputs[0].dataType,e.inputs[0].dims).type.value;it(e,\"Pow\",{scalar:(n,o)=>`pow_custom(${n},${o})`,vector:(n,o)=>`pow_vector_custom(${n},${o})`},`\n fn pow_custom(a : ${t}, b : ${t}) -> ${t} {\n if (b == ${t}(0.0)) {\n return ${t}(1.0);\n } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {\n return ${t}(pow(f32(a), f32(b))); // NaN\n }\n return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t===\"i32\"?\"round\":\"\"}(pow(f32(abs(a)), f32(b))));\n }\n fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {\n // TODO: implement vectorized pow\n return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));\n }\n `)},Au=e=>{it(e,\"Sub\",(t,r)=>`${t}-${r}`)},ku=e=>{it(e,\"Greater\",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},Eu=e=>{it(e,\"Less\",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Pu=e=>{it(e,\"GreaterOrEqual\",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},zu=e=>{it(e,\"LessOrEqual\",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}});var qm,jm,Km,Ym,Du,Bu,Mu=R(()=>{\"use strict\";te();oe();Ie();ae();qm=(e,t)=>{if(!e||e.length<1)throw new Error(\"too few inputs\");let r=0,n=e[r],o=n.dataType,i=n.dims.length;e.forEach((a,l)=>{if(l!==r){if(a.dataType!==o)throw new Error(\"input tensors should be one type\");if(a.dims.length!==i)throw new Error(\"input tensors should have the same shape\");a.dims.forEach((d,c)=>{if(c!==t&&d!==n.dims[c])throw new Error(\"non concat dimensions must match\")})}})},jm=(e,t)=>`\n fn calculateInputIndex(index: u32) -> u32 {\n let sizeInConcatAxis = array(${t});\n for (var i: u32 = 0u; i < ${e}; i += 1u ) {\n if (index < sizeInConcatAxis[i]) {\n return i;\n }\n }\n return ${e}u;\n }`,Km=(e,t)=>{let r=e.length,n=[];for(let o=0;o{let o=k.size(r),i=new Array(e.length),a=new Array(e.length),l=0,d=[],c=[],m=[{type:12,data:o}];for(let g=0;g`uniforms.sizeInConcatAxis${g}`).join(\",\"),y=g=>`\n\n ${(()=>{g.registerUniform(\"outputSize\",\"u32\");for(let x=0;x(${w});\n ${h} -= sizeInConcatAxis[inputIndex - 1u];\n }\n\n ${Km(a,u)}\n }`;return{name:\"Concat\",shaderCache:{hint:`${t}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:m}),getShaderSource:y}},Du=(e,t)=>{let r=e.inputs,n=r[0].dims,o=k.normalizeAxis(t.axis,n.length);qm(r,o);let i=n.slice();i[o]=r.reduce((l,d)=>l+(d.dims.length>o?d.dims[o]:0),0);let a=r.filter(l=>k.size(l.dims)>0);e.compute(Ym(a,o,i,r[0].dataType),{inputs:a})},Bu=e=>re({axis:e.axis})});var Ve,Ne,We,en,lt=R(()=>{\"use strict\";te();oe();Ve=(e,t,r=\"f32\")=>{switch(e.activation){case\"Relu\":return`value = max(value, ${t}(0.0));`;case\"Sigmoid\":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case\"Clip\":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case\"HardSigmoid\":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case\"LeakyRelu\":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case\"Tanh\":return`let e2x = exp(-2.0 * abs(value));\n value = sign(value) * (1.0 - e2x) / (1.0 + e2x);\n `;case\"\":return\"\";default:throw new Error(`Unsupported activation ${e.activation}`)}},Ne=(e,t)=>{e.activation===\"Clip\"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation===\"HardSigmoid\"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation===\"LeakyRelu\"&&t.push({type:1,data:e.alpha})},We=(e,t)=>{e.activation===\"Clip\"?t.push({name:\"clip_max\",type:\"f32\"},{name:\"clip_min\",type:\"f32\"}):e.activation===\"HardSigmoid\"?t.push({name:\"alpha\",type:\"f32\"},{name:\"beta\",type:\"f32\"}):e.activation===\"LeakyRelu\"&&t.push({name:\"alpha\",type:\"f32\"})},en=e=>{let t=e?.activation||\"\";if(t===\"HardSigmoid\"){let[r,n]=e?.activation_params||[.2,.5];return{activation:t,alpha:r,beta:n}}else if(t===\"Clip\"){let[r,n]=e?.activation_params||[rs,ns];return{activation:t,clipMax:n,clipMin:r}}else if(t===\"LeakyRelu\"){let[r]=e?.activation_params||[.01];return{activation:t,alpha:r}}return{activation:t}}});var ze,tn,er=R(()=>{\"use strict\";ze=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},tn=e=>`\n ${e?\"value = value + getBiasByOutputCoords(coords);\":\"\"}\n `});var rn,_o=R(()=>{\"use strict\";rn=e=>`\nfn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 {\n return dot(coords, vec4(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n}\nfn getOutputIndexFromCoords(coords : vec4) -> i32 {\n return dot(coords, vec4(\n i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));\n}\n`});var tr,nn,on=R(()=>{\"use strict\";te();oe();ae();lt();tr=(e,t,r,n,o)=>{let i=n-r;return`\n ${Array.from({length:r}).map((a,l)=>`\n if (${F(t.shape,l,t.rank)} != 1) {\n ${t.indicesSet(e,l,F(o,l+i,n))}\n } else {\n ${t.indicesSet(e,l,0)}\n }`).join(\"\")}\n`},nn=(e,t,r,n,o=!1,i)=>{let a=e[0].dims,l=e[1].dims,d=a[a.length-2],c=l[l.length-1],m=a[a.length-1],u=ye(c),h=ye(m),w=ye(d),y=k.size(r)/u/w,g=e.length>2,x=n?n.slice(0,-2):r.slice(0,-2),v=[k.size(x),d,c],S=[{type:12,data:y},{type:12,data:d},{type:12,data:c},{type:12,data:m}];Ne(t,S),S.push(...V(x,a,l)),g&&S.push(...V(e[2].dims)),S.push(...V(v));let T=C=>{let A=Kr(\"batch_dims\",e[0].dataType,x.length),P=E(\"a\",e[0].dataType,a.length,h),O=E(\"b\",e[1].dataType,l.length,u),U=M(\"output\",e[0].dataType,v.length,u),L=me(U.type.tensor),j=Ve(t,U.type.value,L),K=[P,O],W=\"\";if(g){let Z=o?u:1;K.push(E(\"bias\",e[2].dataType,e[2].dims.length,Z)),W=`${o?`value += bias[col / ${Z}];`:`value += ${U.type.value}(bias[row + i]);`}`}let ee=[{name:\"output_size\",type:\"u32\"},{name:\"M\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"K\",type:\"u32\"}];We(t,ee);let ue=()=>{let Z=`var a_data: ${P.type.value};`;for(let J=0;J;\n for (var k: u32 = 0u; k < uniforms.K; k = k + ${h}) {\n ${ue()}\n }\n for (var i = 0u; i < ${w}u; i++) {\n var value = values[i];\n ${W}\n ${j}\n let cur_indices = ${U.type.indices}(batch, row + i, col);\n let offset = ${U.indicesToOffset(\"cur_indices\")};\n ${U.setByOffset(`offset / ${u}`,\"value\")};\n }\n }\n `};return{name:\"MatMulNaive\",shaderCache:{hint:`${t.activation};${u};${h};${w};${o}`,inputDependencies:g?[\"rank\",\"rank\",\"rank\"]:[\"rank\",\"rank\"]},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:S}),getShaderSource:T}}});var Zm,Xm,rr,Ru,Qm,nr,Jm,or,ir=R(()=>{\"use strict\";te();oe();ae();lt();on();er();Zm=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart / innerElementSize + inputCol${t?\", batchIndices\":\"\"});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRow + innerRow,\n kStart / innerElementSize + inputCol${t?\", batchIndices\":\"\"});\n `,Xm=(e,t)=>e?`\n let ACached0 = mm_Asub[k * innerElementSize][localRow];\n let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];\n let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];\n ${t===3?\"\":\"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];\"}\n for (var i = 0; i < rowPerThread; i = i + 1) {\n acc[i] = BCached0 * ACached0[i] + acc[i];\n acc[i] = BCached1 * ACached1[i] + acc[i];\n acc[i] = BCached2 * ACached2[i] + acc[i];\n ${t===3?\"\":\"acc[i] = BCached3 * ACached3[i] + acc[i];\"}\n }`:`\n for (var i = 0; i < rowPerThread; i = i + 1) {\n let ACached = mm_Asub[tileRow + i][k];\n acc[i] = BCached0 * ACached.x + acc[i];\n acc[i] = BCached1 * ACached.y + acc[i];\n acc[i] = BCached2 * ACached.z + acc[i];\n ${t===3?\"\":\"acc[i] = BCached3 * ACached.w + acc[i];\"}\n }`,rr=(e,t,r=\"f32\",n,o=!1,i=32,a=!1,l=32)=>{let d=t[1]*e[1],c=t[0]*e[0],m=o?d:i,u=o?i:d,h=m/t[0],w=i/t[1];if(!((o&&h===4&&e[1]===4||!o&&(h===3||h===4))&&m%t[0]===0&&i%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${h} and workPerThread[1] ${e[1]} must be 4.\n Otherwise, innerElementSize ${h} must be 3 or 4.\n tileAWidth ${m} must be divisible by workgroupSize[0]${t[0]}. tileInner ${i} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`\nvar mm_Asub: array, ${m/h}>, ${u}>;\nvar mm_Bsub: array, ${c/e[0]}>, ${i}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${h};\nconst tileInner = ${i};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let localRow = i32(localId.y);\n let tileRow = localRow * rowPerThread;\n let tileCol = i32(localId.x);\n\n let globalRow =i32(globalId.y) * rowPerThread;\n let globalCol = i32(globalId.x);\n let batch = ${a?\"0\":\"i32(globalId.z)\"};\n ${n?`let batchIndices = ${n.offsetToIndices(\"u32(batch)\")};`:\"\"}\n let globalRowStart = i32(workgroupId.y) * ${d};\n\n let num_tiles = ${a?`${Math.ceil(l/i)}`:\"(uniforms.dim_inner - 1) / tileInner + 1\"};\n var kStart = ${a?`i32(globalId.z) * ${l}`:\"0\"};\n\n var acc: array, rowPerThread>;\n\n // Loop over shared dimension.\n let tileRowB = localRow * ${w};\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileCol;\n ${Zm(o,n)}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?\", batchIndices\":\"\"});\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {\n let BCached0 = mm_Bsub[k * innerElementSize][tileCol];\n let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];\n let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];\n ${h===3?\"\":\"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];\"}\n\n ${Xm(o,h)}\n }\n\n workgroupBarrier();\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);\n }\n}`},Ru=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart + inputCol${t?\", batchIndices\":\"\"});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRowStart + inputRow,\n kStart + inputCol${t?\", batchIndices\":\"\"});\n `,Qm=e=>e?\"let ACached = mm_Asub[k][tileRow + innerRow];\":\"let ACached = mm_Asub[tileRow + innerRow][k];\",nr=(e,t,r=\"f32\",n,o=!1,i=32,a=!1,l=32,d=!1)=>{let c=e[1]*t[1],m=e[0]*t[0],u=o?c:i,h=o?i:c;if(!(h%t[1]===0&&u%t[0]===0&&i%t[1]===0))throw new Error(`tileAHight ${h} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${u} must be divisible by workgroupSize[0]${t[0]}, tileInner ${i} must be divisible by workgroupSize[1]${t[1]}`);let w=h/t[1],y=u/t[0],g=i/t[1],x=d?`\n let localRow = i32(localId.y);\n let localCol = i32(localId.x);\n let globalRowStart = i32(workgroupId.y) * ${c};\n let globalColStart = i32(workgroupId.x) * ${m};\n\n // Loop over shared dimension.\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var inputRow = localRow; inputRow < ${h}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${t[0]}) {\n ${Ru(o,n)}\n }\n }\n // Load one tile of B into local memory.\n for (var inputRow = localRow; inputRow < ${i}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${m}; inputCol = inputCol + ${t[0]}) {\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalColStart + inputCol${n?\", batchIndices\":\"\"});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] +\n ACached * BCached[innerCol];\n }\n }\n }\n workgroupBarrier();\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let gRow = globalRowStart + localRow + innerRow * ${t[1]};\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let gCol = globalColStart + localCol + innerCol * ${t[0]};\n mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);\n }\n }\n `:`\nlet tileRow = i32(localId.y) * rowPerThread;\nlet tileCol = i32(localId.x) * colPerThread;\n\nlet globalRow = i32(globalId.y) * rowPerThread;\nlet globalCol = i32(globalId.x) * colPerThread;\nlet globalRowStart = i32(workgroupId.y) * ${c};\n\nlet tileRowA = i32(localId.y) * ${w};\nlet tileColA = i32(localId.x) * ${y};\nlet tileRowB = i32(localId.y) * ${g};\n// Loop over shared dimension.\nfor (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${y}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${Ru(o,n)}\n }\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${g}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol + innerCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalCol + innerCol${n?\", batchIndices\":\"\"});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][tileCol + inner];\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n ${Qm(o)}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];\n }\n }\n }\n\n workgroupBarrier();\n}\n\nfor (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n mm_write(batch, globalRow + innerRow, globalCol + innerCol,\n acc[innerRow][innerCol]);\n }\n}\n`;return`\n var mm_Asub : array, ${h}>;\n var mm_Bsub : array, ${i}>;\n const rowPerThread = ${e[1]};\n const colPerThread = ${e[0]};\n const tileInner = ${i};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let batch = ${a?\"0\":\"i32(globalId.z)\"};\n ${n?`let batchIndices = ${n.offsetToIndices(\"u32(batch)\")};`:\"\"}\n let num_tiles = ${a?`${Math.ceil(l/i)}`:\"(uniforms.dim_inner - 1) / tileInner + 1\"};\n var kStart = ${a?`i32(globalId.z) * ${l}`:\"0\"};\n\n var acc : array, rowPerThread>;\n ${x}\n }\n`},Jm=(e,t,r,n,o=!1)=>{let[i,a,l,d]=n,c=me(n[0].type.tensor);return`\n fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${ze(e,c)} {\n var value = ${ze(e,c)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)\n {\n var aIndices: ${a.type.indices};\n ${tr(\"aIndices\",a,a.rank-2,i.rank,\"batchIndices\")}\n ${a.indicesSet(\"aIndices\",a.rank-2,\"u32(row)\")}\n ${a.indicesSet(\"aIndices\",a.rank-1,\"u32(colIn)\")}\n value = ${a.getByIndices(\"aIndices\")};\n }\n return value;\n }\n\n fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${ze(e,c)} {\n var value = ${ze(e,c)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)\n {\n var bIndices: ${l.type.indices};\n ${tr(\"bIndices\",l,l.rank-2,i.rank,\"batchIndices\")}\n ${l.indicesSet(\"bIndices\",l.rank-2,\"u32(row)\")}\n ${l.indicesSet(\"bIndices\",l.rank-1,\"u32(colIn)\")}\n value = ${l.getByIndices(\"bIndices\")};\n }\n return value;\n }\n\n fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${ze(e,c)}) {\n let col = colIn * ${e};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueIn;\n let coords = vec3(batch, row, colIn);\n ${t?`value = value + ${o?\"bias[colIn]\":`${ze(e,c)}(bias[row])`};`:\"\"}\n ${r}\n ${d.setByIndices(\"vec3(coords)\",\"value\")}\n }\n }\n `},or=(e,t,r,n,o=!1,i)=>{let a=e[0].dims,l=e[1].dims,d=a.slice(0,-2),c=l.slice(0,-2),m=n?n.slice(0,-2):r.slice(0,-2),u=k.size(m),h=a[a.length-2],w=a[a.length-1],y=l[l.length-1],g=w%4===0&&y%4===0,x=h<=8?[4,1,1]:[4,4,1],$=[8,8,1],v=[Math.ceil(y/$[0]/x[0]),Math.ceil(h/$[1]/x[1]),Math.ceil(u/$[2]/x[2])],S=g?4:1,T=[...d,h,w/S],C=T.length,A=[...c,w,y/S],P=A.length,O=[u,h,y/S],U=[{type:6,data:h},{type:6,data:y},{type:6,data:w}];Ne(t,U),U.push(...V(m,T,A));let L=[\"rank\",\"rank\"],j=e.length>2;j&&(U.push(...V(e[2].dims)),L.push(\"rank\")),U.push(...V(O));let K=W=>{let ee=m.length,ue=Kr(\"batchDims\",e[0].dataType,ee,1),Z=me(e[0].dataType),J=E(\"a\",e[0].dataType,C,S),Q=E(\"b\",e[1].dataType,P,S),ne=M(\"result\",e[0].dataType,O.length,S),we=[J,Q];if(j){let q=o?S:1;we.push(E(\"bias\",e[2].dataType,e[2].dims.length,q))}let Ae=[{name:\"dim_a_outer\",type:\"i32\"},{name:\"dim_b_outer\",type:\"i32\"},{name:\"dim_inner\",type:\"i32\"}];We(t,Ae);let $e=me(ne.type.tensor),de=Ve(t,ne.type.value,$e),N=Jm(S,j,de,[ue,J,Q,ne],o);return`\n ${W.registerUniforms(Ae).registerInternalVariables(ue).declareVariables(...we,ne)}\n ${N}\n ${g?rr(x,$,Z,ue):nr(x,$,Z,ue)}\n `};return{name:\"MatMul\",shaderCache:{hint:`${x};${t.activation};${g};${o}`,inputDependencies:L},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:v[0],y:v[1],z:v[2]},programUniforms:U}),getShaderSource:K}}});var ef,Uu,Vu=R(()=>{\"use strict\";te();je();ae();lt();er();_o();ir();ef=(e,t,r,n,o=!1,i,a=4,l=4,d=4,c=\"f32\")=>{let m=L=>{switch(L){case 1:return\"resData = x[xIndex];\";case 3:return`resData = vec3<${c}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return\"resData = x[xIndex / 4];\";default:throw new Error(`innerElementSize ${L} is not supported.`)}},u=L=>{switch(L){case 1:return\"return w[row * i32(uniforms.w_shape[3]) + colIn];\";case 4:return\"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];\";default:throw new Error(`innerElementSize ${L} is not supported.`)}},h=e?`\n let coord = vec4(batch, xRow, xCol, xCh);\n `:`\n let coord = vec4(batch, xCh, xRow, xCol);\n `,w=e?`\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n `:`\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n `,y=e?\"i32(uniforms.x_shape[1])\":\"i32(uniforms.x_shape[2])\",g=e?\"i32(uniforms.x_shape[2])\":\"i32(uniforms.x_shape[3])\",x=e?\"row\":\"col\",$=e?\"col\":\"row\",v=`\n let inChannels = i32(uniforms.w_shape[2]);\n let outWidth = ${e?\"i32(uniforms.result_shape[2])\":\"i32(uniforms.result_shape[3])\"};\n let outRow = ${x} / outWidth;\n let outCol = ${x} % outWidth;\n\n let WRow = ${$} / (i32(uniforms.w_shape[1]) * inChannels);\n let WCol = ${$} / inChannels % i32(uniforms.w_shape[1]);\n let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];\n let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];\n let xCh = ${$} % inChannels;\n var resData = ${ze(a,c)}(0.0);\n // The bounds checking is always needed since we use it to pad zero for\n // the 'same' padding type.\n if (xRow >= 0 && xRow < ${y} && xCol >= 0 && xCol < ${g}) {\n ${h}\n let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape));\n ${m(a)}\n }\n return resData;`,S=e?t&&n?`\n let col = colIn * ${a};\n ${v}`:`\n let col = colIn * ${a};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${v}\n }\n return ${ze(a,c)}(0.0);`:n&&r?`\n let col = colIn * ${a};\n ${v}`:`\n let col = colIn * ${a};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${v}\n }\n return ${ze(a,c)}(0.0);`,T=`${u(l)}`,C=ze(d,c),A=e?ze(a,c):ze(l,c),P=e?ze(l,c):ze(a,c),O=Ve(i,C,c);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${A} {\n ${e?S:T}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${P} {\n ${e?T:S}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${C}) {\n let col = colIn * ${d};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)\n {\n var value = valueIn;\n let outWidth = ${e?\"i32(uniforms.result_shape[2])\":\"i32(uniforms.result_shape[3])\"};\n ${w}\n ${tn(o)}\n ${O}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`},Uu=(e,t,r,n,o,i,a,l,d)=>{let c=t.format===\"NHWC\",m=c?e[0].dims[3]:e[0].dims[1],u=r[0],h=c?r[2]:r[3],w=c?r[1]:r[2],y=c?r[3]:r[1],g=c&&(m%4===0||m%3===0)&&y%4===0,x=c?y:h*w,$=c?h*w:y,v=[8,8,1],S=n<=8?[4,1,1]:[4,4,1],T=[Math.ceil(x/v[0]/S[0]),Math.ceil($/v[1]/S[1]),Math.ceil(u/v[2]/S[2])];se(\"verbose\",()=>`[conv2d_mm_webgpu] dispatch = ${T}`);let C=g?c&&m%4!==0?3:4:1,A=v[1]*S[1],P=v[0]*S[0],O=Math.max(v[0]*C,v[1]),U=n%A===0,L=o%P===0,j=i%O===0,K=g?[C,4,4]:[1,1,1],W=[{type:6,data:n},{type:6,data:o},{type:6,data:i},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Ne(t,W),W.push(...V(e[0].dims,e[1].dims));let ee=[\"rank\",\"rank\"];a&&(W.push(...V(e[2].dims)),ee.push(\"rank\")),W.push(...V(r));let ue=Z=>{let J=[{name:\"dim_a_outer\",type:\"i32\"},{name:\"dim_b_outer\",type:\"i32\"},{name:\"dim_inner\",type:\"i32\"},{name:\"pad\",type:\"i32\",length:2},{name:\"stride\",type:\"i32\",length:2},{name:\"dilation\",type:\"i32\",length:2}];We(t,J);let Q=g?4:1,ne=me(e[0].dataType),we=`\n fn setOutputAtIndex(flatIndex : i32, value : ${g?`vec4<${ne}>`:ne}) {\n result[flatIndex] = ${g?`vec4<${ne}>`:ne}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${g?`vec4<${ne}>`:ne}) {\n let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${g?\"/ 4\":\"\"}, value);\n }`,Ae=E(\"x\",e[0].dataType,e[0].dims.length,C===3?1:C),$e=E(\"w\",e[1].dataType,e[1].dims.length,Q),de=[Ae,$e],N=M(\"result\",e[0].dataType,r.length,Q);if(a){let q=E(\"bias\",e[2].dataType,e[2].dims.length,Q);de.push(q),we+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${g?`vec4<${ne}>`:ne} {\n return bias[coords.${c?\"w\":\"y\"}${g?\"/ 4\":\"\"}];\n }`}return`\n ${rn(\"uniforms.result_strides\")}\n //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4,\n // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2,\n // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };\n ${Z.registerUniforms(J).declareVariables(...de,N)}\n ${we}\n ${ef(c,U,L,j,a,t,K[0],K[1],K[2],ne)}\n ${g?rr(S,v,ne,void 0,!c,O):nr(S,v,ne,void 0,!c,O,!1,void 0,l)}`};return{name:\"Conv2DMatMul\",shaderCache:{hint:`${t.cacheKey};${C};${g};${U};${L};${j};${A};${P};${O}`,inputDependencies:ee},getRunData:()=>({outputs:[{dims:d?d(r):r,dataType:e[0].dataType}],dispatchGroup:{x:T[0],y:T[1],z:T[2]},programUniforms:W}),getShaderSource:ue}}});var tf,Nu,an,rf,Wu,nf,Lu,Gu,Hu=R(()=>{\"use strict\";te();je();oe();ae();lt();er();tf=e=>{let t=1;for(let r=0;rtypeof e==\"number\"?[e,e,e]:e,an=(e,t)=>t<=1?e:e+(e-1)*(t-1),rf=(e,t,r,n=1)=>{let o=an(t,n);return Math.floor((e[0]*(r-1)-r+o)/2)},Wu=(e,t,r,n,o)=>{o==null&&(o=rf(e,t[0],n[0]));let i=[0,0,0,r];for(let a=0;a<3;a++)e[a]+2*o>=t[a]&&(i[a]=Math.trunc((e[a]-t[a]+2*o)/n[a]+1));return i},nf=(e,t,r,n,o,i,a,l,d,c)=>{let m,u,h,w;if(e===\"VALID\"&&(e=0),typeof e==\"number\"){m={top:e,bottom:e,left:e,right:e,front:e,back:e};let y=Wu([t,r,n,1],[l,d,c],1,[o,i,a],e);u=y[0],h=y[1],w=y[2]}else if(Array.isArray(e)){if(!e.every((g,x,$)=>g===$[0]))throw Error(`Unsupported padding parameter: ${e}`);m={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let y=Wu([t,r,n,1],[l,d,c],1,[o,i,a],e[0]);u=y[0],h=y[1],w=y[2]}else if(e===\"SAME_UPPER\"){u=Math.ceil(t/o),h=Math.ceil(r/i),w=Math.ceil(n/a);let y=(u-1)*o+l-t,g=(h-1)*i+d-r,x=(w-1)*a+c-n,$=Math.floor(y/2),v=y-$,S=Math.floor(g/2),T=g-S,C=Math.floor(x/2),A=x-C;m={top:S,bottom:T,left:C,right:A,front:$,back:v}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:m,outDepth:u,outHeight:h,outWidth:w}},Lu=(e,t,r,n,o,i=!1,a=\"channelsLast\")=>{let l,d,c,m,u;if(a===\"channelsLast\")[l,d,c,m,u]=e;else if(a===\"channelsFirst\")[l,u,d,c,m]=e;else throw new Error(`Unknown dataFormat ${a}`);let[h,,w,y,g]=t,[x,$,v]=Nu(r),[S,T,C]=Nu(n),A=an(w,S),P=an(y,T),O=an(g,C),{padInfo:U,outDepth:L,outHeight:j,outWidth:K}=nf(o,d,c,m,x,$,v,A,P,O),W=i?h*u:h,ee=[0,0,0,0,0];return a===\"channelsFirst\"?ee=[l,W,L,j,K]:a===\"channelsLast\"&&(ee=[l,L,j,K,W]),{batchSize:l,dataFormat:a,inDepth:d,inHeight:c,inWidth:m,inChannels:u,outDepth:L,outHeight:j,outWidth:K,outChannels:W,padInfo:U,strideDepth:x,strideHeight:$,strideWidth:v,filterDepth:w,filterHeight:y,filterWidth:g,effectiveFilterDepth:A,effectiveFilterHeight:P,effectiveFilterWidth:O,dilationDepth:S,dilationHeight:T,dilationWidth:C,inShape:e,outShape:ee,filterShape:t}},Gu=(e,t,r,n,o,i)=>{let a=i===\"channelsLast\",l=a?e[0].dims[3]:e[0].dims[1],d=!1,c=[64,1,1],m={x:r.map((v,S)=>S)},u=[Math.ceil(tf(m.x.map(v=>r[v]))/c[0]),1,1];se(\"verbose\",()=>`[conv3d_naive_webgpu] dispatch = ${u}`);let h=d?a&&l%4!==0?3:4:1,w=k.size(r),y=[{type:12,data:w},{type:12,data:n},{type:12,data:o},{type:12,data:t.strides},{type:12,data:t.dilations}];Ne(t,y),y.push(...V(e[0].dims,e[1].dims));let g=[\"rank\",\"rank\"],x=e.length===3;x&&(y.push(...V(e[2].dims)),g.push(\"rank\")),y.push(...V(r));let $=v=>{let S=[{name:\"output_size\",type:\"u32\"},{name:\"filter_dims\",type:\"u32\",length:n.length},{name:\"pads\",type:\"u32\",length:o.length},{name:\"strides\",type:\"u32\",length:t.strides.length},{name:\"dilations\",type:\"u32\",length:t.dilations.length}];We(t,S);let T=d?4:1,C=me(e[0].dataType),A=E(\"x\",e[0].dataType,e[0].dims.length,h===3?1:h),P=E(\"W\",e[1].dataType,e[1].dims.length,T),O=[A,P],U=M(\"result\",e[0].dataType,r.length,T),L=\"\";if(x){let W=E(\"bias\",e[2].dataType,e[2].dims.length,T);O.push(W),L+=`\n fn getBiasByOutputCoords(coords : array) -> ${d?`vec4<${C}>`:C} {\n return bias[${a?F(\"coords\",4,5):F(\"coords\",1,5)}${d?\"/ 4\":\"\"}];\n }`}let j=ze(h,C),K=Ve(t,j,C);return`\n ${L}\n fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {\n let aIndices = array(d0, d1, d2, d3, d4);\n return ${A.getByIndices(\"aIndices\")};\n }\n fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {\n let aIndices = array(d0, d1, d2, d3, d4);\n return ${P.getByIndices(\"aIndices\")};\n }\n ${v.registerUniforms(S).declareVariables(...O,U)}\n ${v.mainStart()}\n ${v.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let coords = ${U.offsetToIndices(\"global_idx\")};\n let batch = ${F(\"coords\",0,A.rank)};\n let d2 = ${a?F(\"coords\",A.rank-1,A.rank):F(\"coords\",1,A.rank)};\n let xFRCCorner = vec3(${a?F(\"coords\",1,A.rank):F(\"coords\",2,A.rank)},\n ${a?F(\"coords\",2,A.rank):F(\"coords\",3,A.rank)},\n ${a?F(\"coords\",3,A.rank):F(\"coords\",4,A.rank)}) * uniforms.strides - uniforms.pads;\n let xFCorner = xFRCCorner.x;\n let xRCorner = xFRCCorner.y;\n let xCCorner = xFRCCorner.z;\n let xShapeY = ${a?F(\"uniforms.x_shape\",1,A.rank):F(\"uniforms.x_shape\",2,A.rank)};\n let xShapeZ = ${a?F(\"uniforms.x_shape\",2,A.rank):F(\"uniforms.x_shape\",3,A.rank)};\n let xShapeW = ${a?F(\"uniforms.x_shape\",3,A.rank):F(\"uniforms.x_shape\",4,A.rank)};\n let xShapeU = ${a?F(\"uniforms.x_shape\",4,A.rank):F(\"uniforms.x_shape\",1,A.rank)};\n let inputDepthNearestVec4 = (xShapeU / 4) * 4;\n let inputDepthVec4Remainder = xShapeU % 4;\n\n var value = 0.0;\n for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) {\n let xF = xFCorner + wF * uniforms.dilations[0];\n if (xF < 0 || xF >= xShapeY) {\n continue;\n }\n\n for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) {\n let xR = xRCorner + wR * uniforms.dilations[1];\n if (xR < 0 || xR >= xShapeZ) {\n continue;\n }\n\n for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) {\n let xC = xCCorner + wC * uniforms.dilations[2];\n if (xC < 0 || xC >= xShapeW) {\n continue;\n }\n\n for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) {\n ${a?`let 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 `:`let xValues = vec4(\n getX(batch, d1, xF, xR, xC),\n getX(batch, d1 + 1, xF, xR, xC),\n getX(batch, d1 + 2, xF, xR, xC),\n getX(batch, d1 + 3, xF, xR, xC));\n `}\n let wValues = vec4(\n getW(d2, d1, wF, wR, wC),\n getW(d2, d1 + 1, wF, wR, wC),\n getW(d2, d1 + 2, wF, wR, wC),\n getW(d2, d1 + 3, wF, wR, wC));\n value += dot(xValues, wValues);\n }\n if (inputDepthVec4Remainder == 1) {\n ${a?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4)\n * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC)\n * getW(d2, inputDepthNearestVec4, wF, wR, wC);`}\n } else if (inputDepthVec4Remainder == 2) {\n ${a?`let xValues = vec2(\n getX(batch, xF, xR, xC, inputDepthNearestVec4),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1));\n `:`let xValues = vec2(\n getX(batch, inputDepthNearestVec4, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC));\n `}\n let wValues = vec2(\n getW(d2, inputDepthNearestVec4, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC));\n value += dot(xValues, wValues);\n } else if (inputDepthVec4Remainder == 3) {\n ${a?`let xValues = vec3(\n getX(batch, xF, xR, xC, inputDepthNearestVec4),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2));\n `:`let xValues = vec3(\n getX(batch, inputDepthNearestVec4, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC));\n `}\n let wValues = vec3(\n getW(d2, inputDepthNearestVec4, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC));\n value += dot(xValues, wValues);\n }\n }\n }\n }\n ${x?\"value = value + getBiasByOutputCoords(coords)\":\"\"};\n ${K}\n result[global_idx] = f32(value);\n }`};return{name:\"Conv3DNaive\",shaderCache:{hint:`${t.cacheKey};${a};${h};${x}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:u[0],y:u[1],z:u[2]},programUniforms:y}),getShaderSource:$}}});var Fu,qu,ju=R(()=>{\"use strict\";te();oe();ae();lt();Fu=(e,t,r,n)=>{let o=e.length>2,i=o?\"value += b[output_channel];\":\"\",a=e[0].dims,l=e[1].dims,d=t.format===\"NHWC\",c=d?r[3]:r[1],m=c/t.group,u=d&&m>=4?ye(c):1,h=k.size(r)/u,w=[{type:12,data:h},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:m}];Ne(t,w),w.push(...V(a,[l[0],l[1],l[2],l[3]/u]));let y=o?[\"rank\",\"rank\",\"rank\"]:[\"rank\",\"rank\"];w.push(...V([r[0],r[1],r[2],r[3]/u]));let g=x=>{let $=M(\"output\",e[0].dataType,r.length,u),v=me($.type.tensor),S=Ve(t,$.type.value,v),T=E(\"x\",e[0].dataType,a.length),C=E(\"w\",e[1].dataType,l.length,u),A=[T,C];o&&A.push(E(\"b\",e[2].dataType,e[2].dims,u));let P=[{name:\"output_size\",type:\"u32\"},{name:\"dilations\",type:\"u32\",length:t.dilations.length},{name:\"strides\",type:\"u32\",length:2},{name:\"pads\",type:\"u32\",length:2},{name:\"output_channels_per_group\",type:\"u32\"}];We(t,P);let O=d?`\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) {\n continue;\n }\n\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) {\n let input_channel = in_channel_offset + wInChannel;\n let xVal = ${T.get(\"batch\",\"xHeight\",\"xWidth\",\"input_channel\")};\n let wVal = ${C.get(\"wHeight\",\"wWidth\",\"wInChannel\",\"output_channel\")};\n value += xVal * wVal;\n }\n }\n }\n `:`\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {\n let input_channel = in_channel_offset + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) {\n continue;\n }\n\n let xVal = ${T.get(\"batch\",\"input_channel\",\"xHeight\",\"xWidth\")};\n let wVal = ${C.get(\"output_channel\",\"wInChannel\",\"wHeight\",\"wWidth\")};\n value += xVal * wVal;\n }\n }\n }\n `;return`\n ${x.registerUniforms(P).declareVariables(...A,$)}\n\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let outputIndices = ${$.offsetToIndices(\"global_idx\")};\n let batch: u32 = outputIndices[0];\n let output_channel: u32 = outputIndices[${d?3:1}];\n let xRCCorner: vec2 = vec2(outputIndices[${d?1:2}], outputIndices[${d?2:3}]) * uniforms.strides - uniforms.pads;\n let group_id: u32 = output_channel * ${u} / uniforms.output_channels_per_group;\n var in_channel_offset = group_id * uniforms.w_shape[${d?2:1}];\n\n var value: ${$.type.value} = ${$.type.value}(0);\n ${O}\n ${i}\n ${S}\n ${$.setByOffset(\"global_idx\",\"value\")}\n }`};return{name:\"GroupedConv\",shaderCache:{hint:`${t.cacheKey}_${u}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:w}),getShaderSource:g}},qu=(e,t,r,n)=>{let o=e.length>2,i=ye(r[3]),a=ye(r[2]),l=k.size(r)/i/a,d=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/i],c=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/i],m=[r[0],r[1],r[2],r[3]/i],u=[{type:12,data:l},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Ne(t,u),u.push(...V(d,c,m));let h=(a-1)*t.strides[1]+c[1],w=y=>{let g=M(\"output\",e[0].dataType,m.length,i),x=me(g.type.tensor),$=Ve(t,g.type.value,x),v=E(\"x\",e[0].dataType,d.length,i),S=E(\"w\",e[1].dataType,c.length,i),T=[v,S];o&&T.push(E(\"b\",e[2].dataType,e[2].dims,i));let C=o?\"value += b[output_channel];\":\"\",A=[{name:\"output_size\",type:\"u32\"},{name:\"strides\",type:\"i32\",length:2},{name:\"pads\",type:\"i32\",length:2}];return We(t,A),`\n ${y.registerUniforms(A).declareVariables(...T,g)}\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let width0 = uniforms.output_shape[3];\n let output_channel = global_idx % width0;\n var index1 = global_idx / width0;\n let width1 = uniforms.output_shape[2] / ${a}u;\n let col = (index1 % width1) * ${a}u;\n index1 = index1 / width1;\n let row = index1 % uniforms.output_shape[1];\n let batch = index1 / uniforms.output_shape[1];\n\n let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads;\n\n var x_vals: array<${v.type.value}, ${h}>;\n var values: array<${g.type.value}, ${a}>;\n let input_channel = output_channel;\n // Use constant instead of uniform can give better performance for w's height/width.\n for (var w_height: u32 = 0u; w_height < ${c[0]}; w_height++) {\n let x_height = x_corner.x + i32(w_height);\n if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {\n for (var i = 0; i < ${h}; i++) {\n let x_width = x_corner.y + i;\n if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {\n x_vals[i] = ${v.get(\"batch\",\"u32(x_height)\",\"u32(x_width)\",\"input_channel\")};\n } else {\n x_vals[i] = ${v.type.value}(0);\n }\n }\n for (var w_width: u32 = 0u; w_width < ${c[1]}; w_width++) {\n let w_val = ${S.get(\"w_height\",\"w_width\",\"0\",\"output_channel\")};\n for (var i = 0u; i < ${a}u; i++) {\n values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);\n }\n }\n }\n }\n\n for (var i = 0u; i < ${a}u; i++) {\n var value = values[i];\n ${C}\n ${$}\n ${g.set(\"batch\",\"row\",\"col + i\",\"output_channel\",\"value\")};\n }\n }`};return{name:\"GroupedConv-Vectorize\",shaderCache:{hint:`${t.cacheKey};${i};${a};${h};${c[0]};${c[1]}`,inputDependencies:o?[\"rank\",\"rank\",\"type\"]:[\"rank\",\"rank\"]},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:w}}});var of,vo,af,$o,xo,Ku,sf,uf,So,Yu=R(()=>{\"use strict\";oe();Vu();Hu();ir();ju();lt();on();ut();of=(e,t,r,n,o,i)=>{let a=e[0],l=e.slice(i?1:2,i?3:4),d=l.length,c=t[0],u=t.slice(2).map((y,g)=>y+(y-1)*(r[g]-1)),w=l.map((y,g)=>y+n[g]+n[g+d]).map((y,g)=>Math.floor((y-u[g]+o[g])/o[g]));return w.splice(0,0,a),w.splice(i?3:1,0,c),w},vo=[2,3,1,0],af=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error(\"Conv requires 2 or 3 inputs\");if(e[0].dims.length>5)throw new Error(\"greater than 5D is not supported\");if(e[0].dims.length!==e[1].dims.length)throw new Error(\"filter does not have same dimension as input\");let r=e[0].dims[t.format===\"NHWC\"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(r!==n)throw new Error(\"FILTER_IN_CHANNEL should be equal to DATA_CHANNEL\");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error(\"invalid bias\");let o=e[0].dims.length-2;if(t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error(\"invalid kernel shape\")},$o=(e,t)=>{let r=e.kernelShape.slice();r.length{let t=en(e),r=e.format,n=[\"NOTSET\",\"VALID\",\"SAME_UPPER\",\"SAME_LOWER\"][e.auto_pad],o=e.dilations,i=e.group,a=e.kernel_shape,l=e.pads,d=e.strides,c=e.w_is_const();return{autoPad:n,format:r,dilations:o,group:i,kernelShape:a,pads:l,strides:d,wIsConst:c,...t,cacheKey:`${e.format};${t.activation};`}},Ku=(e,t,r,n)=>{let o=r.format===\"NHWC\",i=of(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,o);if(r.group!==1){let A=[t[0]];if(o){let O=e.kernelCustomData.wT??e.compute(Pe(t[1],vo),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=O),A.push(O)}else A.push(t[1]);t.length===3&&A.push(t[2]),!e.adapterInfo.isArchitecture(\"ampere\")&&o&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(qu(A,r,i,n),{inputs:A}):e.compute(Fu(A,r,i,n),{inputs:A});return}let a=t.length===3,l=t[0].dims[o?1:2],d=t[0].dims[o?2:3],c=t[0].dims[o?3:1],m=t[1].dims[2],u=t[1].dims[3],h=i[o?1:2],w=i[o?2:3],y=i[o?3:1],g=o&&m===l&&u===d&&r.pads[0]===0&&r.pads[1]===0;if(g||m===1&&u===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let A=i[0],P,O,U,L=[];if(o){let W=e.kernelCustomData.wT??e.compute(Pe(t[1],vo),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=W),g){let ee=l*d*c;P=t[0].reshape([1,A,ee]),O=W.reshape([1,ee,y]),U=[1,A,y]}else P=t[0].reshape([A,l*d,c]),O=W.reshape([1,c,y]),U=[A,h*w,y];L.push(P),L.push(O)}else P=t[0].reshape([A,c,l*d]),O=t[1].reshape([1,y,c]),U=[A,y,h*w],L.push(O),L.push(P);a&&L.push(t[2]);let j=U[2],K=L[0].dims[L[0].dims.length-1];j<8&&K<8?e.compute(nn(L,r,i,U,o,n),{inputs:L}):e.compute(or(L,r,i,U,o,n),{inputs:L});return}let x=!0,$=e.kernelCustomData.wT??e.compute(Pe(t[1],vo),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=$);let v=[t[0],$];a&&v.push(t[2]);let S=o?h*w:y,T=o?y:h*w,C=m*u*c;e.compute(Uu(v,r,i,S,T,C,a,x,n),{inputs:v})},sf=(e,t)=>{let r=t.format===\"NHWC\",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=[0,t.pads[0],0,t.pads[1]],i=[1].concat(t.strides),a=[1].concat(t.dilations),l=[1].concat(t.kernelShape),d=$o({...t,pads:o,strides:i,dilations:a,kernelShape:l},n);Ku(e,n,d,c=>r?[c[0],c[2],c[3]]:[c[0],c[1],c[3]])},uf=(e,t,r)=>{let n=r.format===\"NHWC\"?\"channelsLast\":\"channelsFirst\",o=$o(r,t),i=r.autoPad===\"NOTSET\"?r.pads:r.autoPad,a=Lu(t[0].dims,t[1].dims,r.strides,r.dilations,i,!1,n);e.compute(Gu(t,o,a.outShape,[a.filterDepth,a.filterHeight,a.filterWidth],[a.padInfo.front,a.padInfo.top,a.padInfo.left],n))},So=(e,t)=>{if(af(e.inputs,t),e.inputs[0].dims.length===3)sf(e,t);else if(e.inputs[0].dims.length===5)uf(e,e.inputs,t);else{let r=$o(t,e.inputs);Ku(e,e.inputs,r)}}});var lf,Zu,Xu=R(()=>{\"use strict\";te();je();ae();lt();er();_o();ir();lf=(e,t=!1,r,n,o=4)=>{let i=$=>{switch($){case 1:return\"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];\";case 4:return`\n let coord1 = vec4(coordX, coordY, col + 1, rowInner);\n let coord2 = vec4(coordX, coordY, col + 2, rowInner);\n let coord3 = vec4(coordX, coordY, col + 3, rowInner);\n let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];\n let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))];\n let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))];\n let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))];\n return ${n}(v0, v1, v2, v3);\n `;default:throw new Error(`innerElementSize ${$} is not supported.`)}},a=e?`\n let coord = vec4(batch, iXR, iXC, xCh);\n `:`\n let coord = vec4(batch, xCh, iXR, iXC);\n `,l=e?`\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n `:`\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n `,d=e?\"i32(uniforms.x_shape[1])\":\"i32(uniforms.x_shape[2])\",c=e?\"i32(uniforms.x_shape[2])\":\"i32(uniforms.x_shape[3])\",m=e?\"row\":\"col\",u=e?\"col\":\"row\",h=`\n let inChannels = ${e?\"i32(uniforms.x_shape[3])\":\"i32(uniforms.x_shape[1])\"};\n let outWidth = ${e?\"i32(uniforms.result_shape[2])\":\"i32(uniforms.result_shape[3])\"};\n let outRow = ${m} / outWidth;\n let outCol = ${m} % outWidth;\n\n let WRow = ${u} / (uniforms.filter_dims[1] * inChannels);\n let WCol = ${u} / inChannels % uniforms.filter_dims[1];\n let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]);\n let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]);\n if (xR < 0.0 || xR >= f32(${d}) || fract(xR) > 0.0) {\n return ${n}(0.0);\n }\n if (xC < 0.0 || xC >= f32(${c}) || fract(xC) > 0.0) {\n return ${n}(0.0);\n }\n let iXR = i32(xR);\n let iXC = i32(xC);\n let xCh = ${u} % inChannels;\n ${a}\n return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${o}];`,w=e?`\n let col = colIn * ${o};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${h}\n }\n return ${n}(0.0);`:`\n let col = colIn * ${o};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${h}\n }\n return ${n}(0.0);`,y=`\n let col = colIn * ${o};\n let inChannels = ${e?\"i32(uniforms.x_shape[3])\":\"i32(uniforms.x_shape[1])\"};\n let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels);\n let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1];\n if (${e?\"row < uniforms.dim_inner && col < uniforms.dim_b_outer\":\"row < uniforms.dim_inner && col < uniforms.dim_a_outer\"} && coordX >= 0 && coordY >= 0) {\n let rowInner = row % inChannels;\n let coord = vec4(coordX, coordY, col, rowInner);\n ${i(o)}\n }\n return ${n}(0.0);\n `,g=Ve(r,n);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} {\n ${e?w:y}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} {\n ${e?y:w}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) {\n let col = colIn * ${o};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueInput;\n let outWidth = ${e?\"i32(uniforms.result_shape[2])\":\"i32(uniforms.result_shape[3])\"};\n ${l}\n ${tn(t)}\n ${g}\n result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${o}] = value;\n }\n }`},Zu=(e,t,r,n,o,i,a,l)=>{let d=t.format===\"NHWC\",c=d?e[0].dims[3]:e[0].dims[1],m=r[0],u=d?r[2]:r[3],h=d?r[1]:r[2],w=d?r[3]:r[1],y=d&&c%4===0&&c%3&&w%4===0,g=d?w:u*h,x=d?u*h:w,$=[8,8,1],v=n<=8?[4,1,1]:[4,4,1],S=[Math.ceil(g/$[0]/v[0]),Math.ceil(x/$[1]/v[1]),Math.ceil(m/$[2]/v[2])];se(\"verbose\",()=>`[conv_backprop_mm_webgpu] dispatch = ${S}`);let T=y?4:1,C=Math.max($[0]*T,$[1]),A=y?4:1,P=[t.kernelShape[d?1:2],t.kernelShape[d?2:3]],O=[P[0]+(t.dilations[0]<=1?0:(P[0]-1)*(t.dilations[0]-1)),P[1]+(t.dilations[1]<=1?0:(P[1]-1)*(t.dilations[1]-1))],U=[O[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),O[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],L=[{type:6,data:n},{type:6,data:o},{type:6,data:i},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:P},{type:6,data:U}];Ne(t,L),L.push(...V(e[0].dims,e[1].dims));let j=[\"rank\",\"rank\"];a&&(L.push(...V(e[2].dims)),j.push(\"rank\")),L.push(...V(r));let K=W=>{let ee=E(\"x\",e[0].dataType,e[0].dims.length,A),ue=E(\"w\",e[1].dataType,e[1].dims.length,1),Z=M(\"result\",e[0].dataType,r.length,A),J=[ee,ue],Q=\"\";if(a){let Ae=E(\"bias\",e[2].dataType,e[2].dims.length,A);J.push(Ae),Q+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${Ae.type.value} {\n return bias[coords.${d?\"w\":\"y\"}${y?\"/ 4\":\"\"}];\n }`}let ne=[{name:\"dim_a_outer\",type:\"i32\"},{name:\"dim_b_outer\",type:\"i32\"},{name:\"dim_inner\",type:\"i32\"},{name:\"strides\",type:\"i32\",length:2},{name:\"dilations\",type:\"i32\",length:2},{name:\"filter_dims\",type:\"i32\",length:P.length},{name:\"pads\",type:\"i32\",length:U.length}];We(t,ne);let we=me(e[0].dataType,1);if(we!==\"f16\"&&we!==\"f32\")throw new Error(`elemType ${we} is not supported.`);return`\n ${rn(\"uniforms.result_strides\")}\n ${W.registerUniforms(ne).declareVariables(...J,Z)};\n ${Q}\n ${lf(d,a,t,ee.type.value,T)}\n ${y?rr(v,$,we,void 0,!d,C):nr(v,$,we,void 0,!d,C,!1,void 0,l)}`};return{name:\"Conv2DTransposeMatMul\",shaderCache:{hint:`${t.cacheKey};${v};${$};${y}`,inputDependencies:j},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:S[0],y:S[1],z:S[2]},programUniforms:L}),getShaderSource:K}}});var df,To,Qu=R(()=>{\"use strict\";te();je();oe();ae();df=(e,t,r,n,o,i=!1,a,l,d=!1)=>{let c=d?1:2,m=d?2:3,u=d?3:1,h=i?2:1,w=`\n fn setOutputAtIndex(flatIndex : u32, value : ${i?`vec4<${a}>`:a}) {\n result[flatIndex] = ${i?`vec4<${a}>`:a}(value);\n }`;n&&(w+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${i?`vec4<${a}>`:a} {\n return bias[coords.${d?\"w\":\"y\"}${i?\"/ 4\":\"\"}];\n }`);let y=i?4:1,g=E(\"W\",t[1].dataType,t[1].dims.length,y),x=E(\"Dy\",t[0].dataType,t[0].dims.length,y),$=[x,g];n&&$.push(E(\"bias\",t[2].dataType,[r[u]].length,y));let v=M(\"result\",t[0].dataType,r.length,y),S=`{\n let batch: u32 = ${o?\"global_id.z\":\"workgroup_id.z\"} / uniforms.result_shape[1];\n let r = ${o?\"global_id.z\":\"workgroup_id.z\"} % uniforms.result_shape[1];\n let c = ${o?\"global_id.y\":\"workgroup_id.y\"} * ${h};\n let d1: u32 = ${o?\"global_id.x\":\"workgroup_id.x\"} * 4;\n\n let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads);\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 var dotProd: array, ${h}>;\n for (var i = 0; i < ${h}; i++) {\n dotProd[i] = vec4<${a}>(0.0);\n }\n for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) {\n var dyR = (${a}(dyCorner.x) + ${a}(wR)) / ${a}(uniforms.strides.x);\n let wRPerm = uniforms.filter_dims[0] - 1 - wR;\n if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[1]) ||\n fract(dyR) > 0.0 || wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) {\n let dyC = (${a}(dyCorner.y) + ${a}(wC)) / ${a}(uniforms.strides.y);\n let dyC2 = (${a}(dyCorner.y) + 1.0 + ${a}(wC)) / ${a}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims[1] - 1 - wC;\n if (wCPerm < 0) {\n continue;\n }\n var bDyCVal = true;\n var bDyCVal2 = true;\n if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[2]) ||\n fract(dyC) > 0.0) {\n bDyCVal = false;\n }\n if (dyC2 < 0.0 || dyC2 >= ${a}(uniforms.Dy_shape[2]) ||\n fract(dyC2) > 0.0) {\n bDyCVal2 = false;\n }\n\n let idyC: u32 = u32(dyC);\n let idyC2: u32 = u32(dyC2);\n if (bDyCVal && bDyCVal2) {\n let d2Length = uniforms.Dy_shape[3];\n for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1\",\"d2\")};\n let wValue1 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1 + 1\",\"d2\")};\n let wValue2 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1 + 2\",\"d2\")};\n let wValue3 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1 + 3\",\"d2\")};\n\n var xValue = ${x.get(\"batch\",\"idyR\",\"idyC\",\"d2\")};\n let tmpval = vec4<${a}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n\n xValue = ${x.get(\"batch\",\"idyR\",\"idyC2\",\"d2\")};\n\n dotProd[1] = dotProd[1] + vec4<${a}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n }\n } else if (bDyCVal) {\n let d2Length = uniforms.Dy_shape[${u}];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1\",\"d2\")};\n let wValue1 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1 + 1\",\"d2\")};\n let wValue2 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1 + 2\",\"d2\")};\n let wValue3 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1 + 3\",\"d2\")};\n\n var xValue = ${x.get(\"batch\",\"idyR\",\"idyC\",\"d2\")};\n let tmpval = vec4<${a}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n }\n } else if (bDyCVal2) {\n let d2Length = uniforms.Dy_shape[3];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1\",\"d2\")};\n let wValue1 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1 + 1\",\"d2\")};\n let wValue2 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1 + 2\",\"d2\")};\n let wValue3 = ${g.get(\"u32(wRPerm)\",\"u32(wCPerm)\",\"d1 + 3\",\"d2\")};\n\n var xValue = ${x.get(\"batch\",\"idyR\",\"idyC2\",\"d2\")};\n let tmpval = vec4<${a}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[1] = dotProd[1] + tmpval;\n }\n }\n }\n }\n\n for (var i: u32 = 0; i < ${h}; i = i + 1) {\n let value = dotProd[i] + ${n?\"bias[c+i]\":`vec4<${a}>(0.0)`};\n ${v.set(\"batch\",\"r\",\"c + i\",\"d1\",\"value\")};\n }\n }`,T=`\n let outputIndices = ${v.offsetToIndices(\"global_idx\")};\n let batch = ${v.indicesGet(\"outputIndices\",0)};\n let d1 = ${v.indicesGet(\"outputIndices\",u)};\n let r = ${v.indicesGet(\"outputIndices\",c)};\n let c = ${v.indicesGet(\"outputIndices\",m)};\n let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads;\n let dyRCorner = dyCorner.x;\n let dyCCorner = dyCorner.y;\n let groupId = d1 / uniforms.output_channels_per_group;\n let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;\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 var dotProd = ${a}(0.0);\n for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {\n if (wR % uniforms.dilations.x != 0) {\n continue;\n }\n let dyR = (${a}(dyRCorner) + ${a}(wR)) / ${a}(uniforms.strides[0]);\n let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;\n if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[${c}]) || fract(dyR) > 0.0 ||\n wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {\n if (wC % uniforms.dilations.y != 0) {\n continue;\n }\n let dyC = (${a}(dyCCorner) + ${a}(wC)) / ${a}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;\n if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[${m}]) ||\n fract(dyC) > 0.0 || wCPerm < 0) {\n continue;\n }\n let idyC: u32 = u32(dyC);\n var inputChannel = groupId * uniforms.input_channels_per_group;\n for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) {\n let xValue = ${d?x.get(\"batch\",\"idyR\",\"idyC\",\"inputChannel\"):x.get(\"batch\",\"inputChannel\",\"idyR\",\"idyC\")};\n let wValue = ${g.get(\"inputChannel\",\"wOutChannel\",\"u32(wRPerm)\",\"u32(wCPerm)\")};\n dotProd = dotProd + xValue * wValue;\n inputChannel = inputChannel + 1;\n }\n }\n }\n let value = dotProd + ${n?\"bias[d1]\":`${a}(0.0)`};\n ${v.setByOffset(\"global_idx\",\"value\")};\n `;return`\n ${e.registerUniforms(l).declareVariables(...$,v)}\n ${w}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")};\n ${i?S:T}}`},To=(e,t,r)=>{let n=e.length>2,o=t.outputShape,i=k.size(o),a=[Math.ceil(i/64),1,1];se(\"verbose\",()=>`[conv2d_backprop_webgpu] dispatch = ${a}`);let l=t.format===\"NHWC\",d=[\"rank\",\"rank\"],c=[t.strides[0],t.strides[1]],m=[t.kernelShape[l?1:2],t.kernelShape[l?2:3]],u=[t.dilations[0],t.dilations[1]],h=[m[0]+(t.dilations[0]<=1?0:(t.kernelShape[l?1:2]-1)*(t.dilations[0]-1)),m[1]+(t.dilations[1]<=1?0:(t.kernelShape[l?2:3]-1)*(t.dilations[1]-1))],w=[h[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),h[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],y=!1,g=t.group,x=e[1].dims,$=x[0]/g,v=x[1],S=[{type:12,data:i},{type:12,data:c},{type:12,data:m},{type:12,data:u},{type:12,data:h},{type:6,data:w},{type:12,data:$},{type:12,data:v},...V(e[0].dims,e[1].dims)];n&&(S.push(...V(e[2].dims)),d.push(\"rank\")),S.push(...V(o));let T=a[1]===1&&a[2]===1,C=A=>{let P=[{name:\"output_size\",type:\"u32\"},{name:\"strides\",type:\"u32\",length:c.length},{name:\"filter_dims\",type:\"u32\",length:m.length},{name:\"dilations\",type:\"u32\",length:m.length},{name:\"effective_filter_dims\",type:\"u32\",length:h.length},{name:\"pads\",type:\"i32\",length:w.length},{name:\"input_channels_per_group\",type:\"u32\"},{name:\"output_channels_per_group\",type:\"u32\"}],O=me(e[0].dataType);return`${df(A,e,o,n,T,y,O,P,l)}`};return{name:\"ConvTranspose2D\",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:d},getRunData:()=>({dispatchGroup:{x:a[0],y:a[1],z:a[2]},outputs:[{dims:r?r(o):o,dataType:e[0].dataType}],programUniforms:S}),getShaderSource:C}}});var cf,pf,mf,Ju,el,ff,hf,gf,bf,tl,rl=R(()=>{\"use strict\";Xu();Qu();lt();ut();cf=(e,t,r,n,o,i)=>(e-1)*t+r+(n-1)*o+1-i,pf=(e,t,r,n,o)=>{let i=Math.floor(e/2);t===\"SAME_UPPER\"?(r[n]=i,r[o]=e-i):t===\"SAME_LOWER\"&&(r[n]=e-i,r[o]=i)},mf=(e,t,r,n,o,i,a,l,d,c)=>{let m=e.length-2,u=c.length===0;d.length{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((u,h)=>u*h,1)===0){r.length=0;for(let u=2;uu+h,0)===0){let u=t[0].dims.length-2;d=new Array(u).fill(1)}let c=e.strides.slice();if(c.reduce((u,h)=>u+h,0)===0){let u=t[0].dims.length-2;c=new Array(u).fill(1)}mf(l,r,d,e.autoPad,e.group,o,c,n,a,i);let m=Object.assign({},e);return Object.assign(m,{kernelShape:r,pads:o,outputPadding:a,outputShape:i,dilations:d,strides:c}),m},el=e=>{let t=en(e),r=e.format,n=[\"NOTSET\",\"VALID\",\"SAME_UPPER\",\"SAME_LOWER\"][typeof e.autoPad>\"u\"?0:e.autoPad],o=e.dilations,i=e.group,a=e.kernelShape,l=e.pads,d=e.strides,c=e.wIsConst(),m=e.outputPadding,u=e.outputShape;return{autoPad:n,format:r,dilations:o,group:i,kernelShape:a,outputPadding:m,outputShape:u,pads:l,strides:d,wIsConst:c,...t,cacheKey:`${e.format};${t.activation};`}},ff=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error(\"Conv requires 2 or 3 inputs\");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error(\"currently only support 2-dimensional conv\");if(e[0].dims.length!==e[1].dims.length)throw new Error(\"filter does not have same dimension as input\");let r=e[0].dims[t.format===\"NHWC\"?e[0].dims.length-1:1],n=e[1].dims[0];if(r!==n)throw new Error(\"FILTER_IN_CHANNEL should be equal to DATA_CHANNEL\");let o=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error(\"invalid bias\");let i=e[0].dims.length-2;if(t.dilations.reduce((m,u)=>m+u,0)>0&&t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.reduce((m,u)=>m+u,0)>0&&t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.reduce((m,u)=>m+u,0)>0&&t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.outputPadding.length!==i&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${i}D`);if(t.kernelShape.reduce((m,u)=>m+u,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error(\"invalid kernel shape\");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error(\"invalid output shape\")},hf=[2,3,1,0],gf=(e,t,r)=>{let n=Ju(r,t),o=r.format===\"NHWC\",i=n.outputShape,a=i[o?3:1],l=t[0].dims[o?3:1];if(n.group!==1||a===1&&l===1){e.compute(To(t,n));return}let d=i[o?1:2],c=i[o?2:3],m=t[1].dims[2],u=t[1].dims[3],h=o?d*c:a,w=o?a:d*c,y=m*u*l,g=!0,x=e.kernelCustomData.wT??e.compute(Pe(t[1],hf),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=x);let $=[t[0],x],v=t.length===3;v&&(!o&&t[2].dims.length===1?$.push(t[2].reshape([t[2].dims[0],1,1])):$.push(t[2])),e.compute(Zu($,n,i,h,w,y,v,g),{inputs:$})},bf=(e,t)=>{let r=t.format===\"NHWC\",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=t.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let i=t.dilations;(i.length===0||i[0]===0)&&(i=[1]);let a=t.strides;(a.length===0||a[0]===0)&&(a=[1]);let l=t.pads;l.length===0&&(l=[0,0]),l=[0,l[0],0,l[1]],a=[1].concat(a),i=[1].concat(i),o=[1].concat(o);let d=Ju({...t,pads:l,strides:a,dilations:i,kernelShape:o},n);e.compute(To(n,d,c=>r?[c[0],c[2],c[3]]:[c[0],c[1],c[3]]))},tl=(e,t)=>{ff(e.inputs,t),e.inputs[0].dims.length===3?bf(e,t):gf(e,e.inputs,t)}});var yf,nl,ol,il=R(()=>{\"use strict\";te();oe();Ie();ae();yf=(e,t,r,n)=>{let o=k.size(t),i=t.length,a=E(\"input\",e,i),l=M(\"output\",e,i),d=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),c=k.normalizeAxis(d,i),m=u=>{let h=` i32(${a.indicesGet(\"inputIndices\",\"uniforms.axis\")}) `,w=F(\"uniforms.input_shape\",\"uniforms.axis\",i),y=n.reverse?h+(n.exclusive?\" + 1\":\"\"):\"0\",g=n.reverse?w:h+(n.exclusive?\"\":\" + 1\");return`\n ${u.registerUniform(\"outputSize\",\"u32\").registerUniform(\"axis\",\"u32\").declareVariables(a,l)}\n ${u.mainStart()}\n ${u.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n var inputIndices = ${l.offsetToIndices(\"global_idx\")};\n var sum = ${l.type.value}(0);\n let first : i32 = ${y};\n let last : i32 = ${g};\n for (var i : i32 = first; i < last; i++) {\n ${a.indicesSet(\"inputIndices\",\"uniforms.axis\",\"u32(i)\")};\n sum = sum + ${a.getByIndices(\"inputIndices\")};\n }\n ${l.setByOffset(\"global_idx\",\"sum\")};\n }`};return{name:\"CumSum\",shaderCache:{hint:n.cacheKey,inputDependencies:[\"rank\"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:c},...V(t,t)]}),getShaderSource:m}},nl=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,o=e.inputs[1];e.compute(yf(n,r,o,t),{inputs:[0]})},ol=e=>{let t=e.exclusive===1,r=e.reverse===1;return re({exclusive:t,reverse:r})}});var wf,_f,vf,al,sl,ul=R(()=>{\"use strict\";te();oe();Ie();ae();wf=e=>{if(!e||e.length!==1)throw new Error(\"DepthToSpace requires 1 input.\");if(e[0].dims.length!==4)throw new Error(\"DepthToSpace requires 4D input.\")},_f=(e,t,r,n)=>{let o=[];o.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} {\n var a: ${r.type.indices};`);for(let i=0;i{let r,n,o,i,a,l,d=t.format===\"NHWC\",c=t.blocksize,m=t.mode===\"DCR\";d?([r,n,o,i]=e.dims,a=m?[r,n,o,c,c,i/c**2]:[r,n,o,i/c**2,c,c],l=m?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,o,i]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],a=m?[r,c,c,i/c**2,n,o]:[r,i/c**2,c,c,n,o],l=m?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let u=e.reshape(a),h=u.dims.length,w=e.dataType,y=E(\"a\",w,h),g=M(\"output\",w,h),x=$=>`\n ${$.registerUniform(\"output_size\",\"u32\").declareVariables(y,g)}\n\n ${_f(l,h,y,g)}\n\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let indices = ${g.offsetToIndices(\"global_idx\")};\n let aIndices = perm(indices);\n\n ${g.setByOffset(\"global_idx\",y.getByIndices(\"aIndices\"))}\n }`;return{name:\"DepthToSpace\",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:[\"rank\"]},getRunData:$=>{let v=d?[r,n*c,o*c,i/c**2]:[r,i/c**2,n*c,o*c],S=k.size(v),T=u.dims,C=k.sortBasedOnPerm(T,l);return{outputs:[{dims:v,dataType:$[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...V(T,C)]}},getShaderSource:x}},al=(e,t)=>{wf(e.inputs),e.compute(vf(e.inputs[0],t))},sl=e=>re({blocksize:e.blocksize,mode:e.mode,format:e.format})});var Io,sn,ll,$f,xf,Co,Ao,dl,Sf,cl,pl,ml=R(()=>{\"use strict\";te();oe();Ie();ae();Io=\"[a-zA-Z]|\\\\.\\\\.\\\\.\",sn=\"(\"+Io+\")+\",ll=\"^\"+sn+\"$\",$f=\"(\"+sn+\",)*\"+sn,xf=\"^\"+$f+\"$\",Co=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,r){let n=this.symbolToIndices.get(t);n===void 0?n=[r]:n.push(r),this.symbolToIndices.set(t,n)}},Ao=class{constructor(t,r){this.equation=r;this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[n,o]=r.includes(\"->\")?r.split(\"->\",2):[r,\"\"];if(!n.match(RegExp(xf)))throw new Error(\"Invalid LHS term\");if(n.split(\",\").forEach((l,d)=>{let c=t[d].dims.slice();if(!l.match(RegExp(ll)))throw new Error(\"Invalid LHS term\");let m=this.processTerm(l,!0,c,d);this.lhs.push(m)}),o===\"\")o+=[...this.symbolToInfo.entries()].filter(([l,d])=>d.count===1||l===\"...\").map(([l])=>l).join(\"\");else if(!o.match(RegExp(sn)))throw new Error(\"Invalid RHS\");o.match(RegExp(Io,\"g\"))?.forEach(l=>{if(l===\"...\")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let d=this.symbolToInfo.get(l);if(d===void 0)throw new Error(\"Invalid RHS symbol\");this.outputDims.push(d.dimValue)}}),this.rhs=this.processTerm(o,!1,this.outputDims)}addSymbol(t,r,n){let o=this.symbolToInfo.get(t);if(o!==void 0){if(o.dimValue!==r&&o.count!==1)throw new Error(\"Dimension mismatch\");o.count++,o.inputIndices.push(n)}else o={count:1,dimValue:r,inputIndices:[n]};this.symbolToInfo.set(t,o)}processTerm(t,r,n,o=-1){let i=n.length,a=!1,l=[],d=0;if(!t.match(RegExp(ll))&&!r&&t!==\"\")throw new Error(\"Invalid LHS term\");let c=t.match(RegExp(Io,\"g\")),m=new Co(o);return c?.forEach((u,h)=>{if(u===\"...\"){if(a)throw new Error(\"Only one ellipsis is allowed per input term\");a=!0;let w=i-c.length+1;if(w<0)throw new Error(\"Ellipsis out of bounds\");if(l=n.slice(d,d+w),this.hasEllipsis){if(this.ellipsisDims.length!==l.length||this.ellipsisDims.toString()!==l.toString())throw new Error(\"Ellipsis dimensions mismatch\")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=l;else throw new Error(\"Ellipsis must be specified in the LHS\");for(let y=0;ye+\"_max\",Sf=(e,t,r,n)=>{let i=e.map(m=>m.length).map((m,u)=>E(`input${u}`,t,m)),a=k.size(n),l=M(\"output\",t,n.length),d=[...r.symbolToInfo.keys()].filter(m=>!r.rhs.symbolToIndices.has(m)),c=m=>{let u=[],h=\"var prod = 1.0;\",w=\"var sum = 0.0;\",y=\"sum += prod;\",g=[],x=[],$=[],v=[],S=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((C,A)=>{if(r.rhs.symbolToIndices.has(A)){let P=r.rhs.symbolToIndices.get(A)?.[0];P!==void 0&&r.lhs.forEach((O,U)=>{if(C.inputIndices.includes(U)){let L=O.symbolToIndices.get(A);if(L===void 0)throw new Error(\"Invalid symbol error\");L.forEach(j=>{u.push(`${i[U].indicesSet(`input${U}Indices`,j,l.indicesGet(\"outputIndices\",P))}`)})}})}else r.lhs.forEach((P,O)=>{if(C.inputIndices.includes(O)){let U=P.symbolToIndices.get(A);if(U===void 0)throw new Error(\"Invalid symbol error\");U.forEach(L=>{g.push(`${i[O].indicesSet(`input${O}Indices`,L,`${A}`)}`)}),v.push(`prod *= ${i[O].getByIndices(`input${O}Indices`)};`)}}),x.push(`for(var ${A}: u32 = 0; ${A} < uniforms.${dl(A)}; ${A}++) {`),$.push(\"}\")});let T=S?[...u,`let sum = ${i.map((C,A)=>C.getByIndices(`input${A}Indices`)).join(\" * \")};`]:[...u,w,...x,...g,h,...v,y,...$];return`\n ${m.registerUniforms(d.map(C=>({name:`${dl(C)}`,type:\"u32\"}))).registerUniform(\"outputSize\",\"u32\").declareVariables(...i,l)}\n\n ${m.mainStart()}\n ${m.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n var outputIndices = ${l.offsetToIndices(\"global_idx\")};\n ${i.map((C,A)=>`var input${A}Indices: ${i[A].type.indices};`).join(`\n`)}\n ${T.join(`\n`)};\n ${l.setByOffset(\"global_idx\",\"sum\")};\n }`};return{name:\"Einsum\",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>\"rank\")},getRunData:()=>{let m=d.filter(h=>r.symbolToInfo.has(h)).map(h=>({type:12,data:r.symbolToInfo.get(h)?.dimValue||0}));m.push({type:12,data:a});let u=e.map((h,w)=>[...V(h)]).reduce((h,w)=>h.concat(w),m);return u.push(...V(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:u}},getShaderSource:c}},cl=(e,t)=>{let r=new Ao(e.inputs,t.equation),n=r.outputDims,o=e.inputs.map((i,a)=>i.dims);e.compute(Sf(o,e.inputs[0].dataType,r,n))},pl=e=>{let t=e.equation.replace(/\\s+/g,\"\");return re({equation:t})}});var Tf,fl,If,Cf,hl,gl=R(()=>{\"use strict\";te();oe();ae();Tf=e=>{if(!e||e.length!==2)throw new Error(\"Expand requires 2 input.\");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=r.length{let r=e.length-t.length,n=[];for(let o=0;oe.length>t.length?fl(e,t):fl(t,e),Cf=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=If(t,r),o=e[0].dataType,i=o===9?4:1,a=Math.ceil(k.size(n)/i),l=c=>{let m=E(\"input\",o,t.length,i),u=M(\"output\",o,n.length,i),h;if(o===9){let w=(y,g,x=\"\")=>`\n let outputIndices${g} = ${u.offsetToIndices(`outputOffset + ${g}u`)};\n let offset${g} = ${m.broadcastedIndicesToOffset(`outputIndices${g}`,u)};\n let index${g} = offset${g} / 4u;\n let component${g} = offset${g} % 4u;\n ${y}[${g}] = ${x}(${m.getByOffset(`index${g}`)}[component${g}]);\n `;h=`\n let outputOffset = global_idx * ${i};\n var data = vec4(0);\n ${w(\"data\",0,\"u32\")}\n ${w(\"data\",1,\"u32\")}\n ${w(\"data\",2,\"u32\")}\n ${w(\"data\",3,\"u32\")}\n ${u.setByOffset(\"global_idx\",\"data\")}\n }`}else h=`\n let outputIndices = ${u.offsetToIndices(\"global_idx\")};\n let inputOffset = ${m.broadcastedIndicesToOffset(\"outputIndices\",u)};\n ${u.setByOffset(\"global_idx\",m.getByOffset(\"inputOffset\"))}\n }`;return`\n ${c.registerUniform(\"vec_size\",\"u32\").declareVariables(m,u)}\n ${c.mainStart()}\n ${c.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.vec_size\")}\n ${h}`},d=[{type:12,data:a},...V(t,n)];return{name:\"Expand\",shaderCache:{hint:`${n.length}`,inputDependencies:[\"rank\"]},getShaderSource:l,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:d})}},hl=e=>{Tf(e.inputs),e.compute(Cf(e.inputs),{inputs:[0]})}});var Af,bl,yl=R(()=>{\"use strict\";te();oe();ae();Jr();Af=e=>{let t=e[0].dataType,r=k.size(e[0].dims),n=k.size(e[1].dims),o=n%4===0,i=a=>{let l=E(\"x\",t,[1],4),d=E(\"bias\",t,[1],4),c=M(\"y\",t,[1],4),m=[{name:\"output_vec_size\",type:\"u32\"},{name:\"bias_size\",type:\"u32\"}],u=w=>`\n let bias${w}_offset: u32 = (global_idx * 4 + ${w}) % uniforms.bias_size;\n let bias${w} = ${d.getByOffset(`bias${w}_offset / 4`)}[bias${w}_offset % 4];`,h=o?`\n let bias = ${d.getByOffset(\"global_idx % (uniforms.bias_size / 4)\")};`:`${u(0)}${u(1)}${u(2)}${u(3)}\n let bias = ${l.type.value}(bias0, bias1, bias2, bias3);`;return`${a.registerUniforms(m).declareVariables(l,d,c)}\n\n ${yo(Ee(t))}\n\n ${a.mainStart(Ct)}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_vec_size\")}\n\n let x = ${l.getByOffset(\"global_idx\")};\n ${h}\n let x_in = x + bias;\n ${c.setByOffset(\"global_idx\",wo(\"x_in\"))}\n }`};return{name:\"FastGeluWithBias\",shaderCache:{hint:`${o}`,inputDependencies:[\"type\",\"type\"]},getShaderSource:i,getRunData:a=>({outputs:[{dims:a[0].dims,dataType:a[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/Ct/4)}})}},bl=e=>{e.inputs.length<2||k.size(e.inputs[1].dims)===0?gu(e):e.compute(Af(e.inputs))}});var kf,Ef,wl,_l,vl=R(()=>{\"use strict\";te();oe();Ie();ae();kf=e=>{if(!e||e.length!==2)throw new Error(\"Gather requires 2 inputs.\")},Ef=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r.length,i=k.normalizeAxis(t.axis,o),a=r.slice(0);a.splice(i,1,...n);let l=r[i],d=e[0].dataType===9?4:1,c=Math.ceil(k.size(a)/d),m=[{type:12,data:c},{type:6,data:l},{type:12,data:i},...V(e[0].dims,e[1].dims,a)],u=h=>{let w=E(\"data\",e[0].dataType,e[0].dims.length,d),y=E(\"inputIndices\",e[1].dataType,e[1].dims.length),g=M(\"output\",e[0].dataType,a.length,d),x=v=>{let S=n.length,T=`var indicesIndices${v} = ${y.type.indices}(0);`;for(let C=0;C1?`indicesIndices${v}[${C}]`:`indicesIndices${v}`} = ${a.length>1?`outputIndices${v}[uniforms.axis + ${C}]`:`outputIndices${v}`};`;T+=`\n var idx${v} = ${y.getByIndices(`indicesIndices${v}`)};\n if (idx${v} < 0) {\n idx${v} = idx${v} + uniforms.axisDimLimit;\n }\n var dataIndices${v} : ${w.type.indices};\n `;for(let C=0,A=0;C1?`dataIndices${v}[${C}]`:`dataIndices${v}`} = u32(idx${v});`,A+=S):(T+=`${o>1?`dataIndices${v}[${C}]`:`dataIndices${v}`} = ${a.length>1?`outputIndices${v}[${A}]`:`outputIndices${v}`};`,A++);return T},$;if(e[0].dataType===9){let v=(S,T,C=\"\")=>`\n let outputIndices${T} = ${g.offsetToIndices(`outputOffset + ${T}u`)};\n ${x(T)};\n let offset${T} = ${w.indicesToOffset(`dataIndices${T}`)};\n let index${T} = offset${T} / 4u;\n let component${T} = offset${T} % 4u;\n ${S}[${T}] = ${C}(${w.getByOffset(`index${T}`)}[component${T}]);\n `;$=`\n let outputOffset = global_idx * ${d};\n var value = vec4(0);\n ${v(\"value\",0,\"u32\")}\n ${v(\"value\",1,\"u32\")}\n ${v(\"value\",2,\"u32\")}\n ${v(\"value\",3,\"u32\")}\n ${g.setByOffset(\"global_idx\",\"value\")}\n `}else $=`\n let outputIndices = ${g.offsetToIndices(\"global_idx\")};\n ${x(\"\")};\n let value = ${w.getByIndices(\"dataIndices\")};\n ${g.setByOffset(\"global_idx\",\"value\")};\n `;return`\n ${h.registerUniform(\"outputSize\",\"u32\").registerUniform(\"axisDimLimit\",\"i32\").registerUniform(\"axis\",\"u32\").declareVariables(w,y,g)}\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n ${$}\n }`};return{name:\"Gather\",shaderCache:{hint:t.cacheKey,inputDependencies:[\"rank\",\"rank\"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:m}),getShaderSource:u}},wl=e=>re({axis:e.axis}),_l=(e,t)=>{let r=e.inputs;kf(r),e.compute(Ef(e.inputs,t))}});var Pf,zf,$l,xl,Sl=R(()=>{\"use strict\";te();oe();Ie();ae();Pf=(e,t)=>{if(e.length<3||e.length>4)throw new Error(\"GatherBlockQuantized requires 3 or 4 inputs.\");let r=k.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,o=e[0],i=e[2],a=e.length===4?e[3]:void 0;if(i.dims.length!==o.dims.length||!o.dims.map((l,d)=>d===r?Math.ceil(l/n)===i.dims[d]:l===i.dims[d]).reduce((l,d)=>l&&d,!0))throw new Error(\"Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.\");if(a){if(a.dataType!==o.dataType)throw new Error(\"Zero point must have the same data type as the input tensor.\");if(a.dims.length!==i.dims.length||!a.dims.map((l,d)=>l===i.dims[d]).reduce((l,d)=>l&&d,!0))throw new Error(\"Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.\")}},zf=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r.length,i=k.normalizeAxis(t.gatherAxis,o),a=k.normalizeAxis(t.quantizeAxis,o),l=r.slice(0);l.splice(i,1,...n);let d=k.size(l),c=e[2].dataType,u=e[0].dataType===22,h=[{type:12,data:d},{type:12,data:a},{type:12,data:i},{type:12,data:t.blockSize},...V(...e.map((y,g)=>y.dims),l)],w=y=>{let g=E(\"data\",e[0].dataType,e[0].dims.length),x=E(\"inputIndices\",e[1].dataType,e[1].dims.length),$=E(\"scales\",e[2].dataType,e[2].dims.length),v=e.length>3?E(\"zeroPoint\",e[3].dataType,e[3].dims.length):void 0,S=M(\"output\",c,l.length),T=[g,x,$];v&&T.push(v);let C=[{name:\"output_size\",type:\"u32\"},{name:\"quantize_axis\",type:\"u32\"},{name:\"gather_axis\",type:\"u32\"},{name:\"block_size\",type:\"u32\"}];return`\n ${y.registerUniforms(C).declareVariables(...T,S)}\n ${y.mainStart()}\n let output_indices = ${S.offsetToIndices(\"global_idx\")};\n var indices_indices = ${x.type.indices}(0);\n ${(()=>n.length>1?`\n for (var i: u32 = 0; i < ${n.length}; i++) {\n let index = ${S.indicesGet(\"output_indices\",\"uniforms.gather_axis + i\")};\n ${x.indicesSet(\"indices_indices\",\"i\",\"index\")};\n }`:`indices_indices = ${S.indicesGet(\"output_indices\",\"uniforms.gather_axis\")};`)()};\n var data_indices = ${g.type.indices}(0);\n for (var i: u32 = 0; i < uniforms.gather_axis; i++) {\n let index = ${S.indicesGet(\"output_indices\",\"i\")};\n ${g.indicesSet(\"data_indices\",\"i\",\"index\")};\n }\n var index_from_indices = ${x.getByIndices(\"indices_indices\")};\n if (index_from_indices < 0) {\n index_from_indices += ${r[i]};\n }\n ${g.indicesSet(\"data_indices\",\"uniforms.gather_axis\",\"u32(index_from_indices)\")};\n for (var i = uniforms.gather_axis + 1; i < ${l.length}; i++) {\n let index = ${S.indicesGet(\"output_indices\",`i + ${n.length} - 1`)};\n ${g.indicesSet(\"data_indices\",\"i\",\"index\")};\n }\n let data_offset = ${g.indicesToOffset(\"data_indices\")};\n let data_index = data_offset % 8;\n // Convert 4-bit packed data to 8-bit packed data.\n let packed_4bit_quantized_data = ${g.getByOffset(\"data_offset / 8\")};\n let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f;\n let quantized_data_vec = ${u?\"unpack4xI8\":\"unpack4xU8\"}(u32(packed_8bit_quantized_data));\n let quantized_data = quantized_data_vec[data_index / 2];\n var scale_indices = data_indices;\n let quantize_axis_index = ${$.indicesGet(\"data_indices\",\"uniforms.quantize_axis\")} / uniforms.block_size;\n ${$.indicesSet(\"scale_indices\",\"uniforms.quantize_axis\",\"quantize_axis_index\")};\n var scale = ${$.getByIndices(\"scale_indices\")};\n ${(()=>v?`\n let zero_point_indices = scale_indices;\n let zero_point_offset = ${v.indicesToOffset(\"zero_point_indices\")};\n let zero_point_index = zero_point_offset % 8;\n let packed_4bit_zero_points = ${v.getByOffset(\"zero_point_offset / 8\")};\n let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f;\n let zero_point_vec = ${u?\"unpack4xI8\":\"unpack4xU8\"}(u32(packed_8bit_zero_points));\n let zero_point = zero_point_vec[zero_point_index / 2];`:\"var zero_point = 0\")()};\n let dequantized_data = ${Ee(c)}(quantized_data - zero_point) * scale;\n ${S.setByOffset(\"global_idx\",\"dequantized_data\")};\n }`};return{name:\"GatherBlockQuantized\",shaderCache:{hint:`${t.cacheKey};${e.filter((y,g)=>g!==1).map(y=>y.dims.join(\"_\")).join(\";\")}`,inputDependencies:Array.from({length:e.length},(y,g)=>\"rank\")},getRunData:()=>({outputs:[{dims:l,dataType:c}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:h}),getShaderSource:w}},$l=(e,t)=>{let r=e.inputs;Pf(r,t),e.compute(zf(e.inputs,t))},xl=e=>re({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})});var Of,Df,Tl,Il,Cl=R(()=>{\"use strict\";te();oe();Ie();ae();Of=e=>{if(!e||e.length!==2)throw new Error(\"GatherElements requires 2 inputs.\");if(e[0].dims.length<1)throw new Error(\"GatherElements requires that the data input be rank >= 1.\");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and\n indices input tensors be of same rank.`)},Df=(e,t)=>{let r=e[0].dims,n=e[0].dataType,o=r.length,i=e[1].dims,a=e[1].dataType,l=k.normalizeAxis(t.axis,o),d=r[l],c=i.slice(0),m=k.size(c),u=E(\"input\",n,o),h=E(\"indicesInput\",a,i.length),w=M(\"output\",n,c.length),y=[{type:12,data:m},{type:6,data:d},{type:12,data:l}];return y.push(...V(r,i,c)),{name:\"GatherElements\",shaderCache:{inputDependencies:[\"rank\",\"rank\"]},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:y}),getShaderSource:$=>`\n ${$.registerUniform(\"outputSize\",\"u32\").registerUniform(\"axisDimLimit\",\"i32\").registerUniform(\"axis\",\"u32\").declareVariables(u,h,w)}\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n\n let outputIndices = ${w.offsetToIndices(\"global_idx\")};\n\n var idx = ${h.getByOffset(\"global_idx\")};\n if (idx < 0) {\n idx = idx + uniforms.axisDimLimit;\n }\n var inputIndices = ${u.type.indices}(outputIndices);\n ${u.indicesSet(\"inputIndices\",\"uniforms.axis\",\"u32(idx)\")};\n let value = ${u.getByIndices(\"inputIndices\")};\n\n ${w.setByOffset(\"global_idx\",\"value\")};\n }`}},Tl=e=>re({axis:e.axis}),Il=(e,t)=>{let r=e.inputs;Of(r),e.compute(Df(e.inputs,t))}});var Bf,Mf,Al,kl,El=R(()=>{\"use strict\";te();oe();ae();Bf=e=>{if(!e)throw new Error(\"Input is missing\");if(e.length<2||e.length>3)throw new Error(\"Invaid input number.\");if(e.length===3&&e[2].dims.length>2)throw new Error(\"Invalid input shape of C\");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error(\"Input types are mismatched\")},Mf=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[o,i,a]=jr.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),l=[o,i];if(!l)throw new Error(\"Can't use gemm on the given tensors\");let d=16,c=Math.ceil(i/d),m=Math.ceil(o/d),u=!0,h=k.size(l),w=[{type:12,data:u?c:h},{type:12,data:o},{type:12,data:i},{type:12,data:a},{type:1,data:t.alpha},{type:1,data:t.beta}],y=[\"type\",\"type\"];e.length===3&&(w.push(...V(e[2].dims)),y.push(\"rank\")),w.push(...V(l));let g=$=>{let v=\"\";t.transA&&t.transB?v=\"value += a[k * uniforms.M + m] * b[n * uniforms.K + k];\":t.transA&&!t.transB?v=\"value += a[k * uniforms.M + m] * b[k * uniforms.N + n];\":!t.transA&&t.transB?v=\"value += a[m * uniforms.K + k] * b[n * uniforms.K + k];\":!t.transA&&!t.transB&&(v=\"value += a[m * uniforms.K + k] * b[k * uniforms.N + n];\");let S=t.alpha===1?\"\":\"value *= uniforms.alpha;\",T=E(\"a\",e[0].dataType,e[0].dims),C=E(\"b\",e[1].dataType,e[1].dims),A=T.type.value,P=null,O=[T,C];e.length===3&&(P=E(\"c\",e[2].dataType,e[2].dims.length),O.push(P));let U=M(\"output\",e[0].dataType,l.length);O.push(U);let L=[{name:\"output_size\",type:\"u32\"},{name:\"M\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"alpha\",type:\"f32\"},{name:\"beta\",type:\"f32\"}];return`\n ${$.registerUniforms(L).declareVariables(...O)}\n\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let m = global_idx / uniforms.N;\n let n = global_idx % uniforms.N;\n\n var value = ${A}(0);\n for (var k: u32 = 0u; k < uniforms.K; k++) {\n ${v}\n }\n\n ${S}\n ${(()=>P!=null?`let cOffset = ${P.broadcastedIndicesToOffset(\"vec2(m, n)\",U)}; value += ${A}(uniforms.beta) * ${P.getByOffset(\"cOffset\")};`:\"\")()}\n output[global_idx] = value;\n }`},x=$=>{let v=E(\"a\",e[0].dataType,e[0].dims),S=E(\"b\",e[1].dataType,e[1].dims),T=null,C=[v,S];e.length===3&&(T=E(\"c\",e[2].dataType,e[2].dims.length),C.push(T));let A=M(\"output\",e[0].dataType,l.length);C.push(A);let P=[{name:\"num_tile_n\",type:\"u32\"},{name:\"M\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"alpha\",type:\"f32\"},{name:\"beta\",type:\"f32\"}],O=\"\",U=\"\";t.transA&&t.transB?(U=`\n var col = tile_row_start + local_id.x;\n var row = k_start + local_id.y;\n if (col < uniforms.M && row < uniforms.K) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${v.type.value}(0);\n }\n\n col = k_start + local_id.x;\n row = tile_col_start + local_id.y;\n if (col < uniforms.K && row < uniforms.N) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${S.type.value}(0);\n }\n `,O=\"value += tile_a[k][local_id.y] * tile_b[local_id.x][k];\"):t.transA&&!t.transB?(U=`\n var col = tile_row_start + local_id.x;\n var row = k_start + local_id.y;\n if (col < uniforms.M && row < uniforms.K) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${v.type.value}(0);\n }\n\n col = tile_col_start + local_id.x;\n row = k_start + local_id.y;\n if (col < uniforms.N && row < uniforms.K) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${S.type.value}(0);\n }\n `,O=\"value += tile_a[k][local_id.y] * tile_b[k][local_id.x];\"):!t.transA&&t.transB?(U=`\n var col = k_start + local_id.x;\n var row = tile_row_start + local_id.y;\n if (col < uniforms.K && row < uniforms.M) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${v.type.value}(0);\n }\n\n col = k_start + local_id.x;\n row = tile_col_start + local_id.y;\n if (col < uniforms.K && row < uniforms.N) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${S.type.value}(0);\n }\n `,O=\"value += tile_a[local_id.y][k] * tile_b[local_id.x][k];\"):!t.transA&&!t.transB&&(U=`\n var col = k_start + local_id.x;\n var row = tile_row_start + local_id.y;\n if (col < uniforms.K && row < uniforms.M) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${v.type.value}(0);\n }\n\n col = tile_col_start + local_id.x;\n row = k_start + local_id.y;\n if (col < uniforms.N && row < uniforms.K) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${S.type.value}(0);\n }\n `,O=\"value += tile_a[local_id.y][k] * tile_b[k][local_id.x];\");let L=t.alpha===1?\"\":\"value *= uniforms.alpha;\";return`\n ${$.registerUniforms(P).declareVariables(...C)}\n var tile_a: array, ${d}>;\n var tile_b: array, ${d}>;\n ${$.mainStart([d,d,1])}\n let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${d};\n let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${d};\n let num_tiles = (uniforms.K - 1) / ${d} + 1;\n var k_start = 0u;\n var value = ${A.type.value}(0);\n for (var t: u32 = 0u; t < num_tiles; t++) {\n ${U}\n k_start = k_start + ${d};\n workgroupBarrier();\n\n for (var k: u32 = 0u; k < ${d}; k++) {\n ${O}\n }\n workgroupBarrier();\n }\n\n ${L}\n let m = tile_row_start + local_id.y;\n let n = tile_col_start + local_id.x;\n ${(()=>T!=null?`let cOffset = ${T.broadcastedIndicesToOffset(\"vec2(m, n)\",A)}; value += ${A.type.value}(uniforms.beta) * ${T.getByOffset(\"cOffset\")};`:\"\")()}\n if (m < uniforms.M && n < uniforms.N) {\n output[m * uniforms.N + n] = value;\n }\n }`};return u?{name:\"GemmShared\",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:c*m},programUniforms:w}),getShaderSource:x}:{name:\"Gemm\",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:w}),getShaderSource:g}},Al=e=>{let t=e.transA,r=e.transB,n=e.alpha,o=e.beta;return{transA:t,transB:r,alpha:n,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},kl=(e,t)=>{Bf(e.inputs),e.compute(Mf(e.inputs,t))}});var dt,yt,Ut,Vt,Rf,Uf,Vf,Nf,Wf,Lf,Gf,Hf,Pl,zl,Ol=R(()=>{\"use strict\";te();oe();Ie();ae();[dt,yt,Ut,Vt]=[0,1,2,3],Rf=e=>{if(e[0].dims.length!==4)throw new Error(\"only 4-D tensor is supported.\");if(e[0].dims.length!==e[1].dims.length)throw new Error(\"input dimensions must be equal to grid dimensions\");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error(\"grid batch size must match input batch size\")},Uf=`\n fn gs_get_cubic_coeffs(x: f32) -> vec4 {\n let cubic_alpha = -0.75f;\n let x_abs = abs(x);\n var coeffs: vec4;\n coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha);\n coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1);\n coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1);\n coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha);\n return coeffs;\n }\n`,Vf=e=>`\n fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} {\n var v: vec4;\n var coeffs = gs_get_cubic_coeffs(x);\n for (var i = 0; i < 4; i++) {\n v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3];\n }\n coeffs = gs_get_cubic_coeffs(y);\n let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]);\n return pixel;\n }\n`,Nf=e=>`\n fn gs_denormalize(n: f32, length: i32) -> f32 {\n ${e.alignCorners===0?`\n // alignCorners: false => [-1, 1] to [-0.5, length - 0.5]\n return ((n + 1.0) * f32(length) - 1.0) / 2.0;\n `:`\n // alignCorners: true => [-1, 1] to [0, length - 1]\n return (n + 1.0) / 2.0 * (f32(length - 1));\n `}\n }\n`,Wf=e=>`\n ${e.paddingMode===\"reflection\"?`\n fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 {\n var dx = 0.0;\n var fx = f32(x);\n let range = x_max - x_min;\n if (fx < x_min) {\n dx = x_min - fx;\n let n = u32(dx / range);\n let r = dx - f32(n) * range;\n if (n % 2 == 0) {\n fx = x_min + r;\n } else {\n fx = x_max - r;\n }\n } else if (fx > x_max) {\n dx = fx - x_max;\n let n = u32(dx / range);\n let r = dx - f32(n) * range;\n if (n % 2 == 0) {\n fx = x_max - r;\n } else {\n fx = x_min + r;\n }\n }\n return u32(fx);\n }`:\"\"}\n`,Lf=(e,t,r)=>`\n fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} {\n var pixel = ${t}(0);\n var indices = vec4(0);\n indices[${dt}] = batch;\n indices[${yt}] = channel;`+(()=>{switch(r.paddingMode){case\"zeros\":return`\n if (r >= 0 && r < H && c >=0 && c < W) {\n indices[${Ut}] = u32(r);\n indices[${Vt}] = u32(c);\n }\n `;case\"border\":return`\n indices[${Ut}] = u32(clamp(r, 0, H - 1));\n indices[${Vt}] = u32(clamp(c, 0, W - 1));\n `;case\"reflection\":return`\n indices[${Ut}] = gs_reflect(r, border[1], border[3]);\n indices[${Vt}] = gs_reflect(c, border[0], border[2]);\n `;default:throw new Error(`padding mode ${r.paddingMode} is not supported`)}})()+`\n return ${e.getByIndices(\"indices\")};\n }\n`,Gf=(e,t,r)=>(()=>{switch(r.mode){case\"nearest\":return`\n let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${dt}], indices[${yt}], border);\n `;case\"bilinear\":return`\n let x1 = i32(floor(x));\n let y1 = i32(floor(y));\n let x2 = x1 + 1;\n let y2 = y1 + 1;\n\n let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${dt}], indices[${yt}], border);\n let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${dt}], indices[${yt}], border);\n let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${dt}], indices[${yt}], border);\n let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${dt}], indices[${yt}], border);\n\n let dx2 = ${t}(f32(x2) - x);\n let dx1 = ${t}(x - f32(x1));\n let dy2 = ${t}(f32(y2) - y);\n let dy1 = ${t}(y - f32(y1));\n let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22);\n `;case\"bicubic\":return`\n let x0 = i32(floor(x)) - 1;\n let y0 = i32(floor(y)) - 1;\n var p: mat4x4<${t}>;\n for (var h = 0; h < 4; h++) {\n for (var w = 0; w < 4; w++) {\n p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${dt}], indices[${yt}], border);\n }\n }\n\n let dx = x - f32(x0 + 1);\n let dy = y - f32(y0 + 1);\n let result = gs_bicubic_interpolate(p, dx, dy);\n `;default:throw new Error(`mode ${r.mode} is not supported`)}})()+`${e.setByOffset(\"global_idx\",\"result\")}`,Hf=(e,t)=>{let r=E(\"x\",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=E(\"grid\",e[1].dataType,n.length,2),i=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format===\"NHWC\"&&(i=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[dt,yt,Ut,Vt]=[0,3,1,2]);let a=M(\"output\",e[0].dataType,i.length),l=r.type.value,d=k.size(i),c=[{type:12,data:d},...V(e[0].dims,n,i)],m=u=>`\n ${u.registerUniform(\"output_size\",\"u32\").declareVariables(r,o,a)}\n ${Uf}\n ${Vf(l)}\n ${Nf(t)}\n ${Wf(t)}\n ${Lf(r,l,t)}\n\n ${u.mainStart()}\n ${u.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let H_in = i32(uniforms.x_shape[${Ut}]);\n let W_in = i32(uniforms.x_shape[${Vt}]);\n\n ${t.alignCorners===0?`\n let x_min = -0.5;\n let x_max = f32(W_in) - 0.5;\n let y_min = -0.5;\n let y_max = f32(H_in) - 0.5;\n `:`\n let x_min = 0.0;\n let x_max = f32(W_in) - 1.0;\n let y_min = 0.0;\n let y_max = f32(H_in) - 1.0;\n `};\n let border = vec4(x_min, y_min, x_max, y_max);\n\n let indices = ${a.offsetToIndices(\"global_idx\")};\n var grid_indices = vec3(indices[${dt}], indices[${Ut}], indices[${Vt}]);\n let nxy = ${o.getByIndices(\"grid_indices\")};\n var x = gs_denormalize(f32(nxy[0]), W_in);\n var y = gs_denormalize(f32(nxy[1]), H_in);\n\n ${Gf(a,l,t)}\n }`;return{name:\"GridSample\",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:[\"type\",\"type\"]},getRunData:u=>{let h=k.size(i);return{outputs:[{dims:i,dataType:u[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:c}},getShaderSource:m}},Pl=(e,t)=>{Rf(e.inputs),e.compute(Hf(e.inputs,t))},zl=e=>re({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})});var Me,jf,Bl,Dl,Kf,ar,Ml,ko=R(()=>{\"use strict\";te();oe();Ie();qr();Xr();ae();ut();Me=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,jf=(e,t)=>{let r=e[0],n=Me(e,1),o=Me(e,2),i=Me(e,3),a=Me(e,4),l=Me(e,5),d=Me(e,6),c=Me(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error(\"Input query is expected to have 3 or 5 dimensions\");let m=r.dims[0],u=r.dims[1],h=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],w=u,y=0,g=0,x=Math.floor(h/t.numHeads);if(d&&c&&k.size(d.dims)&&k.size(c.dims)){if(d.dims.length!==4)throw new Error('Input \"past_key\" is expected to have 4 dimensions');if(d.dims[0]!==m||d.dims[1]!==t.numHeads||d.dims[3]!==x)throw new Error('Input \"past_key\" shape (batch_size, num_heads, past_sequence_length, head_size)');if(c.dims[0]!==m||c.dims[1]!==t.numHeads||c.dims[3]!==x)throw new Error('Input \"past_value\" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.dims[2]!==c.dims[2])throw new Error('Input \"past_key\" and \"past_value\" shall have same dim 2 (past_sequence_length)');if(c.dims.length!==4)throw new Error('Input \"past_value\" is expected to have 4 dimensions');y=d.dims[2],g=d.dims[2]}else if(d&&k.size(d.dims)||c&&k.size(c.dims))throw new Error('Input \"past_key\" and \"past_value\" shall be both present or both absent');let $;if(n&&k.size(n.dims)>0){if(r.dims.length!==3)throw new Error('Input \"query\" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input \"key\" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input \"query\" and \"key\" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input \"query\" and \"key\" shall have same dim 2 (hidden_size)');$=2,w=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==x)throw new Error('Expect \"key\" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect \"value\" be none when \"key\" has packed kv format.');$=5,w=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==x)throw new Error('Expect \"key\" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');$=0,w=n.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input \"query\" is expected to have 5 dimensions when key is empty');if(r.dims[2]!==t.numHeads||r.dims[3]!==3)throw new Error('Expect \"query\" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');$=3}if(i&&k.size(i.dims)>0){if(i.dims.length!==1)throw new Error('Input \"bias\" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error(\"bias is not allowed for packed kv.\")}let v=y+w,S=0;if(a&&k.size(a.dims)>0){S=8;let P=a.dims;throw P.length===1?P[0]===m?S=1:P[0]===3*m+2&&(S=3):P.length===2&&P[0]===m&&P[1]===v&&(S=5),S===8?new Error('Input \"key_padding_mask\" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error(\"Mask not supported\")}let T=!1,C=h;if(o&&k.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input \"value\" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input \"query\" and \"value\" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(w!==o.dims[1])throw new Error('Input \"key\" and \"value\" shall have the same dim 1 (kv_sequence_length)');C=o.dims[2]}else{if(w!==o.dims[2])throw new Error('Input \"key\" and \"value\" shall have the same dim 2 (kv_sequence_length)');C=o.dims[1]*o.dims[3],T=!0}}let A=!1;if(a&&k.size(a.dims)>0)throw new Error(\"Key padding mask is not supported\");if(l&&k.size(l.dims)>0){if(l.dims.length!==4)throw new Error('Input \"attention_bias\" is expected to have 4 dimensions');if(l.dims[0]!==m||l.dims[1]!==t.numHeads||l.dims[2]!==u||l.dims[3]!==v)throw new Error('Expect \"attention_bias\" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:m,sequenceLength:u,pastSequenceLength:y,kvSequenceLength:w,totalSequenceLength:v,maxSequenceLength:g,inputHiddenSize:0,hiddenSize:h,vHiddenSize:C,headSize:x,vHeadSize:Math.floor(C/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:S,scale:t.scale,broadcastResPosBias:A,passPastInKv:T,qkvFormat:$}},Bl=e=>re({...e}),Dl=re({perm:[0,2,1,3]}),Kf=(e,t,r,n,o,i,a)=>{let l=[n,o,i],d=k.size(l),c=[{type:12,data:d},{type:12,data:a},{type:12,data:i}],m=u=>{let h=M(\"qkv_with_bias\",t.dataType,l),w=E(\"qkv\",t.dataType,l),y=E(\"bias\",r.dataType,l),g=[{name:\"output_size\",type:\"u32\"},{name:\"bias_offset\",type:\"u32\"},{name:\"hidden_size\",type:\"u32\"}];return`\n ${u.registerUniforms(g).declareVariables(w,y,h)}\n ${u.mainStart()}\n ${u.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;\n\n qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];\n }`};return e.compute({name:\"MultiHeadAttentionAddBias\",shaderCache:{inputDependencies:[\"type\",\"type\"]},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c}),getShaderSource:m},{inputs:[t,r],outputs:[-1]})[0]},ar=(e,t,r,n,o,i,a,l)=>{let d=i;if(a&&k.size(a.dims)>0){if(n===1)throw new Error(\"AddBiasReshape is not implemented. Please export your model with packed QKV or KV\");return d=Kf(e,i,a,t,n,r*o,l),d=d.reshape([t,n,r,o]),r===1||n===1?d:e.compute(Pe(d,Dl.perm),{inputs:[d],outputs:[-1]})[0]}else return i.dims.length===3&&(d=i.reshape([t,n,r,o])),r===1||n===1?d:e.compute(Pe(d,Dl.perm),{inputs:[d],outputs:[-1]})[0]},Ml=(e,t)=>{let r=jf(e.inputs,t),n=e.inputs[0],o=Me(e.inputs,1),i=Me(e.inputs,2),a=Me(e.inputs,3),l=Me(e.inputs,4),d=Me(e.inputs,5),c=Me(e.inputs,6),m=Me(e.inputs,7);if(n.dims.length===5)throw new Error(\"Packed QKV is not implemented\");if(o?.dims.length===5)throw new Error(\"Packed KV is not implemented\");let u=o&&i&&o.dims.length===4&&i.dims.length===4,h=ar(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,a,0);if(u)return Rt(e,h,o,i,l,void 0,c,m,d,r);if(!o||!i)throw new Error(\"key and value must be provided\");let w=ar(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,o,a,r.hiddenSize),y=ar(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,i,a,2*r.hiddenSize);Rt(e,h,w,y,l,void 0,c,m,d,r)}});var Yf,Zf,Xf,Qf,Eo,Rl,Ul,Po=R(()=>{\"use strict\";te();oe();Ie();ae();Yf=e=>{if(!e||e.length<1)throw new Error(\"too few inputs\")},Zf=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>r.push(Number(o))),n=r.length),re({numOutputs:n,axis:t.axis,splitSizes:r})},Xf=e=>`\nfn calculateOutputIndex(index: u32) -> u32 {\n for (var i: u32 = 0u; i < ${e}u; i += 1u ) {\n if (index < ${F(\"uniforms.size_in_split_axis\",\"i\",e)}) {\n return i;\n }\n }\n return ${e}u;\n}`,Qf=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=k.size(r),o=e[0].dataType,i=k.normalizeAxis(t.axis,r.length),a=new Array(t.numOutputs),l=E(\"input\",o,r.length),d=new Array(t.numOutputs),c=[],m=[],u=0,h=[{type:12,data:n}];for(let y=0;y`\n ${y.registerUniform(\"input_size\",\"u32\").registerUniform(\"size_in_split_axis\",\"u32\",d.length).declareVariables(l,...a)}\n ${Xf(d.length)}\n ${Qf(a)}\n\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.input_size\")}\n\n var indices = ${l.offsetToIndices(\"global_idx\")};\n var index = ${l.indicesGet(\"indices\",i)};\n let output_number = calculateOutputIndex(index);\n if (output_number != 0) {\n index -= ${F(\"uniforms.size_in_split_axis\",\"output_number - 1u\",d.length)};\n ${l.indicesSet(\"indices\",i,\"index\")};\n }\n writeBufferData(output_number, indices, global_idx);\n }`;return{name:\"Split\",shaderCache:{hint:t.cacheKey,inputDependencies:[\"rank\"]},getShaderSource:w,getRunData:()=>({outputs:c,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:h})}},Rl=(e,t)=>{Yf(e.inputs);let r=e.inputs.length===1?t:Zf(e.inputs,t);e.compute(Eo(e.inputs,r),{inputs:[0]})},Ul=e=>{let t=e.axis,r=e.splitSizes,n=e.numOutputs<0?r.length:e.numOutputs;if(n!==r.length)throw new Error(\"numOutputs and splitSizes lengh must be equal\");return re({axis:t,numOutputs:n,splitSizes:r})}});var Jf,eh,Vl,Nl,Wl=R(()=>{\"use strict\";Ie();Xr();ko();Po();ut();Jf=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error(\"cos_cache and sin_cache inputs are required if do_rotary is specified\");let r=e[0],n=e[1],o=e[2],i=e[3],a=e[4];if(t.localWindowSize!==-1)throw new Error(\"Local attention is not supported\");if(t.softcap!==0)throw new Error(\"Softcap is not supported\");if(t.rotaryInterleaved!==0)throw new Error(\"Rotary interleaved is not supported\");if(t.smoothSoftmax)throw new Error(\"Smooth softmax is not supported\");if(r.dims.length!==3&&r.dims.length!==5)throw new Error(\"Input query is expected to have 3 or 5 dimensions\");let l=!1,d=r.dims[0],c=r.dims[1],m=r.dims.length===3?l?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],u=c,h=0,w=!n||n.dims.length===0,y=Math.floor(w?m/(t.numHeads+2*t.kvNumHeads):m/t.numHeads);w&&(m=y*t.numHeads);let g=i&&i.dims.length!==0,x=a&&a.dims.length!==0;if(g&&i.dims.length===4&&i.dims[0]===d&&i.dims[1]!==t.kvNumHeads&&i.dims[2]===t.kvNumHeads&&i.dims[3]===y)throw new Error(\"BSNH pastKey/pastValue is not supported\");if(g&&x){if(i.dims.length!==4)throw new Error('Input \"past_key\" is expected to have 4 dimensions');if(a.dims.length!==4)throw new Error('Input \"past_value\" is expected to have 4 dimensions');h=i.dims[2]}else if(g||x)throw new Error('Input \"past_key\" and \"past_value\" shall be both present or both absent');let v=1;if(n&&n.dims.length>0){if(r.dims.length!==3)throw new Error('Input \"query\" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input \"key\" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input \"query\" and \"key\" shall have same dim 0 (batch size)');if(n.dims.length===3){if(r.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of \"query\" should be a multiple of \"key\"');u=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==y)throw new Error('Expect \"key\" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect \"value\" be none when \"key\" has packed kv format.');u=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==y)throw new Error('Expect \"key\" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');u=n.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input \"query\" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error('Expect \"query\" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');v=3}let S=0,T=!1,C=t.kvNumHeads?y*t.kvNumHeads:m;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input \"value\" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input \"query\" and \"value\" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(u!==o.dims[1])throw new Error('Input \"key\" and \"value\" shall have the same dim 1 (kv_sequence_length)');C=o.dims[2]}else{if(u!==o.dims[2])throw new Error('Input \"past_key\" and \"past_value\" shall have the same dim 2 (kv_sequence_length)');C=o.dims[1]*o.dims[3],T=!0}}let A=e.length>4?e[5]:void 0;if(A&&A.dims.length!==1&&A.dims[0]!==d)throw new Error('Input \"seqlens\" is expected to have 1 dimension and the same dim 0 as batch_size');let P=-1,O=-1,U=!1;return{batchSize:d,sequenceLength:c,pastSequenceLength:h,kvSequenceLength:u,totalSequenceLength:P,maxSequenceLength:O,inputHiddenSize:0,hiddenSize:m,vHiddenSize:C,headSize:y,vHeadSize:Math.floor(C/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:S,scale:t.scale,broadcastResPosBias:U,passPastInKv:T,qkvFormat:v}},eh=re({perm:[0,2,1,3]}),Vl=(e,t,r)=>{let n=t,o=r.kvNumHeads;return t.dims.length===3&&r.kvSequenceLength!==0&&(n=t.reshape([r.batchSize,r.kvSequenceLength,o,r.headSize]),n=e.compute(Pe(n,eh.perm),{inputs:[n],outputs:[-1]})[0]),n},Nl=(e,t)=>{let r=Jf(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error(\"Packed QKV is not implemented\");if(e.inputs[1]?.dims.length===5)throw new Error(\"Packed KV is not implemented\");let n=e.inputs[0],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,i=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,a=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,l=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,d=e.inputs.length>4?e.inputs[5]:void 0,c=e.inputs.length>5?e.inputs[6]:void 0,m=r.kvNumHeads?r.kvNumHeads:r.numHeads,u=re({axis:2,numOutputs:3,splitSizes:[r.numHeads*r.headSize,m*r.headSize,m*r.headSize]}),[h,w,y]=!o&&!i?e.compute(Eo([n],u),{inputs:[n],outputs:[-1,-1,-1]}):[n,o,i],g=ar(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,h,void 0,0);Rt(e,g,Vl(e,w,r),Vl(e,y,r),void 0,void 0,a,l,void 0,r,d,c)}});var Ll,th,rh,Gl,Hl=R(()=>{\"use strict\";te();oe();ut();ae();Ll=(e,t,r,n,o,i,a,l)=>{let d=ye(i),c=d===1?\"f32\":`vec${d}f`,m=d===1?\"vec2f\":`mat2x${d}f`,u=o*a,h=64;u===1&&(h=256);let w=[o,a,i/d],y=[o,a,2],g=[\"rank\",\"type\",\"type\"],x=[];x.push(...V(w,y));let $=v=>{let S=E(\"x\",t.dataType,3,d),T=E(\"scale\",r.dataType,r.dims),C=E(\"bias\",n.dataType,n.dims),A=M(\"output\",1,3,2),P=[S,T,C,A];return`\n var workgroup_shared : array<${m}, ${h}>;\n const workgroup_size = ${h}u;\n ${v.declareVariables(...P)}\n ${v.mainStart(h)}\n let batch = workgroup_index / uniforms.x_shape[1];\n let channel = workgroup_index % uniforms.x_shape[1];\n let hight = uniforms.x_shape[2];\n // initialize workgroup memory\n var sum = ${c}(0);\n var squared_sum = ${c}(0);\n for (var h = local_idx; h < hight; h += workgroup_size) {\n let value = ${c}(${S.get(\"batch\",\"channel\",\"h\")});\n sum += value;\n squared_sum += value * value;\n }\n workgroup_shared[local_idx] = ${m}(sum, squared_sum);\n workgroupBarrier();\n\n for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) {\n if (local_idx < currSize) {\n workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize];\n }\n workgroupBarrier();\n }\n if (local_idx == 0) {\n let sum_final = ${Ke(\"workgroup_shared[0][0]\",d)} / f32(hight * ${d});\n let squared_sum_final = ${Ke(\"workgroup_shared[0][1]\",d)} / f32(hight * ${d});\n\n let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${l}));\n let channel_scale = inv_std_dev * f32(scale[channel]);\n let channel_shift = f32(bias[channel]) - sum_final * channel_scale;\n output[workgroup_index] = vec2f(channel_scale, channel_shift);\n }\n }`};return e.compute({name:\"InstanceNormComputeChannelScaleShift\",shaderCache:{hint:`${d};${l};${h}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:y,dataType:1}],dispatchGroup:{x:u},programUniforms:x}),getShaderSource:$},{inputs:[t,r,n],outputs:[-1]})[0]},th=(e,t,r)=>{let n=t[0].dims,o=n,i=2,a=n[0],l=n[1],d=k.sizeFromDimension(n,i),c=ye(d),m=k.size(o)/c,u=Ll(e,t[0],t[1],t[2],a,d,l,r.epsilon),h=[a,l,d/c],w=[a,l],y=[\"type\",\"none\"],g=x=>{let $=E(\"x\",t[0].dataType,h.length,c),v=E(\"scale_shift\",1,w.length,2),S=M(\"output\",t[0].dataType,h.length,c),T=[$,v,S];return`\n ${x.registerUniform(\"output_size\",\"u32\").declareVariables(...T)}\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let outputIndices = ${S.offsetToIndices(\"global_idx\")};\n let batch = outputIndices[0];\n let channel = outputIndices[1];\n let scale_shift = ${v.getByIndices(\"vec2(batch, channel)\")};\n let value = ${$.getByOffset(\"global_idx\")} * ${S.type.value}(scale_shift.x) + ${S.type.value}(scale_shift.y);\n ${S.setByOffset(\"global_idx\",\"value\")};\n }`};e.compute({name:\"InstanceNormalization\",shaderCache:{hint:`${c}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...V(h,w,h)]}),getShaderSource:g},{inputs:[t[0],u]})},rh=(e,t,r)=>{let n=t[0].dims,o=n,i=n[0],a=n[n.length-1],l=k.sizeFromDimension(n,1)/a,d=ye(a),c=k.size(o)/d,m=[{type:12,data:l},{type:12,data:Math.floor(a/d)}],u=[\"type\",\"type\"],h=!1,w=[0,n.length-1];for(let $=0;$n[w[v]])),g=Ll(e,y,t[1],t[2],i,l,a,r.epsilon),x=$=>{let v=me(t[0].dataType),S=d===1?\"vec2f\":`mat${d}x2f`,T=P=>{let O=P===0?\"x\":\"y\",U=d===1?\"f32\":`vec${d}f`;switch(d){case 1:return`${v}(${U}(scale.${O}))`;case 2:return`vec2<${v}>(${U}(scale[0].${O}, scale[1].${O}))`;case 4:return`vec4<${v}>(${U}(scale[0].${O}, scale[1].${O}, scale[2].${O}, scale[3].${O}))`;default:throw new Error(`Not supported compoents ${d}`)}},C=E(\"input\",t[0].dataType,t[0].dims,d),A=M(\"output\",t[0].dataType,o,d);return`\n @group(0) @binding(0) var input : array<${C.type.storage}>;\n @group(0) @binding(1) var scale_input : array<${S}>;\n @group(0) @binding(2) var output : array<${A.type.storage}>;\n struct Uniforms {H: u32, C : u32};\n @group(0) @binding(3) var uniforms: Uniforms;\n\n ${$.mainStart()}\n let current_image_number = global_idx / (uniforms.C * uniforms.H);\n let current_channel_number = global_idx % uniforms.C;\n\n let scale_offset = current_image_number * uniforms.C + current_channel_number;\n let scale = scale_input[scale_offset];\n output[global_idx] = fma(input[global_idx], ${T(0)}, ${T(1)});\n }`};e.compute({name:\"InstanceNormalizationNHWC\",shaderCache:{hint:`${d}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:m}),getShaderSource:x},{inputs:[t[0],g]})},Gl=(e,t)=>{t.format===\"NHWC\"?rh(e,e.inputs,t):th(e,e.inputs,t)}});var nh,oh,Fl,ql=R(()=>{\"use strict\";te();oe();ae();nh=e=>{if(!e||e.length<2)throw new Error(\"layerNorm requires at least 2 inputs.\")},oh=(e,t,r)=>{let n=t.simplified,o=e[0].dims,i=e[1],a=!n&&e[2],l=o,d=k.normalizeAxis(t.axis,o.length),c=k.sizeToDimension(o,d),m=k.sizeFromDimension(o,d),u=k.size(i.dims),h=a?k.size(a.dims):0;if(u!==m||a&&h!==m)throw new Error(`Size of X.shape()[axis:] == ${m}.\n Size of scale and bias (if provided) must match this.\n Got scale size of ${u} and bias size of ${h}`);let w=[];for(let C=0;C1,v=r>2,S=C=>{let A=me(e[0].dataType),P=[E(\"x\",e[0].dataType,e[0].dims,y),E(\"scale\",i.dataType,i.dims,y)];a&&P.push(E(\"bias\",a.dataType,a.dims,y)),P.push(M(\"output\",e[0].dataType,l,y)),$&&P.push(M(\"mean_data_output\",1,w)),v&&P.push(M(\"inv_std_output\",1,w));let O=[{name:\"norm_count\",type:\"u32\"},{name:\"norm_size\",type:\"f32\"},{name:\"norm_size_vectorized\",type:\"u32\"},{name:\"epsilon\",type:\"f32\"}];return`\n ${C.registerUniforms(O).declareVariables(...P)}\n ${C.mainStart()}\n ${C.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.norm_count\")}\n let offset = global_idx * uniforms.norm_size_vectorized;\n var mean_vector = ${mo(\"f32\",y)};\n var mean_square_vector = ${mo(\"f32\",y)};\n\n for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {\n let value = ${At(A,y,\"x[h + offset]\")};\n mean_vector += value;\n mean_square_vector += value * value;\n }\n let mean = ${Ke(\"mean_vector\",y)} / uniforms.norm_size;\n let inv_std_dev = inverseSqrt(${Ke(\"mean_square_vector\",y)} / uniforms.norm_size ${n?\"\":\"- mean * mean\"} + uniforms.epsilon);\n\n for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {\n let f32input = ${At(A,y,\"x[j + offset]\")};\n let f32scale = ${At(A,y,\"scale[j]\")};\n output[j + offset] = ${P[0].type.value}((f32input ${n?\"\":\"- mean\"}) * inv_std_dev * f32scale\n ${a?`+ ${At(A,y,\"bias[j]\")}`:\"\"}\n );\n }\n\n ${$?\"mean_data_output[global_idx] = mean\":\"\"};\n ${v?\"inv_std_output[global_idx] = inv_std_dev\":\"\"};\n }`},T=[{dims:l,dataType:e[0].dataType}];return $&&T.push({dims:w,dataType:1}),v&&T.push({dims:w,dataType:1}),{name:\"LayerNormalization\",shaderCache:{hint:`${y};${r};${n}`,inputDependencies:g},getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(c/64)},programUniforms:x}),getShaderSource:S}},Fl=(e,t)=>{nh(e.inputs),e.compute(oh(e.inputs,t,e.outputCount))}});var ih,jl,Kl=R(()=>{\"use strict\";oe();on();ir();ih=e=>{if(!e||e.length!==2)throw new Error(\"MatMul requires 2 inputs.\");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error(\"shared dimension does not match.\")},jl=e=>{ih(e.inputs);let t=et.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error(\"Can't use matmul on the given tensors\");let r=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];if(r<8&&n<8)e.compute(nn(e.inputs,{activation:\"\"},t));else{let o=t[t.length-2],i=k.size(e.inputs[0].dims.slice(0,-2)),a=k.size(e.inputs[1].dims.slice(0,-2));if(i!==1&&o===1&&a===1){let l=e.inputs[0].reshape([1,i,n]),d=e.inputs[1].reshape([1,n,r]),c=[1,i,r],m=[l,d];e.compute(or(m,{activation:\"\"},t,c),{inputs:m})}else e.compute(or(e.inputs,{activation:\"\"},t))}}});var ah,sh,uh,Yl,Zl,Xl=R(()=>{\"use strict\";te();oe();Ie();ae();ah=(e,t)=>{if(e.length<3||e.length>4)throw new Error(\"MatMulNBits requires 3 or 4 inputs\");let r=e[0],n=r.dims.length;if(r.dims[n-1]!==t.k)throw new Error(\"The last dim of input shape does not match the k value\");let o=Math.floor((t.k+t.blockSize-1)/t.blockSize),i=t.blockSize/8*t.bits,a=e[1];if(!k.areEqual(a.dims,[t.n,o,i]))throw new Error(\"The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize\");let d=e[2].dims;if(k.size(d)!==t.n*o)throw new Error(\"scales input size error.\");if(e.length===4){let m=e[3].dims,u=t.bits>4?t.n*o:t.n*Math.floor((o+1)/2);if(k.size(m)!==u)throw new Error(\"zeroPoints input size error.\")}},sh=(e,t)=>{let r=e[0].dims,n=r.length,o=r[n-2],i=t.k,a=t.n,l=r.slice(0,n-2),d=k.size(l),m=e[1].dims[2]/4,u=e[0].dataType,h=ye(t.k),w=ye(m),y=ye(a),g=l.concat([o,a]),x=o>1&&a/y%2===0?2:1,$=k.size(g)/y/x,v=64,S=[],T=[d,o,i/h],C=k.convertShape(e[1].dims).slice();C.splice(-1,1,m/w),S.push(...V(T)),S.push(...V(C)),S.push(...V(e[2].dims)),e.length===4&&S.push(...V(k.convertShape(e[3].dims)));let A=[d,o,a/y];S.push(...V(A));let P=O=>{let U=T.length,L=E(\"a\",e[0].dataType,U,h),j=E(\"b\",12,C.length,w),K=E(\"scales\",e[2].dataType,e[2].dims.length),W=[L,j,K],ee=e.length===4?E(\"zero_points\",12,e[3].dims.length):void 0;ee&&W.push(ee);let ue=A.length,Z=M(\"output\",e[0].dataType,ue,y),J=me(e[0].dataType),Q=(()=>{switch(h){case 1:return`array<${J}, 8>`;case 2:return`mat4x2<${J}>`;case 4:return`mat2x4<${J}>`;default:throw new Error(`${h}-component is not supported.`)}})(),ne=()=>{let $e=`\n // reuse a data\n var input_offset = ${L.indicesToOffset(`${L.type.indices}(batch, row, word_offset)`)};\n var a_data: ${Q};\n for (var j: u32 = 0; j < ${8/h}; j++) {\n a_data[j] = ${L.getByOffset(\"input_offset\")};\n input_offset++;\n }\n `;for(let de=0;de> 4) & b_mask);\n b_quantized_values = ${Q}(${Array.from({length:4},(N,q)=>`${J}(b_value_lower[${q}]), ${J}(b_value_upper[${q}])`).join(\", \")});\n b_dequantized_values = ${(()=>h===1?`${Q}(${Array.from({length:8},(N,q)=>`(b_quantized_values[${q}] - ${ee?`zero_point${de}`:\"zero_point\"}) * scale${de}`).join(\", \")});`:`(b_quantized_values - ${Q}(${Array(8).fill(`${ee?`zero_point${de}`:\"zero_point\"}`).join(\",\")})) * scale${de};`)()};\n workgroup_shared[local_id.x * ${x} + ${Math.floor(de/y)}]${y>1?`[${de%y}]`:\"\"} += ${Array.from({length:8/h},(N,q)=>`${h===1?`a_data[${q}] * b_dequantized_values[${q}]`:`dot(a_data[${q}], b_dequantized_values[${q}])`}`).join(\" + \")};\n `;return $e},we=()=>{let $e=`\n var col_index = col * ${y};\n ${ee?`\n let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2;\n var zero_point_byte_count: u32;\n var zero_point_word_index: u32;\n var zero_point_byte_offset: u32;\n let zero_point_nibble_offset: u32 = block & 0x1u;\n var zero_point_bits_offset: u32;\n var zero_point_word: u32;`:`\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${J}(8);`}\n `;for(let de=0;de> 0x1u);\n zero_point_word_index = zero_point_byte_count >> 0x2u;\n zero_point_byte_offset = zero_point_byte_count & 0x3u;\n zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n zero_point_word = ${ee.getByOffset(\"zero_point_word_index\")} >> zero_point_bits_offset;\n let zero_point${de} = ${J}((zero_point_word) & 0xFu);`:\"\"}\n col_index += 1;`;return $e},Ae=()=>{let $e=`col_index = col * ${y};`;for(let de=0;de;\n var b_value_upper: vec4;\n var b_quantized_values: ${Q};\n var b_dequantized_values: ${Q};`,$e};return`\n var workgroup_shared: array<${Z.type.value}, ${x*v}>;\n ${O.declareVariables(...W,Z)}\n ${O.mainStart([v,1,1])}\n let output_indices = ${Z.offsetToIndices(`(global_idx / ${v}) * ${x}`)};\n let col = output_indices[2];\n let row = output_indices[1];\n let batch = output_indices[0];\n let nBlocksPerCol = uniforms.b_shape[1];\n\n for (var block = local_id.x; block < nBlocksPerCol; block += ${v}) {\n //process one block\n var word_offset: u32 = block * ${t.blockSize/h};\n ${we()}\n for (var word: u32 = 0; word < ${m}; word += ${w}) {\n ${Ae()}\n for (var i: u32 = 0; i < ${w}; i++) {\n ${ne()}\n word_offset += ${8/h};\n }\n }\n }\n workgroupBarrier();\n\n if (local_id.x < ${x}) {\n var output_value: ${Z.type.value} = ${Z.type.value}(0);\n var workgroup_shared_offset: u32 = local_id.x;\n for (var b: u32 = 0u; b < ${v}u; b++) {\n output_value += workgroup_shared[workgroup_shared_offset];\n workgroup_shared_offset += ${x};\n }\n ${Z.setByIndices(`${Z.type.indices}(batch, row, col + local_id.x)`,\"output_value\")};\n }\n }`};return{name:\"MatMulNBits\",shaderCache:{hint:`${t.blockSize};${t.bits};${h};${w};${y};${x};${v}`,inputDependencies:Array(e.length).fill(\"rank\")},getRunData:()=>({outputs:[{dims:g,dataType:u}],dispatchGroup:{x:$},programUniforms:S}),getShaderSource:P}},uh=(e,t)=>{let r=e[0].dims,n=r.length,o=r[n-2],i=t.k,a=t.n,l=r.slice(0,n-2),d=k.size(l),m=e[1].dims[2]/4,u=e[0].dataType,h=ye(t.k),w=ye(m),y=l.concat([o,a]),g=128,x=a%8===0?8:a%4===0?4:1,$=g/x,v=$*w*8,S=v/h,T=v/t.blockSize,C=k.size(y)/x,A=[],P=[d,o,i/h],O=k.convertShape(e[1].dims).slice();O.splice(-1,1,m/w),A.push(...V(P)),A.push(...V(O)),A.push(...V(e[2].dims)),e.length===4&&A.push(...V(k.convertShape(e[3].dims)));let U=[d,o,a];A.push(...V(U));let L=j=>{let K=P.length,W=E(\"a\",e[0].dataType,K,h),ee=E(\"b\",12,O.length,w),ue=E(\"scales\",e[2].dataType,e[2].dims.length),Z=[W,ee,ue],J=e.length===4?E(\"zero_points\",12,e[3].dims.length):void 0;J&&Z.push(J);let Q=U.length,ne=M(\"output\",e[0].dataType,Q),we=me(e[0].dataType),Ae=()=>{switch(h){case 1:return`\n let a_data0 = vec4<${we}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]);\n let a_data1 = vec4<${we}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return`\n let a_data0 = vec4<${we}>(sub_a[word_offset], sub_a[word_offset + 1]);\n let a_data1 = vec4<${we}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return`\n let a_data0 = sub_a[word_offset];\n let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${h}-component is not supported.`)}};return`\n var sub_a: array<${W.type.value}, ${S}>;\n var inter_results: array, ${x}>;\n ${j.declareVariables(...Z,ne)}\n ${j.mainStart([$,x,1])}\n let output_indices = ${ne.offsetToIndices(`workgroup_index * ${x}`)};\n let col = output_indices[2];\n let row = output_indices[1];\n let batch = output_indices[0];\n let n_blocks_per_col = uniforms.b_shape[1];\n let num_tiles = (n_blocks_per_col - 1) / ${T} + 1;\n\n // Loop over shared dimension.\n for (var tile: u32 = 0; tile < num_tiles; tile += 1) {\n let a_col_start = tile * ${S};\n // load one tile A data into shared memory.\n for (var a_offset = local_idx; a_offset < ${S}; a_offset += ${g})\n {\n let a_col = a_col_start + a_offset;\n if (a_col < uniforms.a_shape[2])\n {\n sub_a[a_offset] = ${W.getByIndices(`${W.type.indices}(batch, row, a_col)`)};\n } else {\n sub_a[a_offset] = ${W.type.value}(0);\n }\n }\n workgroupBarrier();\n\n // each thread process one block\n let b_row = col + local_id.y;\n let block = tile * ${T} + local_id.x;\n ${J?`\n let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2;\n let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u);\n let zero_point_word_index = zero_point_byte_count >> 0x2u;\n let zero_point_byte_offset = zero_point_byte_count & 0x3u;\n let zero_point_nibble_offset: u32 = block & 0x1u;\n let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n let zero_point_word = ${J.getByOffset(\"zero_point_word_index\")} >> zero_point_bits_offset;\n let zero_point = ${we}((zero_point_word) & 0xFu);`:`\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${we}(8);`}\n let scale = ${ue.getByOffset(\"b_row * n_blocks_per_col + block\")};\n let b_data = ${ee.getByIndices(`${ee.type.indices}(b_row, block, 0)`)};\n var word_offset = local_id.x * ${t.blockSize/h};\n for (var i: u32 = 0; i < ${w}; i++) {\n ${Ae()}\n let b_value = ${w===1?\"b_data\":\"b_data[i]\"};\n let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu);\n let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu);\n let b_quantized_values = mat2x4<${we}>(${Array.from({length:4},($e,de)=>`${we}(b_value_lower[${de}]), ${we}(b_value_upper[${de}])`).join(\", \")});\n let b_dequantized_values = (b_quantized_values - mat2x4<${we}>(${Array(8).fill(\"zero_point\").join(\",\")})) * scale;\n inter_results[local_id.y][local_id.x] += ${Array.from({length:2},($e,de)=>`${`dot(a_data${de}, b_dequantized_values[${de}])`}`).join(\" + \")};\n word_offset += ${8/h};\n }\n workgroupBarrier();\n }\n\n if (local_idx < ${x}) {\n var output_value: ${ne.type.value} = ${ne.type.value}(0);\n for (var b = 0u; b < ${$}; b++) {\n output_value += inter_results[local_idx][b];\n }\n if (col + local_idx < uniforms.output_shape[2])\n {\n ${ne.setByIndices(`${ne.type.indices}(batch, row, col + local_idx)`,\"output_value\")}\n }\n }\n }`};return{name:\"BlockwiseMatMulNBits32\",shaderCache:{hint:`${t.blockSize};${h};${w};${$};${x}`,inputDependencies:Array(e.length).fill(\"rank\")},getRunData:()=>({outputs:[{dims:y,dataType:u}],dispatchGroup:{x:C},programUniforms:A}),getShaderSource:L}},Yl=(e,t)=>{ah(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor(\"intel\")&&e.adapterInfo.isArchitecture(\"gen-12lp\")?e.compute(uh(e.inputs,t)):e.compute(sh(e.inputs,t))},Zl=e=>re(e)});var lh,dh,ch,ph,mh,fh,hh,gh,Ql,Jl=R(()=>{\"use strict\";te();oe();ae();lh=e=>{if(!e||e.length<1)throw new Error(\"Too few inputs\");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error(\"Input type must be float or float16.\");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error(\"The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].\")}},dh=(e,t,r)=>{let n=\"\";for(let o=t-1;o>=0;--o)n+=`\n k = i32(${e.indicesGet(\"indices\",o)}) - ${F(\"uniforms.pads\",o,r)};\n if (k < 0) {\n break;\n }\n if (k >= i32(${F(\"uniforms.x_shape\",o,t)})) {\n break;\n }\n offset += k * i32(${F(\"uniforms.x_strides\",o,t)});\n `;return`\n value = ${e.type.value}(uniforms.constant_value);\n for (var i = 0; i < 1; i++) {\n var offset = 0;\n var k = 0;\n ${n}\n value = x[offset];\n }\n `},ch=(e,t,r)=>{let n=\"\";for(let o=t-1;o>=0;--o)n+=`\n k = i32(${e.indicesGet(\"indices\",o)}) - ${F(\"uniforms.pads\",o,r)};\n if (k < 0) {\n k = -k;\n }\n {\n let _2n_1 = 2 * (i32(${F(\"uniforms.x_shape\",o,t)}) - 1);\n k = k % _2n_1;\n if(k >= i32(${F(\"uniforms.x_shape\",o,t)})) {\n k = _2n_1 - k;\n }\n }\n offset += k * i32(${F(\"uniforms.x_strides\",o,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${n}\n value = x[offset];\n `},ph=(e,t,r)=>{let n=\"\";for(let o=t-1;o>=0;--o)n+=`\n k = i32(${e.indicesGet(\"indices\",o)}) - ${F(\"uniforms.pads\",o,r)};\n if (k < 0) {\n k = 0;\n }\n if (k >= i32(${F(\"uniforms.x_shape\",o,t)})) {\n k = i32(${F(\"uniforms.x_shape\",o,t)}) - 1;\n }\n offset += k * i32(${F(\"uniforms.x_strides\",o,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${n}\n value = x[offset];\n `},mh=(e,t,r)=>{let n=\"\";for(let o=t-1;o>=0;--o)n+=`\n k = i32(${e.indicesGet(\"indices\",o)}) - ${F(\"uniforms.pads\",o,r)};\n if (k < 0) {\n k += i32(${F(\"uniforms.x_shape\",o,t)}]);\n }\n if (k >= i32(${F(\"uniforms.x_shape\",o,t)})) {\n k -= i32(${F(\"uniforms.x_shape\",o,t)});\n }\n offset += k * i32(${F(\"uniforms.x_strides\",o,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${n}\n value = x[offset];\n `},fh=(e,t,r)=>{switch(r.mode){case 0:return dh(e,t,r.pads.length);case 1:return ch(e,t,r.pads.length);case 2:return ph(e,t,r.pads.length);case 3:return mh(e,t,r.pads.length);default:throw new Error(\"Invalid mode\")}},hh=(e,t)=>{let r=k.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,o=k.size(r),i=[{type:12,data:o},{type:6,data:t.pads}],a=e.length>=3&&e[2].data;t.mode===0&&i.push({type:a?e[2].dataType:1,data:t.value}),i.push(...V(e[0].dims,r));let l=[\"rank\"],d=c=>{let m=M(\"output\",e[0].dataType,r.length),u=E(\"x\",e[0].dataType,n.length),h=u.type.value,w=fh(m,n.length,t),y=[{name:\"output_size\",type:\"u32\"},{name:\"pads\",type:\"i32\",length:t.pads.length}];return t.mode===0&&y.push({name:\"constant_value\",type:a?h:\"f32\"}),`\n ${c.registerUniforms(y).declareVariables(u,m)}\n ${c.mainStart()}\n ${c.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let indices = ${m.offsetToIndices(\"global_idx\")};\n\n var value = ${h}(0);\n ${w}\n output[global_idx] = value;\n }`};return{name:\"Pad\",shaderCache:{hint:`${t.mode}${a}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k.size(r)/64)},programUniforms:i}),getShaderSource:d}},gh=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,i=new Int32Array(2*o).fill(0);if(e.length>=4){let l=e[3].getBigInt64Array();for(let d=0;di[Number(d)]=Number(l));let a=[];return i.forEach(l=>a.push(l)),{mode:t.mode,value:n,pads:a}}else return t},Ql=(e,t)=>{lh(e.inputs);let r=gh(e.inputs,t);e.compute(hh(e.inputs,r),{inputs:[0]})}});var un,ed,td,rd,nd,bh,yh,od,id,ad,sd,ud,ld,dd,cd,pd,md,fd,hd,gd=R(()=>{\"use strict\";He();te();oe();ae();un=e=>{if(ve.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error(\"Pool ops requires 1 input.\")},ed=(e,t,r)=>{let n=t.format===\"NHWC\",o=e.dims.slice();n&&o.splice(1,0,o.pop());let i=Object.hasOwnProperty.call(t,\"dilations\"),a=t.kernelShape.slice(),l=t.strides.slice(),d=i?t.dilations.slice():[],c=t.pads.slice();It.adjustPoolAttributes(r,o,a,l,d,c);let m=It.computePoolOutputShape(r,o,l,d,a,c,t.autoPad),u=Object.assign({},t);i?Object.assign(u,{kernelShape:a,strides:l,pads:c,dilations:d,cacheKey:t.cacheKey}):Object.assign(u,{kernelShape:a,strides:l,pads:c,cacheKey:t.cacheKey});let h=m.slice();return h.push(h.splice(1,1)[0]),[u,n?h:m]},td=(e,t)=>{let r=t.format===\"NHWC\",n=k.size(e),o=k.size(t.kernelShape),i=[{type:12,data:n},{type:12,data:o}],a=[{name:\"outputSize\",type:\"u32\"},{name:\"kernelSize\",type:\"u32\"}];if(t.kernelShape.length<=2){let l=t.kernelShape[t.kernelShape.length-1],d=t.strides[t.strides.length-1],c=t.pads[t.pads.length/2-1],m=t.pads[t.pads.length-1],u=!!(c+m);i.push({type:12,data:l},{type:12,data:d},{type:12,data:c},{type:12,data:m}),a.push({name:\"kw\",type:\"u32\"},{name:\"sw\",type:\"u32\"},{name:\"pwStart\",type:\"u32\"},{name:\"pwEnd\",type:\"u32\"});let h=!1;if(t.kernelShape.length===2){let w=t.kernelShape[t.kernelShape.length-2],y=t.strides[t.strides.length-2],g=t.pads[t.pads.length/2-2],x=t.pads[t.pads.length-2];h=!!(g+x),i.push({type:12,data:w},{type:12,data:y},{type:12,data:g},{type:12,data:x}),a.push({name:\"kh\",type:\"u32\"},{name:\"sh\",type:\"u32\"},{name:\"phStart\",type:\"u32\"},{name:\"phEnd\",type:\"u32\"})}return[i,a,!0,u,h]}else{if(r)throw new Error(\"Pooling with kernelShape.length > 2 is not supported for NHWC format.\");let l=k.computeStrides(t.kernelShape);i.push({type:12,data:l},{type:12,data:t.pads},{type:12,data:t.strides}),a.push({name:\"kernelStrides\",type:\"u32\",length:l.length},{name:\"pads\",type:\"u32\",length:t.pads.length},{name:\"strides\",type:\"u32\",length:t.strides.length});let d=t.pads.reduce((c,m)=>c+m);return[i,a,!!d,!1,!1]}},rd=(e,t,r,n,o,i,a,l,d,c,m,u)=>{let h=o.format===\"NHWC\",w=t.type.value,y=M(\"output\",t.type.tensor,n);if(o.kernelShape.length<=2){let g=\"\",x=\"\",$=\"\",v=r-(h?2:1);if(m?g=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i;\n if (xIndices[${v}] < 0 || xIndices[${v}]\n >= uniforms.x_shape[${v}]) {\n pad++;\n continue;\n }\n let x_val = x[${t.indicesToOffset(\"xIndices\")}];\n ${i}\n }`:g=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i;\n let x_val = x[${t.indicesToOffset(\"xIndices\")}];\n ${i}\n }`,o.kernelShape.length===2){let T=r-(h?3:2);u?x=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j;\n if (xIndices[${T}] < 0 || xIndices[${T}] >= uniforms.x_shape[${T}]) {\n pad += i32(uniforms.kw);\n continue;\n }\n `:x=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j;\n `,$=`\n }\n `}return`\n ${e.registerUniforms(d).declareVariables(t,y)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n\n let indices = ${y.offsetToIndices(\"global_idx\")};\n var xIndices = ${y.offsetToIndices(\"global_idx\")};\n\n var value = ${w}(${l});\n var pad = 0;\n ${x}\n ${g}\n ${$}\n ${a}\n\n output[global_idx] = value;\n }`}else{if(h)throw new Error(\"Pooling with kernelShape.length > 2 is not supported for NHWC format.\");let g=o.kernelShape.length,x=o.pads.length,$=\"\";return c?$=`\n if (xIndices[j] >= uniforms.x_shape[j]) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n let x_val = x[${t.indicesToOffset(\"xIndices\")}];\n ${i}\n }`:$=`\n }\n let x_val = x[${t.indicesToOffset(\"xIndices\")}];\n ${i}\n `,`\n ${e.registerUniforms(d).declareVariables(t,y)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n let indices = ${y.offsetToIndices(\"global_idx\")};\n var xIndices = ${y.offsetToIndices(\"global_idx\")};\n\n var offsets: array;\n\n var value = ${w}(${l});\n var pad = 0;\n var isPad = false;\n\n for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {\n var offset = i;\n for (var j = 0u; j < ${g-1}u; j++) {\n offsets[j] = offset / ${F(\"uniforms.kernelStrides\",\"j\",g)};\n offset -= offsets[j] * ${F(\"uniforms.kernelStrides\",\"j\",g)};\n }\n offsets[${g-1}] = offset;\n\n isPad = false;\n for (var j = ${r-g}u; j < ${r}u; j++) {\n xIndices[j] = indices[j] * ${F(\"uniforms.strides\",`j - ${r-g}u`,g)}\n + offsets[j - ${r-g}u] - ${F(\"uniforms.pads\",\"j - 2u\",x)};\n ${$}\n }\n ${a}\n\n output[global_idx] = value;\n }`}},nd=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,bh=e=>`${nd(e)};${e.countIncludePad}`,yh=e=>`${nd(e)};${e.storageOrder};${e.dilations}`,od=e=>({format:e.format,autoPad:[\"NOTSET\",\"VALID\",\"SAME_UPPER\",\"SAME_LOWER\"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),id=(e,t,r,n)=>{let[o,i]=ed(t,n,r),a=E(\"x\",t.dataType,t.dims.length),l=a.type.value,d=\"value += x_val;\",c=\"\";o.countIncludePad?c+=`value /= ${l}(uniforms.kernelSize);`:c+=`value /= ${l}(i32(uniforms.kernelSize) - pad);`;let[m,u,h,w,y]=td(i,o);m.push(...V(t.dims,i));let g=[\"rank\"];return{name:e,shaderCache:{hint:`${n.cacheKey};${h};${w};${y}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(k.size(i)/64)},programUniforms:m}),getShaderSource:x=>rd(x,a,t.dims.length,i.length,o,d,c,0,u,h,w,y)}},ad=e=>{let t=e.count_include_pad!==0,r=od(e);if(r.ceilMode!==0)throw new Error(\"using ceil() in shape computation is not yet supported for AveragePool\");let n={countIncludePad:t,...r,cacheKey:\"\"};return{...n,cacheKey:bh(n)}},sd=(e,t)=>{un(e.inputs),e.compute(id(\"AveragePool\",e.inputs[0],!1,t))},ud={autoPad:\"\",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},ld=e=>{let t=e.format;return{format:t,...ud,cacheKey:t}},dd=(e,t)=>{un(e.inputs),e.compute(id(\"GlobalAveragePool\",e.inputs[0],!0,t))},cd=(e,t,r,n)=>{let[o,i]=ed(t,n,r),a=`\n value = max(x_val, value);\n `,l=\"\",d=E(\"x\",t.dataType,t.dims.length),c=[\"rank\"],[m,u,h,w,y]=td(i,o);return m.push(...V(t.dims,i)),{name:e,shaderCache:{hint:`${n.cacheKey};${h};${w};${y}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(k.size(i)/64)},programUniforms:m}),getShaderSource:g=>rd(g,d,t.dims.length,i.length,o,a,l,t.dataType===10?-65504:-1e5,u,h,w,y)}},pd=(e,t)=>{un(e.inputs),e.compute(cd(\"MaxPool\",e.inputs[0],!1,t))},md=e=>{let t=e.storage_order,r=e.dilations,n=od(e);if(t!==0)throw new Error(\"column major storage order is not yet supported for MaxPool\");if(n.ceilMode!==0)throw new Error(\"using ceil() in shape computation is not yet supported for MaxPool\");let o={storageOrder:t,dilations:r,...n,cacheKey:\"\"};return{...o,cacheKey:yh(o)}},fd=e=>{let t=e.format;return{format:t,...ud,cacheKey:t}},hd=(e,t)=>{un(e.inputs),e.compute(cd(\"GlobalMaxPool\",e.inputs[0],!0,t))}});var _h,vh,bd,yd,wd=R(()=>{\"use strict\";te();oe();Ie();ae();_h=(e,t)=>{if(e.length<2||e.length>3)throw new Error(\"DequantizeLinear requires 2 or 3 inputs.\");if(e.length===3&&e[1].dims===e[2].dims)throw new Error(\"x-scale and x-zero-point must have the same shape.\");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error(\"x and x-zero-point must have the same data type.\");if(e[0].dataType===6&&e.length>2)throw new Error(\"In the case of dequantizing int32 there is no zero point.\");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error(\"scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.\");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error(\"x and x-zero-point must have the same data type.\");if(e[1].dims.length!==e[2].dims.length)throw new Error(\"scale and zero-point inputs must have the same rank.\");if(!e[1].dims.map((r,n)=>r===e[2].dims[n]).reduce((r,n)=>r&&n,!0))throw new Error(\"scale and zero-point inputs must have the same shape.\")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error(\"blockSize must be set only for block quantization.\");if(!e[1].dims.map((o,i)=>i===t.axis||o===e[0].dims[i]).reduce((o,i)=>o&&i,!0))throw new Error(\"For block qunatization, scale input shape to match the input shape except for the axis\");if(e[1].dims.length!==e[0].dims.length)throw new Error(\"For block qunatization the scale input rank must be the same as the x rank.\");let r=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(n-1)-1))throw new Error(\"blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].\")}},vh=(e,t)=>{let r=k.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,o=n===3,i=e[0].dims,a=e[1].dataType,l=k.size(i),d=n===3||n===2,c=d?[Math.ceil(k.size(e[0].dims)/4)]:e[0].dims,m=e[1].dims,u=e.length>2?e[2]:void 0,h=u?d?[Math.ceil(k.size(u.dims)/4)]:u.dims:void 0,w=m.length===0||m.length===1&&m[0]===1,y=w===!1&&m.length===1,g=ye(l),x=w&&(!d||g===4),$=x?g:1,v=x&&!d?g:1,S=E(\"input\",d?12:n,c.length,v),T=E(\"scale\",a,m.length),C=u?E(\"zero_point\",d?12:n,h.length):void 0,A=M(\"output\",a,i.length,$),P=[S,T];C&&P.push(C);let O=[c,m];u&&O.push(h);let U=[{type:12,data:l/$},{type:12,data:r},{type:12,data:t.blockSize},...V(...O,i)],L=j=>{let K=[{name:\"output_size\",type:\"u32\"},{name:\"axis\",type:\"u32\"},{name:\"block_size\",type:\"u32\"}];return`\n ${j.registerUniforms(K).declareVariables(...P,A)}\n ${j.mainStart()}\n ${j.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let output_indices = ${A.offsetToIndices(\"global_idx\")};\n\n // Set input x\n ${(()=>d?`\n let input = ${S.getByOffset(\"global_idx / 4\")};\n let x_vec = ${o?\"unpack4xI8(input)\":\"unpack4xU8(input)\"};\n let x_value = ${$===1?\"x_vec[global_idx % 4]\":\"x_vec\"};`:`let x_value = ${S.getByOffset(\"global_idx\")};`)()};\n\n // Set scale input\n ${(()=>w?`let scale_value= ${T.getByOffset(\"0\")}`:y?`\n let scale_index = ${A.indicesGet(\"output_indices\",\"uniforms.axis\")};\n let scale_value= ${T.getByOffset(\"scale_index\")};`:`\n var scale_indices: ${T.type.indices} = output_indices;\n let index = ${T.indicesGet(\"scale_indices\",\"uniforms.axis\")} / uniforms.block_size;\n ${T.indicesSet(\"scale_indices\",\"uniforms.axis\",\"index\")};\n let scale_value= ${T.getByIndices(\"scale_indices\")};`)()};\n\n // Set zero-point input\n ${(()=>C?w?d?`\n let zero_point_input = ${C.getByOffset(\"0\")};\n let zero_point_vec = ${o?\"unpack4xI8(zero_point_input)\":\"unpack4xU8(zero_point_input)\"};\n let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${C.getByOffset(\"0\")}`:y?d?`\n let zero_point_index = ${A.indicesGet(\"output_indices\",\"uniforms.axis\")};\n let zero_point_input = ${C.getByOffset(\"zero_point_index / 4\")};\n let zero_point_vec = ${o?\"unpack4xI8(zero_point_input)\":\"unpack4xU8(zero_point_input)\"};\n let zero_point_value = zero_point_vec[zero_point_index % 4]`:`\n let zero_point_index = ${A.indicesGet(\"output_indices\",\"uniforms.axis\")};\n let zero_point_value = ${C.getByOffset(\"zero_point_index\")};`:d?`\n let zero_point_offset = ${T.indicesToOffset(\"scale_indices\")};\n let zero_point_input = ${C.getByOffset(\"zero_point_offset / 4\")};\n let zero_point_vec = ${o?\"unpack4xI8(zero_point_input)\":\"unpack4xU8(zero_point_input)\"};\n let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${C.getByIndices(\"scale_indices\")};`:`let zero_point_value = ${d?o?\"i32\":\"u32\":S.type.value}(0);`)()};\n // Compute and write output\n ${A.setByOffset(\"global_idx\",`${A.type.value}(x_value - zero_point_value) * scale_value`)};\n }`};return{name:\"DequantizeLinear\",shaderCache:{hint:t.cacheKey,inputDependencies:C?[\"rank\",\"rank\",\"rank\"]:[\"rank\",\"rank\"]},getShaderSource:L,getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:Math.ceil(l/$/64),y:1,z:1},programUniforms:U})}},bd=(e,t)=>{_h(e.inputs,t),e.compute(vh(e.inputs,t))},yd=e=>re({axis:e.axis,blockSize:e.blockSize})});var $h,xh,_d,vd=R(()=>{\"use strict\";He();te();ae();$h=(e,t,r)=>{let n=e===t,o=et&&r>0;if(n||o||i)throw new Error(\"Range these inputs' contents are invalid.\")},xh=(e,t,r,n)=>{let o=Math.abs(Math.ceil((t-e)/r)),i=[o],a=o,l=[{type:12,data:a},{type:n,data:e},{type:n,data:r},...V(i)],d=c=>{let m=M(\"output\",n,i.length),u=m.type.value,h=[{name:\"outputSize\",type:\"u32\"},{name:\"start\",type:u},{name:\"delta\",type:u}];return`\n ${c.registerUniforms(h).declareVariables(m)}\n ${c.mainStart()}\n ${c.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n output[global_idx] = uniforms.start + ${u}(global_idx) * uniforms.delta;\n }`};return{name:\"Range\",shaderCache:{hint:`${n}`},getShaderSource:d,getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l})}},_d=e=>{let t=0,r=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),ve.webgpu.validateInputContent&&$h(t,r,n),e.compute(xh(t,r,n,e.inputs[0].dataType),{inputs:[]})}});var Sh,Th,Ih,Ch,Ah,kh,Eh,Ph,zh,Oh,Dh,$d,Bh,Mh,Rh,Uh,Vh,xd,Sd,Td=R(()=>{\"use strict\";te();oe();Ie();ae();Sh=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error(\"Resize requires scales input values to be positive\")})),e.length>0){if(t.mode===\"linear\"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and\n one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode===\"cubic\"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error(\"Resize requires scales input size to be 2 or 4 for cubic mode\")}},Th=(e,t,r)=>{t.every(o=>o>=0&&o{throw new Error(\"Resize requires axes input values to be positive and less than rank\")}));let n=new Array(r).fill(1);return t.forEach((o,i)=>n[o]=e[i]),n},Ih=(e,t,r,n,o,i)=>{let[a,l,d]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],c=e[0].dims.length;if(a>0&&e.length>a&&e[a].dims.length>0)e[a].getFloat32Array().forEach(m=>i.push(m));else if(t.coordinateTransformMode===\"tf_crop_and_resize\")throw new Error(\"Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize\");if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0){if(e[l].getFloat32Array().forEach(m=>n.push(m)),n.length!==0&&n.length!==c&&r>=18&&n.length!==t.axes.length)throw new Error(\"Resize requires scales input size to be same as input rank or axes size for opset 18 and up\");Sh(n,t),t.axes.length>0&&Th(n,t.axes,c).forEach((m,u)=>n[u]=m)}if(d>0&&e.length>d&&e[d].dims.length===1&&e[d].dims[0]>0&&(e[d].getBigInt64Array().forEach(m=>o.push(Number(m))),o.length!==0&&o.length!==c&&r>=18&&o.length!==t.axes.length))throw new Error(\"Resize requires sizes input size to be same as input rank or axes size for opset 18 and up\");if(t.axes.length>0){if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires \"scales\" input size to be of axes rank when axes attributes is specified');if(o.length!==0&&o.length!==t.axes.length)throw new Error('Resize requires \"sizes\" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<\"u\"&&typeof o<\"u\"&&n.length>0&&o.length>c)throw new Error(\"Resize requires only of scales or sizes to be specified\")},Ch=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,\n lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case\"asymmetric\":return`return ${t}(xResized) / ${t}(xScale);`;case\"pytorch_half_pixel\":return`if (lengthResized > 1) {\n return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;\n } else {\n return 0.0;\n }`;case\"tf_half_pixel_for_nn\":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case\"align_corners\":return`if (lengthResized == 1) {\n return 0.0;\n } else {\n // The whole part and the fractional part are calculated separately due to inaccuracy of floating\n // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an\n // offset-by-one error later in floor().\n let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1));\n let fract =\n ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1);\n return whole + fract;\n }`;case\"tf_crop_and_resize\":return`if (lengthResized > 1) {\n return ${t}(roiStart) * ${t}(lengthOriginal - 1) +\n (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /\n ${t}(lengthResized - 1);\n } else {\n return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);\n }`;case\"half_pixel_symmetric\":return`const outputWidth = ${t}xScale * ${t}(lengthResized);\n const adjustment = ${t}(lengthResized) / outputWidth;\n const center = ${t}(lengthOriginal) / 2;\n const offset = center * (1 - adjustment);\n return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case\"half_pixel\":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+\"}\",Ah=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case\"round_prefer_ceil\":return\"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }\";case\"floor\":return\"return floor(xOriginal);\";case\"ceil\":return\"return ceil(xOriginal);\";case\"round_prefer_floor\":return\"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }\";case\"simple\":default:if(t<11)return\"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }\";throw new Error(`Nearest mode ${e} is not supported`)}})()+\"}\",kh=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),o=e.length===0?n:e.slice();return t.length>0?(t.forEach((i,a)=>{n[i]=o[a],n[a+r]=o[t.length+a]}),n):o},Eh=(e,t,r,n)=>{let o=[];if(r.length>0)if(n.length>0){if(e.forEach(i=>o.push(i)),Math.max(...n)>e.length)throw new Error(\"axes is out of bound\");n.forEach((i,a)=>o[i]=r[a])}else r.forEach(i=>o.push(i));else{if(t.length===0)throw new Error(\"Resize requires either scales or sizes.\");o=e.map((i,a)=>Math.round(i*t[a]))}return o},Ph=(e,t,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case\"not_larger\":return r.axes.length>0?Math.min(...r.axes.map(i=>t[i]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case\"not_smaller\":return r.axes.length>0?Math.max(...r.axes.map(i=>t[i]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let o=e.slice();return r.axes.length>0?(r.axes.forEach(i=>t[i]=n),r.axes.forEach(i=>o[i]=Math.round(e[i]*t[i]))):(t.fill(n,0,t.length),o.forEach((i,a)=>o[a]=Math.round(i*t[a]))),o},zh=(e,t,r,n,o)=>`\n fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> {\n var original_indices: array<${e.type.value}, ${r.length}>;\n for (var i:u32 = 0; i < ${r.length}; i++) {\n var output_index = ${e.indicesGet(\"output_indices\",\"i\")};\n var scale = ${F(\"uniforms.scales\",\"i\",n)};\n var roi_low = ${F(\"uniforms.roi\",\"i\",o)};\n var roi_hi = ${F(\"uniforms.roi\",`i + ${t.length}`,o)};\n if (scale == 1.0) {\n original_indices[i] = ${e.type.value}(output_index);\n } else {\n var input_shape_i = ${F(\"uniforms.input_shape\",\"i\",t.length)};\n var output_shape_i = ${F(\"uniforms.output_shape\",\"i\",r.length)};\n original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n }\n }\n return original_indices;\n }`,Oh=(e,t,r,n,o,i,a)=>`\n fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n for (var i:u32 = 0; i < ${n.length}; i++) {\n var output_index = ${t.indicesGet(\"output_indices\",\"i\")};\n var input_index: u32;\n var scale = ${F(\"uniforms.scales\",\"i\",o)};\n if (scale == 1.0) {\n input_index = output_index;\n } else {\n var roi_low = ${F(\"uniforms.roi\",\"i\",i)};\n var roi_hi = ${F(\"uniforms.roi\",`i + ${r.length}`,i)};\n var input_shape_i = ${F(\"uniforms.input_shape\",\"i\",r.length)};\n var output_shape_i = ${F(\"uniforms.output_shape\",\"i\",n.length)};\n var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n if (!${a} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {\n if (original_idx < 0) {\n input_index = 0;\n } else if (original_idx > ${t.type.value}(input_shape_i - 1)) {\n input_index = input_shape_i - 1;\n } else {\n input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));\n }\n } else {\n input_index = u32(original_idx);\n }\n }\n ${e.indicesSet(\"input_indices\",\"i\",\" input_index\")}\n }\n return input_indices;\n }`,Dh=(e,t)=>`\n fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {\n for (var i:u32 = 0; i < ${t.length}; i++) {\n var input_index = ${e.indicesGet(\"input_indices\",\"i\")};\n if (input_index < 0 || input_index >= ${F(\"uniforms.input_shape\",\"i\",t.length)}) {\n return false;\n }\n }\n return true;\n }`,$d=(e,t,r,n)=>e.rank>n?`\n ${e.indicesSet(\"input_indices\",t,\"channel\")};\n ${e.indicesSet(\"input_indices\",r,\"batch\")};\n`:\"\",Bh=(e,t,r,n,o)=>{let[a,l,d,c]=r.length===2?[-1,0,1,-1]:[0,2,3,1],m=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${m} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet(\"input_indices\",l,`max(0, min(row, ${r[l]} - 1))`)};\n ${e.indicesSet(\"input_indices\",d,`max(0, min(col, ${r[d]} - 1))`)};\n ${$d(e,c,a,2)}\n return ${e.getByIndices(\"input_indices\")};\n }\n\n fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${m} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var row:${m} = originalIndices[${l}];\n var col:${m} = originalIndices[${d}];\n ${n?`if (row < 0 || row > (${r[l]} - 1) || col < 0 || col > (${r[d]} - 1)) {\n return ${o};\n }`:\"\"};\n row = max(0, min(row, ${r[l]} - 1));\n col = max(0, min(col, ${r[d]} - 1));\n var row1: u32 = u32(row);\n var col1: u32 = u32(col);\n var row2: u32 = u32(row + 1);\n var col2: u32 = u32(col + 1);\n var channel: u32 = ${r.length>2?`u32(originalIndices[${c}])`:\"0\"};\n var batch: u32 = ${r.length>2?`u32(originalIndices[${a}])`:\"0\"};\n var x11: ${m} = getInputValue(batch, channel, row1, col1);\n var x12: ${m} = getInputValue(batch, channel, row1, col2);\n var x21: ${m} = getInputValue(batch, channel, row2, col1);\n var x22: ${m} = getInputValue(batch, channel, row2, col2);\n var dx1: ${m} = abs(row - ${m}(row1));\n var dx2: ${m} = abs(${m}(row2) - row);\n var dy1: ${m} = abs(col - ${m}(col1));\n var dy2: ${m} = abs(${m}(col2) - col);\n if (row1 == row2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (col1 == col2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);\n }`},Mh=(e,t,r,n,o,i,a,l,d,c)=>{let m=r.length===2,u=!0,[h,w]=m?[0,1]:u?[2,3]:[1,2],y=e.type.value,g=x=>{let $=x===h?\"row\":\"col\";return`\n fn ${$}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${y} {\n var output_index = ${t.indicesGet(\"output_indices\",x)};\n var originalIdx: ${y} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[x]},\n ${n[x]}, ${r[x]}, ${i[x]}, ${i[x]} + ${r.length});\n var fractOriginalIdx: ${y} = originalIdx - floor(originalIdx);\n var coefs = getCubicInterpolationCoefs(fractOriginalIdx);\n\n if (${l} && (originalIdx < 0 || originalIdx > (${r[x]} - 1))) {\n return ${d};\n }\n var data: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0);\n for (var i: i32 = -1; i < 3; i++) {\n var ${$}: ${y} = originalIdx + ${y}(i);\n if (${$} < 0 || ${$} >= ${r[x]}) {\n ${(()=>c?`coefs[i + 1] = 0.0;\n continue;`:l?`return ${d};`:`${$} = max(0, min(${$}, ${r[x]} - 1));`)()};\n }\n var input_indices_copy: ${e.type.indices} = input_indices;\n ${e.indicesSet(\"input_indices_copy\",x,`u32(${$})`)};\n data[i + 1] = ${x===h?e.getByIndices(\"input_indices_copy\"):\"rowCubicInterpolation(input_indices_copy, output_indices)\"};\n }\n return cubicInterpolation1D(data, coefs);\n }`};return`\n ${g(h)};\n ${g(w)};\n fn getCubicInterpolationCoefs(s: ${y}) -> array<${y}, 4> {\n var absS = abs(s);\n var coeffs: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0);\n var oneMinusAbsS: ${y} = 1.0 - absS;\n var twoMinusAbsS: ${y} = 2.0 - absS;\n var onePlusAbsS: ${y} = 1.0 + absS;\n coeffs[0] = ((${a} * onePlusAbsS - 5 * ${a}) * onePlusAbsS + 8 * ${a}) * onePlusAbsS - 4 * ${a};\n coeffs[1] = ((${a} + 2) * absS - (${a} + 3)) * absS * absS + 1;\n coeffs[2] = ((${a} + 2) * oneMinusAbsS - (${a} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;\n coeffs[3] = ((${a} * twoMinusAbsS - 5 * ${a}) * twoMinusAbsS + 8 * ${a}) * twoMinusAbsS - 4 * ${a};\n return coeffs;\n }\n\n fn cubicInterpolation1D(x: array<${y}, 4>, coefs: array<${y}, 4>) -> ${y} {\n var coefsSum: ${y} = coefs[0] + coefs[1] + coefs[2] + coefs[3];\n return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;\n }\n\n fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${y} {\n var input_indices: ${e.type.indices} = output_indices;\n return colCubicInterpolation(input_indices, output_indices);\n }\n `},Rh=(e,t,r,n,o)=>{let[a,l,d,c,m]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],u=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${u} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet(\"input_indices\",l,`max(0, min(depth, ${r[l]} - 1))`)};\n ${e.indicesSet(\"input_indices\",d,`max(0, min(height, ${r[d]} - 1))`)};\n ${e.indicesSet(\"input_indices\",c,`max(0, min(width, ${r[c]} - 1))`)};\n ${$d(e,m,a,3)}\n return ${e.getByIndices(\"input_indices\")};\n }\n\n fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${u} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var depth:${u} = originalIndices[${l}];\n var height:${u} = originalIndices[${d}];\n var width:${u} = originalIndices[${c}];\n ${n?`if (depth < 0 || depth > (${r[l]} - 1) || height < 0 || height > (${r[d]} - 1) || width < 0 || (width > ${r[c]} - 1)) {\n return ${o};\n }`:\"\"};\n\n depth = max(0, min(depth, ${r[l]} - 1));\n height = max(0, min(height, ${r[d]} - 1));\n width = max(0, min(width, ${r[c]} - 1));\n var depth1: u32 = u32(depth);\n var height1: u32 = u32(height);\n var width1: u32 = u32(width);\n var depth2: u32 = u32(depth + 1);\n var height2: u32 = u32(height + 1);\n var width2: u32 = u32(width + 1);\n var channel: u32 = ${r.length>3?`u32(originalIndices[${m}])`:\"0\"};\n var batch: u32 = ${r.length>3?`u32(originalIndices[${a}])`:\"0\"};\n\n var x111: ${u} = getInputValue(batch, channel, depth1, height1, width1);\n var x112: ${u} = getInputValue(batch, channel, depth1, height1, width2);\n var x121: ${u} = getInputValue(batch, channel, depth1, height2, width1);\n var x122: ${u} = getInputValue(batch, channel, depth1, height2, width2);\n var x211: ${u} = getInputValue(batch, channel, depth2, height1, width1);\n var x212: ${u} = getInputValue(batch, channel, depth2, height1, width2);\n var x221: ${u} = getInputValue(batch, channel, depth2, height2, width1);\n var x222: ${u} = getInputValue(batch, channel, depth2, height2, width2);\n var dx1: ${u} = abs(depth - ${u}(depth1));\n var dx2: ${u} = abs(${u}(depth2) - depth);\n var dy1: ${u} = abs(height - ${u}(height1));\n var dy2: ${u} = abs(${u}(height2) - height);\n var dz1: ${u} = abs(width - ${u}(width1));\n var dz2: ${u} = abs(${u}(width2) - width);\n if (depth1 == depth2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (height1 == height2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n if (width1 == width2) {\n dz1 = 0.5;\n dz2 = 0.5;\n }\n return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +\n x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);\n }`},Uh=(e,t,r,n,o,i)=>{let a=e.dims,l=kh(i,t.axes,a.length),d=Eh(a,n,o,t.axes),c=n.slice();n.length===0&&(c=a.map((v,S)=>v===0?1:d[S]/v),t.keepAspectRatioPolicy!==\"stretch\"&&(d=Ph(a,c,t)));let m=M(\"output\",e.dataType,d.length),u=E(\"input\",e.dataType,a.length),h=k.size(d),w=a.length===d.length&&a.every((v,S)=>v===d[S]),y=t.coordinateTransformMode===\"tf_crop_and_resize\",g=t.extrapolationValue,x=u.type.value,$=v=>`\n ${w?\"\":`\n ${Ch(t.coordinateTransformMode,x)};\n ${(()=>{switch(t.mode){case\"nearest\":return`\n ${Dh(u,a)};\n ${Ah(t.nearestMode,r,x)};\n ${Oh(u,m,a,d,c.length,l.length,y)};\n `;case\"linear\":return`\n ${zh(m,a,d,c.length,l.length)};\n ${(()=>{if(a.length===2||a.length===4)return`${Bh(u,m,a,y,g)}`;if(a.length===3||a.length===5)return`${Rh(u,m,a,y,g)}`;throw Error(\"Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.\")})()};\n `;case\"cubic\":return`\n ${(()=>{if(a.length===2||a.length===4)return`${Mh(u,m,a,d,c,l,t.cubicCoeffA,y,t.extrapolationValue,t.excludeOutside)}`;throw Error(\"Cubic mode only supports input dims 2 and 4 are supported in linear mode.\")})()};\n `;default:throw Error(\"Invalid resize mode\")}})()};\n `}\n ${v.registerUniform(\"output_size\",\"u32\").registerUniform(\"scales\",\"f32\",c.length).registerUniform(\"roi\",\"f32\",l.length).declareVariables(u,m)}\n ${v.mainStart()}\n ${v.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n ${w?\"output[global_idx] = input[global_idx];\":`\n let output_indices = ${m.offsetToIndices(\"global_idx\")};\n var input_indices: ${u.type.indices};\n ${(()=>{switch(t.mode){case\"nearest\":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);\n if (checkInputIndices(input_indices)) {\n output[global_idx] = ${u.getByIndices(\"input_indices\")};\n } else {\n output[global_idx] = ${t.extrapolationValue};\n }`;case\"linear\":return`output[global_idx] = ${a.length===2||a.length===4?\"bilinearInterpolation\":\"trilinearInterpolation\"}(output_indices);`;case\"cubic\":return\"output[global_idx] = bicubicInterpolation(output_indices);\";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};\n`}\n }`;return{name:\"Resize\",shaderCache:{hint:`${t.cacheKey}|${r}|${c.length>0?c:\"\"}|${o.length>0?o:\"\"}|${l.length>0?l:\"\"}|${w}|${a}`,inputDependencies:[\"rank\"]},getShaderSource:$,getRunData:()=>({outputs:[{dims:d,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:[{type:12,data:h},{type:1,data:c},{type:1,data:l},...V(a,d)]})}},Vh=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},xd=(e,t)=>{let r=[],n=[],o=[],i=Vh(e);if(t.antialias!==0)throw Error(\"Only default value (0) for Antialias attribute is supported\");Ih(e.inputs,t,i,r,n,o),e.compute(Uh(e.inputs[0],t,i,r,n,o),{inputs:[0]})},Sd=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,o=e.cubicCoeffA,i=e.excludeOutside!==0,a=e.extrapolationValue,l=e.keepAspectRatioPolicy,d=e.mode,c=e.nearestMode===\"\"?\"simple\":e.nearestMode;return re({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:o,excludeOutside:i,extrapolationValue:a,keepAspectRatioPolicy:l,mode:d,nearestMode:c})}});var Nh,Wh,Id,Cd=R(()=>{\"use strict\";te();oe();Ie();ae();Nh=(e,t)=>{let[r,n,o,i]=e,{numHeads:a,rotaryEmbeddingDim:l}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!k.areEqual(n.dims,[])&&!k.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(!k.areEqual(o.dims,i.dims))throw new Error(\"Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape\");if(l>0&&a===0)throw new Error(\"num_heads must be provided if rotary_embedding_dim is specified\");let d=r.dims[0],c=r.dims[r.dims.length-2],m=o.dims[0],u=k.sizeFromDimension(r.dims,1)/c,h=l===0?o.dims[1]*2:u/a;if(l>h)throw new Error(\"rotary_embedding_dim must be less than or equal to head_size\");if(n.dims.length===2){if(d!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(c!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(h/2!==o.dims[1]&&l/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(c>m)throw new Error(\"Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported\")},Wh=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:o,scale:i}=t,a=e[0].dims[0],l=k.sizeFromDimension(e[0].dims,1),d=e[0].dims[e[0].dims.length-2],c=l/d,m=e[2].dims[1],u=o===0?m*2:c/n,h=new Array(a,d,c/u,u-m),w=k.computeStrides(h),y=[{type:1,data:i},{type:12,data:h},{type:12,data:w},...e[0].dims.length===3?new Array({type:12,data:[l,c,u,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[l,u,d*u,1]}):[],...V(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],g=x=>{let $=E(\"input\",e[0].dataType,e[0].dims.length),v=E(\"position_ids\",e[1].dataType,e[1].dims.length),S=E(\"cos_cache\",e[2].dataType,e[2].dims.length),T=E(\"sin_cache\",e[3].dataType,e[3].dims.length),C=M(\"output\",e[0].dataType,e[0].dims.length);return x.registerUniforms([{name:\"scale\",type:\"f32\"},{name:\"global_shape\",type:\"u32\",length:h.length},{name:\"global_strides\",type:\"u32\",length:w.length},{name:\"input_output_strides\",type:\"u32\",length:w.length}]),`\n ${x.declareVariables($,v,S,T,C)}\n\n ${x.mainStart(Ct)}\n let half_rotary_emb_dim = uniforms.${S.name}_shape[1];\n let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;\n let size = uniforms.global_shape[0] * uniforms.global_strides[0];\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(\"size\")}\n\n if (bsnh[3] < half_rotary_emb_dim) {\n let position_ids_idx =\n ${v.broadcastedIndicesToOffset(\"bsnh.xy\",M(\"\",v.type.tensor,2))};\n let position_id =\n u32(${v.getByOffset(\"position_ids_idx\")}) + select(0, bsnh[1], position_ids_idx == 0);\n let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r});\n let j = i + select(half_rotary_emb_dim, 1, ${r});\n let re = ${$.getByOffset(\"i\")} * ${S.get(\"position_id\",\"bsnh[3]\")} -\n ${$.getByOffset(\"j\")} * ${T.get(\"position_id\",\"bsnh[3]\")};\n ${C.setByOffset(\"i\",\"re\")}\n let im = ${$.getByOffset(\"i\")} * ${T.get(\"position_id\",\"bsnh[3]\")} +\n ${$.getByOffset(\"j\")} * ${S.get(\"position_id\",\"bsnh[3]\")};\n ${C.setByOffset(\"j\",\"im\")}\n } else {\n let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;\n ${C.setByOffset(\"k\",$.getByOffset(\"k\"))}\n }\n }`};return{name:\"RotaryEmbedding\",shaderCache:{hint:re({interleaved:r}).cacheKey,inputDependencies:[\"rank\",\"rank\",\"rank\",\"rank\"]},getShaderSource:g,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k.size(h)/Ct)},programUniforms:y})}},Id=(e,t)=>{Nh(e.inputs,t),e.compute(Wh(e.inputs,t))}});var Lh,Gh,Ad,kd=R(()=>{\"use strict\";te();oe();ae();Lh=e=>{if(!e||e.length<3)throw new Error(\"layerNorm requires at least 3 inputs.\");let t=e[0],r=e[1],n=e[2];if(t.dataType!==r.dataType||t.dataType!==n.dataType)throw new Error(\"All inputs must have the same data type\");if(t.dims.length!==3&&t.dims.length!==2)throw new Error(\"Input must be 2D or 3D\");if(r.dims.length!==3&&r.dims.length!==2)throw new Error(\"Skip must be 2D or 3D\");let o=t.dims[t.dims.length-1],i=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==o)throw new Error(\"Skip must have the same hidden size as input\");if(r.dims[r.dims.length-2]!==i)throw new Error(\"Skip must have the same sequence length as input\");if(n.dims.length!==1)throw new Error(\"Gamma must be 1D\");if(n.dims[n.dims.length-1]!==o)throw new Error(\"Gamma must have the same hidden size as input\");if(e.length>3){let a=e[3];if(a.dims.length!==1)throw new Error(\"Beta must be 1D\");if(a.dims[a.dims.length-1]!==o)throw new Error(\"Beta must have the same hidden size as input\")}if(e.length>4){let a=e[4];if(a.dims.length!==1)throw new Error(\"Bias must be 1D\");if(a.dims[a.dims.length-1]!==o)throw new Error(\"Bias must have the same hidden size as input\")}},Gh=(e,t,r,n)=>{let o=t.simplified,i=e[0].dims,a=k.size(i),l=i,d=a,c=i.slice(-1)[0],m=n?i.slice(0,-1).concat(1):[],u=!o&&e.length>3,h=e.length>4,w=n&&r>1,y=n&&r>2,g=r>3,x=64,$=ye(c),v=[{type:12,data:d},{type:12,data:$},{type:12,data:c},{type:1,data:t.epsilon}],S=C=>{let A=[{name:\"output_size\",type:\"u32\"},{name:\"components\",type:\"u32\"},{name:\"hidden_size\",type:\"u32\"},{name:\"epsilon\",type:\"f32\"}],P=[E(\"x\",e[0].dataType,e[0].dims,$),E(\"skip\",e[1].dataType,e[1].dims,$),E(\"gamma\",e[2].dataType,e[2].dims,$)];u&&P.push(E(\"beta\",e[3].dataType,e[3].dims,$)),h&&P.push(E(\"bias\",e[4].dataType,e[4].dims,$)),P.push(M(\"output\",e[0].dataType,l,$)),w&&P.push(M(\"mean_output\",1,m)),y&&P.push(M(\"inv_std_output\",1,m)),g&&P.push(M(\"input_skip_bias_sum\",e[0].dataType,l,$));let O=me(e[0].dataType),U=me(1,$);return`\n\n ${C.registerUniforms(A).declareVariables(...P)}\n var sum_shared : array<${U}, ${x}>;\n var sum_squared_shared : array<${U}, ${x}>;\n\n ${C.mainStart([x,1,1])}\n let ix = local_id.x;\n let iy = global_id.x / ${x};\n\n let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;\n var stride = hidden_size_vectorized / ${x};\n let offset = ix * stride + iy * hidden_size_vectorized;\n let offset1d = stride * ix;\n if (ix == ${x-1}) {\n stride = hidden_size_vectorized - stride * ix;\n }\n for (var i: u32 = 0; i < stride; i++) {\n let skip_value = skip[offset + i];\n let bias_value = ${h?\"bias[offset1d + i]\":O+\"(0.0)\"};\n let input_value = x[offset + i];\n let value = input_value + skip_value + bias_value;\n ${g?\"input_skip_bias_sum[offset + i] = value;\":\"\"}\n output[offset + i] = value;\n let f32_value = ${At(O,$,\"value\")};\n sum_shared[ix] += f32_value;\n sum_squared_shared[ix] += f32_value * f32_value;\n }\n workgroupBarrier();\n\n var reduce_size : u32 = ${x};\n for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) {\n reduce_size = curr_size + (reduce_size & 1);\n if (ix < curr_size) {\n sum_shared[ix] += sum_shared[ix + reduce_size];\n sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size];\n }\n workgroupBarrier();\n }\n\n let sum = sum_shared[0];\n let square_sum = sum_squared_shared[0];\n let mean = ${Ke(\"sum\",$)} / f32(uniforms.hidden_size);\n let inv_std_dev = inverseSqrt(${Ke(\"square_sum\",$)} / f32(uniforms.hidden_size) ${o?\"\":\"- mean * mean\"} + uniforms.epsilon);\n ${w?\"mean_output[global_idx] = mean;\":\"\"}\n ${y?\"inv_std_output[global_idx] = inv_std_dev;\":\"\"}\n\n for (var i: u32 = 0; i < stride; i++) {\n output[offset + i] = (output[offset + i] ${o?\"\":`- ${O}(mean)`}) *\n ${O}(inv_std_dev) * gamma[offset1d + i]\n ${u?\"+ beta[offset1d + i]\":\"\"};\n }\n }`},T=[{dims:l,dataType:e[0].dataType}];return r>1&&T.push({dims:m,dataType:1}),r>2&&T.push({dims:m,dataType:1}),r>3&&T.push({dims:i,dataType:e[0].dataType}),{name:\"SkipLayerNormalization\",shaderCache:{hint:`${$};${w};${y};${g}`,inputDependencies:e.map((C,A)=>\"type\")},getShaderSource:S,getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(d/c)},programUniforms:v})}},Ad=(e,t)=>{Lh(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(Gh(e.inputs,t,e.outputCount,!1),{outputs:n})}});var Hh,ln,Fh,Ed,qh,jh,Pd,zd,Od=R(()=>{\"use strict\";te();oe();Ie();ae();Hh=(e,t)=>{if(!e||e.length<1)throw new Error(\"too few inputs\");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error(\"axes, starts and ends must have the same length\")}else if(t.starts.length!==t.ends.length)throw new Error(\"starts and ends must have the same length\");e.slice(1).forEach((r,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},ln=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>r.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>r.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},Fh=(e,t)=>{if(e.length>1){let r=ln(e,1),n=ln(e,2),o=ln(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),re({starts:r,ends:n,axes:o})}else return t},Ed=(e,t,r,n,o)=>{let i=e;return e<0&&(i+=r[n[t]]),o[t]<0?Math.max(0,Math.min(i,r[n[t]]-1)):Math.max(0,Math.min(i,r[n[t]]))},qh=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n var carry = 0u;\n for (var i = ${r.length}; i >= 0; i--) {\n let input_shape_i = ${F(\"uniforms.input_shape\",\"i\",r.length)};\n let steps_i = ${F(\"uniforms.steps\",\"i\",r.length)};\n let signs_i = ${F(\"uniforms.signs\",\"i\",r.length)};\n let starts_i = ${F(\"uniforms.starts\",\"i\",r.length)};\n var output_index = ${t.indicesGet(\"output_indices\",\"i\")};\n var input_index = output_index * steps_i + starts_i + carry;\n carry = input_index / input_shape_i;\n input_index = input_index % input_shape_i;\n if (signs_i < 0) {\n input_index = input_shape_i - input_index - 1u + starts_i;\n }\n ${e.indicesSet(\"input_indices\",\"i\",\"input_index\")};\n }\n return input_indices;\n }`,jh=(e,t)=>{let r=e[0].dims,n=k.size(r),o=t.axes.length>0?k.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],i=ln(e,4);i.forEach($=>$!==0||(()=>{throw new Error(\"step cannot be 0\")})),i.length===0&&(i=Array(o.length).fill(1));let a=t.starts.map(($,v)=>Ed($,v,r,o,i)),l=t.ends.map(($,v)=>Ed($,v,r,o,i));if(o.length!==a.length||o.length!==l.length)throw new Error(\"start, ends and axes should have the same number of elements\");if(o.length!==r.length)for(let $=0;$Math.sign($));i.forEach(($,v,S)=>{if($<0){let T=(l[v]-a[v])/$,C=a[v],A=C+T*i[v];a[v]=A,l[v]=C,S[v]=-$}});let c=r.slice(0);o.forEach(($,v)=>{c[$]=Math.ceil((l[$]-a[$])/i[$])});let m={dims:c,dataType:e[0].dataType},u=M(\"output\",e[0].dataType,c.length),h=E(\"input\",e[0].dataType,e[0].dims.length),w=k.size(c),y=[{name:\"outputSize\",type:\"u32\"},{name:\"starts\",type:\"u32\",length:a.length},{name:\"signs\",type:\"i32\",length:d.length},{name:\"steps\",type:\"u32\",length:i.length}],g=[{type:12,data:w},{type:12,data:a},{type:6,data:d},{type:12,data:i},...V(e[0].dims,c)],x=$=>`\n ${$.registerUniforms(y).declareVariables(h,u)}\n ${qh(h,u,r)}\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n let output_indices = ${u.offsetToIndices(\"global_idx\")};\n let input_indices = calculateInputIndices(output_indices);\n ${u.setByOffset(\"global_idx\",h.getByIndices(\"input_indices\"))}\n }`;return{name:\"Slice\",shaderCache:{hint:`${d.length}_${a.length}_${i.length}`,inputDependencies:[\"rank\"]},getShaderSource:x,getRunData:()=>({outputs:[m],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:g})}},Pd=(e,t)=>{Hh(e.inputs,t);let r=Fh(e.inputs,t);e.compute(jh(e.inputs,r),{inputs:[0]})},zd=e=>{let t=e.starts,r=e.ends,n=e.axes;return re({starts:t,ends:r,axes:n})}});var Kh,Yh,Dd,Bd,Md=R(()=>{\"use strict\";te();oe();Ie();ut();ae();Kh=e=>{if(!e||e.length!==1)throw new Error(\"Softmax op requires 1 input.\")},Yh=(e,t)=>{let r=e.inputs[0],n=r.dims,o=k.size(n),i=n.length,a=k.normalizeAxis(t.axis,i),l=aO),c[a]=i-1,c[i-1]=a,d=e.compute(Pe(r,c),{inputs:[r],outputs:[-1]})[0]):d=r;let m=d.dims,u=m[i-1],h=o/u,w=ye(u),y=u/w,g=64;h===1&&(g=256);let x=(P,O)=>O===4?`max(max(${P}.x, ${P}.y), max(${P}.z, ${P}.w))`:O===2?`max(${P}.x, ${P}.y)`:O===3?`max(max(${P}.x, ${P}.y), ${P}.z)`:P,$=E(\"x\",d.dataType,d.dims,w),v=M(\"result\",d.dataType,d.dims,w),S=$.type.value,T=me(d.dataType)===\"f32\"?`var threadMax = ${S}(-3.402823e+38f);`:`var threadMax = ${S}(-65504.0h);`,C=P=>`\n var rowMaxShared : ${S};\n var rowSumShared : ${S};\n var threadShared : array<${S}, ${g}>;\n\n fn getValue(row: i32, col: i32, row_stride: i32) -> ${S} {\n let index = row * row_stride + col;\n return x[index];\n }\n\n fn setValue(row: i32, col: i32, row_stride: i32, value: ${S}) {\n let index = row * row_stride + col;\n result[index] = value;\n }\n ${P.registerUniform(\"packedCols\",\"i32\").declareVariables($,v)}\n ${P.mainStart(g)}\n let gindex = i32(global_idx);\n let lindex = i32(local_idx);\n const wg = ${g};\n let row = gindex / wg;\n let cols = uniforms.packedCols;\n let row_stride : i32 = uniforms.packedCols;\n\n // find the rows max\n ${T}\n for (var col = lindex; col < cols; col += wg) {\n let value = getValue(row, col, row_stride);\n threadMax = max(threadMax, value);\n }\n if (lindex < cols) {\n threadShared[lindex] = threadMax;\n }\n workgroupBarrier();\n\n var reduceSize = min(cols, wg);\n for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {\n reduceSize = currSize + (reduceSize & 1);\n if (lindex < currSize) {\n threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowMaxShared = ${S}(${x(\"threadShared[0]\",w)});\n }\n workgroupBarrier();\n\n // find the rows sum\n var threadSum = ${S}(0.0);\n for (var col = lindex; col < cols; col += wg) {\n let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);\n threadSum += subExp;\n }\n threadShared[lindex] = threadSum;\n workgroupBarrier();\n\n for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {\n if (lindex < currSize) {\n threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowSumShared = ${S}(${Ke(\"threadShared[0]\",w)});\n }\n workgroupBarrier();\n\n // calculate final value for each element in the row\n for (var col = lindex; col < cols; col += wg) {\n let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;\n setValue(row, col, row_stride, value);\n }\n }`,A=e.compute({name:\"Softmax\",shaderCache:{hint:`${w};${g}`,inputDependencies:[\"type\"]},getRunData:()=>({outputs:[{dims:m,dataType:d.dataType}],dispatchGroup:{x:h},programUniforms:[{type:6,data:y}]}),getShaderSource:C},{inputs:[d],outputs:[l?-1:0]})[0];l&&e.compute(Pe(A,c),{inputs:[A]})},Dd=(e,t)=>{Kh(e.inputs),Yh(e,t)},Bd=e=>re({axis:e.axis})});var Rd,Zh,Xh,Qh,Ud,Vd=R(()=>{\"use strict\";te();oe();ae();Rd=e=>Array.from(e.getBigInt64Array(),Number),Zh=e=>{if(!e||e.length!==2)throw new Error(\"Tile requires 2 inputs.\");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error(\"Tile only support float, float16, int32, and uint32 data types\");if(e[1].dataType!==7)throw new Error(\"Tile `repeats` input should be of int64 data type\");if(e[1].dims.length!==1)throw new Error(\"Tile `repeats` input should be 1-D\");if(Rd(e[1]).length!==e[0].dims.length)throw new Error(\"Tile `repeats` input should have same number of elements as rank of input data tensor\")},Xh=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??Rd(e[1]),o=Xh(r,n),i=k.size(o),a=e[0].dataType,l=E(\"input\",a,r.length),d=M(\"output\",a,o.length),c=m=>`\n const inputShape = ${l.indices(...r)};\n ${m.registerUniform(\"output_size\",\"u32\").declareVariables(l,d)}\n ${m.mainStart()}\n ${m.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let output_indices = ${d.offsetToIndices(\"global_idx\")};\n var input_indices: ${l.type.indices};\n for (var i = 0; i < ${r.length}; i++) {\n let input_dim_i = ${l.indicesGet(\"uniforms.input_shape\",\"i\")};\n let input_dim_value = ${d.indicesGet(\"output_indices\",\"i\")} % input_dim_i;\n\n ${l.indicesSet(\"input_indices\",\"i\",\"input_dim_value\")}\n }\n ${d.setByOffset(\"global_idx\",l.getByIndices(\"input_indices\"))}\n }`;return{name:\"Tile\",shaderCache:{hint:`${n}`,inputDependencies:[\"rank\"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...V(e[0].dims,o)]}),getShaderSource:c}},Ud=e=>{Zh(e.inputs),e.compute(Qh(e.inputs),{inputs:[0]})}});var Jh,eg,Nd,Wd=R(()=>{\"use strict\";te();oe();ae();Jh=(e,t,r,n,o)=>{let i=M(\"output_data\",o,r.length,4),a=E(\"a_data\",t[1].dataType,t[1].dims.length,4),l=E(\"b_data\",t[2].dataType,t[2].dims.length,4),d=E(\"c_data\",t[0].dataType,t[0].dims.length,4),c,m=(u,h,w)=>`select(${h}, ${u}, ${w})`;if(!n)c=i.setByOffset(\"global_idx\",m(a.getByOffset(\"global_idx\"),l.getByOffset(\"global_idx\"),d.getByOffset(\"global_idx\")));else{let u=(h,w,y=\"\")=>{let g=`a_data[index_a${w}][component_a${w}]`,x=`b_data[index_b${w}][component_b${w}]`,$=`bool(c_data[index_c${w}] & (0xffu << (component_c${w} * 8)))`;return`\n let output_indices${w} = ${i.offsetToIndices(`global_idx * 4u + ${w}u`)};\n let offset_a${w} = ${a.broadcastedIndicesToOffset(`output_indices${w}`,i)};\n let offset_b${w} = ${l.broadcastedIndicesToOffset(`output_indices${w}`,i)};\n let offset_c${w} = ${d.broadcastedIndicesToOffset(`output_indices${w}`,i)};\n let index_a${w} = offset_a${w} / 4u;\n let index_b${w} = offset_b${w} / 4u;\n let index_c${w} = offset_c${w} / 4u;\n let component_a${w} = offset_a${w} % 4u;\n let component_b${w} = offset_b${w} % 4u;\n let component_c${w} = offset_c${w} % 4u;\n ${h}[${w}] = ${y}(${m(g,x,$)});\n `};o===9?c=`\n var data = vec4(0);\n ${u(\"data\",0,\"u32\")}\n ${u(\"data\",1,\"u32\")}\n ${u(\"data\",2,\"u32\")}\n ${u(\"data\",3,\"u32\")}\n output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:c=`\n ${u(\"output_data[global_idx]\",0)}\n ${u(\"output_data[global_idx]\",1)}\n ${u(\"output_data[global_idx]\",2)}\n ${u(\"output_data[global_idx]\",3)}\n `}return`\n ${e.registerUniform(\"vec_size\",\"u32\").declareVariables(d,a,l,i)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.vec_size\")}\n ${c}\n }`},eg=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,o=e[1].dataType,i=!(k.areEqual(t,r)&&k.areEqual(r,n)),a=t,l=k.size(t);if(i){let c=et.calcShape(et.calcShape(t,r,!1),n,!1);if(!c)throw new Error(\"Can't perform where op on the given tensors\");a=c,l=k.size(a)}let d=Math.ceil(l/4);return{name:\"Where\",shaderCache:{inputDependencies:[\"rank\",\"rank\",\"rank\"]},getShaderSource:c=>Jh(c,e,a,i,o),getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:Math.ceil(l/64/4)},programUniforms:[{type:12,data:d},...V(n,t,r,a)]})}},Nd=e=>{e.compute(eg(e.inputs))}});var Ld,Gd=R(()=>{\"use strict\";zs();Xr();Bs();Rs();$u();Ou();Mu();Yu();rl();il();ul();ml();gl();yl();vl();Sl();Cl();El();Ol();Wl();Hl();ql();Kl();Xl();ko();Jl();gd();wd();vd();Yr();Td();Cd();kd();Od();Md();Po();Vd();ut();Jr();Wd();Ld=new Map([[\"Abs\",[Us]],[\"Acos\",[Vs]],[\"Acosh\",[Ns]],[\"Add\",[xu]],[\"ArgMax\",[Ps,go]],[\"ArgMin\",[Es,go]],[\"Asin\",[Ws]],[\"Asinh\",[Ls]],[\"Atan\",[Gs]],[\"Atanh\",[Hs]],[\"Attention\",[Os]],[\"AveragePool\",[sd,ad]],[\"BatchNormalization\",[Ds]],[\"BiasAdd\",[Ms]],[\"BiasSplitGelu\",[vu]],[\"Cast\",[qs,Fs]],[\"Ceil\",[Ks]],[\"Clip\",[js]],[\"Concat\",[Du,Bu]],[\"Conv\",[So,xo]],[\"ConvTranspose\",[tl,el]],[\"Cos\",[Ys]],[\"Cosh\",[Zs]],[\"CumSum\",[nl,ol]],[\"DepthToSpace\",[al,sl]],[\"DequantizeLinear\",[bd,yd]],[\"Div\",[Su]],[\"Einsum\",[cl,pl]],[\"Elu\",[Xs,Jt]],[\"Equal\",[Tu]],[\"Erf\",[Qs]],[\"Exp\",[Js]],[\"Expand\",[hl]],[\"FastGelu\",[bl]],[\"Floor\",[eu]],[\"FusedConv\",[So,xo]],[\"Gather\",[_l,wl]],[\"GatherElements\",[Il,Tl]],[\"GatherBlockQuantized\",[$l,xl]],[\"Gelu\",[tu]],[\"Gemm\",[kl,Al]],[\"GlobalAveragePool\",[dd,ld]],[\"GlobalMaxPool\",[hd,fd]],[\"Greater\",[ku]],[\"GreaterOrEqual\",[Pu]],[\"GridSample\",[Pl,zl]],[\"GroupQueryAttention\",[Nl]],[\"HardSigmoid\",[lu,uu]],[\"InstanceNormalization\",[Gl]],[\"LayerNormalization\",[Fl]],[\"LeakyRelu\",[ru,Jt]],[\"Less\",[Eu]],[\"LessOrEqual\",[zu]],[\"Log\",[yu]],[\"MatMul\",[jl]],[\"MatMulNBits\",[Yl,Zl]],[\"MaxPool\",[pd,md]],[\"Mul\",[Iu]],[\"MultiHeadAttention\",[Ml,Bl]],[\"Neg\",[ou]],[\"Not\",[nu]],[\"Pad\",[Ql]],[\"Pow\",[Cu]],[\"QuickGelu\",[wu,Jt]],[\"Range\",[_d]],[\"Reciprocal\",[iu]],[\"ReduceMin\",[Ss]],[\"ReduceMean\",[ws]],[\"ReduceMax\",[xs]],[\"ReduceSum\",[Is]],[\"ReduceProd\",[Ts]],[\"ReduceL1\",[_s]],[\"ReduceL2\",[vs]],[\"ReduceLogSum\",[As]],[\"ReduceLogSumExp\",[$s]],[\"ReduceSumSquare\",[Cs]],[\"Relu\",[au]],[\"Resize\",[xd,Sd]],[\"RotaryEmbedding\",[Id]],[\"Sigmoid\",[su]],[\"Sin\",[du]],[\"Sinh\",[cu]],[\"Slice\",[Pd,zd]],[\"SkipLayerNormalization\",[Ad]],[\"Split\",[Rl,Ul]],[\"Sqrt\",[pu]],[\"Softmax\",[Dd,Bd]],[\"Sub\",[Au]],[\"Tan\",[mu]],[\"Tanh\",[hu]],[\"ThresholdedRelu\",[bu,Jt]],[\"Tile\",[Ud]],[\"Transpose\",[as,ss]],[\"Where\",[Nd]]])});var dn,Hd=R(()=>{\"use strict\";He();je();ae();dn=class{constructor(t){this.backend=t;this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,r){this.repo.set(t,r)}run(t,r,n,o,i){Ue(t.programInfo.name);let a=this.backend.device,l=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let d=[];for(let m of r)d.push({binding:d.length,resource:{buffer:m.buffer}});for(let m of n)d.push({binding:d.length,resource:{buffer:m.buffer}});i&&d.push({binding:d.length,resource:i});let c=a.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:d,label:t.programInfo.name});if(this.backend.sessionStatus===\"capturing\"){let m={kernelId:this.backend.currentKernelId,computePipeline:t.computePipeline,bindGroup:c,dispatchGroup:o};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(m)}l.setPipeline(t.computePipeline),l.setBindGroup(0,c),l.dispatchWorkgroups(...o),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType===\"at-passes\")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Be(t.programInfo.name)}dispose(){}build(t,r){Ue(t.name);let n=this.backend.device,o=[];[{feature:\"shader-f16\",extension:\"f16\"},{feature:\"subgroups\",extension:\"subgroups\"},{feature:\"subgroups-f16\",extension:\"subgroups_f16\"}].forEach(u=>{n.features.has(u.feature)&&o.push(`enable ${u.extension};`)});let a=os(r,this.backend.device.limits),l=t.getShaderSource(a),d=`${o.join(`\n`)}\n${a.additionalImplementations}\n${l}`,c=n.createShaderModule({code:d,label:t.name});se(\"verbose\",()=>`[WebGPU] ${t.name} shader code: ${d}`);let m=n.createComputePipeline({compute:{module:c,entryPoint:\"main\"},layout:\"auto\",label:t.name});return Be(t.name),{programInfo:t,computePipeline:m,uniformVariablesInfo:a.variablesInfo}}normalizeDispatchGroupSize(t){let r=typeof t==\"number\"?t:t.x,n=typeof t==\"number\"?1:t.y||1,o=typeof t==\"number\"?1:t.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=i&&n<=i&&o<=i)return[r,n,o];let a=r*n*o,l=Math.ceil(Math.sqrt(a));if(l>i){if(l=Math.ceil(Math.cbrt(a)),l>i)throw new Error(\"Total dispatch size exceeds WebGPU maximum.\");return[l,l,l]}else return[l,l,1]}}});var tg,rg,zo,Oo,cn,Fd=R(()=>{\"use strict\";He();te();je();no();ts();Gd();Hd();tg=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let n=0;n{let n=e.name;return e.shaderCache?.hint&&(n+=\"[\"+e.shaderCache.hint+\"]\"),n+=\":\"+r+`:${tg(t,e.shaderCache?.inputDependencies??new Array(t.length).fill(\"dims\"))}`,n},zo=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},Oo=class{constructor(t){this.subgroupsSupported=t.features.has(\"subgroups\"),this.subgroupsF16Supported=t.features.has(\"subgroups\");let r=t.limits;!this.subgroupsSupported||!r.minSubgroupSize||!r.maxSubgroupSize?this.subgroupSizeRange=void 0:this.subgroupSizeRange=[r.minSubgroupSize,r.maxSubgroupSize]}},cn=class{constructor(){this.currentSessionId=null;this.currentKernelId=null;this.commandEncoder=null;this.computePassEncoder=null;this.maxDispatchNumber=16;this.pendingDispatchNumber=0;this.pendingKernels=[];this.pendingQueries=new Map;this.sessionStatus=\"default\";this.capturedCommandList=new Map;this.capturedPendingKernels=new Map;this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error(\"currentKernelCustomData(): currentKernelId is null. (should not happen)\");let t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,r){this.env=t;let n=[],o={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},i=a=>r.features.has(a)&&n.push(a)&&!0;i(\"chromium-experimental-timestamp-query-inside-passes\")||i(\"timestamp-query\"),i(\"shader-f16\"),i(\"subgroups\")&&i(\"subgroups-f16\"),this.device=await r.requestDevice(o),this.deviceInfo=new Oo(this.device),this.adapterInfo=new zo(r.info||await r.requestAdapterInfo()),this.gpuDataManager=es(this),this.programManager=new dn(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Hr(t.logLevel,!!t.debug),this.device.onuncapturederror=a=>{a.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${a.error.message}`)},Object.defineProperty(this.env.webgpu,\"device\",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,\"adapter\",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<\"u\"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t=this.getCommandEncoder(),r={};this.queryType===\"at-passes\"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ue(),this.endComputePass();let t;this.queryType!==\"none\"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),t=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(t,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,t,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!==\"none\"&&t.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(t.getMappedRange()),n=this.pendingQueries.get(t);for(let o=0;o\"u\"&&(this.queryTimeBase=w);let g=Number(w-this.queryTimeBase),x=Number(y-this.queryTimeBase);if(!Number.isSafeInteger(g)||!Number.isSafeInteger(x))throw new RangeError(\"incorrect timestamp range\");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:u.map($=>({dims:$.dims,dataType:bt($.dataType)})),outputsMetadata:h.map($=>({dims:$.dims,dataType:bt($.dataType)})),kernelId:a,kernelType:d,kernelName:c,programName:m,startTime:g,endTime:x});else{let $=\"\";u.forEach((S,T)=>{$+=`input[${T}]: [${S.dims}] | ${bt(S.dataType)}, `});let v=\"\";h.forEach((S,T)=>{v+=`output[${T}]: [${S.dims}] | ${bt(S.dataType)}, `}),console.log(`[profiling] kernel \"${a}|${d}|${c}|${m}\" ${$}${v}execution time: ${x-g} ns`)}Cr(\"GPU\",`${m}::${w}::${y}`)}t.unmap(),this.pendingQueries.delete(t)}),Be()}run(t,r,n,o,i,a){Ue(t.name);let l=[];for(let S=0;ST):n;if(u.length!==d.length)throw new Error(`Output size ${u.length} must be equal to ${d.length}.`);let h=[],w=[];for(let S=0;S=a)throw new Error(`Invalid output index: ${u[S]}`);if(u[S]===-3)continue;let T=u[S]===-1,C=u[S]===-2,A=T||C?i(d[S].dataType,d[S].dims):o(u[S],d[S].dataType,d[S].dims);if(h.push(A),A.data===0)continue;let P=this.gpuDataManager.get(A.data);if(!P)throw new Error(`no GPU data for output: ${A.data}`);if(T&&this.temporaryData.push(P),C){let O=this.kernelPersistentData.get(this.currentKernelId);O||(O=[],this.kernelPersistentData.set(this.currentKernelId,O)),O.push(P)}w.push(P)}if(l.length!==r.length||w.length!==h.length){if(w.length===0)return Be(t.name),h;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let y;if(m){let S=0,T=[];m.forEach(O=>{let U=typeof O.data==\"number\"?[O.data]:O.data;if(U.length===0)return;let L=O.type===10?2:4,j,K;O.type===10?(K=U.length>4?16:U.length>2?8:U.length*L,j=U.length>4?16:L*U.length):(K=U.length<=2?U.length*L:16,j=16),S=Math.ceil(S/K)*K,T.push(S);let W=O.type===10?8:4;S+=U.length>4?Math.ceil(U.length/W)*j:U.length*L});let C=16;S=Math.ceil(S/C)*C;let A=new ArrayBuffer(S);m.forEach((O,U)=>{let L=T[U],j=typeof O.data==\"number\"?[O.data]:O.data;if(O.type===6)new Int32Array(A,L,j.length).set(j);else if(O.type===12)new Uint32Array(A,L,j.length).set(j);else if(O.type===10)new Uint16Array(A,L,j.length).set(j);else if(O.type===1)new Float32Array(A,L,j.length).set(j);else throw new Error(`Unsupported uniform type: ${bt(O.type)}`)});let P=this.gpuDataManager.create(S,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(P.buffer,0,A,0,S),this.gpuDataManager.release(P.id),y={offset:0,size:S,buffer:P.buffer}}let g=this.programManager.normalizeDispatchGroupSize(c),x=g[1]===1&&g[2]===1,$=rg(t,r,x),v=this.programManager.getArtifact($);if(v||(v=this.programManager.build(t,g),this.programManager.setArtifact($,v),se(\"info\",()=>`[artifact] key: ${$}, programName: ${t.name}`)),m&&v.uniformVariablesInfo){if(m.length!==v.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${v.uniformVariablesInfo.length}, got ${m.length} in program \"${v.programInfo.name}\".`);for(let S=0;S`[ProgramManager] run \"${t.name}\" (key=${$}) with ${g[0]}x${g[1]}x${g[2]}`),this.queryType!==\"none\"||this.sessionStatus===\"capturing\"){let S={kernelId:this.currentKernelId,programName:v.programInfo.name,inputTensorViews:r,outputTensorViews:h};this.pendingKernels.push(S),this.sessionStatus===\"capturing\"&&this.capturedPendingKernels.get(this.currentSessionId).push(S)}return this.programManager.run(v,l,w,g,y),Be(t.name),h}upload(t,r){this.gpuDataManager.upload(t,r)}memcpy(t,r){this.gpuDataManager.memcpy(t,r)}async download(t,r){await this.gpuDataManager.download(t,r)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,r,n,o){let i=Ld.get(t);if(!i)throw new Error(`kernel not implemented: ${t}`);let a={kernelType:t,kernelName:o,kernelEntry:i[0],attributes:[i[1],n]};this.kernels.set(r,a)}releaseKernel(t){let r=this.kernelPersistentData.get(t);if(r){for(let n of r)this.gpuDataManager.release(n.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,r,n){let o=this.kernels.get(t);if(!o)throw new Error(`kernel not created: ${t}`);let i=o.kernelType,a=o.kernelName,l=o.kernelEntry,d=o.attributes;if(this.currentKernelId!==null)throw new Error(`kernel \"[${i}] ${a}\" is not allowed to be called recursively`);this.currentKernelId=t,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),se(\"info\",()=>`[WebGPU] Start to run kernel \"[${i}] ${a}\"...`);let c=this.env.debug;this.temporaryData=[];try{return c&&this.device.pushErrorScope(\"validation\"),l(r,d[1]),0}catch(m){return n.push(Promise.resolve(`[WebGPU] Kernel \"[${i}] ${a}\" failed. ${m}`)),1}finally{c&&n.push(this.device.popErrorScope().then(m=>m?`GPU validation error for kernel \"[${i}] ${a}\": ${m.message}`:null));for(let m of this.temporaryData)this.gpuDataManager.release(m.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,r,n,o){let i=this.sessionExternalDataMapping.get(t);i||(i=new Map,this.sessionExternalDataMapping.set(t,i));let a=i.get(r),l=this.gpuDataManager.registerExternalBuffer(n,o,a);return i.set(r,[l,n]),l}unregisterBuffers(t){let r=this.sessionExternalDataMapping.get(t);r&&(r.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[0])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let r=this.gpuDataManager.get(t);if(!r)throw new Error(`no GPU data for buffer: ${t}`);return r.buffer}createDownloader(t,r,n){return async()=>{let o=await so(this,t,r);return Fr(o.buffer,n)}}writeTimestamp(t){this.queryType===\"inside-passes\"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}setQueryType(){this.queryType=\"none\",(this.env.webgpu.profiling?.mode===\"default\"||(typeof this.env.trace>\"u\"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has(\"chromium-experimental-timestamp-query-inside-passes\")?this.queryType=\"inside-passes\":this.device.features.has(\"timestamp-query\")&&(this.queryType=\"at-passes\"),this.queryType!==\"none\"&&typeof this.querySet>\"u\"&&(this.querySet=this.device.createQuerySet({type:\"timestamp\",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){se(\"info\",\"captureBegin\"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus=\"capturing\"}captureEnd(){se(\"info\",\"captureEnd\"),this.flush(),this.sessionStatus=\"default\"}replay(){se(\"info\",\"replay\"),this.sessionStatus=\"replaying\";let t=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),n=t.length;this.pendingKernels=[];for(let o=0;o=this.maxDispatchNumber||this.queryType===\"at-passes\")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus=\"default\"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}});var ng,qd,og,jd,pn,mn,Do,Kd,Yd=R(()=>{\"use strict\";je();ng=1,qd=()=>ng++,og=new Map([[\"float32\",32],[\"float16\",16],[\"int32\",32],[\"uint32\",32],[\"int64\",64],[\"uint64\",64],[\"int8\",8],[\"uint8\",8],[\"int4\",4],[\"uint4\",4]]),jd=(e,t)=>{let r=og.get(e);if(!r)throw new Error(\"Unsupported data type.\");return Math.ceil(t.reduce((n,o)=>n*o)*r/8)},pn=class{constructor(t){this.sessionId=t.sessionId,this.mlContext=t.context,this.mlTensor=t.tensor,this.dataType=t.dataType,this.tensorShape=t.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return jd(this.dataType,this.tensorShape)}destroy(){se(\"verbose\",()=>\"[WebNN] TensorWrapper.destroy\"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t){return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}sameTypeAndShape(t,r){return this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((n,o)=>n===r[o])}},mn=class{constructor(t,r){this.tensorManager=t;this.wrapper=r}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(t,r,n){if(this.wrapper){if(this.wrapper.sameTypeAndShape(t,r))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==jd(t,r))throw new Error(\"Unable to copy data to tensor with different size.\");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let o=MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,r,o,!0,!0),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(t){if(this.wrapper)if(t.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else se(\"verbose\",()=>\"Data size does not match tensor size. Releasing tensor.\"),this.releaseTensor();this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(t){if(this.activeUpload)if(t){t instanceof ArrayBuffer?new Uint8Array(t).set(this.activeUpload):new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.wrapper)throw new Error(\"Tensor has not been created.\");return t?this.wrapper.read(t):this.wrapper.read()}},Do=class{constructor(t){this.backend=t;this.tensorTrackersById=new Map;this.freeTensors=[];this.externalTensors=new Set}reserveTensorId(){let t=qd();return this.tensorTrackersById.set(t,new mn(this)),t}releaseTensorId(t){let r=this.tensorTrackersById.get(t);r&&(this.tensorTrackersById.delete(t),r.tensorWrapper&&this.releaseTensor(r.tensorWrapper))}async ensureTensor(t,r,n,o){se(\"verbose\",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${n}, copyOld: ${o}}`);let i=this.tensorTrackersById.get(t);if(!i)throw new Error(\"Tensor not found.\");return i.ensureTensor(r,n,o)}upload(t,r){let n=this.tensorTrackersById.get(t);if(!n)throw new Error(\"Tensor not found.\");n.upload(r)}async download(t,r){se(\"verbose\",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${r?.byteLength}}`);let n=this.tensorTrackersById.get(t);if(!n)throw new Error(\"Tensor not found.\");return n.download(r)}releaseTensorsForSession(t){for(let r of this.freeTensors)r.sessionId===t&&r.destroy();this.freeTensors=this.freeTensors.filter(r=>r.sessionId!==t)}registerTensor(t,r,n,o){let i=qd(),a=new pn({sessionId:this.backend.currentSessionId,context:t,tensor:r,dataType:n,shape:o});return this.tensorTrackersById.set(i,new mn(this,a)),this.externalTensors.add(a),i}async getCachedTensor(t,r,n,o,i){let a=this.backend.currentSessionId;for(let[c,m]of this.freeTensors.entries())if(m.sameTypeAndShape(t,r)){se(\"verbose\",()=>`[WebNN] Reusing tensor {dataType: ${t}, shape: ${r}}`);let u=this.freeTensors.splice(c,1)[0];return u.sessionId=a,u}let l=this.backend.currentContext;se(\"verbose\",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, shape: ${r}}`);let d=await l.createTensor({dataType:t,shape:r,dimensions:r,usage:n,writable:o,readable:i});return new pn({sessionId:a,context:l,tensor:d,dataType:t,shape:r})}releaseTensor(t){this.externalTensors.has(t)&&this.externalTensors.delete(t),this.freeTensors.push(t)}},Kd=(...e)=>new Do(...e)});var Zd,ig,fn,Xd=R(()=>{\"use strict\";te();gt();no();Yd();je();Zd=new Map([[1,\"float32\"],[10,\"float16\"],[6,\"int32\"],[12,\"uint32\"],[7,\"int64\"],[13,\"uint64\"],[22,\"int4\"],[21,\"uint4\"],[3,\"int8\"],[2,\"uint8\"],[9,\"uint8\"]]),ig=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.length===n.length&&r.every((o,i)=>o===n[i]&&e[o]===t[o])},fn=class{constructor(t){this.tensorManager=Kd(this);this.mlContextBySessionId=new Map;this.sessionIdsByMLContext=new Map;this.mlContextCache=[];Hr(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error(\"No active session\");return this.activeSessionId}onRunStart(t){this.activeSessionId=t}async createMLContext(t){if(t instanceof GPUDevice){let n=this.mlContextCache.findIndex(o=>o.gpuDevice===t);if(n!==-1)return this.mlContextCache[n].mlContext;{let o=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:o}),o}}else if(t===void 0){let n=this.mlContextCache.findIndex(o=>o.options===void 0&&o.gpuDevice===void 0);if(n!==-1)return this.mlContextCache[n].mlContext;{let o=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:o}),o}}let r=this.mlContextCache.findIndex(n=>ig(n.options,t));if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:n}),n}}get currentContext(){let t=this.getMLContext(this.currentSessionId);if(!t)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return t}registerMLContext(t,r){this.mlContextBySessionId.set(t,r);let n=this.sessionIdsByMLContext.get(r);n||(n=new Set,this.sessionIdsByMLContext.set(r,n)),n.add(t)}onReleaseSession(t){let r=this.mlContextBySessionId.get(t);if(!r)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t);let n=this.sessionIdsByMLContext.get(r);if(n.delete(t),n.size===0){this.sessionIdsByMLContext.delete(r);let o=this.mlContextCache.findIndex(i=>i.mlContext===r);o!==-1&&this.mlContextCache.splice(o,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){se(\"verbose\",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,r,n,o){let i=Zd.get(r);if(!i)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(t,i,n,o)}uploadTensor(t,r){if(!Te().shouldTransferToMLTensor)throw new Error(\"Trying to upload to a MLTensor while shouldTransferToMLTensor is false\");se(\"verbose\",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${r.byteLength}}`),this.tensorManager.upload(t,r)}async downloadTensor(t,r){return this.tensorManager.download(t,r)}createMLTensorDownloader(t,r){return async()=>{let n=await this.tensorManager.download(t);return Fr(n,r)}}registerMLTensor(t,r,n){let o=Zd.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);let i=this.tensorManager.registerTensor(this.currentContext,t,o,n);return se(\"verbose\",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${o}, dimensions: ${n}} -> {tensorId: ${i}}`),i}registerMLConstant(t,r,n,o,i,a){if(!a)throw new Error(\"External mounted files are not available.\");let l=t;t.startsWith(\"./\")&&(l=t.substring(2));let d=a.get(l);if(!d)throw new Error(`File with name ${l} not found in preloaded files.`);if(r+n>d.byteLength)throw new Error(\"Out of bounds: data offset and length exceed the external file data size.\");let c=d.slice(r,r+n).buffer,m;switch(i.dataType){case\"float32\":m=new Float32Array(c);break;case\"float16\":m=new Uint16Array(c);break;case\"int32\":m=new Int32Array(c);break;case\"uint32\":m=new Uint32Array(c);break;case\"int64\":m=new BigInt64Array(c);break;case\"uint64\":m=new BigUint64Array(c);break;case\"int8\":m=new Int8Array(c);break;case\"int4\":case\"uint4\":case\"uint8\":m=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return se(\"verbose\",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`),o.constant(i,m)}flush(){}}});var Qd={};Ft(Qd,{init:()=>ag});var sr,Bo,ag,Jd=R(()=>{\"use strict\";te();Fd();je();oe();Xd();sr=class e{constructor(t,r,n,o){this.module=t;this.dataType=r;this.data=n;this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error(\"Invalid data type\");let t=k.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error(\"Invalid data type\");let t=k.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error(\"Invalid data type\");let t=k.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error(\"Invalid data type\");let t=k.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(k.size(t)!==k.size(this.dims))throw new Error(\"Invalid new shape\");return new e(this.module,this.dataType,this.data,t)}},Bo=class{constructor(t,r,n){this.module=t;this.backend=r;this.customDataOffset=0;this.customDataSize=0;this.adapterInfo=r.adapterInfo,this.deviceInfo=r.deviceInfo;let o=t.PTR_SIZE,i=n/t.PTR_SIZE,a=o===4?\"i32\":\"i64\";this.opKernelContext=Number(t.getValue(o*i++,a));let l=Number(t.getValue(o*i++,a));this.outputCount=Number(t.getValue(o*i++,a)),this.customDataOffset=Number(t.getValue(o*i++,\"*\")),this.customDataSize=Number(t.getValue(o*i++,a));let d=[];for(let c=0;ctypeof l==\"number\"?this.inputs[l]:l)??this.inputs,o=r?.outputs??[],i=(l,d,c)=>new sr(this.module,d,this.output(l,c),c),a=(l,d)=>{let c=Tt(l,d);if(!c)throw new Error(`Unsupported data type: ${l}`);let m=c>0?this.backend.gpuDataManager.create(c).id:0;return new sr(this.module,l,m,d)};return this.backend.run(t,n,o,i,a,this.outputCount)}output(t,r){let n=this.module.stackSave();try{let o=this.module.PTR_SIZE,i=o===4?\"i32\":\"i64\",a=this.module.stackAlloc((1+r.length)*o);this.module.setValue(a,r.length,i);for(let l=0;l{let o=t.jsepInit;if(!o)throw new Error(\"Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.\");if(e===\"webgpu\"){let i=new cn;await i.initialize(r,n),o(\"webgpu\",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,d,c=!1)=>{if(c)se(\"verbose\",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(d)}`),i.memcpy(Number(a),Number(l));else{se(\"verbose\",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(d)}`);let m=t.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(d));i.upload(Number(l),m)}},async(a,l,d)=>{se(\"verbose\",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${d}`),await i.download(Number(a),()=>t.HEAPU8.subarray(Number(l)>>>0,Number(l+d)>>>0))},(a,l,d)=>i.createKernel(a,Number(l),d,t.UTF8ToString(t._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,d,c)=>{se(\"verbose\",()=>`[WebGPU] jsepRun: sessionHandle=${d}, kernel=${a}, contextDataOffset=${l}`);let m=new Bo(t,i,Number(l));return i.computeKernel(Number(a),m,c)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let i=new fn(r);o(\"webnn\",[i,()=>i.reserveTensorId(),a=>i.releaseTensorId(a),async(a,l,d,c)=>i.ensureTensor(a,l,d,c),(a,l)=>{i.uploadTensor(a,l)},async(a,l)=>i.downloadTensor(a,l)])}}});var sg,zr,Or,kt,ug,Kt,Dr,Br,ec,Mr,Rr,Ur,Xn=R(()=>{\"use strict\";qa();Ka();te();gt();Nr();ro();sg=(e,t)=>{Te()._OrtInit(e,t)!==0&&pe(\"Can't initialize onnxruntime.\")},zr=async e=>{sg(e.wasm.numThreads,Xt(e.logLevel))},Or=async(e,t)=>{{let r=(Jd(),vr(Qd)).init;if(t===\"webgpu\"){if(typeof navigator>\"u\"||!navigator.gpu)throw new Error(\"WebGPU is not supported in current environment\");let n=e.webgpu.adapter;if(n){if(typeof n.limits!=\"object\"||typeof n.features!=\"object\"||typeof n.requestDevice!=\"function\")throw new Error(\"Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.\")}else{let o=e.webgpu.powerPreference;if(o!==void 0&&o!==\"low-power\"&&o!==\"high-performance\")throw new Error(`Invalid powerPreference setting: \"${o}\"`);let i=e.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!=\"boolean\")throw new Error(`Invalid forceFallbackAdapter setting: \"${i}\"`);if(n=await navigator.gpu.requestAdapter({powerPreference:o,forceFallbackAdapter:i}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag \"--enable-unsafe-webgpu\" if you are using Chrome.')}await r(\"webgpu\",Te(),e,n)}if(t===\"webnn\"){if(typeof navigator>\"u\"||!navigator.ml)throw new Error(\"WebNN is not supported in current environment\");await r(\"webnn\",Te(),e)}}},kt=new Map,ug=e=>{let t=Te(),r=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,o,o+n)!==0&&pe(\"Can't get session input/output count.\");let a=n===4?\"i32\":\"i64\";return[Number(t.getValue(o,a)),Number(t.getValue(o+n,a))]}finally{t.stackRestore(r)}},Kt=e=>{let t=Te(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},Dr=async(e,t)=>{let r,n,o=Te();Array.isArray(e)?[r,n]=e:e.buffer===o.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=Kt(e);let i=0,a=0,l=0,d=[],c=[],m=[];try{if([a,d]=ja(t),t?.externalData&&o.mountExternalData){let v=[];for(let S of t.externalData){let T=typeof S==\"string\"?S:S.path;v.push(Qt(typeof S==\"string\"?S:S.data).then(C=>{o.mountExternalData(T,C)}))}await Promise.all(v)}for(let v of t?.executionProviders??[])if((typeof v==\"string\"?v:v.name)===\"webnn\"){if(o.shouldTransferToMLTensor=!1,o.currentContext)throw new Error(\"WebNN execution provider is already set.\");if(typeof v!=\"string\"){let T=v,C=T?.context,A=T?.gpuDevice,P=T?.deviceType,O=T?.powerPreference;C?o.currentContext=C:A?o.currentContext=await o.jsepCreateMLContext(A):o.currentContext=await o.jsepCreateMLContext({deviceType:P,powerPreference:O})}else o.currentContext=await o.jsepCreateMLContext();break}i=await o._OrtCreateSession(r,n,a),i===0&&pe(\"Can't create a session.\"),o.jsepOnCreateSession?.(),o.currentContext&&(o.jsepRegisterMLContext(i,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[u,h]=ug(i),w=!!t?.enableGraphCapture,y=[],g=[],x=[];for(let v=0;vv===\"gpu-buffer\"||v===\"ml-tensor\")&&(l=o._OrtCreateBinding(i),l===0&&pe(\"Can't create IO binding.\"),$={handle:l,outputPreferredLocations:x,outputPreferredLocationsEncoded:x.map(v=>to(v))}),kt.set(i,[i,c,m,$,w,!1]),[i,y,g]}catch(u){throw c.forEach(h=>o._OrtFree(h)),m.forEach(h=>o._OrtFree(h)),l!==0&&o._OrtReleaseBinding(l)!==0&&pe(\"Can't release IO binding.\"),i!==0&&o._OrtReleaseSession(i)!==0&&pe(\"Can't release session.\"),u}finally{o._free(r),a!==0&&o._OrtReleaseSessionOptions(a)!==0&&pe(\"Can't release session options.\"),d.forEach(u=>o._free(u)),o.unmountExternalData?.()}},Br=e=>{let t=Te(),r=kt.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,o,i,a,l]=r;a&&(l&&t._OrtClearBoundOutputs(a.handle)!==0&&pe(\"Can't clear bound outputs.\"),t._OrtReleaseBinding(a.handle)!==0&&pe(\"Can't release IO binding.\")),t.jsepOnReleaseSession?.(e),o.forEach(d=>t._OrtFree(d)),i.forEach(d=>t._OrtFree(d)),t._OrtReleaseSession(n)!==0&&pe(\"Can't release session.\"),kt.delete(e)},ec=(e,t,r,n,o,i=!1)=>{if(!e){t.push(0);return}let a=Te(),l=a.PTR_SIZE,d=e[0],c=e[1],m=e[3],u,h;if(d===\"string\"&&(m===\"gpu-buffer\"||m===\"ml-tensor\"))throw new Error(\"String tensor is not supported on GPU.\");if(i&&m!==\"gpu-buffer\")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(m===\"gpu-buffer\"){let g=e[2].gpuBuffer;h=Tt(Zt(d),c);let x=a.jsepRegisterBuffer;if(!x)throw new Error('Tensor location \"gpu-buffer\" is not supported without using WebGPU.');u=x(n,o,g,h)}else if(m===\"ml-tensor\"){let g=e[2].mlTensor;h=Tt(Zt(d),c);let x=a.jsepRegisterMLTensor;if(!x)throw new Error('Tensor location \"ml-tensor\" is not supported without using WebNN.');u=x(g,Zt(d),c)}else{let g=e[2];if(Array.isArray(g)){h=l*g.length,u=a._malloc(h),r.push(u);for(let x=0;xa.setValue(y+$*l,x,l===4?\"i32\":\"i64\"));let g=a._OrtCreateTensor(Zt(d),u,h,y,c.length,to(m));g===0&&pe(`Can't create tensor for input/output. session=${n}, index=${o}.`),t.push(g)}finally{a.stackRestore(w)}},Mr=async(e,t,r,n,o,i)=>{let a=Te(),l=a.PTR_SIZE,d=kt.get(e);if(!d)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=d[0],m=d[1],u=d[2],h=d[3],w=d[4],y=d[5],g=t.length,x=n.length,$=0,v=[],S=[],T=[],C=[],A=a.stackSave(),P=a.stackAlloc(g*l),O=a.stackAlloc(g*l),U=a.stackAlloc(x*l),L=a.stackAlloc(x*l);try{a.jsepOnRunStart?.(c),[$,v]=Fa(i);for(let W=0;W_e*be,1);Q=bt($e);let qe=h?.outputPreferredLocations[n[W]];if(Q===\"string\"){if(qe===\"gpu-buffer\"||qe===\"ml-tensor\")throw new Error(\"String tensor is not supported on GPU.\");let _e=[];for(let be=0;be0){let _e=a.jsepGetBuffer;if(!_e)throw new Error('preferredLocation \"gpu-buffer\" is not supported without using WebGPU.');let be=_e(ne),Ye=Tt($e,he);if(Ye===void 0||!Lr(Q))throw new Error(`Unsupported data type: ${Q}`);J=!0,K.push([Q,q,{gpuBuffer:be,download:a.jsepCreateDownloader(be,Ye,Q),dispose:()=>{a._OrtReleaseTensor(ee)!==0&&pe(\"Can't release tensor.\")}},\"gpu-buffer\"])}else if(qe===\"ml-tensor\"&&he>0){let _e=a.jsepEnsureTensor;if(!_e)throw new Error('preferredLocation \"ml-tensor\" is not supported without using WebNN.');if(Tt($e,he)===void 0||!Gr(Q))throw new Error(`Unsupported data type: ${Q}`);let Ye=await _e(ne,$e,q,!1);J=!0,K.push([Q,q,{mlTensor:Ye,download:a.jsepCreateMLTensorDownloader(ne,Q),dispose:()=>{a.jsepReleaseTensorId(ne),a._OrtReleaseTensor(ee)}},\"ml-tensor\"])}else{let _e=Wr(Q),be=new _e(he);new Uint8Array(be.buffer,be.byteOffset,be.byteLength).set(a.HEAPU8.subarray(ne,ne+be.byteLength)),K.push([Q,q,be,\"cpu\"])}}finally{a.stackRestore(ue),Q===\"string\"&&ne&&a._free(ne),J||a._OrtReleaseTensor(ee)}}return h&&!w&&(a._OrtClearBoundOutputs(h.handle)!==0&&pe(\"Can't clear bound outputs.\"),kt.set(e,[c,m,u,h,w,!1])),K}finally{a.stackRestore(A),S.forEach(j=>a._OrtReleaseTensor(j)),T.forEach(j=>a._OrtReleaseTensor(j)),C.forEach(j=>a._free(j)),$!==0&&a._OrtReleaseRunOptions($),v.forEach(j=>a._free(j))}},Rr=e=>{let t=Te(),r=kt.get(e);if(!r)throw new Error(\"invalid session id\");let n=r[0],o=t._OrtEndProfiling(n);o===0&&pe(\"Can't get an profile file name.\"),t._OrtFree(o)},Ur=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&\"buffer\"in n&&t.push(n.buffer)}return t}});var Et,Fe,ur,gn,bn,hn,Mo,Ro,Nt,Wt,dg,tc,rc,nc,oc,ic,ac,sc,Uo=R(()=>{\"use strict\";He();Xn();gt();jt();Et=()=>!!ve.wasm.proxy&&typeof document<\"u\",ur=!1,gn=!1,bn=!1,Ro=new Map,Nt=(e,t)=>{let r=Ro.get(e);r?r.push(t):Ro.set(e,[t])},Wt=()=>{if(ur||!gn||bn||!Fe)throw new Error(\"worker not ready\")},dg=e=>{switch(e.data.type){case\"init-wasm\":ur=!1,e.data.err?(bn=!0,Mo[1](e.data.err)):(gn=!0,Mo[0]()),hn&&(URL.revokeObjectURL(hn),hn=void 0);break;case\"init-ep\":case\"copy-from\":case\"create\":case\"release\":case\"run\":case\"end-profiling\":{let t=Ro.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},tc=async()=>{if(!gn){if(ur)throw new Error(\"multiple calls to 'initWasm()' detected.\");if(bn)throw new Error(\"previous call to 'initWasm()' failed.\");if(ur=!0,Et())return new Promise((e,t)=>{Fe?.terminate(),La().then(([r,n])=>{try{Fe=n,Fe.onerror=i=>t(i),Fe.onmessage=dg,Mo=[e,t];let o={type:\"init-wasm\",in:ve};Fe.postMessage(o),hn=r}catch(o){t(o)}},t)});try{await Pr(ve.wasm),await zr(ve),gn=!0}catch(e){throw bn=!0,e}finally{ur=!1}}},rc=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Nt(\"init-ep\",[t,r]);let n={type:\"init-ep\",in:{epName:e,env:ve}};Fe.postMessage(n)});await Or(ve,e)},nc=async e=>Et()?(Wt(),new Promise((t,r)=>{Nt(\"copy-from\",[t,r]);let n={type:\"copy-from\",in:{buffer:e}};Fe.postMessage(n,[e.buffer])})):Kt(e),oc=async(e,t)=>{if(Et()){if(t?.preferredOutputLocation)throw new Error('session option \"preferredOutputLocation\" is not supported for proxy.');return Wt(),new Promise((r,n)=>{Nt(\"create\",[r,n]);let o={type:\"create\",in:{model:e,options:{...t}}},i=[];e instanceof Uint8Array&&i.push(e.buffer),Fe.postMessage(o,i)})}else return Dr(e,t)},ic=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Nt(\"release\",[t,r]);let n={type:\"release\",in:e};Fe.postMessage(n)});Br(e)},ac=async(e,t,r,n,o,i)=>{if(Et()){if(r.some(a=>a[3]!==\"cpu\"))throw new Error(\"input tensor on GPU is not supported for proxy.\");if(o.some(a=>a))throw new Error(\"pre-allocated output tensor is not supported for proxy.\");return Wt(),new Promise((a,l)=>{Nt(\"run\",[a,l]);let d=r,c={type:\"run\",in:{sessionId:e,inputIndices:t,inputs:d,outputIndices:n,options:i}};Fe.postMessage(c,Ur(d))})}else return Mr(e,t,r,n,o,i)},sc=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Nt(\"end-profiling\",[t,r]);let n={type:\"end-profiling\",in:e};Fe.postMessage(n)});Rr(e)}});var uc,cg,yn,lc=R(()=>{\"use strict\";He();Uo();te();Er();ro();uc=(e,t)=>{switch(e.location){case\"cpu\":return[e.type,e.dims,e.data,\"cpu\"];case\"gpu-buffer\":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},\"gpu-buffer\"];case\"ml-tensor\":return[e.type,e.dims,{mlTensor:e.mlTensor},\"ml-tensor\"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},cg=e=>{switch(e[3]){case\"cpu\":return new De(e[0],e[2],e[1]);case\"gpu-buffer\":{let t=e[0];if(!Lr(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:o}=e[2];return De.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:o})}case\"ml-tensor\":{let t=e[0];if(!Gr(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:o}=e[2];return De.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},yn=class{async fetchModelAndCopyToWasmMemory(t){return nc(await Qt(t))}async loadModel(t,r){Ue();let n;typeof t==\"string\"?!1?n=await Qt(t):n=await this.fetchModelAndCopyToWasmMemory(t):n=t,[this.sessionId,this.inputNames,this.outputNames]=await oc(n,r),Be()}async dispose(){return ic(this.sessionId)}async run(t,r,n){Ue();let o=[],i=[];Object.entries(t).forEach(h=>{let w=h[0],y=h[1],g=this.inputNames.indexOf(w);if(g===-1)throw new Error(`invalid input '${w}'`);o.push(y),i.push(g)});let a=[],l=[];Object.entries(r).forEach(h=>{let w=h[0],y=h[1],g=this.outputNames.indexOf(w);if(g===-1)throw new Error(`invalid output '${w}'`);a.push(y),l.push(g)});let d=o.map((h,w)=>uc(h,()=>`input \"${this.inputNames[i[w]]}\"`)),c=a.map((h,w)=>h?uc(h,()=>`output \"${this.outputNames[l[w]]}\"`):null),m=await ac(this.sessionId,i,d,l,c,n),u={};for(let h=0;hwn,initializeFlags:()=>dc,wasmBackend:()=>pg});var dc,wn,pg,pc=R(()=>{\"use strict\";He();Uo();lc();jt();dc=()=>{if((typeof ve.wasm.initTimeout!=\"number\"||ve.wasm.initTimeout<0)&&(ve.wasm.initTimeout=0),ve.wasm.simd===!1&&console.warn('Deprecated property \"env.wasm.simd\" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof ve.wasm.proxy!=\"boolean\"&&(ve.wasm.proxy=!1),typeof ve.wasm.trace!=\"boolean\"&&(ve.wasm.trace=!1),typeof ve.wasm.numThreads!=\"number\"||!Number.isInteger(ve.wasm.numThreads)||ve.wasm.numThreads<=0)if(typeof self<\"u\"&&!self.crossOriginIsolated)ve.wasm.numThreads=1;else{let e=typeof navigator>\"u\"?qn(\"node:os\").cpus().length:navigator.hardwareConcurrency;ve.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},wn=class{async init(t){dc(),await tc(),await rc(t)}async createInferenceSessionHandler(t,r){let n=new yn;return await n.loadModel(t,r),Promise.resolve(n)}},pg=new wn});He();He();He();var Oa=\"1.21.0-dev.20241109-d3ad76b2cf\";var y1=Zn;{let e=(pc(),vr(cc)).wasmBackend;xt(\"webgpu\",e,5),xt(\"webnn\",e,5),xt(\"cpu\",e,10),xt(\"wasm\",e,10)}Object.defineProperty(ve.versions,\"web\",{value:Oa,enumerable:!0});export{Mp as InferenceSession,Cr as TRACE,Ue as TRACE_FUNC_BEGIN,Be as TRACE_FUNC_END,De as Tensor,Up as TrainingSession,y1 as default,ve as env,xt as registerBackend};\n/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n//# sourceMappingURL=ort.webgpu.bundle.min.mjs.map\n","/**\n * @file Handler file for choosing the correct version of ONNX Runtime, based on the environment.\n * Ideally, we could import the `onnxruntime-web` and `onnxruntime-node` packages only when needed,\n * but dynamic imports don't seem to work with the current webpack version and/or configuration.\n * This is possibly due to the experimental nature of top-level await statements.\n * So, we just import both packages, and use the appropriate one based on the environment:\n * - When running in node, we use `onnxruntime-node`.\n * - When running in the browser, we use `onnxruntime-web` (`onnxruntime-node` is not bundled).\n * \n * This module is not directly exported, but can be accessed through the environment variables:\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * console.log(env.backends.onnx);\n * ```\n * \n * @module backends/onnx\n */\n\nimport { env, apis } from '../env.js';\n\n// NOTE: Import order matters here. We need to import `onnxruntime-node` before `onnxruntime-web`.\n// In either case, we select the default export if it exists, otherwise we use the named export.\nimport * as ONNX_NODE from 'onnxruntime-node';\n\n// Use subpath-imports to ensure Node.js and browser interoperability.\n// See package.json and https://nodejs.org/api/packages.html#subpath-imports\n// for more information.\n// @ts-ignore\nimport * as ONNX_WEB from '#onnxruntime-webgpu';\n\nexport { Tensor } from 'onnxruntime-common';\n\n/**\n * @typedef {import('onnxruntime-common').InferenceSession.ExecutionProviderConfig} ONNXExecutionProviders\n */\n\n/** @type {Record} */\nconst DEVICE_TO_EXECUTION_PROVIDER_MAPPING = Object.freeze({\n auto: null, // Auto-detect based on device and environment\n gpu: null, // Auto-detect GPU\n cpu: 'cpu', // CPU\n wasm: 'wasm', // WebAssembly\n webgpu: 'webgpu', // WebGPU\n cuda: 'cuda', // CUDA\n dml: 'dml', // DirectML\n\n webnn: { name: 'webnn', deviceType: 'cpu' }, // WebNN (default)\n 'webnn-npu': { name: 'webnn', deviceType: 'npu' }, // WebNN NPU\n 'webnn-gpu': { name: 'webnn', deviceType: 'gpu' }, // WebNN GPU\n 'webnn-cpu': { name: 'webnn', deviceType: 'cpu' }, // WebNN CPU\n});\n\n/** \n * The list of supported devices, sorted by priority/performance.\n * @type {import(\"../utils/devices.js\").DeviceType[]}\n */\nconst supportedDevices = [];\n\n/** @type {ONNXExecutionProviders[]} */\nlet defaultDevices;\nlet ONNX;\nconst ORT_SYMBOL = Symbol.for('onnxruntime');\n\nif (ORT_SYMBOL in globalThis) {\n // If the JS runtime exposes their own ONNX runtime, use it\n ONNX = globalThis[ORT_SYMBOL];\n\n} else if (apis.IS_NODE_ENV) {\n ONNX = ONNX_NODE.default ?? ONNX_NODE;\n\n // Updated as of ONNX Runtime 1.18.0\n // The following table lists the supported versions of ONNX Runtime Node.js binding provided with pre-built binaries.\n // | EPs/Platforms | Windows x64 | Windows arm64 | Linux x64 | Linux arm64 | MacOS x64 | MacOS arm64 |\n // | ------------- | ----------- | ------------- | ----------------- | ----------- | --------- | ----------- |\n // | CPU | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |\n // | DirectML | ✔️ | ✔️ | ❌ | ❌ | ❌ | ❌ |\n // | CUDA | ❌ | ❌ | ✔️ (CUDA v11.8) | ❌ | ❌ | ❌ |\n switch (process.platform) {\n case 'win32': // Windows x64 and Windows arm64\n supportedDevices.push('dml');\n break;\n case 'linux': // Linux x64 and Linux arm64\n if (process.arch === 'x64') {\n supportedDevices.push('cuda');\n }\n break;\n case 'darwin': // MacOS x64 and MacOS arm64\n break;\n }\n\n supportedDevices.push('cpu');\n defaultDevices = ['cpu'];\n} else {\n ONNX = ONNX_WEB;\n\n if (apis.IS_WEBNN_AVAILABLE) {\n // TODO: Only push supported providers (depending on available hardware)\n supportedDevices.push('webnn-npu', 'webnn-gpu', 'webnn-cpu', 'webnn');\n }\n\n if (apis.IS_WEBGPU_AVAILABLE) {\n supportedDevices.push('webgpu');\n }\n\n supportedDevices.push('wasm');\n defaultDevices = ['wasm'];\n}\n\n// @ts-ignore\nconst InferenceSession = ONNX.InferenceSession;\n\n/**\n * Map a device to the execution providers to use for the given device.\n * @param {import(\"../utils/devices.js\").DeviceType|\"auto\"|null} [device=null] (Optional) The device to run the inference on.\n * @returns {ONNXExecutionProviders[]} The execution providers to use for the given device.\n */\nexport function deviceToExecutionProviders(device = null) {\n // Use the default execution providers if the user hasn't specified anything\n if (!device) return defaultDevices;\n\n // Handle overloaded cases\n switch (device) {\n case \"auto\":\n return supportedDevices;\n case \"gpu\":\n return supportedDevices.filter(x =>\n [\"webgpu\", \"cuda\", \"dml\", \"webnn-gpu\"].includes(x),\n );\n }\n\n if (supportedDevices.includes(device)) {\n return [DEVICE_TO_EXECUTION_PROVIDER_MAPPING[device] ?? device];\n }\n\n throw new Error(`Unsupported device: \"${device}\". Should be one of: ${supportedDevices.join(', ')}.`)\n}\n\n\n/**\n * To prevent multiple calls to `initWasm()`, we store the first call in a Promise\n * that is resolved when the first InferenceSession is created. Subsequent calls\n * will wait for this Promise to resolve before creating their own InferenceSession.\n * @type {Promise|null}\n */\nlet wasmInitPromise = null;\n\n/**\n * Create an ONNX inference session.\n * @param {Uint8Array} buffer The ONNX model buffer.\n * @param {import('onnxruntime-common').InferenceSession.SessionOptions} session_options ONNX inference session options.\n * @param {Object} session_config ONNX inference session configuration.\n * @returns {Promise} The ONNX inference session.\n */\nexport async function createInferenceSession(buffer, session_options, session_config) {\n if (wasmInitPromise) {\n // A previous session has already initialized the WASM runtime\n // so we wait for it to resolve before creating this new session.\n await wasmInitPromise;\n }\n\n const sessionPromise = InferenceSession.create(buffer, session_options);\n wasmInitPromise ??= sessionPromise;\n const session = await sessionPromise;\n session.config = session_config;\n return session;\n}\n\n/**\n * Check if an object is an ONNX tensor.\n * @param {any} x The object to check\n * @returns {boolean} Whether the object is an ONNX tensor.\n */\nexport function isONNXTensor(x) {\n return x instanceof ONNX.Tensor;\n}\n\n/** @type {import('onnxruntime-common').Env} */\n// @ts-ignore\nconst ONNX_ENV = ONNX?.env;\nif (ONNX_ENV?.wasm) {\n // Initialize wasm backend with suitable default settings.\n\n // (Optional) Set path to wasm files. This is needed when running in a web worker.\n // https://onnxruntime.ai/docs/api/js/interfaces/Env.WebAssemblyFlags.html#wasmPaths\n // We use remote wasm files by default to make it easier for newer users.\n // In practice, users should probably self-host the necessary .wasm files.\n ONNX_ENV.wasm.wasmPaths = `https://cdn.jsdelivr.net/npm/@huggingface/transformers@${env.version}/dist/`;\n\n // TODO: Add support for loading WASM files from cached buffer when we upgrade to onnxruntime-web@1.19.0\n // https://github.com/microsoft/onnxruntime/pull/21534\n\n // Users may wish to proxy the WASM backend to prevent the UI from freezing,\n // However, this is not necessary when using WebGPU, so we default to false.\n ONNX_ENV.wasm.proxy = false;\n\n // https://developer.mozilla.org/en-US/docs/Web/API/crossOriginIsolated\n if (typeof crossOriginIsolated === 'undefined' || !crossOriginIsolated) {\n ONNX_ENV.wasm.numThreads = 1;\n }\n}\n\nif (ONNX_ENV?.webgpu) {\n ONNX_ENV.webgpu.powerPreference = 'high-performance';\n}\n\n/**\n * Check if ONNX's WASM backend is being proxied.\n * @returns {boolean} Whether ONNX's WASM backend is being proxied.\n */\nexport function isONNXProxy() {\n // TODO: Update this when allowing non-WASM backends.\n return ONNX_ENV?.wasm?.proxy;\n}\n\n// Expose ONNX environment variables to `env.backends.onnx`\nenv.backends.onnx = ONNX_ENV;\n","\n/**\n * @file Helper module for using model configs. For more information, see the corresponding\n * [Python documentation](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoConfig).\n * \n * **Example:** Load an `AutoConfig`.\n * \n * ```javascript\n * import { AutoConfig } from '@huggingface/transformers';\n * const config = await AutoConfig.from_pretrained('bert-base-uncased');\n * console.log(config);\n * // PretrainedConfig {\n * // \"model_type\": \"bert\",\n * // \"is_encoder_decoder\": false,\n * // \"architectures\": [\n * // \"BertForMaskedLM\"\n * // ],\n * // \"vocab_size\": 30522\n * // \"num_attention_heads\": 12,\n * // \"num_hidden_layers\": 12,\n * // \"hidden_size\": 768,\n * // \"max_position_embeddings\": 512,\n * // ...\n * // }\n * ```\n * \n * @module configs\n */\n\nimport { pick } from './utils/core.js';\nimport {\n getModelJSON,\n} from './utils/hub.js';\n\n/**\n * @typedef {import('./utils/hub.js').PretrainedOptions} PretrainedOptions\n */\n\n\n/**\n * Loads a config from the specified path.\n * @param {string} pretrained_model_name_or_path The path to the config directory.\n * @param {PretrainedOptions} options Additional options for loading the config.\n * @returns {Promise} A promise that resolves with information about the loaded config.\n */\nasync function loadConfig(pretrained_model_name_or_path, options) {\n return await getModelJSON(pretrained_model_name_or_path, 'config.json', true, options);\n}\n\n/**\n * \n * @param {PretrainedConfig} config \n * @returns {Object} The normalized configuration.\n */\nfunction getNormalizedConfig(config) {\n const mapping = {};\n\n let init_normalized_config = {};\n switch (config.model_type) {\n // Sub-configs\n case 'llava':\n case 'paligemma':\n case 'florence2':\n init_normalized_config = getNormalizedConfig(config.text_config);\n break;\n case 'moondream1':\n init_normalized_config = getNormalizedConfig(config.phi_config);\n break;\n case 'musicgen':\n init_normalized_config = getNormalizedConfig(config.decoder);\n break;\n\n // Decoder-only models\n case 'gpt2':\n case 'gptj':\n case 'jais':\n case 'codegen':\n case 'gpt_bigcode':\n mapping['num_heads'] = 'n_head';\n mapping['num_layers'] = 'n_layer';\n mapping['hidden_size'] = 'n_embd';\n break;\n case 'gpt_neox':\n case 'stablelm':\n case 'opt':\n case 'phi':\n case 'phi3':\n case 'falcon':\n mapping['num_heads'] = 'num_attention_heads';\n mapping['num_layers'] = 'num_hidden_layers';\n mapping['hidden_size'] = 'hidden_size';\n break;\n case 'llama':\n case 'granite':\n case 'cohere':\n case 'mistral':\n case 'starcoder2':\n case 'qwen2':\n mapping['num_heads'] = 'num_key_value_heads';\n mapping['num_layers'] = 'num_hidden_layers';\n mapping['hidden_size'] = 'hidden_size';\n mapping['num_attention_heads'] = 'num_attention_heads';\n break;\n case 'gemma':\n case 'gemma2':\n mapping['num_heads'] = 'num_key_value_heads';\n mapping['num_layers'] = 'num_hidden_layers';\n mapping['dim_kv'] = 'head_dim';\n break;\n case 'openelm':\n mapping['num_heads'] = 'num_kv_heads';\n mapping['num_layers'] = 'num_transformer_layers';\n mapping['dim_kv'] = 'head_dim';\n break;\n case 'gpt_neo':\n case 'donut-swin':\n mapping['num_heads'] = 'num_heads';\n mapping['num_layers'] = 'num_layers';\n mapping['hidden_size'] = 'hidden_size';\n break;\n case 'bloom':\n mapping['num_heads'] = 'n_head';\n mapping['num_layers'] = 'n_layer';\n mapping['hidden_size'] = 'hidden_size';\n break;\n case 'mpt':\n mapping['num_heads'] = 'n_heads';\n mapping['num_layers'] = 'n_layers';\n mapping['hidden_size'] = 'd_model';\n break;\n\n // Encoder-decoder models\n case 't5':\n case 'mt5':\n case 'longt5':\n mapping['num_decoder_layers'] = 'num_decoder_layers';\n mapping['num_decoder_heads'] = 'num_heads';\n mapping['decoder_dim_kv'] = 'd_kv';\n mapping['num_encoder_layers'] = 'num_layers';\n mapping['num_encoder_heads'] = 'num_heads';\n mapping['encoder_dim_kv'] = 'd_kv';\n break;\n case 'bart':\n case 'mbart':\n case 'marian':\n case 'whisper':\n case 'm2m_100':\n case 'blenderbot':\n case 'blenderbot-small':\n case 'florence2_language':\n mapping['num_decoder_layers'] = 'decoder_layers';\n mapping['num_decoder_heads'] = 'decoder_attention_heads';\n mapping['decoder_hidden_size'] = 'd_model';\n mapping['num_encoder_layers'] = 'encoder_layers';\n mapping['num_encoder_heads'] = 'encoder_attention_heads';\n mapping['encoder_hidden_size'] = 'd_model';\n break;\n case 'speecht5':\n mapping['num_decoder_layers'] = 'decoder_layers';\n mapping['num_decoder_heads'] = 'decoder_attention_heads';\n mapping['decoder_hidden_size'] = 'hidden_size';\n mapping['num_encoder_layers'] = 'encoder_layers';\n mapping['num_encoder_heads'] = 'encoder_attention_heads';\n mapping['encoder_hidden_size'] = 'hidden_size';\n break;\n case 'trocr':\n mapping['num_encoder_layers'] = mapping['num_decoder_layers'] = 'decoder_layers';\n mapping['num_encoder_heads'] = mapping['num_decoder_heads'] = 'decoder_attention_heads';\n mapping['encoder_hidden_size'] = mapping['decoder_hidden_size'] = 'd_model';\n break;\n case 'musicgen_decoder':\n mapping['num_encoder_layers'] = mapping['num_decoder_layers'] = 'num_hidden_layers';\n mapping['num_encoder_heads'] = mapping['num_decoder_heads'] = 'num_attention_heads';\n mapping['encoder_hidden_size'] = mapping['decoder_hidden_size'] = 'hidden_size';\n break;\n\n case 'vision-encoder-decoder':\n const decoderConfig = getNormalizedConfig(config.decoder);\n\n const add_encoder_pkv = 'num_decoder_layers' in decoderConfig;\n const result = pick(config, ['model_type', 'is_encoder_decoder']);\n if (add_encoder_pkv) {\n // Decoder is part of an encoder-decoder model\n result.num_decoder_layers = decoderConfig.num_decoder_layers;\n result.num_decoder_heads = decoderConfig.num_decoder_heads;\n result.decoder_hidden_size = decoderConfig.decoder_hidden_size;\n\n result.num_encoder_layers = decoderConfig.num_encoder_layers;\n result.num_encoder_heads = decoderConfig.num_encoder_heads;\n result.encoder_hidden_size = decoderConfig.encoder_hidden_size;\n } else {\n // Decoder is a decoder-only model\n result.num_layers = decoderConfig.num_layers;\n result.num_heads = decoderConfig.num_heads;\n result.hidden_size = decoderConfig.hidden_size;\n }\n return result;\n\n }\n\n // NOTE: If `num_attention_heads` is not set, it is assumed to be equal to `num_heads`\n const normalized_config = {\n ...init_normalized_config,\n ...pick(config, ['model_type', 'multi_query', 'is_encoder_decoder']),\n };\n for (const key in mapping) {\n normalized_config[key] = config[mapping[key]];\n }\n return normalized_config;\n}\n\n/**\n * \n * @param {PretrainedConfig} config \n * @returns {Record}\n */\nexport function getKeyValueShapes(config, {\n prefix = 'past_key_values',\n} = {}) {\n /** @type {Record} */\n const decoderFeeds = {};\n const normalized_config = config.normalized_config;\n\n // TODO support batches (i.e., batch_size > 1)\n const batch_size = 1;\n\n if (normalized_config.is_encoder_decoder && (\n 'num_encoder_heads' in normalized_config && 'num_decoder_heads' in normalized_config\n )) {\n const encoder_dim_kv = normalized_config.encoder_dim_kv ?? (\n normalized_config.encoder_hidden_size / normalized_config.num_encoder_heads\n );\n const decoder_dim_kv = normalized_config.decoder_dim_kv ?? (\n normalized_config.decoder_hidden_size / normalized_config.num_decoder_heads\n );\n\n const encoder_dims = [batch_size, normalized_config.num_encoder_heads, 0, encoder_dim_kv];\n const decoder_dims = [batch_size, normalized_config.num_decoder_heads, 0, decoder_dim_kv];\n for (let i = 0; i < normalized_config.num_decoder_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.encoder.key`] = encoder_dims;\n decoderFeeds[`${prefix}.${i}.encoder.value`] = encoder_dims;\n decoderFeeds[`${prefix}.${i}.decoder.key`] = decoder_dims;\n decoderFeeds[`${prefix}.${i}.decoder.value`] = decoder_dims;\n }\n } else { // Decoders\n const num_heads = normalized_config.num_heads;\n const num_layers = normalized_config.num_layers;\n const dim_kv = normalized_config.dim_kv ?? (\n normalized_config.hidden_size /\n (normalized_config.num_attention_heads ?? num_heads)\n );\n\n if (normalized_config.model_type === 'falcon') {\n // NOTE: Custom implementation for Falcon\n const dims = [batch_size * num_heads, 0, dim_kv]\n for (let i = 0; i < num_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.key`] = dims;\n decoderFeeds[`${prefix}.${i}.value`] = dims;\n }\n } else if (normalized_config.multi_query) { // e.g., for `gpt_bigcode`\n const dims = [batch_size * num_heads, 0, 2 * dim_kv]\n\n for (let i = 0; i < num_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.key_value`] = dims;\n }\n } else if (normalized_config.model_type === 'bloom') {\n // NOTE: Custom implementation for Bloom\n\n const keyDims = [batch_size * num_heads, dim_kv, 0] // [batch_size x num_heads,64,past_sequence_length]\n const valueDims = [batch_size * num_heads, 0, dim_kv] // [batch_size x num_heads,past_sequence_length,64]\n for (let i = 0; i < num_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.key`] = keyDims;\n decoderFeeds[`${prefix}.${i}.value`] = valueDims;\n }\n } else if (normalized_config.model_type === 'openelm') {\n for (let i = 0; i < num_layers; ++i) {\n const dims = [batch_size, num_heads[i], 0, dim_kv]\n\n decoderFeeds[`${prefix}.${i}.key`] = dims;\n decoderFeeds[`${prefix}.${i}.value`] = dims;\n }\n } else { // Decoder-only\n const dims = [batch_size, num_heads, 0, dim_kv]\n for (let i = 0; i < num_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.key`] = dims;\n decoderFeeds[`${prefix}.${i}.value`] = dims;\n }\n }\n }\n\n return decoderFeeds;\n}\n/**\n * Base class for all configuration classes. For more information, see the corresponding\n * [Python documentation](https://huggingface.co/docs/transformers/main/en/main_classes/configuration#transformers.PretrainedConfig).\n */\nexport class PretrainedConfig {\n // NOTE: Typo in original\n\n /** @type {string|null} */\n model_type = null;\n\n /** @type {boolean} */\n is_encoder_decoder = false;\n\n /** @type {number} */\n max_position_embeddings;\n\n /** @type {TransformersJSConfig} */\n 'transformers.js_config';\n\n /**\n * Create a new PreTrainedTokenizer instance.\n * @param {Object} configJSON The JSON of the config.\n */\n constructor(configJSON) {\n Object.assign(this, configJSON);\n this.normalized_config = getNormalizedConfig(this);\n }\n\n /**\n * Loads a pre-trained config from the given `pretrained_model_name_or_path`. \n * \n * @param {string} pretrained_model_name_or_path The path to the pre-trained config.\n * @param {PretrainedOptions} options Additional options for loading the config.\n * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.\n * \n * @returns {Promise} A new instance of the `PretrainedConfig` class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n } = {}) {\n if (config && !(config instanceof PretrainedConfig)) {\n config = new PretrainedConfig(config);\n }\n\n const data = config ?? await loadConfig(pretrained_model_name_or_path, {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n })\n return new this(data);\n }\n}\n\n/**\n * Helper class which is used to instantiate pretrained configs with the `from_pretrained` function.\n * \n * @example\n * const config = await AutoConfig.from_pretrained('Xenova/bert-base-uncased'); \n */\nexport class AutoConfig {\n /** @type {typeof PretrainedConfig.from_pretrained} */\n static async from_pretrained(...args) {\n return PretrainedConfig.from_pretrained(...args);\n }\n}\n\n/**\n * Transformers.js-specific configuration, possibly present in config.json under the key `transformers.js_config`.\n * @typedef {Object} TransformersJSConfig\n * @property {import('./utils/tensor.js').DataType|Record} [kv_cache_dtype] The data type of the key-value cache.\n * @property {Record} [free_dimension_overrides] Override the free dimensions of the model.\n * See https://onnxruntime.ai/docs/tutorials/web/env-flags-and-session-options.html#freedimensionoverrides\n * for more information.\n * @property {import('./utils/devices.js').DeviceType} [device] The default device to use for the model.\n * @property {import('./utils/dtypes.js').DataType} [dtype] The default data type to use for the model.\n * @property {boolean|Record} [use_external_data_format=false] Whether to load the model using the external data format (used for models >= 2GB in size).\n */\n","/**\n * @file Module used to configure Transformers.js.\n * \n * **Example:** Disable remote models.\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * env.allowRemoteModels = false;\n * ```\n * \n * **Example:** Set local model path.\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * env.localModelPath = '/path/to/local/models/';\n * ```\n * \n * **Example:** Set cache directory.\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * env.cacheDir = '/path/to/cache/directory/';\n * ```\n * \n * @module env\n */\n\nimport fs from 'fs';\nimport path from 'path';\nimport url from 'url';\n\nconst VERSION = '3.0.0';\n\n// Check if various APIs are available (depends on environment)\nconst IS_BROWSER_ENV = typeof self !== 'undefined';\nconst IS_WEBWORKER_ENV = IS_BROWSER_ENV && self.constructor.name === 'DedicatedWorkerGlobalScope';\nconst IS_WEB_CACHE_AVAILABLE = IS_BROWSER_ENV && 'caches' in self;\nconst IS_WEBGPU_AVAILABLE = typeof navigator !== 'undefined' && 'gpu' in navigator;\nconst IS_WEBNN_AVAILABLE = typeof navigator !== 'undefined' && 'ml' in navigator;\n\nconst IS_PROCESS_AVAILABLE = typeof process !== 'undefined';\nconst IS_NODE_ENV = IS_PROCESS_AVAILABLE && process?.release?.name === 'node';\nconst IS_FS_AVAILABLE = !isEmpty(fs);\nconst IS_PATH_AVAILABLE = !isEmpty(path);\n\n/**\n * A read-only object containing information about the APIs available in the current environment.\n */\nexport const apis = Object.freeze({\n /** Whether we are running in a browser environment */\n IS_BROWSER_ENV,\n\n /** Whether we are running in a web worker environment */\n IS_WEBWORKER_ENV,\n\n /** Whether the Cache API is available */\n IS_WEB_CACHE_AVAILABLE,\n\n /** Whether the WebGPU API is available */\n IS_WEBGPU_AVAILABLE,\n\n /** Whether the WebNN API is available */\n IS_WEBNN_AVAILABLE,\n\n /** Whether the Node.js process API is available */\n IS_PROCESS_AVAILABLE,\n\n /** Whether we are running in a Node.js environment */\n IS_NODE_ENV,\n\n /** Whether the filesystem API is available */\n IS_FS_AVAILABLE,\n\n /** Whether the path API is available */\n IS_PATH_AVAILABLE,\n});\n\nconst RUNNING_LOCALLY = IS_FS_AVAILABLE && IS_PATH_AVAILABLE;\nconst dirname__ = RUNNING_LOCALLY\n ? path.dirname(path.dirname(url.fileURLToPath(import.meta.url)))\n : './';\n\n// Only used for environments with access to file system\nconst DEFAULT_CACHE_DIR = RUNNING_LOCALLY\n ? path.join(dirname__, '/.cache/')\n : null;\n\n// Set local model path, based on available APIs\nconst DEFAULT_LOCAL_MODEL_PATH = '/models/';\nconst localModelPath = RUNNING_LOCALLY\n ? path.join(dirname__, DEFAULT_LOCAL_MODEL_PATH)\n : DEFAULT_LOCAL_MODEL_PATH;\n\n/**\n * Global variable given visible to users to control execution. This provides users a simple way to configure Transformers.js.\n * @typedef {Object} TransformersEnvironment\n * @property {string} version This version of Transformers.js.\n * @property {{onnx: Partial}} backends Expose environment variables of different backends,\n * allowing users to set these variables if they want to.\n * @property {boolean} allowRemoteModels Whether to allow loading of remote files, defaults to `true`.\n * If set to `false`, it will have the same effect as setting `local_files_only=true` when loading pipelines, models, tokenizers, processors, etc.\n * @property {string} remoteHost Host URL to load models from. Defaults to the Hugging Face Hub.\n * @property {string} remotePathTemplate Path template to fill in and append to `remoteHost` when loading models.\n * @property {boolean} allowLocalModels Whether to allow loading of local files, defaults to `false` if running in-browser, and `true` otherwise.\n * If set to `false`, it will skip the local file check and try to load the model from the remote host.\n * @property {string} localModelPath Path to load local models from. Defaults to `/models/`.\n * @property {boolean} useFS Whether to use the file system to load files. By default, it is `true` if available.\n * @property {boolean} useBrowserCache Whether to use Cache API to cache models. By default, it is `true` if available.\n * @property {boolean} useFSCache Whether to use the file system to cache files. By default, it is `true` if available.\n * @property {string} cacheDir The directory to use for caching files with the file system. By default, it is `./.cache`.\n * @property {boolean} useCustomCache Whether to use a custom cache system (defined by `customCache`), defaults to `false`.\n * @property {Object} customCache The custom cache to use. Defaults to `null`. Note: this must be an object which\n * implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache\n */\n\n/** @type {TransformersEnvironment} */\nexport const env = {\n version: VERSION,\n\n /////////////////// Backends settings ///////////////////\n // NOTE: These will be populated later by the backends themselves.\n backends: {\n // onnxruntime-web/onnxruntime-node\n onnx: {},\n },\n\n /////////////////// Model settings ///////////////////\n allowRemoteModels: true,\n remoteHost: 'https://huggingface.co/',\n remotePathTemplate: '{model}/resolve/{revision}/',\n\n allowLocalModels: !IS_BROWSER_ENV,\n localModelPath: localModelPath,\n useFS: IS_FS_AVAILABLE,\n\n /////////////////// Cache settings ///////////////////\n useBrowserCache: IS_WEB_CACHE_AVAILABLE,\n\n useFSCache: IS_FS_AVAILABLE,\n cacheDir: DEFAULT_CACHE_DIR,\n\n useCustomCache: false,\n customCache: null,\n //////////////////////////////////////////////////////\n}\n\n\n/**\n * @param {Object} obj\n * @private\n */\nfunction isEmpty(obj) {\n return Object.keys(obj).length === 0;\n}\n\n","\n/**\n * @module generation/configuration_utils\n */\n\nimport { pick } from \"../utils/core.js\";\n\n/**\n * Class that holds a configuration for a generation task.\n */\nexport class GenerationConfig {\n // Parameters that control the length of the output\n /**\n * The maximum length the generated tokens can have.\n * Corresponds to the length of the input prompt + `max_new_tokens`.\n * Its effect is overridden by `max_new_tokens`, if also set.\n * @type {number}\n * @default 20\n */\n max_length = 20;\n\n /**\n * The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt.\n * @type {number}\n * @default null\n */\n max_new_tokens = null;\n\n /**\n * The minimum length of the sequence to be generated.\n * Corresponds to the length of the input prompt + `min_new_tokens`.\n * Its effect is overridden by `min_new_tokens`, if also set.\n * @type {number}\n * @default 0\n */\n min_length = 0;\n\n /**\n * The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt.\n * @type {number}\n * @default null\n */\n min_new_tokens = null;\n\n /**\n * Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:\n * - `true`, where the generation stops as soon as there are `num_beams` complete candidates;\n * - `false`, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates;\n * - `\"never\"`, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm).\n * @type {boolean|\"never\"}\n * @default false\n */\n early_stopping = false;\n\n /**\n * The maximum amount of time you allow the computation to run for in seconds.\n * Generation will still finish the current pass after allocated time has been passed.\n * @type {number}\n * @default null\n */\n max_time = null;\n\n // Parameters that control the generation strategy used\n /**\n * Whether or not to use sampling; use greedy decoding otherwise.\n * @type {boolean}\n * @default false\n */\n do_sample = false;\n\n /**\n * Number of beams for beam search. 1 means no beam search.\n * @type {number}\n * @default 1\n */\n num_beams = 1;\n\n /**\n * Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams.\n * See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.\n * @type {number}\n * @default 1\n */\n num_beam_groups = 1;\n\n /**\n * The values balance the model confidence and the degeneration penalty in contrastive search decoding.\n * @type {number}\n * @default null\n */\n penalty_alpha = null;\n\n /**\n * Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding.\n * @type {boolean}\n * @default true\n */\n use_cache = true;\n\n // Parameters for manipulation of the model output logits\n /**\n * The value used to modulate the next token probabilities.\n * @type {number}\n * @default 1.0\n */\n temperature = 1.0;\n\n /**\n * The number of highest probability vocabulary tokens to keep for top-k-filtering.\n * @type {number}\n * @default 50\n */\n top_k = 50;\n\n /**\n * If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation.\n * @type {number}\n * @default 1.0\n */\n top_p = 1.0;\n\n /**\n * Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated.\n * If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to `typical_p` or higher are kept for generation.\n * See [this paper](https://arxiv.org/pdf/2202.00666.pdf) for more details.\n * @type {number}\n * @default 1.0\n */\n typical_p = 1.0;\n\n /**\n * If set to float strictly between 0 and 1, only tokens with a conditional probability greater than `epsilon_cutoff` will be sampled.\n * In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model.\n * See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.\n * @type {number}\n * @default 0.0\n */\n epsilon_cutoff = 0.0;\n\n /**\n * Eta sampling is a hybrid of locally typical sampling and epsilon sampling.\n * If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`.\n * The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model.\n * See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.\n * @type {number}\n * @default 0.0\n */\n eta_cutoff = 0.0;\n\n /**\n * This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time.\n * Note that `diversity_penalty` is only effective if `group beam search` is enabled.\n * @type {number}\n * @default 0.0\n */\n diversity_penalty = 0.0;\n\n /**\n * The parameter for repetition penalty. 1.0 means no penalty.\n * See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.\n * @type {number}\n * @default 1.0\n */\n repetition_penalty = 1.0;\n\n /**\n * The paramater for encoder_repetition_penalty.\n * An exponential penalty on sequences that are not in the original input.\n * 1.0 means no penalty.\n * @type {number}\n * @default 1.0\n */\n encoder_repetition_penalty = 1.0;\n\n /**\n * Exponential penalty to the length that is used with beam-based generation.\n * It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence.\n * Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences.\n * @type {number}\n * @default 1.0\n */\n length_penalty = 1.0;\n\n /**\n * If set to int > 0, all ngrams of that size can only occur once.\n * @type {number}\n * @default 0\n */\n no_repeat_ngram_size = 0;\n\n /**\n * List of token ids that are not allowed to be generated.\n * In order to get the token ids of the words that should not appear in the generated text, use\n * `tokenizer(bad_words, { add_prefix_space: true, add_special_tokens: false }).input_ids`.\n * @type {number[][]}\n * @default null\n */\n bad_words_ids = null;\n\n /**\n * List of token ids that must be generated.\n * If given a `number[][]`, this is treated as a simple list of words that must be included, the opposite to `bad_words_ids`.\n * If given `number[][][]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one can allow different forms of each word.\n * @type {number[][]|number[][][]}\n * @default null\n */\n force_words_ids = null;\n\n /**\n * Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones).\n * It's highly recommended to set this flag to `true` as the search algorithms suppose the score logits are normalized but some logit processors or warpers break the normalization.\n * @type {boolean}\n * @default false\n */\n renormalize_logits = false;\n\n /**\n * Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by `Constraint` objects, in the most sensible way possible.\n * @type {Object[]}\n * @default null\n */\n constraints = null;\n\n /**\n * The id of the token to force as the first generated token after the `decoder_start_token_id`.\n * Useful for multilingual models like mBART where the first generated token needs to be the target language token.\n * @type {number}\n * @default null\n */\n forced_bos_token_id = null;\n\n /**\n * The id of the token to force as the last generated token when `max_length` is reached.\n * Optionally, use a list to set multiple *end-of-sequence* tokens.\n * @type {number|number[]}\n * @default null\n */\n forced_eos_token_id = null;\n\n /**\n * Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash. Note that using `remove_invalid_values` can slow down generation.\n * @type {boolean}\n */\n remove_invalid_values = false;\n\n /**\n * This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been generated.\n * The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty starts and `decay_factor` represents the factor of exponential decay.\n * @type {[number, number]}\n * @default null\n */\n exponential_decay_length_penalty = null;\n\n /**\n * A list of tokens that will be suppressed at generation.\n * The `SuppressTokens` logit processor will set their log probs to `-inf` so that they are not sampled.\n * @type {number[]}\n * @default null\n */\n suppress_tokens = null;\n\n /**\n * A list of tokens that will be suppressed at the beginning of the generation.\n * The `SuppressBeginTokens` logit processor will set their log probs to `-inf` so that they are not sampled.\n * @type {number[]}\n * @default null\n */\n begin_suppress_tokens = null;\n\n /**\n * A list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling.\n * For example, `[[1, 123]]` means the second generated token will always be a token of index 123.\n * @type {[number, number][]}\n * @default null\n */\n forced_decoder_ids = null;\n\n /**\n * The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.\n * Higher guidance scale encourages the model to generate samples that are more closely linked to the input\n * prompt, usually at the expense of poorer quality.\n * @type {number}\n * @default null\n */\n guidance_scale = null;\n\n // Parameters that define the output variables of `generate`\n /**\n * The number of independently computed returned sequences for each element in the batch.\n * @type {number}\n * @default 1\n */\n num_return_sequences = 1;\n\n /**\n * Whether or not to return the attentions tensors of all attention layers.\n * See `attentions` under returned tensors for more details.\n * @type {boolean}\n * @default false\n */\n output_attentions = false;\n\n /**\n * Whether or not to return the hidden states of all layers.\n * See `hidden_states` under returned tensors for more details.\n * @type {boolean}\n * @default false\n */\n output_hidden_states = false;\n\n /**\n * Whether or not to return the prediction scores.\n * See `scores` under returned tensors for more details.\n * @type {boolean}\n * @default false\n */\n output_scores = false;\n\n /**\n * Whether or not to return a `ModelOutput` instead of a plain tuple.\n * @type {boolean}\n * @default false\n */\n return_dict_in_generate = false;\n\n // Special tokens that can be used at generation time\n /**\n * The id of the *padding* token.\n * @type {number}\n * @default null\n */\n pad_token_id = null;\n\n /**\n * The id of the *beginning-of-sequence* token.\n * @type {number}\n * @default null\n */\n bos_token_id = null;\n\n /**\n * The id of the *end-of-sequence* token.\n * Optionally, use a list to set multiple *end-of-sequence* tokens.\n * @type {number|number[]}\n * @default null\n */\n eos_token_id = null;\n\n // Generation parameters exclusive to encoder-decoder models\n /**\n * If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`.\n * @type {number}\n * @default 0\n */\n encoder_no_repeat_ngram_size = 0;\n\n /**\n * If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token.\n * @type {number}\n * @default null\n */\n decoder_start_token_id = null;\n\n // Wild card\n /**\n * Additional generation kwargs will be forwarded to the `generate` function of the model.\n * Kwargs that are not present in `generate`'s signature will be used in the model forward pass.\n * @type {Object}\n * @default {}\n */\n generation_kwargs = {};\n\n /**\n * \n * @param {GenerationConfig|import('../configs.js').PretrainedConfig} config \n */\n constructor(config) {\n Object.assign(this, pick(config, Object.getOwnPropertyNames(this)));\n }\n}\n\n","\n/**\n * @module generation/logits_process\n */\n\nimport { Callable } from \"../utils/generic.js\";\nimport { Tensor } from \"../utils/tensor.js\";\n\nimport { max, log_softmax } from \"../utils/maths.js\";\n\n/**\n * Abstract base class for all logit processors that can be applied during generation.\n */\nexport class LogitsProcessor extends Callable {\n /**\n * Apply the processor to the input logits.\n *\n * @abstract\n * @param {bigint[][]} input_ids The input ids.\n * @param {Tensor} logits The logits to process.\n * @throws {Error} Throws an error if `_call` is not implemented in the subclass.\n */\n _call(input_ids, logits) {\n throw Error(\"`_call` should be implemented in a subclass\")\n }\n}\n\n\n/**\n * Abstract base class for all logit warpers that can be applied during generation with multinomial sampling.\n */\nexport class LogitsWarper extends Callable {\n /**\n * Apply the processor to the input logits.\n *\n * @abstract\n * @param {bigint[][]} input_ids The input ids.\n * @param {Tensor} logits The logits to process.\n * @throws {Error} Throws an error if `_call` is not implemented in the subclass.\n */\n _call(input_ids, logits) {\n throw Error(\"`_call` should be implemented in a subclass\")\n }\n}\n\n\n/**\n * A class representing a list of logits processors. A logits processor is a function that modifies the logits\n * output of a language model. This class provides methods for adding new processors and applying all processors to a\n * batch of logits.\n */\nexport class LogitsProcessorList extends Callable {\n /**\n * Constructs a new instance of `LogitsProcessorList`.\n */\n constructor() {\n super();\n this.processors = [];\n }\n\n /**\n * Adds a new logits processor to the list.\n *\n * @param {LogitsProcessor} item The logits processor function to add.\n */\n push(item) {\n this.processors.push(item);\n }\n\n /**\n * Adds multiple logits processors to the list.\n *\n * @param {LogitsProcessor[]} items The logits processor functions to add.\n */\n extend(items) {\n this.processors.push(...items);\n }\n\n /**\n * Applies all logits processors in the list to a batch of logits, modifying them in-place.\n *\n * @param {bigint[][]} input_ids The input IDs for the language model.\n * @param {Tensor} logits\n */\n _call(input_ids, logits) {\n let toReturn = logits;\n // NOTE: Most processors modify logits inplace\n for (const processor of this.processors) {\n toReturn = processor(input_ids, toReturn);\n }\n return toReturn;\n }\n\n [Symbol.iterator]() {\n return this.processors.values();\n }\n}\n\n// DEPRECATED: https://github.com/huggingface/transformers/pull/29485\n// /**\n// * A logits processor that forces a specific token to be generated by the decoder.\n// */\n// export class ForceTokensLogitsProcessor extends LogitsProcessor {\n// /**\n// * Constructs a new instance of `ForceTokensLogitsProcessor`.\n// * \n// * @param {[number, number][]} forced_decoder_ids The ids of tokens that should be forced.\n// */\n// constructor(forced_decoder_ids) {\n// super();\n// // TODO: convert to `new Map(forced_decoder_ids)`\n// this.force_token_map = Object.fromEntries(forced_decoder_ids ?? []);\n// }\n\n// /**\n// * Apply the processor to the input logits.\n// *\n// * @param {bigint[][]} input_ids The input ids.\n// * @param {Tensor} logits The logits to process.\n// * @returns {Tensor} The processed logits.\n// */\n// _call(input_ids, logits) {\n// console.log('this.force_token_map', this.force_token_map)\n// console.log('call ForceTokensLogitsProcessor', input_ids, logits)\n// console.log('input_ids.length', input_ids.length)\n// let map = this.force_token_map[input_ids.length];\n// if (map) { // There exists a mapping\n// logits.data.fill(-Infinity)\n// logits.data[map] = 0;\n// }\n// console.log('map', map)\n// // throw Error(\"Not implemented\")\n// return logits;\n// }\n// }\n\n/**\n * A LogitsProcessor that forces a BOS token at the beginning of the generated sequence.\n */\nexport class ForcedBOSTokenLogitsProcessor extends LogitsProcessor {\n /**\n * Create a ForcedBOSTokenLogitsProcessor.\n * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced.\n */\n constructor(bos_token_id) {\n super();\n this.bos_token_id = bos_token_id;\n }\n\n /**\n * Apply the BOS token forcing to the logits.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The logits with BOS token forcing.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n if (input_ids[i].length === 1) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n batch_logits_data.fill(-Infinity);\n batch_logits_data[this.bos_token_id] = 0;\n }\n }\n return logits;\n }\n}\n\n/**\n * A logits processor that enforces the specified token as the last generated token when `max_length` is reached.\n */\nexport class ForcedEOSTokenLogitsProcessor extends LogitsProcessor {\n /**\n * Create a ForcedEOSTokenLogitsProcessor.\n * @param {number} max_length The maximum length of the sequence to be generated.\n * @param {number|number[]} eos_token_id The id(s) of the *end-of-sequence* token.\n */\n constructor(max_length, eos_token_id) {\n super();\n this.max_length = max_length;\n this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];\n }\n\n /**\n * Apply the processor to input_ids and logits.\n * \n * @param {bigint[][]} input_ids The input ids.\n * @param {Tensor} logits The logits tensor.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n if (input_ids[i].length === this.max_length - 1) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n batch_logits_data.fill(-Infinity);\n for (const eos_token of this.eos_token_id) {\n batch_logits_data[eos_token] = 0;\n }\n }\n }\n return logits;\n }\n}\n\n/**\n * A LogitsProcessor that suppresses a list of tokens as soon as the `generate` function starts\n * generating using `begin_index` tokens. This should ensure that the tokens defined by\n * `begin_suppress_tokens` at not sampled at the begining of the generation.\n */\nexport class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor {\n /**\n * Create a SuppressTokensAtBeginLogitsProcessor.\n * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress.\n * @param {number} begin_index The number of tokens to generate before suppressing tokens.\n */\n constructor(begin_suppress_tokens, begin_index) {\n super();\n this.begin_suppress_tokens = begin_suppress_tokens;\n this.begin_index = begin_index;\n }\n\n /**\n * Apply the BOS token forcing to the logits.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The logits with BOS token forcing.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n if (input_ids[i].length === this.begin_index) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n for (const token_id of this.begin_suppress_tokens) {\n batch_logits_data[token_id] = -Infinity;\n }\n }\n }\n return logits;\n }\n}\n\n/**\n * A LogitsProcessor that handles adding timestamps to generated text.\n */\nexport class WhisperTimeStampLogitsProcessor extends LogitsProcessor {\n /**\n * Constructs a new WhisperTimeStampLogitsProcessor.\n * @param {import('../models/whisper/generation_whisper.js').WhisperGenerationConfig} generate_config The config object passed to the `generate()` method of a transformer model.\n * @param {number[]} init_tokens The initial tokens of the input sequence.\n */\n constructor(generate_config, init_tokens) {\n super();\n this.eos_token_id =\n Array.isArray(generate_config.eos_token_id)\n ? generate_config.eos_token_id[0]\n : generate_config.eos_token_id;\n\n this.no_timestamps_token_id = generate_config.no_timestamps_token_id;\n this.timestamp_begin = this.no_timestamps_token_id + 1;\n\n this.begin_index = init_tokens.length;\n if (init_tokens.at(-1) === this.no_timestamps_token_id) {\n this.begin_index -= 1;\n }\n this.max_initial_timestamp_index = generate_config.max_initial_timestamp_index;\n }\n\n /**\n * Modify the logits to handle timestamp tokens.\n * @param {bigint[][]} input_ids The input sequence of tokens.\n * @param {Tensor} logits The logits output by the model.\n * @returns {Tensor} The modified logits.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n\n // suppress <|notimestamps|> which is handled by without_timestamps\n batch_logits_data[this.no_timestamps_token_id] = -Infinity;\n\n if (input_ids[i].length === this.begin_index - 1) {\n batch_logits_data.fill(-Infinity);\n batch_logits_data[this.timestamp_begin] = 0;\n continue;\n }\n\n // timestamps have to appear in pairs, except directly before eos_token; mask logits accordingly\n const seq = input_ids[i].slice(this.begin_index);\n const last_was_timestamp = seq.length >= 1 && seq[seq.length - 1] >= this.timestamp_begin;\n const penultimate_was_timestamp = seq.length < 2 || seq[seq.length - 2] >= this.timestamp_begin;\n\n if (last_was_timestamp) {\n if (penultimate_was_timestamp) { // has to be non-timestamp\n batch_logits_data.subarray(this.timestamp_begin).fill(-Infinity);\n } else { // cannot be normal text tokens\n batch_logits_data.subarray(0, this.eos_token_id).fill(-Infinity);\n }\n }\n\n // apply the `max_initial_timestamp` option\n if (input_ids[i].length === this.begin_index && this.max_initial_timestamp_index !== null) {\n const last_allowed = this.timestamp_begin + this.max_initial_timestamp_index;\n batch_logits_data.subarray(last_allowed + 1).fill(-Infinity);\n }\n\n // if sum of probability over timestamps is above any other token, sample timestamp\n const logprobs = log_softmax(batch_logits_data);\n const timestamp_logprob = Math.log(logprobs.subarray(this.timestamp_begin).map(Math.exp).reduce((a, b) => a + b));\n const max_text_token_logprob = max(logprobs.subarray(0, this.timestamp_begin))[0];\n\n if (timestamp_logprob > max_text_token_logprob) {\n batch_logits_data.subarray(0, this.timestamp_begin).fill(-Infinity);\n }\n }\n\n return logits;\n }\n}\n\n/**\n * A logits processor that disallows ngrams of a certain size to be repeated.\n */\nexport class NoRepeatNGramLogitsProcessor extends LogitsProcessor {\n /**\n * Create a NoRepeatNGramLogitsProcessor.\n * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once.\n */\n constructor(no_repeat_ngram_size) {\n super();\n this.no_repeat_ngram_size = no_repeat_ngram_size;\n }\n\n /**\n * Generate n-grams from a sequence of token ids.\n * @param {bigint[]} prevInputIds List of previous input ids\n * @returns {Map} Map of generated n-grams\n */\n getNgrams(prevInputIds) {\n const curLen = prevInputIds.length;\n\n /**@type {number[][]} */\n const ngrams = [];\n for (let j = 0; j < curLen + 1 - this.no_repeat_ngram_size; ++j) {\n const ngram = [];\n for (let k = 0; k < this.no_repeat_ngram_size; ++k) {\n ngram.push(prevInputIds[j + k]);\n }\n ngrams.push(ngram.map(Number));\n }\n\n /** @type {Map} */\n const generatedNgram = new Map();\n for (const ngram of ngrams) {\n const prevNgram = ngram.slice(0, ngram.length - 1);\n const prevNgramKey = JSON.stringify(prevNgram);\n const prevNgramValue = generatedNgram.get(prevNgramKey) ?? [];\n prevNgramValue.push(ngram[ngram.length - 1]);\n generatedNgram.set(prevNgramKey, prevNgramValue);\n }\n return generatedNgram;\n }\n\n /**\n * Generate n-grams from a sequence of token ids.\n * @param {Map} bannedNgrams Map of banned n-grams\n * @param {bigint[]} prevInputIds List of previous input ids\n * @returns {number[]} Map of generated n-grams\n */\n getGeneratedNgrams(bannedNgrams, prevInputIds) {\n const ngramIdx = prevInputIds.slice(prevInputIds.length + 1 - this.no_repeat_ngram_size, prevInputIds.length);\n const banned = bannedNgrams.get(JSON.stringify(ngramIdx.map(Number))) ?? [];\n return banned;\n }\n\n /**\n * Calculate banned n-gram tokens\n * @param {bigint[]} prevInputIds List of previous input ids\n * @returns {number[]} Map of generated n-grams\n */\n calcBannedNgramTokens(prevInputIds) {\n const bannedTokens = [];\n if (prevInputIds.length + 1 < this.no_repeat_ngram_size) {\n // return no banned tokens if we haven't generated no_repeat_ngram_size tokens yet\n return bannedTokens;\n\n } else {\n const generatedNgrams = this.getNgrams(prevInputIds);\n const bannedTokens = this.getGeneratedNgrams(generatedNgrams, prevInputIds);\n return bannedTokens;\n }\n }\n\n /**\n * Apply the no-repeat-ngram processor to the logits.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The logits with no-repeat-ngram processing.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n const bannedTokens = this.calcBannedNgramTokens(input_ids[i]);\n for (const token of bannedTokens) {\n batch_logits_data[token] = -Infinity;\n }\n }\n return logits;\n }\n}\n\n/**\n * A logits processor that penalises repeated output tokens.\n */\nexport class RepetitionPenaltyLogitsProcessor extends LogitsProcessor {\n /**\n * Create a RepetitionPenaltyLogitsProcessor.\n * @param {number} penalty The penalty to apply for repeated tokens.\n */\n constructor(penalty) {\n super();\n this.penalty = penalty;\n }\n\n /**\n * Apply the repetition penalty to the logits.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The logits with repetition penalty processing.\n */\n _call(input_ids, logits) {\n // Modify the logits corresponding to each element in `input_ids`.\n // As a consequence, the logits corresponding to tokens that appear\n // many times in the output will be penalised more.\n\n for (let i = 0; i < input_ids.length; ++i) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n for (const input_id of input_ids[i]) {\n const token = Number(input_id);\n if (batch_logits_data[token] < 0) {\n batch_logits_data[token] *= this.penalty;\n } else {\n batch_logits_data[token] /= this.penalty;\n }\n }\n }\n\n return logits\n }\n}\n\n/**\n * A logits processor that enforces a minimum number of tokens.\n */\nexport class MinLengthLogitsProcessor extends LogitsProcessor {\n /**\n * Create a MinLengthLogitsProcessor.\n * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity.\n * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.\n */\n constructor(min_length, eos_token_id) {\n super();\n this.min_length = min_length;\n this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];\n }\n\n /**\n * Apply logit processor.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n if (input_ids[i].length < this.min_length) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n\n for (const eos_token of this.eos_token_id) {\n batch_logits_data[eos_token] = -Infinity;\n }\n }\n }\n\n return logits\n }\n}\n\n/**\n * A logits processor that enforces a minimum number of new tokens.\n */\nexport class MinNewTokensLengthLogitsProcessor extends LogitsProcessor {\n /**\n * Create a MinNewTokensLengthLogitsProcessor.\n * @param {number} prompt_length_to_skip The input tokens length.\n * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity.\n * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.\n */\n constructor(prompt_length_to_skip, min_new_tokens, eos_token_id) {\n super();\n this.prompt_length_to_skip = prompt_length_to_skip;\n this.min_new_tokens = min_new_tokens;\n this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];\n }\n\n /**\n * Apply logit processor.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n const new_tokens_length = input_ids[i].length - this.prompt_length_to_skip;\n if (new_tokens_length < this.min_new_tokens) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n\n for (const eos_token of this.eos_token_id) {\n batch_logits_data[eos_token] = -Infinity;\n }\n }\n }\n return logits\n }\n}\n\nexport class NoBadWordsLogitsProcessor extends LogitsProcessor {\n /**\n * Create a `NoBadWordsLogitsProcessor`.\n * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated.\n * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.\n */\n constructor(bad_words_ids, eos_token_id) {\n super();\n this.bad_words_ids = bad_words_ids;\n this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];\n }\n\n /**\n * Apply logit processor.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n const ids = input_ids[i];\n for (const bad_word_ids of this.bad_words_ids) {\n // Whether to modify the logits of the last token in the bad word id sequence\n let mark = true;\n\n // For each bad word in the list, if the current sequence of input ids ends with this sequence (excluding the last),\n // then we set the logits of the last bad word id to -Infinity.\n for (let j = 1; j <= bad_word_ids.length - 1 && bad_word_ids.length < ids.length; ++j) {\n\n // NOTE: We use != instead of !== to compare bigint and number\n // @ts-ignore\n if (bad_word_ids.at(-j - 1) != ids.at(-j)) {\n // We have found a mismatch\n mark = false;\n break;\n }\n }\n if (mark) {\n batch_logits_data[bad_word_ids.at(-1)] = -Infinity;\n }\n }\n }\n return logits\n }\n}\n\n/**\n * [`LogitsProcessor`] for classifier free guidance (CFG). The scores are split over the batch dimension,\n * where the first half correspond to the conditional logits (predicted from the input prompt) and the second half\n * correspond to the unconditional logits (predicted from an empty or 'null' prompt). The processor computes a\n * weighted average across the conditional and unconditional logits, parameterised by the `guidance_scale`.\n * \n * See [the paper](https://arxiv.org/abs/2306.05284) for more information.\n */\nexport class ClassifierFreeGuidanceLogitsProcessor extends LogitsProcessor {\n\n /**\n * Create a `ClassifierFreeGuidanceLogitsProcessor`.\n * @param {number} guidance_scale The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.\n * Higher guidance scale encourages the model to generate samples that are more closely linked to the input\n * prompt, usually at the expense of poorer quality.\n */\n constructor(guidance_scale) {\n super();\n if (guidance_scale <= 1) {\n throw new Error(\n `Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${guidance_scale}.`\n )\n }\n this.guidance_scale = guidance_scale;\n }\n\n /**\n * Apply logit processor.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n if (logits.dims[0] !== 2 * input_ids.length) {\n throw new Error(\n `Logits should have twice the batch size of the input ids, the first half of batches corresponding to ` +\n `the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got ` +\n `batch size ${logits.dims[0]} for the logits and ${input_ids.length} for the input ids.`\n )\n }\n\n const unguided_bsz = input_ids.length;\n const cond_logits = logits.slice([0, unguided_bsz], null);\n const uncond_logits = logits.slice([unguided_bsz, logits.dims[0]], null);\n\n // Merge into uncond_logits (to save memory). This is equivalent to the following:\n // scores = uncond_logits + (cond_logits - uncond_logits) * guidance_scale\n for (let i = 0; i < uncond_logits.data.length; ++i) {\n uncond_logits.data[i] += (cond_logits.data[i] - uncond_logits.data[i]) * this.guidance_scale;\n }\n\n return uncond_logits;\n }\n}\n\n/**\n * [`LogitsWarper`] for temperature (exponential scaling output probability distribution), which effectively means\n * that it can control the randomness of the predicted tokens. Often used together with [`TopPLogitsWarper`] and [`TopKLogitsWarper`].\n */\nexport class TemperatureLogitsWarper extends LogitsWarper {\n /**\n * Create a `TemperatureLogitsWarper`.\n * @param {number} temperature Strictly positive float value used to modulate the logits distribution.\n * A value smaller than `1` decreases randomness (and vice versa), with `0` being equivalent to shifting\n * all probability mass to the most likely token.\n */\n constructor(temperature) {\n super();\n\n if (typeof temperature !== 'number' || temperature <= 0) {\n let errorMessage =\n `\\`temperature\\` (=${temperature}) must be a strictly positive float, otherwise your next token scores will be invalid.`;\n\n if (temperature === 0) {\n errorMessage += \" If you're looking for greedy decoding strategies, set `do_sample=false`.\"\n }\n }\n this.temperature = temperature;\n }\n\n /**\n * Apply logit warper.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n const batch_logits_data = /** @type {Float32Array} */(logits.data);\n for (let i = 0; i < batch_logits_data.length; ++i) {\n batch_logits_data[i] /= this.temperature;\n }\n return logits;\n }\n}\n\n/**\n * [`LogitsWarper`] that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off.\n * Often used together with [`TemperatureLogitsWarper`] and [`TopKLogitsWarper`].\n */\nexport class TopPLogitsWarper extends LogitsWarper {\n /**\n * Create a `TopPLogitsWarper`.\n * @param {number} top_p If set to < 1, only the smallest set of most probable tokens with\n * probabilities that add up to `top_p` or higher are kept for generation.\n * @param {Object} options Additional options for the top-p sampling.\n * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value.\n * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered.\n */\n constructor(top_p, {\n filter_value = -Infinity,\n min_tokens_to_keep = 1,\n } = {}) {\n super();\n if (top_p < 0 || top_p > 1.0) {\n throw new Error(`\\`top_p\\` must be a float > 0 and < 1, but is ${top_p}`)\n }\n if (!Number.isInteger(min_tokens_to_keep) || min_tokens_to_keep < 1) {\n throw new Error(`\\`min_tokens_to_keep\\` must be a positive integer, but is ${min_tokens_to_keep}`)\n }\n\n this.top_p = top_p\n this.filter_value = filter_value\n this.min_tokens_to_keep = min_tokens_to_keep\n }\n}\n\n/**\n * [`LogitsWarper`] that performs top-k, i.e. restricting to the k highest probability elements.\n * Often used together with [`TemperatureLogitsWarper`] and [`TopPLogitsWarper`].\n */\nexport class TopKLogitsWarper extends LogitsWarper {\n /**\n * Create a `TopKLogitsWarper`.\n * @param {number} top_k If set to > 0, only the top `top_k` tokens are kept for generation.\n * @param {Object} options Additional options for the top-k sampling.\n * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value.\n * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered.\n */\n constructor(top_k, {\n filter_value = -Infinity,\n min_tokens_to_keep = 1,\n } = {}) {\n super();\n if (!Number.isInteger(top_k) || top_k < 0) {\n throw new Error(`\\`top_k\\` must be a positive integer, but is ${top_k}`)\n }\n\n this.top_k = Math.max(top_k, min_tokens_to_keep)\n this.filter_value = filter_value\n }\n}","\n/**\n * @module generation/logits_sampler\n */\n\nimport { Callable } from \"../utils/generic.js\";\nimport { Tensor, topk } from \"../utils/tensor.js\";\n\nimport {\n max,\n softmax,\n} from '../utils/maths.js';\nimport { GenerationConfig } from '../generation/configuration_utils.js';\n\n/**\n * Sampler is a base class for all sampling methods used for text generation.\n */\nexport class LogitsSampler extends Callable {\n /**\n * Creates a new Sampler object with the specified generation config.\n * @param {GenerationConfig} generation_config The generation config.\n */\n constructor(generation_config) {\n super();\n this.generation_config = generation_config;\n }\n\n /**\n * Executes the sampler, using the specified logits.\n * @param {Tensor} logits\n * @returns {Promise<[bigint, number][]>}\n */\n async _call(logits) {\n // Sample from logits, of dims [batch, sequence_length, vocab_size].\n // If index is specified, sample from [batch, index, vocab_size].\n return this.sample(logits);\n }\n\n /**\n * Abstract method for sampling the logits.\n * @param {Tensor} logits\n * @throws {Error} If not implemented in subclass.\n * @returns {Promise<[bigint, number][]>}\n */\n async sample(logits) {\n throw Error(\"sample should be implemented in subclasses.\")\n }\n\n /**\n * Returns the specified logits as an array, with temperature applied.\n * @param {Tensor} logits\n * @param {number} index\n * @returns {Float32Array}\n */\n getLogits(logits, index) {\n let vocabSize = logits.dims.at(-1);\n\n let logs = /** @type {Float32Array} */(logits.data);\n\n if (index === -1) {\n logs = logs.slice(-vocabSize);\n } else {\n let startIndex = index * vocabSize;\n logs = logs.slice(startIndex, startIndex + vocabSize);\n }\n return logs;\n }\n\n /**\n * Selects an item randomly based on the specified probabilities.\n * @param {import(\"../transformers.js\").DataArray} probabilities An array of probabilities to use for selection.\n * @returns {number} The index of the selected item.\n */\n randomSelect(probabilities) {\n // Return index of chosen item\n let sumProbabilities = 0;\n for (let i = 0; i < probabilities.length; ++i) {\n sumProbabilities += probabilities[i];\n }\n\n let r = Math.random() * sumProbabilities;\n for (let i = 0; i < probabilities.length; ++i) {\n r -= probabilities[i];\n if (r <= 0) {\n return i;\n }\n }\n return 0; // return first (most probable) as a fallback\n }\n\n /**\n * Returns a Sampler object based on the specified options.\n * @param {GenerationConfig} generation_config An object containing options for the sampler.\n * @returns {LogitsSampler} A Sampler object.\n */\n static getSampler(generation_config) {\n // - *greedy decoding*: `num_beams=1` and `do_sample=False`\n // - *contrastive search*: `penalty_alpha>0` and `top_k>1`\n // - *multinomial sampling*: `num_beams=1` and `do_sample=True`\n // - *beam-search decoding*: `num_beams>1` and `do_sample=False`\n // - *beam-search multinomial sampling*: `num_beams>1` and `do_sample=True`\n // - *diverse beam-search decoding*: `num_beams>1` and `num_beam_groups>1`\n // - *constrained beam-search decoding*: `constraints!=None` or `force_words_ids!=None`\n\n // NOTE: beam search is implemented directly into the generation function\n if (generation_config.do_sample) {\n return new MultinomialSampler(generation_config);\n\n } else if (generation_config.num_beams > 1) {\n return new BeamSearchSampler(generation_config);\n\n } else {\n if (generation_config.num_return_sequences > 1) {\n throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${generation_config.num_return_sequences}.`)\n }\n return new GreedySampler(generation_config);\n }\n }\n}\n\n/**\n * Class representing a Greedy Sampler.\n */\nclass GreedySampler extends LogitsSampler {\n /**\n * Sample the maximum probability of a given logits tensor.\n * @param {Tensor} logits\n * @returns {Promise<[bigint, number][]>} An array with a single tuple, containing the index of the maximum value and a meaningless score (since this is a greedy search).\n */\n async sample(logits) {\n // NOTE: no need to do log_softmax here since we only take the maximum\n const argmax = max(logits.data)[1];\n\n // Note: score is meaningless in this context, since we are performing\n // greedy search (p = 1 => log(p) = 0)\n return [\n [BigInt(argmax), 0]\n ];\n }\n}\n\n/**\n * Class representing a MultinomialSampler.\n */\nclass MultinomialSampler extends LogitsSampler {\n\n /**\n * Sample from the logits.\n * @param {Tensor} logits\n * @returns {Promise<[bigint, number][]>}\n */\n async sample(logits) {\n let k = logits.dims.at(-1); // defaults to vocab size\n if (this.generation_config.top_k > 0) {\n k = Math.min(this.generation_config.top_k, k);\n }\n\n // Get top k tokens\n const [v, i] = await topk(logits, k);\n\n // Compute softmax over logits\n const probabilities = softmax(/** @type {Float32Array} */(v.data));\n\n return Array.from({ length: this.generation_config.num_beams }, () => {\n const sampledIndex = this.randomSelect(probabilities);\n return [\n i.data[sampledIndex], // token id\n Math.log(probabilities[sampledIndex]), // score\n ];\n });\n }\n}\n\n\n/**\n * Class representing a BeamSearchSampler.\n */\nclass BeamSearchSampler extends LogitsSampler {\n\n /**\n * Sample from the logits.\n * @param {Tensor} logits\n * @returns {Promise<[bigint, number][]>}\n */\n async sample(logits) {\n let k = logits.dims.at(-1); // defaults to vocab size\n if (this.generation_config.top_k > 0) {\n k = Math.min(this.generation_config.top_k, k);\n }\n\n // Get top k tokens\n const [v, i] = await topk(logits, k);\n\n // Compute softmax over logits\n const probabilities = softmax(/** @type {Float32Array} */(v.data));\n\n return Array.from({ length: this.generation_config.num_beams }, (_, x) => {\n return [\n i.data[x], // token id\n Math.log(probabilities[x]), // score\n ];\n });\n }\n}\n","\n/**\n * @module generation/stopping_criteria\n */\n\nimport { Callable } from \"../utils/generic.js\";\n\n// NOTE:\n// Stopping Criteria returns a list of `batch_size` booleans, indicating whether each sequence in the batch should be stopped.\n\n/**\n * Abstract base class for all stopping criteria that can be applied during generation.\n */\nexport class StoppingCriteria extends Callable {\n /**\n * \n * @param {number[][]} input_ids (`number[][]` of shape `(batch_size, sequence_length)`):\n * Indices of input sequence tokens in the vocabulary.\n * @param {number[][]} scores scores (`number[][]` of shape `(batch_size, config.vocab_size)`):\n * Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax\n * or scores for each vocabulary token after SoftMax.\n * @returns {boolean[]} A list of booleans indicating whether each sequence should be stopped.\n */\n _call(input_ids, scores) {\n throw Error(\"StoppingCriteria needs to be subclassed\");\n }\n}\n/**\n */\nexport class StoppingCriteriaList extends Callable {\n /**\n * Constructs a new instance of `StoppingCriteriaList`.\n */\n constructor() {\n super();\n this.criteria = [];\n }\n\n /**\n * Adds a new stopping criterion to the list.\n *\n * @param {StoppingCriteria} item The stopping criterion to add.\n */\n push(item) {\n this.criteria.push(item);\n }\n\n /**\n * Adds multiple stopping criteria to the list.\n *\n * @param {StoppingCriteria|StoppingCriteriaList|StoppingCriteria[]} items The stopping criteria to add.\n */\n extend(items) {\n if (items instanceof StoppingCriteriaList) {\n items = items.criteria;\n } else if (items instanceof StoppingCriteria) {\n items = [items];\n }\n this.criteria.push(...items);\n }\n\n _call(input_ids, scores) {\n const is_done = new Array(input_ids.length).fill(false);\n for (const criterion of this.criteria) {\n const criterion_done = criterion(input_ids, scores);\n for (let i = 0; i < is_done.length; ++i) {\n is_done[i] ||= criterion_done[i];\n }\n }\n return is_done;\n }\n\n [Symbol.iterator]() {\n return this.criteria.values();\n }\n}\n\n/**\n * This class can be used to stop generation whenever the full generated number of tokens exceeds `max_length`.\n * Keep in mind for decoder-only type of transformers, this will include the initial prompted tokens.\n */\nexport class MaxLengthCriteria extends StoppingCriteria {\n\n /**\n * \n * @param {number} max_length The maximum length that the output sequence can have in number of tokens.\n * @param {number} [max_position_embeddings=null] The maximum model length, as defined by the model's `config.max_position_embeddings` attribute.\n */\n constructor(max_length, max_position_embeddings = null) {\n super();\n this.max_length = max_length;\n this.max_position_embeddings = max_position_embeddings;\n }\n\n _call(input_ids) {\n return input_ids.map(ids => ids.length >= this.max_length);\n }\n}\n\n// TODO: add MaxTimeCriteria\n\n/**\n * This class can be used to stop generation whenever the \"end-of-sequence\" token is generated.\n * By default, it uses the `model.generation_config.eos_token_id`.\n */\nexport class EosTokenCriteria extends StoppingCriteria {\n\n /**\n * \n * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token.\n * Optionally, use a list to set multiple *end-of-sequence* tokens.\n */\n constructor(eos_token_id) {\n super();\n if (!Array.isArray(eos_token_id)) {\n eos_token_id = [eos_token_id];\n }\n this.eos_token_id = eos_token_id;\n }\n\n /**\n * \n * @param {number[][]} input_ids \n * @param {number[][]} scores \n * @returns {boolean[]}\n */\n _call(input_ids, scores) {\n return input_ids.map(ids => {\n const last = ids.at(-1);\n // NOTE: We use == instead of === to allow for number/bigint comparison\n return this.eos_token_id.some(eos_id => last == eos_id);\n });\n }\n}\n\n/**\n * This class can be used to stop generation whenever the user interrupts the process.\n */\nexport class InterruptableStoppingCriteria extends StoppingCriteria {\n constructor() {\n super();\n this.interrupted = false;\n }\n\n interrupt() {\n this.interrupted = true;\n }\n\n reset() {\n this.interrupted = false;\n }\n\n _call(input_ids, scores) {\n return new Array(input_ids.length).fill(this.interrupted);\n }\n}\n","\n/**\n * @module generation/streamers\n */\n\nimport { mergeArrays } from '../utils/core.js';\nimport { is_chinese_char } from '../tokenizers.js';\nimport { apis } from '../env.js';\n\nexport class BaseStreamer {\n /**\n * Function that is called by `.generate()` to push new tokens\n * @param {bigint[][]} value \n */\n put(value) {\n throw Error('Not implemented');\n }\n\n /**\n * Function that is called by `.generate()` to signal the end of generation\n */\n end() {\n throw Error('Not implemented');\n }\n}\n\nconst stdout_write = apis.IS_PROCESS_AVAILABLE\n ? x => process.stdout.write(x)\n : x => console.log(x);\n\n/**\n * Simple text streamer that prints the token(s) to stdout as soon as entire words are formed.\n */\nexport class TextStreamer extends BaseStreamer {\n /**\n * \n * @param {import('../tokenizers.js').PreTrainedTokenizer} tokenizer \n */\n constructor(tokenizer, {\n skip_prompt = false,\n callback_function = null,\n token_callback_function = null,\n decode_kwargs = {},\n ...kwargs\n } = {}) {\n super();\n this.tokenizer = tokenizer;\n this.skip_prompt = skip_prompt;\n this.callback_function = callback_function ?? stdout_write;\n this.token_callback_function = token_callback_function;\n this.decode_kwargs = { ...decode_kwargs, ...kwargs };\n\n // variables used in the streaming process\n this.token_cache = [];\n this.print_len = 0;\n this.next_tokens_are_prompt = true;\n }\n\n /**\n * Receives tokens, decodes them, and prints them to stdout as soon as they form entire words.\n * @param {bigint[][]} value \n */\n put(value) {\n if (value.length > 1) {\n throw Error('TextStreamer only supports batch size of 1');\n }\n\n if (this.skip_prompt && this.next_tokens_are_prompt) {\n this.next_tokens_are_prompt = false;\n return;\n }\n\n const tokens = value[0];\n this.token_callback_function?.(tokens)\n\n // Add the new token to the cache and decodes the entire thing.\n this.token_cache = mergeArrays(this.token_cache, tokens);\n const text = this.tokenizer.decode(this.token_cache, this.decode_kwargs);\n\n let printable_text;\n if (text.endsWith('\\n')) {\n // After the symbol for a new line, we flush the cache.\n printable_text = text.slice(this.print_len);\n this.token_cache = [];\n this.print_len = 0;\n } else if (text.length > 0 && is_chinese_char(text.charCodeAt(text.length - 1))) {\n // If the last token is a CJK character, we print the characters.\n printable_text = text.slice(this.print_len);\n this.print_len += printable_text.length;\n } else {\n // Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words,\n // which may change with the subsequent token -- there are probably smarter ways to do this!)\n printable_text = text.slice(this.print_len, text.lastIndexOf(' ') + 1);\n this.print_len += printable_text.length;\n }\n\n this.on_finalized_text(printable_text, false);\n }\n\n /**\n * Flushes any remaining cache and prints a newline to stdout.\n */\n end() {\n let printable_text;\n if (this.token_cache.length > 0) {\n const text = this.tokenizer.decode(this.token_cache, this.decode_kwargs);\n printable_text = text.slice(this.print_len);\n this.token_cache = [];\n this.print_len = 0;\n } else {\n printable_text = '';\n }\n this.next_tokens_are_prompt = true;\n this.on_finalized_text(printable_text, true);\n }\n\n /**\n * Prints the new text to stdout. If the stream is ending, also prints a newline.\n * @param {string} text \n * @param {boolean} stream_end \n */\n on_finalized_text(text, stream_end) {\n if (text.length > 0) {\n this.callback_function?.(text);\n }\n if (stream_end && this.callback_function === stdout_write && apis.IS_PROCESS_AVAILABLE) {\n this.callback_function?.('\\n');\n }\n }\n}\n\n/**\n * Utility class to handle streaming of tokens generated by whisper speech-to-text models.\n * Callback functions are invoked when each of the following events occur:\n * - A new chunk starts (on_chunk_start)\n * - A new token is generated (callback_function)\n * - A chunk ends (on_chunk_end)\n * - The stream is finalized (on_finalize)\n */\nexport class WhisperTextStreamer extends TextStreamer {\n /**\n * @param {import('../tokenizers.js').WhisperTokenizer} tokenizer\n * @param {Object} options\n * @param {boolean} [options.skip_prompt=false] Whether to skip the prompt tokens\n * @param {function(string): void} [options.callback_function=null] Function to call when a piece of text is ready to display\n * @param {function(string): void} [options.token_callback_function=null] Function to call when a new token is generated\n * @param {function(number): void} [options.on_chunk_start=null] Function to call when a new chunk starts\n * @param {function(number): void} [options.on_chunk_end=null] Function to call when a chunk ends\n * @param {function(): void} [options.on_finalize=null] Function to call when the stream is finalized\n * @param {number} [options.time_precision=0.02] Precision of the timestamps\n * @param {boolean} [options.skip_special_tokens=true] Whether to skip special tokens when decoding\n * @param {Object} [options.decode_kwargs={}] Additional keyword arguments to pass to the tokenizer's decode method\n */\n constructor(tokenizer, {\n skip_prompt = false,\n callback_function = null,\n token_callback_function = null,\n on_chunk_start = null,\n on_chunk_end = null,\n on_finalize = null,\n time_precision = 0.02,\n skip_special_tokens = true,\n decode_kwargs = {},\n } = {}) {\n super(tokenizer, {\n skip_prompt,\n callback_function,\n token_callback_function,\n decode_kwargs: { skip_special_tokens, ...decode_kwargs },\n });\n this.timestamp_begin = tokenizer.timestamp_begin;\n\n this.on_chunk_start = on_chunk_start;\n this.on_chunk_end = on_chunk_end;\n this.on_finalize = on_finalize;\n\n this.time_precision = time_precision;\n\n this.waiting_for_timestamp = false;\n }\n\n /**\n * @param {bigint[][]} value \n */\n put(value) {\n if (value.length > 1) {\n throw Error('WhisperTextStreamer only supports batch size of 1');\n }\n const tokens = value[0];\n\n // Check if the token is a timestamp\n if (tokens.length === 1) {\n const offset = Number(tokens[0]) - this.timestamp_begin;\n if (offset >= 0) {\n const time = offset * this.time_precision;\n if (this.waiting_for_timestamp) {\n this.on_chunk_end?.(time);\n } else {\n this.on_chunk_start?.(time);\n }\n this.waiting_for_timestamp = !this.waiting_for_timestamp; // Toggle\n value = [[]]; // Skip timestamp\n }\n }\n return super.put(value);\n }\n\n end() {\n super.end();\n this.on_finalize?.();\n }\n}\n","\n/**\n * @file Definitions of all models available in Transformers.js.\n * \n * **Example:** Load and run an `AutoModel`.\n * \n * ```javascript\n * import { AutoModel, AutoTokenizer } from '@huggingface/transformers';\n * \n * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');\n * let model = await AutoModel.from_pretrained('Xenova/bert-base-uncased');\n * \n * let inputs = await tokenizer('I love transformers!');\n * let { logits } = await model(inputs);\n * // Tensor {\n * // data: Float32Array(183132) [-7.117443084716797, -7.107812881469727, -7.092104911804199, ...]\n * // dims: (3) [1, 6, 30522],\n * // type: \"float32\",\n * // size: 183132,\n * // }\n * ```\n * \n * We also provide other `AutoModel`s (listed below), which you can use in the same way as the Python library. For example:\n * \n * **Example:** Load and run an `AutoModelForSeq2SeqLM`.\n * ```javascript\n * import { AutoModelForSeq2SeqLM, AutoTokenizer } from '@huggingface/transformers';\n * \n * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/t5-small');\n * let model = await AutoModelForSeq2SeqLM.from_pretrained('Xenova/t5-small');\n * \n * let { input_ids } = await tokenizer('translate English to German: I love transformers!');\n * let outputs = await model.generate(input_ids);\n * let decoded = tokenizer.decode(outputs[0], { skip_special_tokens: true });\n * // 'Ich liebe Transformatoren!'\n * ```\n * \n * @module models\n */\n\nimport {\n AutoConfig,\n getKeyValueShapes,\n} from './configs.js';\n\nimport {\n deviceToExecutionProviders,\n createInferenceSession,\n isONNXTensor,\n isONNXProxy,\n} from './backends/onnx.js';\nimport {\n DATA_TYPES,\n DEFAULT_DEVICE_DTYPE_MAPPING,\n DEFAULT_DTYPE_SUFFIX_MAPPING,\n isWebGpuFp16Supported,\n} from './utils/dtypes.js';\n\nimport {\n Callable,\n} from './utils/generic.js';\n\nimport {\n isIntegralNumber,\n mergeArrays,\n pick,\n} from './utils/core.js';\n\nimport {\n getModelFile,\n getModelJSON,\n} from './utils/hub.js';\n\nimport {\n GITHUB_ISSUE_URL,\n} from './utils/constants.js';\n\nimport {\n LogitsProcessorList,\n ForcedBOSTokenLogitsProcessor,\n ForcedEOSTokenLogitsProcessor,\n SuppressTokensAtBeginLogitsProcessor,\n WhisperTimeStampLogitsProcessor,\n NoRepeatNGramLogitsProcessor,\n RepetitionPenaltyLogitsProcessor,\n NoBadWordsLogitsProcessor,\n MinLengthLogitsProcessor,\n MinNewTokensLengthLogitsProcessor,\n\n TemperatureLogitsWarper,\n TopKLogitsWarper,\n TopPLogitsWarper,\n ClassifierFreeGuidanceLogitsProcessor,\n} from './generation/logits_process.js';\n\nimport {\n GenerationConfig,\n} from './generation/configuration_utils.js';\n\nimport {\n cat,\n full_like,\n mean,\n ones,\n ones_like,\n stack,\n std_mean,\n Tensor,\n zeros_like,\n} from './utils/tensor.js';\n\nimport { dynamic_time_warping, medianFilter } from './utils/maths.js';\nimport { EosTokenCriteria, MaxLengthCriteria, StoppingCriteriaList } from './generation/stopping_criteria.js';\nimport { LogitsSampler } from './generation/logits_sampler.js';\nimport { apis } from './env.js';\n\nimport { WhisperGenerationConfig } from './models/whisper/generation_whisper.js';\nimport { whisper_language_to_code } from './models/whisper/common_whisper.js';\n\n//////////////////////////////////////////////////\n// Model types: used internally\nconst MODEL_TYPES = {\n EncoderOnly: 0,\n EncoderDecoder: 1,\n Seq2Seq: 2,\n Vision2Seq: 3,\n DecoderOnly: 4,\n MaskGeneration: 5,\n ImageTextToText: 6,\n Musicgen: 7,\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Helper functions\n\n// NOTE: These will be populated fully later\nconst MODEL_TYPE_MAPPING = new Map();\nconst MODEL_NAME_TO_CLASS_MAPPING = new Map();\nconst MODEL_CLASS_TO_NAME_MAPPING = new Map();\n\n\n/**\n * Constructs an InferenceSession using a model file located at the specified path.\n * @param {string} pretrained_model_name_or_path The path to the directory containing the model file.\n * @param {string} fileName The name of the model file.\n * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the model.\n * @returns {Promise<{buffer: Uint8Array, session_options: Object, session_config: Object}>} A Promise that resolves to the data needed to create an InferenceSession object.\n * @private\n */\nasync function getSession(pretrained_model_name_or_path, fileName, options) {\n const custom_config = options.config?.['transformers.js_config'] ?? {};\n let device = options.device ?? custom_config.device;\n if (device && typeof device !== 'string') {\n if (device.hasOwnProperty(fileName)) {\n device = device[fileName];\n } else {\n console.warn(`device not specified for \"${fileName}\". Using the default device.`);\n device = null;\n }\n }\n\n // If the device is not specified, we use the default (supported) execution providers.\n const selectedDevice = /** @type {import(\"./utils/devices.js\").DeviceType} */(\n device ?? (apis.IS_NODE_ENV ? 'cpu' : 'wasm')\n );\n const executionProviders = deviceToExecutionProviders(selectedDevice);\n\n // If options.dtype is specified, we use it to choose the suffix for the model file.\n // Otherwise, we use the default dtype for the device.\n let dtype = options.dtype ?? custom_config.dtype;\n if (typeof dtype !== 'string') {\n if (dtype && dtype.hasOwnProperty(fileName)) {\n dtype = dtype[fileName];\n } else {\n dtype = DEFAULT_DEVICE_DTYPE_MAPPING[selectedDevice] ?? DATA_TYPES.fp32;\n console.warn(`dtype not specified for \"${fileName}\". Using the default dtype (${dtype}) for this device (${selectedDevice}).`);\n }\n }\n\n const selectedDtype = /** @type {import(\"./utils/dtypes.js\").DataType} */(dtype);\n\n if (!DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(selectedDtype)) {\n throw new Error(`Invalid dtype: ${selectedDtype}. Should be one of: ${Object.keys(DATA_TYPES).join(', ')}`);\n } else if (selectedDtype === DATA_TYPES.fp16 && selectedDevice === 'webgpu' && !(await isWebGpuFp16Supported())) {\n throw new Error(`The device (${selectedDevice}) does not support fp16.`);\n }\n\n // Only valid for models with a decoder\n const kv_cache_dtype = custom_config.kv_cache_dtype\n ? (typeof custom_config.kv_cache_dtype === 'string'\n ? custom_config.kv_cache_dtype\n : custom_config.kv_cache_dtype[selectedDtype] ?? 'float32')\n : undefined;\n\n if (kv_cache_dtype && !['float32', 'float16'].includes(kv_cache_dtype)) {\n throw new Error(`Invalid kv_cache_dtype: ${kv_cache_dtype}. Should be one of: float32, float16`);\n }\n\n const session_config = {\n dtype: selectedDtype,\n kv_cache_dtype,\n }\n\n // Construct the model file name\n const suffix = DEFAULT_DTYPE_SUFFIX_MAPPING[selectedDtype];\n const modelFileName = `${options.subfolder ?? ''}/${fileName}${suffix}.onnx`;\n\n const session_options = { ...options.session_options };\n\n // Overwrite `executionProviders` if not specified\n session_options.executionProviders ??= executionProviders;\n\n // Overwrite `freeDimensionOverrides` if specified in config and not set in session options\n const free_dimension_overrides = custom_config.free_dimension_overrides;\n if (free_dimension_overrides) {\n session_options.freeDimensionOverrides ??= free_dimension_overrides;\n } else if (selectedDevice.startsWith('webnn') && !session_options.freeDimensionOverrides) {\n console.warn(\n 'WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within \"transformers.js_config\". ' +\n 'When `free_dimension_overrides` is not set, you may experience significant performance degradation.'\n );\n }\n\n const bufferPromise = getModelFile(pretrained_model_name_or_path, modelFileName, true, options);\n\n // handle onnx external data files\n const use_external_data_format = options.use_external_data_format ?? custom_config.use_external_data_format;\n /** @type {Promise<{path: string, data: Uint8Array}>[]} */\n let externalDataPromises = [];\n if (use_external_data_format && (\n use_external_data_format === true ||\n (\n typeof use_external_data_format === 'object' &&\n use_external_data_format.hasOwnProperty(fileName) &&\n use_external_data_format[fileName] === true\n )\n )) {\n if (apis.IS_NODE_ENV) {\n throw new Error('External data format is not yet supported in Node.js');\n }\n const path = `${fileName}${suffix}.onnx_data`;\n const fullPath = `${options.subfolder ?? ''}/${path}`;\n externalDataPromises.push(new Promise(async (resolve, reject) => {\n const data = await getModelFile(pretrained_model_name_or_path, fullPath, true, options);\n resolve({ path, data })\n }));\n\n } else if (session_options.externalData !== undefined) {\n externalDataPromises = session_options.externalData.map(async (ext) => {\n // if the external data is a string, fetch the file and replace the string with its content\n if (typeof ext.data === \"string\") {\n const ext_buffer = await getModelFile(pretrained_model_name_or_path, ext.data, true, options);\n return { ...ext, data: ext_buffer };\n }\n return ext;\n });\n }\n\n if (externalDataPromises.length > 0) {\n session_options.externalData = await Promise.all(externalDataPromises);\n }\n\n if (selectedDevice === 'webgpu') {\n const shapes = getKeyValueShapes(options.config, {\n prefix: 'present',\n });\n if (Object.keys(shapes).length > 0 && !isONNXProxy()) {\n // Only set preferredOutputLocation if shapes are present and we aren't proxying ONNX\n /** @type {Record} */\n const preferredOutputLocation = {};\n for (const key in shapes) {\n preferredOutputLocation[key] = 'gpu-buffer';\n }\n session_options.preferredOutputLocation = preferredOutputLocation;\n }\n }\n\n const buffer = await bufferPromise;\n\n return { buffer, session_options, session_config };\n}\n\n/**\n * Helper function to create multiple InferenceSession objects.\n * \n * @param {string} pretrained_model_name_or_path The path to the directory containing the model file.\n * @param {Record} names The names of the model files to load.\n * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the model.\n * @returns {Promise>} A Promise that resolves to a dictionary of InferenceSession objects.\n * @private\n */\nasync function constructSessions(pretrained_model_name_or_path, names, options) {\n return Object.fromEntries(await Promise.all(\n Object.keys(names).map(async (name) => {\n const { buffer, session_options, session_config } = await getSession(pretrained_model_name_or_path, names[name], options);\n const session = await createInferenceSession(buffer, session_options, session_config);\n return [name, session];\n })\n ));\n}\n\n/**\n * Helper function to load multiple optional configuration files\n * @param {string} pretrained_model_name_or_path The path to the directory containing the config file.\n * @param {Record} names The names of the config files to load.\n * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the configs.\n * @returns {Promise>} A Promise that resolves to a dictionary of configuration objects.\n * @private\n */\nasync function getOptionalConfigs(pretrained_model_name_or_path, names, options) {\n return Object.fromEntries(await Promise.all(\n Object.keys(names).map(async (name) => {\n const config = await getModelJSON(pretrained_model_name_or_path, names[name], false, options);\n return [name, config];\n })\n ));\n}\n\n/**\n * Validate model inputs\n * @param {Object} session The InferenceSession object that will be run.\n * @param {Object} inputs The inputs to check.\n * @returns {Record} The checked inputs.\n * @throws {Error} If any inputs are missing.\n * @private\n */\nfunction validateInputs(session, inputs) {\n /**\n * NOTE: Create either a shallow or deep copy based on `onnx.wasm.proxy`\n * @type {Record}\n */\n const checkedInputs = Object.create(null);\n const missingInputs = [];\n for (const inputName of session.inputNames) {\n const tensor = inputs[inputName];\n // Rare case where one of the model's input names corresponds to a built-in\n // object name (e.g., toString), which would cause a simple (!tensor) check to fail,\n // because it's not undefined but a function.\n if (!(tensor instanceof Tensor)) {\n missingInputs.push(inputName);\n continue;\n }\n // NOTE: When `env.wasm.proxy is true` the tensor is moved across the Worker\n // boundary, transferring ownership to the worker and invalidating the tensor.\n // So, in this case, we simply sacrifice a clone for it.\n checkedInputs[inputName] = isONNXProxy() ? tensor.clone() : tensor;\n }\n if (missingInputs.length > 0) {\n throw new Error(\n `An error occurred during model execution: \"Missing the following inputs: ${missingInputs.join(', ')}.`);\n }\n\n const numInputsProvided = Object.keys(inputs).length;\n const numInputsNeeded = session.inputNames.length;\n if (numInputsProvided > numInputsNeeded) {\n // No missing inputs, but too many inputs were provided.\n // Warn the user and ignore the extra inputs.\n let ignored = Object.keys(inputs).filter(inputName => !session.inputNames.includes(inputName));\n console.warn(`WARNING: Too many inputs were provided (${numInputsProvided} > ${numInputsNeeded}). The following inputs will be ignored: \"${ignored.join(', ')}\".`);\n }\n\n return checkedInputs;\n}\n\nconst getQueryValue = (name) => {\n const urlParams = new URLSearchParams(window.location.search);\n return urlParams.get(name);\n};\n\nlet runs = 1;\n\nlet perf = {\n warmup: 0,\n inference: [],\n throughput: 0\n};\n\nexport function getPerf() {\n return perf;\n}\n\n/**\n * Executes an InferenceSession using the specified inputs.\n * NOTE: `inputs` must contain at least the input names of the model.\n * - If additional inputs are passed, they will be ignored.\n * - If inputs are missing, an error will be thrown.\n * \n * @param {Object} session The InferenceSession object to run.\n * @param {Object} inputs An object that maps input names to input tensors.\n * @returns {Promise} A Promise that resolves to an object that maps output names to output tensors.\n * @private\n */\nasync function sessionRun(session, inputs) {\n perf = {\n warmup: 0,\n inference: [],\n throughput: 0\n };\n const checkedInputs = validateInputs(session, inputs);\n try {\n // pass the original ort tensor\n const ortFeed = Object.fromEntries(Object.entries(checkedInputs).map(([k, v]) => [k, v.ort_tensor]));\n let output;\n let numOfWarmups = 1;\n // let numOfRuns = 100;\n console.log(`-- number of test runs --`);\n if (getQueryValue(\"run\")) {\n runs = parseInt(getQueryValue(\"run\"));\n } else {\n runs = 1;\n }\n console.log(runs);\n let start = performance.now();\n let loopStart;\n let current;\n let arrayInference = [];\n for(let i=0; i < numOfWarmups + runs; i++) {\n loopStart = performance.now();\n output = await session.run(ortFeed);\n current = performance.now() - loopStart;\n if(i==0) {\n perf.warmup = current;\n } else {\n arrayInference.push(current);\n }\n console.log(`Session run time: ${current}ms`);\n }\n perf.inference = arrayInference;\n perf.throughput = parseFloat((1000.00 / ((performance.now() - start) / (numOfWarmups + runs))).toFixed(2));\n output = replaceTensors(output);\n return output;\n } catch (e) {\n // This usually occurs when the inputs are of the wrong type.\n console.error(`An error occurred during model execution: \"${e}\".`);\n console.error('Inputs given to model:', checkedInputs);\n throw e;\n }\n}\n\n/**\n * Replaces ONNX Tensor objects with custom Tensor objects to support additional functions.\n * @param {Object} obj The object to replace tensor objects in.\n * @returns {Object} The object with tensor objects replaced by custom Tensor objects.\n * @private\n */\nfunction replaceTensors(obj) {\n for (let prop in obj) {\n if (isONNXTensor(obj[prop])) {\n obj[prop] = new Tensor(obj[prop]);\n } else if (typeof obj[prop] === 'object') {\n replaceTensors(obj[prop]);\n }\n }\n return obj;\n}\n\n\n/**\n * Converts an array or Tensor of integers to an int64 Tensor.\n * @param {Array|Tensor} items The input integers to be converted.\n * @returns {Tensor} The int64 Tensor with the converted values.\n * @throws {Error} If the input array is empty or the input is a batched Tensor and not all sequences have the same length.\n * @private\n */\nfunction toI64Tensor(items) {\n if (items instanceof Tensor) {\n return items;\n }\n // items is an array\n if (items.length === 0) {\n throw Error(\"items must be non-empty\");\n }\n\n if (Array.isArray(items[0])) {\n // batched\n if (items.some(x => x.length !== items[0].length)) {\n throw Error(\"Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.\")\n }\n\n return new Tensor('int64',\n BigInt64Array.from(items.flat().map(x => BigInt(x))),\n [items.length, items[0].length]\n );\n } else {\n //flat\n return new Tensor('int64',\n BigInt64Array.from(items.map(x => BigInt(x))),\n [1, items.length]\n );\n }\n}\n\n/**\n * Creates a boolean tensor with a single value.\n * @param {boolean} value The value of the tensor.\n * @returns {Tensor} The boolean tensor.\n * @private\n */\nfunction boolTensor(value) {\n return new Tensor('bool', [value], [1]);\n}\n\n// JS doesn't support mixins, so we define some reused functions here, and allow \"this\" to be passed in\n/**\n * Perform forward pass on the seq2seq model (both encoder and decoder).\n * @param {Object} self The seq2seq model object.\n * @param {Object} model_inputs The input object for the model containing encoder and decoder inputs.\n * @returns {Promise} Promise that resolves with the output of the seq2seq model.\n * @private\n */\nasync function seq2seqForward(self, model_inputs) {\n let { encoder_outputs, input_ids, decoder_input_ids, ...other_decoder_inputs } = model_inputs;\n // Encode if needed\n if (!encoder_outputs) {\n const encoder_inputs = pick(model_inputs, self.sessions['model'].inputNames);\n // Encoder outputs are not given, so we must compute them.\n encoder_outputs = (await encoderForward(self, encoder_inputs)).last_hidden_state;\n }\n\n other_decoder_inputs.input_ids = decoder_input_ids;\n other_decoder_inputs.encoder_hidden_states = encoder_outputs;\n\n if (self.sessions['decoder_model_merged'].inputNames.includes('encoder_attention_mask')) {\n other_decoder_inputs.encoder_attention_mask = model_inputs.attention_mask\n }\n\n const decoderResults = await decoderForward(self, other_decoder_inputs, true);\n\n return decoderResults;\n}\n\n/**\n * Forward pass of an encoder model.\n * @param {Object} self The encoder model.\n * @param {Object} model_inputs The input data to be used for the forward pass.\n * @returns {Promise} The model's outputs.\n * @private\n */\nasync function encoderForward(self, model_inputs) {\n const session = self.sessions['model'];\n const encoderFeeds = pick(model_inputs, session.inputNames);\n\n if (session.inputNames.includes('inputs_embeds') && !encoderFeeds.inputs_embeds) {\n if (!model_inputs.input_ids) {\n throw new Error('Both `input_ids` and `inputs_embeds` are missing in the model inputs.');\n }\n encoderFeeds.inputs_embeds = await self.encode_text({ input_ids: model_inputs.input_ids });\n }\n if (session.inputNames.includes('token_type_ids') && !encoderFeeds.token_type_ids) {\n // Assign default `token_type_ids` (all zeroes) to the `encoderFeeds` if the model expects it,\n // but they weren't created by the tokenizer.\n encoderFeeds.token_type_ids = new Tensor(\n 'int64',\n new BigInt64Array(encoderFeeds.input_ids.data.length),\n encoderFeeds.input_ids.dims\n )\n }\n return await sessionRun(session, encoderFeeds);\n}\n\n/**\n * Forward pass of a decoder model.\n * @param {Object} self The decoder model.\n * @param {Object} model_inputs The input data to be used for the forward pass.\n * @returns {Promise} The logits and past key values.\n * @private\n */\nasync function decoderForward(self, model_inputs, is_encoder_decoder = false) {\n\n const session = self.sessions[\n is_encoder_decoder ? 'decoder_model_merged' : 'model'\n ]\n\n const { past_key_values, ...new_model_inputs } = model_inputs;\n\n if (session.inputNames.includes('use_cache_branch')) {\n new_model_inputs.use_cache_branch = boolTensor(!!past_key_values);\n }\n if (session.inputNames.includes('position_ids') && new_model_inputs.attention_mask && !new_model_inputs.position_ids) {\n new_model_inputs.position_ids = createPositionIds(new_model_inputs, past_key_values);\n }\n\n // Unpack the `past_key_values` object into model inputs\n self.addPastKeyValues(new_model_inputs, past_key_values);\n\n // Select only the inputs that are needed for the current session\n const fixed = pick(new_model_inputs, session.inputNames);\n return await sessionRun(session, fixed);\n}\n\n\n/**\n * Forward pass of an image-text-to-text model.\n * @param {Object} self The image-text-to-text model model.\n * @param {Object} model_inputs The input data to be used for the forward pass.\n * @param {Tensor} [model_inputs.input_ids=null]\n * @param {Tensor} [model_inputs.attention_mask=null]\n * @param {Tensor} [model_inputs.pixel_values=null]\n * @param {Tensor} [model_inputs.position_ids=null]\n * @param {Tensor} [model_inputs.inputs_embeds=null]\n * @param {Tensor} [model_inputs.past_key_values=null]\n * @param {Object} [model_inputs.generation_config=null]\n * @param {Object} [model_inputs.logits_processor=null]\n * @returns {Promise} The model's output tensor\n * @private\n */\nasync function imageTextToTextForward(self, {\n // Produced by the tokenizer/processor:\n input_ids = null,\n attention_mask = null,\n pixel_values = null,\n\n // Used during generation:\n position_ids = null,\n inputs_embeds = null,\n past_key_values = null,\n\n // Generic generation parameters\n generation_config = null,\n logits_processor = null,\n\n // TODO: needed?\n ...kwargs\n}) {\n\n if (!inputs_embeds) {\n // 1. Extract the input embeddings\n inputs_embeds = await self.encode_text({ input_ids });\n\n // 2. Possibly, merge text and images\n if (pixel_values && input_ids.dims[1] !== 1) {\n const image_features = await self.encode_image({ pixel_values });\n\n ({ inputs_embeds, attention_mask } = self._merge_input_ids_with_image_features({\n image_features,\n inputs_embeds,\n input_ids,\n attention_mask,\n }));\n\n } else if (past_key_values && pixel_values && input_ids.dims[1] === 1) {\n // This is the case when we are generating with cache\n const target_length = input_ids.dims[1]; // always 1\n const past_length = Object.values(past_key_values)[0].dims.at(-2);\n\n attention_mask = cat([\n ones([input_ids.dims[0], past_length]),\n attention_mask.slice(null, [attention_mask.dims[1] - target_length, attention_mask.dims[1]]),\n ], 1);\n }\n }\n\n const outputs = await decoderForward(self, {\n inputs_embeds,\n past_key_values,\n attention_mask,\n position_ids,\n generation_config,\n logits_processor,\n }, true);\n return outputs;\n}\n\nfunction createPositionIds(model_inputs, past_key_values = null) {\n // If the model supports providing position_ids, we create position_ids on the fly for batch generation,\n // by computing the cumulative sum of the attention mask along the sequence length dimension.\n // \n // Equivalent to:\n // position_ids = attention_mask.long().cumsum(-1) - 1\n // position_ids.masked_fill_(attention_mask == 0, 1)\n // if past_key_values:\n // position_ids = position_ids[:, -input_ids.shape[1] :]\n const { input_ids, inputs_embeds, attention_mask } = model_inputs;\n const [bz, seq_len] = attention_mask.dims;\n\n const data = new BigInt64Array(attention_mask.data.length);\n for (let i = 0; i < bz; ++i) {\n const start = i * seq_len;\n let sum = BigInt(0);\n for (let j = 0; j < seq_len; ++j) {\n const index = start + j;\n if (attention_mask.data[index] === 0n) {\n data[index] = BigInt(1);\n } else { // === 1n\n data[index] = sum;\n sum += attention_mask.data[index];\n }\n }\n }\n\n let position_ids = new Tensor('int64', data, attention_mask.dims);\n if (past_key_values) {\n const offset = -(input_ids ?? inputs_embeds).dims.at(1);\n position_ids = position_ids.slice(null, [offset, null]);\n }\n return position_ids;\n}\n\nfunction decoder_prepare_inputs_for_generation(self, input_ids, model_inputs, generation_config) {\n if (model_inputs.past_key_values) {\n const past_length = Object.values(model_inputs.past_key_values)[0].dims.at(-2);\n const { input_ids, attention_mask } = model_inputs;\n\n // Keep only the unprocessed tokens:\n // 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where\n // some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as\n // input)\n if (attention_mask && attention_mask.dims[1] > input_ids.dims[1]) {\n // NOTE: not needed since we only pass the generated tokens to the next forward pass\n // const offset = -(attention_mask.dims[1] - past_length);\n // model_inputs.input_ids = input_ids.slice(null, [offset, null]);\n }\n // 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens.\n // We can discard input_ids based on the past_length.\n else if (past_length < input_ids.dims[1]) {\n // NOTE: Required for phi models.\n // See https://github.com/huggingface/transformers/issues/30809#issuecomment-2111918479 for more information.\n model_inputs.input_ids = input_ids.slice(null, [past_length, null]);\n }\n // 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.\n else {\n if (\n // NOTE: Only used by VLMs (!= so that null matches undefined)\n self.config.image_token_index != null &&\n // Equivalent to `self.config.image_token_index in input_ids` (== so that int matches bigint)\n input_ids.data.some(x => x == self.config.image_token_index)\n ) {\n // TODO: Support multiple image tokens\n const num_image_tokens = self.config.num_image_tokens;\n if (!num_image_tokens) {\n throw new Error('`num_image_tokens` is missing in the model configuration.');\n }\n\n const num_new_tokens = input_ids.dims[1] - (past_length - num_image_tokens);\n model_inputs.input_ids = input_ids.slice(null, [-num_new_tokens, null]);\n\n // TODO: The attention mask should be formed from the attention mask passed in model_inputs\n model_inputs.attention_mask = ones([1, past_length + num_new_tokens]);\n }\n }\n }\n\n return model_inputs;\n}\n\nfunction encoder_decoder_prepare_inputs_for_generation(self, input_ids, model_inputs, generation_config) {\n if (model_inputs.past_key_values) {\n input_ids = input_ids.map(x => [x.at(-1)]);\n }\n\n return {\n ...model_inputs,\n decoder_input_ids: toI64Tensor(input_ids),\n };\n}\n\nfunction image_text_to_text_prepare_inputs_for_generation(self, ...args) {\n if (self.config.is_encoder_decoder) {\n return encoder_decoder_prepare_inputs_for_generation(self, ...args);\n } else {\n return decoder_prepare_inputs_for_generation(self, ...args);\n }\n}\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n/**\n * A base class for pre-trained models that provides the model configuration and an ONNX session.\n */\nexport class PreTrainedModel extends Callable {\n main_input_name = 'input_ids';\n forward_params = ['input_ids', 'attention_mask'];\n /**\n * Creates a new instance of the `PreTrainedModel` class.\n * @param {import('./configs.js').PretrainedConfig} config The model configuration.\n * @param {Record} sessions The inference sessions for the model.\n * @param {Record} configs Additional configuration files (e.g., generation_config.json).\n */\n constructor(config, sessions, configs) {\n super();\n\n this.config = config;\n this.sessions = sessions;\n this.configs = configs;\n\n const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);\n const modelType = MODEL_TYPE_MAPPING.get(modelName);\n\n this.can_generate = false;\n this._forward = null;\n\n this._prepare_inputs_for_generation = null;\n switch (modelType) {\n case MODEL_TYPES.DecoderOnly:\n this.can_generate = true;\n this._forward = decoderForward;\n this._prepare_inputs_for_generation = decoder_prepare_inputs_for_generation;\n break;\n case MODEL_TYPES.Seq2Seq:\n case MODEL_TYPES.Vision2Seq:\n case MODEL_TYPES.Musicgen:\n this.can_generate = true;\n\n this._forward = seq2seqForward;\n this._prepare_inputs_for_generation = encoder_decoder_prepare_inputs_for_generation;\n break;\n\n case MODEL_TYPES.EncoderDecoder:\n this._forward = seq2seqForward;\n break;\n case MODEL_TYPES.ImageTextToText:\n this.can_generate = true;\n this._forward = imageTextToTextForward;\n this._prepare_inputs_for_generation = image_text_to_text_prepare_inputs_for_generation;\n break;\n\n default:\n // should be MODEL_TYPES.EncoderOnly\n this._forward = encoderForward;\n break;\n }\n\n if (this.can_generate) {\n this.forward_params.push('past_key_values');\n }\n\n /** @type {import('./configs.js').TransformersJSConfig} */\n this.custom_config = this.config['transformers.js_config'] ?? {};\n }\n\n /**\n * Disposes of all the ONNX sessions that were created during inference.\n * @returns {Promise} An array of promises, one for each ONNX session that is being disposed.\n * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n */\n async dispose() {\n const promises = [];\n for (const session of Object.values(this.sessions)) {\n if (session?.handler?.dispose) {\n promises.push(session.handler.dispose())\n }\n }\n return await Promise.all(promises);\n }\n\n /**\n * Instantiate one of the model classes of the library from a pretrained model.\n * \n * The model class to instantiate is selected based on the `model_type` property of the config object\n * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)\n * \n * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:\n * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.\n * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a\n * user or organization name, like `dbmdz/bert-base-german-cased`.\n * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`.\n * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the model.\n * \n * @returns {Promise} A new instance of the `PreTrainedModel` class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n model_file_name = null,\n subfolder = 'onnx',\n device = null,\n dtype = null,\n use_external_data_format = null,\n session_options = {},\n } = {}) {\n\n let options = {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n model_file_name,\n subfolder,\n device,\n dtype,\n use_external_data_format,\n session_options,\n }\n\n const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this);\n const modelType = MODEL_TYPE_MAPPING.get(modelName);\n\n config = options.config = await AutoConfig.from_pretrained(pretrained_model_name_or_path, options);\n\n let info;\n if (modelType === MODEL_TYPES.DecoderOnly) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: options.model_file_name ?? 'model',\n }, options),\n getOptionalConfigs(pretrained_model_name_or_path, {\n generation_config: 'generation_config.json',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: 'encoder_model',\n decoder_model_merged: 'decoder_model_merged',\n }, options),\n getOptionalConfigs(pretrained_model_name_or_path, {\n generation_config: 'generation_config.json',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.MaskGeneration) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: 'vision_encoder',\n prompt_encoder_mask_decoder: 'prompt_encoder_mask_decoder',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.EncoderDecoder) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: 'encoder_model',\n decoder_model_merged: 'decoder_model_merged',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.ImageTextToText) {\n const sessions = {\n embed_tokens: 'embed_tokens',\n vision_encoder: 'vision_encoder',\n decoder_model_merged: 'decoder_model_merged',\n }\n if (config.is_encoder_decoder) {\n sessions['model'] = 'encoder_model';\n }\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, sessions, options),\n getOptionalConfigs(pretrained_model_name_or_path, {\n generation_config: 'generation_config.json',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.Musicgen) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: 'text_encoder',\n decoder_model_merged: 'decoder_model_merged',\n encodec_decode: 'encodec_decode',\n }, options),\n getOptionalConfigs(pretrained_model_name_or_path, {\n generation_config: 'generation_config.json',\n }, options),\n ]);\n\n } else { // should be MODEL_TYPES.EncoderOnly\n if (modelType !== MODEL_TYPES.EncoderOnly) {\n console.warn(`Model type for '${modelName ?? config?.model_type}' not found, assuming encoder-only architecture. Please report this at ${GITHUB_ISSUE_URL}.`)\n }\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: options.model_file_name ?? 'model',\n }, options),\n ]);\n }\n\n // @ts-ignore\n return new this(config, ...info);\n }\n\n /**\n * Runs the model with the provided inputs\n * @param {Object} model_inputs Object containing input tensors\n * @returns {Promise} Object containing output tensors\n */\n async _call(model_inputs) {\n return await this.forward(model_inputs);\n }\n\n /**\n * Forward method for a pretrained model. If not overridden by a subclass, the correct forward method\n * will be chosen based on the model type.\n * @param {Object} model_inputs The input data to the model in the format specified in the ONNX model.\n * @returns {Promise} The output data from the model in the format specified in the ONNX model.\n * @throws {Error} This method must be implemented in subclasses.\n */\n async forward(model_inputs) {\n return await this._forward(this, model_inputs);\n }\n\n /**\n * Get the model's generation config, if it exists.\n * @returns {GenerationConfig|null} The model's generation config if it exists, otherwise `null`.\n */\n get generation_config() {\n return this.configs?.generation_config ?? null;\n }\n\n /**\n * This function returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsWarper`]\n * instances used for multinomial sampling.\n * @param {GenerationConfig} generation_config The generation config.\n * @returns {LogitsProcessorList} generation_config \n */\n _get_logits_warper(generation_config) {\n\n // instantiate warpers list\n const warpers = new LogitsProcessorList();\n\n if (generation_config.temperature !== null && generation_config.temperature !== 1.0) {\n warpers.push(new TemperatureLogitsWarper(generation_config.temperature));\n }\n if (generation_config.top_k !== null && generation_config.top_k !== 0) {\n // TODO: add min_tokens_to_keep\n warpers.push(new TopKLogitsWarper(generation_config.top_k));\n }\n if (generation_config.top_p !== null && generation_config.top_p < 1.0) {\n // TODO: add min_tokens_to_keep\n warpers.push(new TopPLogitsWarper(generation_config.top_p));\n }\n\n return warpers;\n }\n\n /**\n * @param {GenerationConfig} generation_config \n * @param {number} input_ids_seq_length The starting sequence length for the input ids.\n * @returns {LogitsProcessorList}\n * @private\n */\n _get_logits_processor(\n generation_config,\n input_ids_seq_length,\n // encoder_input_ids, TODO\n // prefix_allowed_tokens_fn, TODO\n logits_processor = null\n ) {\n const processors = new LogitsProcessorList();\n\n // if (generation_config.diversity_penalty !== null && generation_config.diversity_penalty > 0.0) {\n // processors.push(new HammingDiversityLogitsProcessor(\n // generation_config.diversity_penalty,\n // generation_config.num_beams,\n // generation_config.num_beam_groups\n // ));\n // }\n\n // if (generation_config.encoder_repetition_penalty !== null && generation_config.encoder_repetition_penalty !== 1.0) {\n // processors.push(new EncoderRepetitionPenaltyLogitsProcessor(\n // generation_config.encoder_repetition_penalty,\n // encoder_input_ids\n // ));\n // }\n\n if (generation_config.repetition_penalty !== null && generation_config.repetition_penalty !== 1.0) {\n processors.push(new RepetitionPenaltyLogitsProcessor(generation_config.repetition_penalty));\n }\n\n if (generation_config.no_repeat_ngram_size !== null && generation_config.no_repeat_ngram_size > 0) {\n processors.push(new NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size));\n }\n\n // if (generation_config.encoder_no_repeat_ngram_size !== null && generation_config.encoder_no_repeat_ngram_size > 0) {\n // if (this.config.is_encoder_decoder) {\n // processors.push(new EncoderNoRepeatNGramLogitsProcessor(\n // generation_config.encoder_no_repeat_ngram_size,\n // encoder_input_ids\n // ));\n // } else {\n // throw new Error(\"It's impossible to use `encoder_no_repeat_ngram_size` with decoder-only architecture\");\n // }\n // }\n\n if (generation_config.bad_words_ids !== null) {\n processors.push(new NoBadWordsLogitsProcessor(generation_config.bad_words_ids, generation_config.eos_token_id));\n }\n\n if (generation_config.min_length !== null && generation_config.eos_token_id !== null && generation_config.min_length > 0) {\n processors.push(new MinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id));\n }\n\n if (generation_config.min_new_tokens !== null && generation_config.eos_token_id !== null && generation_config.min_new_tokens > 0) {\n processors.push(new MinNewTokensLengthLogitsProcessor(\n input_ids_seq_length,\n generation_config.min_new_tokens,\n generation_config.eos_token_id\n ));\n }\n\n // if (prefix_allowed_tokens_fn !== null) {\n // processors.push(new PrefixConstrainedLogitsProcessor(\n // prefix_allowed_tokens_fn,\n // generation_config.num_beams / generation_config.num_beam_groups\n // ));\n // }\n\n\n if (generation_config.forced_bos_token_id !== null) {\n processors.push(new ForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id));\n }\n\n if (generation_config.forced_eos_token_id !== null) {\n processors.push(new ForcedEOSTokenLogitsProcessor(\n generation_config.max_length,\n generation_config.forced_eos_token_id\n ));\n }\n\n // if (generation_config.remove_invalid_values === true) {\n // processors.push(new InfNanRemoveLogitsProcessor());\n // }\n\n // if (generation_config.exponential_decay_length_penalty !== null) {\n // processors.push(new ExponentialDecayLengthPenalty(\n // generation_config.exponential_decay_length_penalty,\n // generation_config.eos_token_id,\n // input_ids_seq_length\n // ));\n // }\n\n // if (generation_config.suppress_tokens !== null) {\n // processors.push(new SuppressTokensLogitsProcessor(generation_config.suppress_tokens));\n // }\n\n if (generation_config.begin_suppress_tokens !== null) {\n const begin_index = (input_ids_seq_length > 1 || generation_config.forced_bos_token_id === null)\n ? input_ids_seq_length\n : input_ids_seq_length + 1;\n\n processors.push(new SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index));\n }\n\n // DEPRECATED: https://github.com/huggingface/transformers/pull/29485\n // if (generation_config.forced_decoder_ids !== null) {\n // processors.push(new ForceTokensLogitsProcessor(generation_config.forced_decoder_ids));\n // }\n\n\n // 8. prepare batched CFG externally\n if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) {\n processors.push(new ClassifierFreeGuidanceLogitsProcessor(generation_config.guidance_scale));\n }\n\n if (logits_processor !== null) {\n processors.extend(logits_processor)\n }\n\n // `LogitNormalization` should always be the last logit processor, when present\n // if (generation_config.renormalize_logits === true) {\n // processors.push(new LogitNormalization());\n // }\n\n return processors;\n }\n\n /**\n * This function merges multiple generation configs together to form a final generation config to be used by the model for text generation.\n * It first creates an empty `GenerationConfig` object, then it applies the model's own `generation_config` property to it. Finally, if a `generation_config` object was passed in the arguments, it overwrites the corresponding properties in the final config with those of the passed config object.\n * @param {GenerationConfig|null} generation_config A `GenerationConfig` object containing generation parameters.\n * @param {Object} kwargs Additional generation parameters to be used in place of those in the `generation_config` object.\n * @returns {GenerationConfig} The final generation config object to be used by the model for text generation.\n */\n _prepare_generation_config(generation_config, kwargs, cls = GenerationConfig) {\n // Create empty generation config (contains defaults)\n // We pass `this.config` so that if `eos_token_id` or `bos_token_id` exist in the model's config, we will use them\n const config = { ...this.config };\n for (const key of [\"decoder\", \"generator\", \"text_config\"]) {\n // Special case: some models have generation attributes set in the decoder.\n // Use them if still unset in the generation config.\n if (key in config) {\n Object.assign(config, config[key]);\n }\n }\n\n const gen_config = new cls(config);\n\n // Apply model's generation config, if it exists\n Object.assign(gen_config, this.generation_config ?? {});\n\n // Next, use any generation config specified by the user\n // when calling `generate`\n if (generation_config) {\n Object.assign(gen_config, generation_config);\n }\n\n // Finally, if any kwargs were passed, use them to overwrite\n if (kwargs) {\n Object.assign(gen_config, pick(kwargs, Object.getOwnPropertyNames(gen_config)));\n }\n\n return gen_config;\n }\n\n /**\n * \n * @param {GenerationConfig} generation_config \n * @param {StoppingCriteriaList} [stopping_criteria=null] \n */\n _get_stopping_criteria(generation_config, stopping_criteria = null) {\n const criteria = new StoppingCriteriaList();\n\n if (generation_config.max_length !== null) {\n criteria.push(new MaxLengthCriteria(\n generation_config.max_length,\n this.config.max_position_embeddings ?? null,\n ));\n }\n // if (generation_config.max_time !== null) {\n // criteria.push(new MaxTimeCriteria(generation_config.max_time));\n // }\n if (generation_config.eos_token_id !== null) {\n criteria.push(new EosTokenCriteria(generation_config.eos_token_id));\n }\n\n if (stopping_criteria) {\n criteria.extend(stopping_criteria);\n }\n return criteria;\n\n }\n\n /**\n * Confirms that the model class is compatible with generation.\n * If not, raises an exception that points to the right class to use.\n */\n _validate_model_class() {\n if (!this.can_generate) {\n const generate_compatible_mappings = [\n MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,\n // MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING, // TODO\n MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,\n MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,\n MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES,\n ];\n\n const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);\n\n const generate_compatible_classes = new Set();\n const modelType = this.config.model_type;\n for (const model_mapping of generate_compatible_mappings) {\n const supported_models = model_mapping.get(modelType);\n if (supported_models) {\n generate_compatible_classes.add(supported_models[0]);\n }\n }\n\n let errorMessage = `The current model class (${modelName}) is not compatible with \\`.generate()\\`, as it doesn't have a language model head.`\n if (generate_compatible_classes.size > 0) {\n errorMessage += ` Please use the following class instead: ${[...generate_compatible_classes].join(', ')}`;\n }\n throw Error(errorMessage);\n }\n }\n\n prepare_inputs_for_generation(...args) {\n return this._prepare_inputs_for_generation(this, ...args);\n }\n\n /**\n * \n * @param {Object} inputs\n * @param {bigint[][]} inputs.generated_input_ids\n * @param {Object} inputs.outputs\n * @param {Object} inputs.model_inputs\n * @param {boolean} inputs.is_encoder_decoder\n * @returns {Object} The updated model inputs for the next generation iteration.\n */\n _update_model_kwargs_for_generation({ generated_input_ids, outputs, model_inputs, is_encoder_decoder }) {\n // update past_key_values\n model_inputs['past_key_values'] = this.getPastKeyValues(outputs, model_inputs.past_key_values);\n\n // update inputs for next run\n model_inputs['input_ids'] = new Tensor('int64', generated_input_ids.flat(), [generated_input_ids.length, 1]);\n\n if (!is_encoder_decoder) {\n // update attention mask\n model_inputs.attention_mask = cat(\n [\n model_inputs.attention_mask,\n ones([model_inputs.attention_mask.dims[0], 1]),\n ], 1\n );\n } else if ('decoder_attention_mask' in model_inputs) {\n // TODO: update decoder attention mask if the model requires it\n }\n\n // force recreate position_ids in next iteration\n model_inputs['position_ids'] = null;\n\n return model_inputs;\n }\n\n /**\n * This function extracts the model-specific `inputs` for generation.\n * @param {Object} params\n * @param {Tensor} [params.inputs=null]\n * @param {number} [params.bos_token_id=null]\n * @param {Record} [params.model_kwargs]\n * @returns {{inputs_tensor: Tensor, model_inputs: Record, model_input_name: string}} The model-specific inputs for generation.\n */\n _prepare_model_inputs({ inputs, bos_token_id, model_kwargs }) {\n const model_inputs = pick(model_kwargs, this.forward_params);\n const input_name = this.main_input_name;\n if (input_name in model_inputs) {\n if (inputs) {\n throw new Error(\n \"`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. \" +\n \"Make sure to either pass {inputs} or {input_name}=...\"\n );\n }\n } else {\n model_inputs[input_name] = inputs;\n }\n\n const inputs_tensor = model_inputs[input_name];\n\n return { inputs_tensor, model_inputs, model_input_name: input_name };\n }\n\n async _prepare_encoder_decoder_kwargs_for_generation({ inputs_tensor, model_inputs, model_input_name, generation_config }) {\n if (\n this.sessions['model'].inputNames.includes('inputs_embeds')\n && !model_inputs.inputs_embeds\n && '_prepare_inputs_embeds' in this\n ) {\n // Encoder expects `inputs_embeds` instead of `input_ids`\n const { input_ids, pixel_values, attention_mask, ...kwargs } = model_inputs;\n // @ts-ignore\n const prepared_inputs = await this._prepare_inputs_embeds(model_inputs);\n model_inputs = {\n ...kwargs,\n ...pick(prepared_inputs, ['inputs_embeds', 'attention_mask']),\n };\n }\n let { last_hidden_state } = await encoderForward(this, model_inputs);\n\n // for classifier free guidance we need to add a 'null' input to our encoder hidden states\n if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) {\n\n last_hidden_state = cat([\n last_hidden_state,\n full_like(last_hidden_state, 0.0),\n ], 0);\n\n if ('attention_mask' in model_inputs) {\n model_inputs['attention_mask'] = cat([\n model_inputs['attention_mask'],\n zeros_like(model_inputs['attention_mask']),\n ], 0);\n }\n\n } else if (model_inputs.decoder_input_ids) {\n // Ensure that the encoder outputs have the same batch size as the decoder inputs,\n // allowing for more efficient batched generation for single inputs\n const decoder_input_ids_batch_size = toI64Tensor(model_inputs.decoder_input_ids).dims[0];\n if (decoder_input_ids_batch_size !== last_hidden_state.dims[0]) {\n if (last_hidden_state.dims[0] !== 1) {\n throw new Error(\n `The encoder outputs have a different batch size (${last_hidden_state.dims[0]}) than the decoder inputs (${decoder_input_ids_batch_size}).`\n )\n }\n last_hidden_state = cat(Array.from({ length: decoder_input_ids_batch_size }, () => last_hidden_state), 0);\n }\n }\n model_inputs['encoder_outputs'] = last_hidden_state;\n\n return model_inputs;\n }\n\n /**\n * Prepares `decoder_input_ids` for generation with encoder-decoder models\n * @param {*} param0 \n */\n _prepare_decoder_input_ids_for_generation({ batch_size, model_input_name, model_kwargs, decoder_start_token_id, bos_token_id, generation_config }) {\n let { decoder_input_ids, ...model_inputs } = model_kwargs;\n\n // Prepare input ids if the user has not defined `decoder_input_ids` manually.\n if (!decoder_input_ids) {\n decoder_start_token_id ??= bos_token_id;\n\n if (this.config.model_type === 'musicgen') {\n // Custom logic (TODO: move to Musicgen class)\n decoder_input_ids = Array.from({\n length: batch_size * this.config.decoder.num_codebooks\n }, () => [decoder_start_token_id]);\n\n } else if (Array.isArray(decoder_start_token_id)) {\n if (decoder_start_token_id.length !== batch_size) {\n throw new Error(\n `\\`decoder_start_token_id\\` expcted to have length ${batch_size} but got ${decoder_start_token_id.length}`\n )\n }\n decoder_input_ids = decoder_start_token_id;\n } else {\n decoder_input_ids = Array.from({\n length: batch_size,\n }, () => [decoder_start_token_id]);\n }\n } else if (!Array.isArray(decoder_input_ids[0])) {\n // Correct batch size\n decoder_input_ids = Array.from({\n length: batch_size,\n }, () => decoder_input_ids);\n }\n\n decoder_input_ids = toI64Tensor(decoder_input_ids);\n model_kwargs['decoder_attention_mask'] = ones_like(decoder_input_ids);\n\n return { input_ids: decoder_input_ids, model_inputs };\n }\n\n /**\n * Generates sequences of token ids for models with a language modeling head.\n * @param {import('./generation/parameters.js').GenerationFunctionParameters} options\n * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores.\n */\n async generate({\n inputs = null,\n generation_config = null,\n logits_processor = null,\n stopping_criteria = null,\n streamer = null,\n\n // inputs_attention_mask = null,\n ...kwargs\n }) {\n this._validate_model_class();\n\n // Update generation config with defaults and kwargs\n generation_config = this._prepare_generation_config(generation_config, kwargs);\n\n // 3. Define model inputs\n let { inputs_tensor, model_inputs, model_input_name } = this._prepare_model_inputs({\n inputs,\n model_kwargs: kwargs,\n });\n\n const is_encoder_decoder = this.config.is_encoder_decoder;\n\n // 4. Define other model kwargs\n if (!is_encoder_decoder) {\n // decoder-only models should use left-padding for generation\n } else if (!('encoder_outputs' in model_inputs)) {\n // if model is encoder decoder encoder_outputs are created\n // and added to `model_kwargs`\n model_inputs = await this._prepare_encoder_decoder_kwargs_for_generation(\n { inputs_tensor, model_inputs, model_input_name, generation_config }\n )\n }\n\n // 5. Prepare `input_ids` which will be used for auto-regressive generation\n // TODO: Update to align with HF transformers' implementation\n let input_ids;\n if (is_encoder_decoder) {\n // Generating from the encoder outputs\n ({ input_ids, model_inputs } = this._prepare_decoder_input_ids_for_generation({\n batch_size: model_inputs[model_input_name].dims.at(0),\n model_input_name,\n model_kwargs: model_inputs,\n decoder_start_token_id: generation_config.decoder_start_token_id,\n bos_token_id: generation_config.bos_token_id,\n generation_config,\n }));\n } else {\n input_ids = model_inputs[model_input_name]\n }\n\n // 6. Prepare `max_length` depending on other stopping criteria.\n let input_ids_length = input_ids.dims.at(-1);\n\n if (generation_config.max_new_tokens !== null) {\n generation_config.max_length = input_ids_length + generation_config.max_new_tokens;\n }\n\n // input_ids_length = model_inputs[model_input_name].dims.at(1);\n // // inputs instanceof Tensor ? : inputs.length;\n\n // // decoder-only\n // if (input_ids_length === 0) {\n // throw Error(\"Must supply a non-empty array of input token ids.\")\n // }\n\n // let decoder_input_ids =\n // generation_config.decoder_input_ids\n // ?? generation_config.decoder_start_token_id\n // ?? generation_config.bos_token_id\n // ?? generation_config.eos_token_id;\n\n // Update logits processor\n // 8. prepare distribution pre_processing samplers\n const prepared_logits_processor = this._get_logits_processor(\n generation_config,\n input_ids_length,\n logits_processor,\n )\n\n // 9. prepare stopping criteria\n const prepared_stopping_criteria = this._get_stopping_criteria(\n generation_config, stopping_criteria\n )\n\n // /** @type {number[]} */\n // let eos_token_ids = generation_config.eos_token_id;\n // if (eos_token_ids !== null && !Array.isArray(eos_token_ids)) {\n // eos_token_ids = [eos_token_ids];\n // }\n\n const numInputs = model_inputs[model_input_name].dims.at(0);\n\n // TODO:\n // done is a list of booleans to keep track of which inputs are done\n // const done = new Array(numInputs).fill(false);\n // For efficiency purposes, we remove completed rows from model_inputs\n // when the beam is complete, and we keep track of the row index\n // const rowIndexToBatchIndex = new Map();\n\n const sampler = LogitsSampler.getSampler(generation_config);\n\n // TODO make > numInputs\n const scores = new Array(numInputs).fill(0);\n /** @type {bigint[][]} */\n const all_input_ids = input_ids.tolist();\n if (streamer) {\n streamer.put(all_input_ids);\n }\n // const all_generated_input_ids = Array.from({ length: numInputs }, () => []);\n\n // NOTE: For now, we don't support spawning new beams\n // TODO: when we do, we simply copy past key values and accumulate into single large tensor\n\n ////////////////////////////////////////////////////\n // Generic search which handles 4 generation modes:\n // - GenerationMode.GREEDY_SEARCH\n // - GenerationMode.SAMPLE\n // - GenerationMode.BEAM_SEARCH\n // - GenerationMode.BEAM_SAMPLE\n ////////////////////////////////////////////////////\n let outputs;\n let attentions = {};\n while (true) {\n // prepare model inputs\n model_inputs = this.prepare_inputs_for_generation(all_input_ids, model_inputs, generation_config);\n outputs = await this.forward(model_inputs);\n\n if (generation_config.output_attentions && generation_config.return_dict_in_generate) {\n // Get attentions if they are present\n const token_attentions = this.getAttentions(outputs);\n for (const key in token_attentions) {\n if (!(key in attentions)) {\n attentions[key] = [];\n }\n attentions[key].push(token_attentions[key]);\n }\n }\n\n // Logits are of the form [batch_size, out_seq_length, vocab_size]\n // In most cases, this will be [batch_size, 1, vocab_size]\n // So, we select the last token's logits:\n // (equivalent to `logits = outputs.logits[:, -1, :]`)\n const logits = outputs.logits.slice(null, -1, null);\n\n const next_tokens_scores = prepared_logits_processor(all_input_ids, logits);\n\n /** @type {[bigint][]} */\n const generated_input_ids = [];\n // const new_kv_cache = [];// NOTE: Only used for beam search when concatenating new kv\n // Loop over each batch\n for (let batch_idx = 0; batch_idx < next_tokens_scores.dims.at(0); ++batch_idx) {\n const logs = next_tokens_scores[batch_idx];\n\n const sampledTokens = await sampler(logs);\n for (const [newTokenId, logProb] of sampledTokens) {\n const bigint = BigInt(newTokenId);\n // TODO: If branching, use previous beam as a starting point\n // update generated ids, model inputs, and length for next step\n scores[batch_idx] += logProb;\n all_input_ids[batch_idx].push(bigint);\n generated_input_ids.push([bigint]);\n\n // TODO: Support beam search\n break;\n }\n }\n if (streamer) {\n streamer.put(generated_input_ids);\n }\n\n const stop = prepared_stopping_criteria(all_input_ids);\n if (stop.every(x => x)) {\n break;\n }\n\n model_inputs = this._update_model_kwargs_for_generation({\n generated_input_ids, outputs, model_inputs, is_encoder_decoder,\n });\n }\n\n if (streamer) {\n streamer.end();\n }\n\n // Retrieve and dispose all final past key values (including encoder attentions)\n const past_key_values = this.getPastKeyValues(outputs, model_inputs.past_key_values, true);\n\n // TODO: ensure all_input_ids is padded correctly...\n const sequences = new Tensor('int64', all_input_ids.flat(), [all_input_ids.length, all_input_ids[0].length]);\n\n if (generation_config.return_dict_in_generate) {\n return {\n sequences,\n past_key_values,\n ...attentions,\n // TODO:\n // scores,\n // logits,\n }\n } else {\n // Dispose all remaining tensors\n for (const tensor of Object.values(outputs)) {\n if (tensor.location === 'gpu-buffer') {\n tensor.dispose();\n }\n }\n return sequences;\n }\n }\n\n /**\n * Returns an object containing past key values from the given decoder results object.\n *\n * @param {Object} decoderResults The decoder results object.\n * @param {Object} pastKeyValues The previous past key values.\n * @returns {Object} An object containing past key values.\n */\n getPastKeyValues(decoderResults, pastKeyValues, disposeEncoderPKVs = false) {\n const pkvs = Object.create(null);\n\n for (const name in decoderResults) {\n if (name.startsWith('present')) {\n const newName = name.replace('present', 'past_key_values');\n const is_encoder_pkv = name.includes('encoder');\n if (is_encoder_pkv && pastKeyValues) {\n // Optimization introduced by optimum to reuse past key values.\n // So, we just replace the constant outputs (`decoderResults[name]`) with the previous past key values.\n // https://github.com/huggingface/optimum/blob/0bf2c05fb7e1182b52d21b703cfc95fd9e4ea3dc/optimum/onnxruntime/base.py#L677-L704\n pkvs[newName] = pastKeyValues[newName];\n } else { // decoder or using first encoder PKVs\n pkvs[newName] = decoderResults[name];\n }\n\n if (pastKeyValues && (!is_encoder_pkv || disposeEncoderPKVs)) {\n // - Always dispose decoder PKVs\n // - Only dispose encoder past key values when requested (after generation)\n const t = pastKeyValues[newName];\n if (t.location === 'gpu-buffer') {\n t.dispose();\n }\n }\n }\n }\n return pkvs;\n }\n\n /**\n * Returns an object containing attentions from the given model output object.\n *\n * @param {Object} model_output The output of the model.\n * @returns {{cross_attentions?: Tensor[]}} An object containing attentions.\n */\n getAttentions(model_output) {\n const attentions = {};\n\n for (const attnName of ['cross_attentions', 'encoder_attentions', 'decoder_attentions']) {\n for (const name in model_output) {\n if (name.startsWith(attnName)) {\n if (!(attnName in attentions)) {\n attentions[attnName] = [];\n }\n attentions[attnName].push(model_output[name]);\n }\n }\n }\n return attentions;\n }\n\n /**\n * Adds past key values to the decoder feeds object. If pastKeyValues is null, creates new tensors for past key values.\n *\n * @param {Object} decoderFeeds The decoder feeds object to add past key values to.\n * @param {Object} pastKeyValues An object containing past key values.\n */\n addPastKeyValues(decoderFeeds, pastKeyValues) {\n if (pastKeyValues) {\n Object.assign(decoderFeeds, pastKeyValues)\n } else {\n const session = this.sessions['decoder_model_merged'] ?? this.sessions['model'];\n const dtype = session?.config?.kv_cache_dtype ?? 'float32';\n const empty = (dtype === 'float16') ? new Uint16Array() : [];\n\n const shapes = getKeyValueShapes(this.config);\n\n for (const name in shapes) {\n decoderFeeds[name] = new Tensor(dtype, empty, shapes[name]);\n }\n }\n }\n\n async encode_image({ pixel_values }) {\n // image_inputs === { pixel_values }\n const features = (await sessionRun(this.sessions['vision_encoder'], { pixel_values })).image_features;\n if (!this.config.num_image_tokens) {\n console.warn(\n 'The number of image tokens was not set in the model configuration. ' +\n `Setting it to the number of features detected by the vision encoder (${features.dims[1]}).`\n )\n this.config.num_image_tokens = features.dims[1];\n }\n return features;\n }\n\n async encode_text({ input_ids }) {\n // text_inputs === { input_ids, attention_mask }\n return (await sessionRun(this.sessions['embed_tokens'], { input_ids })).inputs_embeds;\n }\n}\n\n//////////////////////////////////////////////////\n// Base model output class\nexport class ModelOutput { }\n\n/**\n * Base class for model's outputs, with potential hidden states and attentions.\n */\nexport class BaseModelOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.last_hidden_state Sequence of hidden-states at the output of the last layer of the model.\n * @param {Tensor} [output.hidden_states] Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.\n * @param {Tensor} [output.attentions] Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n */\n constructor({ last_hidden_state, hidden_states = null, attentions = null }) {\n super();\n this.last_hidden_state = last_hidden_state;\n this.hidden_states = hidden_states;\n this.attentions = attentions;\n }\n}\n//////////////////////////////////////////////////\n// Bert models\nexport class BertPreTrainedModel extends PreTrainedModel { }\nexport class BertModel extends BertPreTrainedModel { }\n\n/**\n * BertForMaskedLM is a class representing a BERT model for masked language modeling.\n */\nexport class BertForMaskedLM extends BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * BertForSequenceClassification is a class representing a BERT model for sequence classification.\n */\nexport class BertForSequenceClassification extends BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * BertForTokenClassification is a class representing a BERT model for token classification.\n */\nexport class BertForTokenClassification extends BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * BertForQuestionAnswering is a class representing a BERT model for question answering.\n */\nexport class BertForQuestionAnswering extends BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// NomicBert models\nexport class NomicBertPreTrainedModel extends PreTrainedModel { }\nexport class NomicBertModel extends NomicBertPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// RoFormer models\nexport class RoFormerPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare RoFormer Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class RoFormerModel extends RoFormerPreTrainedModel { }\n\n/**\n * RoFormer Model with a `language modeling` head on top.\n */\nexport class RoFormerForMaskedLM extends RoFormerPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RoFormer Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class RoFormerForSequenceClassification extends RoFormerPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RoFormer Model with a token classification head on top (a linear layer on top of the hidden-states output)\n * e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class RoFormerForTokenClassification extends RoFormerPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RoFormer Model with a span classification head on top for extractive question-answering tasks like SQuAD\n * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n */\nexport class RoFormerForQuestionAnswering extends RoFormerPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n// TODO: Add RoFormerForCausalLM and RoFormerForMultipleChoice\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// ConvBert models\nexport class ConvBertPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ConvBERT Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class ConvBertModel extends ConvBertPreTrainedModel { }\n\n/**\n * ConvBERT Model with a language modeling head on top.\n */\nexport class ConvBertForMaskedLM extends ConvBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ConvBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class ConvBertForSequenceClassification extends ConvBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ConvBERT Model with a token classification head on top (a linear layer on top of the hidden-states output)\n * e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class ConvBertForTokenClassification extends ConvBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ConvBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD\n * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`)\n */\nexport class ConvBertForQuestionAnswering extends ConvBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Electra models\nexport class ElectraPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Electra Model transformer outputting raw hidden-states without any specific head on top.\n * Identical to the BERT model except that it uses an additional linear layer between the embedding\n * layer and the encoder if the hidden size and embedding size are different.\n */\nexport class ElectraModel extends ElectraPreTrainedModel { }\n// TODO add ElectraForPreTraining\n/**\n * Electra model with a language modeling head on top.\n */\nexport class ElectraForMaskedLM extends ElectraPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ELECTRA Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class ElectraForSequenceClassification extends ElectraPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * Electra model with a token classification head on top.\n */\nexport class ElectraForTokenClassification extends ElectraPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * LECTRA Model with a span classification head on top for extractive question-answering tasks like SQuAD\n * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n */\nexport class ElectraForQuestionAnswering extends ElectraPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// CamemBERT models\nexport class CamembertPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare CamemBERT Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class CamembertModel extends CamembertPreTrainedModel { }\n\n/**\n * CamemBERT Model with a `language modeling` head on top.\n */\nexport class CamembertForMaskedLM extends CamembertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * CamemBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.\n */\nexport class CamembertForSequenceClassification extends CamembertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * CamemBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class CamembertForTokenClassification extends CamembertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * CamemBERT Model with a span classification head on top for extractive question-answering tasks\n */\nexport class CamembertForQuestionAnswering extends CamembertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// DeBERTa models\nexport class DebertaPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare DeBERTa Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class DebertaModel extends DebertaPreTrainedModel { }\n\n/**\n * DeBERTa Model with a `language modeling` head on top.\n */\nexport class DebertaForMaskedLM extends DebertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class DebertaForSequenceClassification extends DebertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class DebertaForTokenClassification extends DebertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear\n * layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n */\nexport class DebertaForQuestionAnswering extends DebertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// DeBERTa-v2 models\nexport class DebertaV2PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare DeBERTa-V2 Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class DebertaV2Model extends DebertaV2PreTrainedModel { }\n\n/**\n * DeBERTa-V2 Model with a `language modeling` head on top.\n */\nexport class DebertaV2ForMaskedLM extends DebertaV2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa-V2 Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class DebertaV2ForSequenceClassification extends DebertaV2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa-V2 Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class DebertaV2ForTokenClassification extends DebertaV2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa-V2 Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear\n * layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n */\nexport class DebertaV2ForQuestionAnswering extends DebertaV2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// DistilBert models\nexport class DistilBertPreTrainedModel extends PreTrainedModel { }\nexport class DistilBertModel extends DistilBertPreTrainedModel { }\n\n/**\n * DistilBertForSequenceClassification is a class representing a DistilBERT model for sequence classification.\n */\nexport class DistilBertForSequenceClassification extends DistilBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DistilBertForTokenClassification is a class representing a DistilBERT model for token classification.\n */\nexport class DistilBertForTokenClassification extends DistilBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n\n/**\n * DistilBertForQuestionAnswering is a class representing a DistilBERT model for question answering.\n */\nexport class DistilBertForQuestionAnswering extends DistilBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DistilBertForMaskedLM is a class representing a DistilBERT model for masking task.\n */\nexport class DistilBertForMaskedLM extends DistilBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// ESM models\nexport class EsmPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ESM Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class EsmModel extends EsmPreTrainedModel { }\n\n/**\n * ESM Model with a `language modeling` head on top.\n */\nexport class EsmForMaskedLM extends EsmPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ESM Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class EsmForSequenceClassification extends EsmPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ESM Model with a token classification head on top (a linear layer on top of the hidden-states output)\n * e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class EsmForTokenClassification extends EsmPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// MobileBert models\nexport class MobileBertPreTrainedModel extends PreTrainedModel { }\nexport class MobileBertModel extends MobileBertPreTrainedModel { }\n\n/**\n * MobileBertForMaskedLM is a class representing a MobileBERT model for masking task.\n */\nexport class MobileBertForMaskedLM extends MobileBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class MobileBertForSequenceClassification extends MobileBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MobileBert Model with a span classification head on top for extractive question-answering tasks\n */\nexport class MobileBertForQuestionAnswering extends MobileBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MPNet models\nexport class MPNetPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MPNet Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class MPNetModel extends MPNetPreTrainedModel { }\n\n/**\n * MPNetForMaskedLM is a class representing a MPNet model for masked language modeling.\n */\nexport class MPNetForMaskedLM extends MPNetPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MPNetForSequenceClassification is a class representing a MPNet model for sequence classification.\n */\nexport class MPNetForSequenceClassification extends MPNetPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MPNetForTokenClassification is a class representing a MPNet model for token classification.\n */\nexport class MPNetForTokenClassification extends MPNetPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MPNetForQuestionAnswering is a class representing a MPNet model for question answering.\n */\nexport class MPNetForQuestionAnswering extends MPNetPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// SqueezeBert models\nexport class SqueezeBertPreTrainedModel extends PreTrainedModel { }\nexport class SqueezeBertModel extends SqueezeBertPreTrainedModel { }\nexport class SqueezeBertForMaskedLM extends SqueezeBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\nexport class SqueezeBertForSequenceClassification extends SqueezeBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\nexport class SqueezeBertForQuestionAnswering extends SqueezeBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Albert models\nexport class AlbertPreTrainedModel extends PreTrainedModel { }\nexport class AlbertModel extends AlbertPreTrainedModel { }\nexport class AlbertForSequenceClassification extends AlbertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\nexport class AlbertForQuestionAnswering extends AlbertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\nexport class AlbertForMaskedLM extends AlbertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// T5 models\nexport class T5PreTrainedModel extends PreTrainedModel {\n forward_params = [\n 'input_ids',\n 'attention_mask',\n 'encoder_outputs',\n 'decoder_input_ids',\n 'decoder_attention_mask',\n 'past_key_values',\n ];\n};\n\nexport class T5Model extends T5PreTrainedModel { }\n\n/**\n * T5Model is a class representing a T5 model for conditional generation.\n */\nexport class T5ForConditionalGeneration extends T5PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// LONGT5 models\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class LongT5PreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare LONGT5 Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class LongT5Model extends LongT5PreTrainedModel { }\n\n/**\n * LONGT5 Model with a `language modeling` head on top.\n */\nexport class LongT5ForConditionalGeneration extends LongT5PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// MT5 models\nexport class MT5PreTrainedModel extends PreTrainedModel { };\n\nexport class MT5Model extends MT5PreTrainedModel { }\n\n/**\n * A class representing a conditional sequence-to-sequence model based on the MT5 architecture.\n */\nexport class MT5ForConditionalGeneration extends MT5PreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Bart models\nexport class BartPretrainedModel extends PreTrainedModel { };\n\n/**\n * The bare BART Model outputting raw hidden-states without any specific head on top.\n */\nexport class BartModel extends BartPretrainedModel { }\n\n/**\n * The BART Model with a language modeling head. Can be used for summarization.\n */\nexport class BartForConditionalGeneration extends BartPretrainedModel { }\n\n/**\n * Bart model with a sequence classification/head on top (a linear layer on top of the pooled output)\n */\nexport class BartForSequenceClassification extends BartPretrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MBart models\nexport class MBartPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare MBART Model outputting raw hidden-states without any specific head on top.\n */\nexport class MBartModel extends MBartPreTrainedModel { }\n\n/**\n * The MBART Model with a language modeling head. Can be used for summarization, after fine-tuning the pretrained models.\n */\nexport class MBartForConditionalGeneration extends MBartPreTrainedModel { }\n\n/**\n * MBart model with a sequence classification/head on top (a linear layer on top of the pooled output).\n */\nexport class MBartForSequenceClassification extends MBartPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n\nexport class MBartForCausalLM extends MBartPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Blenderbot models\nexport class BlenderbotPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare Blenderbot Model outputting raw hidden-states without any specific head on top.\n */\nexport class BlenderbotModel extends BlenderbotPreTrainedModel { }\n\n/**\n * The Blenderbot Model with a language modeling head. Can be used for summarization.\n */\nexport class BlenderbotForConditionalGeneration extends BlenderbotPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Blenderbot models\nexport class BlenderbotSmallPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare BlenderbotSmall Model outputting raw hidden-states without any specific head on top.\n */\nexport class BlenderbotSmallModel extends BlenderbotSmallPreTrainedModel { }\n\n/**\n * The BlenderbotSmall Model with a language modeling head. Can be used for summarization.\n */\nexport class BlenderbotSmallForConditionalGeneration extends BlenderbotSmallPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Roberta models\nexport class RobertaPreTrainedModel extends PreTrainedModel { }\nexport class RobertaModel extends RobertaPreTrainedModel { }\n\n/**\n * RobertaForMaskedLM class for performing masked language modeling on Roberta models.\n */\nexport class RobertaForMaskedLM extends RobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RobertaForSequenceClassification class for performing sequence classification on Roberta models.\n */\nexport class RobertaForSequenceClassification extends RobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RobertaForTokenClassification class for performing token classification on Roberta models.\n */\nexport class RobertaForTokenClassification extends RobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RobertaForQuestionAnswering class for performing question answering on Roberta models.\n */\nexport class RobertaForQuestionAnswering extends RobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// XLM models\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class XLMPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare XLM Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class XLMModel extends XLMPreTrainedModel { }\n\n/**\n * The XLM Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class XLMWithLMHeadModel extends XLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLM Model with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class XLMForSequenceClassification extends XLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLM Model with a token classification head on top (a linear layer on top of the hidden-states output)\n */\nexport class XLMForTokenClassification extends XLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLM Model with a span classification head on top for extractive question-answering tasks\n */\nexport class XLMForQuestionAnswering extends XLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// XLMRoberta models\nexport class XLMRobertaPreTrainedModel extends PreTrainedModel { }\nexport class XLMRobertaModel extends XLMRobertaPreTrainedModel { }\n\n/**\n * XLMRobertaForMaskedLM class for performing masked language modeling on XLMRoberta models.\n */\nexport class XLMRobertaForMaskedLM extends XLMRobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLMRobertaForSequenceClassification class for performing sequence classification on XLMRoberta models.\n */\nexport class XLMRobertaForSequenceClassification extends XLMRobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLMRobertaForTokenClassification class for performing token classification on XLMRoberta models.\n */\nexport class XLMRobertaForTokenClassification extends XLMRobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLMRobertaForQuestionAnswering class for performing question answering on XLMRoberta models.\n */\nexport class XLMRobertaForQuestionAnswering extends XLMRobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Audio Spectrogram Transformer (AST) models\nexport class ASTPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare AST Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class ASTModel extends ASTPreTrainedModel { }\n\n/**\n * Audio Spectrogram Transformer model with an audio classification head on top\n * (a linear layer on top of the pooled output) e.g. for datasets like AudioSet, Speech Commands v2.\n */\nexport class ASTForAudioClassification extends ASTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Whisper models\nexport class WhisperPreTrainedModel extends PreTrainedModel {\n\n requires_attention_mask = false;\n main_input_name = 'input_features';\n forward_params = [\n 'input_features',\n 'attention_mask',\n 'decoder_input_ids',\n 'decoder_attention_mask',\n 'past_key_values',\n ];\n};\n\n/**\n * WhisperModel class for training Whisper models without a language model head.\n */\nexport class WhisperModel extends WhisperPreTrainedModel { }\n\n\n/**\n * WhisperForConditionalGeneration class for generating conditional outputs from Whisper models.\n */\nexport class WhisperForConditionalGeneration extends WhisperPreTrainedModel {\n\n _prepare_generation_config(generation_config, kwargs) {\n return /** @type {WhisperGenerationConfig} */ (super._prepare_generation_config(generation_config, kwargs, WhisperGenerationConfig));\n }\n\n /**\n * \n * @param {WhisperGenerationConfig} generation_config \n */\n _retrieve_init_tokens(generation_config) {\n // prefix tokens are of the form: \n // - Multilingual: <|startoftranscript|> <|lang_id|> <|task|> [<|notimestamps|>]\n // - English-only: <|startoftranscript|> [<|notimestamps|>]\n\n // 1. Handle <|startoftranscript|> token\n const init_tokens = [generation_config.decoder_start_token_id];\n\n // 2. Handle <|lang_id|> and <|task> tokens\n let language = generation_config.language;\n const task = generation_config.task;\n if (generation_config.is_multilingual) {\n if (!language) {\n // TODO: Implement language detection\n console.warn('No language specified - defaulting to English (en).');\n language = 'en';\n }\n\n // Add language token\n const language_code = whisper_language_to_code(language);\n const language_token = `<|${language_code}|>`;\n init_tokens.push(generation_config.lang_to_id[language_token])\n\n // Add task token\n // NOTE: Defaults to 'transcribe' if no task is specified\n init_tokens.push(generation_config.task_to_id[task ?? 'transcribe']);\n\n } else if (language || task) {\n throw new Error(\n \"Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.\"\n )\n }\n\n // 3. Handle <|notimestamps|> token\n if (\n !generation_config.return_timestamps\n && generation_config.no_timestamps_token_id\n && init_tokens.at(-1) !== generation_config.no_timestamps_token_id\n ) {\n init_tokens.push(generation_config.no_timestamps_token_id);\n } else if (\n generation_config.return_timestamps\n &&\n init_tokens.at(-1) === generation_config.no_timestamps_token_id\n ) {\n console.warn(\"<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`.\");\n init_tokens.pop();\n }\n\n // let's make sure we don't pass `null` tokens as prompt tokens\n return init_tokens.filter(token => token != null);\n }\n\n /**\n * Transcribes or translates log-mel input features to a sequence of auto-regressively generated token ids.\n * @param {import('./models/whisper/generation_whisper.js').WhisperGenerationFunctionParameters} options\n * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores.\n */\n async generate({\n inputs = null,\n generation_config = null,\n logits_processor = null,\n stopping_criteria = null,\n\n // Whisper-specific options (passed to kwargs)\n // prompt_ids = null,\n // language = null,\n // task = null,\n\n ...kwargs\n }) {\n generation_config = this._prepare_generation_config(generation_config, kwargs);\n\n const init_tokens = kwargs.decoder_input_ids ?? this._retrieve_init_tokens(generation_config);\n\n if (generation_config.return_timestamps) {\n logits_processor ??= new LogitsProcessorList();\n logits_processor.push(\n new WhisperTimeStampLogitsProcessor(generation_config, init_tokens)\n );\n }\n\n if (generation_config.begin_suppress_tokens) {\n logits_processor ??= new LogitsProcessorList();\n logits_processor.push(\n new SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, init_tokens.length)\n );\n }\n\n if (generation_config.return_token_timestamps) {\n if (!generation_config.alignment_heads) {\n throw new Error(\n \"Model generation config has no `alignment_heads`, token-level timestamps not available. \" +\n \"See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.\"\n )\n }\n\n if (generation_config.task === 'translate') {\n console.warn(\"Token-level timestamps may not be reliable for task 'translate'.\")\n }\n\n generation_config.output_attentions = true;\n generation_config.return_dict_in_generate = true;\n }\n\n const outputs = await super.generate({\n inputs,\n generation_config,\n logits_processor,\n decoder_input_ids: init_tokens,\n ...kwargs\n });\n\n if (generation_config.return_token_timestamps) {\n outputs[\"token_timestamps\"] = this._extract_token_timestamps(\n outputs,\n generation_config.alignment_heads,\n generation_config.num_frames,\n );\n }\n\n return outputs;\n }\n\n /**\n * Calculates token-level timestamps using the encoder-decoder cross-attentions and\n * dynamic time-warping (DTW) to map each output token to a position in the input audio.\n * If `num_frames` is specified, the encoder-decoder cross-attentions will be cropped before applying DTW.\n * @param {Object} generate_outputs Outputs generated by the model\n * @param {Tensor[][]} generate_outputs.cross_attentions The cross attentions output by the model\n * @param {Tensor} generate_outputs.sequences The sequences output by the model\n * @param {number[][]} alignment_heads Alignment heads of the model\n * @param {number} [num_frames=null] Number of frames in the input audio.\n * @param {number} [time_precision=0.02] Precision of the timestamps in seconds\n * @returns {Tensor} tensor containing the timestamps in seconds for each predicted token\n */\n _extract_token_timestamps(generate_outputs, alignment_heads, num_frames = null, time_precision = 0.02) {\n if (!generate_outputs.cross_attentions) {\n throw new Error(\n \"Model outputs must contain cross attentions to extract timestamps. \" +\n \"This is most likely because the model was not exported with `output_attentions=True`.\"\n )\n }\n if (num_frames == null) {\n console.warn(\n \"`num_frames` has not been set, meaning the entire audio will be analyzed. \" +\n \"This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).\"\n );\n }\n\n let median_filter_width = this.config.median_filter_width;\n if (median_filter_width === undefined) {\n console.warn(\"Model config has no `median_filter_width`, using default value of 7.\")\n median_filter_width = 7;\n }\n\n // TODO: Improve batch processing\n const batch = generate_outputs.cross_attentions;\n // Create a list with `decoder_layers` elements, each a tensor of shape\n // (batch size, attention_heads, output length, input length).\n const cross_attentions = Array.from({ length: this.config.decoder_layers },\n // Concatenate the cross attentions for each layer across sequence length dimension.\n (_, i) => cat(batch.map(x => x[i]), 2)\n );\n\n const weights = stack(alignment_heads.map(([l, h]) => {\n if (l >= cross_attentions.length) {\n throw new Error(`Layer index ${l} is out of bounds for cross attentions (length ${cross_attentions.length}).`)\n }\n return num_frames\n ? cross_attentions[l].slice(null, h, null, [0, num_frames])\n : cross_attentions[l].slice(null, h);\n })).transpose(1, 0, 2, 3);\n\n const [std, calculatedMean] = std_mean(weights, -2, 0, true);\n\n // Normalize and smoothen the weights.\n const smoothedWeights = weights.clone(); // [1, 8, seqLength, 1500]\n\n for (let a = 0; a < smoothedWeights.dims[0]; ++a) {\n const aTensor = smoothedWeights[a]; // [8, seqLength, 1500]\n\n for (let b = 0; b < aTensor.dims[0]; ++b) {\n const bTensor = aTensor[b]; // [seqLength, 1500]\n\n const stdTensorData = std[a][b][0].data; // [1500]\n const meanTensorData = calculatedMean[a][b][0].data; // [1500]\n\n for (let c = 0; c < bTensor.dims[0]; ++c) {\n\n let cTensorData = bTensor[c].data; // [1500]\n for (let d = 0; d < cTensorData.length; ++d) {\n cTensorData[d] = (cTensorData[d] - meanTensorData[d]) / stdTensorData[d]\n }\n\n // Apply median filter.\n cTensorData.set(medianFilter(cTensorData, median_filter_width))\n }\n }\n }\n\n // Average the different cross-attention heads.\n const batchedMatrices = [mean(smoothedWeights, 1)];\n\n const timestampsShape = generate_outputs.sequences.dims;\n\n const timestamps = new Tensor(\n 'float32',\n new Float32Array(timestampsShape[0] * timestampsShape[1]),\n timestampsShape\n );\n\n // Perform dynamic time warping on each element of the batch.\n for (let batch_idx = 0; batch_idx < timestampsShape[0]; ++batch_idx) {\n // NOTE: Since we run only one batch at a time, we can squeeze to get the same dimensions\n // as the python implementation\n const matrix = batchedMatrices[batch_idx].neg().squeeze_(0);\n const [text_indices, time_indices] = dynamic_time_warping(matrix.tolist());\n\n const diffs = Array.from({ length: text_indices.length - 1 }, (v, i) => text_indices[i + 1] - text_indices[i]);\n const jumps = mergeArrays([1], diffs).map(x => !!x); // convert to boolean\n\n const jump_times = [];\n for (let i = 0; i < jumps.length; ++i) {\n if (jumps[i]) {\n // NOTE: No point in rounding here, since we set to Float32Array later\n jump_times.push(time_indices[i] * time_precision);\n }\n }\n timestamps[batch_idx].data.set(jump_times, 1)\n }\n\n return timestamps;\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n/**\n * Vision Encoder-Decoder model based on OpenAI's GPT architecture for image captioning and other vision tasks\n */\nexport class VisionEncoderDecoderModel extends PreTrainedModel {\n main_input_name = 'pixel_values';\n forward_params = [\n 'pixel_values',\n 'input_ids',\n 'encoder_hidden_states',\n 'past_key_values',\n ];\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// LLaVa Models\nexport class LlavaPreTrainedModel extends PreTrainedModel {\n forward_params = [\n 'input_ids',\n 'pixel_values',\n 'attention_mask',\n 'position_ids',\n 'past_key_values',\n ];\n}\n\n/**\n * The LLAVA model which consists of a vision backbone and a language model.\n */\nexport class LlavaForConditionalGeneration extends LlavaPreTrainedModel {\n\n _merge_input_ids_with_image_features({\n inputs_embeds,\n image_features,\n input_ids,\n attention_mask,\n }) {\n\n const image_token_index = this.config.image_token_index;\n\n const idsList = input_ids.tolist();\n\n // NOTE: we use .findIndex instead of .indexOf to perform weak comparison (==) between BigInt and Number\n const indexOfImage = idsList.map(x => x.findIndex(x => x == image_token_index));\n\n const noImages = indexOfImage.every(x => x === -1);\n const allImages = indexOfImage.every(x => x !== -1);\n if (!noImages && !allImages) {\n // Check for padding reasons\n throw new Error('Every input should contain either 0 or 1 image token.');\n }\n\n if (noImages) {\n return {\n inputs_embeds,\n attention_mask,\n }\n }\n\n const stacked = [];\n const stacked_attention_mask = [];\n for (let i = 0; i < indexOfImage.length; ++i) {\n const index = indexOfImage[i];\n\n const e = inputs_embeds[i];\n const im = image_features[i];\n const am = attention_mask[i];\n stacked.push(\n cat([\n e.slice([0, index]),\n im,\n e.slice([index + 1, e.dims[0]]),\n ], 0)\n );\n\n stacked_attention_mask.push(\n cat([\n am.slice([0, index]),\n ones([im.dims[0]]),\n am.slice([index + 1, am.dims[0]])\n ], 0)\n )\n }\n\n return {\n inputs_embeds: stack(stacked, 0),\n attention_mask: stack(stacked_attention_mask, 0),\n }\n }\n}\n//////////////////////////////////////////////////\n\nexport class Moondream1ForConditionalGeneration extends LlavaForConditionalGeneration { } // NOTE: extends LlavaForConditionalGeneration\n\nexport class Florence2PreTrainedModel extends PreTrainedModel {\n forward_params = [\n // Encoder inputs\n 'input_ids',\n 'inputs_embeds',\n 'attention_mask',\n 'pixel_values',\n\n // Decoder inputs\n 'encoder_outputs',\n 'decoder_input_ids',\n 'decoder_inputs_embeds',\n 'decoder_attention_mask',\n 'past_key_values',\n ];\n main_input_name = 'inputs_embeds';\n}\n\nexport class Florence2ForConditionalGeneration extends Florence2PreTrainedModel {\n\n _merge_input_ids_with_image_features({\n inputs_embeds,\n image_features,\n input_ids,\n attention_mask,\n }) {\n return {\n inputs_embeds: cat([\n image_features, // image embeds\n inputs_embeds, // task prefix embeds\n ], 1),\n attention_mask: cat([\n ones(image_features.dims.slice(0, 2)), // image attention mask\n attention_mask, // task prefix attention mask\n ], 1),\n }\n }\n\n async _prepare_inputs_embeds({ input_ids, pixel_values, inputs_embeds, attention_mask }) {\n if (!input_ids && !pixel_values) {\n throw new Error('Either `input_ids` or `pixel_values` should be provided.');\n }\n\n // 1. Possibly, extract the input embeddings\n let text_features, image_features;\n if (input_ids) {\n text_features = await this.encode_text({ input_ids });\n }\n if (pixel_values) {\n image_features = await this.encode_image({ pixel_values });\n }\n\n // 2. Possibly, merge text and images\n if (text_features && image_features) {\n ({ inputs_embeds, attention_mask } = this._merge_input_ids_with_image_features({\n inputs_embeds: text_features,\n image_features,\n input_ids,\n attention_mask,\n }));\n } else {\n inputs_embeds = text_features || image_features;\n }\n\n return { inputs_embeds, attention_mask };\n }\n\n async forward({\n input_ids,\n pixel_values,\n attention_mask,\n decoder_input_ids,\n decoder_attention_mask,\n encoder_outputs,\n past_key_values,\n\n inputs_embeds,\n decoder_inputs_embeds,\n }) {\n if (!inputs_embeds) {\n ({ inputs_embeds, attention_mask } = await this._prepare_inputs_embeds({ input_ids, pixel_values, inputs_embeds, attention_mask }));\n }\n\n if (!encoder_outputs) {\n // Must compute encoder outputs\n let { last_hidden_state } = await encoderForward(this, { inputs_embeds, attention_mask });\n encoder_outputs = last_hidden_state;\n }\n\n if (!decoder_inputs_embeds) {\n if (!decoder_input_ids) {\n throw new Error('Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.');\n }\n decoder_inputs_embeds = await this.encode_text({ input_ids: decoder_input_ids });\n }\n\n const decoderFeeds = {\n inputs_embeds: decoder_inputs_embeds,\n attention_mask: decoder_attention_mask,\n encoder_attention_mask: attention_mask,\n encoder_hidden_states: encoder_outputs,\n past_key_values,\n };\n const decoder_outputs = await decoderForward(this, decoderFeeds, true);\n return decoder_outputs;\n }\n}\nexport class CLIPPreTrainedModel extends PreTrainedModel { }\n\n/**\n * CLIP Text and Vision Model with a projection layers on top\n * \n * **Example:** Perform zero-shot image classification with a `CLIPModel`.\n * \n * ```javascript\n * import { AutoTokenizer, AutoProcessor, CLIPModel, RawImage } from '@huggingface/transformers';\n * \n * // Load tokenizer, processor, and model\n * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/clip-vit-base-patch16');\n * let processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16');\n * let model = await CLIPModel.from_pretrained('Xenova/clip-vit-base-patch16');\n * \n * // Run tokenization\n * let texts = ['a photo of a car', 'a photo of a football match']\n * let text_inputs = tokenizer(texts, { padding: true, truncation: true });\n * \n * // Read image and run processor\n * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * let image_inputs = await processor(image);\n * \n * // Run model with both text and pixel inputs\n * let output = await model({ ...text_inputs, ...image_inputs });\n * // {\n * // logits_per_image: Tensor {\n * // dims: [ 1, 2 ],\n * // data: Float32Array(2) [ 18.579734802246094, 24.31830596923828 ],\n * // },\n * // logits_per_text: Tensor {\n * // dims: [ 2, 1 ],\n * // data: Float32Array(2) [ 18.579734802246094, 24.31830596923828 ],\n * // },\n * // text_embeds: Tensor {\n * // dims: [ 2, 512 ],\n * // data: Float32Array(1024) [ ... ],\n * // },\n * // image_embeds: Tensor {\n * // dims: [ 1, 512 ],\n * // data: Float32Array(512) [ ... ],\n * // }\n * // }\n * ```\n */\nexport class CLIPModel extends CLIPPreTrainedModel { }\n\n/**\n * The text model from CLIP without any head or projection on top.\n */\nexport class CLIPTextModel extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'text_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * CLIP Text Model with a projection layer on top (a linear layer on top of the pooled output)\n * \n * **Example:** Compute text embeddings with `CLIPTextModelWithProjection`.\n * \n * ```javascript\n * import { AutoTokenizer, CLIPTextModelWithProjection } from '@huggingface/transformers';\n * \n * // Load tokenizer and text model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clip-vit-base-patch16');\n * const text_model = await CLIPTextModelWithProjection.from_pretrained('Xenova/clip-vit-base-patch16');\n * \n * // Run tokenization\n * let texts = ['a photo of a car', 'a photo of a football match'];\n * let text_inputs = tokenizer(texts, { padding: true, truncation: true });\n * \n * // Compute embeddings\n * const { text_embeds } = await text_model(text_inputs);\n * // Tensor {\n * // dims: [ 2, 512 ],\n * // type: 'float32',\n * // data: Float32Array(1024) [ ... ],\n * // size: 1024\n * // }\n * ```\n */\nexport class CLIPTextModelWithProjection extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'text_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * The vision model from CLIP without any head or projection on top.\n */\nexport class CLIPVisionModel extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'vision_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * CLIP Vision Model with a projection layer on top (a linear layer on top of the pooled output)\n * \n * **Example:** Compute vision embeddings with `CLIPVisionModelWithProjection`.\n * \n * ```javascript\n * import { AutoProcessor, CLIPVisionModelWithProjection, RawImage} from '@huggingface/transformers';\n * \n * // Load processor and vision model\n * const processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16');\n * const vision_model = await CLIPVisionModelWithProjection.from_pretrained('Xenova/clip-vit-base-patch16');\n * \n * // Read image and run processor\n * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * let image_inputs = await processor(image);\n * \n * // Compute embeddings\n * const { image_embeds } = await vision_model(image_inputs);\n * // Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [ ... ],\n * // size: 512\n * // }\n * ```\n */\nexport class CLIPVisionModelWithProjection extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'vision_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// SigLIP models\nexport class SiglipPreTrainedModel extends PreTrainedModel { }\n\n/**\n * SigLIP Text and Vision Model with a projection layers on top\n * \n * **Example:** Perform zero-shot image classification with a `SiglipModel`.\n * \n * ```javascript\n * import { AutoTokenizer, AutoProcessor, SiglipModel, RawImage } from '@huggingface/transformers';\n * \n * // Load tokenizer, processor, and model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/siglip-base-patch16-224');\n * const processor = await AutoProcessor.from_pretrained('Xenova/siglip-base-patch16-224');\n * const model = await SiglipModel.from_pretrained('Xenova/siglip-base-patch16-224');\n * \n * // Run tokenization\n * const texts = ['a photo of 2 cats', 'a photo of 2 dogs'];\n * const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true });\n * \n * // Read image and run processor\n * const image = await RawImage.read('http://images.cocodataset.org/val2017/000000039769.jpg');\n * const image_inputs = await processor(image);\n * \n * // Run model with both text and pixel inputs\n * const output = await model({ ...text_inputs, ...image_inputs });\n * // {\n * // logits_per_image: Tensor {\n * // dims: [ 1, 2 ],\n * // data: Float32Array(2) [ -1.6019744873046875, -10.720091819763184 ],\n * // },\n * // logits_per_text: Tensor {\n * // dims: [ 2, 1 ],\n * // data: Float32Array(2) [ -1.6019744873046875, -10.720091819763184 ],\n * // },\n * // text_embeds: Tensor {\n * // dims: [ 2, 768 ],\n * // data: Float32Array(1536) [ ... ],\n * // },\n * // image_embeds: Tensor {\n * // dims: [ 1, 768 ],\n * // data: Float32Array(768) [ ... ],\n * // }\n * // }\n * ```\n */\nexport class SiglipModel extends SiglipPreTrainedModel { }\n\n/**\n * The text model from SigLIP without any head or projection on top.\n * \n * **Example:** Compute text embeddings with `SiglipTextModel`.\n * \n * ```javascript\n * import { AutoTokenizer, SiglipTextModel } from '@huggingface/transformers';\n * \n * // Load tokenizer and text model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/siglip-base-patch16-224');\n * const text_model = await SiglipTextModel.from_pretrained('Xenova/siglip-base-patch16-224');\n * \n * // Run tokenization\n * const texts = ['a photo of 2 cats', 'a photo of 2 dogs'];\n * const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true });\n * \n * // Compute embeddings\n * const { pooler_output } = await text_model(text_inputs);\n * // Tensor {\n * // dims: [ 2, 768 ],\n * // type: 'float32',\n * // data: Float32Array(1536) [ ... ],\n * // size: 1536\n * // }\n * ```\n */\nexport class SiglipTextModel extends SiglipPreTrainedModel {\n\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'text_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * The vision model from SigLIP without any head or projection on top.\n * \n * **Example:** Compute vision embeddings with `SiglipVisionModel`.\n * \n * ```javascript\n * import { AutoProcessor, SiglipVisionModel, RawImage} from '@huggingface/transformers';\n * \n * // Load processor and vision model\n * const processor = await AutoProcessor.from_pretrained('Xenova/siglip-base-patch16-224');\n * const vision_model = await SiglipVisionModel.from_pretrained('Xenova/siglip-base-patch16-224');\n * \n * // Read image and run processor\n * const image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * const image_inputs = await processor(image);\n * \n * // Compute embeddings\n * const { pooler_output } = await vision_model(image_inputs);\n * // Tensor {\n * // dims: [ 1, 768 ],\n * // type: 'float32',\n * // data: Float32Array(768) [ ... ],\n * // size: 768\n * // }\n * ```\n */\nexport class SiglipVisionModel extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'vision_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n//////////////////////////////////////////////////\n// ChineseCLIP models\nexport class ChineseCLIPPreTrainedModel extends PreTrainedModel { }\n\nexport class ChineseCLIPModel extends ChineseCLIPPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// CLIPSeg models\nexport class CLIPSegPreTrainedModel extends PreTrainedModel { }\n\nexport class CLIPSegModel extends CLIPSegPreTrainedModel { }\n\n/**\n * CLIPSeg model with a Transformer-based decoder on top for zero-shot and one-shot image segmentation.\n * \n * **Example:** Perform zero-shot image segmentation with a `CLIPSegForImageSegmentation` model.\n * \n * ```javascript\n * import { AutoTokenizer, AutoProcessor, CLIPSegForImageSegmentation, RawImage } from '@huggingface/transformers';\n * \n * // Load tokenizer, processor, and model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clipseg-rd64-refined');\n * const processor = await AutoProcessor.from_pretrained('Xenova/clipseg-rd64-refined');\n * const model = await CLIPSegForImageSegmentation.from_pretrained('Xenova/clipseg-rd64-refined');\n * \n * // Run tokenization\n * const texts = ['a glass', 'something to fill', 'wood', 'a jar'];\n * const text_inputs = tokenizer(texts, { padding: true, truncation: true });\n * \n * // Read image and run processor\n * const image = await RawImage.read('https://github.com/timojl/clipseg/blob/master/example_image.jpg?raw=true');\n * const image_inputs = await processor(image);\n * \n * // Run model with both text and pixel inputs\n * const { logits } = await model({ ...text_inputs, ...image_inputs });\n * // logits: Tensor {\n * // dims: [4, 352, 352],\n * // type: 'float32',\n * // data: Float32Array(495616) [ ... ],\n * // size: 495616\n * // }\n * ```\n * \n * You can visualize the predictions as follows:\n * ```javascript\n * const preds = logits\n * .unsqueeze_(1)\n * .sigmoid_()\n * .mul_(255)\n * .round_()\n * .to('uint8');\n * \n * for (let i = 0; i < preds.dims[0]; ++i) {\n * const img = RawImage.fromTensor(preds[i]);\n * img.save(`prediction_${i}.png`);\n * }\n * ```\n */\nexport class CLIPSegForImageSegmentation extends CLIPSegPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// GPT2 models\nexport class GPT2PreTrainedModel extends PreTrainedModel { }\n\nexport class GPT2Model extends GPT2PreTrainedModel { }\n\n/**\n * GPT-2 language model head on top of the GPT-2 base model. This model is suitable for text generation tasks.\n */\nexport class GPT2LMHeadModel extends GPT2PreTrainedModel { }\n// export class GPT2ForSequenceClassification extends GPT2PreTrainedModel {\n// TODO\n// }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// JAIS models\nexport class JAISPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare JAIS Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class JAISModel extends JAISPreTrainedModel { }\n\n/**\n * The JAIS Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class JAISLMHeadModel extends JAISPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// GPTNeo models\nexport class GPTNeoPreTrainedModel extends PreTrainedModel { }\nexport class GPTNeoModel extends GPTNeoPreTrainedModel { }\n\nexport class GPTNeoForCausalLM extends GPTNeoPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// GPTNeoX models\nexport class GPTNeoXPreTrainedModel extends PreTrainedModel { }\nexport class GPTNeoXModel extends GPTNeoXPreTrainedModel { }\n\nexport class GPTNeoXForCausalLM extends GPTNeoXPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// GPT-J models\nexport class GPTJPreTrainedModel extends PreTrainedModel { }\n\nexport class GPTJModel extends GPTJPreTrainedModel { }\n\nexport class GPTJForCausalLM extends GPTJPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// GPTBigCode models\nexport class GPTBigCodePreTrainedModel extends PreTrainedModel { }\n\nexport class GPTBigCodeModel extends GPTBigCodePreTrainedModel { }\n\nexport class GPTBigCodeForCausalLM extends GPTBigCodePreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// CodeGen models\nexport class CodeGenPreTrainedModel extends PreTrainedModel { }\n/**\n * CodeGenModel is a class representing a code generation model without a language model head.\n */\nexport class CodeGenModel extends CodeGenPreTrainedModel { }\n\n/**\n * CodeGenForCausalLM is a class that represents a code generation model based on the GPT-2 architecture. It extends the `CodeGenPreTrainedModel` class.\n */\nexport class CodeGenForCausalLM extends CodeGenPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// LLama models\n\n/**\n * The bare LLama Model outputting raw hidden-states without any specific head on top.\n */\nexport class LlamaPreTrainedModel extends PreTrainedModel { }\n/**\n * The bare LLaMA Model outputting raw hidden-states without any specific head on top.\n */\nexport class LlamaModel extends LlamaPreTrainedModel { }\n\nexport class LlamaForCausalLM extends LlamaPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Granite models\nexport class GranitePreTrainedModel extends PreTrainedModel { }\nexport class GraniteModel extends GranitePreTrainedModel { }\nexport class GraniteForCausalLM extends GranitePreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Cohere models\n\n/**\n * The bare Cohere Model outputting raw hidden-states without any specific head on top.\n */\nexport class CoherePreTrainedModel extends PreTrainedModel { }\nexport class CohereModel extends CoherePreTrainedModel { }\n\nexport class CohereForCausalLM extends CoherePreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Gemma models\n\n/**\n * The bare Gemma Model outputting raw hidden-states without any specific head on top.\n */\nexport class GemmaPreTrainedModel extends PreTrainedModel { }\n/**\n * The bare Gemma Model outputting raw hidden-states without any specific head on top.\n */\nexport class GemmaModel extends GemmaPreTrainedModel { }\n\nexport class GemmaForCausalLM extends GemmaPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Gemma2 models\n\n/**\n * The bare Gemma2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Gemma2PreTrainedModel extends PreTrainedModel { }\n/**\n * The bare Gemma2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Gemma2Model extends Gemma2PreTrainedModel { }\n\nexport class Gemma2ForCausalLM extends Gemma2PreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class OpenELMPreTrainedModel extends PreTrainedModel { }\nexport class OpenELMModel extends OpenELMPreTrainedModel { }\n\nexport class OpenELMForCausalLM extends OpenELMPreTrainedModel { }\n\n\n//////////////////////////////////////////////////\n// Qwen2 models\n\n/**\n * The bare Qwen2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Qwen2PreTrainedModel extends PreTrainedModel { }\n/**\n * The bare Qwen2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Qwen2Model extends Qwen2PreTrainedModel { }\n\nexport class Qwen2ForCausalLM extends Qwen2PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Phi models\nexport class PhiPreTrainedModel extends PreTrainedModel { }\n/**\n * The bare Phi Model outputting raw hidden-states without any specific head on top.\n */\nexport class PhiModel extends PhiPreTrainedModel { }\n\nexport class PhiForCausalLM extends PhiPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Phi3 models\nexport class Phi3PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Phi3 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Phi3Model extends Phi3PreTrainedModel { }\n\nexport class Phi3ForCausalLM extends Phi3PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Bloom models\n/**\n * The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class BloomPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Bloom Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class BloomModel extends BloomPreTrainedModel { }\n\n/**\n * The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class BloomForCausalLM extends BloomPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MPT models\nexport class MptPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Mpt Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class MptModel extends MptPreTrainedModel { }\n\n/**\n * The MPT Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class MptForCausalLM extends MptPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// OPT models\nexport class OPTPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare OPT Model outputting raw hidden-states without any specific head on top.\n */\nexport class OPTModel extends OPTPreTrainedModel { }\n\n/**\n * The OPT Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class OPTForCausalLM extends OPTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class ViTPreTrainedModel extends PreTrainedModel { }\nexport class ViTModel extends ViTPreTrainedModel { }\nexport class ViTForImageClassification extends ViTPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class PvtPreTrainedModel extends PreTrainedModel { }\nexport class PvtModel extends PvtPreTrainedModel { }\nexport class PvtForImageClassification extends PvtPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class ViTMAEPreTrainedModel extends PreTrainedModel { }\nexport class ViTMAEModel extends ViTMAEPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class ViTMSNPreTrainedModel extends PreTrainedModel { }\nexport class ViTMSNModel extends ViTMSNPreTrainedModel { }\nexport class ViTMSNForImageClassification extends ViTMSNPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class GroupViTPreTrainedModel extends PreTrainedModel { }\nexport class GroupViTModel extends GroupViTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class FastViTPreTrainedModel extends PreTrainedModel { }\nexport class FastViTModel extends FastViTPreTrainedModel { }\nexport class FastViTForImageClassification extends FastViTPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class VitMattePreTrainedModel extends PreTrainedModel { }\n\n/**\n * ViTMatte framework leveraging any vision backbone e.g. for ADE20k, CityScapes.\n * \n * **Example:** Perform image matting with a `VitMatteForImageMatting` model.\n * ```javascript\n * import { AutoProcessor, VitMatteForImageMatting, RawImage } from '@huggingface/transformers';\n * \n * // Load processor and model\n * const processor = await AutoProcessor.from_pretrained('Xenova/vitmatte-small-distinctions-646');\n * const model = await VitMatteForImageMatting.from_pretrained('Xenova/vitmatte-small-distinctions-646');\n * \n * // Load image and trimap\n * const image = await RawImage.fromURL('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/vitmatte_image.png');\n * const trimap = await RawImage.fromURL('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/vitmatte_trimap.png');\n * \n * // Prepare image + trimap for the model\n * const inputs = await processor(image, trimap);\n * \n * // Predict alpha matte\n * const { alphas } = await model(inputs);\n * // Tensor {\n * // dims: [ 1, 1, 640, 960 ],\n * // type: 'float32',\n * // size: 614400,\n * // data: Float32Array(614400) [ 0.9894027709960938, 0.9970508813858032, ... ]\n * // }\n * ```\n * \n * You can visualize the alpha matte as follows:\n * ```javascript\n * import { Tensor, cat } from '@huggingface/transformers';\n * \n * // Visualize predicted alpha matte\n * const imageTensor = image.toTensor();\n * \n * // Convert float (0-1) alpha matte to uint8 (0-255)\n * const alphaChannel = alphas\n * .squeeze(0)\n * .mul_(255)\n * .clamp_(0, 255)\n * .round_()\n * .to('uint8');\n * \n * // Concatenate original image with predicted alpha\n * const imageData = cat([imageTensor, alphaChannel], 0);\n * \n * // Save output image\n * const outputImage = RawImage.fromTensor(imageData);\n * outputImage.save('output.png');\n * ```\n */\nexport class VitMatteForImageMatting extends VitMattePreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new ImageMattingOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class MobileViTPreTrainedModel extends PreTrainedModel { }\nexport class MobileViTModel extends MobileViTPreTrainedModel { }\nexport class MobileViTForImageClassification extends MobileViTPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n// TODO: MobileViTForSemanticSegmentation\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class MobileViTV2PreTrainedModel extends PreTrainedModel { }\nexport class MobileViTV2Model extends MobileViTV2PreTrainedModel { }\nexport class MobileViTV2ForImageClassification extends MobileViTV2PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n// TODO: MobileViTV2ForSemanticSegmentation\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class OwlViTPreTrainedModel extends PreTrainedModel { }\nexport class OwlViTModel extends OwlViTPreTrainedModel { }\nexport class OwlViTForObjectDetection extends OwlViTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class Owlv2PreTrainedModel extends PreTrainedModel { }\nexport class Owlv2Model extends Owlv2PreTrainedModel { }\nexport class Owlv2ForObjectDetection extends Owlv2PreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Beit Models\nexport class BeitPreTrainedModel extends PreTrainedModel { }\nexport class BeitModel extends BeitPreTrainedModel { }\nexport class BeitForImageClassification extends BeitPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class DetrPreTrainedModel extends PreTrainedModel { }\nexport class DetrModel extends DetrPreTrainedModel { }\nexport class DetrForObjectDetection extends DetrPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new DetrObjectDetectionOutput(await super._call(model_inputs));\n }\n}\n\nexport class DetrForSegmentation extends DetrPreTrainedModel {\n /**\n * Runs the model with the provided inputs\n * @param {Object} model_inputs Model inputs\n * @returns {Promise} Object containing segmentation outputs\n */\n async _call(model_inputs) {\n return new DetrSegmentationOutput(await super._call(model_inputs));\n }\n}\n\nexport class DetrObjectDetectionOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification logits (including no-object) for all queries.\n * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).\n * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).\n */\n constructor({ logits, pred_boxes }) {\n super();\n this.logits = logits;\n this.pred_boxes = pred_boxes;\n }\n}\n\nexport class DetrSegmentationOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits The output logits of the model.\n * @param {Tensor} output.pred_boxes Predicted boxes.\n * @param {Tensor} output.pred_masks Predicted masks.\n */\n constructor({ logits, pred_boxes, pred_masks }) {\n super();\n this.logits = logits;\n this.pred_boxes = pred_boxes;\n this.pred_masks = pred_masks;\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class RTDetrPreTrainedModel extends PreTrainedModel { }\nexport class RTDetrModel extends RTDetrPreTrainedModel { }\nexport class RTDetrForObjectDetection extends RTDetrPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new RTDetrObjectDetectionOutput(await super._call(model_inputs));\n }\n}\n\nexport class RTDetrObjectDetectionOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification logits (including no-object) for all queries.\n * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).\n * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).\n */\n constructor({ logits, pred_boxes }) {\n super();\n this.logits = logits;\n this.pred_boxes = pred_boxes;\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class TableTransformerPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Table Transformer Model (consisting of a backbone and encoder-decoder Transformer)\n * outputting raw hidden-states without any specific head on top.\n */\nexport class TableTransformerModel extends TableTransformerPreTrainedModel { }\n\n/**\n * Table Transformer Model (consisting of a backbone and encoder-decoder Transformer)\n * with object detection heads on top, for tasks such as COCO detection.\n */\nexport class TableTransformerForObjectDetection extends TableTransformerPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new TableTransformerObjectDetectionOutput(await super._call(model_inputs));\n }\n}\nexport class TableTransformerObjectDetectionOutput extends DetrObjectDetectionOutput { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class DeiTPreTrainedModel extends PreTrainedModel { }\nexport class DeiTModel extends DeiTPreTrainedModel { }\nexport class DeiTForImageClassification extends DeiTPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class HieraPreTrainedModel extends PreTrainedModel { }\nexport class HieraModel extends HieraPreTrainedModel { }\nexport class HieraForImageClassification extends HieraPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class ResNetPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ResNet model outputting raw features without any specific head on top.\n */\nexport class ResNetModel extends ResNetPreTrainedModel { }\n\n/**\n * ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.\n */\nexport class ResNetForImageClassification extends ResNetPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class SwinPreTrainedModel extends PreTrainedModel { }\nexport class SwinModel extends SwinPreTrainedModel { }\nexport class SwinForImageClassification extends SwinPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class Swin2SRPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Swin2SR Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class Swin2SRModel extends Swin2SRPreTrainedModel { }\n\n/**\n * Swin2SR Model transformer with an upsampler head on top for image super resolution and restoration.\n * \n * **Example:** Super-resolution w/ `Xenova/swin2SR-classical-sr-x2-64`.\n * \n * ```javascript\n * import { AutoProcessor, Swin2SRForImageSuperResolution, RawImage } from '@huggingface/transformers';\n * \n * // Load processor and model\n * const model_id = 'Xenova/swin2SR-classical-sr-x2-64';\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * const model = await Swin2SRForImageSuperResolution.from_pretrained(model_id);\n * \n * // Prepare model inputs\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg';\n * const image = await RawImage.fromURL(url);\n * const inputs = await processor(image);\n * \n * // Run model\n * const outputs = await model(inputs);\n * \n * // Convert Tensor to RawImage\n * const output = outputs.reconstruction.squeeze().clamp_(0, 1).mul_(255).round_().to('uint8');\n * const outputImage = RawImage.fromTensor(output);\n * // RawImage {\n * // data: Uint8Array(786432) [ 41, 31, 24, ... ],\n * // width: 512,\n * // height: 512,\n * // channels: 3\n * // }\n * ```\n */\nexport class Swin2SRForImageSuperResolution extends Swin2SRPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class DPTPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare DPT Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class DPTModel extends DPTPreTrainedModel { }\n\n/**\n * DPT Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2.\n * \n * **Example:** Depth estimation w/ `Xenova/dpt-hybrid-midas`.\n * ```javascript\n * import { DPTForDepthEstimation, AutoProcessor, RawImage, interpolate, max } from '@huggingface/transformers';\n * \n * // Load model and processor\n * const model_id = 'Xenova/dpt-hybrid-midas';\n * const model = await DPTForDepthEstimation.from_pretrained(model_id);\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * \n * // Load image from URL\n * const url = 'http://images.cocodataset.org/val2017/000000039769.jpg';\n * const image = await RawImage.fromURL(url);\n * \n * // Prepare image for the model\n * const inputs = await processor(image);\n * \n * // Run model\n * const { predicted_depth } = await model(inputs);\n * \n * // Interpolate to original size\n * const prediction = interpolate(predicted_depth, image.size.reverse(), 'bilinear', false);\n * \n * // Visualize the prediction\n * const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8');\n * const depth = RawImage.fromTensor(formatted);\n * // RawImage {\n * // data: Uint8Array(307200) [ 85, 85, 84, ... ],\n * // width: 640,\n * // height: 480,\n * // channels: 1\n * // }\n * ```\n */\nexport class DPTForDepthEstimation extends DPTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class DepthAnythingPreTrainedModel extends PreTrainedModel { }\n\n/**\n * Depth Anything Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2.\n */\nexport class DepthAnythingForDepthEstimation extends DepthAnythingPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class SapiensPreTrainedModel extends PreTrainedModel { }\nexport class SapiensForSemanticSegmentation extends SapiensPreTrainedModel { }\nexport class SapiensForDepthEstimation extends SapiensPreTrainedModel { }\nexport class SapiensForNormalEstimation extends SapiensPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class DepthProPreTrainedModel extends PreTrainedModel { }\nexport class DepthProForDepthEstimation extends DepthProPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class MaskFormerPreTrainedModel extends PreTrainedModel { }\nexport class MaskFormerModel extends MaskFormerPreTrainedModel { }\nexport class MaskFormerForInstanceSegmentation extends MaskFormerPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class GLPNPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare GLPN encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top.\n */\nexport class GLPNModel extends GLPNPreTrainedModel { }\n\n/**\n * GLPN Model transformer with a lightweight depth estimation head on top e.g. for KITTI, NYUv2.\n * \n * **Example:** Depth estimation w/ `Xenova/glpn-kitti`.\n * ```javascript\n * import { GLPNForDepthEstimation, AutoProcessor, RawImage, interpolate, max } from '@huggingface/transformers';\n * \n * // Load model and processor\n * const model_id = 'Xenova/glpn-kitti';\n * const model = await GLPNForDepthEstimation.from_pretrained(model_id);\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * \n * // Load image from URL\n * const url = 'http://images.cocodataset.org/val2017/000000039769.jpg';\n * const image = await RawImage.fromURL(url);\n * \n * // Prepare image for the model\n * const inputs = await processor(image);\n * \n * // Run model\n * const { predicted_depth } = await model(inputs);\n * \n * // Interpolate to original size\n * const prediction = interpolate(predicted_depth, image.size.reverse(), 'bilinear', false);\n * \n * // Visualize the prediction\n * const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8');\n * const depth = RawImage.fromTensor(formatted);\n * // RawImage {\n * // data: Uint8Array(307200) [ 207, 169, 154, ... ],\n * // width: 640,\n * // height: 480,\n * // channels: 1\n * // }\n * ```\n */\nexport class GLPNForDepthEstimation extends GLPNPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class DonutSwinPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Donut Swin Model transformer outputting raw hidden-states without any specific head on top.\n * \n * **Example:** Step-by-step Document Parsing.\n * \n * ```javascript\n * import { AutoProcessor, AutoTokenizer, AutoModelForVision2Seq, RawImage } from '@huggingface/transformers';\n * \n * // Choose model to use\n * const model_id = 'Xenova/donut-base-finetuned-cord-v2';\n * \n * // Prepare image inputs\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/receipt.png';\n * const image = await RawImage.read(url);\n * const image_inputs = await processor(image);\n * \n * // Prepare decoder inputs\n * const tokenizer = await AutoTokenizer.from_pretrained(model_id);\n * const task_prompt = '';\n * const decoder_input_ids = tokenizer(task_prompt, {\n * add_special_tokens: false,\n * }).input_ids;\n * \n * // Create the model\n * const model = await AutoModelForVision2Seq.from_pretrained(model_id);\n * \n * // Run inference\n * const output = await model.generate(image_inputs.pixel_values, {\n * decoder_input_ids,\n * max_length: model.config.decoder.max_position_embeddings,\n * });\n * \n * // Decode output\n * const decoded = tokenizer.batch_decode(output)[0];\n * // CINNAMON SUGAR 17,000 1 x 17,000 17,000 17,000 20,000 3,000\n * ```\n * \n * **Example:** Step-by-step Document Visual Question Answering (DocVQA)\n * \n * ```javascript\n * import { AutoProcessor, AutoTokenizer, AutoModelForVision2Seq, RawImage } from '@huggingface/transformers';\n * \n * // Choose model to use\n * const model_id = 'Xenova/donut-base-finetuned-docvqa';\n * \n * // Prepare image inputs\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/invoice.png';\n * const image = await RawImage.read(url);\n * const image_inputs = await processor(image);\n * \n * // Prepare decoder inputs\n * const tokenizer = await AutoTokenizer.from_pretrained(model_id);\n * const question = 'What is the invoice number?';\n * const task_prompt = `${question}`;\n * const decoder_input_ids = tokenizer(task_prompt, {\n * add_special_tokens: false,\n * }).input_ids;\n * \n * // Create the model\n * const model = await AutoModelForVision2Seq.from_pretrained(model_id);\n * \n * // Run inference\n * const output = await model.generate(image_inputs.pixel_values, {\n * decoder_input_ids,\n * max_length: model.config.decoder.max_position_embeddings,\n * });\n * \n * // Decode output\n * const decoded = tokenizer.batch_decode(output)[0];\n * // What is the invoice number? us-001\n * ```\n */\nexport class DonutSwinModel extends DonutSwinPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class ConvNextPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ConvNext model outputting raw features without any specific head on top.\n */\nexport class ConvNextModel extends ConvNextPreTrainedModel { }\n\n/**\n * ConvNext Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.\n */\nexport class ConvNextForImageClassification extends ConvNextPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class ConvNextV2PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ConvNextV2 model outputting raw features without any specific head on top.\n */\nexport class ConvNextV2Model extends ConvNextV2PreTrainedModel { }\n\n/**\n * ConvNextV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.\n */\nexport class ConvNextV2ForImageClassification extends ConvNextV2PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class Dinov2PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare DINOv2 Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class Dinov2Model extends Dinov2PreTrainedModel { }\n\n/**\n * Dinov2 Model transformer with an image classification head on top (a linear layer on top of the final hidden state of the [CLS] token) e.g. for ImageNet.\n */\nexport class Dinov2ForImageClassification extends Dinov2PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class YolosPreTrainedModel extends PreTrainedModel { }\nexport class YolosModel extends YolosPreTrainedModel { }\nexport class YolosForObjectDetection extends YolosPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new YolosObjectDetectionOutput(await super._call(model_inputs));\n }\n}\n\nexport class YolosObjectDetectionOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification logits (including no-object) for all queries.\n * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).\n * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).\n */\n constructor({ logits, pred_boxes }) {\n super();\n this.logits = logits;\n this.pred_boxes = pred_boxes;\n }\n}\n//////////////////////////////////////////////////\n\n\n\n\n//////////////////////////////////////////////////\nexport class SamPreTrainedModel extends PreTrainedModel { }\n\n/**\n * Segment Anything Model (SAM) for generating segmentation masks, given an input image\n * and optional 2D location and bounding boxes.\n * \n * **Example:** Perform mask generation w/ `Xenova/sam-vit-base`.\n * ```javascript\n * import { SamModel, AutoProcessor, RawImage } from '@huggingface/transformers';\n * \n * const model = await SamModel.from_pretrained('Xenova/sam-vit-base');\n * const processor = await AutoProcessor.from_pretrained('Xenova/sam-vit-base');\n * \n * const img_url = 'https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png';\n * const raw_image = await RawImage.read(img_url);\n * const input_points = [[[450, 600]]] // 2D localization of a window\n * \n * const inputs = await processor(raw_image, { input_points });\n * const outputs = await model(inputs);\n * \n * const masks = await processor.post_process_masks(outputs.pred_masks, inputs.original_sizes, inputs.reshaped_input_sizes);\n * // [\n * // Tensor {\n * // dims: [ 1, 3, 1764, 2646 ],\n * // type: 'bool',\n * // data: Uint8Array(14002632) [ ... ],\n * // size: 14002632\n * // }\n * // ]\n * const scores = outputs.iou_scores;\n * // Tensor {\n * // dims: [ 1, 1, 3 ],\n * // type: 'float32',\n * // data: Float32Array(3) [\n * // 0.8892380595207214,\n * // 0.9311248064041138,\n * // 0.983696699142456\n * // ],\n * // size: 3\n * // }\n * ```\n */\nexport class SamModel extends SamPreTrainedModel {\n\n /**\n * Compute image embeddings and positional image embeddings, given the pixel values of an image.\n * @param {Object} model_inputs Object containing the model inputs.\n * @param {Tensor} model_inputs.pixel_values Pixel values obtained using a `SamProcessor`.\n * @returns {Promise<{ image_embeddings: Tensor, image_positional_embeddings: Tensor }>} The image embeddings and positional image embeddings.\n */\n async get_image_embeddings({ pixel_values }) {\n // in:\n // - pixel_values: tensor.float32[batch_size,3,1024,1024]\n // \n // out:\n // - image_embeddings: tensor.float32[batch_size,256,64,64]\n // - image_positional_embeddings: tensor.float32[batch_size,256,64,64]\n return await encoderForward(this, { pixel_values })\n }\n\n /**\n * @typedef {Object} SamModelInputs Object containing the model inputs.\n * @property {Tensor} pixel_values Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`.\n * These can be obtained using a `SamProcessor`.\n * @property {Tensor} [input_points] Input 2D spatial points with shape `(batch_size, num_points, 2)`.\n * This is used by the prompt encoder to encode the prompt.\n * @property {Tensor} [input_labels] Input labels for the points, as a Tensor of shape `(batch_size, point_batch_size, num_points)`.\n * This is used by the prompt encoder to encode the prompt. There are 4 types of labels:\n * - `1`: the point is a point that contains the object of interest\n * - `0`: the point is a point that does not contain the object of interest\n * - `-1`: the point corresponds to the background\n * - `-10`: the point is a padding point, thus should be ignored by the prompt encoder\n * @property {Tensor} [input_boxes] Input bounding boxes with shape `(batch_size, num_boxes, 4)`.\n * @property {Tensor} [image_embeddings] Image embeddings used by the mask decoder.\n * @property {Tensor} [image_positional_embeddings] Image positional embeddings used by the mask decoder.\n */\n\n /**\n * @param {SamModelInputs} model_inputs Object containing the model inputs.\n * @returns {Promise} The output of the model.\n */\n async forward(model_inputs) {\n if (!model_inputs.image_embeddings || !model_inputs.image_positional_embeddings) {\n // Compute the image embeddings if they are missing\n model_inputs = {\n ...model_inputs,\n ...(await this.get_image_embeddings(model_inputs))\n }\n }\n\n if (!model_inputs.input_labels && model_inputs.input_points) {\n // Set default input labels if they are missing\n const shape = model_inputs.input_points.dims.slice(0, -1);\n const numElements = shape.reduce((a, b) => a * b, 1);\n model_inputs.input_labels = new Tensor(\n 'int64',\n new BigInt64Array(numElements).fill(1n),\n shape\n );\n }\n\n const decoder_inputs = {\n image_embeddings: model_inputs.image_embeddings,\n image_positional_embeddings: model_inputs.image_positional_embeddings,\n };\n if (model_inputs.input_points) {\n decoder_inputs.input_points = model_inputs.input_points;\n }\n if (model_inputs.input_labels) {\n decoder_inputs.input_labels = model_inputs.input_labels;\n }\n if (model_inputs.input_boxes) {\n decoder_inputs.input_boxes = model_inputs.input_boxes;\n }\n\n // Returns:\n // - iou_scores: tensor.float32[batch_size,point_batch_size,3]\n // - pred_masks: tensor.float32[batch_size,point_batch_size,3,256,256]\n return await sessionRun(this.sessions['prompt_encoder_mask_decoder'], decoder_inputs);\n }\n\n /**\n * Runs the model with the provided inputs\n * @param {Object} model_inputs Model inputs\n * @returns {Promise} Object containing segmentation outputs\n */\n async _call(model_inputs) {\n return new SamImageSegmentationOutput(await super._call(model_inputs));\n }\n}\n\n\n/**\n * Base class for Segment-Anything model's output.\n */\nexport class SamImageSegmentationOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.iou_scores The output logits of the model.\n * @param {Tensor} output.pred_masks Predicted boxes.\n */\n constructor({ iou_scores, pred_masks }) {\n super();\n this.iou_scores = iou_scores;\n this.pred_masks = pred_masks;\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// MarianMT models\nexport class MarianPreTrainedModel extends PreTrainedModel { };\n\nexport class MarianModel extends MarianPreTrainedModel { }\n\nexport class MarianMTModel extends MarianPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// M2M100 models\nexport class M2M100PreTrainedModel extends PreTrainedModel { };\n\nexport class M2M100Model extends M2M100PreTrainedModel { }\n\nexport class M2M100ForConditionalGeneration extends M2M100PreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Wav2Vec2 models\nexport class Wav2Vec2PreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare Wav2Vec2 Model transformer outputting raw hidden-states without any specific head on top.\n * \n * **Example:** Load and run a `Wav2Vec2Model` for feature extraction.\n * \n * ```javascript\n * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/mms-300m');\n * const audio = await read_audio('https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac', 16000);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const model = await AutoModel.from_pretrained('Xenova/mms-300m');\n * const output = await model(inputs);\n * // {\n * // last_hidden_state: Tensor {\n * // dims: [ 1, 1144, 1024 ],\n * // type: 'float32',\n * // data: Float32Array(1171456) [ ... ],\n * // size: 1171456\n * // }\n * // }\n * ```\n */\nexport class Wav2Vec2Model extends Wav2Vec2PreTrainedModel { }\n\nexport class Wav2Vec2ForCTC extends Wav2Vec2PreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\nexport class Wav2Vec2ForSequenceClassification extends Wav2Vec2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * Wav2Vec2 Model with a frame classification head on top for tasks like Speaker Diarization.\n */\nexport class Wav2Vec2ForAudioFrameClassification extends Wav2Vec2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// PyAnnote models\nexport class PyAnnotePreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare PyAnnote Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class PyAnnoteModel extends PyAnnotePreTrainedModel { }\n\n/**\n * PyAnnote Model with a frame classification head on top for tasks like Speaker Diarization.\n * \n * **Example:** Load and run a `PyAnnoteForAudioFrameClassification` for speaker diarization.\n * \n * ```javascript\n * import { AutoProcessor, AutoModelForAudioFrameClassification, read_audio } from '@huggingface/transformers';\n * \n * // Load model and processor\n * const model_id = 'onnx-community/pyannote-segmentation-3.0';\n * const model = await AutoModelForAudioFrameClassification.from_pretrained(model_id);\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * \n * // Read and preprocess audio\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/mlk.wav';\n * const audio = await read_audio(url, processor.feature_extractor.config.sampling_rate);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const { logits } = await model(inputs);\n * // {\n * // logits: Tensor {\n * // dims: [ 1, 767, 7 ], // [batch_size, num_frames, num_classes]\n * // type: 'float32',\n * // data: Float32Array(5369) [ ... ],\n * // size: 5369\n * // }\n * // }\n * \n * const result = processor.post_process_speaker_diarization(logits, audio.length);\n * // [\n * // [\n * // { id: 0, start: 0, end: 1.0512535626298245, confidence: 0.8220156481664611 },\n * // { id: 2, start: 1.0512535626298245, end: 2.3398869619825127, confidence: 0.9008811707860472 },\n * // ...\n * // ]\n * // ]\n * \n * // Display result\n * console.table(result[0], ['start', 'end', 'id', 'confidence']);\n * // ┌─────────┬────────────────────┬────────────────────┬────┬─────────────────────┐\n * // │ (index) │ start │ end │ id │ confidence │\n * // ├─────────┼────────────────────┼────────────────────┼────┼─────────────────────┤\n * // │ 0 │ 0 │ 1.0512535626298245 │ 0 │ 0.8220156481664611 │\n * // │ 1 │ 1.0512535626298245 │ 2.3398869619825127 │ 2 │ 0.9008811707860472 │\n * // │ 2 │ 2.3398869619825127 │ 3.5946089560890773 │ 0 │ 0.7521651315796233 │\n * // │ 3 │ 3.5946089560890773 │ 4.578039708226655 │ 2 │ 0.8491978128022479 │\n * // │ 4 │ 4.578039708226655 │ 4.594995410849717 │ 0 │ 0.2935352600416393 │\n * // │ 5 │ 4.594995410849717 │ 6.121008646925269 │ 3 │ 0.6788051309866024 │\n * // │ 6 │ 6.121008646925269 │ 6.256654267909762 │ 0 │ 0.37125512393851134 │\n * // │ 7 │ 6.256654267909762 │ 8.630452635138397 │ 2 │ 0.7467035186353542 │\n * // │ 8 │ 8.630452635138397 │ 10.088643060721703 │ 0 │ 0.7689364814666032 │\n * // │ 9 │ 10.088643060721703 │ 12.58113134631177 │ 2 │ 0.9123324509131324 │\n * // │ 10 │ 12.58113134631177 │ 13.005023911888312 │ 0 │ 0.4828358177572041 │\n * // └─────────┴────────────────────┴────────────────────┴────┴─────────────────────┘\n * ```\n */\nexport class PyAnnoteForAudioFrameClassification extends PyAnnotePreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// WeSpeakerResNet models\nexport class WeSpeakerResNetPreTrainedModel extends PreTrainedModel { };\nexport class WeSpeakerResNetModel extends WeSpeakerResNetPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// UniSpeech models\nexport class UniSpeechPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare UniSpeech Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class UniSpeechModel extends UniSpeechPreTrainedModel { }\n\n/**\n * UniSpeech Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class UniSpeechForCTC extends UniSpeechPreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * UniSpeech Model with a sequence classification head on top (a linear layer over the pooled output).\n */\nexport class UniSpeechForSequenceClassification extends UniSpeechPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// UniSpeechSat models\nexport class UniSpeechSatPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare UniSpeechSat Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class UniSpeechSatModel extends UniSpeechSatPreTrainedModel { }\n\n/**\n * UniSpeechSat Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class UniSpeechSatForCTC extends UniSpeechSatPreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * UniSpeechSat Model with a sequence classification head on top (a linear layer over the pooled output).\n */\nexport class UniSpeechSatForSequenceClassification extends UniSpeechSatPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * UniSpeechSat Model with a frame classification head on top for tasks like Speaker Diarization.\n */\nexport class UniSpeechSatForAudioFrameClassification extends UniSpeechSatPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Wav2Vec2Bert models\nexport class Wav2Vec2BertPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare Wav2Vec2Bert Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class Wav2Vec2BertModel extends Wav2Vec2BertPreTrainedModel { }\n\n/**\n * Wav2Vec2Bert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class Wav2Vec2BertForCTC extends Wav2Vec2BertPreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_features Float values of input mel-spectrogram.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * Wav2Vec2Bert Model with a sequence classification head on top (a linear layer over the pooled output).\n */\nexport class Wav2Vec2BertForSequenceClassification extends Wav2Vec2BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Hubert models\nexport class HubertPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Hubert Model transformer outputting raw hidden-states without any specific head on top.\n * \n * **Example:** Load and run a `HubertModel` for feature extraction.\n * \n * ```javascript\n * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/hubert-base-ls960');\n * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav', 16000);\n * const inputs = await processor(audio);\n * \n * // Load and run model with inputs\n * const model = await AutoModel.from_pretrained('Xenova/hubert-base-ls960');\n * const output = await model(inputs);\n * // {\n * // last_hidden_state: Tensor {\n * // dims: [ 1, 549, 768 ],\n * // type: 'float32',\n * // data: Float32Array(421632) [0.0682469978928566, 0.08104046434164047, -0.4975186586380005, ...],\n * // size: 421632\n * // }\n * // }\n * ```\n */\nexport class HubertModel extends Wav2Vec2PreTrainedModel { }\n\n/**\n * Hubert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class HubertForCTC extends Wav2Vec2PreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * Hubert Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like SUPERB Keyword Spotting.\n */\nexport class HubertForSequenceClassification extends Wav2Vec2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// WavLM models\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class WavLMPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare WavLM Model transformer outputting raw hidden-states without any specific head on top.\n * \n * **Example:** Load and run a `WavLMModel` for feature extraction.\n * \n * ```javascript\n * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base');\n * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav', 16000);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const model = await AutoModel.from_pretrained('Xenova/wavlm-base');\n * const output = await model(inputs);\n * // {\n * // last_hidden_state: Tensor {\n * // dims: [ 1, 549, 768 ],\n * // type: 'float32',\n * // data: Float32Array(421632) [-0.349443256855011, -0.39341306686401367, 0.022836603224277496, ...],\n * // size: 421632\n * // }\n * // }\n * ```\n */\nexport class WavLMModel extends WavLMPreTrainedModel { }\n\n/**\n * WavLM Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class WavLMForCTC extends WavLMPreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * WavLM Model with a sequence classification head on top (a linear layer over the pooled output).\n */\nexport class WavLMForSequenceClassification extends WavLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * WavLM Model with an XVector feature extraction head on top for tasks like Speaker Verification.\n * \n * **Example:** Extract speaker embeddings with `WavLMForXVector`.\n * ```javascript\n * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base-plus-sv');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const audio = await read_audio(url, 16000);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const model = await AutoModel.from_pretrained('Xenova/wavlm-base-plus-sv');\n * const outputs = await model(inputs);\n * // {\n * // logits: Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [0.5847219228744507, ...],\n * // size: 512\n * // },\n * // embeddings: Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [-0.09079201519489288, ...],\n * // size: 512\n * // }\n * // }\n * ```\n */\nexport class WavLMForXVector extends WavLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits and speaker embeddings.\n */\n async _call(model_inputs) {\n return new XVectorOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * WavLM Model with a frame classification head on top for tasks like Speaker Diarization.\n * \n * **Example:** Perform speaker diarization with `WavLMForAudioFrameClassification`.\n * ```javascript\n * import { AutoProcessor, AutoModelForAudioFrameClassification, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base-plus-sd');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const audio = await read_audio(url, 16000);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const model = await AutoModelForAudioFrameClassification.from_pretrained('Xenova/wavlm-base-plus-sd');\n * const { logits } = await model(inputs);\n * // {\n * // logits: Tensor {\n * // dims: [ 1, 549, 2 ], // [batch_size, num_frames, num_speakers]\n * // type: 'float32',\n * // data: Float32Array(1098) [-3.5301010608673096, ...],\n * // size: 1098\n * // }\n * // }\n * \n * const labels = logits[0].sigmoid().tolist().map(\n * frames => frames.map(speaker => speaker > 0.5 ? 1 : 0)\n * );\n * console.log(labels); // labels is a one-hot array of shape (num_frames, num_speakers)\n * // [\n * // [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],\n * // [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],\n * // [0, 0], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1],\n * // ...\n * // ]\n * ```\n */\nexport class WavLMForAudioFrameClassification extends WavLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n//////////////////////////////////////////////////\n// SpeechT5 models\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class SpeechT5PreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare SpeechT5 Encoder-Decoder Model outputting raw hidden-states without any specific pre- or post-nets.\n */\nexport class SpeechT5Model extends SpeechT5PreTrainedModel { };\n\n/**\n * SpeechT5 Model with a speech encoder and a text decoder.\n * \n * **Example:** Generate speech from text with `SpeechT5ForSpeechToText`.\n * ```javascript\n * import { AutoTokenizer, AutoProcessor, SpeechT5ForTextToSpeech, SpeechT5HifiGan, Tensor } from '@huggingface/transformers';\n * \n * // Load the tokenizer and processor\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/speecht5_tts');\n * const processor = await AutoProcessor.from_pretrained('Xenova/speecht5_tts');\n * \n * // Load the models\n * // NOTE: We use the full-precision versions as they are more accurate\n * const model = await SpeechT5ForTextToSpeech.from_pretrained('Xenova/speecht5_tts', { dtype: 'fp32' });\n * const vocoder = await SpeechT5HifiGan.from_pretrained('Xenova/speecht5_hifigan', { dtype: 'fp32' });\n * \n * // Load speaker embeddings from URL\n * const speaker_embeddings_data = new Float32Array(\n * await (await fetch('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin')).arrayBuffer()\n * );\n * const speaker_embeddings = new Tensor(\n * 'float32',\n * speaker_embeddings_data,\n * [1, speaker_embeddings_data.length]\n * )\n * \n * // Run tokenization\n * const { input_ids } = tokenizer('Hello, my dog is cute');\n * \n * // Generate waveform\n * const { waveform } = await model.generate_speech(input_ids, speaker_embeddings, { vocoder });\n * console.log(waveform)\n * // Tensor {\n * // dims: [ 26112 ],\n * // type: 'float32',\n * // size: 26112,\n * // data: Float32Array(26112) [ -0.00043630177970044315, -0.00018082228780258447, ... ],\n * // }\n * ```\n */\nexport class SpeechT5ForSpeechToText extends SpeechT5PreTrainedModel { }\n\n/**\n * SpeechT5 Model with a text encoder and a speech decoder.\n */\nexport class SpeechT5ForTextToSpeech extends SpeechT5PreTrainedModel {\n\n /**\n * @typedef {Object} SpeechOutput\n * @property {Tensor} [spectrogram] The predicted log-mel spectrogram of shape\n * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided\n * @property {Tensor} [waveform] The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided.\n * @property {Tensor} [cross_attentions] The outputs of the decoder's cross-attention layers of shape\n * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`.\n */\n\n /**\n * Converts a sequence of input tokens into a sequence of mel spectrograms, which are subsequently turned into a speech waveform using a vocoder.\n * @param {Tensor} input_values Indices of input sequence tokens in the vocabulary.\n * @param {Tensor} speaker_embeddings Tensor containing the speaker embeddings.\n * @param {Object} options Optional parameters for generating speech.\n * @param {number} [options.threshold=0.5] The generated sequence ends when the predicted stop token probability exceeds this value.\n * @param {number} [options.minlenratio=0.0] Used to calculate the minimum required length for the output sequence.\n * @param {number} [options.maxlenratio=20.0] Used to calculate the maximum allowed length for the output sequence.\n * @param {Object} [options.vocoder=null] The vocoder that converts the mel spectrogram into a speech waveform. If `null`, the output is the mel spectrogram.\n * @param {boolean} [options.output_cross_attentions=false] Whether or not to return the attentions tensors of the decoder's cross-attention layers.\n * @returns {Promise} A promise which resolves to an object containing the spectrogram, waveform, and cross-attention tensors.\n */\n async generate_speech(input_values, speaker_embeddings, {\n threshold = 0.5,\n minlenratio = 0.0,\n maxlenratio = 20.0,\n vocoder = null,\n // output_cross_attentions = false, // TODO add\n } = {}) {\n\n const model_inputs = {\n input_ids: input_values\n }\n\n const { encoder_outputs, encoder_attention_mask } = await encoderForward(this, model_inputs);\n\n const r = encoder_outputs.dims[1] / this.config.reduction_factor;\n const maxlen = Math.floor(r * maxlenratio);\n const minlen = Math.floor(r * minlenratio);\n\n const num_mel_bins = this.config.num_mel_bins;\n\n let spectrogramParts = [];\n let past_key_values = null;\n let decoder_outputs = null;\n let idx = 0;\n\n while (true) {\n ++idx;\n\n const use_cache_branch = boolTensor(!!decoder_outputs);\n let output_sequence;\n if (decoder_outputs) {\n output_sequence = decoder_outputs.output_sequence_out;\n } else {\n output_sequence = new Tensor(\n 'float32',\n new Float32Array(num_mel_bins),\n [1, 1, num_mel_bins],\n )\n }\n let decoderFeeds = {\n use_cache_branch,\n output_sequence,\n encoder_attention_mask: encoder_attention_mask,\n speaker_embeddings: speaker_embeddings,\n encoder_hidden_states: encoder_outputs,\n };\n\n this.addPastKeyValues(decoderFeeds, past_key_values);\n decoder_outputs = await sessionRun(this.sessions['decoder_model_merged'], decoderFeeds);\n past_key_values = this.getPastKeyValues(decoder_outputs, past_key_values);\n\n const { prob, spectrum } = decoder_outputs;\n spectrogramParts.push(spectrum);\n\n if (idx >= minlen && (\n // Finished when stop token or maximum length is reached.\n Array.from(prob.data).filter(p => p >= threshold).length > 0 || idx >= maxlen\n )) {\n break;\n }\n }\n\n const spectrogram = cat(spectrogramParts);\n const { waveform } = await sessionRun(vocoder.sessions['model'], { spectrogram });\n\n return {\n spectrogram,\n waveform,\n // cross_attentions: null, // TODO add\n }\n }\n}\n\n/**\n * HiFi-GAN vocoder.\n * \n * See [SpeechT5ForSpeechToText](./models#module_models.SpeechT5ForSpeechToText) for example usage.\n */\nexport class SpeechT5HifiGan extends PreTrainedModel {\n main_input_name = 'spectrogram';\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// TrOCR models\nexport class TrOCRPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The TrOCR Decoder with a language modeling head.\n */\nexport class TrOCRForCausalLM extends TrOCRPreTrainedModel { }\n\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Mistral models\n/**\n * The bare Mistral Model outputting raw hidden-states without any specific head on top.\n */\nexport class MistralPreTrainedModel extends PreTrainedModel { }\n\nexport class MistralModel extends MistralPreTrainedModel { }\n\nexport class MistralForCausalLM extends MistralPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Starcoder2 models\n/**\n * The bare Starcoder2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Starcoder2PreTrainedModel extends PreTrainedModel { }\n\nexport class Starcoder2Model extends Starcoder2PreTrainedModel { }\n\nexport class Starcoder2ForCausalLM extends Starcoder2PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Falcon models\n/**\n * The bare Falcon Model outputting raw hidden-states without any specific head on top.\n */\nexport class FalconPreTrainedModel extends PreTrainedModel { }\n\nexport class FalconModel extends FalconPreTrainedModel { }\n\nexport class FalconForCausalLM extends FalconPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// CLAP models\nexport class ClapPreTrainedModel extends PreTrainedModel { }\n\nexport class ClapModel extends ClapPreTrainedModel { }\n\n/**\n * CLAP Text Model with a projection layer on top (a linear layer on top of the pooled output).\n * \n * **Example:** Compute text embeddings with `ClapTextModelWithProjection`.\n * \n * ```javascript\n * import { AutoTokenizer, ClapTextModelWithProjection } from '@huggingface/transformers';\n * \n * // Load tokenizer and text model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clap-htsat-unfused');\n * const text_model = await ClapTextModelWithProjection.from_pretrained('Xenova/clap-htsat-unfused');\n * \n * // Run tokenization\n * const texts = ['a sound of a cat', 'a sound of a dog'];\n * const text_inputs = tokenizer(texts, { padding: true, truncation: true });\n * \n * // Compute embeddings\n * const { text_embeds } = await text_model(text_inputs);\n * // Tensor {\n * // dims: [ 2, 512 ],\n * // type: 'float32',\n * // data: Float32Array(1024) [ ... ],\n * // size: 1024\n * // }\n * ```\n */\nexport class ClapTextModelWithProjection extends ClapPreTrainedModel {\n\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'text_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * CLAP Audio Model with a projection layer on top (a linear layer on top of the pooled output).\n * \n * **Example:** Compute audio embeddings with `ClapAudioModelWithProjection`.\n * \n * ```javascript\n * import { AutoProcessor, ClapAudioModelWithProjection, read_audio } from '@huggingface/transformers';\n * \n * // Load processor and audio model\n * const processor = await AutoProcessor.from_pretrained('Xenova/clap-htsat-unfused');\n * const audio_model = await ClapAudioModelWithProjection.from_pretrained('Xenova/clap-htsat-unfused');\n * \n * // Read audio and run processor\n * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cat_meow.wav');\n * const audio_inputs = await processor(audio);\n * \n * // Compute embeddings\n * const { audio_embeds } = await audio_model(audio_inputs);\n * // Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [ ... ],\n * // size: 512\n * // }\n * ```\n */\nexport class ClapAudioModelWithProjection extends ClapPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'audio_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// VITS models\nexport class VitsPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The complete VITS model, for text-to-speech synthesis.\n * \n * **Example:** Generate speech from text with `VitsModel`.\n * ```javascript\n * import { AutoTokenizer, VitsModel } from '@huggingface/transformers';\n * \n * // Load the tokenizer and model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/mms-tts-eng');\n * const model = await VitsModel.from_pretrained('Xenova/mms-tts-eng');\n * \n * // Run tokenization\n * const inputs = tokenizer('I love transformers');\n * \n * // Generate waveform\n * const { waveform } = await model(inputs);\n * // Tensor {\n * // dims: [ 1, 35328 ],\n * // type: 'float32',\n * // data: Float32Array(35328) [ ... ],\n * // size: 35328,\n * // }\n * ```\n */\nexport class VitsModel extends VitsPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} The outputs for the VITS model.\n */\n async _call(model_inputs) {\n return new VitsModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Segformer models\nexport class SegformerPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare SegFormer encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top.\n */\nexport class SegformerModel extends SegformerPreTrainedModel { }\n\n/**\n * SegFormer Model transformer with an image classification head on top (a linear layer on top of the final hidden states) e.g. for ImageNet.\n */\nexport class SegformerForImageClassification extends SegformerPreTrainedModel { }\n\n/**\n * SegFormer Model transformer with an all-MLP decode head on top e.g. for ADE20k, CityScapes.\n */\nexport class SegformerForSemanticSegmentation extends SegformerPreTrainedModel { }\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// StableLm models\nexport class StableLmPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare StableLm Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class StableLmModel extends StableLmPreTrainedModel { }\n\n/**\n * StableLm Model with a `language modeling` head on top for Causal Language Modeling (with past).\n */\nexport class StableLmForCausalLM extends StableLmPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class EfficientNetPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare EfficientNet model outputting raw features without any specific head on top.\n */\nexport class EfficientNetModel extends EfficientNetPreTrainedModel { }\n\n/**\n * EfficientNet Model with an image classification head on top (a linear layer on top of the pooled features).\n */\nexport class EfficientNetForImageClassification extends EfficientNetPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Musicgen models\nexport class MusicgenPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Musicgen decoder model outputting raw hidden-states without any specific head on top.\n */\nexport class MusicgenModel extends MusicgenPreTrainedModel { }\n\n/**\n * The MusicGen decoder model with a language modelling head on top.\n */\nexport class MusicgenForCausalLM extends MusicgenPreTrainedModel { }\n\n/**\n * The composite MusicGen model with a text encoder, audio encoder and Musicgen decoder,\n * for music generation tasks with one or both of text and audio prompts.\n * \n * **Example:** Generate music from text with `Xenova/musicgen-small`.\n * ```javascript\n * import { AutoTokenizer, MusicgenForConditionalGeneration } from '@huggingface/transformers';\n * \n * // Load tokenizer and model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/musicgen-small');\n * const model = await MusicgenForConditionalGeneration.from_pretrained(\n * 'Xenova/musicgen-small', { dtype: 'fp32' }\n * );\n * \n * // Prepare text input\n * const prompt = '80s pop track with bassy drums and synth';\n * const inputs = tokenizer(prompt);\n * \n * // Generate audio\n * const audio_values = await model.generate({\n * ...inputs,\n * max_new_tokens: 512,\n * do_sample: true,\n * guidance_scale: 3,\n * });\n * \n * // (Optional) Write the output to a WAV file\n * import wavefile from 'wavefile';\n * import fs from 'fs';\n * \n * const wav = new wavefile.WaveFile();\n * wav.fromScratch(1, model.config.audio_encoder.sampling_rate, '32f', audio_values.data);\n * fs.writeFileSync('musicgen_out.wav', wav.toBuffer());\n * ```\n */\nexport class MusicgenForConditionalGeneration extends PreTrainedModel { // NOTE: not MusicgenPreTrainedModel\n forward_params = [\n 'input_ids',\n 'attention_mask',\n 'encoder_outputs',\n 'decoder_input_ids',\n 'decoder_attention_mask',\n 'past_key_values',\n ];\n\n /**\n * Apply the pattern mask to the final ids,\n * then revert the pattern delay mask by filtering the pad token id in a single step.\n * @param {Tensor} outputs The output tensor from the model.\n * @returns {Tensor} The filtered output tensor.\n */\n _apply_and_filter_by_delay_pattern_mask(outputs) {\n const [bs_x_codebooks, seqLength] = outputs.dims;\n const num_codebooks = this.config.decoder.num_codebooks;\n const upperBound = (seqLength - num_codebooks);\n\n let newDataSize = 0;\n for (let i = 0; i < outputs.size; ++i) {\n if (outputs.data[i] === this.config.decoder.pad_token_id) {\n continue;\n }\n\n const row = (i % seqLength);\n const col = Math.floor(i / seqLength) % num_codebooks;\n\n const diff = row - col;\n if (diff > 0 && diff <= upperBound) {\n outputs.data[newDataSize++] = outputs.data[i];\n }\n }\n\n const batch_size = Math.floor(bs_x_codebooks / num_codebooks);\n const inferred = newDataSize / (batch_size * num_codebooks);\n // TODO: assert `inferred` is an integer\n return new Tensor(\n outputs.type,\n outputs.data.slice(0, newDataSize),\n [batch_size, num_codebooks, inferred]\n );\n }\n\n\n prepare_inputs_for_generation(input_ids, model_inputs, generation_config) {\n // apply the delay pattern mask\n let clonedInputIds = structuredClone(input_ids);\n for (let i = 0; i < clonedInputIds.length; ++i) {\n for (let j = 0; j < clonedInputIds[i].length; ++j) {\n if ((i % this.config.decoder.num_codebooks) >= j) {\n clonedInputIds[i][j] = BigInt(this.config.decoder.pad_token_id);\n }\n }\n }\n // for classifier free guidance we need to replicate the decoder args across the batch dim\n // (we'll split these before sampling)\n if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) {\n // [batch, seqLength] -> [2 * batch, seqLength]\n clonedInputIds = clonedInputIds.concat(clonedInputIds);\n }\n\n const prepped = super.prepare_inputs_for_generation(clonedInputIds, model_inputs, generation_config);\n return prepped;\n }\n\n /**\n * Generates sequences of token ids for models with a language modeling head.\n * @param {import('./generation/parameters.js').GenerationFunctionParameters} options\n * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores.\n */\n async generate(options) {\n\n const output_ids = await super.generate(options);\n\n // apply the pattern mask to the final ids\n // tensor: int64[1,batch_size,4,chunk_length]\n const audio_codes = this._apply_and_filter_by_delay_pattern_mask(\n /** @type {Tensor} */(output_ids)\n ).unsqueeze_(0); // append the frame dimension back to the audio codes\n\n const { audio_values } = await sessionRun(this.sessions['encodec_decode'], { audio_codes })\n\n return audio_values;\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MobileNetV1 models\nexport class MobileNetV1PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.\n */\nexport class MobileNetV1Model extends MobileNetV1PreTrainedModel { }\n\n/**\n * MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features),\n * e.g. for ImageNet.\n */\nexport class MobileNetV1ForImageClassification extends MobileNetV1PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MobileNetV2 models\nexport class MobileNetV2PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MobileNetV2 model outputting raw hidden-states without any specific head on top.\n */\nexport class MobileNetV2Model extends MobileNetV2PreTrainedModel { }\n\n/**\n * MobileNetV2 model with an image classification head on top (a linear layer on top of the pooled features),\n * e.g. for ImageNet.\n */\nexport class MobileNetV2ForImageClassification extends MobileNetV2PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MobileNetV3 models\nexport class MobileNetV3PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MobileNetV3 model outputting raw hidden-states without any specific head on top.\n */\nexport class MobileNetV3Model extends MobileNetV3PreTrainedModel { }\n\n/**\n * MobileNetV3 model with an image classification head on top (a linear layer on top of the pooled features),\n * e.g. for ImageNet.\n */\nexport class MobileNetV3ForImageClassification extends MobileNetV3PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MobileNetV4 models\nexport class MobileNetV4PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MobileNetV4 model outputting raw hidden-states without any specific head on top.\n */\nexport class MobileNetV4Model extends MobileNetV4PreTrainedModel { }\n\n/**\n * MobileNetV4 model with an image classification head on top (a linear layer on top of the pooled features),\n * e.g. for ImageNet.\n */\nexport class MobileNetV4ForImageClassification extends MobileNetV4PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Decision Transformer models\nexport class DecisionTransformerPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The model builds upon the GPT2 architecture to perform autoregressive prediction of actions in an offline RL setting.\n * Refer to the paper for more details: https://arxiv.org/abs/2106.01345\n */\nexport class DecisionTransformerModel extends DecisionTransformerPreTrainedModel { }\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// AutoModels, used to simplify construction of PreTrainedModels\n// (uses config to instantiate correct class)\n\n/**\n * Base class of all AutoModels. Contains the `from_pretrained` function\n * which is used to instantiate pretrained models.\n */\nexport class PretrainedMixin {\n /**\n * Mapping from model type to model class.\n * @type {Map[]}\n */\n static MODEL_CLASS_MAPPINGS = null;\n\n /**\n * Whether to attempt to instantiate the base class (`PretrainedModel`) if \n * the model type is not found in the mapping.\n */\n static BASE_IF_FAIL = false;\n\n\n /** @type {typeof PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n model_file_name = null,\n subfolder = 'onnx',\n device = null,\n dtype = null,\n use_external_data_format = null,\n session_options = {},\n } = {}) {\n\n const options = {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n model_file_name,\n subfolder,\n device,\n dtype,\n use_external_data_format,\n session_options,\n }\n options.config = await AutoConfig.from_pretrained(pretrained_model_name_or_path, options);\n\n if (!this.MODEL_CLASS_MAPPINGS) {\n throw new Error(\"`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: \" + this.name);\n }\n\n for (const MODEL_CLASS_MAPPING of this.MODEL_CLASS_MAPPINGS) {\n const modelInfo = MODEL_CLASS_MAPPING.get(options.config.model_type);\n if (!modelInfo) {\n continue; // Item not found in this mapping\n }\n return await modelInfo[1].from_pretrained(pretrained_model_name_or_path, options);\n }\n\n if (this.BASE_IF_FAIL) {\n console.warn(`Unknown model class \"${options.config.model_type}\", attempting to construct from base class.`);\n return await PreTrainedModel.from_pretrained(pretrained_model_name_or_path, options);\n } else {\n throw Error(`Unsupported model type: ${options.config.model_type}`)\n }\n }\n}\n\nconst MODEL_MAPPING_NAMES_ENCODER_ONLY = new Map([\n ['bert', ['BertModel', BertModel]],\n ['nomic_bert', ['NomicBertModel', NomicBertModel]],\n ['roformer', ['RoFormerModel', RoFormerModel]],\n ['electra', ['ElectraModel', ElectraModel]],\n ['esm', ['EsmModel', EsmModel]],\n ['convbert', ['ConvBertModel', ConvBertModel]],\n ['camembert', ['CamembertModel', CamembertModel]],\n ['deberta', ['DebertaModel', DebertaModel]],\n ['deberta-v2', ['DebertaV2Model', DebertaV2Model]],\n ['mpnet', ['MPNetModel', MPNetModel]],\n ['albert', ['AlbertModel', AlbertModel]],\n ['distilbert', ['DistilBertModel', DistilBertModel]],\n ['roberta', ['RobertaModel', RobertaModel]],\n ['xlm', ['XLMModel', XLMModel]],\n ['xlm-roberta', ['XLMRobertaModel', XLMRobertaModel]],\n ['clap', ['ClapModel', ClapModel]],\n ['clip', ['CLIPModel', CLIPModel]],\n ['clipseg', ['CLIPSegModel', CLIPSegModel]],\n ['chinese_clip', ['ChineseCLIPModel', ChineseCLIPModel]],\n ['siglip', ['SiglipModel', SiglipModel]],\n ['mobilebert', ['MobileBertModel', MobileBertModel]],\n ['squeezebert', ['SqueezeBertModel', SqueezeBertModel]],\n ['wav2vec2', ['Wav2Vec2Model', Wav2Vec2Model]],\n ['wav2vec2-bert', ['Wav2Vec2BertModel', Wav2Vec2BertModel]],\n ['unispeech', ['UniSpeechModel', UniSpeechModel]],\n ['unispeech-sat', ['UniSpeechSatModel', UniSpeechSatModel]],\n ['hubert', ['HubertModel', HubertModel]],\n ['wavlm', ['WavLMModel', WavLMModel]],\n ['audio-spectrogram-transformer', ['ASTModel', ASTModel]],\n ['vits', ['VitsModel', VitsModel]],\n ['pyannote', ['PyAnnoteModel', PyAnnoteModel]],\n ['wespeaker-resnet', ['WeSpeakerResNetModel', WeSpeakerResNetModel]],\n\n ['detr', ['DetrModel', DetrModel]],\n ['rt_detr', ['RTDetrModel', RTDetrModel]],\n ['table-transformer', ['TableTransformerModel', TableTransformerModel]],\n ['vit', ['ViTModel', ViTModel]],\n ['pvt', ['PvtModel', PvtModel]],\n ['vit_msn', ['ViTMSNModel', ViTMSNModel]],\n ['vit_mae', ['ViTMAEModel', ViTMAEModel]],\n ['groupvit', ['GroupViTModel', GroupViTModel]],\n ['fastvit', ['FastViTModel', FastViTModel]],\n ['mobilevit', ['MobileViTModel', MobileViTModel]],\n ['mobilevitv2', ['MobileViTV2Model', MobileViTV2Model]],\n ['owlvit', ['OwlViTModel', OwlViTModel]],\n ['owlv2', ['Owlv2Model', Owlv2Model]],\n ['beit', ['BeitModel', BeitModel]],\n ['deit', ['DeiTModel', DeiTModel]],\n ['hiera', ['HieraModel', HieraModel]],\n ['convnext', ['ConvNextModel', ConvNextModel]],\n ['convnextv2', ['ConvNextV2Model', ConvNextV2Model]],\n ['dinov2', ['Dinov2Model', Dinov2Model]],\n ['resnet', ['ResNetModel', ResNetModel]],\n ['swin', ['SwinModel', SwinModel]],\n ['swin2sr', ['Swin2SRModel', Swin2SRModel]],\n ['donut-swin', ['DonutSwinModel', DonutSwinModel]],\n ['yolos', ['YolosModel', YolosModel]],\n ['dpt', ['DPTModel', DPTModel]],\n ['glpn', ['GLPNModel', GLPNModel]],\n\n ['hifigan', ['SpeechT5HifiGan', SpeechT5HifiGan]],\n ['efficientnet', ['EfficientNetModel', EfficientNetModel]],\n\n ['decision_transformer', ['DecisionTransformerModel', DecisionTransformerModel]],\n\n ['mobilenet_v1', ['MobileNetV1Model', MobileNetV1Model]],\n ['mobilenet_v2', ['MobileNetV2Model', MobileNetV2Model]],\n ['mobilenet_v3', ['MobileNetV3Model', MobileNetV3Model]],\n ['mobilenet_v4', ['MobileNetV4Model', MobileNetV4Model]],\n\n ['maskformer', ['MaskFormerModel', MaskFormerModel]],\n]);\n\nconst MODEL_MAPPING_NAMES_ENCODER_DECODER = new Map([\n ['t5', ['T5Model', T5Model]],\n ['longt5', ['LongT5Model', LongT5Model]],\n ['mt5', ['MT5Model', MT5Model]],\n ['bart', ['BartModel', BartModel]],\n ['mbart', ['MBartModel', MBartModel]],\n ['marian', ['MarianModel', MarianModel]],\n ['whisper', ['WhisperModel', WhisperModel]],\n ['m2m_100', ['M2M100Model', M2M100Model]],\n ['blenderbot', ['BlenderbotModel', BlenderbotModel]],\n ['blenderbot-small', ['BlenderbotSmallModel', BlenderbotSmallModel]],\n]);\n\n\nconst MODEL_MAPPING_NAMES_DECODER_ONLY = new Map([\n ['bloom', ['BloomModel', BloomModel]],\n ['jais', ['JAISModel', JAISModel]],\n ['gpt2', ['GPT2Model', GPT2Model]],\n ['gptj', ['GPTJModel', GPTJModel]],\n ['gpt_bigcode', ['GPTBigCodeModel', GPTBigCodeModel]],\n ['gpt_neo', ['GPTNeoModel', GPTNeoModel]],\n ['gpt_neox', ['GPTNeoXModel', GPTNeoXModel]],\n ['codegen', ['CodeGenModel', CodeGenModel]],\n ['llama', ['LlamaModel', LlamaModel]],\n ['granite', ['GraniteModel', GraniteModel]],\n ['cohere', ['CohereModel', CohereModel]],\n ['gemma', ['GemmaModel', GemmaModel]],\n ['gemma2', ['Gemma2Model', Gemma2Model]],\n ['openelm', ['OpenELMModel', OpenELMModel]],\n ['qwen2', ['Qwen2Model', Qwen2Model]],\n ['phi', ['PhiModel', PhiModel]],\n ['phi3', ['Phi3Model', Phi3Model]],\n ['mpt', ['MptModel', MptModel]],\n ['opt', ['OPTModel', OPTModel]],\n ['mistral', ['MistralModel', MistralModel]],\n ['starcoder2', ['Starcoder2Model', Starcoder2Model]],\n ['falcon', ['FalconModel', FalconModel]],\n ['stablelm', ['StableLmModel', StableLmModel]],\n]);\n\nconst MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = new Map([\n ['speecht5', ['SpeechT5ForSpeechToText', SpeechT5ForSpeechToText]],\n ['whisper', ['WhisperForConditionalGeneration', WhisperForConditionalGeneration]],\n]);\n\nconst MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES = new Map([\n ['speecht5', ['SpeechT5ForTextToSpeech', SpeechT5ForTextToSpeech]],\n]);\n\nconst MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES = new Map([\n ['vits', ['VitsModel', VitsModel]],\n ['musicgen', ['MusicgenForConditionalGeneration', MusicgenForConditionalGeneration]],\n]);\n\nconst MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['bert', ['BertForSequenceClassification', BertForSequenceClassification]],\n ['roformer', ['RoFormerForSequenceClassification', RoFormerForSequenceClassification]],\n ['electra', ['ElectraForSequenceClassification', ElectraForSequenceClassification]],\n ['esm', ['EsmForSequenceClassification', EsmForSequenceClassification]],\n ['convbert', ['ConvBertForSequenceClassification', ConvBertForSequenceClassification]],\n ['camembert', ['CamembertForSequenceClassification', CamembertForSequenceClassification]],\n ['deberta', ['DebertaForSequenceClassification', DebertaForSequenceClassification]],\n ['deberta-v2', ['DebertaV2ForSequenceClassification', DebertaV2ForSequenceClassification]],\n ['mpnet', ['MPNetForSequenceClassification', MPNetForSequenceClassification]],\n ['albert', ['AlbertForSequenceClassification', AlbertForSequenceClassification]],\n ['distilbert', ['DistilBertForSequenceClassification', DistilBertForSequenceClassification]],\n ['roberta', ['RobertaForSequenceClassification', RobertaForSequenceClassification]],\n ['xlm', ['XLMForSequenceClassification', XLMForSequenceClassification]],\n ['xlm-roberta', ['XLMRobertaForSequenceClassification', XLMRobertaForSequenceClassification]],\n ['bart', ['BartForSequenceClassification', BartForSequenceClassification]],\n ['mbart', ['MBartForSequenceClassification', MBartForSequenceClassification]],\n ['mobilebert', ['MobileBertForSequenceClassification', MobileBertForSequenceClassification]],\n ['squeezebert', ['SqueezeBertForSequenceClassification', SqueezeBertForSequenceClassification]],\n]);\n\nconst MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['bert', ['BertForTokenClassification', BertForTokenClassification]],\n ['roformer', ['RoFormerForTokenClassification', RoFormerForTokenClassification]],\n ['electra', ['ElectraForTokenClassification', ElectraForTokenClassification]],\n ['esm', ['EsmForTokenClassification', EsmForTokenClassification]],\n ['convbert', ['ConvBertForTokenClassification', ConvBertForTokenClassification]],\n ['camembert', ['CamembertForTokenClassification', CamembertForTokenClassification]],\n ['deberta', ['DebertaForTokenClassification', DebertaForTokenClassification]],\n ['deberta-v2', ['DebertaV2ForTokenClassification', DebertaV2ForTokenClassification]],\n ['mpnet', ['MPNetForTokenClassification', MPNetForTokenClassification]],\n ['distilbert', ['DistilBertForTokenClassification', DistilBertForTokenClassification]],\n ['roberta', ['RobertaForTokenClassification', RobertaForTokenClassification]],\n ['xlm', ['XLMForTokenClassification', XLMForTokenClassification]],\n ['xlm-roberta', ['XLMRobertaForTokenClassification', XLMRobertaForTokenClassification]],\n]);\n\nconst MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = new Map([\n ['t5', ['T5ForConditionalGeneration', T5ForConditionalGeneration]],\n ['longt5', ['LongT5ForConditionalGeneration', LongT5ForConditionalGeneration]],\n ['mt5', ['MT5ForConditionalGeneration', MT5ForConditionalGeneration]],\n ['bart', ['BartForConditionalGeneration', BartForConditionalGeneration]],\n ['mbart', ['MBartForConditionalGeneration', MBartForConditionalGeneration]],\n ['marian', ['MarianMTModel', MarianMTModel]],\n ['m2m_100', ['M2M100ForConditionalGeneration', M2M100ForConditionalGeneration]],\n ['blenderbot', ['BlenderbotForConditionalGeneration', BlenderbotForConditionalGeneration]],\n ['blenderbot-small', ['BlenderbotSmallForConditionalGeneration', BlenderbotSmallForConditionalGeneration]],\n]);\n\nconst MODEL_FOR_CAUSAL_LM_MAPPING_NAMES = new Map([\n ['bloom', ['BloomForCausalLM', BloomForCausalLM]],\n ['gpt2', ['GPT2LMHeadModel', GPT2LMHeadModel]],\n ['jais', ['JAISLMHeadModel', JAISLMHeadModel]],\n ['gptj', ['GPTJForCausalLM', GPTJForCausalLM]],\n ['gpt_bigcode', ['GPTBigCodeForCausalLM', GPTBigCodeForCausalLM]],\n ['gpt_neo', ['GPTNeoForCausalLM', GPTNeoForCausalLM]],\n ['gpt_neox', ['GPTNeoXForCausalLM', GPTNeoXForCausalLM]],\n ['codegen', ['CodeGenForCausalLM', CodeGenForCausalLM]],\n ['llama', ['LlamaForCausalLM', LlamaForCausalLM]],\n ['granite', ['GraniteForCausalLM', GraniteForCausalLM]],\n ['cohere', ['CohereForCausalLM', CohereForCausalLM]],\n ['gemma', ['GemmaForCausalLM', GemmaForCausalLM]],\n ['gemma2', ['Gemma2ForCausalLM', Gemma2ForCausalLM]],\n ['openelm', ['OpenELMForCausalLM', OpenELMForCausalLM]],\n ['qwen2', ['Qwen2ForCausalLM', Qwen2ForCausalLM]],\n ['phi', ['PhiForCausalLM', PhiForCausalLM]],\n ['phi3', ['Phi3ForCausalLM', Phi3ForCausalLM]],\n ['mpt', ['MptForCausalLM', MptForCausalLM]],\n ['opt', ['OPTForCausalLM', OPTForCausalLM]],\n ['mbart', ['MBartForCausalLM', MBartForCausalLM]],\n ['mistral', ['MistralForCausalLM', MistralForCausalLM]],\n ['starcoder2', ['Starcoder2ForCausalLM', Starcoder2ForCausalLM]],\n ['falcon', ['FalconForCausalLM', FalconForCausalLM]],\n ['trocr', ['TrOCRForCausalLM', TrOCRForCausalLM]],\n ['stablelm', ['StableLmForCausalLM', StableLmForCausalLM]],\n]);\n\nconst MODEL_FOR_MASKED_LM_MAPPING_NAMES = new Map([\n ['bert', ['BertForMaskedLM', BertForMaskedLM]],\n ['roformer', ['RoFormerForMaskedLM', RoFormerForMaskedLM]],\n ['electra', ['ElectraForMaskedLM', ElectraForMaskedLM]],\n ['esm', ['EsmForMaskedLM', EsmForMaskedLM]],\n ['convbert', ['ConvBertForMaskedLM', ConvBertForMaskedLM]],\n ['camembert', ['CamembertForMaskedLM', CamembertForMaskedLM]],\n ['deberta', ['DebertaForMaskedLM', DebertaForMaskedLM]],\n ['deberta-v2', ['DebertaV2ForMaskedLM', DebertaV2ForMaskedLM]],\n ['mpnet', ['MPNetForMaskedLM', MPNetForMaskedLM]],\n ['albert', ['AlbertForMaskedLM', AlbertForMaskedLM]],\n ['distilbert', ['DistilBertForMaskedLM', DistilBertForMaskedLM]],\n ['roberta', ['RobertaForMaskedLM', RobertaForMaskedLM]],\n ['xlm', ['XLMWithLMHeadModel', XLMWithLMHeadModel]],\n ['xlm-roberta', ['XLMRobertaForMaskedLM', XLMRobertaForMaskedLM]],\n ['mobilebert', ['MobileBertForMaskedLM', MobileBertForMaskedLM]],\n ['squeezebert', ['SqueezeBertForMaskedLM', SqueezeBertForMaskedLM]],\n]);\n\nconst MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = new Map([\n ['bert', ['BertForQuestionAnswering', BertForQuestionAnswering]],\n ['roformer', ['RoFormerForQuestionAnswering', RoFormerForQuestionAnswering]],\n ['electra', ['ElectraForQuestionAnswering', ElectraForQuestionAnswering]],\n ['convbert', ['ConvBertForQuestionAnswering', ConvBertForQuestionAnswering]],\n ['camembert', ['CamembertForQuestionAnswering', CamembertForQuestionAnswering]],\n ['deberta', ['DebertaForQuestionAnswering', DebertaForQuestionAnswering]],\n ['deberta-v2', ['DebertaV2ForQuestionAnswering', DebertaV2ForQuestionAnswering]],\n ['mpnet', ['MPNetForQuestionAnswering', MPNetForQuestionAnswering]],\n ['albert', ['AlbertForQuestionAnswering', AlbertForQuestionAnswering]],\n ['distilbert', ['DistilBertForQuestionAnswering', DistilBertForQuestionAnswering]],\n ['roberta', ['RobertaForQuestionAnswering', RobertaForQuestionAnswering]],\n ['xlm', ['XLMForQuestionAnswering', XLMForQuestionAnswering]],\n ['xlm-roberta', ['XLMRobertaForQuestionAnswering', XLMRobertaForQuestionAnswering]],\n ['mobilebert', ['MobileBertForQuestionAnswering', MobileBertForQuestionAnswering]],\n ['squeezebert', ['SqueezeBertForQuestionAnswering', SqueezeBertForQuestionAnswering]],\n]);\n\nconst MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = new Map([\n ['vision-encoder-decoder', ['VisionEncoderDecoderModel', VisionEncoderDecoderModel]],\n]);\n\nconst MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES = new Map([\n ['llava', ['LlavaForConditionalGeneration', LlavaForConditionalGeneration]],\n ['moondream1', ['Moondream1ForConditionalGeneration', Moondream1ForConditionalGeneration]],\n ['florence2', ['Florence2ForConditionalGeneration', Florence2ForConditionalGeneration]],\n]);\n\nconst MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES = new Map([\n ['vision-encoder-decoder', ['VisionEncoderDecoderModel', VisionEncoderDecoderModel]],\n]);\n\nconst MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['vit', ['ViTForImageClassification', ViTForImageClassification]],\n ['pvt', ['PvtForImageClassification', PvtForImageClassification]],\n ['vit_msn', ['ViTMSNForImageClassification', ViTMSNForImageClassification]],\n ['fastvit', ['FastViTForImageClassification', FastViTForImageClassification]],\n ['mobilevit', ['MobileViTForImageClassification', MobileViTForImageClassification]],\n ['mobilevitv2', ['MobileViTV2ForImageClassification', MobileViTV2ForImageClassification]],\n ['beit', ['BeitForImageClassification', BeitForImageClassification]],\n ['deit', ['DeiTForImageClassification', DeiTForImageClassification]],\n ['hiera', ['HieraForImageClassification', HieraForImageClassification]],\n ['convnext', ['ConvNextForImageClassification', ConvNextForImageClassification]],\n ['convnextv2', ['ConvNextV2ForImageClassification', ConvNextV2ForImageClassification]],\n ['dinov2', ['Dinov2ForImageClassification', Dinov2ForImageClassification]],\n ['resnet', ['ResNetForImageClassification', ResNetForImageClassification]],\n ['swin', ['SwinForImageClassification', SwinForImageClassification]],\n ['segformer', ['SegformerForImageClassification', SegformerForImageClassification]],\n ['efficientnet', ['EfficientNetForImageClassification', EfficientNetForImageClassification]],\n ['mobilenet_v1', ['MobileNetV1ForImageClassification', MobileNetV1ForImageClassification]],\n ['mobilenet_v2', ['MobileNetV2ForImageClassification', MobileNetV2ForImageClassification]],\n ['mobilenet_v3', ['MobileNetV3ForImageClassification', MobileNetV3ForImageClassification]],\n ['mobilenet_v4', ['MobileNetV4ForImageClassification', MobileNetV4ForImageClassification]],\n]);\n\nconst MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = new Map([\n ['detr', ['DetrForObjectDetection', DetrForObjectDetection]],\n ['rt_detr', ['RTDetrForObjectDetection', RTDetrForObjectDetection]],\n ['table-transformer', ['TableTransformerForObjectDetection', TableTransformerForObjectDetection]],\n ['yolos', ['YolosForObjectDetection', YolosForObjectDetection]],\n]);\n\nconst MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = new Map([\n ['owlvit', ['OwlViTForObjectDetection', OwlViTForObjectDetection]],\n ['owlv2', ['Owlv2ForObjectDetection', Owlv2ForObjectDetection]],\n]);\n\nconst MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = new Map([\n // TODO: Do not add new models here\n ['detr', ['DetrForSegmentation', DetrForSegmentation]],\n ['clipseg', ['CLIPSegForImageSegmentation', CLIPSegForImageSegmentation]],\n]);\n\nconst MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = new Map([\n ['segformer', ['SegformerForSemanticSegmentation', SegformerForSemanticSegmentation]],\n ['sapiens', ['SapiensForSemanticSegmentation', SapiensForSemanticSegmentation]],\n]);\n\nconst MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES = new Map([\n ['detr', ['DetrForSegmentation', DetrForSegmentation]],\n ['maskformer', ['MaskFormerForInstanceSegmentation', MaskFormerForInstanceSegmentation]],\n]);\n\nconst MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = new Map([\n ['sam', ['SamModel', SamModel]],\n]);\n\nconst MODEL_FOR_CTC_MAPPING_NAMES = new Map([\n ['wav2vec2', ['Wav2Vec2ForCTC', Wav2Vec2ForCTC]],\n ['wav2vec2-bert', ['Wav2Vec2BertForCTC', Wav2Vec2BertForCTC]],\n ['unispeech', ['UniSpeechForCTC', UniSpeechForCTC]],\n ['unispeech-sat', ['UniSpeechSatForCTC', UniSpeechSatForCTC]],\n ['wavlm', ['WavLMForCTC', WavLMForCTC]],\n ['hubert', ['HubertForCTC', HubertForCTC]],\n]);\n\nconst MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['wav2vec2', ['Wav2Vec2ForSequenceClassification', Wav2Vec2ForSequenceClassification]],\n ['wav2vec2-bert', ['Wav2Vec2BertForSequenceClassification', Wav2Vec2BertForSequenceClassification]],\n ['unispeech', ['UniSpeechForSequenceClassification', UniSpeechForSequenceClassification]],\n ['unispeech-sat', ['UniSpeechSatForSequenceClassification', UniSpeechSatForSequenceClassification]],\n ['wavlm', ['WavLMForSequenceClassification', WavLMForSequenceClassification]],\n ['hubert', ['HubertForSequenceClassification', HubertForSequenceClassification]],\n ['audio-spectrogram-transformer', ['ASTForAudioClassification', ASTForAudioClassification]],\n]);\n\nconst MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES = new Map([\n ['wavlm', ['WavLMForXVector', WavLMForXVector]],\n]);\n\nconst MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['unispeech-sat', ['UniSpeechSatForAudioFrameClassification', UniSpeechSatForAudioFrameClassification]],\n ['wavlm', ['WavLMForAudioFrameClassification', WavLMForAudioFrameClassification]],\n ['wav2vec2', ['Wav2Vec2ForAudioFrameClassification', Wav2Vec2ForAudioFrameClassification]],\n ['pyannote', ['PyAnnoteForAudioFrameClassification', PyAnnoteForAudioFrameClassification]],\n]);\n\nconst MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES = new Map([\n ['vitmatte', ['VitMatteForImageMatting', VitMatteForImageMatting]],\n]);\n\nconst MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES = new Map([\n ['swin2sr', ['Swin2SRForImageSuperResolution', Swin2SRForImageSuperResolution]],\n])\n\nconst MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = new Map([\n ['dpt', ['DPTForDepthEstimation', DPTForDepthEstimation]],\n ['depth_anything', ['DepthAnythingForDepthEstimation', DepthAnythingForDepthEstimation]],\n ['glpn', ['GLPNForDepthEstimation', GLPNForDepthEstimation]],\n ['sapiens', ['SapiensForDepthEstimation', SapiensForDepthEstimation]],\n ['depth_pro', ['DepthProForDepthEstimation', DepthProForDepthEstimation]],\n])\n\nconst MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES = new Map([\n ['sapiens', ['SapiensForNormalEstimation', SapiensForNormalEstimation]],\n])\n\n// NOTE: This is custom to Transformers.js, and is necessary because certain models\n// (e.g., CLIP) are split into vision and text components\nconst MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES = new Map([\n ['clip', ['CLIPVisionModelWithProjection', CLIPVisionModelWithProjection]],\n ['siglip', ['SiglipVisionModel', SiglipVisionModel]],\n])\n\nconst MODEL_CLASS_TYPE_MAPPING = [\n [MODEL_MAPPING_NAMES_ENCODER_ONLY, MODEL_TYPES.EncoderOnly],\n [MODEL_MAPPING_NAMES_ENCODER_DECODER, MODEL_TYPES.EncoderDecoder],\n [MODEL_MAPPING_NAMES_DECODER_ONLY, MODEL_TYPES.DecoderOnly],\n [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],\n [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],\n [MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.DecoderOnly],\n [MODEL_FOR_MASKED_LM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Vision2Seq],\n [MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES, MODEL_TYPES.ImageTextToText],\n [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES, MODEL_TYPES.MaskGeneration],\n [MODEL_FOR_CTC_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],\n [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n\n // Custom:\n [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n];\n\nfor (const [mappings, type] of MODEL_CLASS_TYPE_MAPPING) {\n // @ts-ignore\n for (const [name, model] of mappings.values()) {\n MODEL_TYPE_MAPPING.set(name, type);\n MODEL_CLASS_TO_NAME_MAPPING.set(model, name);\n MODEL_NAME_TO_CLASS_MAPPING.set(name, model);\n }\n}\n\nconst CUSTOM_MAPPING = [\n // OVERRIDE:\n // TODO: Refactor to allow class to specify model\n ['MusicgenForConditionalGeneration', MusicgenForConditionalGeneration, MODEL_TYPES.Musicgen],\n\n ['CLIPTextModelWithProjection', CLIPTextModelWithProjection, MODEL_TYPES.EncoderOnly],\n ['SiglipTextModel', SiglipTextModel, MODEL_TYPES.EncoderOnly],\n ['ClapTextModelWithProjection', ClapTextModelWithProjection, MODEL_TYPES.EncoderOnly],\n ['ClapAudioModelWithProjection', ClapAudioModelWithProjection, MODEL_TYPES.EncoderOnly],\n]\nfor (const [name, model, type] of CUSTOM_MAPPING) {\n MODEL_TYPE_MAPPING.set(name, type);\n MODEL_CLASS_TO_NAME_MAPPING.set(model, name);\n MODEL_NAME_TO_CLASS_MAPPING.set(name, model);\n}\n\n\n/**\n * Helper class which is used to instantiate pretrained models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModel.from_pretrained('Xenova/bert-base-uncased');\n */\nexport class AutoModel extends PretrainedMixin {\n /** @type {Map[]} */\n // @ts-ignore\n static MODEL_CLASS_MAPPINGS = MODEL_CLASS_TYPE_MAPPING.map(x => x[0]);\n static BASE_IF_FAIL = true;\n}\n\n/**\n * Helper class which is used to instantiate pretrained sequence classification models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForSequenceClassification.from_pretrained('Xenova/distilbert-base-uncased-finetuned-sst-2-english');\n */\nexport class AutoModelForSequenceClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained token classification models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForTokenClassification.from_pretrained('Xenova/distilbert-base-multilingual-cased-ner-hrl');\n */\nexport class AutoModelForTokenClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained sequence-to-sequence models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForSeq2SeqLM.from_pretrained('Xenova/t5-small');\n */\nexport class AutoModelForSeq2SeqLM extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained sequence-to-sequence speech-to-text models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForSpeechSeq2Seq.from_pretrained('openai/whisper-tiny.en');\n */\nexport class AutoModelForSpeechSeq2Seq extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained sequence-to-sequence text-to-spectrogram models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForTextToSpectrogram.from_pretrained('microsoft/speecht5_tts');\n */\nexport class AutoModelForTextToSpectrogram extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained text-to-waveform models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForTextToSpectrogram.from_pretrained('facebook/mms-tts-eng');\n */\nexport class AutoModelForTextToWaveform extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained causal language models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForCausalLM.from_pretrained('Xenova/gpt2');\n */\nexport class AutoModelForCausalLM extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_CAUSAL_LM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained masked language models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForMaskedLM.from_pretrained('Xenova/bert-base-uncased');\n */\nexport class AutoModelForMaskedLM extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_MASKED_LM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained question answering models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForQuestionAnswering.from_pretrained('Xenova/distilbert-base-cased-distilled-squad');\n */\nexport class AutoModelForQuestionAnswering extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained vision-to-sequence models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForVision2Seq.from_pretrained('Xenova/vit-gpt2-image-captioning');\n */\nexport class AutoModelForVision2Seq extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained image classification models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForImageClassification.from_pretrained('Xenova/vit-base-patch16-224');\n */\nexport class AutoModelForImageClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained image segmentation models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForImageSegmentation.from_pretrained('Xenova/detr-resnet-50-panoptic');\n */\nexport class AutoModelForImageSegmentation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained image segmentation models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForSemanticSegmentation.from_pretrained('nvidia/segformer-b3-finetuned-cityscapes-1024-1024');\n */\nexport class AutoModelForSemanticSegmentation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained universal image segmentation models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForUniversalSegmentation.from_pretrained('hf-internal-testing/tiny-random-MaskFormerForInstanceSegmentation');\n */\nexport class AutoModelForUniversalSegmentation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained object detection models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForObjectDetection.from_pretrained('Xenova/detr-resnet-50');\n */\nexport class AutoModelForObjectDetection extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES];\n}\n\nexport class AutoModelForZeroShotObjectDetection extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES];\n}\n\n\n/**\n * Helper class which is used to instantiate pretrained mask generation models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForMaskGeneration.from_pretrained('Xenova/sam-vit-base');\n */\nexport class AutoModelForMaskGeneration extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForCTC extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_CTC_MAPPING_NAMES];\n}\n\nexport class AutoModelForAudioClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForXVector extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES];\n}\n\nexport class AutoModelForAudioFrameClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForDocumentQuestionAnswering extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES];\n}\n\nexport class AutoModelForImageMatting extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES];\n}\n\nexport class AutoModelForImageToImage extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES];\n}\n\nexport class AutoModelForDepthEstimation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForNormalEstimation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForImageFeatureExtraction extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES];\n}\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class Seq2SeqLMOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits The output logits of the model.\n * @param {Tensor} output.past_key_values An tensor of key/value pairs that represent the previous state of the model.\n * @param {Tensor} output.encoder_outputs The output of the encoder in a sequence-to-sequence model.\n * @param {Tensor} [output.decoder_attentions] Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.\n * @param {Tensor} [output.cross_attentions] Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.\n */\n constructor({ logits, past_key_values, encoder_outputs, decoder_attentions = null, cross_attentions = null }) {\n super();\n this.logits = logits;\n this.past_key_values = past_key_values;\n this.encoder_outputs = encoder_outputs;\n this.decoder_attentions = decoder_attentions;\n this.cross_attentions = cross_attentions;\n }\n}\n\n/**\n * Base class for outputs of sentence classification models.\n */\nexport class SequenceClassifierOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits classification (or regression if config.num_labels==1) scores (before SoftMax).\n */\n constructor({ logits }) {\n super();\n this.logits = logits;\n }\n}\n\n/**\n * Base class for outputs of XVector models.\n */\nexport class XVectorOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification hidden states before AMSoftmax, of shape `(batch_size, config.xvector_output_dim)`.\n * @param {Tensor} output.embeddings Utterance embeddings used for vector similarity-based retrieval, of shape `(batch_size, config.xvector_output_dim)`.\n */\n constructor({ logits, embeddings }) {\n super();\n this.logits = logits;\n this.embeddings = embeddings;\n }\n}\n\n/**\n * Base class for outputs of token classification models.\n */\nexport class TokenClassifierOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification scores (before SoftMax).\n */\n constructor({ logits }) {\n super();\n this.logits = logits;\n }\n}\n\n/**\n * Base class for masked language models outputs.\n */\nexport class MaskedLMOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).\n */\n constructor({ logits }) {\n super();\n this.logits = logits;\n }\n}\n\n/**\n * Base class for outputs of question answering models.\n */\nexport class QuestionAnsweringModelOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.start_logits Span-start scores (before SoftMax).\n * @param {Tensor} output.end_logits Span-end scores (before SoftMax).\n */\n constructor({ start_logits, end_logits }) {\n super();\n this.start_logits = start_logits;\n this.end_logits = end_logits;\n }\n}\n\n\n/**\n * Base class for causal language model (or autoregressive) outputs.\n */\nexport class CausalLMOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax).\n */\n constructor({ logits }) {\n super();\n this.logits = logits;\n }\n}\n\n/**\n * Base class for causal language model (or autoregressive) outputs.\n */\nexport class CausalLMOutputWithPast extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax).\n * @param {Tensor} output.past_key_values Contains pre-computed hidden-states (key and values in the self-attention blocks)\n * that can be used (see `past_key_values` input) to speed up sequential decoding.\n */\n constructor({ logits, past_key_values }) {\n super();\n this.logits = logits;\n this.past_key_values = past_key_values;\n }\n}\n\nexport class ImageMattingOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.alphas Estimated alpha values, of shape `(batch_size, num_channels, height, width)`.\n */\n constructor({ alphas }) {\n super();\n this.alphas = alphas;\n }\n}\n\n/**\n * Describes the outputs for the VITS model.\n */\nexport class VitsModelOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.waveform The final audio waveform predicted by the model, of shape `(batch_size, sequence_length)`.\n * @param {Tensor} output.spectrogram The log-mel spectrogram predicted at the output of the flow model.\n * This spectrogram is passed to the Hi-Fi GAN decoder model to obtain the final audio waveform.\n */\n constructor({ waveform, spectrogram }) {\n super();\n this.waveform = waveform;\n this.spectrogram = spectrogram;\n }\n}\n","\n\nconst WHISPER_LANGUAGES = [\n [\"en\", \"english\"],\n [\"zh\", \"chinese\"],\n [\"de\", \"german\"],\n [\"es\", \"spanish\"],\n [\"ru\", \"russian\"],\n [\"ko\", \"korean\"],\n [\"fr\", \"french\"],\n [\"ja\", \"japanese\"],\n [\"pt\", \"portuguese\"],\n [\"tr\", \"turkish\"],\n [\"pl\", \"polish\"],\n [\"ca\", \"catalan\"],\n [\"nl\", \"dutch\"],\n [\"ar\", \"arabic\"],\n [\"sv\", \"swedish\"],\n [\"it\", \"italian\"],\n [\"id\", \"indonesian\"],\n [\"hi\", \"hindi\"],\n [\"fi\", \"finnish\"],\n [\"vi\", \"vietnamese\"],\n [\"he\", \"hebrew\"],\n [\"uk\", \"ukrainian\"],\n [\"el\", \"greek\"],\n [\"ms\", \"malay\"],\n [\"cs\", \"czech\"],\n [\"ro\", \"romanian\"],\n [\"da\", \"danish\"],\n [\"hu\", \"hungarian\"],\n [\"ta\", \"tamil\"],\n [\"no\", \"norwegian\"],\n [\"th\", \"thai\"],\n [\"ur\", \"urdu\"],\n [\"hr\", \"croatian\"],\n [\"bg\", \"bulgarian\"],\n [\"lt\", \"lithuanian\"],\n [\"la\", \"latin\"],\n [\"mi\", \"maori\"],\n [\"ml\", \"malayalam\"],\n [\"cy\", \"welsh\"],\n [\"sk\", \"slovak\"],\n [\"te\", \"telugu\"],\n [\"fa\", \"persian\"],\n [\"lv\", \"latvian\"],\n [\"bn\", \"bengali\"],\n [\"sr\", \"serbian\"],\n [\"az\", \"azerbaijani\"],\n [\"sl\", \"slovenian\"],\n [\"kn\", \"kannada\"],\n [\"et\", \"estonian\"],\n [\"mk\", \"macedonian\"],\n [\"br\", \"breton\"],\n [\"eu\", \"basque\"],\n [\"is\", \"icelandic\"],\n [\"hy\", \"armenian\"],\n [\"ne\", \"nepali\"],\n [\"mn\", \"mongolian\"],\n [\"bs\", \"bosnian\"],\n [\"kk\", \"kazakh\"],\n [\"sq\", \"albanian\"],\n [\"sw\", \"swahili\"],\n [\"gl\", \"galician\"],\n [\"mr\", \"marathi\"],\n [\"pa\", \"punjabi\"],\n [\"si\", \"sinhala\"],\n [\"km\", \"khmer\"],\n [\"sn\", \"shona\"],\n [\"yo\", \"yoruba\"],\n [\"so\", \"somali\"],\n [\"af\", \"afrikaans\"],\n [\"oc\", \"occitan\"],\n [\"ka\", \"georgian\"],\n [\"be\", \"belarusian\"],\n [\"tg\", \"tajik\"],\n [\"sd\", \"sindhi\"],\n [\"gu\", \"gujarati\"],\n [\"am\", \"amharic\"],\n [\"yi\", \"yiddish\"],\n [\"lo\", \"lao\"],\n [\"uz\", \"uzbek\"],\n [\"fo\", \"faroese\"],\n [\"ht\", \"haitian creole\"],\n [\"ps\", \"pashto\"],\n [\"tk\", \"turkmen\"],\n [\"nn\", \"nynorsk\"],\n [\"mt\", \"maltese\"],\n [\"sa\", \"sanskrit\"],\n [\"lb\", \"luxembourgish\"],\n [\"my\", \"myanmar\"],\n [\"bo\", \"tibetan\"],\n [\"tl\", \"tagalog\"],\n [\"mg\", \"malagasy\"],\n [\"as\", \"assamese\"],\n [\"tt\", \"tatar\"],\n [\"haw\", \"hawaiian\"],\n [\"ln\", \"lingala\"],\n [\"ha\", \"hausa\"],\n [\"ba\", \"bashkir\"],\n [\"jw\", \"javanese\"],\n [\"su\", \"sundanese\"],\n]\n\n// @ts-ignore\nexport const WHISPER_LANGUAGE_MAPPING = new Map(WHISPER_LANGUAGES);\n// @ts-ignore\nexport const WHISPER_TO_LANGUAGE_CODE_MAPPING = new Map([\n ...WHISPER_LANGUAGES.map(([k, v]) => [v, k]),\n ...[\n [\"burmese\", \"my\"],\n [\"valencian\", \"ca\"],\n [\"flemish\", \"nl\"],\n [\"haitian\", \"ht\"],\n [\"letzeburgesch\", \"lb\"],\n [\"pushto\", \"ps\"],\n [\"panjabi\", \"pa\"],\n [\"moldavian\", \"ro\"],\n [\"moldovan\", \"ro\"],\n [\"sinhalese\", \"si\"],\n [\"castilian\", \"es\"],\n ]\n]);\n\n/**\n * @param {string} language The language name or code\n * @returns {string} The language code\n */\nexport function whisper_language_to_code(language) {\n language = language.toLowerCase();\n\n // Map to code from user-friendly name (e.g., \"english\" -> \"en\")\n let language_code = WHISPER_TO_LANGUAGE_CODE_MAPPING.get(language);\n\n if (language_code === undefined) {\n // User provided something that is not a language name\n\n if (WHISPER_LANGUAGE_MAPPING.has(language)) {\n // User provided the language code directly (e.g., \"en\")\n language_code = language;\n\n } else {\n // User provided something that is not a language code or name\n const is_language_code = language.length === 2;\n const langs = is_language_code ? WHISPER_LANGUAGE_MAPPING.keys() : WHISPER_LANGUAGE_MAPPING.values();\n\n throw new Error(`Language \"${language}\" is not supported. Must be one of: ${JSON.stringify(langs)}`);\n }\n }\n return language_code;\n}\n","import { GenerationConfig } from \"../../generation/configuration_utils.js\";\n\nexport class WhisperGenerationConfig extends GenerationConfig {\n\n /**\n * Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`.\n * @type {boolean}\n */\n return_timestamps = null;\n\n /**\n * Whether to return token-level timestamps\n * with the text. This can be used with or without the `return_timestamps` option. To get word-level\n * timestamps, use the tokenizer to group the tokens into words.\n * @type {boolean}\n */\n return_token_timestamps = null;\n\n /**\n * The number of audio frames available in this chunk. This is only used generating word-level timestamps.\n * @type {number}\n */\n num_frames = null;\n\n /**\n * Alignment heads to predict word-level timestamps. This is a list of [layer, head] pairs that\n * select the cross-attention heads that are highly correlated to word-level timing.\n * @type {[number, number][]}\n */\n alignment_heads = null;\n\n /**\n * Task to use for generation, either \"translate\" or \"transcribe\".\n * @type {string}\n */\n task = null;\n\n /**\n * Language token to use for generation, can be either in the form of `<|en|>`, `en` or `english`.\n * You can find all the possible language tokens in the `model.generation_config.lang_to_id` dictionary.\n * @type {string}\n */\n language = null;\n\n /**\n * The id of the `\"<|notimestamps|>\"` token.\n * @type {number}\n */\n no_timestamps_token_id = null;\n\n /**\n * Rank-1 list of token IDs created by passing text to [`~WhisperProcessor.get_prompt_ids`] that is\n * provided as a prompt to each chunk. This can be used to provide or \"prompt-engineer\" a context for\n * transcription, e.g. custom vocabularies or proper nouns to make it more likely to predict those words\n * correctly. It cannot be used in conjunction with `decoder_start_token_id` as it overwrites this value.\n * @type {number[]}\n */\n prompt_ids = null;\n\n /**\n * Whether the model is multilingual or not.\n * @type {boolean}\n */\n is_multilingual = null;\n\n /**\n * (Optional) A mapping from language tokens to their corresponding IDs.\n * Only required if the model is multilingual.\n * @type {Record|null}\n */\n lang_to_id = null;\n\n /**\n * (Optional) A mapping from task tokens to their corresponding IDs.\n * @type {Record|null}\n */\n task_to_id = null;\n\n /**\n * Used to set the maximum value of the initial timestamp. This is used to prevent the model from\n * predicting timestamps that are too far in the future.\n * @type {number}\n */\n max_initial_timestamp_index = 1;\n}\n\n/**\n * @typedef {import('../../generation/parameters.js').GenerationFunctionParameters & {generation_config: WhisperGenerationConfig} & WhisperGenerationConfig} WhisperGenerationFunctionParameters\n */\n","import { createInferenceSession } from \"../backends/onnx.js\";\nimport { Tensor } from \"../utils/tensor.js\";\n\n/**\n * Asynchronously creates a wrapper function for running an ONNX inference session.\n *\n * @param {number[]} session_bytes The session data in bytes.\n * @param {import('onnxruntime-common').InferenceSession.SessionOptions} session_options The options for the ONNX session.\n * @template {string | [string] | string[]} T\n * @param {T} names The name(s) of the output tensor(s).\n * \n * @returns {Promise): Promise>}\n * The wrapper function for running the ONNX inference session.\n */\nconst wrap = async (session_bytes, session_options, names) => {\n const session = await createInferenceSession(\n new Uint8Array(session_bytes), session_options,\n );\n return /** @type {any} */(async (/** @type {Record} */ inputs) => {\n const ortFeed = Object.fromEntries(Object.entries(inputs).map(([k, v]) => [k, v.ort_tensor]));\n const outputs = await session.run(ortFeed);\n\n if (Array.isArray(names)) {\n return names.map((n) => new Tensor(outputs[n]));\n } else {\n return new Tensor(outputs[/** @type {string} */(names)]);\n }\n })\n}\n\n// In-memory registry of initialized ONNX operators\nexport class TensorOpRegistry {\n static session_options = {\n // TODO: Allow for multiple execution providers\n // executionProviders: ['webgpu'],\n };\n\n static get bilinear_interpolate_4d() {\n if (!this._bilinear_interpolate_4d) {\n this._bilinear_interpolate_4d = wrap(\n [8, 9, 18, 0, 58, 128, 1, 10, 40, 10, 1, 120, 10, 0, 10, 0, 10, 1, 115, 18, 1, 121, 34, 6, 82, 101, 115, 105, 122, 101, 42, 17, 10, 4, 109, 111, 100, 101, 34, 6, 108, 105, 110, 101, 97, 114, 160, 1, 3, 18, 1, 114, 90, 31, 10, 1, 120, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 90, 15, 10, 1, 115, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 4, 98, 31, 10, 1, 121, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 66, 2, 16, 20],\n this.session_options,\n 'y',\n );\n }\n return this._bilinear_interpolate_4d;\n }\n\n static get bicubic_interpolate_4d() {\n if (!this._bicubic_interpolate_4d) {\n this._bicubic_interpolate_4d = wrap(\n [8, 9, 18, 0, 58, 127, 10, 39, 10, 1, 120, 10, 0, 10, 0, 10, 1, 115, 18, 1, 121, 34, 6, 82, 101, 115, 105, 122, 101, 42, 16, 10, 4, 109, 111, 100, 101, 34, 5, 99, 117, 98, 105, 99, 160, 1, 3, 18, 1, 114, 90, 31, 10, 1, 120, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 90, 15, 10, 1, 115, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 4, 98, 31, 10, 1, 121, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 66, 2, 16, 20],\n this.session_options,\n 'y',\n );\n }\n return this._bicubic_interpolate_4d;\n }\n\n static get matmul() {\n if (!this._matmul) {\n this._matmul = wrap(\n [8, 9, 18, 0, 58, 55, 10, 17, 10, 1, 97, 10, 1, 98, 18, 1, 99, 34, 6, 77, 97, 116, 77, 117, 108, 18, 1, 114, 90, 9, 10, 1, 97, 18, 4, 10, 2, 8, 1, 90, 9, 10, 1, 98, 18, 4, 10, 2, 8, 1, 98, 9, 10, 1, 99, 18, 4, 10, 2, 8, 1, 66, 2, 16, 20],\n this.session_options,\n 'c',\n );\n }\n return this._matmul;\n }\n\n static get stft() {\n if (!this._stft) {\n this._stft = wrap(\n [8, 7, 18, 0, 58, 148, 1, 10, 38, 10, 1, 115, 10, 1, 106, 10, 1, 119, 10, 1, 108, 18, 1, 111, 34, 4, 83, 84, 70, 84, 42, 15, 10, 8, 111, 110, 101, 115, 105, 100, 101, 100, 24, 1, 160, 1, 2, 18, 1, 115, 90, 26, 10, 1, 115, 18, 21, 10, 19, 8, 1, 18, 15, 10, 3, 18, 1, 98, 10, 3, 18, 1, 115, 10, 3, 18, 1, 99, 90, 11, 10, 1, 106, 18, 6, 10, 4, 8, 7, 18, 0, 90, 16, 10, 1, 119, 18, 11, 10, 9, 8, 1, 18, 5, 10, 3, 18, 1, 119, 90, 11, 10, 1, 108, 18, 6, 10, 4, 8, 7, 18, 0, 98, 31, 10, 1, 111, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 102, 10, 3, 18, 1, 100, 10, 3, 18, 1, 99, 66, 2, 16, 17],\n this.session_options,\n 'o',\n )\n }\n return this._stft;\n }\n\n static get rfft() {\n if (!this._rfft) {\n this._rfft = wrap(\n [8, 9, 18, 0, 58, 97, 10, 33, 10, 1, 120, 10, 0, 10, 1, 97, 18, 1, 121, 34, 3, 68, 70, 84, 42, 15, 10, 8, 111, 110, 101, 115, 105, 100, 101, 100, 24, 1, 160, 1, 2, 18, 1, 100, 90, 21, 10, 1, 120, 18, 16, 10, 14, 8, 1, 18, 10, 10, 3, 18, 1, 115, 10, 3, 18, 1, 99, 90, 11, 10, 1, 97, 18, 6, 10, 4, 8, 7, 18, 0, 98, 21, 10, 1, 121, 18, 16, 10, 14, 8, 1, 18, 10, 10, 3, 18, 1, 115, 10, 3, 18, 1, 99, 66, 2, 16, 20],\n this.session_options,\n 'y',\n )\n }\n return this._rfft;\n }\n\n static get top_k() {\n if (!this._top_k) {\n this._top_k = wrap(\n [8, 10, 18, 0, 58, 73, 10, 18, 10, 1, 120, 10, 1, 107, 18, 1, 118, 18, 1, 105, 34, 4, 84, 111, 112, 75, 18, 1, 116, 90, 9, 10, 1, 120, 18, 4, 10, 2, 8, 1, 90, 15, 10, 1, 107, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 1, 98, 9, 10, 1, 118, 18, 4, 10, 2, 8, 1, 98, 9, 10, 1, 105, 18, 4, 10, 2, 8, 7, 66, 2, 16, 21],\n this.session_options,\n [ /* Values */ 'v', /* Indices */ 'i']\n )\n }\n return this._top_k;\n }\n}\n","/**\n * @file Pipelines provide a high-level, easy to use, API for running machine learning models.\n * \n * **Example:** Instantiate pipeline using the `pipeline` function.\n * ```javascript\n * import { pipeline } from '@huggingface/transformers';\n * \n * const classifier = await pipeline('sentiment-analysis');\n * const output = await classifier('I love transformers!');\n * // [{'label': 'POSITIVE', 'score': 0.999817686}]\n * ```\n * \n * @module pipelines\n */\n\nimport {\n AutoTokenizer,\n PreTrainedTokenizer,\n} from './tokenizers.js';\nimport {\n AutoModel,\n AutoModelForSequenceClassification,\n AutoModelForAudioClassification,\n AutoModelForTokenClassification,\n AutoModelForQuestionAnswering,\n AutoModelForMaskedLM,\n AutoModelForSeq2SeqLM,\n AutoModelForSpeechSeq2Seq,\n AutoModelForTextToWaveform,\n AutoModelForTextToSpectrogram,\n AutoModelForCTC,\n AutoModelForCausalLM,\n AutoModelForVision2Seq,\n AutoModelForImageClassification,\n AutoModelForImageSegmentation,\n AutoModelForSemanticSegmentation,\n AutoModelForUniversalSegmentation,\n AutoModelForObjectDetection,\n AutoModelForZeroShotObjectDetection,\n AutoModelForDocumentQuestionAnswering,\n AutoModelForImageToImage,\n AutoModelForDepthEstimation,\n AutoModelForImageFeatureExtraction,\n PreTrainedModel,\n} from './models.js';\nimport {\n AutoProcessor,\n Processor\n} from './processors.js';\n\nimport {\n Callable,\n} from './utils/generic.js';\n\nimport {\n dispatchCallback,\n pop,\n product,\n} from './utils/core.js';\nimport {\n softmax,\n max,\n round,\n} from './utils/maths.js';\nimport {\n read_audio\n} from './utils/audio.js';\nimport {\n Tensor,\n mean_pooling,\n interpolate,\n quantize_embeddings,\n topk,\n} from './utils/tensor.js';\nimport { RawImage } from './utils/image.js';\n\n\n/**\n * @typedef {string | RawImage | URL} ImageInput\n * @typedef {ImageInput|ImageInput[]} ImagePipelineInputs\n */\n\n/**\n * Prepare images for further tasks.\n * @param {ImagePipelineInputs} images images to prepare.\n * @returns {Promise} returns processed images.\n * @private\n */\nasync function prepareImages(images) {\n if (!Array.isArray(images)) {\n images = [images];\n }\n\n // Possibly convert any non-images to images\n return await Promise.all(images.map(x => RawImage.read(x)));\n}\n\n/**\n * @typedef {string | URL | Float32Array | Float64Array} AudioInput\n * @typedef {AudioInput|AudioInput[]} AudioPipelineInputs\n */\n\n/**\n * Prepare audios for further tasks.\n * @param {AudioPipelineInputs} audios audios to prepare.\n * @param {number} sampling_rate sampling rate of the audios.\n * @returns {Promise} The preprocessed audio data.\n * @private\n */\nasync function prepareAudios(audios, sampling_rate) {\n if (!Array.isArray(audios)) {\n audios = [audios];\n }\n\n return await Promise.all(audios.map(x => {\n if (typeof x === 'string' || x instanceof URL) {\n return read_audio(x, sampling_rate);\n } else if (x instanceof Float64Array) {\n return new Float32Array(x);\n }\n return x;\n }));\n}\n\n/**\n * @typedef {Object} BoundingBox\n * @property {number} xmin The minimum x coordinate of the bounding box.\n * @property {number} ymin The minimum y coordinate of the bounding box.\n * @property {number} xmax The maximum x coordinate of the bounding box.\n * @property {number} ymax The maximum y coordinate of the bounding box.\n */\n\n/**\n * Helper function to convert list [xmin, xmax, ymin, ymax] into object { \"xmin\": xmin, ... }\n * @param {number[]} box The bounding box as a list.\n * @param {boolean} asInteger Whether to cast to integers.\n * @returns {BoundingBox} The bounding box as an object.\n * @private\n */\nfunction get_bounding_box(box, asInteger) {\n if (asInteger) {\n box = box.map(x => x | 0);\n }\n const [xmin, ymin, xmax, ymax] = box;\n\n return { xmin, ymin, xmax, ymax };\n}\n\n\n/**\n * @callback DisposeType Disposes the item.\n * @returns {Promise} A promise that resolves when the item has been disposed.\n * \n * @typedef {Object} Disposable\n * @property {DisposeType} dispose A promise that resolves when the pipeline has been disposed.\n */\n\n/**\n * The Pipeline class is the class from which all pipelines inherit.\n * Refer to this class for methods shared across different pipelines.\n * @extends Callable\n */\nexport class Pipeline extends Callable {\n /**\n * Create a new Pipeline.\n * @param {Object} options An object containing the following properties:\n * @param {string} [options.task] The task of the pipeline. Useful for specifying subtasks.\n * @param {PreTrainedModel} [options.model] The model used by the pipeline.\n * @param {PreTrainedTokenizer} [options.tokenizer=null] The tokenizer used by the pipeline (if any).\n * @param {Processor} [options.processor=null] The processor used by the pipeline (if any).\n */\n constructor({ task, model, tokenizer = null, processor = null }) {\n super();\n this.task = task;\n this.model = model;\n this.tokenizer = tokenizer;\n this.processor = processor;\n }\n\n /** @type {DisposeType} */\n async dispose() {\n await this.model.dispose();\n }\n}\n\n/**\n * @typedef {Object} ModelTokenizerConstructorArgs\n * @property {string} task The task of the pipeline. Useful for specifying subtasks.\n * @property {PreTrainedModel} model The model used by the pipeline.\n * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline.\n * \n * @typedef {ModelTokenizerConstructorArgs} TextPipelineConstructorArgs An object used to instantiate a text-based pipeline.\n */\n\n/**\n * @typedef {Object} ModelProcessorConstructorArgs\n * @property {string} task The task of the pipeline. Useful for specifying subtasks.\n * @property {PreTrainedModel} model The model used by the pipeline.\n * @property {Processor} processor The processor used by the pipeline.\n * \n * @typedef {ModelProcessorConstructorArgs} AudioPipelineConstructorArgs An object used to instantiate an audio-based pipeline.\n * @typedef {ModelProcessorConstructorArgs} ImagePipelineConstructorArgs An object used to instantiate an image-based pipeline.\n */\n\n\n/**\n * @typedef {Object} ModelTokenizerProcessorConstructorArgs\n * @property {string} task The task of the pipeline. Useful for specifying subtasks.\n * @property {PreTrainedModel} model The model used by the pipeline.\n * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline.\n * @property {Processor} processor The processor used by the pipeline.\n * \n * @typedef {ModelTokenizerProcessorConstructorArgs} TextAudioPipelineConstructorArgs An object used to instantiate a text- and audio-based pipeline.\n * @typedef {ModelTokenizerProcessorConstructorArgs} TextImagePipelineConstructorArgs An object used to instantiate a text- and image-based pipeline.\n */\n\n/**\n * @typedef {Object} TextClassificationSingle\n * @property {string} label The label predicted.\n * @property {number} score The corresponding probability.\n * @typedef {TextClassificationSingle[]} TextClassificationOutput\n * \n * @typedef {Object} TextClassificationPipelineOptions Parameters specific to text classification pipelines.\n * @property {number} [top_k=1] The number of top predictions to be returned.\n * \n * @callback TextClassificationPipelineCallback Classify the text(s) given as inputs.\n * @param {string|string[]} texts The input text(s) to be classified.\n * @param {TextClassificationPipelineOptions} [options] The options to use for text classification.\n * @returns {Promise} An array or object containing the predicted labels and scores.\n * \n * @typedef {TextPipelineConstructorArgs & TextClassificationPipelineCallback & Disposable} TextClassificationPipelineType\n */\n\n/**\n * Text classification pipeline using any `ModelForSequenceClassification`.\n *\n * **Example:** Sentiment-analysis w/ `Xenova/distilbert-base-uncased-finetuned-sst-2-english`.\n * ```javascript\n * const classifier = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english');\n * const output = await classifier('I love transformers!');\n * // [{ label: 'POSITIVE', score: 0.999788761138916 }]\n * ```\n * \n * **Example:** Multilingual sentiment-analysis w/ `Xenova/bert-base-multilingual-uncased-sentiment` (and return top 5 classes).\n * ```javascript\n * const classifier = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment');\n * const output = await classifier('Le meilleur film de tous les temps.', { top_k: 5 });\n * // [\n * // { label: '5 stars', score: 0.9610759615898132 },\n * // { label: '4 stars', score: 0.03323351591825485 },\n * // { label: '3 stars', score: 0.0036155181005597115 },\n * // { label: '1 star', score: 0.0011325967498123646 },\n * // { label: '2 stars', score: 0.0009423971059732139 }\n * // ]\n * ```\n * \n * **Example:** Toxic comment classification w/ `Xenova/toxic-bert` (and return all classes).\n * ```javascript\n * const classifier = await pipeline('text-classification', 'Xenova/toxic-bert');\n * const output = await classifier('I hate you!', { top_k: null });\n * // [\n * // { label: 'toxic', score: 0.9593140482902527 },\n * // { label: 'insult', score: 0.16187334060668945 },\n * // { label: 'obscene', score: 0.03452680632472038 },\n * // { label: 'identity_hate', score: 0.0223250575363636 },\n * // { label: 'threat', score: 0.019197041168808937 },\n * // { label: 'severe_toxic', score: 0.005651099607348442 }\n * // ]\n * ```\n */\nexport class TextClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TextClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new TextClassificationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {TextClassificationPipelineCallback} */\n async _call(texts, {\n top_k = 1\n } = {}) {\n\n // Run tokenization\n const model_inputs = this.tokenizer(texts, {\n padding: true,\n truncation: true,\n });\n\n // Run model\n const outputs = await this.model(model_inputs)\n\n // TODO: Use softmax tensor function\n const function_to_apply =\n this.model.config.problem_type === 'multi_label_classification'\n ? batch => batch.sigmoid()\n : batch => new Tensor(\n 'float32',\n softmax(batch.data),\n batch.dims,\n ); // single_label_classification (default)\n\n const id2label = this.model.config.id2label;\n\n const toReturn = [];\n for (const batch of outputs.logits) {\n const output = function_to_apply(batch);\n\n const scores = await topk(output, top_k);\n\n const values = scores[0].tolist();\n const indices = scores[1].tolist();\n const vals = indices.map((x, i) => ({\n label: id2label ? id2label[x] : `LABEL_${x}`,\n score: values[i],\n }));\n if (top_k === 1) {\n toReturn.push(...vals);\n } else {\n toReturn.push(vals);\n }\n }\n\n return Array.isArray(texts) || top_k === 1 ? /** @type {TextClassificationOutput} */ (toReturn) : /** @type {TextClassificationOutput[]} */ (toReturn)[0];\n }\n}\n\n/**\n * @typedef {Object} TokenClassificationSingle\n * @property {string} word The token/word classified. This is obtained by decoding the selected tokens.\n * @property {number} score The corresponding probability for `entity`.\n * @property {string} entity The entity predicted for that token/word.\n * @property {number} index The index of the corresponding token in the sentence.\n * @property {number} [start] The index of the start of the corresponding entity in the sentence.\n * @property {number} [end] The index of the end of the corresponding entity in the sentence.\n * @typedef {TokenClassificationSingle[]} TokenClassificationOutput\n * \n * @typedef {Object} TokenClassificationPipelineOptions Parameters specific to token classification pipelines.\n * @property {string[]} [ignore_labels] A list of labels to ignore.\n * \n * @callback TokenClassificationPipelineCallback Classify each token of the text(s) given as inputs.\n * @param {string|string[]} texts One or several texts (or one list of texts) for token classification.\n * @param {TokenClassificationPipelineOptions} [options] The options to use for token classification.\n * @returns {Promise} The result.\n * \n * @typedef {TextPipelineConstructorArgs & TokenClassificationPipelineCallback & Disposable} TokenClassificationPipelineType\n */\n\n/**\n * Named Entity Recognition pipeline using any `ModelForTokenClassification`.\n * \n * **Example:** Perform named entity recognition with `Xenova/bert-base-NER`.\n * ```javascript\n * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER');\n * const output = await classifier('My name is Sarah and I live in London');\n * // [\n * // { entity: 'B-PER', score: 0.9980202913284302, index: 4, word: 'Sarah' },\n * // { entity: 'B-LOC', score: 0.9994474053382874, index: 9, word: 'London' }\n * // ]\n * ```\n * \n * **Example:** Perform named entity recognition with `Xenova/bert-base-NER` (and return all labels).\n * ```javascript\n * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER');\n * const output = await classifier('Sarah lives in the United States of America', { ignore_labels: [] });\n * // [\n * // { entity: 'B-PER', score: 0.9966587424278259, index: 1, word: 'Sarah' },\n * // { entity: 'O', score: 0.9987385869026184, index: 2, word: 'lives' },\n * // { entity: 'O', score: 0.9990072846412659, index: 3, word: 'in' },\n * // { entity: 'O', score: 0.9988298416137695, index: 4, word: 'the' },\n * // { entity: 'B-LOC', score: 0.9995510578155518, index: 5, word: 'United' },\n * // { entity: 'I-LOC', score: 0.9990395307540894, index: 6, word: 'States' },\n * // { entity: 'I-LOC', score: 0.9986724853515625, index: 7, word: 'of' },\n * // { entity: 'I-LOC', score: 0.9975294470787048, index: 8, word: 'America' }\n * // ]\n * ```\n */\nexport class TokenClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TokenClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new TokenClassificationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {TokenClassificationPipelineCallback} */\n async _call(texts, {\n ignore_labels = ['O'],\n } = {}) {\n\n const isBatched = Array.isArray(texts);\n\n // Run tokenization\n const model_inputs = this.tokenizer(isBatched ? texts : [texts], {\n padding: true,\n truncation: true,\n });\n\n // Run model\n const outputs = await this.model(model_inputs)\n\n const logits = outputs.logits;\n const id2label = this.model.config.id2label;\n\n const toReturn = [];\n for (let i = 0; i < logits.dims[0]; ++i) {\n const ids = model_inputs.input_ids[i];\n const batch = logits[i];\n\n // List of tokens that aren't ignored\n const tokens = [];\n for (let j = 0; j < batch.dims[0]; ++j) {\n const tokenData = batch[j];\n const topScoreIndex = max(tokenData.data)[1];\n\n const entity = id2label ? id2label[topScoreIndex] : `LABEL_${topScoreIndex}`;\n if (ignore_labels.includes(entity)) {\n // We predicted a token that should be ignored. So, we skip it.\n continue;\n }\n\n // TODO add option to keep special tokens?\n const word = this.tokenizer.decode([ids[j].item()], { skip_special_tokens: true });\n if (word === '') {\n // Was a special token. So, we skip it.\n continue;\n }\n\n const scores = softmax(tokenData.data);\n\n tokens.push({\n entity: entity,\n score: scores[topScoreIndex],\n index: j,\n word: word,\n\n // TODO: Add support for start and end\n // start: null,\n // end: null,\n });\n }\n toReturn.push(tokens);\n }\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} QuestionAnsweringOutput\n * @property {number} score The probability associated to the answer.\n * @property {number} [start] The character start index of the answer (in the tokenized version of the input).\n * @property {number} [end] The character end index of the answer (in the tokenized version of the input).\n * @property {string} answer The answer to the question.\n * \n * @typedef {Object} QuestionAnsweringPipelineOptions Parameters specific to question answering pipelines.\n * @property {number} [top_k=1] The number of top answer predictions to be returned.\n * \n * @callback QuestionAnsweringPipelineCallback Answer the question(s) given as inputs by using the context(s).\n * @param {string|string[]} question One or several question(s) (must be used in conjunction with the `context` argument).\n * @param {string|string[]} context One or several context(s) associated with the question(s) (must be used in conjunction with the `question` argument).\n * @param {QuestionAnsweringPipelineOptions} [options] The options to use for question answering.\n * @returns {Promise} An array or object containing the predicted answers and scores.\n * \n * @typedef {TextPipelineConstructorArgs & QuestionAnsweringPipelineCallback & Disposable} QuestionAnsweringPipelineType\n */\n\n/**\n * Question Answering pipeline using any `ModelForQuestionAnswering`.\n * \n * **Example:** Run question answering with `Xenova/distilbert-base-uncased-distilled-squad`.\n * ```javascript\n * const answerer = await pipeline('question-answering', 'Xenova/distilbert-base-uncased-distilled-squad');\n * const question = 'Who was Jim Henson?';\n * const context = 'Jim Henson was a nice puppet.';\n * const output = await answerer(question, context);\n * // {\n * // answer: \"a nice puppet\",\n * // score: 0.5768911502526741\n * // }\n * ```\n */\nexport class QuestionAnsweringPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => QuestionAnsweringPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new QuestionAnsweringPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {QuestionAnsweringPipelineCallback} */\n async _call(question, context, {\n top_k = 1\n } = {}) {\n\n // Run tokenization\n const inputs = this.tokenizer(question, {\n text_pair: context,\n padding: true,\n truncation: true,\n });\n\n const { start_logits, end_logits } = await this.model(inputs);\n const input_ids = inputs.input_ids.tolist();\n const attention_mask = inputs.attention_mask.tolist();\n\n // TODO: add support for `return_special_tokens_mask`\n const special_tokens = this.tokenizer.all_special_ids;\n\n /** @type {QuestionAnsweringOutput[]} */\n const toReturn = [];\n for (let j = 0; j < start_logits.dims[0]; ++j) {\n const ids = input_ids[j];\n const sepIndex = ids.findIndex(x =>\n // We use == to match bigint with number\n // @ts-ignore\n x == this.tokenizer.sep_token_id\n );\n\n\n const valid_mask = attention_mask[j].map((y, ix) => (\n y == 1\n && (\n ix === 0 // is cls_token\n || (\n ix > sepIndex\n && special_tokens.findIndex(x => x == ids[ix]) === -1 // token is not a special token (special_tokens_mask == 0)\n )\n )\n ));\n\n const start = start_logits[j].tolist();\n const end = end_logits[j].tolist();\n\n // Now, we mask out values that can't be in the answer\n // NOTE: We keep the cls_token unmasked (some models use it to indicate unanswerable questions)\n for (let i = 1; i < start.length; ++i) {\n if (\n attention_mask[j] == 0 // is part of padding\n || i <= sepIndex // is before the sep_token\n || special_tokens.findIndex(x => x == ids[i]) !== -1 // Is a special token\n ) {\n // Make sure non-context indexes in the tensor cannot contribute to the softmax\n start[i] = -Infinity;\n end[i] = -Infinity;\n }\n }\n\n // Normalize logits and spans to retrieve the answer\n const start_scores = softmax(start).map((x, i) => [x, i]);\n const end_scores = softmax(end).map((x, i) => [x, i]);\n\n // Mask CLS\n start_scores[0][0] = 0;\n end_scores[0][0] = 0;\n\n // Generate all valid spans and select best ones\n const options = product(start_scores, end_scores)\n .filter(x => x[0][1] <= x[1][1])\n .map(x => [x[0][1], x[1][1], x[0][0] * x[1][0]])\n .sort((a, b) => b[2] - a[2]);\n\n for (let k = 0; k < Math.min(options.length, top_k); ++k) {\n const [start, end, score] = options[k];\n\n const answer_tokens = ids.slice(start, end + 1)\n\n const answer = this.tokenizer.decode(answer_tokens, {\n skip_special_tokens: true,\n });\n\n // TODO add start and end?\n // NOTE: HF returns character index\n toReturn.push({\n answer, score\n });\n }\n }\n\n // Mimic HF's return type based on top_k\n return (top_k === 1) ? toReturn[0] : toReturn;\n }\n}\n\n\n/**\n * @typedef {Object} FillMaskSingle\n * @property {string} sequence The corresponding input with the mask token prediction.\n * @property {number} score The corresponding probability.\n * @property {number} token The predicted token id (to replace the masked one).\n * @property {string} token_str The predicted token (to replace the masked one).\n * @typedef {FillMaskSingle[]} FillMaskOutput\n * \n * @typedef {Object} FillMaskPipelineOptions Parameters specific to fill mask pipelines.\n * @property {number} [top_k=5] When passed, overrides the number of predictions to return.\n * \n * @callback FillMaskPipelineCallback Fill the masked token in the text(s) given as inputs.\n * @param {string|string[]} texts One or several texts (or one list of prompts) with masked tokens.\n * @param {FillMaskPipelineOptions} [options] The options to use for masked language modelling.\n * @returns {Promise} An array of objects containing the score, predicted token, predicted token string,\n * and the sequence with the predicted token filled in, or an array of such arrays (one for each input text).\n * If only one input text is given, the output will be an array of objects.\n * @throws {Error} When the mask token is not found in the input text.\n * \n * @typedef {TextPipelineConstructorArgs & FillMaskPipelineCallback & Disposable} FillMaskPipelineType\n */\n\n/**\n * Masked language modeling prediction pipeline using any `ModelWithLMHead`.\n * \n * **Example:** Perform masked language modelling (a.k.a. \"fill-mask\") with `Xenova/bert-base-uncased`.\n * ```javascript\n * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased');\n * const output = await unmasker('The goal of life is [MASK].');\n * // [\n * // { token_str: 'survival', score: 0.06137419492006302, token: 8115, sequence: 'The goal of life is survival.' },\n * // { token_str: 'love', score: 0.03902450203895569, token: 1567, sequence: 'The goal of life is love.' },\n * // { token_str: 'happiness', score: 0.03253183513879776, token: 9266, sequence: 'The goal of life is happiness.' },\n * // { token_str: 'freedom', score: 0.018736306577920914, token: 4438, sequence: 'The goal of life is freedom.' },\n * // { token_str: 'life', score: 0.01859794743359089, token: 1297, sequence: 'The goal of life is life.' }\n * // ]\n * ```\n * \n * **Example:** Perform masked language modelling (a.k.a. \"fill-mask\") with `Xenova/bert-base-cased` (and return top result).\n * ```javascript\n * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased');\n * const output = await unmasker('The Milky Way is a [MASK] galaxy.', { top_k: 1 });\n * // [{ token_str: 'spiral', score: 0.6299987435340881, token: 14061, sequence: 'The Milky Way is a spiral galaxy.' }]\n * ```\n */\nexport class FillMaskPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => FillMaskPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new FillMaskPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {FillMaskPipelineCallback} */\n async _call(texts, {\n top_k = 5\n } = {}) {\n\n // Run tokenization\n const model_inputs = this.tokenizer(texts, {\n padding: true,\n truncation: true,\n });\n\n // Run model\n const { logits } = await this.model(model_inputs)\n\n const toReturn = [];\n\n /** @type {bigint[][]} */\n const input_ids = model_inputs.input_ids.tolist();\n for (let i = 0; i < input_ids.length; ++i) {\n const ids = input_ids[i];\n const mask_token_index = ids.findIndex(x =>\n // We use == to match bigint with number\n // @ts-ignore\n x == this.tokenizer.mask_token_id\n );\n if (mask_token_index === -1) {\n throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`)\n }\n const itemLogits = logits[i][mask_token_index];\n\n const scores = await topk(new Tensor(\n 'float32',\n softmax(itemLogits.data),\n itemLogits.dims,\n ), top_k);\n const values = scores[0].tolist();\n const indices = scores[1].tolist();\n\n toReturn.push(indices.map((x, i) => {\n const sequence = ids.slice();\n sequence[mask_token_index] = x;\n\n return {\n score: values[i],\n token: Number(x),\n token_str: this.tokenizer.model.vocab[x],\n sequence: this.tokenizer.decode(sequence, { skip_special_tokens: true }),\n }\n }));\n }\n return Array.isArray(texts) ? toReturn : toReturn[0];\n }\n}\n\n\n/**\n * @typedef {Object} Text2TextGenerationSingle\n * @property {string} generated_text The generated text.\n * @typedef {Text2TextGenerationSingle[]} Text2TextGenerationOutput\n * \n * @callback Text2TextGenerationPipelineCallback Generate the output text(s) using text(s) given as inputs.\n * @param {string|string[]} texts Input text for the encoder.\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise}\n * \n * @typedef {TextPipelineConstructorArgs & Text2TextGenerationPipelineCallback & Disposable} Text2TextGenerationPipelineType\n */\n\n/**\n * Text2TextGenerationPipeline class for generating text using a model that performs text-to-text generation tasks.\n * \n * **Example:** Text-to-text generation w/ `Xenova/LaMini-Flan-T5-783M`.\n * ```javascript\n * const generator = await pipeline('text2text-generation', 'Xenova/LaMini-Flan-T5-783M');\n * const output = await generator('how can I become more healthy?', {\n * max_new_tokens: 100,\n * });\n * // [{ generated_text: \"To become more healthy, you can: 1. Eat a balanced diet with plenty of fruits, vegetables, whole grains, lean proteins, and healthy fats. 2. Stay hydrated by drinking plenty of water. 3. Get enough sleep and manage stress levels. 4. Avoid smoking and excessive alcohol consumption. 5. Regularly exercise and maintain a healthy weight. 6. Practice good hygiene and sanitation. 7. Seek medical attention if you experience any health issues.\" }]\n * ```\n */\nexport class Text2TextGenerationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => Text2TextGenerationPipelineType} */ (Pipeline)) {\n /** @type {'generated_text'} */\n _key = 'generated_text';\n\n /**\n * Create a new Text2TextGenerationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {Text2TextGenerationPipelineCallback} */\n async _call(texts, generate_kwargs = {}) {\n if (!Array.isArray(texts)) {\n texts = [texts];\n }\n\n\n // Add global prefix, if present\n if (this.model.config.prefix) {\n texts = texts.map(x => this.model.config.prefix + x)\n }\n\n // Handle task specific params:\n const task_specific_params = this.model.config.task_specific_params\n if (task_specific_params && task_specific_params[this.task]) {\n // Add prefixes, if present\n if (task_specific_params[this.task].prefix) {\n texts = texts.map(x => task_specific_params[this.task].prefix + x)\n }\n\n // TODO update generation config\n }\n\n const tokenizer = this.tokenizer;\n const tokenizer_options = {\n padding: true,\n truncation: true,\n }\n let inputs;\n if (this instanceof TranslationPipeline && '_build_translation_inputs' in tokenizer) {\n // TODO: move to Translation pipeline?\n // Currently put here to avoid code duplication\n // @ts-ignore\n inputs = tokenizer._build_translation_inputs(texts, tokenizer_options, generate_kwargs);\n\n } else {\n inputs = tokenizer(texts, tokenizer_options);\n }\n\n const outputTokenIds = await this.model.generate({ ...inputs, ...generate_kwargs });\n return tokenizer.batch_decode(/** @type {Tensor} */(outputTokenIds), {\n skip_special_tokens: true,\n }).map(text => ({ [this._key]: text }));\n }\n}\n\n\n/**\n * @typedef {Object} SummarizationSingle\n * @property {string} summary_text The summary text.\n * @typedef {SummarizationSingle[]} SummarizationOutput\n * \n * @callback SummarizationPipelineCallback Summarize the text(s) given as inputs.\n * @param {string|string[]} texts One or several articles (or one list of articles) to summarize.\n * @param {import('./generation/configuration_utils.js').GenerationConfig} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise}\n * \n * @typedef {TextPipelineConstructorArgs & SummarizationPipelineCallback & Disposable} SummarizationPipelineType\n */\n\n/**\n * A pipeline for summarization tasks, inheriting from Text2TextGenerationPipeline.\n * \n * **Example:** Summarization w/ `Xenova/distilbart-cnn-6-6`.\n * ```javascript\n * const generator = await pipeline('summarization', 'Xenova/distilbart-cnn-6-6');\n * const text = 'The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, ' +\n * 'and the tallest structure in Paris. Its base is square, measuring 125 metres (410 ft) on each side. ' +\n * 'During its construction, the Eiffel Tower surpassed the Washington Monument to become the tallest ' +\n * 'man-made structure in the world, a title it held for 41 years until the Chrysler Building in New ' +\n * 'York City was finished in 1930. It was the first structure to reach a height of 300 metres. Due to ' +\n * 'the addition of a broadcasting aerial at the top of the tower in 1957, it is now taller than the ' +\n * 'Chrysler Building by 5.2 metres (17 ft). Excluding transmitters, the Eiffel Tower is the second ' +\n * 'tallest free-standing structure in France after the Millau Viaduct.';\n * const output = await generator(text, {\n * max_new_tokens: 100,\n * });\n * // [{ summary_text: ' The Eiffel Tower is about the same height as an 81-storey building and the tallest structure in Paris. It is the second tallest free-standing structure in France after the Millau Viaduct.' }]\n * ```\n */\nexport class SummarizationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => SummarizationPipelineType} */ (/** @type {any} */ (Text2TextGenerationPipeline))) {\n /** @type {'summary_text'} */\n _key = 'summary_text';\n\n /**\n * Create a new SummarizationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n}\n\n\n/**\n * @typedef {Object} TranslationSingle\n * @property {string} translation_text The translated text.\n * @typedef {TranslationSingle[]} TranslationOutput\n * \n * @callback TranslationPipelineCallback Translate the text(s) given as inputs.\n * @param {string|string[]} texts Texts to be translated.\n * @param {import('./generation/configuration_utils.js').GenerationConfig} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise}\n * \n * @typedef {TextPipelineConstructorArgs & TranslationPipelineCallback & Disposable} TranslationPipelineType\n */\n\n/**\n * Translates text from one language to another.\n * \n * **Example:** Multilingual translation w/ `Xenova/nllb-200-distilled-600M`.\n * \n * See [here](https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200)\n * for the full list of languages and their corresponding codes.\n * \n * ```javascript\n * const translator = await pipeline('translation', 'Xenova/nllb-200-distilled-600M');\n * const output = await translator('जीवन एक चॉकलेट बॉक्स की तरह है।', {\n * src_lang: 'hin_Deva', // Hindi\n * tgt_lang: 'fra_Latn', // French\n * });\n * // [{ translation_text: 'La vie est comme une boîte à chocolat.' }]\n * ```\n * \n * **Example:** Multilingual translation w/ `Xenova/m2m100_418M`.\n * \n * See [here](https://huggingface.co/facebook/m2m100_418M#languages-covered)\n * for the full list of languages and their corresponding codes.\n * \n * ```javascript\n * const translator = await pipeline('translation', 'Xenova/m2m100_418M');\n * const output = await translator('生活就像一盒巧克力。', {\n * src_lang: 'zh', // Chinese\n * tgt_lang: 'en', // English\n * });\n * // [{ translation_text: 'Life is like a box of chocolate.' }]\n * ```\n * \n * **Example:** Multilingual translation w/ `Xenova/mbart-large-50-many-to-many-mmt`.\n * \n * See [here](https://huggingface.co/facebook/mbart-large-50-many-to-many-mmt#languages-covered)\n * for the full list of languages and their corresponding codes.\n * \n * ```javascript\n * const translator = await pipeline('translation', 'Xenova/mbart-large-50-many-to-many-mmt');\n * const output = await translator('संयुक्त राष्ट्र के प्रमुख का कहना है कि सीरिया में कोई सैन्य समाधान नहीं है', {\n * src_lang: 'hi_IN', // Hindi\n * tgt_lang: 'fr_XX', // French\n * });\n * // [{ translation_text: 'Le chef des Nations affirme qu 'il n 'y a military solution in Syria.' }]\n * ```\n */\nexport class TranslationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TranslationPipelineType} */ (/** @type {any} */ (Text2TextGenerationPipeline))) {\n /** @type {'translation_text'} */\n _key = 'translation_text';\n\n /**\n * Create a new TranslationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n}\n\nfunction isChat(x) {\n return Array.isArray(x) && x.every(x => 'role' in x && 'content' in x);\n}\n\n/**\n * @typedef {import('./tokenizers.js').Message[]} Chat\n * \n * @typedef {Object} TextGenerationSingle\n * @property {string|Chat} generated_text The generated text.\n * @typedef {TextGenerationSingle[]} TextGenerationOutput\n * \n * @typedef {Object} TextGenerationSpecificParams Parameters specific to text-generation pipelines.\n * @property {boolean} [add_special_tokens] Whether or not to add special tokens when tokenizing the sequences.\n * @property {boolean} [return_full_text=true] If set to `false` only added text is returned, otherwise the full text is returned.\n * @typedef {import('./generation/configuration_utils.js').GenerationConfig & TextGenerationSpecificParams} TextGenerationConfig\n * \n * @callback TextGenerationPipelineCallback Complete the prompt(s) given as inputs.\n * @param {string|string[]|Chat|Chat[]} texts One or several prompts (or one list of prompts) to complete.\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise} An array or object containing the generated texts.\n * \n * @typedef {TextPipelineConstructorArgs & TextGenerationPipelineCallback & Disposable} TextGenerationPipelineType\n */\n\n/**\n * Language generation pipeline using any `ModelWithLMHead` or `ModelForCausalLM`.\n * This pipeline predicts the words that will follow a specified text prompt.\n * NOTE: For the full list of generation parameters, see [`GenerationConfig`](./utils/generation#module_utils/generation.GenerationConfig).\n * \n * **Example:** Text generation with `Xenova/distilgpt2` (default settings).\n * ```javascript\n * const generator = await pipeline('text-generation', 'Xenova/distilgpt2');\n * const text = 'I enjoy walking with my cute dog,';\n * const output = await generator(text);\n * // [{ generated_text: \"I enjoy walking with my cute dog, and I love to play with the other dogs.\" }]\n * ```\n * \n * **Example:** Text generation with `Xenova/distilgpt2` (custom settings).\n * ```javascript\n * const generator = await pipeline('text-generation', 'Xenova/distilgpt2');\n * const text = 'Once upon a time, there was';\n * const output = await generator(text, {\n * temperature: 2,\n * max_new_tokens: 10,\n * repetition_penalty: 1.5,\n * no_repeat_ngram_size: 2,\n * num_beams: 2,\n * num_return_sequences: 2,\n * });\n * // [{\n * // \"generated_text\": \"Once upon a time, there was an abundance of information about the history and activities that\"\n * // }, {\n * // \"generated_text\": \"Once upon a time, there was an abundance of information about the most important and influential\"\n * // }]\n * ```\n * \n * **Example:** Run code generation with `Xenova/codegen-350M-mono`.\n * ```javascript\n * const generator = await pipeline('text-generation', 'Xenova/codegen-350M-mono');\n * const text = 'def fib(n):';\n * const output = await generator(text, {\n * max_new_tokens: 44,\n * });\n * // [{\n * // generated_text: 'def fib(n):\\n' +\n * // ' if n == 0:\\n' +\n * // ' return 0\\n' +\n * // ' elif n == 1:\\n' +\n * // ' return 1\\n' +\n * // ' else:\\n' +\n * // ' return fib(n-1) + fib(n-2)\\n'\n * // }]\n * ```\n */\nexport class TextGenerationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TextGenerationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new TextGenerationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {TextGenerationPipelineCallback} */\n async _call(texts, generate_kwargs = {}) {\n let isBatched = false;\n let isChatInput = false;\n\n // Normalize inputs\n /** @type {string[]} */\n let inputs;\n if (typeof texts === 'string') {\n inputs = texts = [texts];\n } else if (Array.isArray(texts) && texts.every(x => typeof x === 'string')) {\n isBatched = true;\n inputs = /** @type {string[]} */(texts);\n } else {\n if (isChat(texts)) {\n texts = [/** @type {Chat} */(texts)];\n } else if (Array.isArray(texts) && texts.every(isChat)) {\n isBatched = true;\n } else {\n throw new Error('Input must be a string, an array of strings, a Chat, or an array of Chats');\n }\n isChatInput = true;\n\n // If the input is a chat, we need to apply the chat template\n inputs = /** @type {string[]} */(/** @type {Chat[]} */ (texts).map(\n x => this.tokenizer.apply_chat_template(x, {\n tokenize: false,\n add_generation_prompt: true,\n })\n ));\n }\n\n // By default, do not add special tokens\n const add_special_tokens = generate_kwargs.add_special_tokens ?? false;\n\n // By default, return full text\n const return_full_text = isChatInput\n ? false\n : generate_kwargs.return_full_text ?? true;\n\n this.tokenizer.padding_side = 'left';\n const text_inputs = this.tokenizer(inputs, {\n add_special_tokens,\n padding: true,\n truncation: true,\n });\n\n const outputTokenIds = /** @type {Tensor} */(await this.model.generate({\n ...text_inputs,\n ...generate_kwargs\n }));\n\n const decoded = this.tokenizer.batch_decode(outputTokenIds, {\n skip_special_tokens: true,\n });\n\n let promptLengths;\n if (!return_full_text && text_inputs.input_ids.dims.at(-1) > 0) {\n promptLengths = this.tokenizer.batch_decode(text_inputs.input_ids, {\n skip_special_tokens: true,\n }).map(x => x.length);\n }\n\n /** @type {TextGenerationOutput[]} */\n const toReturn = Array.from({ length: texts.length }, _ => []);\n for (let i = 0; i < decoded.length; ++i) {\n const textIndex = Math.floor(i / outputTokenIds.dims[0] * texts.length);\n\n if (promptLengths) {\n // Trim the decoded text to only include the generated part\n decoded[i] = decoded[i].slice(promptLengths[textIndex]);\n }\n toReturn[textIndex].push({\n generated_text: isChatInput\n ? [\n ...((/** @type {Chat[]} */(texts)[textIndex])),\n { role: 'assistant', content: decoded[i] },\n ]\n : decoded[i]\n });\n }\n return (!isBatched && toReturn.length === 1) ? toReturn[0] : toReturn;\n }\n}\n\n/**\n * @typedef {Object} ZeroShotClassificationOutput\n * @property {string} sequence The sequence for which this is the output.\n * @property {string[]} labels The labels sorted by order of likelihood.\n * @property {number[]} scores The probabilities for each of the labels.\n * \n * @typedef {Object} ZeroShotClassificationPipelineOptions Parameters specific to zero-shot classification pipelines.\n * @property {string} [hypothesis_template=\"This example is {}.\"] The template used to turn each\n * candidate label into an NLI-style hypothesis. The candidate label will replace the {} placeholder.\n * @property {boolean} [multi_label=false] Whether or not multiple candidate labels can be true.\n * If `false`, the scores are normalized such that the sum of the label likelihoods for each sequence\n * is 1. If `true`, the labels are considered independent and probabilities are normalized for each\n * candidate by doing a softmax of the entailment score vs. the contradiction score.\n * \n * @callback ZeroShotClassificationPipelineCallback Classify the sequence(s) given as inputs.\n * @param {string|string[]} texts The sequence(s) to classify, will be truncated if the model input is too large.\n * @param {string|string[]} candidate_labels The set of possible class labels to classify each sequence into.\n * Can be a single label, a string of comma-separated labels, or a list of labels.\n * @param {ZeroShotClassificationPipelineOptions} [options] The options to use for zero-shot classification.\n * @returns {Promise} An array or object containing the predicted labels and scores.\n * \n * @typedef {TextPipelineConstructorArgs & ZeroShotClassificationPipelineCallback & Disposable} ZeroShotClassificationPipelineType\n */\n\n/**\n * NLI-based zero-shot classification pipeline using a `ModelForSequenceClassification`\n * trained on NLI (natural language inference) tasks. Equivalent of `text-classification`\n * pipelines, but these models don't require a hardcoded number of potential classes, they\n * can be chosen at runtime. It usually means it's slower but it is **much** more flexible.\n * \n * **Example:** Zero shot classification with `Xenova/mobilebert-uncased-mnli`.\n * ```javascript\n * const classifier = await pipeline('zero-shot-classification', 'Xenova/mobilebert-uncased-mnli');\n * const text = 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.';\n * const labels = [ 'mobile', 'billing', 'website', 'account access' ];\n * const output = await classifier(text, labels);\n * // {\n * // sequence: 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.',\n * // labels: [ 'mobile', 'website', 'billing', 'account access' ],\n * // scores: [ 0.5562091040482018, 0.1843621307860853, 0.13942646639336376, 0.12000229877234923 ]\n * // }\n * ```\n * \n * **Example:** Zero shot classification with `Xenova/nli-deberta-v3-xsmall` (multi-label).\n * ```javascript\n * const classifier = await pipeline('zero-shot-classification', 'Xenova/nli-deberta-v3-xsmall');\n * const text = 'I have a problem with my iphone that needs to be resolved asap!';\n * const labels = [ 'urgent', 'not urgent', 'phone', 'tablet', 'computer' ];\n * const output = await classifier(text, labels, { multi_label: true });\n * // {\n * // sequence: 'I have a problem with my iphone that needs to be resolved asap!',\n * // labels: [ 'urgent', 'phone', 'computer', 'tablet', 'not urgent' ],\n * // scores: [ 0.9958870956360275, 0.9923963400697035, 0.002333537946160235, 0.0015134138567598765, 0.0010699384208377163 ]\n * // }\n * ```\n */\nexport class ZeroShotClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => ZeroShotClassificationPipelineType} */ (Pipeline)) {\n /**\n * Create a new ZeroShotClassificationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n\n // Use model config to get label2id mapping\n this.label2id = Object.fromEntries(\n Object.entries((/** @type {any} */(this).model).config.label2id).map(\n ([k, v]) => [k.toLowerCase(), v]\n )\n );\n\n this.entailment_id = this.label2id['entailment'];\n if (this.entailment_id === undefined) {\n console.warn(\"Could not find 'entailment' in label2id mapping. Using 2 as entailment_id.\");\n this.entailment_id = 2;\n }\n\n this.contradiction_id = this.label2id['contradiction'] ?? this.label2id['not_entailment'];\n if (this.contradiction_id === undefined) {\n console.warn(\"Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id.\");\n this.contradiction_id = 0;\n }\n }\n\n /** @type {ZeroShotClassificationPipelineCallback} */\n async _call(texts, candidate_labels, {\n hypothesis_template = \"This example is {}.\",\n multi_label = false,\n } = {}) {\n\n const isBatched = Array.isArray(texts);\n if (!isBatched) {\n texts = [/** @type {string} */ (texts)];\n }\n if (!Array.isArray(candidate_labels)) {\n candidate_labels = [candidate_labels];\n }\n\n // Insert labels into hypothesis template\n const hypotheses = candidate_labels.map(\n x => hypothesis_template.replace('{}', x)\n );\n\n // How to perform the softmax over the logits:\n // - true: softmax over the entailment vs. contradiction dim for each label independently\n // - false: softmax the \"entailment\" logits over all candidate labels\n const softmaxEach = multi_label || candidate_labels.length === 1;\n\n /** @type {ZeroShotClassificationOutput[]} */\n const toReturn = [];\n for (const premise of texts) {\n const entails_logits = [];\n\n for (const hypothesis of hypotheses) {\n const inputs = this.tokenizer(premise, {\n text_pair: hypothesis,\n padding: true,\n truncation: true,\n })\n const outputs = await this.model(inputs)\n\n if (softmaxEach) {\n entails_logits.push([\n outputs.logits.data[this.contradiction_id],\n outputs.logits.data[this.entailment_id]\n ])\n } else {\n entails_logits.push(outputs.logits.data[this.entailment_id])\n }\n }\n\n /** @type {number[]} */\n const scores = softmaxEach\n ? entails_logits.map(x => softmax(x)[1])\n : softmax(entails_logits);\n\n // Sort by scores (desc) and return scores with indices\n const scores_sorted = scores\n .map((x, i) => [x, i])\n .sort((a, b) => (b[0] - a[0]));\n\n toReturn.push({\n sequence: premise,\n labels: scores_sorted.map(x => candidate_labels[x[1]]),\n scores: scores_sorted.map(x => x[0]),\n });\n }\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} FeatureExtractionPipelineOptions Parameters specific to feature extraction pipelines.\n * @property {'none'|'mean'|'cls'} [pooling=\"none\"] The pooling method to use.\n * @property {boolean} [normalize=false] Whether or not to normalize the embeddings in the last dimension.\n * @property {boolean} [quantize=false] Whether or not to quantize the embeddings.\n * @property {'binary'|'ubinary'} [precision='binary'] The precision to use for quantization. \n * \n * @callback FeatureExtractionPipelineCallback Extract the features of the input(s).\n * @param {string|string[]} texts One or several texts (or one list of texts) to get the features of.\n * @param {FeatureExtractionPipelineOptions} [options] The options to use for feature extraction.\n * @returns {Promise} The features computed by the model.\n * \n * @typedef {TextPipelineConstructorArgs & FeatureExtractionPipelineCallback & Disposable} FeatureExtractionPipelineType\n */\n\n/**\n * Feature extraction pipeline using no model head. This pipeline extracts the hidden\n * states from the base transformer, which can be used as features in downstream tasks.\n * \n * **Example:** Run feature extraction with `bert-base-uncased` (without pooling/normalization).\n * ```javascript\n * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' });\n * const output = await extractor('This is a simple test.');\n * // Tensor {\n * // type: 'float32',\n * // data: Float32Array [0.05939924716949463, 0.021655935794115067, ...],\n * // dims: [1, 8, 768]\n * // }\n * ```\n * \n * **Example:** Run feature extraction with `bert-base-uncased` (with pooling/normalization).\n * ```javascript\n * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' });\n * const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true });\n * // Tensor {\n * // type: 'float32',\n * // data: Float32Array [0.03373778983950615, -0.010106077417731285, ...],\n * // dims: [1, 768]\n * // }\n * ```\n * \n * **Example:** Calculating embeddings with `sentence-transformers` models.\n * ```javascript\n * const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');\n * const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true });\n * // Tensor {\n * // type: 'float32',\n * // data: Float32Array [0.09094982594251633, -0.014774246141314507, ...],\n * // dims: [1, 384]\n * // }\n * ```\n * **Example:** Calculating binary embeddings with `sentence-transformers` models.\n * ```javascript\n * const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');\n * const output = await extractor('This is a simple test.', { pooling: 'mean', quantize: true, precision: 'binary' });\n * // Tensor {\n * // type: 'int8',\n * // data: Int8Array [49, 108, 24, ...],\n * // dims: [1, 48]\n * // }\n * ```\n */\nexport class FeatureExtractionPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => FeatureExtractionPipelineType} */ (Pipeline)) {\n /**\n * Create a new FeatureExtractionPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {FeatureExtractionPipelineCallback} */\n async _call(texts, {\n pooling = /** @type {'none'} */('none'),\n normalize = false,\n quantize = false,\n precision = /** @type {'binary'} */('binary'),\n } = {}) {\n\n // Run tokenization\n const model_inputs = this.tokenizer(texts, {\n padding: true,\n truncation: true,\n });\n\n // Run model\n const outputs = await this.model(model_inputs)\n\n // TODO: Provide warning to the user that they might be using model which was not exported\n // specifically for feature extraction\n // console.log(this.model.config)\n // console.log(outputs)\n\n /** @type {Tensor} */\n let result = outputs.last_hidden_state ?? outputs.logits ?? outputs.token_embeddings;\n if (pooling === 'none') {\n // Skip pooling\n } else if (pooling === 'mean') {\n result = mean_pooling(result, model_inputs.attention_mask);\n } else if (pooling === 'cls') {\n result = result.slice(null, 0);\n } else {\n throw Error(`Pooling method '${pooling}' not supported.`);\n }\n\n if (normalize) {\n result = result.normalize(2, -1);\n }\n\n if (quantize) {\n result = quantize_embeddings(result, precision);\n }\n\n return result;\n }\n}\n\n\n/**\n * @typedef {Object} ImageFeatureExtractionPipelineOptions Parameters specific to image feature extraction pipelines.\n * @property {boolean} [pool=null] Whether or not to return the pooled output. If set to `false`, the model will return the raw hidden states.\n * \n * @callback ImageFeatureExtractionPipelineCallback Extract the features of the input(s).\n * @param {ImagePipelineInputs} images One or several images (or one list of images) to get the features of.\n * @param {ImageFeatureExtractionPipelineOptions} [options] The options to use for image feature extraction.\n * @returns {Promise} The image features computed by the model.\n * \n * @typedef {ImagePipelineConstructorArgs & ImageFeatureExtractionPipelineCallback & Disposable} ImageFeatureExtractionPipelineType\n */\n\n/**\n * Image feature extraction pipeline using no model head. This pipeline extracts the hidden\n * states from the base transformer, which can be used as features in downstream tasks.\n * \n * **Example:** Perform image feature extraction with `Xenova/vit-base-patch16-224-in21k`.\n * ```javascript\n * const image_feature_extractor = await pipeline('image-feature-extraction', 'Xenova/vit-base-patch16-224-in21k');\n * const url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png';\n * const features = await image_feature_extractor(url);\n * // Tensor {\n * // dims: [ 1, 197, 768 ],\n * // type: 'float32',\n * // data: Float32Array(151296) [ ... ],\n * // size: 151296\n * // }\n * ```\n * \n * **Example:** Compute image embeddings with `Xenova/clip-vit-base-patch32`.\n * ```javascript\n * const image_feature_extractor = await pipeline('image-feature-extraction', 'Xenova/clip-vit-base-patch32');\n * const url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png';\n * const features = await image_feature_extractor(url);\n * // Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [ ... ],\n * // size: 512\n * // }\n * ```\n */\nexport class ImageFeatureExtractionPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageFeatureExtractionPipelineType} */ (Pipeline)) {\n /**\n * Create a new ImageFeatureExtractionPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ImageFeatureExtractionPipelineCallback} */\n async _call(images, {\n pool = null,\n } = {}) {\n\n const preparedImages = await prepareImages(images);\n const { pixel_values } = await this.processor(preparedImages);\n const outputs = await this.model({ pixel_values });\n\n /** @type {Tensor} */\n let result;\n if (pool) {\n if (!('pooler_output' in outputs)) {\n throw Error(`No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.`);\n }\n result = outputs.pooler_output;\n\n } else {\n result = outputs.last_hidden_state ?? outputs.logits ?? outputs.image_embeds;\n }\n return result;\n }\n}\n\n// TODO\n// export class SentenceSimilarityPipeline extends Pipeline {\n// }\n\n/**\n * @typedef {Object} AudioClassificationSingle\n * @property {string} label The label predicted.\n * @property {number} score The corresponding probability.\n * @typedef {AudioClassificationSingle[]} AudioClassificationOutput\n * \n * @typedef {Object} AudioClassificationPipelineOptions Parameters specific to audio classification pipelines.\n * @property {number} [top_k=5] The number of top labels that will be returned by the pipeline.\n * If the provided number is `null` or higher than the number of labels available in the model configuration,\n * it will default to the number of labels.\n * \n * @callback AudioClassificationPipelineCallback Classify the sequence(s) given as inputs.\n * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either:\n * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate\n * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API.\n * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`.\n * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).\n * @param {AudioClassificationPipelineOptions} [options] The options to use for audio classification.\n * @returns {Promise} An array or object containing the predicted labels and scores.\n * \n * @typedef {AudioPipelineConstructorArgs & AudioClassificationPipelineCallback & Disposable} AudioClassificationPipelineType\n */\n\n/**\n * Audio classification pipeline using any `AutoModelForAudioClassification`.\n * This pipeline predicts the class of a raw waveform or an audio file.\n * \n * **Example:** Perform audio classification with `Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech`.\n * ```javascript\n * const classifier = await pipeline('audio-classification', 'Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const output = await classifier(url);\n * // [\n * // { label: 'male', score: 0.9981542229652405 },\n * // { label: 'female', score: 0.001845747814513743 }\n * // ]\n * ```\n * \n * **Example:** Perform audio classification with `Xenova/ast-finetuned-audioset-10-10-0.4593` and return top 4 results.\n * ```javascript\n * const classifier = await pipeline('audio-classification', 'Xenova/ast-finetuned-audioset-10-10-0.4593');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cat_meow.wav';\n * const output = await classifier(url, { top_k: 4 });\n * // [\n * // { label: 'Meow', score: 0.5617874264717102 },\n * // { label: 'Cat', score: 0.22365376353263855 },\n * // { label: 'Domestic animals, pets', score: 0.1141069084405899 },\n * // { label: 'Animal', score: 0.08985692262649536 },\n * // ]\n * ```\n */\nexport class AudioClassificationPipeline extends (/** @type {new (options: AudioPipelineConstructorArgs) => AudioClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new AudioClassificationPipeline.\n * @param {AudioPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {AudioClassificationPipelineCallback} */\n async _call(audio, {\n top_k = 5\n } = {}) {\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n const preparedAudios = await prepareAudios(audio, sampling_rate);\n\n const id2label = this.model.config.id2label;\n\n const toReturn = [];\n for (const aud of preparedAudios) {\n const inputs = await this.processor(aud);\n const output = await this.model(inputs);\n const logits = output.logits[0];\n\n const scores = await topk(new Tensor(\n 'float32',\n softmax(logits.data),\n logits.dims,\n ), top_k);\n\n const values = scores[0].tolist();\n const indices = scores[1].tolist();\n\n const vals = indices.map((x, i) => ({\n label: /** @type {string} */ (id2label ? id2label[x] : `LABEL_${x}`),\n score: /** @type {number} */ (values[i]),\n }));\n\n toReturn.push(vals);\n };\n return Array.isArray(audio) ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} ZeroShotAudioClassificationOutput\n * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`.\n * @property {number} score The score attributed by the model for that label (between 0 and 1).\n * \n * @typedef {Object} ZeroShotAudioClassificationPipelineOptions Parameters specific to zero-shot audio classification pipelines.\n * @property {string} [hypothesis_template=\"This is a sound of {}.\"] The sentence used in conjunction with `candidate_labels`\n * to attempt the audio classification by replacing the placeholder with the candidate_labels.\n * Then likelihood is estimated by using `logits_per_audio`.\n * \n * @callback ZeroShotAudioClassificationPipelineCallback Classify the sequence(s) given as inputs.\n * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either:\n * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate\n * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API.\n * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`.\n * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).\n * @param {string[]} candidate_labels The candidate labels for this audio.\n * @param {ZeroShotAudioClassificationPipelineOptions} [options] The options to use for zero-shot audio classification.\n * @returns {Promise} An array of objects containing the predicted labels and scores.\n * \n * @typedef {TextAudioPipelineConstructorArgs & ZeroShotAudioClassificationPipelineCallback & Disposable} ZeroShotAudioClassificationPipelineType\n */\n\n/**\n * Zero shot audio classification pipeline using `ClapModel`. This pipeline predicts the class of an audio when you\n * provide an audio and a set of `candidate_labels`.\n * \n * **Example**: Perform zero-shot audio classification with `Xenova/clap-htsat-unfused`.\n * ```javascript\n * const classifier = await pipeline('zero-shot-audio-classification', 'Xenova/clap-htsat-unfused');\n * const audio = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/dog_barking.wav';\n * const candidate_labels = ['dog', 'vaccum cleaner'];\n * const scores = await classifier(audio, candidate_labels);\n * // [\n * // { score: 0.9993992447853088, label: 'dog' },\n * // { score: 0.0006007603369653225, label: 'vaccum cleaner' }\n * // ]\n * ```\n */\nexport class ZeroShotAudioClassificationPipeline extends (/** @type {new (options: TextAudioPipelineConstructorArgs) => ZeroShotAudioClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ZeroShotAudioClassificationPipeline.\n * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ZeroShotAudioClassificationPipelineCallback} */\n async _call(audio, candidate_labels, {\n hypothesis_template = \"This is a sound of {}.\"\n } = {}) {\n\n const single = !Array.isArray(audio);\n if (single) {\n audio = [/** @type {AudioInput} */ (audio)];\n }\n\n // Insert label into hypothesis template \n const texts = candidate_labels.map(\n x => hypothesis_template.replace('{}', x)\n );\n\n // Run tokenization\n const text_inputs = this.tokenizer(texts, {\n padding: true,\n truncation: true,\n });\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n const preparedAudios = await prepareAudios(audio, sampling_rate);\n\n const toReturn = [];\n for (const aud of preparedAudios) {\n const audio_inputs = await this.processor(aud);\n\n // Run model with both text and audio inputs\n const output = await this.model({ ...text_inputs, ...audio_inputs });\n\n // Compute softmax per audio\n const probs = softmax(output.logits_per_audio.data);\n\n toReturn.push([...probs].map((x, i) => ({\n score: x,\n label: candidate_labels[i]\n })));\n }\n return single ? toReturn[0] : toReturn;\n }\n}\n\n/**\n * @typedef {Object} Chunk\n * @property {[number, number]} timestamp The start and end timestamp of the chunk in seconds.\n * @property {string} text The recognized text.\n */\n\n/**\n * @typedef {Object} AutomaticSpeechRecognitionOutput\n * @property {string} text The recognized text.\n * @property {Chunk[]} [chunks] When using `return_timestamps`, the `chunks` will become a list\n * containing all the various text chunks identified by the model.\n * \n * @typedef {Object} AutomaticSpeechRecognitionSpecificParams Parameters specific to automatic-speech-recognition pipelines.\n * @property {boolean|'word'} [return_timestamps] Whether to return timestamps or not. Default is `false`.\n * @property {number} [chunk_length_s] The length of audio chunks to process in seconds. Default is 0 (no chunking).\n * @property {number} [stride_length_s] The length of overlap between consecutive audio chunks in seconds. If not provided, defaults to `chunk_length_s / 6`.\n * @property {boolean} [force_full_sequences] Whether to force outputting full sequences or not. Default is `false`.\n * @property {string} [language] The source language. Default is `null`, meaning it should be auto-detected. Use this to potentially improve performance if the source language is known.\n * @property {string} [task] The task to perform. Default is `null`, meaning it should be auto-detected.\n * @property {number} [num_frames] The number of frames in the input audio.\n * @typedef {import('./generation/configuration_utils.js').GenerationConfig & AutomaticSpeechRecognitionSpecificParams} AutomaticSpeechRecognitionConfig\n * \n * @callback AutomaticSpeechRecognitionPipelineCallback Transcribe the audio sequence(s) given as inputs to text.\n * @param {AudioPipelineInputs} audio The input audio file(s) to be transcribed. The input is either:\n * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate\n * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API.\n * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`.\n * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise} An object containing the transcription text and optionally timestamps if `return_timestamps` is `true`.\n * \n * @typedef {TextAudioPipelineConstructorArgs & AutomaticSpeechRecognitionPipelineCallback & Disposable} AutomaticSpeechRecognitionPipelineType\n */\n\n/**\n * Pipeline that aims at extracting spoken text contained within some audio.\n *\n * **Example:** Transcribe English.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const output = await transcriber(url);\n * // { text: \" And so my fellow Americans ask not what your country can do for you, ask what you can do for your country.\" }\n * ```\n * \n * **Example:** Transcribe English w/ timestamps.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const output = await transcriber(url, { return_timestamps: true });\n * // {\n * // text: \" And so my fellow Americans ask not what your country can do for you, ask what you can do for your country.\"\n * // chunks: [\n * // { timestamp: [0, 8], text: \" And so my fellow Americans ask not what your country can do for you\" }\n * // { timestamp: [8, 11], text: \" ask what you can do for your country.\" }\n * // ]\n * // }\n * ```\n * \n * **Example:** Transcribe English w/ word-level timestamps.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const output = await transcriber(url, { return_timestamps: 'word' });\n * // {\n * // \"text\": \" And so my fellow Americans ask not what your country can do for you ask what you can do for your country.\",\n * // \"chunks\": [\n * // { \"text\": \" And\", \"timestamp\": [0, 0.78] },\n * // { \"text\": \" so\", \"timestamp\": [0.78, 1.06] },\n * // { \"text\": \" my\", \"timestamp\": [1.06, 1.46] },\n * // ...\n * // { \"text\": \" for\", \"timestamp\": [9.72, 9.92] },\n * // { \"text\": \" your\", \"timestamp\": [9.92, 10.22] },\n * // { \"text\": \" country.\", \"timestamp\": [10.22, 13.5] }\n * // ]\n * // }\n * ```\n * \n * **Example:** Transcribe French.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3';\n * const output = await transcriber(url, { language: 'french', task: 'transcribe' });\n * // { text: \" J'adore, j'aime, je n'aime pas, je déteste.\" }\n * ```\n * \n * **Example:** Translate French to English.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3';\n * const output = await transcriber(url, { language: 'french', task: 'translate' });\n * // { text: \" I love, I like, I don't like, I hate.\" }\n * ```\n * \n * **Example:** Transcribe/translate audio longer than 30 seconds.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/ted_60.wav';\n * const output = await transcriber(url, { chunk_length_s: 30, stride_length_s: 5 });\n * // { text: \" So in college, I was a government major, which means [...] So I'd start off light and I'd bump it up\" }\n * ```\n */\nexport class AutomaticSpeechRecognitionPipeline extends (/** @type {new (options: TextAudioPipelineConstructorArgs) => AutomaticSpeechRecognitionPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new AutomaticSpeechRecognitionPipeline.\n * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {AutomaticSpeechRecognitionPipelineCallback} */\n async _call(audio, kwargs = {}) {\n switch (this.model.config.model_type) {\n case 'whisper':\n return this._call_whisper(audio, kwargs)\n case 'wav2vec2':\n case 'wav2vec2-bert':\n case 'unispeech':\n case 'unispeech-sat':\n case 'hubert':\n return this._call_wav2vec2(audio, kwargs)\n default:\n throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)\n }\n }\n\n /**\n * @type {AutomaticSpeechRecognitionPipelineCallback}\n * @private\n */\n async _call_wav2vec2(audio, kwargs) {\n // TODO use kwargs\n\n if (kwargs.language) {\n console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to \"English\".');\n }\n if (kwargs.task) {\n console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to \"transcribe\".');\n }\n\n const single = !Array.isArray(audio);\n if (single) {\n audio = [/** @type {AudioInput} */ (audio)];\n }\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n const preparedAudios = await prepareAudios(audio, sampling_rate);\n\n const toReturn = [];\n for (const aud of preparedAudios) {\n const inputs = await this.processor(aud);\n const output = await this.model(inputs);\n const logits = output.logits[0];\n\n const predicted_ids = [];\n for (const item of logits) {\n predicted_ids.push(max(item.data)[1])\n }\n const predicted_sentences = this.tokenizer.decode(predicted_ids)\n toReturn.push({ text: predicted_sentences })\n }\n return single ? toReturn[0] : toReturn;\n }\n\n /**\n * @type {AutomaticSpeechRecognitionPipelineCallback}\n * @private\n */\n async _call_whisper(audio, kwargs) {\n const return_timestamps = kwargs.return_timestamps ?? false;\n const chunk_length_s = kwargs.chunk_length_s ?? 0;\n const force_full_sequences = kwargs.force_full_sequences ?? false;\n let stride_length_s = kwargs.stride_length_s ?? null;\n\n const generation_config = { ...kwargs }\n\n if (return_timestamps === 'word') {\n generation_config['return_token_timestamps'] = true;\n generation_config['return_timestamps'] = false; // Do not predict timestamp tokens\n }\n\n const single = !Array.isArray(audio);\n if (single) {\n audio = [/** @type {AudioInput} */ (audio)];\n }\n\n const time_precision = this.processor.feature_extractor.config.chunk_length / this.model.config.max_source_positions;\n const hop_length = this.processor.feature_extractor.config.hop_length;\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n const preparedAudios = await prepareAudios(audio, sampling_rate);\n\n const toReturn = [];\n for (const aud of preparedAudios) {\n /** @type {{stride: number[], input_features: Tensor, is_last: boolean, tokens?: bigint[], token_timestamps?: number[]}[]} */\n let chunks = [];\n if (chunk_length_s > 0) {\n if (stride_length_s === null) {\n stride_length_s = chunk_length_s / 6;\n } else if (chunk_length_s <= stride_length_s) {\n throw Error(\"`chunk_length_s` must be larger than `stride_length_s`.\")\n }\n\n // TODO support different stride_length_s (for left and right)\n\n const window = sampling_rate * chunk_length_s;\n const stride = sampling_rate * stride_length_s;\n const jump = window - 2 * stride;\n let offset = 0;\n\n // Create subarrays of audio with overlaps\n while (true) {\n const offset_end = offset + window;\n const subarr = aud.subarray(offset, offset_end);\n const feature = await this.processor(subarr);\n\n const is_first = offset === 0;\n const is_last = offset_end >= aud.length;\n chunks.push({\n stride: [\n subarr.length,\n is_first ? 0 : stride,\n is_last ? 0 : stride\n ],\n input_features: feature.input_features,\n is_last,\n })\n if (is_last) break;\n offset += jump;\n }\n\n } else {\n chunks = [{\n stride: [aud.length, 0, 0],\n input_features: (await this.processor(aud)).input_features,\n is_last: true\n }]\n }\n\n // Generate for each set of input features\n for (const chunk of chunks) {\n generation_config.num_frames = Math.floor(chunk.stride[0] / hop_length);\n\n // NOTE: doing sequentially for now\n const data = await this.model.generate({\n inputs: chunk.input_features,\n ...generation_config\n });\n\n // TODO: Right now we only get top beam\n if (return_timestamps === 'word') {\n chunk.tokens = data.sequences.tolist()[0];\n chunk.token_timestamps = data.token_timestamps.tolist()[0].map(\n (/** @type {number} */ x) => round(x, 2)\n );\n\n } else {\n chunk.tokens = (/** @type {Tensor} */(data))[0].tolist();\n }\n\n // convert stride to seconds\n chunk.stride = chunk.stride.map(x => x / sampling_rate);\n }\n\n // Merge text chunks\n // @ts-ignore\n const [full_text, optional] = this.tokenizer._decode_asr(chunks, {\n time_precision, return_timestamps, force_full_sequences\n });\n\n toReturn.push({ text: full_text, ...optional })\n }\n return single ? toReturn[0] : toReturn;\n }\n}\n\n/**\n * @typedef {Object} ImageToTextSingle\n * @property {string} generated_text The generated text.\n * @typedef {ImageToTextSingle[]} ImageToTextOutput\n * \n * @callback ImageToTextPipelineCallback Assign labels to the image(s) passed as inputs.\n * @param {ImagePipelineInputs} texts The images to be captioned.\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise} An object (or array of objects) containing the generated text(s).\n * \n * @typedef {TextImagePipelineConstructorArgs & ImageToTextPipelineCallback & Disposable} ImageToTextPipelineType\n */\n\n/**\n * Image To Text pipeline using a `AutoModelForVision2Seq`. This pipeline predicts a caption for a given image.\n * \n * **Example:** Generate a caption for an image w/ `Xenova/vit-gpt2-image-captioning`.\n * ```javascript\n * const captioner = await pipeline('image-to-text', 'Xenova/vit-gpt2-image-captioning');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';\n * const output = await captioner(url);\n * // [{ generated_text: 'a cat laying on a couch with another cat' }]\n * ```\n * \n * **Example:** Optical Character Recognition (OCR) w/ `Xenova/trocr-small-handwritten`.\n * ```javascript\n * const captioner = await pipeline('image-to-text', 'Xenova/trocr-small-handwritten');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/handwriting.jpg';\n * const output = await captioner(url);\n * // [{ generated_text: 'Mr. Brown commented icily.' }]\n * ```\n */\nexport class ImageToTextPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ImageToTextPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ImageToTextPipeline.\n * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ImageToTextPipelineCallback} */\n async _call(images, generate_kwargs = {}) {\n\n const isBatched = Array.isArray(images);\n const preparedImages = await prepareImages(images);\n\n const { pixel_values } = await this.processor(preparedImages);\n\n const toReturn = [];\n for (const batch of pixel_values) {\n batch.dims = [1, ...batch.dims]\n const output = await this.model.generate({ inputs: batch, ...generate_kwargs });\n const decoded = this.tokenizer.batch_decode(/** @type {Tensor} */(output), {\n skip_special_tokens: true,\n }).map(x => ({ generated_text: x.trim() }))\n toReturn.push(decoded);\n }\n\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} ImageClassificationSingle\n * @property {string} label The label identified by the model.\n * @property {number} score The score attributed by the model for that label.\n * @typedef {ImageClassificationSingle[]} ImageClassificationOutput\n * \n * @typedef {Object} ImageClassificationPipelineOptions Parameters specific to image classification pipelines.\n * @property {number} [top_k=1] The number of top labels that will be returned by the pipeline. \n * \n * @callback ImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The input images(s) to be classified.\n * @param {ImageClassificationPipelineOptions} [options] The options to use for image classification.\n * @returns {Promise} An array or object containing the predicted labels and scores.\n * \n * @typedef {ImagePipelineConstructorArgs & ImageClassificationPipelineCallback & Disposable} ImageClassificationPipelineType\n */\n\n/**\n * Image classification pipeline using any `AutoModelForImageClassification`.\n * This pipeline predicts the class of an image.\n * \n * **Example:** Classify an image.\n * ```javascript\n * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';\n * const output = await classifier(url);\n * // [\n * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 },\n * // ]\n * ```\n * \n * **Example:** Classify an image and return top `n` classes.\n * ```javascript\n * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';\n * const output = await classifier(url, { top_k: 3 });\n * // [\n * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 },\n * // { label: 'tiger cat', score: 0.3634825646877289 },\n * // { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 },\n * // ]\n * ```\n * \n * **Example:** Classify an image and return all classes.\n * ```javascript\n * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';\n * const output = await classifier(url, { top_k: 0 });\n * // [\n * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 },\n * // { label: 'tiger cat', score: 0.3634825646877289 },\n * // { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 },\n * // { label: 'jaguar, panther, Panthera onca, Felis onca', score: 0.00035465499968267977 },\n * // ...\n * // ]\n * ```\n */\nexport class ImageClassificationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ImageClassificationPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ImageClassificationPipelineCallback} */\n async _call(images, {\n top_k = 5\n } = {}) {\n\n const preparedImages = await prepareImages(images);\n\n const { pixel_values } = await this.processor(preparedImages);\n const output = await this.model({ pixel_values });\n\n const id2label = this.model.config.id2label;\n\n /** @type {ImageClassificationOutput[]} */\n const toReturn = [];\n for (const batch of output.logits) {\n const scores = await topk(new Tensor(\n 'float32',\n softmax(batch.data),\n batch.dims,\n ), top_k);\n\n const values = scores[0].tolist();\n const indices = scores[1].tolist();\n\n const vals = indices.map((x, i) => ({\n label: /** @type {string} */ (id2label ? id2label[x] : `LABEL_${x}`),\n score: /** @type {number} */ (values[i]),\n }));\n toReturn.push(vals);\n }\n\n return Array.isArray(images) ? toReturn : toReturn[0];\n }\n\n}\n\n/**\n * @typedef {Object} ImageSegmentationPipelineOutput\n * @property {string} label The label of the segment.\n * @property {number|null} score The score of the segment.\n * @property {RawImage} mask The mask of the segment.\n * \n * @typedef {Object} ImageSegmentationPipelineOptions Parameters specific to image segmentation pipelines.\n * @property {number} [threshold=0.5] Probability threshold to filter out predicted masks.\n * @property {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values.\n * @property {number} [overlap_mask_area_threshold=0.8] Mask overlap threshold to eliminate small, disconnected segments.\n * @property {null|string} [subtask=null] Segmentation task to be performed. One of [`panoptic`, `instance`, and `semantic`],\n * depending on model capabilities. If not set, the pipeline will attempt to resolve (in that order).\n * @property {number[]} [label_ids_to_fuse=null] List of label ids to fuse. If not set, do not fuse any labels.\n * @property {number[][]} [target_sizes=null] List of target sizes for the input images. If not set, use the original image sizes.\n * \n * @callback ImageSegmentationPipelineCallback Segment the input images.\n * @param {ImagePipelineInputs} images The input images.\n * @param {ImageSegmentationPipelineOptions} [options] The options to use for image segmentation.\n * @returns {Promise} The annotated segments.\n * \n * @typedef {ImagePipelineConstructorArgs & ImageSegmentationPipelineCallback & Disposable} ImageSegmentationPipelineType\n */\n\n/**\n * Image segmentation pipeline using any `AutoModelForXXXSegmentation`.\n * This pipeline predicts masks of objects and their classes.\n * \n * **Example:** Perform image segmentation with `Xenova/detr-resnet-50-panoptic`.\n * ```javascript\n * const segmenter = await pipeline('image-segmentation', 'Xenova/detr-resnet-50-panoptic');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';\n * const output = await segmenter(url);\n * // [\n * // { label: 'remote', score: 0.9984649419784546, mask: RawImage { ... } },\n * // { label: 'cat', score: 0.9994316101074219, mask: RawImage { ... } }\n * // ]\n * ```\n */\nexport class ImageSegmentationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageSegmentationPipelineType} */ (Pipeline)) {\n /**\n * Create a new ImageSegmentationPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n\n this.subtasks_mapping = {\n // Mapping of subtasks to their corresponding post-processing function names.\n panoptic: 'post_process_panoptic_segmentation',\n instance: 'post_process_instance_segmentation',\n semantic: 'post_process_semantic_segmentation'\n }\n }\n\n /** @type {ImageSegmentationPipelineCallback} */\n async _call(images, {\n threshold = 0.5,\n mask_threshold = 0.5,\n overlap_mask_area_threshold = 0.8,\n label_ids_to_fuse = null,\n target_sizes = null,\n subtask = null,\n } = {}) {\n const isBatched = Array.isArray(images);\n\n if (isBatched && images.length !== 1) {\n throw Error(\"Image segmentation pipeline currently only supports a batch size of 1.\");\n }\n\n const preparedImages = await prepareImages(images);\n const imageSizes = preparedImages.map(x => [x.height, x.width]);\n\n const { pixel_values, pixel_mask } = await this.processor(preparedImages);\n const output = await this.model({ pixel_values, pixel_mask });\n\n let fn = null;\n if (subtask !== null) {\n fn = this.subtasks_mapping[subtask];\n } else {\n for (let [task, func] of Object.entries(this.subtasks_mapping)) {\n if (func in this.processor.feature_extractor) {\n fn = this.processor.feature_extractor[func].bind(this.processor.feature_extractor);\n subtask = task;\n break;\n }\n }\n }\n\n const id2label = this.model.config.id2label;\n\n /** @type {ImageSegmentationPipelineOutput[]} */\n const annotation = [];\n if (subtask === 'panoptic' || subtask === 'instance') {\n const processed = fn(\n output,\n threshold,\n mask_threshold,\n overlap_mask_area_threshold,\n label_ids_to_fuse,\n target_sizes ?? imageSizes, // TODO FIX?\n )[0];\n\n const segmentation = processed.segmentation;\n\n for (const segment of processed.segments_info) {\n const maskData = new Uint8ClampedArray(segmentation.data.length);\n for (let i = 0; i < segmentation.data.length; ++i) {\n if (segmentation.data[i] === segment.id) {\n maskData[i] = 255;\n }\n }\n\n const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1)\n\n annotation.push({\n score: segment.score,\n label: id2label[segment.label_id],\n mask: mask\n })\n }\n\n } else if (subtask === 'semantic') {\n const { segmentation, labels } = fn(output, target_sizes ?? imageSizes)[0];\n\n for (const label of labels) {\n const maskData = new Uint8ClampedArray(segmentation.data.length);\n for (let i = 0; i < segmentation.data.length; ++i) {\n if (segmentation.data[i] === label) {\n maskData[i] = 255;\n }\n }\n\n const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1);\n\n annotation.push({\n score: null,\n label: id2label[label],\n mask: mask\n });\n }\n } else {\n throw Error(`Subtask ${subtask} not supported.`);\n }\n\n return annotation;\n }\n}\n\n/**\n * @typedef {Object} ZeroShotImageClassificationOutput\n * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`.\n * @property {number} score The score attributed by the model for that label (between 0 and 1).\n * \n * @typedef {Object} ZeroShotImageClassificationPipelineOptions Parameters specific to zero-shot image classification pipelines.\n * @property {string} [hypothesis_template=\"This is a photo of {}\"] The sentence used in conjunction with `candidate_labels`\n * to attempt the image classification by replacing the placeholder with the candidate_labels.\n * Then likelihood is estimated by using `logits_per_image`.\n * \n * @callback ZeroShotImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The input images.\n * @param {string[]} candidate_labels The candidate labels for this image.\n * @param {ZeroShotImageClassificationPipelineOptions} [options] The options to use for zero-shot image classification.\n * @returns {Promise} An array of objects containing the predicted labels and scores.\n * \n * @typedef {TextImagePipelineConstructorArgs & ZeroShotImageClassificationPipelineCallback & Disposable} ZeroShotImageClassificationPipelineType\n */\n\n/**\n * Zero shot image classification pipeline. This pipeline predicts the class of\n * an image when you provide an image and a set of `candidate_labels`.\n * \n * **Example:** Zero shot image classification w/ `Xenova/clip-vit-base-patch32`.\n * ```javascript\n * const classifier = await pipeline('zero-shot-image-classification', 'Xenova/clip-vit-base-patch32');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';\n * const output = await classifier(url, ['tiger', 'horse', 'dog']);\n * // [\n * // { score: 0.9993917942047119, label: 'tiger' },\n * // { score: 0.0003519294841680676, label: 'horse' },\n * // { score: 0.0002562698791734874, label: 'dog' }\n * // ]\n * ```\n */\nexport class ZeroShotImageClassificationPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotImageClassificationPipelineType} */ (Pipeline)) {\n /**\n * Create a new ZeroShotImageClassificationPipeline.\n * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ZeroShotImageClassificationPipelineCallback} */\n async _call(images, candidate_labels, {\n hypothesis_template = \"This is a photo of {}\"\n } = {}) {\n\n const isBatched = Array.isArray(images);\n const preparedImages = await prepareImages(images);\n\n // Insert label into hypothesis template \n const texts = candidate_labels.map(\n x => hypothesis_template.replace('{}', x)\n );\n\n // Run tokenization\n const text_inputs = this.tokenizer(texts, {\n padding: this.model.config.model_type === 'siglip' ? 'max_length' : true,\n truncation: true,\n });\n\n // Run processor\n const { pixel_values } = await this.processor(preparedImages);\n\n // Run model with both text and pixel inputs\n const output = await this.model({ ...text_inputs, pixel_values });\n\n const function_to_apply =\n this.model.config.model_type === 'siglip'\n ? batch => batch.sigmoid().data\n : batch => softmax(batch.data);\n\n // Compare each image with each candidate label\n const toReturn = [];\n for (const batch of output.logits_per_image) {\n // Compute softmax per image\n const probs = function_to_apply(batch);\n\n const result = [...probs].map((x, i) => ({\n score: x,\n label: candidate_labels[i]\n }));\n result.sort((a, b) => b.score - a.score); // sort by score in descending order\n toReturn.push(result);\n }\n\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n\n/**\n * @typedef {Object} ObjectDetectionPipelineSingle\n * @property {string} label The class label identified by the model.\n * @property {number} score The score attributed by the model for that label.\n * @property {BoundingBox} box The bounding box of detected object in image's original size, or as a percentage if `percentage` is set to true.\n * @typedef {ObjectDetectionPipelineSingle[]} ObjectDetectionPipelineOutput\n * \n * @typedef {Object} ObjectDetectionPipelineOptions Parameters specific to object detection pipelines.\n * @property {number} [threshold=0.9] The threshold used to filter boxes by score.\n * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false).\n * \n * @callback ObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The input images.\n * @param {ObjectDetectionPipelineOptions} [options] The options to use for object detection.\n * @returns {Promise} A list of objects or a list of list of objects. \n * \n * @typedef {ImagePipelineConstructorArgs & ObjectDetectionPipelineCallback & Disposable} ObjectDetectionPipelineType\n */\n\n/**\n * Object detection pipeline using any `AutoModelForObjectDetection`.\n * This pipeline predicts bounding boxes of objects and their classes.\n * \n * **Example:** Run object-detection with `Xenova/detr-resnet-50`.\n * ```javascript\n * const detector = await pipeline('object-detection', 'Xenova/detr-resnet-50');\n * const img = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';\n * const output = await detector(img, { threshold: 0.9 });\n * // [{\n * // score: 0.9976370930671692,\n * // label: \"remote\",\n * // box: { xmin: 31, ymin: 68, xmax: 190, ymax: 118 }\n * // },\n * // ...\n * // {\n * // score: 0.9984092116355896,\n * // label: \"cat\",\n * // box: { xmin: 331, ymin: 19, xmax: 649, ymax: 371 }\n * // }]\n * ```\n */\nexport class ObjectDetectionPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ObjectDetectionPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ObjectDetectionPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ObjectDetectionPipelineCallback} */\n async _call(images, {\n threshold = 0.9,\n percentage = false,\n } = {}) {\n\n const isBatched = Array.isArray(images);\n\n if (isBatched && images.length !== 1) {\n throw Error(\"Object detection pipeline currently only supports a batch size of 1.\");\n }\n const preparedImages = await prepareImages(images);\n\n const imageSizes = percentage ? null : preparedImages.map(x => [x.height, x.width]);\n\n const { pixel_values, pixel_mask } = await this.processor(preparedImages);\n const output = await this.model({ pixel_values, pixel_mask });\n\n // @ts-ignore\n const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSizes);\n\n // Add labels\n const id2label = this.model.config.id2label;\n\n // Format output\n /** @type {ObjectDetectionPipelineOutput[]} */\n const result = processed.map(batch => (\n batch.boxes.map((box, i) => ({\n score: batch.scores[i],\n label: id2label[batch.classes[i]],\n box: get_bounding_box(box, !percentage),\n }))\n ))\n\n return isBatched ? result : result[0];\n }\n}\n\n\n/**\n * @typedef {Object} ZeroShotObjectDetectionOutput\n * @property {string} label Text query corresponding to the found object.\n * @property {number} score Score corresponding to the object (between 0 and 1).\n * @property {BoundingBox} box Bounding box of the detected object in image's original size, or as a percentage if `percentage` is set to true.\n * \n * @typedef {Object} ZeroShotObjectDetectionPipelineOptions Parameters specific to zero-shot object detection pipelines.\n * @property {number} [threshold=0.1] The probability necessary to make a prediction.\n * @property {number} [top_k=null] The number of top predictions that will be returned by the pipeline.\n * If the provided number is `null` or higher than the number of predictions available, it will default\n * to the number of predictions.\n * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false).\n * \n * @callback ZeroShotObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The input images.\n * @param {string[]} candidate_labels What the model should recognize in the image.\n * @param {ZeroShotObjectDetectionPipelineOptions} [options] The options to use for zero-shot object detection.\n * @returns {Promise} An array of objects containing the predicted labels, scores, and bounding boxes.\n * \n * @typedef {TextImagePipelineConstructorArgs & ZeroShotObjectDetectionPipelineCallback & Disposable} ZeroShotObjectDetectionPipelineType\n */\n\n/**\n * Zero-shot object detection pipeline. This pipeline predicts bounding boxes of\n * objects when you provide an image and a set of `candidate_labels`.\n * \n * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32`.\n * ```javascript\n * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/astronaut.png';\n * const candidate_labels = ['human face', 'rocket', 'helmet', 'american flag'];\n * const output = await detector(url, candidate_labels);\n * // [\n * // {\n * // score: 0.24392342567443848,\n * // label: 'human face',\n * // box: { xmin: 180, ymin: 67, xmax: 274, ymax: 175 }\n * // },\n * // {\n * // score: 0.15129457414150238,\n * // label: 'american flag',\n * // box: { xmin: 0, ymin: 4, xmax: 106, ymax: 513 }\n * // },\n * // {\n * // score: 0.13649864494800568,\n * // label: 'helmet',\n * // box: { xmin: 277, ymin: 337, xmax: 511, ymax: 511 }\n * // },\n * // {\n * // score: 0.10262022167444229,\n * // label: 'rocket',\n * // box: { xmin: 352, ymin: -1, xmax: 463, ymax: 287 }\n * // }\n * // ]\n * ```\n * \n * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32` (returning top 4 matches and setting a threshold).\n * ```javascript\n * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/beach.png';\n * const candidate_labels = ['hat', 'book', 'sunglasses', 'camera'];\n * const output = await detector(url, candidate_labels, { top_k: 4, threshold: 0.05 });\n * // [\n * // {\n * // score: 0.1606510728597641,\n * // label: 'sunglasses',\n * // box: { xmin: 347, ymin: 229, xmax: 429, ymax: 264 }\n * // },\n * // {\n * // score: 0.08935828506946564,\n * // label: 'hat',\n * // box: { xmin: 38, ymin: 174, xmax: 258, ymax: 364 }\n * // },\n * // {\n * // score: 0.08530698716640472,\n * // label: 'camera',\n * // box: { xmin: 187, ymin: 350, xmax: 260, ymax: 411 }\n * // },\n * // {\n * // score: 0.08349756896495819,\n * // label: 'book',\n * // box: { xmin: 261, ymin: 280, xmax: 494, ymax: 425 }\n * // }\n * // ]\n * ```\n */\nexport class ZeroShotObjectDetectionPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotObjectDetectionPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ZeroShotObjectDetectionPipeline.\n * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ZeroShotObjectDetectionPipelineCallback} */\n async _call(images, candidate_labels, {\n threshold = 0.1,\n top_k = null,\n percentage = false,\n } = {}) {\n\n const isBatched = Array.isArray(images);\n const preparedImages = await prepareImages(images);\n\n // Run tokenization\n const text_inputs = this.tokenizer(candidate_labels, {\n padding: true,\n truncation: true,\n });\n\n // Run processor\n const model_inputs = await this.processor(preparedImages);\n\n // Since non-maximum suppression is performed for exporting, we need to\n // process each image separately. For more information, see:\n // https://github.com/huggingface/optimum/blob/e3b7efb1257c011db907ef40ab340e795cc5684c/optimum/exporters/onnx/model_configs.py#L1028-L1032\n const toReturn = [];\n for (let i = 0; i < preparedImages.length; ++i) {\n const image = preparedImages[i];\n const imageSize = percentage ? null : [[image.height, image.width]];\n const pixel_values = model_inputs.pixel_values[i].unsqueeze_(0);\n\n // Run model with both text and pixel inputs\n const output = await this.model({ ...text_inputs, pixel_values });\n\n // @ts-ignore\n const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSize, true)[0];\n let result = processed.boxes.map((box, i) => ({\n score: processed.scores[i],\n label: candidate_labels[processed.classes[i]],\n box: get_bounding_box(box, !percentage),\n })).sort((a, b) => b.score - a.score);\n if (top_k !== null) {\n result = result.slice(0, top_k);\n }\n toReturn.push(result)\n }\n\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} DocumentQuestionAnsweringSingle\n * @property {string} answer The generated text.\n * @typedef {DocumentQuestionAnsweringSingle[]} DocumentQuestionAnsweringOutput\n * \n * @callback DocumentQuestionAnsweringPipelineCallback Answer the question given as input by using the document.\n * @param {ImageInput} image The image of the document to use.\n * @param {string} question A question to ask of the document.\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise} An object (or array of objects) containing the answer(s).\n * \n * @typedef {TextImagePipelineConstructorArgs & DocumentQuestionAnsweringPipelineCallback & Disposable} DocumentQuestionAnsweringPipelineType\n */\n\n/**\n * Document Question Answering pipeline using any `AutoModelForDocumentQuestionAnswering`.\n * The inputs/outputs are similar to the (extractive) question answering pipeline; however,\n * the pipeline takes an image (and optional OCR'd words/boxes) as input instead of text context.\n * \n * **Example:** Answer questions about a document with `Xenova/donut-base-finetuned-docvqa`.\n * ```javascript\n * const qa_pipeline = await pipeline('document-question-answering', 'Xenova/donut-base-finetuned-docvqa');\n * const image = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/invoice.png';\n * const question = 'What is the invoice number?';\n * const output = await qa_pipeline(image, question);\n * // [{ answer: 'us-001' }]\n * ```\n */\nexport class DocumentQuestionAnsweringPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => DocumentQuestionAnsweringPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new DocumentQuestionAnsweringPipeline.\n * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {DocumentQuestionAnsweringPipelineCallback} */\n async _call(image, question, generate_kwargs = {}) {\n throw new Error('This pipeline is not yet supported in Transformers.js v3.'); // TODO: Remove when implemented\n\n // NOTE: For now, we only support a batch size of 1\n\n // Preprocess image\n const preparedImage = (await prepareImages(image))[0];\n const { pixel_values } = await this.processor(preparedImage);\n\n // Run tokenization\n const task_prompt = `${question}`;\n const decoder_input_ids = this.tokenizer(task_prompt, {\n add_special_tokens: false,\n padding: true,\n truncation: true,\n }).input_ids;\n\n // Run model\n const output = await this.model.generate({\n inputs: pixel_values,\n max_length: this.model.config.decoder.max_position_embeddings,\n decoder_input_ids,\n ...generate_kwargs,\n });\n\n // Decode output\n const decoded = this.tokenizer.batch_decode(/** @type {Tensor} */(output))[0];\n\n // Parse answer\n const match = decoded.match(/(.*?)<\\/s_answer>/);\n let answer = null;\n if (match && match.length >= 2) {\n answer = match[1].trim();\n }\n return [{ answer }];\n }\n}\n\n\n/**\n * @typedef {Object} VocoderOptions\n * @property {PreTrainedModel} [vocoder] The vocoder used by the pipeline (if the model uses one). If not provided, use the default HifiGan vocoder.\n * @typedef {TextAudioPipelineConstructorArgs & VocoderOptions} TextToAudioPipelineConstructorArgs\n */\n\n/**\n * @typedef {Object} TextToAudioOutput\n * @property {Float32Array} audio The generated audio waveform.\n * @property {number} sampling_rate The sampling rate of the generated audio waveform.\n * \n * @typedef {Object} TextToAudioPipelineOptions Parameters specific to text-to-audio pipelines.\n * @property {Tensor|Float32Array|string|URL} [speaker_embeddings=null] The speaker embeddings (if the model requires it).\n * \n * @callback TextToAudioPipelineCallback Generates speech/audio from the inputs.\n * @param {string|string[]} texts The text(s) to generate.\n * @param {TextToAudioPipelineOptions} options Parameters passed to the model generation/forward method.\n * @returns {Promise} An object containing the generated audio and sampling rate.\n * \n * @typedef {TextToAudioPipelineConstructorArgs & TextToAudioPipelineCallback & Disposable} TextToAudioPipelineType\n */\n\n/**\n * Text-to-audio generation pipeline using any `AutoModelForTextToWaveform` or `AutoModelForTextToSpectrogram`.\n * This pipeline generates an audio file from an input text and optional other conditional inputs.\n * \n * **Example:** Generate audio from text with `Xenova/speecht5_tts`.\n * ```javascript\n * const synthesizer = await pipeline('text-to-speech', 'Xenova/speecht5_tts', { quantized: false });\n * const speaker_embeddings = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin';\n * const out = await synthesizer('Hello, my dog is cute', { speaker_embeddings });\n * // {\n * // audio: Float32Array(26112) [-0.00005657337896991521, 0.00020583874720614403, ...],\n * // sampling_rate: 16000\n * // }\n * ```\n * \n * You can then save the audio to a .wav file with the `wavefile` package:\n * ```javascript\n * import wavefile from 'wavefile';\n * import fs from 'fs';\n * \n * const wav = new wavefile.WaveFile();\n * wav.fromScratch(1, out.sampling_rate, '32f', out.audio);\n * fs.writeFileSync('out.wav', wav.toBuffer());\n * ```\n * \n * **Example:** Multilingual speech generation with `Xenova/mms-tts-fra`. See [here](https://huggingface.co/models?pipeline_tag=text-to-speech&other=vits&sort=trending) for the full list of available languages (1107).\n * ```javascript\n * const synthesizer = await pipeline('text-to-speech', 'Xenova/mms-tts-fra');\n * const out = await synthesizer('Bonjour');\n * // {\n * // audio: Float32Array(23808) [-0.00037693005288019776, 0.0003325853613205254, ...],\n * // sampling_rate: 16000\n * // }\n * ```\n */\nexport class TextToAudioPipeline extends (/** @type {new (options: TextToAudioPipelineConstructorArgs) => TextToAudioPipelineType} */ (Pipeline)) {\n DEFAULT_VOCODER_ID = \"Xenova/speecht5_hifigan\"\n\n /**\n * Create a new TextToAudioPipeline.\n * @param {TextToAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n\n // TODO: Find a better way for `pipeline` to set the default vocoder\n this.vocoder = options.vocoder ?? null;\n }\n\n\n /** @type {TextToAudioPipelineCallback} */\n async _call(text_inputs, {\n speaker_embeddings = null,\n } = {}) {\n\n // If this.processor is not set, we are using a `AutoModelForTextToWaveform` model\n if (this.processor) {\n return this._call_text_to_spectrogram(text_inputs, { speaker_embeddings });\n } else {\n return this._call_text_to_waveform(text_inputs);\n }\n }\n\n async _call_text_to_waveform(text_inputs) {\n\n // Run tokenization\n const inputs = this.tokenizer(text_inputs, {\n padding: true,\n truncation: true,\n });\n\n // Generate waveform\n const { waveform } = await this.model(inputs);\n\n const sampling_rate = this.model.config.sampling_rate;\n return {\n audio: waveform.data,\n sampling_rate,\n }\n }\n\n async _call_text_to_spectrogram(text_inputs, { speaker_embeddings }) {\n\n // Load vocoder, if not provided\n if (!this.vocoder) {\n console.log('No vocoder specified, using default HifiGan vocoder.');\n this.vocoder = await AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID, { dtype: 'fp32' });\n }\n\n // Load speaker embeddings as Float32Array from path/URL\n if (typeof speaker_embeddings === 'string' || speaker_embeddings instanceof URL) {\n // Load from URL with fetch\n speaker_embeddings = new Float32Array(\n await (await fetch(speaker_embeddings)).arrayBuffer()\n );\n }\n\n if (speaker_embeddings instanceof Float32Array) {\n speaker_embeddings = new Tensor(\n 'float32',\n speaker_embeddings,\n [1, speaker_embeddings.length]\n )\n } else if (!(speaker_embeddings instanceof Tensor)) {\n throw new Error(\"Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.\")\n }\n\n // Run tokenization\n const { input_ids } = this.tokenizer(text_inputs, {\n padding: true,\n truncation: true,\n });\n\n // NOTE: At this point, we are guaranteed that `speaker_embeddings` is a `Tensor`\n // @ts-ignore\n const { waveform } = await this.model.generate_speech(input_ids, speaker_embeddings, { vocoder: this.vocoder });\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n return {\n audio: waveform.data,\n sampling_rate,\n }\n }\n}\n\n/**\n * @callback ImageToImagePipelineCallback Transform the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The images to transform.\n * @returns {Promise} The transformed image or list of images.\n * \n * @typedef {ImagePipelineConstructorArgs & ImageToImagePipelineCallback & Disposable} ImageToImagePipelineType\n */\n\n/**\n * Image to Image pipeline using any `AutoModelForImageToImage`. This pipeline generates an image based on a previous image input.\n * \n * **Example:** Super-resolution w/ `Xenova/swin2SR-classical-sr-x2-64`\n * ```javascript\n * const upscaler = await pipeline('image-to-image', 'Xenova/swin2SR-classical-sr-x2-64');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg';\n * const output = await upscaler(url);\n * // RawImage {\n * // data: Uint8Array(786432) [ 41, 31, 24, 43, ... ],\n * // width: 512,\n * // height: 512,\n * // channels: 3\n * // }\n * ```\n */\nexport class ImageToImagePipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageToImagePipelineType} */ (Pipeline)) {\n /**\n * Create a new ImageToImagePipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ImageToImagePipelineCallback} */\n async _call(images) {\n\n const preparedImages = await prepareImages(images);\n const inputs = await this.processor(preparedImages);\n const outputs = await this.model(inputs);\n\n /** @type {RawImage[]} */\n const toReturn = [];\n for (const batch of outputs.reconstruction) {\n const output = batch.squeeze().clamp_(0, 1).mul_(255).round_().to('uint8');\n toReturn.push(RawImage.fromTensor(output));\n }\n\n return toReturn.length > 1 ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} DepthEstimationPipelineOutput\n * @property {Tensor} predicted_depth The raw depth map predicted by the model.\n * @property {RawImage} depth The processed depth map as an image (with the same size as the input image).\n * \n * @callback DepthEstimationPipelineCallback Predicts the depth for the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The images to compute depth for.\n * @returns {Promise} An image or a list of images containing result(s).\n * \n * @typedef {ImagePipelineConstructorArgs & DepthEstimationPipelineCallback & Disposable} DepthEstimationPipelineType\n */\n\n/**\n * Depth estimation pipeline using any `AutoModelForDepthEstimation`. This pipeline predicts the depth of an image.\n * \n * **Example:** Depth estimation w/ `Xenova/dpt-hybrid-midas`\n * ```javascript\n * const depth_estimator = await pipeline('depth-estimation', 'Xenova/dpt-hybrid-midas');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';\n * const out = await depth_estimator(url);\n * // {\n * // predicted_depth: Tensor {\n * // dims: [ 384, 384 ],\n * // type: 'float32',\n * // data: Float32Array(147456) [ 542.859130859375, 545.2833862304688, 546.1649169921875, ... ],\n * // size: 147456\n * // },\n * // depth: RawImage {\n * // data: Uint8Array(307200) [ 86, 86, 86, ... ],\n * // width: 640,\n * // height: 480,\n * // channels: 1\n * // }\n * // }\n * ```\n */\nexport class DepthEstimationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => DepthEstimationPipelineType} */ (Pipeline)) {\n /**\n * Create a new DepthEstimationPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {DepthEstimationPipelineCallback} */\n async _call(images) {\n\n const preparedImages = await prepareImages(images);\n\n const inputs = await this.processor(preparedImages);\n const { predicted_depth } = await this.model(inputs);\n\n const toReturn = [];\n for (let i = 0; i < preparedImages.length; ++i) {\n const prediction = interpolate(predicted_depth[i], preparedImages[i].size.reverse(), 'bilinear', false);\n const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8');\n toReturn.push({\n predicted_depth: predicted_depth[i],\n depth: RawImage.fromTensor(formatted),\n });\n }\n\n return toReturn.length > 1 ? toReturn : toReturn[0];\n }\n}\n\nconst SUPPORTED_TASKS = Object.freeze({\n \"text-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TextClassificationPipeline,\n \"model\": AutoModelForSequenceClassification,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"distilbert-base-uncased-finetuned-sst-2-english\",\n \"model\": \"Xenova/distilbert-base-uncased-finetuned-sst-2-english\",\n },\n \"type\": \"text\",\n },\n \"token-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TokenClassificationPipeline,\n \"model\": AutoModelForTokenClassification,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"Davlan/bert-base-multilingual-cased-ner-hrl\",\n \"model\": \"Xenova/bert-base-multilingual-cased-ner-hrl\",\n },\n \"type\": \"text\",\n },\n \"question-answering\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": QuestionAnsweringPipeline,\n \"model\": AutoModelForQuestionAnswering,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"distilbert-base-cased-distilled-squad\",\n \"model\": \"Xenova/distilbert-base-cased-distilled-squad\",\n },\n \"type\": \"text\",\n },\n\n \"fill-mask\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": FillMaskPipeline,\n \"model\": AutoModelForMaskedLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"bert-base-uncased\",\n \"model\": \"Xenova/bert-base-uncased\",\n },\n \"type\": \"text\",\n },\n \"summarization\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": SummarizationPipeline,\n \"model\": AutoModelForSeq2SeqLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"sshleifer/distilbart-cnn-6-6\",\n \"model\": \"Xenova/distilbart-cnn-6-6\",\n },\n \"type\": \"text\",\n },\n \"translation\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TranslationPipeline,\n \"model\": AutoModelForSeq2SeqLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"t5-small\",\n \"model\": \"Xenova/t5-small\",\n },\n \"type\": \"text\",\n },\n \"text2text-generation\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": Text2TextGenerationPipeline,\n \"model\": AutoModelForSeq2SeqLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"google/flan-t5-small\",\n \"model\": \"Xenova/flan-t5-small\",\n },\n \"type\": \"text\",\n },\n \"text-generation\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TextGenerationPipeline,\n \"model\": AutoModelForCausalLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"gpt2\",\n \"model\": \"Xenova/gpt2\",\n },\n \"type\": \"text\",\n },\n \"zero-shot-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ZeroShotClassificationPipeline,\n \"model\": AutoModelForSequenceClassification,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"typeform/distilbert-base-uncased-mnli\",\n \"model\": \"Xenova/distilbert-base-uncased-mnli\",\n },\n \"type\": \"text\",\n },\n \"audio-classification\": {\n \"pipeline\": AudioClassificationPipeline,\n \"model\": AutoModelForAudioClassification,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"superb/wav2vec2-base-superb-ks\",\n \"model\": \"Xenova/wav2vec2-base-superb-ks\",\n },\n \"type\": \"audio\",\n },\n \"zero-shot-audio-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ZeroShotAudioClassificationPipeline,\n \"model\": AutoModel,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"laion/clap-htsat-fused\",\n \"model\": \"Xenova/clap-htsat-unfused\",\n },\n \"type\": \"multimodal\",\n },\n \"automatic-speech-recognition\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": AutomaticSpeechRecognitionPipeline,\n \"model\": [AutoModelForSpeechSeq2Seq, AutoModelForCTC],\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"openai/whisper-tiny.en\",\n \"model\": \"Xenova/whisper-tiny.en\",\n },\n \"type\": \"multimodal\",\n },\n \"text-to-audio\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TextToAudioPipeline,\n \"model\": [AutoModelForTextToWaveform, AutoModelForTextToSpectrogram],\n \"processor\": [AutoProcessor, /* Some don't use a processor */ null],\n \"default\": {\n // TODO: replace with original\n // \"model\": \"microsoft/speecht5_tts\",\n \"model\": \"Xenova/speecht5_tts\",\n },\n \"type\": \"text\",\n },\n \"image-to-text\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ImageToTextPipeline,\n \"model\": AutoModelForVision2Seq,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"nlpconnect/vit-gpt2-image-captioning\",\n \"model\": \"Xenova/vit-gpt2-image-captioning\",\n },\n \"type\": \"multimodal\",\n },\n\n \"image-classification\": {\n // no tokenizer\n \"pipeline\": ImageClassificationPipeline,\n \"model\": AutoModelForImageClassification,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"google/vit-base-patch16-224\",\n \"model\": \"Xenova/vit-base-patch16-224\",\n },\n \"type\": \"multimodal\",\n },\n\n \"image-segmentation\": {\n // no tokenizer\n \"pipeline\": ImageSegmentationPipeline,\n \"model\": [AutoModelForImageSegmentation, AutoModelForSemanticSegmentation, AutoModelForUniversalSegmentation],\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"facebook/detr-resnet-50-panoptic\",\n \"model\": \"Xenova/detr-resnet-50-panoptic\",\n },\n \"type\": \"multimodal\",\n },\n\n \"zero-shot-image-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ZeroShotImageClassificationPipeline,\n \"model\": AutoModel,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"openai/clip-vit-base-patch32\",\n \"model\": \"Xenova/clip-vit-base-patch32\",\n },\n \"type\": \"multimodal\",\n },\n\n \"object-detection\": {\n // no tokenizer\n \"pipeline\": ObjectDetectionPipeline,\n \"model\": AutoModelForObjectDetection,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"facebook/detr-resnet-50\",\n \"model\": \"Xenova/detr-resnet-50\",\n },\n \"type\": \"multimodal\",\n },\n \"zero-shot-object-detection\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ZeroShotObjectDetectionPipeline,\n \"model\": AutoModelForZeroShotObjectDetection,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"google/owlvit-base-patch32\",\n \"model\": \"Xenova/owlvit-base-patch32\",\n },\n \"type\": \"multimodal\",\n },\n \"document-question-answering\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": DocumentQuestionAnsweringPipeline,\n \"model\": AutoModelForDocumentQuestionAnswering,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"naver-clova-ix/donut-base-finetuned-docvqa\",\n \"model\": \"Xenova/donut-base-finetuned-docvqa\",\n },\n \"type\": \"multimodal\",\n },\n \"image-to-image\": {\n // no tokenizer\n \"pipeline\": ImageToImagePipeline,\n \"model\": AutoModelForImageToImage,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"caidas/swin2SR-classical-sr-x2-64\",\n \"model\": \"Xenova/swin2SR-classical-sr-x2-64\",\n },\n \"type\": \"image\",\n },\n \"depth-estimation\": {\n // no tokenizer\n \"pipeline\": DepthEstimationPipeline,\n \"model\": AutoModelForDepthEstimation,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"Intel/dpt-large\",\n \"model\": \"Xenova/dpt-large\",\n },\n \"type\": \"image\",\n },\n\n // This task serves as a useful interface for dealing with sentence-transformers (https://huggingface.co/sentence-transformers).\n \"feature-extraction\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": FeatureExtractionPipeline,\n \"model\": AutoModel,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"sentence-transformers/all-MiniLM-L6-v2\",\n \"model\": \"Xenova/all-MiniLM-L6-v2\",\n },\n \"type\": \"text\",\n },\n \"image-feature-extraction\": {\n \"processor\": AutoProcessor,\n \"pipeline\": ImageFeatureExtractionPipeline,\n \"model\": [AutoModelForImageFeatureExtraction, AutoModel],\n \"default\": {\n // TODO: replace with original\n // \"model\": \"google/vit-base-patch16-224\",\n \"model\": \"Xenova/vit-base-patch16-224-in21k\",\n },\n \"type\": \"image\",\n },\n})\n\n\n// TODO: Add types for TASK_ALIASES\nconst TASK_ALIASES = Object.freeze({\n \"sentiment-analysis\": \"text-classification\",\n \"ner\": \"token-classification\",\n // \"vqa\": \"visual-question-answering\", // TODO: Add\n \"asr\": \"automatic-speech-recognition\",\n \"text-to-speech\": \"text-to-audio\",\n\n // Add for backwards compatibility\n \"embeddings\": \"feature-extraction\",\n});\n\n/**\n * @typedef {keyof typeof SUPPORTED_TASKS} TaskType\n * @typedef {keyof typeof TASK_ALIASES} AliasType\n * @typedef {TaskType | AliasType} PipelineType All possible pipeline types.\n * @typedef {{[K in TaskType]: InstanceType}} SupportedTasks A mapping of pipeline names to their corresponding pipeline classes.\n * @typedef {{[K in AliasType]: InstanceType}} AliasTasks A mapping from pipeline aliases to their corresponding pipeline classes.\n * @typedef {SupportedTasks & AliasTasks} AllTasks A mapping from all pipeline names and aliases to their corresponding pipeline classes.\n */\n\n/**\n * Utility factory method to build a `Pipeline` object.\n * \n * @template {PipelineType} T The type of pipeline to return.\n * @param {T} task The task defining which pipeline will be returned. Currently accepted tasks are:\n * - `\"audio-classification\"`: will return a `AudioClassificationPipeline`.\n * - `\"automatic-speech-recognition\"`: will return a `AutomaticSpeechRecognitionPipeline`.\n * - `\"depth-estimation\"`: will return a `DepthEstimationPipeline`.\n * - `\"document-question-answering\"`: will return a `DocumentQuestionAnsweringPipeline`.\n * - `\"feature-extraction\"`: will return a `FeatureExtractionPipeline`.\n * - `\"fill-mask\"`: will return a `FillMaskPipeline`.\n * - `\"image-classification\"`: will return a `ImageClassificationPipeline`.\n * - `\"image-segmentation\"`: will return a `ImageSegmentationPipeline`.\n * - `\"image-to-text\"`: will return a `ImageToTextPipeline`.\n * - `\"object-detection\"`: will return a `ObjectDetectionPipeline`.\n * - `\"question-answering\"`: will return a `QuestionAnsweringPipeline`.\n * - `\"summarization\"`: will return a `SummarizationPipeline`.\n * - `\"text2text-generation\"`: will return a `Text2TextGenerationPipeline`.\n * - `\"text-classification\"` (alias \"sentiment-analysis\" available): will return a `TextClassificationPipeline`.\n * - `\"text-generation\"`: will return a `TextGenerationPipeline`.\n * - `\"token-classification\"` (alias \"ner\" available): will return a `TokenClassificationPipeline`.\n * - `\"translation\"`: will return a `TranslationPipeline`.\n * - `\"translation_xx_to_yy\"`: will return a `TranslationPipeline`.\n * - `\"zero-shot-classification\"`: will return a `ZeroShotClassificationPipeline`.\n * - `\"zero-shot-audio-classification\"`: will return a `ZeroShotAudioClassificationPipeline`.\n * - `\"zero-shot-image-classification\"`: will return a `ZeroShotImageClassificationPipeline`.\n * - `\"zero-shot-object-detection\"`: will return a `ZeroShotObjectDetectionPipeline`.\n * @param {string} [model=null] The name of the pre-trained model to use. If not specified, the default model for the task will be used.\n * @param {import('./utils/hub.js').PretrainedModelOptions} [options] Optional parameters for the pipeline.\n * @returns {Promise} A Pipeline object for the specified task.\n * @throws {Error} If an unsupported pipeline is requested.\n */\nexport async function pipeline(\n task,\n model = null,\n {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n device = null,\n dtype = null,\n model_file_name = null,\n session_options = {},\n } = {}\n) {\n // Helper method to construct pipeline\n\n // Apply aliases\n // @ts-ignore\n task = TASK_ALIASES[task] ?? task;\n\n // Get pipeline info\n const pipelineInfo = SUPPORTED_TASKS[task.split('_', 1)[0]];\n if (!pipelineInfo) {\n throw Error(`Unsupported pipeline: ${task}. Must be one of [${Object.keys(SUPPORTED_TASKS)}]`)\n }\n\n // Use model if specified, otherwise, use default\n if (!model) {\n model = pipelineInfo.default.model\n console.log(`No model specified. Using default model: \"${model}\".`);\n }\n\n const pretrainedOptions = {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n device,\n dtype,\n model_file_name,\n session_options,\n }\n\n const classes = new Map([\n ['tokenizer', pipelineInfo.tokenizer],\n ['model', pipelineInfo.model],\n ['processor', pipelineInfo.processor],\n ]);\n\n // Load model, tokenizer, and processor (if they exist)\n const results = await loadItems(classes, model, pretrainedOptions);\n results.task = task;\n\n dispatchCallback(progress_callback, {\n 'status': 'ready',\n 'task': task,\n 'model': model,\n });\n\n const pipelineClass = pipelineInfo.pipeline;\n return new pipelineClass(results);\n}\n\n\n/**\n * Helper function to get applicable model, tokenizer, or processor classes for a given model.\n * @param {Map} mapping The mapping of names to classes, arrays of classes, or null.\n * @param {string} model The name of the model to load.\n * @param {import('./utils/hub.js').PretrainedOptions} pretrainedOptions The options to pass to the `from_pretrained` method.\n * @private\n */\nasync function loadItems(mapping, model, pretrainedOptions) {\n\n const result = Object.create(null);\n\n /**@type {Promise[]} */\n const promises = [];\n for (const [name, cls] of mapping.entries()) {\n if (!cls) continue;\n\n /**@type {Promise} */\n let promise;\n if (Array.isArray(cls)) {\n promise = new Promise(async (resolve, reject) => {\n let e;\n for (const c of cls) {\n if (c === null) {\n // If null, we resolve it immediately, meaning the relevant\n // class was not found, but it is optional.\n resolve(null);\n return;\n }\n try {\n resolve(await c.from_pretrained(model, pretrainedOptions));\n return;\n } catch (err) {\n if (err.message?.includes('Unsupported model type')) {\n // If the error is due to an unsupported model type, we\n // save the error and try the next class.\n e = err;\n } else if (err.message?.includes('Could not locate file')) {\n e = err;\n } else {\n reject(err);\n return;\n }\n\n }\n }\n reject(e);\n })\n } else {\n promise = cls.from_pretrained(model, pretrainedOptions);\n }\n\n result[name] = promise;\n promises.push(promise);\n }\n\n // Wait for all promises to resolve (in parallel)\n await Promise.all(promises);\n\n // Then assign to result\n for (const [name, promise] of Object.entries(result)) {\n result[name] = await promise;\n }\n\n return result;\n}","\n/**\n * @file Processors are used to prepare non-textual inputs (e.g., image or audio) for a model.\n * \n * **Example:** Using a `WhisperProcessor` to prepare an audio input for a model.\n * ```javascript\n * import { AutoProcessor, read_audio } from '@huggingface/transformers';\n *\n * let processor = await AutoProcessor.from_pretrained('openai/whisper-tiny.en');\n * let audio = await read_audio('https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac', 16000);\n * let { input_features } = await processor(audio);\n * // Tensor {\n * // data: Float32Array(240000) [0.4752984642982483, 0.5597258806228638, 0.56434166431427, ...],\n * // dims: [1, 80, 3000],\n * // type: 'float32',\n * // size: 240000,\n * // }\n * ```\n * \n * @module processors\n */\nimport {\n Callable,\n} from './utils/generic.js';\n\nimport {\n calculateDimensions,\n calculateReflectOffset,\n} from './utils/core.js';\n\nimport {\n getModelJSON,\n} from './utils/hub.js';\n\nimport {\n min,\n max,\n softmax,\n bankers_round,\n} from './utils/maths.js';\n\n\nimport { Tensor, cat, interpolate, stack, interpolate_4d, full } from './utils/tensor.js';\n\nimport { RawImage } from './utils/image.js';\nimport {\n window_function,\n spectrogram,\n mel_filter_bank,\n} from './utils/audio.js';\n\n\n// Helper functions\n\n/**\n * Converts bounding boxes from center format to corners format.\n * \n * @param {number[]} arr The coordinate for the center of the box and its width, height dimensions (center_x, center_y, width, height)\n * @returns {number[]} The coodinates for the top-left and bottom-right corners of the box (top_left_x, top_left_y, bottom_right_x, bottom_right_y)\n */\nfunction center_to_corners_format([centerX, centerY, width, height]) {\n return [\n centerX - width / 2,\n centerY - height / 2,\n centerX + width / 2,\n centerY + height / 2\n ];\n}\n\n/**\n * Post-processes the outputs of the model (for object detection).\n * @param {Object} outputs The outputs of the model that must be post-processed\n * @param {Tensor} outputs.logits The logits\n * @param {Tensor} outputs.pred_boxes The predicted boxes.\n * @param {number} [threshold=0.5] The threshold to use for the scores.\n * @param {[number, number][]} [target_sizes=null] The sizes of the original images.\n * @param {boolean} [is_zero_shot=false] Whether zero-shot object detection was performed.\n * @return {Object[]} An array of objects containing the post-processed outputs.\n * @private\n */\nfunction post_process_object_detection(outputs, threshold = 0.5, target_sizes = null, is_zero_shot = false) {\n const out_logits = outputs.logits;\n const out_bbox = outputs.pred_boxes;\n const [batch_size, num_boxes, num_classes] = out_logits.dims;\n\n if (target_sizes !== null && target_sizes.length !== batch_size) {\n throw Error(\"Make sure that you pass in as many target sizes as the batch dimension of the logits\")\n }\n let toReturn = [];\n for (let i = 0; i < batch_size; ++i) {\n let target_size = target_sizes !== null ? target_sizes[i] : null;\n let info = {\n boxes: [],\n classes: [],\n scores: []\n }\n let logits = out_logits[i];\n let bbox = out_bbox[i];\n\n for (let j = 0; j < num_boxes; ++j) {\n let logit = logits[j];\n\n let indices = [];\n let probs;\n if (is_zero_shot) {\n // Get indices of classes with high enough probability\n probs = logit.sigmoid().data;\n for (let k = 0; k < probs.length; ++k) {\n if (probs[k] > threshold) {\n indices.push(k);\n }\n }\n\n } else {\n // Get most probable class\n let maxIndex = max(logit.data)[1];\n\n if (maxIndex === num_classes - 1) {\n // This is the background class, skip it\n continue;\n }\n // Compute softmax over classes\n probs = softmax(logit.data);\n\n if (probs[maxIndex] < threshold) {\n continue;\n }\n indices.push(maxIndex);\n }\n\n for (const index of indices) {\n\n // Some class has a high enough probability\n /** @type {number[]} */\n let box = bbox[j].data;\n\n // convert to [x0, y0, x1, y1] format\n box = center_to_corners_format(box)\n if (target_size !== null) {\n box = box.map((x, i) => x * target_size[(i + 1) % 2])\n }\n\n info.boxes.push(box);\n info.classes.push(index);\n info.scores.push(probs[index]);\n }\n }\n toReturn.push(info);\n }\n return toReturn;\n}\n\n\n/**\n * Post-processes the outputs of the model (for semantic segmentation).\n * @param {*} outputs Raw outputs of the model.\n * @param {[number, number][]} [target_sizes=null] List of tuples corresponding to the requested final size\n * (height, width) of each prediction. If unset, predictions will not be resized.\n * @returns {{segmentation: Tensor; labels: number[]}[]} The semantic segmentation maps.\n */\nfunction post_process_semantic_segmentation(outputs, target_sizes = null) {\n\n const logits = outputs.logits;\n const batch_size = logits.dims[0];\n\n if (target_sizes !== null && target_sizes.length !== batch_size) {\n throw Error(\"Make sure that you pass in as many target sizes as the batch dimension of the logits\")\n }\n\n const toReturn = [];\n for (let i = 0; i < batch_size; ++i) {\n const target_size = target_sizes !== null ? target_sizes[i] : null;\n\n let data = logits[i];\n\n // 1. If target_size is not null, we need to resize the masks to the target size\n if (target_size !== null) {\n // resize the masks to the target size\n data = interpolate(data, target_size, 'bilinear', false);\n }\n const [height, width] = target_size ?? data.dims.slice(-2);\n\n const segmentation = new Tensor(\n 'int32',\n new Int32Array(height * width),\n [height, width]\n );\n\n // Buffer to store current largest value\n const buffer = data[0].data;\n const segmentation_data = segmentation.data;\n for (let j = 1; j < data.dims[0]; ++j) {\n const row = data[j].data;\n for (let k = 0; k < row.length; ++k) {\n if (row[k] > buffer[k]) {\n buffer[k] = row[k];\n segmentation_data[k] = j;\n }\n }\n }\n\n // Store which objects have labels\n // This is much more efficient that creating a set of the final values\n const hasLabel = new Array(data.dims[0]);\n for (let j = 0; j < segmentation_data.length; ++j) {\n const index = segmentation_data[j];\n hasLabel[index] = index;\n }\n /** @type {number[]} The unique list of labels that were detected */\n const labels = hasLabel.filter(x => x !== undefined);\n\n toReturn.push({ segmentation, labels });\n }\n return toReturn;\n}\n\n\n/**\n * Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and `labels`.\n * @param {Tensor} class_logits The class logits.\n * @param {Tensor} mask_logits The mask logits.\n * @param {number} object_mask_threshold A number between 0 and 1 used to binarize the masks.\n * @param {number} num_labels The number of labels.\n * @returns {[Tensor[], number[], number[]]} The binarized masks, the scores, and the labels.\n * @private\n */\nfunction remove_low_and_no_objects(class_logits, mask_logits, object_mask_threshold, num_labels) {\n\n const mask_probs_item = [];\n const pred_scores_item = [];\n const pred_labels_item = [];\n\n for (let j = 0; j < class_logits.dims[0]; ++j) {\n const cls = class_logits[j];\n const mask = mask_logits[j];\n\n const pred_label = max(cls.data)[1];\n if (pred_label === num_labels) {\n // Is the background, so we ignore it\n continue;\n }\n\n const scores = softmax(cls.data);\n const pred_score = scores[pred_label];\n if (pred_score > object_mask_threshold) {\n mask_probs_item.push(mask);\n pred_scores_item.push(pred_score);\n pred_labels_item.push(pred_label);\n }\n }\n\n return [mask_probs_item, pred_scores_item, pred_labels_item];\n}\n\n/**\n * Checks whether the segment is valid or not.\n * @param {Int32Array} mask_labels Labels for each pixel in the mask.\n * @param {Tensor[]} mask_probs Probabilities for each pixel in the masks.\n * @param {number} k The class id of the segment.\n * @param {number} mask_threshold The mask threshold.\n * @param {number} overlap_mask_area_threshold The overlap mask area threshold.\n * @returns {[boolean, number[]]} Whether the segment is valid or not, and the indices of the valid labels.\n * @private\n */\nfunction check_segment_validity(\n mask_labels,\n mask_probs,\n k,\n mask_threshold = 0.5,\n overlap_mask_area_threshold = 0.8\n) {\n // mask_k is a 1D array of indices, indicating where the mask is equal to k\n const mask_k = [];\n let mask_k_area = 0;\n let original_area = 0;\n\n const mask_probs_k_data = mask_probs[k].data;\n\n // Compute the area of all the stuff in query k\n for (let i = 0; i < mask_labels.length; ++i) {\n if (mask_labels[i] === k) {\n mask_k.push(i);\n ++mask_k_area;\n }\n\n if (mask_probs_k_data[i] >= mask_threshold) {\n ++original_area;\n }\n }\n let mask_exists = mask_k_area > 0 && original_area > 0;\n\n // Eliminate disconnected tiny segments\n if (mask_exists) {\n // Perform additional check\n let area_ratio = mask_k_area / original_area;\n mask_exists = area_ratio > overlap_mask_area_threshold;\n }\n\n return [mask_exists, mask_k]\n}\n\n/**\n * Computes the segments.\n * @param {Tensor[]} mask_probs The mask probabilities.\n * @param {number[]} pred_scores The predicted scores.\n * @param {number[]} pred_labels The predicted labels.\n * @param {number} mask_threshold The mask threshold.\n * @param {number} overlap_mask_area_threshold The overlap mask area threshold.\n * @param {Set} label_ids_to_fuse The label ids to fuse.\n * @param {number[]} target_size The target size of the image.\n * @returns {[Tensor, Array<{id: number, label_id: number, score: number}>]} The computed segments.\n * @private\n */\nfunction compute_segments(\n mask_probs,\n pred_scores,\n pred_labels,\n mask_threshold,\n overlap_mask_area_threshold,\n label_ids_to_fuse = null,\n target_size = null,\n) {\n const [height, width] = target_size ?? mask_probs[0].dims;\n\n const segmentation = new Tensor(\n 'int32',\n new Int32Array(height * width),\n [height, width]\n );\n const segments = [];\n\n // 1. If target_size is not null, we need to resize the masks to the target size\n if (target_size !== null) {\n // resize the masks to the target size\n for (let i = 0; i < mask_probs.length; ++i) {\n mask_probs[i] = interpolate(mask_probs[i], target_size, 'bilinear', false);\n }\n }\n\n // 2. Weigh each mask by its prediction score\n // NOTE: `mask_probs` is updated in-place\n // \n // Temporary storage for the best label/scores for each pixel ([height, width]):\n const mask_labels = new Int32Array(mask_probs[0].data.length);\n const bestScores = new Float32Array(mask_probs[0].data.length);\n\n for (let i = 0; i < mask_probs.length; ++i) {\n let score = pred_scores[i];\n\n const mask_probs_i_data = mask_probs[i].data;\n\n for (let j = 0; j < mask_probs_i_data.length; ++j) {\n mask_probs_i_data[j] *= score\n if (mask_probs_i_data[j] > bestScores[j]) {\n mask_labels[j] = i;\n bestScores[j] = mask_probs_i_data[j];\n }\n }\n }\n\n let current_segment_id = 0;\n\n // let stuff_memory_list = {}\n const segmentation_data = segmentation.data;\n for (let k = 0; k < pred_labels.length; ++k) {\n const pred_class = pred_labels[k];\n\n // TODO add `should_fuse`\n // let should_fuse = pred_class in label_ids_to_fuse\n\n // Check if mask exists and large enough to be a segment\n const [mask_exists, mask_k] = check_segment_validity(\n mask_labels,\n mask_probs,\n k,\n mask_threshold,\n overlap_mask_area_threshold\n )\n\n if (!mask_exists) {\n // Nothing to see here\n continue;\n }\n\n // TODO\n // if (pred_class in stuff_memory_list) {\n // current_segment_id = stuff_memory_list[pred_class]\n // } else {\n // current_segment_id += 1;\n // }\n ++current_segment_id;\n\n\n // Add current object segment to final segmentation map\n for (const index of mask_k) {\n segmentation_data[index] = current_segment_id;\n }\n\n segments.push({\n id: current_segment_id,\n label_id: pred_class,\n // was_fused: should_fuse, TODO\n score: pred_scores[k],\n })\n\n // TODO\n // if(should_fuse){\n // stuff_memory_list[pred_class] = current_segment_id\n // }\n }\n\n return [segmentation, segments];\n}\n\n\n/**\n * Post-process the model output to generate the final panoptic segmentation.\n * @param {*} outputs The model output to post process\n * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks.\n * @param {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values.\n * @param {number} [overlap_mask_area_threshold=0.8] The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask.\n * @param {Set} [label_ids_to_fuse=null] The labels in this state will have all their instances be fused together.\n * @param {[number, number][]} [target_sizes=null] The target sizes to resize the masks to.\n * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>}\n */\nfunction post_process_panoptic_segmentation(\n outputs,\n threshold = 0.5,\n mask_threshold = 0.5,\n overlap_mask_area_threshold = 0.8,\n label_ids_to_fuse = null,\n target_sizes = null,\n) {\n if (label_ids_to_fuse === null) {\n console.warn(\"`label_ids_to_fuse` unset. No instance will be fused.\")\n label_ids_to_fuse = new Set();\n }\n\n const class_queries_logits = outputs.class_queries_logits ?? outputs.logits; // [batch_size, num_queries, num_classes+1]\n const masks_queries_logits = outputs.masks_queries_logits ?? outputs.pred_masks; // [batch_size, num_queries, height, width]\n\n const mask_probs = masks_queries_logits.sigmoid() // [batch_size, num_queries, height, width]\n\n let [batch_size, num_queries, num_labels] = class_queries_logits.dims;\n num_labels -= 1; // Remove last class (background)\n\n if (target_sizes !== null && target_sizes.length !== batch_size) {\n throw Error(\"Make sure that you pass in as many target sizes as the batch dimension of the logits\")\n }\n\n let toReturn = [];\n for (let i = 0; i < batch_size; ++i) {\n let target_size = target_sizes !== null ? target_sizes[i] : null;\n\n let class_logits = class_queries_logits[i];\n let mask_logits = mask_probs[i];\n\n let [mask_probs_item, pred_scores_item, pred_labels_item] = remove_low_and_no_objects(class_logits, mask_logits, threshold, num_labels);\n\n if (pred_labels_item.length === 0) {\n // No mask found\n let [height, width] = target_size ?? mask_logits.dims.slice(-2);\n\n let segmentation = new Tensor(\n 'int32',\n new Int32Array(height * width).fill(-1),\n [height, width]\n )\n toReturn.push({\n segmentation: segmentation,\n segments_info: []\n });\n continue;\n }\n\n\n // Get segmentation map and segment information of batch item\n let [segmentation, segments] = compute_segments(\n mask_probs_item,\n pred_scores_item,\n pred_labels_item,\n mask_threshold,\n overlap_mask_area_threshold,\n label_ids_to_fuse,\n target_size,\n )\n\n toReturn.push({\n segmentation: segmentation,\n segments_info: segments\n })\n }\n\n return toReturn;\n}\n\n\n/**\n * Post-processes the outputs of the model (for instance segmentation).\n * @param {*} outputs Raw outputs of the model.\n * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks.\n * @param {[number, number][]} [target_sizes=null] List of tuples corresponding to the requested final size\n * (height, width) of each prediction. If unset, predictions will not be resized.\n * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>}\n */\nfunction post_process_instance_segmentation(outputs, threshold = 0.5, target_sizes = null) {\n throw new Error('Not implemented yet');\n return [];\n}\n\n/**\n * Named tuple to indicate the order we are using is (height x width), even though\n * the Graphics’ industry standard is (width x height).\n * @typedef {[height: number, width: number]} HeightWidth\n */\n\n/**\n * Helper function to validate audio inputs.\n * @param {any} audio The audio data.\n * @param {string} feature_extractor The name of the feature extractor.\n * @private\n */\nfunction validate_audio_inputs(audio, feature_extractor) {\n if (!(audio instanceof Float32Array || audio instanceof Float64Array)) {\n throw new Error(\n `${feature_extractor} expects input to be a Float32Array or a Float64Array, but got ${audio?.constructor?.name ?? typeof audio} instead. ` +\n `If using the feature extractor directly, remember to use \\`read_audio(url, sampling_rate)\\` to obtain the raw audio data of the file/url.`\n )\n }\n}\n\n/**\n * Helper function to constrain a value to be a multiple of a number.\n * @param {number} val The value to constrain.\n * @param {number} multiple The number to constrain to.\n * @param {number} [minVal=0] The minimum value to constrain to.\n * @param {number} [maxVal=null] The maximum value to constrain to.\n * @returns {number} The constrained value.\n * @private\n */\nfunction constraint_to_multiple_of(val, multiple, minVal = 0, maxVal = null) {\n const a = val / multiple;\n let x = bankers_round(a) * multiple;\n\n if (maxVal !== null && x > maxVal) {\n x = Math.floor(a) * multiple;\n }\n\n if (x < minVal) {\n x = Math.ceil(a) * multiple;\n }\n\n return x;\n}\n\n/**\n * Rounds the height and width down to the closest multiple of size_divisibility\n * @param {[number, number]} size The size of the image\n * @param {number} divisor The divisor to use.\n * @returns {[number, number]} The rounded size.\n */\nfunction enforce_size_divisibility([width, height], divisor) {\n return [\n Math.max(Math.floor(width / divisor), 1) * divisor,\n Math.max(Math.floor(height / divisor), 1) * divisor\n ];\n}\n\n\n/**\n * Base class for feature extractors.\n *\n * @extends Callable\n */\nexport class FeatureExtractor extends Callable {\n /**\n * Constructs a new FeatureExtractor instance.\n *\n * @param {Object} config The configuration for the feature extractor.\n */\n constructor(config) {\n super();\n this.config = config\n }\n}\n\n/**\n * @typedef {object} ImageFeatureExtractorResult\n * @property {Tensor} pixel_values The pixel values of the batched preprocessed images.\n * @property {HeightWidth[]} original_sizes Array of two-dimensional tuples like [[480, 640]].\n * @property {HeightWidth[]} reshaped_input_sizes Array of two-dimensional tuples like [[1000, 1330]].\n */\n\n/**\n * Feature extractor for image models.\n *\n * @extends FeatureExtractor\n */\nexport class ImageFeatureExtractor extends FeatureExtractor {\n\n /**\n * Constructs a new ImageFeatureExtractor instance.\n *\n * @param {Object} config The configuration for the feature extractor.\n * @param {number[]} config.image_mean The mean values for image normalization.\n * @param {number[]} config.image_std The standard deviation values for image normalization.\n * @param {boolean} config.do_rescale Whether to rescale the image pixel values to the [0,1] range.\n * @param {number} config.rescale_factor The factor to use for rescaling the image pixel values.\n * @param {boolean} config.do_normalize Whether to normalize the image pixel values.\n * @param {boolean} config.do_resize Whether to resize the image.\n * @param {number} config.resample What method to use for resampling.\n * @param {number|Object} config.size The size to resize the image to.\n * @param {boolean} [config.do_flip_channel_order=false] Whether to flip the color channels from RGB to BGR.\n * Can be overridden by the `do_flip_channel_order` parameter in the `preprocess` method.\n */\n constructor(config) {\n super(config);\n\n this.image_mean = this.config.image_mean ?? this.config.mean;\n this.image_std = this.config.image_std ?? this.config.std;\n\n this.resample = this.config.resample ?? 2; // 2 => bilinear\n this.do_rescale = this.config.do_rescale ?? true;\n this.rescale_factor = this.config.rescale_factor ?? (1 / 255);\n this.do_normalize = this.config.do_normalize;\n\n this.do_resize = this.config.do_resize;\n this.do_thumbnail = this.config.do_thumbnail;\n this.size = this.config.size;\n this.size_divisibility = this.config.size_divisibility ?? this.config.size_divisor;\n\n this.do_center_crop = this.config.do_center_crop;\n this.crop_size = this.config.crop_size;\n this.do_convert_rgb = this.config.do_convert_rgb ?? true;\n this.do_crop_margin = this.config.do_crop_margin;\n\n this.pad_size = this.config.pad_size;\n this.do_pad = this.config.do_pad;\n\n if (this.do_pad && !this.pad_size && this.size && this.size.width !== undefined && this.size.height !== undefined) {\n // Should pad, but no pad size specified\n // We infer the pad size from the resize size\n this.pad_size = this.size\n }\n\n this.do_flip_channel_order = this.config.do_flip_channel_order ?? false;\n }\n\n /**\n * Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any\n * corresponding dimension of the specified size.\n * @param {RawImage} image The image to be resized.\n * @param {{height:number, width:number}} size The size `{\"height\": h, \"width\": w}` to resize the image to.\n * @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use.\n * @returns {Promise} The resized image.\n */\n async thumbnail(image, size, resample = 2) {\n const input_height = image.height;\n const input_width = image.width;\n\n const output_height = size.height;\n const output_width = size.width;\n\n // We always resize to the smallest of either the input or output size.\n let height = Math.min(input_height, output_height)\n let width = Math.min(input_width, output_width)\n\n if (height === input_height && width === input_width) {\n return image;\n }\n if (input_height > input_width) {\n width = Math.floor(input_width * height / input_height);\n } else if (input_width > input_height) {\n height = Math.floor(input_height * width / input_width);\n }\n return await image.resize(width, height, { resample });\n }\n\n\n /**\n * Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold).\n * @param {RawImage} image The image to be cropped.\n * @param {number} gray_threshold Value below which pixels are considered to be gray.\n * @returns {Promise} The cropped image.\n */\n async crop_margin(image, gray_threshold = 200) {\n\n const gray_image = image.clone().grayscale();\n\n const minValue = min(gray_image.data)[0];\n const maxValue = max(gray_image.data)[0];\n const diff = maxValue - minValue;\n\n if (diff === 0) {\n return image;\n }\n\n const threshold = gray_threshold / 255;\n\n let x_min = gray_image.width, y_min = gray_image.height, x_max = 0, y_max = 0;\n const gray_image_data = gray_image.data;\n for (let j = 0; j < gray_image.height; ++j) {\n const row = j * gray_image.width;\n for (let i = 0; i < gray_image.width; ++i) {\n if ((gray_image_data[row + i] - minValue) / diff < threshold) {\n // We have a non-zero pixel, so we update the min/max values accordingly\n x_min = Math.min(x_min, i);\n y_min = Math.min(y_min, j);\n x_max = Math.max(x_max, i);\n y_max = Math.max(y_max, j);\n }\n }\n }\n\n image = await image.crop([x_min, y_min, x_max, y_max]);\n return image;\n }\n\n /**\n * Pad the image by a certain amount.\n * @param {Float32Array} pixelData The pixel data to pad.\n * @param {number[]} imgDims The dimensions of the image (height, width, channels).\n * @param {{width:number; height:number}|number} padSize The dimensions of the padded image.\n * @param {Object} options The options for padding.\n * @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add.\n * @param {boolean} [options.center=false] Whether to center the image.\n * @param {number} [options.constant_values=0] The constant value to use for padding.\n * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions.\n */\n pad_image(pixelData, imgDims, padSize, {\n mode = 'constant',\n center = false,\n constant_values = 0,\n } = {}) {\n const [imageHeight, imageWidth, imageChannels] = imgDims;\n\n let paddedImageWidth, paddedImageHeight;\n if (typeof padSize === 'number') {\n paddedImageWidth = padSize;\n paddedImageHeight = padSize;\n } else {\n paddedImageWidth = padSize.width;\n paddedImageHeight = padSize.height;\n }\n\n // Only add padding if there is a difference in size\n if (paddedImageWidth !== imageWidth || paddedImageHeight !== imageHeight) {\n const paddedPixelData = new Float32Array(paddedImageWidth * paddedImageHeight * imageChannels);\n if (Array.isArray(constant_values)) {\n // Fill with constant values, cycling through the array\n for (let i = 0; i < paddedPixelData.length; ++i) {\n paddedPixelData[i] = constant_values[i % imageChannels];\n }\n } else if (constant_values !== 0) {\n paddedPixelData.fill(constant_values);\n }\n\n const [left, top] = center\n ? [Math.floor((paddedImageWidth - imageWidth) / 2), Math.floor((paddedImageHeight - imageHeight) / 2)]\n : [0, 0];\n\n // Copy the original image into the padded image\n for (let i = 0; i < imageHeight; ++i) {\n const a = (i + top) * paddedImageWidth;\n const b = i * imageWidth;\n for (let j = 0; j < imageWidth; ++j) {\n const c = (a + j + left) * imageChannels;\n const d = (b + j) * imageChannels;\n for (let k = 0; k < imageChannels; ++k) {\n paddedPixelData[c + k] = pixelData[d + k];\n }\n }\n }\n\n if (mode === 'symmetric') {\n if (center) {\n throw new Error('`center` padding is not supported when `mode` is set to `symmetric`.');\n // TODO: Implement this\n }\n const h1 = imageHeight - 1;\n const w1 = imageWidth - 1;\n for (let i = 0; i < paddedImageHeight; ++i) {\n const a = i * paddedImageWidth;\n const b = calculateReflectOffset(i, h1) * imageWidth;\n\n for (let j = 0; j < paddedImageWidth; ++j) {\n if (i < imageHeight && j < imageWidth) continue; // Do not overwrite original image\n const c = (a + j) * imageChannels;\n const d = (b + calculateReflectOffset(j, w1)) * imageChannels;\n\n // Copy channel-wise\n for (let k = 0; k < imageChannels; ++k) {\n paddedPixelData[c + k] = pixelData[d + k];\n }\n }\n }\n }\n\n\n // Update pixel data and image dimensions\n pixelData = paddedPixelData;\n imgDims = [paddedImageHeight, paddedImageWidth, imageChannels]\n }\n return [pixelData, imgDims];\n }\n\n /**\n * Rescale the image' pixel values by `this.rescale_factor`.\n * @param {Float32Array} pixelData The pixel data to rescale.\n * @returns {void}\n */\n rescale(pixelData) {\n for (let i = 0; i < pixelData.length; ++i) {\n pixelData[i] = this.rescale_factor * pixelData[i];\n }\n }\n\n /**\n * Find the target (width, height) dimension of the output image after\n * resizing given the input image and the desired size.\n * @param {RawImage} image The image to resize.\n * @param {any} size The size to use for resizing the image. \n * @returns {[number, number]} The target (width, height) dimension of the output image after resizing.\n */\n get_resize_output_image_size(image, size) {\n // `size` comes in many forms, so we need to handle them all here:\n // 1. `size` is an integer, in which case we resize the image to be a square \n\n const [srcWidth, srcHeight] = image.size;\n\n let shortest_edge;\n let longest_edge;\n\n if (this.do_thumbnail) {\n // NOTE: custom logic for `Donut` models\n const { height, width } = size;\n shortest_edge = Math.min(height, width)\n }\n // Support both formats for backwards compatibility\n else if (Number.isInteger(size)) {\n shortest_edge = size;\n longest_edge = this.config.max_size ?? shortest_edge;\n\n } else if (size !== undefined) {\n // Extract known properties from `size`\n shortest_edge = size.shortest_edge;\n longest_edge = size.longest_edge;\n }\n\n // If `longest_edge` and `shortest_edge` are set, maintain aspect ratio and resize to `shortest_edge`\n // while keeping the largest dimension <= `longest_edge`\n if (shortest_edge !== undefined || longest_edge !== undefined) {\n // http://opensourcehacker.com/2011/12/01/calculate-aspect-ratio-conserving-resize-for-images-in-javascript/\n // Try resize so that shortest edge is `shortest_edge` (target)\n const shortResizeFactor = shortest_edge === undefined\n ? 1 // If `shortest_edge` is not set, don't upscale\n : Math.max(shortest_edge / srcWidth, shortest_edge / srcHeight);\n\n const newWidth = srcWidth * shortResizeFactor;\n const newHeight = srcHeight * shortResizeFactor;\n\n // The new width and height might be greater than `longest_edge`, so\n // we downscale again to ensure the largest dimension is `longest_edge` \n const longResizeFactor = longest_edge === undefined\n ? 1 // If `longest_edge` is not set, don't downscale\n : Math.min(longest_edge / newWidth, longest_edge / newHeight);\n\n // To avoid certain floating point precision issues, we round to 2 decimal places\n let finalWidth = Math.floor(Number((newWidth * longResizeFactor).toFixed(2)));\n let finalHeight = Math.floor(Number((newHeight * longResizeFactor).toFixed(2)));\n\n if (this.size_divisibility !== undefined) {\n [finalWidth, finalHeight] = enforce_size_divisibility([finalWidth, finalHeight], this.size_divisibility)\n }\n return [finalWidth, finalHeight];\n\n } else if (size !== undefined && size.width !== undefined && size.height !== undefined) {\n // If `width` and `height` are set, resize to those dimensions\n\n let newWidth = size.width;\n let newHeight = size.height;\n\n // Custom for DPT models\n if (this.config.keep_aspect_ratio && this.config.ensure_multiple_of) {\n\n // determine new height and width\n let scale_height = newHeight / srcHeight;\n let scale_width = newWidth / srcWidth;\n\n // scale as little as possible\n if (Math.abs(1 - scale_width) < Math.abs(1 - scale_height)) {\n // fit width\n scale_height = scale_width;\n } else {\n // fit height\n scale_width = scale_height;\n }\n\n newHeight = constraint_to_multiple_of(scale_height * srcHeight, this.config.ensure_multiple_of);\n newWidth = constraint_to_multiple_of(scale_width * srcWidth, this.config.ensure_multiple_of);\n }\n\n return [newWidth, newHeight];\n\n } else if (this.size_divisibility !== undefined) {\n return enforce_size_divisibility([srcWidth, srcHeight], this.size_divisibility);\n } else {\n throw new Error(`Could not resize image due to unsupported \\`this.size\\` option in config: ${JSON.stringify(size)}`);\n }\n }\n\n /**\n * Resizes the image.\n * @param {RawImage} image The image to resize.\n * @returns {Promise} The resized image.\n */\n async resize(image) {\n const [newWidth, newHeight] = this.get_resize_output_image_size(image, this.size);\n return await image.resize(newWidth, newHeight, {\n resample: this.resample,\n });\n }\n\n /**\n * @typedef {object} PreprocessedImage\n * @property {HeightWidth} original_size The original size of the image.\n * @property {HeightWidth} reshaped_input_size The reshaped input size of the image.\n * @property {Tensor} pixel_values The pixel values of the preprocessed image.\n */\n\n /**\n * Preprocesses the given image.\n *\n * @param {RawImage} image The image to preprocess.\n * @param {Object} overrides The overrides for the preprocessing options.\n * @returns {Promise} The preprocessed image.\n */\n async preprocess(image, {\n do_normalize = null,\n do_pad = null,\n do_convert_rgb = null,\n do_convert_grayscale = null,\n do_flip_channel_order = null,\n } = {}) {\n if (this.do_crop_margin) {\n // NOTE: Specific to nougat processors. This is done before resizing,\n // and can be interpreted as a pre-preprocessing step.\n image = await this.crop_margin(image);\n }\n\n const [srcWidth, srcHeight] = image.size; // original image size\n\n // Convert image to RGB if specified in config.\n if (do_convert_rgb ?? this.do_convert_rgb) {\n image = image.rgb();\n } else if (do_convert_grayscale) {\n image = image.grayscale();\n }\n\n // TODO:\n // For efficiency reasons, it might be best to merge the resize and center crop operations into one.\n\n // Resize all images\n if (this.do_resize) {\n image = await this.resize(image);\n }\n\n // Resize the image using thumbnail method.\n if (this.do_thumbnail) {\n image = await this.thumbnail(image, this.size, this.resample);\n }\n\n if (this.do_center_crop) {\n\n let crop_width;\n let crop_height;\n if (Number.isInteger(this.crop_size)) {\n crop_width = this.crop_size;\n crop_height = this.crop_size;\n } else {\n crop_width = this.crop_size.width;\n crop_height = this.crop_size.height;\n }\n\n image = await image.center_crop(crop_width, crop_height);\n }\n\n /** @type {HeightWidth} */\n const reshaped_input_size = [image.height, image.width];\n\n // NOTE: All pixel-level manipulation (i.e., modifying `pixelData`)\n // occurs with data in the hwc format (height, width, channels), \n // to emulate the behavior of the original Python code (w/ numpy).\n let pixelData = Float32Array.from(image.data);\n let imgDims = [image.height, image.width, image.channels];\n\n if (this.do_rescale) {\n this.rescale(pixelData);\n }\n\n if (do_normalize ?? this.do_normalize) {\n let image_mean = this.image_mean;\n if (!Array.isArray(this.image_mean)) {\n image_mean = new Array(image.channels).fill(image_mean);\n }\n\n let image_std = this.image_std;\n if (!Array.isArray(this.image_std)) {\n image_std = new Array(image.channels).fill(image_mean);\n }\n\n if (image_mean.length !== image.channels || image_std.length !== image.channels) {\n throw new Error(`When set to arrays, the length of \\`image_mean\\` (${image_mean.length}) and \\`image_std\\` (${image_std.length}) must match the number of channels in the image (${image.channels}).`);\n }\n\n for (let i = 0; i < pixelData.length; i += image.channels) {\n for (let j = 0; j < image.channels; ++j) {\n pixelData[i + j] = (pixelData[i + j] - image_mean[j]) / image_std[j];\n }\n }\n }\n\n // do padding after rescaling/normalizing\n if (do_pad ?? this.do_pad) {\n if (this.pad_size) {\n const padded = this.pad_image(pixelData, [image.height, image.width, image.channels], this.pad_size);\n [pixelData, imgDims] = padded; // Update pixel data and image dimensions\n } else if (this.size_divisibility) {\n const [paddedWidth, paddedHeight] = enforce_size_divisibility([imgDims[1], imgDims[0]], this.size_divisibility);\n [pixelData, imgDims] = this.pad_image(pixelData, imgDims, { width: paddedWidth, height: paddedHeight });\n }\n }\n\n if (do_flip_channel_order ?? this.do_flip_channel_order) {\n if (imgDims[2] !== 3) {\n throw new Error('Flipping channel order is only supported for RGB images.');\n }\n // Convert RGB to BGR\n for (let i = 0; i < pixelData.length; i += 3) {\n const temp = pixelData[i];\n pixelData[i] = pixelData[i + 2];\n pixelData[i + 2] = temp;\n }\n }\n\n const pixel_values = new Tensor('float32', pixelData, imgDims)\n .permute(2, 0, 1); // convert to channel dimension format (hwc -> chw)\n\n return {\n original_size: [srcHeight, srcWidth],\n reshaped_input_size: reshaped_input_size,\n pixel_values,\n }\n }\n\n /**\n * Calls the feature extraction process on an array of images,\n * preprocesses each image, and concatenates the resulting\n * features into a single Tensor.\n * @param {RawImage[]} images The image(s) to extract features from.\n * @param {...any} args Additional arguments.\n * @returns {Promise} An object containing the concatenated pixel values (and other metadata) of the preprocessed images.\n */\n async _call(images, ...args) {\n if (!Array.isArray(images)) {\n images = [images];\n }\n /** @type {PreprocessedImage[]} */\n const imageData = await Promise.all(images.map(x => this.preprocess(x)));\n\n // Stack pixel values\n const pixel_values = stack(imageData.map(x => x.pixel_values), 0);\n\n return {\n pixel_values,\n\n // Original sizes of images\n original_sizes: imageData.map(x => x.original_size),\n\n // Reshaped sizes of images, before padding or cropping\n reshaped_input_sizes: imageData.map(x => x.reshaped_input_size),\n }\n }\n\n}\n\nexport class SapiensFeatureExtractor extends ImageFeatureExtractor {\n /** @type {typeof post_process_semantic_segmentation} */\n post_process_semantic_segmentation(...args) {\n return post_process_semantic_segmentation(...args);\n }\n}\nexport class SegformerFeatureExtractor extends ImageFeatureExtractor {\n /** @type {typeof post_process_semantic_segmentation} */\n post_process_semantic_segmentation(...args) {\n return post_process_semantic_segmentation(...args);\n }\n}\nexport class PvtImageProcessor extends ImageFeatureExtractor { }\nexport class DPTFeatureExtractor extends ImageFeatureExtractor { }\nexport class DPTImageProcessor extends DPTFeatureExtractor { } // NOTE: extends DPTFeatureExtractor\nexport class BitImageProcessor extends ImageFeatureExtractor { }\nexport class GLPNFeatureExtractor extends ImageFeatureExtractor { }\nexport class CLIPFeatureExtractor extends ImageFeatureExtractor { }\nexport class CLIPImageProcessor extends CLIPFeatureExtractor { } // NOTE: extends CLIPFeatureExtractor\nexport class ChineseCLIPFeatureExtractor extends ImageFeatureExtractor { }\nexport class SiglipImageProcessor extends ImageFeatureExtractor { }\nexport class ConvNextFeatureExtractor extends ImageFeatureExtractor {\n constructor(config) {\n super(config);\n\n /**\n * Percentage of the image to crop. Only has an effect if this.size < 384.\n */\n this.crop_pct = this.config.crop_pct ?? (224 / 256);\n }\n\n async resize(image) {\n const shortest_edge = this.size?.shortest_edge;\n if (shortest_edge === undefined) {\n throw new Error(`Size dictionary must contain 'shortest_edge' key.`);\n }\n\n if (shortest_edge < 384) {\n // maintain same ratio, resizing shortest edge to shortest_edge/crop_pct\n const resize_shortest_edge = Math.floor(shortest_edge / this.crop_pct);\n\n const [newWidth, newHeight] = this.get_resize_output_image_size(image, {\n shortest_edge: resize_shortest_edge,\n });\n\n image = await image.resize(newWidth, newHeight, {\n resample: this.resample,\n });\n\n // then crop to (shortest_edge, shortest_edge)\n image = await image.center_crop(shortest_edge, shortest_edge);\n } else {\n // warping (no cropping) when evaluated at 384 or larger\n image = await image.resize(shortest_edge, shortest_edge, {\n resample: this.resample,\n });\n }\n\n return image;\n }\n}\nexport class ConvNextImageProcessor extends ConvNextFeatureExtractor { } // NOTE extends ConvNextFeatureExtractor\nexport class ViTFeatureExtractor extends ImageFeatureExtractor { }\nexport class ViTImageProcessor extends ImageFeatureExtractor { }\n\nexport class EfficientNetImageProcessor extends ImageFeatureExtractor {\n constructor(config) {\n super(config);\n this.include_top = this.config.include_top ?? true;\n if (this.include_top) {\n this.image_std = this.image_std.map(x => x * x);\n }\n }\n}\n\nexport class MobileNetV1FeatureExtractor extends ImageFeatureExtractor { }\nexport class MobileNetV2FeatureExtractor extends ImageFeatureExtractor { }\nexport class MobileNetV3FeatureExtractor extends ImageFeatureExtractor { }\nexport class MobileNetV4FeatureExtractor extends ImageFeatureExtractor { }\n\nexport class MobileViTFeatureExtractor extends ImageFeatureExtractor { }\nexport class MobileViTImageProcessor extends MobileViTFeatureExtractor { } // NOTE extends MobileViTFeatureExtractor\nexport class OwlViTFeatureExtractor extends ImageFeatureExtractor {\n /** @type {typeof post_process_object_detection} */\n post_process_object_detection(...args) {\n return post_process_object_detection(...args);\n }\n}\nexport class Owlv2ImageProcessor extends OwlViTFeatureExtractor { } // NOTE extends OwlViTFeatureExtractor\n\nexport class RTDetrImageProcessor extends ImageFeatureExtractor {\n /** @type {typeof post_process_object_detection} */\n post_process_object_detection(...args) {\n return post_process_object_detection(...args);\n }\n}\n\nexport class DeiTFeatureExtractor extends ImageFeatureExtractor { }\nexport class BeitFeatureExtractor extends ImageFeatureExtractor { }\nexport class DonutFeatureExtractor extends ImageFeatureExtractor {\n pad_image(pixelData, imgDims, padSize, options = {}) {\n const [imageHeight, imageWidth, imageChannels] = imgDims;\n\n let image_mean = this.image_mean;\n if (!Array.isArray(this.image_mean)) {\n image_mean = new Array(imageChannels).fill(image_mean);\n }\n\n let image_std = this.image_std;\n if (!Array.isArray(image_std)) {\n image_std = new Array(imageChannels).fill(image_mean);\n }\n\n const constant_values = image_mean.map((x, i) => - x / image_std[i]);\n\n return super.pad_image(pixelData, imgDims, padSize, {\n center: true,\n\n // Since normalization is done after padding, we need to use certain constant values to ensure the same behaviour is observed.\n // For more information, see https://github.com/huggingface/transformers/blob/main/src/transformers/models/donut/image_processing_donut.py#L433-L451\n constant_values: constant_values,\n ...options,\n });\n }\n}\nexport class NougatImageProcessor extends DonutFeatureExtractor { } // NOTE extends DonutFeatureExtractor\n\n/**\n * @typedef {object} DetrFeatureExtractorResultProps\n * @property {Tensor} pixel_mask\n * @typedef {ImageFeatureExtractorResult & DetrFeatureExtractorResultProps} DetrFeatureExtractorResult\n */\n\n/**\n * Detr Feature Extractor.\n *\n * @extends ImageFeatureExtractor\n */\nexport class DetrFeatureExtractor extends ImageFeatureExtractor {\n /**\n * Calls the feature extraction process on an array of images, preprocesses\n * each image, and concatenates the resulting features into a single Tensor.\n * @param {RawImage[]} images The image(s) to extract features from.\n * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images.\n */\n async _call(images) {\n const result = await super._call(images);\n\n // TODO support differently-sized images, for now assume all images are the same size.\n // TODO support different mask sizes (not just 64x64)\n // Currently, just fill pixel mask with 1s\n const maskSize = [result.pixel_values.dims[0], 64, 64];\n const pixel_mask = full(maskSize, 1n);\n\n return { ...result, pixel_mask };\n }\n\n /** @type {typeof post_process_object_detection} */\n post_process_object_detection(...args) {\n return post_process_object_detection(...args);\n }\n\n /** @type {typeof post_process_panoptic_segmentation} */\n post_process_panoptic_segmentation(...args) {\n return post_process_panoptic_segmentation(...args);\n }\n\n post_process_instance_segmentation() {\n // TODO\n throw Error(\"Not implemented yet\");\n }\n}\n\nexport class MaskFormerFeatureExtractor extends ImageFeatureExtractor {\n\n /** @type {typeof post_process_panoptic_segmentation} */\n post_process_panoptic_segmentation(...args) {\n return post_process_panoptic_segmentation(...args);\n }\n\n post_process_instance_segmentation() {\n // TODO\n throw Error(\"Not implemented yet\");\n }\n}\n\n\nexport class YolosFeatureExtractor extends ImageFeatureExtractor {\n /** @type {typeof post_process_object_detection} */\n post_process_object_detection(...args) {\n return post_process_object_detection(...args);\n }\n}\n\n/**\n * @typedef {object} SamImageProcessorResult\n * @property {Tensor} pixel_values\n * @property {HeightWidth[]} original_sizes\n * @property {HeightWidth[]} reshaped_input_sizes\n * @property {Tensor} [input_points]\n * @property {Tensor} [input_labels]\n * @property {Tensor} [input_boxes]\n */\n\nexport class SamImageProcessor extends ImageFeatureExtractor {\n\n /**\n * \n * @param {any} input_points \n * @param {HeightWidth[]} original_sizes \n * @param {HeightWidth[]} reshaped_input_sizes \n * @returns {Tensor}\n */\n reshape_input_points(input_points, original_sizes, reshaped_input_sizes, is_bounding_box = false) {\n\n // Make deep copy to avoid altering user's input\n input_points = structuredClone(input_points);\n let shape = calculateDimensions(input_points);\n\n // TODO: add support for 2D input_points\n if (shape.length === 3) {\n // Correct user's input\n if (!is_bounding_box) {\n shape = [1, ...shape];\n }\n input_points = [input_points];\n } else if (shape.length !== 4) {\n throw Error(\"The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.\")\n }\n\n // Reshape input points\n for (let i = 0; i < input_points.length; ++i) { // batch_size\n let originalImageSize = original_sizes[i];\n let reshapedImageSize = reshaped_input_sizes[i];\n\n let resizeFactors = [\n reshapedImageSize[0] / originalImageSize[0],\n reshapedImageSize[1] / originalImageSize[1]\n ]\n\n for (let j = 0; j < input_points[i].length; ++j) { // point_batch_size\n for (let k = 0; k < input_points[i][j].length; ++k) { // nb_points_per_image\n for (let w = 0; w < input_points[i][j][k].length; ++w) { // 2 or 4\n input_points[i][j][k][w] *= resizeFactors[w % 2];\n }\n }\n }\n }\n\n return new Tensor(\n 'float32',\n Float32Array.from(input_points.flat(Infinity)),\n shape\n )\n\n }\n\n /**\n * \n * @param {any} input_labels \n * @param {Tensor} input_points \n * @returns {Tensor}\n */\n add_input_labels(input_labels, input_points) {\n let shape = calculateDimensions(input_labels);\n if (shape.length === 2) {\n // Correct user's input\n shape = [1, ...shape];\n input_labels = [input_labels];\n } else if (shape.length !== 3) {\n throw Error(\"The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.\")\n }\n\n if (shape.some((x, i) => x !== input_points.dims[i])) {\n throw Error(`The first ${shape.length} dimensions of 'input_points' and 'input_labels' must be the same.`)\n }\n return new Tensor(\n 'int64',\n input_labels.flat(Infinity).map(BigInt),\n shape,\n )\n }\n /**\n * @param {any[]} images The URL(s) of the image(s) to extract features from.\n * @param {Object} [options] Additional options for the processor.\n * @param {any} [options.input_points=null] A 3D or 4D array, representing the input points provided by the user.\n * - 3D: `[point_batch_size, nb_points_per_image, 2]`. In this case, `batch_size` is assumed to be 1.\n * - 4D: `[batch_size, point_batch_size, nb_points_per_image, 2]`.\n * @param {any} [options.input_labels=null] A 2D or 3D array, representing the input labels for the points, used by the prompt encoder to encode the prompt.\n * - 2D: `[point_batch_size, nb_points_per_image]`. In this case, `batch_size` is assumed to be 1.\n * - 3D: `[batch_size, point_batch_size, nb_points_per_image]`.\n * @param {number[][][]} [options.input_boxes=null] A 3D array of shape `(batch_size, num_boxes, 4)`, representing the input boxes provided by the user.\n * This is used by the prompt encoder to encode the prompt. Generally yields to much better generated masks.\n * The processor will generate a tensor, with each dimension corresponding respectively to the image batch size,\n * the number of boxes per image and the coordinates of the top left and botton right point of the box.\n * In the order (`x1`, `y1`, `x2`, `y2`):\n * - `x1`: the x coordinate of the top left point of the input box\n * - `y1`: the y coordinate of the top left point of the input box\n * - `x2`: the x coordinate of the bottom right point of the input box\n * - `y2`: the y coordinate of the bottom right point of the input box\n * @returns {Promise}\n */\n async _call(images, {\n input_points = null,\n input_labels = null,\n input_boxes = null\n } = {}) {\n // TODO allow user to use preprocessed images\n /** @type {SamImageProcessorResult} */\n const processed = await super._call(images);\n\n if (input_points) {\n processed.input_points = this.reshape_input_points(\n input_points, processed.original_sizes, processed.reshaped_input_sizes\n );\n }\n\n if (input_labels) {\n if (!processed.input_points) {\n throw Error(\"`input_points` must be provided if `input_labels` are provided.\")\n }\n processed.input_labels = this.add_input_labels(input_labels, processed.input_points);\n }\n\n if (input_boxes) {\n processed.input_boxes = this.reshape_input_points(\n input_boxes, processed.original_sizes, processed.reshaped_input_sizes, true,\n );\n }\n\n return processed;\n }\n\n /**\n * Remove padding and upscale masks to the original image size.\n * @param {Tensor} masks Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.\n * @param {[number, number][]} original_sizes The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format.\n * @param {[number, number][]} reshaped_input_sizes The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.\n * @param {Object} options Optional parameters for post-processing.\n * @param {number} [options.mask_threshold] The threshold to use for binarizing the masks.\n * @param {boolean} [options.binarize] Whether to binarize the masks.\n * @param {Object} [options.pad_size] The target size the images were padded to before being passed to the model. If `null`, the target size is assumed to be the processor's `pad_size`.\n * @param {number} [options.pad_size.height] The height the images were padded to.\n * @param {number} [options.pad_size.width] The width the images were padded to.\n * @returns {Promise} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size.\n */\n async post_process_masks(masks, original_sizes, reshaped_input_sizes, {\n mask_threshold = 0.0,\n binarize = true,\n pad_size = null,\n } = {}) {\n // masks: [1, 1, 3, 256, 256]\n\n const output_masks = [];\n\n pad_size = pad_size ?? this.pad_size;\n\n /** @type {[number, number]} */\n const target_image_size = [pad_size.height, pad_size.width];\n\n for (let i = 0; i < original_sizes.length; ++i) {\n const original_size = original_sizes[i];\n const reshaped_input_size = reshaped_input_sizes[i];\n\n // Upscale mask to padded size\n let interpolated_mask = (await interpolate_4d(\n masks[i],\n { mode: 'bilinear', size: target_image_size }\n ));\n\n // Crop mask\n interpolated_mask = interpolated_mask.slice(null, null, [0, reshaped_input_size[0]], [0, reshaped_input_size[1]]);\n\n // Downscale mask\n interpolated_mask = (await interpolate_4d(\n interpolated_mask,\n { mode: 'bilinear', size: original_size }\n ));\n\n if (binarize) {\n const data = interpolated_mask.data;\n const binarizedMaskData = new Uint8Array(data.length);\n for (let i = 0; i < data.length; ++i) {\n if (data[i] > mask_threshold) {\n binarizedMaskData[i] = 1;\n }\n }\n interpolated_mask = new Tensor(\n 'bool',\n binarizedMaskData,\n interpolated_mask.dims\n )\n }\n\n output_masks.push(interpolated_mask);\n }\n\n return output_masks;\n }\n\n /**\n * Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.\n * @param {RawImage} image Input original image\n * @param {number} target_size Target size of the resized image\n * @param {Object} options Options for generating crop boxes \n * @param {number} [options.crop_n_layers] If >0, mask prediction will be run again on crops of the image.\n * Sets the number of layers to run, where each layer has 2**i_layer number of image crops.\n * @param {number} [options.overlap_ratio] Sets the degree to which crops overlap. In the first crop layer,\n * crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap.\n * @param {number} [options.points_per_crop] Number of points to sample from each crop.\n * @param {number} [options.crop_n_points_downscale_factor] The number of points-per-side sampled in layer n is\n * scaled down by crop_n_points_downscale_factor**n.\n * @returns {Object} An object containing the crop boxes, number of points per crop, cropped images, and input labels.\n */\n generate_crop_boxes(image, target_size, {\n crop_n_layers = 0,\n overlap_ratio = 512 / 1500,\n points_per_crop = 32,\n crop_n_points_downscale_factor = 1,\n } = {}) {\n // TODO: Implement\n // return { crop_boxes, points_per_crop, cropped_images, input_labels }\n }\n}\n\nexport class Swin2SRImageProcessor extends ImageFeatureExtractor {\n pad_image(pixelData, imgDims, padSize, options = {}) {\n // NOTE: In this case, `padSize` represents the size of the sliding window for the local attention.\n // In other words, the image is padded so that its width and height are multiples of `padSize`.\n const [imageHeight, imageWidth, imageChannels] = imgDims;\n\n return super.pad_image(pixelData, imgDims, {\n // NOTE: For Swin2SR models, the original python implementation adds padding even when the image's width/height is already\n // a multiple of `pad_size`. However, this is most likely a bug (PR: https://github.com/mv-lab/swin2sr/pull/19).\n // For this reason, we only add padding when the image's width/height is not a multiple of `pad_size`.\n width: imageWidth + (padSize - imageWidth % padSize) % padSize,\n height: imageHeight + (padSize - imageHeight % padSize) % padSize,\n }, {\n mode: 'symmetric',\n center: false,\n constant_values: -1,\n ...options,\n })\n }\n}\n\nexport class VitMatteImageProcessor extends ImageFeatureExtractor {\n /**\n * Calls the feature extraction process on an array of images, preprocesses\n * each image, and concatenates the resulting features into a single Tensor.\n * @param {RawImage[]} images The image(s) to extract features from.\n * @param {RawImage[]} trimaps The trimaps(s) to extract features from.\n * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images.\n */\n async _call(images, trimaps) {\n if (!Array.isArray(images)) {\n images = [images];\n }\n if (!Array.isArray(trimaps)) {\n trimaps = [trimaps];\n }\n\n const imageData = await Promise.all(images.map(x => this.preprocess(x)));\n const trimapData = await Promise.all(trimaps.map(x => this.preprocess(x, {\n do_normalize: false,\n do_convert_rgb: false,\n do_convert_grayscale: true,\n })));\n\n\n // Stack pixel values\n const pixel_values = stack(imageData.map(\n // Concatenate images and trimaps\n (x, i) => cat([x.pixel_values, trimapData[i].pixel_values], 0)\n ), 0);\n\n return {\n pixel_values,\n\n // Original sizes of images\n original_sizes: imageData.map(x => x.original_size),\n\n // Reshaped sizes of images, before padding or cropping\n reshaped_input_sizes: imageData.map(x => x.reshaped_input_size),\n }\n }\n}\n\nexport class WhisperFeatureExtractor extends FeatureExtractor {\n\n constructor(config) {\n super(config);\n\n // Prefer given `mel_filters` from preprocessor_config.json, or calculate them if they don't exist.\n this.config.mel_filters ??= mel_filter_bank(\n Math.floor(1 + this.config.n_fft / 2), // num_frequency_bins\n this.config.feature_size, // num_mel_filters\n 0.0, // min_frequency\n 8000.0, // max_frequency\n this.config.sampling_rate, // sampling_rate\n \"slaney\", // norm\n \"slaney\", // mel_scale\n );\n\n this.window = window_function(this.config.n_fft, 'hann');\n }\n\n /**\n * Computes the log-Mel spectrogram of the provided audio waveform.\n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform) {\n const features = await spectrogram(\n waveform,\n this.window, // window\n this.config.n_fft, // frame_length\n this.config.hop_length, // hop_length\n {\n power: 2.0,\n mel_filters: this.config.mel_filters,\n log_mel: 'log10',\n\n // Custom\n max_num_frames: this.config.nb_max_frames, // 3000\n }\n )\n\n const data = features.data;\n const maxValue = max(data)[0];\n\n for (let i = 0; i < data.length; ++i) {\n data[i] = (Math.max(data[i], maxValue - 8.0) + 4.0) / 4.0;\n }\n\n return features;\n }\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'WhisperFeatureExtractor');\n\n let waveform;\n if (audio.length > this.config.n_samples) {\n console.warn(\n \"Attempting to extract features for audio longer than 30 seconds. \" +\n \"If using a pipeline to extract transcript from a long audio clip, \" +\n \"remember to specify `chunk_length_s` and/or `stride_length_s`.\"\n );\n waveform = audio.slice(0, this.config.n_samples);\n } else {\n // pad with zeros\n waveform = new Float32Array(this.config.n_samples);\n waveform.set(audio);\n }\n\n const features = await this._extract_fbank_features(waveform);\n\n return {\n input_features: features.unsqueeze_(0)\n };\n }\n}\n\nexport class Wav2Vec2FeatureExtractor extends FeatureExtractor {\n\n /**\n * @param {Float32Array} input_values \n * @returns {Float32Array} \n */\n _zero_mean_unit_var_norm(input_values) {\n // TODO support batch?\n const sum = input_values.reduce((a, b) => a + b, 0);\n const mean = sum / input_values.length;\n const variance = input_values.reduce((a, b) => a + (b - mean) ** 2, 0) / input_values.length;\n return input_values.map(x => (x - mean) / Math.sqrt(variance + 1e-7));\n }\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_values: Tensor; attention_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention mask as Tensors.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'Wav2Vec2FeatureExtractor');\n\n if (audio instanceof Float64Array) {\n audio = new Float32Array(audio);\n }\n\n let input_values = audio;\n\n // zero-mean and unit-variance normalization\n if (this.config.do_normalize) {\n input_values = this._zero_mean_unit_var_norm(input_values);\n }\n\n // TODO: allow user to pass in attention mask\n const shape = [1, input_values.length];\n return {\n input_values: new Tensor('float32', input_values, shape),\n attention_mask: new Tensor('int64', new BigInt64Array(input_values.length).fill(1n), shape)\n };\n }\n}\n\nexport class SeamlessM4TFeatureExtractor extends FeatureExtractor {\n\n constructor(config) {\n super(config);\n\n const sampling_rate = this.config.sampling_rate;\n const mel_filters = mel_filter_bank(\n 256, // num_frequency_bins\n this.config.num_mel_bins, // num_mel_filters\n 20, // min_frequency\n Math.floor(sampling_rate / 2), // max_frequency\n sampling_rate, // sampling_rate\n null, // norm\n \"kaldi\", // mel_scale\n true, // triangularize_in_mel_space\n );\n\n // Do padding:\n for (let i = 0; i < mel_filters.length; ++i) {\n mel_filters[i].push(0);\n }\n this.mel_filters = mel_filters;\n\n this.window = window_function(400, 'povey', {\n periodic: false,\n })\n }\n\n /**\n * Computes the log-Mel spectrogram of the provided audio waveform.\n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @param {number} max_length The maximum number of frames to return.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform, max_length) {\n // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`\n\n // Kaldi compliance: 16-bit signed integers\n // 32768 == 2 ** 15\n waveform = waveform.map((/** @type {number} */ x) => x * 32768)\n\n return spectrogram(\n waveform,\n this.window, // window\n 400, // frame_length\n 160, // hop_length\n {\n fft_length: 512,\n power: 2.0,\n center: false,\n preemphasis: 0.97,\n mel_filters: this.mel_filters,\n log_mel: 'log',\n mel_floor: 1.192092955078125e-07,\n remove_dc_offset: true,\n\n // Custom\n max_num_frames: max_length,\n transpose: true,\n }\n )\n }\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @param {Object} options Optional parameters for feature extraction.\n * @param {boolean} [options.padding=true] Whether to pad the sequence to a multiple of `pad_to_multiple_of`.\n * @param {number} [options.pad_to_multiple_of=2] The number to pad the sequence to a multiple of.\n * @param {boolean} [options.do_normalize_per_mel_bins=true] Whether or not to zero-mean unit-variance normalize the input per mel-channel.\n * @param {boolean} [options.return_attention_mask=true] Whether to return the attention mask.\n * @returns {Promise<{ input_features: Tensor, attention_mask?: Tensor }>} A Promise resolving to an object containing the extracted input features and attention masks as Tensors.\n */\n async _call(audio, {\n padding = true,\n pad_to_multiple_of = 2,\n do_normalize_per_mel_bins = true,\n return_attention_mask = true,\n } = {}) {\n validate_audio_inputs(audio, 'SeamlessM4TFeatureExtractor');\n\n let features = await this._extract_fbank_features(audio, this.config.max_length);\n\n if (do_normalize_per_mel_bins) {\n const [num_features, feature_size] = features.dims;\n const data = features.data;\n for (let i = 0; i < feature_size; ++i) {\n let sum = 0;\n for (let j = 0; j < num_features; ++j) {\n sum += data[j * feature_size + i];\n }\n\n const mean = sum / num_features;\n\n let variance = 0;\n for (let j = 0; j < num_features; ++j) {\n variance += (data[j * feature_size + i] - mean) ** 2;\n }\n variance /= num_features - 1; // NOTE: We use ddof=1\n\n const std = Math.sqrt(variance + 1e-7);\n for (let j = 0; j < num_features; ++j) {\n const index = j * feature_size + i;\n data[index] = (data[index] - mean) / std;\n }\n }\n }\n\n let padded_attention_mask;\n if (padding) {\n const [num_frames, num_channels] = features.dims;\n const data = /** @type {Float32Array} */(features.data);\n\n const pad_size = num_frames % pad_to_multiple_of;\n if (pad_size > 0) {\n const padded_data = new Float32Array(num_channels * (num_frames + pad_size));\n padded_data.set(data)\n padded_data.fill(this.config.padding_value, data.length)\n\n const numPaddedFrames = num_frames + pad_size;\n features = new Tensor(\n features.type,\n padded_data,\n [numPaddedFrames, num_channels],\n )\n\n if (return_attention_mask) {\n padded_attention_mask = new Tensor(\n 'int64',\n new BigInt64Array(numPaddedFrames),\n [1, numPaddedFrames],\n )\n padded_attention_mask.data.fill(1n, 0, num_frames);\n }\n }\n }\n\n const [num_frames, num_channels] = features.dims;\n\n const stride = this.config.stride;\n const remainder = num_frames % stride;\n if (remainder !== 0) {\n throw new Error(`The number of frames (${num_frames}) must be a multiple of the stride (${stride}).`)\n }\n\n const input_features = features.view(\n 1,\n Math.floor(num_frames / stride),\n num_channels * stride,\n );\n\n const result = { input_features }\n\n if (return_attention_mask) {\n const reshapedNumFrames = input_features.dims[1];\n\n const attention_mask_data = new BigInt64Array(reshapedNumFrames);\n\n if (padded_attention_mask) {\n const padded_attention_mask_data = padded_attention_mask.data;\n for (let i = 1, j = 0; i < num_frames; i += stride, ++j) {\n attention_mask_data[j] = padded_attention_mask_data[i];\n }\n } else {\n attention_mask_data.fill(1n);\n }\n result.attention_mask = new Tensor(\n 'int64',\n attention_mask_data,\n [1, reshapedNumFrames],\n );\n }\n\n return result;\n }\n}\n\nexport class ASTFeatureExtractor extends FeatureExtractor {\n\n\n constructor(config) {\n super(config);\n\n const sampling_rate = this.config.sampling_rate;\n const mel_filters = mel_filter_bank(\n 256, // num_frequency_bins\n this.config.num_mel_bins, // num_mel_filters\n 20, // min_frequency\n Math.floor(sampling_rate / 2), // max_frequency\n sampling_rate, // sampling_rate\n null, // norm\n \"kaldi\", // mel_scale\n true, // triangularize_in_mel_space\n );\n\n // Do padding:\n for (let i = 0; i < mel_filters.length; ++i) {\n mel_filters[i].push(0);\n }\n this.mel_filters = mel_filters;\n\n this.window = window_function(400, 'hann', {\n periodic: false,\n })\n\n this.mean = this.config.mean;\n this.std = this.config.std;\n }\n\n /**\n * Computes the log-Mel spectrogram of the provided audio waveform.\n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @param {number} max_length The maximum number of frames to return.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform, max_length) {\n // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`\n return spectrogram(\n waveform,\n this.window, // window\n 400, // frame_length\n 160, // hop_length\n {\n fft_length: 512,\n power: 2.0,\n center: false,\n preemphasis: 0.97,\n mel_filters: this.mel_filters,\n log_mel: 'log',\n mel_floor: 1.192092955078125e-07,\n remove_dc_offset: true,\n\n // Custom\n max_num_frames: max_length,\n transpose: true,\n }\n )\n }\n\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_values: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'ASTFeatureExtractor');\n\n const features = await this._extract_fbank_features(audio, this.config.max_length);\n if (this.config.do_normalize) {\n // Normalize the input audio spectrogram to have mean=0, std=0.5\n const denom = this.std * 2;\n const features_data = features.data;\n for (let i = 0; i < features_data.length; ++i) {\n features_data[i] = (features_data[i] - this.mean) / denom;\n }\n }\n\n return {\n input_values: features.unsqueeze_(0)\n };\n }\n}\n\nexport class ClapFeatureExtractor extends FeatureExtractor {\n\n constructor(config) {\n super(config);\n\n this.mel_filters = mel_filter_bank(\n this.config.nb_frequency_bins, // num_frequency_bins\n this.config.feature_size, // num_mel_filters\n this.config.frequency_min, // min_frequency\n this.config.frequency_max, // max_frequency\n this.config.sampling_rate, // sampling_rate\n null, // norm\n \"htk\", // mel_scale\n );\n\n this.mel_filters_slaney = mel_filter_bank(\n this.config.nb_frequency_bins, // num_frequency_bins\n this.config.feature_size, // num_mel_filters\n this.config.frequency_min, // min_frequency\n this.config.frequency_max, // max_frequency\n this.config.sampling_rate, // sampling_rate\n \"slaney\", // norm\n \"slaney\", // mel_scale\n );\n\n this.window = window_function(this.config.fft_window_size, 'hann')\n\n }\n\n\n /**\n * Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments.\n * \n * Four different path are possible:\n * - `truncation=\"fusion\"` and the length of the waveform is greater than the max length: the mel spectrogram\n * will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram\n * are then stacked together. They will later be used for `feature_fusion`.\n * - `truncation=\"rand_trunc\"` and the length of the waveform is smaller than the max length: the audio is\n * padded based on `padding`.\n * - `truncation=\"fusion\"` and the length of the waveform is smaller than the max length: the audio is padded\n * based on `padding`, and is repeated `4` times.\n * - `truncation=\"rand_trunc\"` and the length of the waveform is greater than the max length: the mel\n * spectrogram will be computed on a random crop of the waveform.\n * \n * @param {Float32Array|Float64Array} waveform The input waveform.\n * @param {number} max_length The maximum length of the waveform.\n * @param {string} truncation The truncation strategy to use.\n * @param {string} padding The padding strategy to use.\n * @returns {Promise} An object containing the mel spectrogram data as a Float32Array, its dimensions as an array of numbers, and a boolean indicating whether the waveform was longer than the max length.\n * @private\n */\n async _get_input_mel(waveform, max_length, truncation, padding) {\n\n /** @type {Tensor} */\n let input_mel;\n let longer = false;\n const diff = waveform.length - max_length;\n if (diff > 0) {\n if (truncation === 'rand_trunc') {\n longer = true;\n const idx = Math.floor(Math.random() * (diff + 1));\n waveform = waveform.subarray(idx, idx + max_length);\n\n input_mel = await this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples);\n } else {\n // TODO implement fusion strategy\n throw new Error(`Truncation strategy \"${truncation}\" not implemented`)\n }\n } else {\n if (diff < 0) {\n let padded = new Float64Array(max_length); // already padded with zeros\n padded.set(waveform);\n\n if (padding === 'repeat') {\n for (let i = waveform.length; i < max_length; i += waveform.length) {\n padded.set(waveform.subarray(0, Math.min(waveform.length, max_length - i)), i);\n }\n } else if (padding === 'repeatpad') {\n for (let i = waveform.length; i < -diff; i += waveform.length) {\n padded.set(waveform, i);\n }\n }\n waveform = padded;\n }\n\n if (truncation === 'fusion') {\n throw new Error(`Truncation strategy \"${truncation}\" not implemented`)\n }\n\n input_mel = await this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples);\n }\n\n return input_mel.unsqueeze_(0);\n }\n\n /**\n * Compute the log-mel spectrogram of the provided `waveform` using the Hann window.\n * In CLAP, two different filter banks are used depending on the truncation pattern:\n * - `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from\n * calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation`\n * is set to `\"fusion\"`.\n * - `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used\n * `librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original\n * implementation when the truncation mode is not `\"fusion\"`.\n * \n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @param {number[][]} mel_filters The mel filters to use.\n * @param {number} [max_length=null] The maximum number of frames to return.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform, mel_filters, max_length = null) {\n // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`\n return spectrogram(\n waveform,\n this.window, // window\n this.config.fft_window_size, // frame_length\n this.config.hop_length, // hop_length\n {\n power: 2.0,\n mel_filters,\n log_mel: 'dB',\n\n // Custom\n max_num_frames: max_length,\n do_pad: false,\n transpose: true,\n }\n )\n }\n\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.\n */\n async _call(audio, {\n max_length = null,\n } = {}) {\n validate_audio_inputs(audio, 'ClapFeatureExtractor');\n\n // convert to mel spectrogram, truncate and pad if needed.\n const padded_inputs = await this._get_input_mel(\n audio,\n max_length ?? this.config.nb_max_samples,\n this.config.truncation,\n this.config.padding,\n );\n\n return {\n input_features: padded_inputs.unsqueeze_(0),\n }\n }\n}\n\n\nexport class PyAnnoteFeatureExtractor extends FeatureExtractor {\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_values: Tensor; }>} The extracted input features.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'PyAnnoteFeatureExtractor');\n\n if (audio instanceof Float64Array) {\n audio = new Float32Array(audio);\n }\n\n const shape = [\n 1, /* batch_size */\n 1, /* num_channels */\n audio.length, /* num_samples */\n ];\n return {\n input_values: new Tensor('float32', audio, shape),\n };\n }\n\n /**\n * NOTE: Can return fractional values. `Math.ceil` will ensure correct value.\n * @param {number} samples The number of frames in the audio.\n * @returns {number} The number of frames in the audio.\n */\n samples_to_frames(samples) {\n return ((samples - this.config.offset) / this.config.step);\n }\n\n /**\n * Post-processes the speaker diarization logits output by the model.\n * @param {Tensor} logits The speaker diarization logits output by the model.\n * @param {number} num_samples Number of samples in the input audio.\n * @returns {Array>} The post-processed speaker diarization results.\n */\n post_process_speaker_diarization(logits, num_samples) {\n const ratio = (\n num_samples / this.samples_to_frames(num_samples)\n ) / this.config.sampling_rate;\n\n const results = [];\n for (const scores of logits.tolist()) {\n const accumulated_segments = [];\n\n let current_speaker = -1;\n for (let i = 0; i < scores.length; ++i) {\n const probabilities = softmax(scores[i]);\n const [score, id] = max(probabilities);\n const [start, end] = [i, i + 1];\n\n if (id !== current_speaker) {\n // Speaker has changed\n current_speaker = id;\n accumulated_segments.push({ id, start, end, score });\n } else {\n // Continue the current segment\n accumulated_segments.at(-1).end = end;\n accumulated_segments.at(-1).score += score;\n }\n }\n\n results.push(accumulated_segments.map(\n // Convert frame-space to time-space\n // and compute the confidence\n ({ id, start, end, score }) => ({\n id,\n start: start * ratio,\n end: end * ratio,\n confidence: score / (end - start),\n })\n ));\n }\n return results;\n }\n\n}\n\nexport class WeSpeakerFeatureExtractor extends FeatureExtractor {\n\n constructor(config) {\n super(config);\n\n const sampling_rate = this.config.sampling_rate;\n const mel_filters = mel_filter_bank(\n 256, // num_frequency_bins\n this.config.num_mel_bins, // num_mel_filters\n 20, // min_frequency\n Math.floor(sampling_rate / 2), // max_frequency\n sampling_rate, // sampling_rate\n null, // norm\n \"kaldi\", // mel_scale\n true, // triangularize_in_mel_space\n );\n\n // Do padding:\n for (let i = 0; i < mel_filters.length; ++i) {\n mel_filters[i].push(0);\n }\n this.mel_filters = mel_filters;\n\n this.window = window_function(400, 'hamming', {\n periodic: false,\n })\n this.min_num_frames = this.config.min_num_frames;\n }\n\n /**\n * Computes the log-Mel spectrogram of the provided audio waveform.\n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform) {\n // Kaldi compliance: 16-bit signed integers\n // 32768 == 2 ** 15\n waveform = waveform.map((/** @type {number} */ x) => x * 32768)\n\n return spectrogram(\n waveform,\n this.window, // window\n 400, // frame_length\n 160, // hop_length\n {\n fft_length: 512,\n power: 2.0,\n center: false,\n preemphasis: 0.97,\n mel_filters: this.mel_filters,\n log_mel: 'log',\n mel_floor: 1.192092955078125e-07,\n remove_dc_offset: true,\n\n // Custom\n transpose: true,\n min_num_frames: this.min_num_frames,\n }\n )\n }\n\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'WeSpeakerFeatureExtractor');\n\n const features = (await this._extract_fbank_features(audio)).unsqueeze_(0);\n\n if (this.config.fbank_centering_span === null) {\n // center features with global average\n const meanData = /** @type {Float32Array} */ (features.mean(1).data);\n const featuresData = /** @type {Float32Array} */(features.data);\n const [batch_size, num_frames, feature_size] = features.dims;\n\n for (let i = 0; i < batch_size; ++i) {\n const offset1 = i * num_frames * feature_size;\n const offset2 = i * feature_size;\n for (let j = 0; j < num_frames; ++j) {\n const offset3 = offset1 + j * feature_size;\n for (let k = 0; k < feature_size; ++k) {\n featuresData[offset3 + k] -= meanData[offset2 + k];\n }\n }\n }\n }\n\n return {\n input_features: features\n };\n }\n}\n\nexport class SpeechT5FeatureExtractor extends FeatureExtractor { }\n\n/**\n * Represents a Processor that extracts features from an input.\n * @extends Callable\n */\nexport class Processor extends Callable {\n /**\n * Creates a new Processor with the given feature extractor.\n * @param {FeatureExtractor} feature_extractor The function used to extract features from the input.\n */\n constructor(feature_extractor) {\n super();\n this.feature_extractor = feature_extractor;\n // TODO use tokenizer here?\n }\n\n /**\n * Calls the feature_extractor function with the given input.\n * @param {any} input The input to extract features from.\n * @param {...any} args Additional arguments.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(input, ...args) {\n return await this.feature_extractor(input, ...args);\n }\n}\n\nexport class SamProcessor extends Processor {\n /**\n * @borrows SamImageProcessor#_call as _call\n */\n async _call(...args) {\n return await this.feature_extractor(...args);\n }\n\n /**\n * @borrows SamImageProcessor#post_process_masks as post_process_masks\n */\n post_process_masks(...args) {\n // @ts-ignore\n return this.feature_extractor.post_process_masks(...args);\n }\n /**\n * @borrows SamImageProcessor#reshape_input_points as reshape_input_points\n */\n reshape_input_points(...args) {\n // @ts-ignore\n return this.feature_extractor.reshape_input_points(...args);\n }\n}\n\n/**\n * Represents a WhisperProcessor that extracts features from an audio input.\n * @extends Processor\n */\nexport class WhisperProcessor extends Processor {\n /**\n * Calls the feature_extractor function with the given audio input.\n * @param {any} audio The audio input to extract features from.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(audio) {\n return await this.feature_extractor(audio)\n }\n}\n\n\nexport class Wav2Vec2ProcessorWithLM extends Processor {\n /**\n * Calls the feature_extractor function with the given audio input.\n * @param {any} audio The audio input to extract features from.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(audio) {\n return await this.feature_extractor(audio)\n }\n}\n\nexport class PyAnnoteProcessor extends Processor {\n /**\n * Calls the feature_extractor function with the given audio input.\n * @param {any} audio The audio input to extract features from.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(audio) {\n return await this.feature_extractor(audio)\n }\n\n post_process_speaker_diarization(...args) {\n // @ts-ignore\n return this.feature_extractor.post_process_speaker_diarization(...args);\n }\n\n}\n\nexport class SpeechT5Processor extends Processor {\n /**\n * Calls the feature_extractor function with the given input.\n * @param {any} input The input to extract features from.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(input) {\n return await this.feature_extractor(input)\n }\n}\n\nexport class OwlViTProcessor extends Processor { }\n\nexport class Florence2Processor extends Processor {\n constructor(feature_extractor) {\n super(feature_extractor);\n\n const {\n tasks_answer_post_processing_type,\n task_prompts_without_inputs,\n task_prompts_with_input,\n } = feature_extractor.config;\n\n /** @type {Map} */\n this.tasks_answer_post_processing_type = new Map(Object.entries(tasks_answer_post_processing_type ?? {}));\n\n /** @type {Map} */\n this.task_prompts_without_inputs = new Map(Object.entries(task_prompts_without_inputs ?? {}));\n\n /** @type {Map} */\n this.task_prompts_with_input = new Map(Object.entries(task_prompts_with_input ?? {}));\n\n this.regexes = {\n quad_boxes: /(.+?)/gm,\n bboxes: /([^<]+)?/gm,\n }\n this.size_per_bin = 1000;\n }\n\n /**\n * Helper function to construct prompts from input texts\n * @param {string|string[]} text\n * @returns {string[]}\n */\n construct_prompts(text) {\n if (typeof text === 'string') {\n text = [text];\n }\n\n const prompts = [];\n for (const t of text) {\n // 1. fixed task prompts without additional inputs\n if (this.task_prompts_without_inputs.has(t)) {\n prompts.push(this.task_prompts_without_inputs.get(t));\n }\n // 2. task prompts with additional inputs \n else {\n for (const [task, prompt] of this.task_prompts_with_input) {\n if (t.includes(task)) {\n prompts.push(prompt.replaceAll('{input}', t).replaceAll(task, ''));\n break;\n }\n }\n\n // 3. default prompt\n if (prompts.length !== text.length) {\n prompts.push(t);\n }\n }\n }\n return prompts;\n }\n\n /**\n * Post-process the output of the model to each of the task outputs.\n * @param {string} text The text to post-process.\n * @param {string} task The task to post-process the text for.\n * @param {[number, number]} image_size The size of the image. height x width.\n */\n post_process_generation(text, task, image_size) {\n const task_answer_post_processing_type = this.tasks_answer_post_processing_type.get(task) ?? 'pure_text';\n\n // remove the special tokens\n text = text.replaceAll('', '').replaceAll('', '');\n\n let final_answer;\n switch (task_answer_post_processing_type) {\n case 'pure_text':\n final_answer = text;\n break;\n\n case 'description_with_bboxes':\n case 'bboxes':\n case 'phrase_grounding':\n case 'ocr':\n const key = task_answer_post_processing_type === 'ocr' ? 'quad_boxes' : 'bboxes';\n const matches = text.matchAll(this.regexes[key]);\n const labels = [];\n const items = [];\n for (const [_, label, ...locations] of matches) {\n // Push new label, or duplicate the last label\n labels.push(label ? label.trim() : labels.at(-1) ?? '');\n items.push(locations.map((x, i) =>\n // NOTE: Add 0.5 to use the center position of the bin as the coordinate.\n (Number(x) + 0.5) / this.size_per_bin * image_size[i % 2])\n );\n }\n final_answer = { labels, [key]: items };\n break;\n\n default:\n throw new Error(`Task \"${task}\" (of type \"${task_answer_post_processing_type}\") not yet implemented.`);\n }\n\n return { [task]: final_answer }\n }\n}\n\n//////////////////////////////////////////////////\n/**\n * Helper class which is used to instantiate pretrained processors with the `from_pretrained` function.\n * The chosen processor class is determined by the type specified in the processor config.\n * \n * **Example:** Load a processor using `from_pretrained`.\n * ```javascript\n * let processor = await AutoProcessor.from_pretrained('openai/whisper-tiny.en');\n * ```\n * \n * **Example:** Run an image through a processor.\n * ```javascript\n * let processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16');\n * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * let image_inputs = await processor(image);\n * // {\n * // \"pixel_values\": {\n * // \"dims\": [ 1, 3, 224, 224 ],\n * // \"type\": \"float32\",\n * // \"data\": Float32Array [ -1.558687686920166, -1.558687686920166, -1.5440893173217773, ... ],\n * // \"size\": 150528\n * // },\n * // \"original_sizes\": [\n * // [ 533, 800 ]\n * // ],\n * // \"reshaped_input_sizes\": [\n * // [ 224, 224 ]\n * // ]\n * // }\n * ```\n */\nexport class AutoProcessor {\n static FEATURE_EXTRACTOR_CLASS_MAPPING = {\n ImageFeatureExtractor,\n WhisperFeatureExtractor,\n ViTFeatureExtractor,\n MobileViTFeatureExtractor,\n MobileViTImageProcessor,\n MobileNetV1FeatureExtractor,\n MobileNetV2FeatureExtractor,\n MobileNetV3FeatureExtractor,\n MobileNetV4FeatureExtractor,\n OwlViTFeatureExtractor,\n Owlv2ImageProcessor,\n CLIPFeatureExtractor,\n CLIPImageProcessor,\n Florence2Processor,\n ChineseCLIPFeatureExtractor,\n SiglipImageProcessor,\n ConvNextFeatureExtractor,\n ConvNextImageProcessor,\n SegformerFeatureExtractor,\n SapiensFeatureExtractor,\n BitImageProcessor,\n DPTImageProcessor,\n DPTFeatureExtractor,\n PvtImageProcessor,\n GLPNFeatureExtractor,\n BeitFeatureExtractor,\n DeiTFeatureExtractor,\n DetrFeatureExtractor,\n RTDetrImageProcessor,\n MaskFormerFeatureExtractor,\n YolosFeatureExtractor,\n DonutFeatureExtractor,\n NougatImageProcessor,\n EfficientNetImageProcessor,\n\n ViTImageProcessor,\n VitMatteImageProcessor,\n SamImageProcessor,\n Swin2SRImageProcessor,\n Wav2Vec2FeatureExtractor,\n SeamlessM4TFeatureExtractor,\n SpeechT5FeatureExtractor,\n ASTFeatureExtractor,\n ClapFeatureExtractor,\n PyAnnoteFeatureExtractor,\n WeSpeakerFeatureExtractor,\n }\n\n static PROCESSOR_CLASS_MAPPING = {\n WhisperProcessor,\n Wav2Vec2ProcessorWithLM,\n PyAnnoteProcessor,\n SamProcessor,\n SpeechT5Processor,\n OwlViTProcessor,\n Florence2Processor,\n }\n\n /**\n * Instantiate one of the processor classes of the library from a pretrained model.\n * \n * The processor class to instantiate is selected based on the `feature_extractor_type` property of the config object\n * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)\n * \n * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:\n * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co.\n * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a\n * user or organization name, like `dbmdz/bert-base-german-cased`.\n * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`.\n * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the processor.\n * \n * @returns {Promise} A new instance of the Processor class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n } = {}) {\n\n let preprocessorConfig = config ?? await getModelJSON(pretrained_model_name_or_path, 'preprocessor_config.json', true, {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n })\n\n // Determine feature extractor class\n // TODO: Ensure backwards compatibility with old configs\n let key = preprocessorConfig.feature_extractor_type ?? preprocessorConfig.image_processor_type;\n let feature_extractor_class = this.FEATURE_EXTRACTOR_CLASS_MAPPING[key];\n\n if (!feature_extractor_class) {\n if (preprocessorConfig.size !== undefined) {\n // Assume ImageFeatureExtractor\n console.warn(`Feature extractor type \"${key}\" not found, assuming ImageFeatureExtractor due to size parameter in config.`);\n feature_extractor_class = ImageFeatureExtractor;\n } else {\n throw new Error(`Unknown Feature Extractor type: ${key}`);\n }\n }\n\n // If no associated processor class, use default\n let processor_class = this.PROCESSOR_CLASS_MAPPING[preprocessorConfig.processor_class] ?? Processor;\n\n // Instantiate processor and feature extractor\n let feature_extractor = new feature_extractor_class(preprocessorConfig);\n return new processor_class(feature_extractor);\n }\n}\n//////////////////////////////////////////////////\n\n","\n/**\n * @file Tokenizers are used to prepare textual inputs for a model.\n * \n * **Example:** Create an `AutoTokenizer` and use it to tokenize a sentence.\n * This will automatically detect the tokenizer type based on the tokenizer class defined in `tokenizer.json`.\n * ```javascript\n * import { AutoTokenizer } from '@huggingface/transformers';\n * \n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');\n * const { input_ids } = await tokenizer('I love transformers!');\n * // Tensor {\n * // data: BigInt64Array(6) [101n, 1045n, 2293n, 19081n, 999n, 102n],\n * // dims: [1, 6],\n * // type: 'int64',\n * // size: 6,\n * // }\n * ```\n * \n * @module tokenizers\n */\nimport {\n Callable,\n} from './utils/generic.js';\n\nimport {\n reverseDictionary,\n escapeRegExp,\n isIntegralNumber,\n mergeArrays,\n len,\n} from './utils/core.js';\n\nimport {\n getModelJSON,\n} from './utils/hub.js';\n\nimport { max, min, round } from './utils/maths.js';\nimport { Tensor } from './utils/tensor.js';\n\nimport {\n PriorityQueue,\n TokenLattice,\n CharTrie,\n} from './utils/data-structures.js';\n\nimport { Template } from '@huggingface/jinja';\n\nimport {\n WHISPER_LANGUAGE_MAPPING,\n whisper_language_to_code,\n} from './models/whisper/common_whisper.js';\nimport { GITHUB_ISSUE_URL } from './utils/constants.js';\n\n/**\n * @typedef {Object} TokenizerProperties Additional tokenizer-specific properties.\n * @property {boolean} [legacy=false] Whether or not the `legacy` behavior of the tokenizer should be used.\n * @typedef {import('./utils/hub.js').PretrainedOptions & TokenizerProperties} PretrainedTokenizerOptions\n */\n\n/**\n * Loads a tokenizer from the specified path.\n * @param {string} pretrained_model_name_or_path The path to the tokenizer directory.\n * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.\n * @returns {Promise} A promise that resolves with information about the loaded tokenizer.\n */\nasync function loadTokenizer(pretrained_model_name_or_path, options) {\n\n const info = await Promise.all([\n getModelJSON(pretrained_model_name_or_path, 'tokenizer.json', true, options),\n getModelJSON(pretrained_model_name_or_path, 'tokenizer_config.json', true, options),\n ])\n\n // Override legacy option if `options.legacy` is not null\n if (options.legacy !== null) {\n info[1].legacy = options.legacy;\n }\n return info;\n}\n\n\n/**\n * Helper function to split a string on a regex, but keep the delimiters.\n * This is required, because the JavaScript `.split()` method does not keep the delimiters,\n * and wrapping in a capturing group causes issues with existing capturing groups (due to nesting).\n * @param {string} text The text to split.\n * @param {RegExp} regex The regex to split on.\n * @returns {string[]} The split string.\n */\nfunction regexSplit(text, regex) {\n const result = [];\n let prev = 0;\n for (const match of text.matchAll(regex)) {\n const fullMatch = match[0];\n if (prev < match.index) {\n result.push(text.slice(prev, match.index));\n }\n if (fullMatch.length > 0) {\n result.push(fullMatch);\n }\n prev = match.index + fullMatch.length;\n }\n if (prev < text.length) {\n result.push(text.slice(prev));\n }\n return result;\n}\n\n\n/**\n * Helper method to construct a pattern from a config object.\n * @param {Object} pattern The pattern object.\n * @param {boolean} invert Whether to invert the pattern.\n * @returns {RegExp|null} The compiled pattern.\n */\nfunction createPattern(pattern, invert = true) {\n\n if (pattern.Regex !== undefined) {\n // In certain cases, the pattern may contain unnecessary escape sequences (e.g., \\# or \\& or \\~).\n // i.e., valid in Python (where the patterns are exported from) but invalid in JavaScript (where the patterns are parsed).\n // This isn't an issue when creating the regex w/o the 'u' flag, but it is when the 'u' flag is used.\n // For this reason, it is necessary to remove these backslashes before creating the regex.\n // See https://stackoverflow.com/a/63007777/13989043 for more information\n let regex = pattern.Regex.replace(/\\\\([#&~])/g, '$1'); // TODO: add more characters to this list if necessary\n\n // We also handle special cases where the regex contains invalid (non-JS compatible) syntax.\n for (const [key, value] of PROBLEMATIC_REGEX_MAP) {\n regex = regex.replaceAll(key, value);\n }\n\n return new RegExp(regex, 'gu');\n\n } else if (pattern.String !== undefined) {\n const escaped = escapeRegExp(pattern.String);\n // NOTE: if invert is true, we wrap the pattern in a group so that it is kept when performing .split()\n return new RegExp(invert ? escaped : `(${escaped})`, 'gu');\n\n } else {\n console.warn('Unknown pattern type:', pattern)\n return null;\n }\n}\n\n/**\n * Helper function to convert an Object to a Map\n * @param {Object} obj The object to convert.\n * @returns {Map} The map.\n */\nfunction objectToMap(obj) {\n return new Map(Object.entries(obj));\n}\n\n/**\n * Helper function to convert a tensor to a list before decoding.\n * @param {Tensor} tensor The tensor to convert.\n * @returns {number[]} The tensor as a list.\n */\nfunction prepareTensorForDecode(tensor) {\n const dims = tensor.dims;\n switch (dims.length) {\n case 1:\n return tensor.tolist();\n case 2:\n if (dims[0] !== 1) {\n throw new Error('Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.');\n }\n return tensor.tolist()[0];\n default:\n throw new Error(`Expected tensor to have 1-2 dimensions, got ${dims.length}.`)\n }\n}\n\n/**\n * Clean up a list of simple English tokenization artifacts like spaces before punctuations and abbreviated forms\n * @param {string} text The text to clean up.\n * @returns {string} The cleaned up text.\n */\nfunction clean_up_tokenization(text) {\n // Clean up a list of simple English tokenization artifacts\n // like spaces before punctuations and abbreviated forms\n return text.replace(/ \\./g, '.')\n .replace(/ \\?/g, '?')\n .replace(/ \\!/g, '!')\n .replace(/ ,/g, ',')\n .replace(/ \\' /g, \"'\")\n .replace(/ n\\'t/g, \"n't\")\n .replace(/ \\'m/g, \"'m\")\n .replace(/ \\'s/g, \"'s\")\n .replace(/ \\'ve/g, \"'ve\")\n .replace(/ \\'re/g, \"'re\");\n}\n\n/**\n * Helper function to remove accents from a string.\n * @param {string} text The text to remove accents from.\n * @returns {string} The text with accents removed.\n */\nfunction remove_accents(text) {\n return text.replace(/\\p{M}/gu, '');\n}\n\n/**\n * Helper function to lowercase a string and remove accents.\n * @param {string} text The text to lowercase and remove accents from.\n * @returns {string} The lowercased text with accents removed.\n */\nfunction lowercase_and_remove_accent(text) {\n return remove_accents(text.toLowerCase());\n}\n\n\n/**\n * Checks whether the given Unicode codepoint represents a CJK (Chinese, Japanese, or Korean) character.\n *\n * A \"chinese character\" is defined as anything in the CJK Unicode block:\n * https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)\n *\n * Note that the CJK Unicode block is NOT all Japanese and Korean characters, despite its name.\n * The modern Korean Hangul alphabet is a different block, as is Japanese Hiragana and Katakana.\n * Those alphabets are used to write space-separated words, so they are not treated specially\n * and are handled like all other languages.\n *\n * @param {number|bigint} cp The Unicode codepoint to check.\n * @returns {boolean} True if the codepoint represents a CJK character, false otherwise.\n */\nexport function is_chinese_char(cp) {\n return (\n (cp >= 0x4E00 && cp <= 0x9FFF)\n || (cp >= 0x3400 && cp <= 0x4DBF)\n || (cp >= 0x20000 && cp <= 0x2A6DF)\n || (cp >= 0x2A700 && cp <= 0x2B73F)\n || (cp >= 0x2B740 && cp <= 0x2B81F)\n || (cp >= 0x2B820 && cp <= 0x2CEAF)\n || (cp >= 0xF900 && cp <= 0xFAFF)\n || (cp >= 0x2F800 && cp <= 0x2FA1F)\n )\n}\n\n/**\n * Helper function to fuse consecutive unknown tokens.\n * @param {string[]} arr The list of input tokens\n * @param {Map} tokens_to_ids The mapping from tokens to token ids.\n * @param {number} unk_token_id The value to fuse on.\n * @private\n */\nfunction fuse_unk(arr, tokens_to_ids, unk_token_id) {\n const fused = [];\n let i = 0;\n while (i < arr.length) {\n fused.push(arr[i])\n if ((tokens_to_ids.get(arr[i]) ?? unk_token_id) !== unk_token_id) {\n ++i;\n continue;\n }\n\n while (++i < arr.length && (tokens_to_ids.get(arr[i]) ?? unk_token_id) === unk_token_id) {\n if (tokens_to_ids.get(fused.at(-1)) !== unk_token_id) {\n fused[fused.length - 1] += arr[i];\n }\n }\n }\n\n return fused;\n}\n\n/**\n * Split a string on whitespace.\n * @param {string} text The text to split.\n * @returns {string[]} The split string.\n */\nfunction whitespace_split(text) {\n return text.match(/\\S+/g) || [];\n}\n\nconst PUNCTUATION_REGEX = '\\\\p{P}\\\\u0021-\\\\u002F\\\\u003A-\\\\u0040\\\\u005B-\\\\u0060\\\\u007B-\\\\u007E';\nconst PUNCTUATION_ONLY_REGEX = new RegExp(`^[${PUNCTUATION_REGEX}]+$`, 'gu');\nconst BLOOM_SPLIT_CHARS = '.,!?\\u2026\\u3002\\uff0c\\u3001\\u0964\\u06d4\\u060c';\n\n// A mapping of regex patterns to their equivalent (but possibly longer) JS-compatible versions.\nconst PROBLEMATIC_REGEX_MAP = new Map([\n // This uses the case insensitive group modifier, which is not supported in JavaScript.\n // When parsing the regex, an \"Invalid group\" error is thrown.\n [\"(?i:'s|'t|'re|'ve|'m|'ll|'d)\", \"(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))\"],\n\n // Used to override the default (invalid) regex of the bloom pretokenizer.\n // For more information, see https://github.com/huggingface/transformers.js/issues/94\n [` ?[^(\\\\s|[${BLOOM_SPLIT_CHARS}])]+`, ` ?[^\\\\s${BLOOM_SPLIT_CHARS}]+`],\n])\n\n\n/**\n * Represent a token added by the user on top of the existing Model vocabulary.\n * AddedToken can be configured to specify the behavior they should have in various situations like:\n * - Whether they should only match single words\n * - Whether to include any whitespace on its left or right\n */\nclass AddedToken {\n /**\n * Creates a new instance of AddedToken.\n * @param {Object} config Added token configuration object.\n * @param {string} config.content The content of the added token.\n * @param {number} config.id The id of the added token.\n * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words.\n * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left.\n * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right.\n * @param {boolean} [config.normalized=false] Whether this token should be normalized.\n * @param {boolean} [config.special=false] Whether this token is special.\n */\n constructor(config) {\n this.content = config.content;\n this.id = config.id;\n this.single_word = config.single_word ?? false;\n this.lstrip = config.lstrip ?? false;\n this.rstrip = config.rstrip ?? false;\n this.special = config.special ?? false;\n this.normalized = config.normalized ?? null;\n }\n}\n\n/**\n * Abstract base class for tokenizer models.\n *\n * @extends Callable\n */\nexport class TokenizerModel extends Callable {\n /**\n * Creates a new instance of TokenizerModel.\n * @param {Object} config The configuration object for the TokenizerModel.\n */\n constructor(config) {\n super();\n this.config = config;\n\n /** @type {string[]} */\n this.vocab = [];\n\n /**\n * A mapping of tokens to ids.\n * @type {Map}\n */\n this.tokens_to_ids = new Map();\n\n this.unk_token_id = undefined;\n this.unk_token = undefined;\n this.end_of_word_suffix = undefined;\n\n /** @type {boolean} Whether to fuse unknown tokens when encoding. Defaults to false. */\n this.fuse_unk = this.config.fuse_unk ?? false;\n }\n\n /**\n * Instantiates a new TokenizerModel instance based on the configuration object provided.\n * @param {Object} config The configuration object for the TokenizerModel.\n * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor.\n * @returns {TokenizerModel} A new instance of a TokenizerModel.\n * @throws Will throw an error if the TokenizerModel type in the config is not recognized.\n */\n static fromConfig(config, ...args) {\n switch (config.type) {\n case 'WordPiece':\n return new WordPieceTokenizer(config);\n case 'Unigram':\n // @ts-ignore\n return new Unigram(config, ...args);\n case 'BPE':\n return new BPE(config);\n\n default:\n // Some tokenizers, like for google-t5/t5-small, do not have a `type` field.\n // In this case, we can infer the tokenizer type based on the structure of the `vocab` field.\n if (config.vocab) {\n if (Array.isArray(config.vocab)) {\n // config.vocab is of type `[string, number][]`\n // @ts-ignore\n return new Unigram(config, ...args);\n } else {\n // @ts-ignore\n return new LegacyTokenizerModel(config, ...args);\n }\n }\n throw new Error(`Unknown TokenizerModel type: ${config.type}`);\n }\n }\n\n /**\n * Internal function to call the TokenizerModel instance.\n * @param {string[]} tokens The tokens to encode.\n * @returns {string[]} The encoded tokens.\n */\n _call(tokens) {\n tokens = this.encode(tokens);\n if (this.fuse_unk) {\n // Fuse unknown tokens\n tokens = fuse_unk(tokens, this.tokens_to_ids, this.unk_token_id);\n }\n return tokens;\n }\n\n /**\n * Encodes a list of tokens into a list of token IDs.\n * @param {string[]} tokens The tokens to encode.\n * @returns {string[]} The encoded tokens.\n * @throws Will throw an error if not implemented in a subclass.\n */\n encode(tokens) {\n throw Error(\"encode should be implemented in subclass.\")\n }\n\n /**\n * Converts a list of tokens into a list of token IDs.\n * @param {string[]} tokens The tokens to convert.\n * @returns {number[]} The converted token IDs.\n */\n convert_tokens_to_ids(tokens) {\n return tokens.map(t => this.tokens_to_ids.get(t) ?? this.unk_token_id);\n }\n\n /**\n * Converts a list of token IDs into a list of tokens.\n * @param {number[]|bigint[]} ids The token IDs to convert.\n * @returns {string[]} The converted tokens.\n */\n convert_ids_to_tokens(ids) {\n return ids.map(i => this.vocab[i] ?? this.unk_token);\n }\n}\n\n/**\n * A subclass of TokenizerModel that uses WordPiece encoding to encode tokens.\n * @extends TokenizerModel\n */\nclass WordPieceTokenizer extends TokenizerModel {\n /**\n * @param {Object} config The configuration object.\n * @param {Object} config.vocab A mapping of tokens to ids.\n * @param {string} config.unk_token The unknown token string.\n * @param {string} config.continuing_subword_prefix The prefix to use for continuing subwords.\n * @param {number} [config.max_input_chars_per_word=100] The maximum number of characters per word.\n */\n constructor(config) {\n super(config);\n /**\n * A mapping of tokens to ids.\n * @type {Map}\n */\n this.tokens_to_ids = objectToMap(config.vocab);\n\n /**\n * The id of the unknown token.\n * @type {number}\n */\n this.unk_token_id = this.tokens_to_ids.get(config.unk_token);\n\n /**\n * The unknown token string.\n * @type {string}\n */\n this.unk_token = config.unk_token;\n\n /**\n * The maximum number of characters allowed per word.\n * @type {number}\n */\n this.max_input_chars_per_word = config.max_input_chars_per_word ?? 100;\n\n /**\n * An array of tokens.\n * @type {string[]}\n */\n this.vocab = new Array(this.tokens_to_ids.size);\n for (const [key, value] of this.tokens_to_ids) {\n this.vocab[value] = key;\n }\n }\n\n /**\n * Encodes an array of tokens using WordPiece encoding.\n * @param {string[]} tokens The tokens to encode.\n * @returns {string[]} An array of encoded tokens.\n */\n encode(tokens) {\n const outputTokens = [];\n for (const token of tokens) {\n const chars = [...token];\n if (chars.length > this.max_input_chars_per_word) {\n outputTokens.push(this.unk_token);\n continue;\n }\n\n let isUnknown = false;\n let start = 0;\n const subTokens = [];\n\n while (start < chars.length) {\n let end = chars.length;\n let currentSubstring = null;\n while (start < end) {\n let substr = chars.slice(start, end).join('');\n\n if (start > 0) {\n substr = this.config.continuing_subword_prefix + substr;\n }\n if (this.tokens_to_ids.has(substr)) {\n currentSubstring = substr;\n break;\n }\n\n --end;\n }\n if (currentSubstring === null) {\n isUnknown = true;\n break;\n }\n subTokens.push(currentSubstring);\n start = end;\n }\n if (isUnknown) {\n outputTokens.push(this.unk_token);\n } else {\n outputTokens.push(...subTokens);\n }\n }\n\n return outputTokens;\n }\n\n}\n\n/**\n * Class representing a Unigram tokenizer model.\n * @extends TokenizerModel\n */\nclass Unigram extends TokenizerModel {\n /**\n * Create a new Unigram tokenizer model.\n * @param {Object} config The configuration object for the Unigram model.\n * @param {number} config.unk_id The ID of the unknown token\n * @param {any[][]} config.vocab A 2D array representing a mapping of tokens to scores.\n * @param {Object} moreConfig Additional configuration object for the Unigram model.\n */\n constructor(config, moreConfig) {\n super(config);\n\n const vocabSize = config.vocab.length;\n this.vocab = new Array(vocabSize);\n this.scores = new Array(vocabSize);\n for (let i = 0; i < vocabSize; ++i) {\n const piece = config.vocab[i];\n this.vocab[i] = piece[0];\n this.scores[i] = piece[1];\n }\n\n this.unk_token_id = config.unk_id;\n this.unk_token = this.vocab[config.unk_id];\n\n this.tokens_to_ids = new Map(this.vocab.map((x, i) => [x, i]));\n this.bos_token = ' '; // beginning of a sentence token\n\n this.bos_token_id = this.tokens_to_ids.get(this.bos_token); // NOTE: may be undefined\n this.eos_token = moreConfig.eos_token;\n\n this.eos_token_id = this.tokens_to_ids.get(this.eos_token);\n this.unk_token = this.vocab[this.unk_token_id];\n\n this.minScore = min(this.scores)[0];\n\n this.unk_score = this.minScore - 10.0;\n this.scores[this.unk_token_id] = this.unk_score;\n\n this.trie = new CharTrie();\n this.trie.extend(this.vocab);\n\n // NOTE: `fuse_unk` is hardcoded to true for Unigram models\n // See: https://github.com/huggingface/tokenizers/blob/b58227c7f1ccf8b73ee2268354336da56d91e492/tokenizers/src/models/unigram/model.rs#L119\n this.fuse_unk = true;\n }\n\n /**\n * Populates lattice nodes.\n * @param {TokenLattice} lattice The token lattice to populate with nodes.\n */\n populateNodes(lattice) {\n const chars = lattice.chars;\n const mblen = 1;\n let beginPos = 0;\n while (beginPos < chars.length) {\n let hasSingleNode = false;\n\n const tokens = [];\n const sliced = chars.slice(beginPos).join('');\n const prefixedTokens = this.trie.commonPrefixSearch(sliced);\n for (const token of prefixedTokens) {\n tokens.push(token);\n const tokenId = this.tokens_to_ids.get(token);\n const tokenScore = this.scores[tokenId];\n const n = len(token);\n lattice.insert(beginPos, n, tokenScore, tokenId);\n if (!hasSingleNode && n === mblen) {\n hasSingleNode = true;\n }\n }\n if (!hasSingleNode) {\n lattice.insert(beginPos, mblen, this.unk_score, this.unk_token_id);\n }\n beginPos += mblen;\n }\n }\n\n /**\n * Encodes an array of tokens into an array of subtokens using the unigram model.\n *\n * @param {string} normalized The normalized string.\n * @returns {string[]} An array of subtokens obtained by encoding the input tokens using the unigram model.\n */\n tokenize(normalized) {\n const lattice = new TokenLattice(normalized, this.bos_token_id, this.eos_token_id);\n this.populateNodes(lattice);\n return lattice.tokens();\n }\n\n /**\n * Encodes an array of tokens using Unigram encoding.\n * @param {string[]} tokens The tokens to encode.\n * @returns {string[]} An array of encoded tokens.\n */\n encode(tokens) {\n const toReturn = [];\n for (const token of tokens) {\n const tokenized = this.tokenize(token);\n toReturn.push(...tokenized);\n }\n return toReturn;\n }\n\n}\n\n/**\n * Returns list of utf-8 byte and a mapping to unicode strings.\n * Specifically avoids mapping to whitespace/control characters the BPE code barfs on.\n * @returns {Object} Object with utf-8 byte keys and unicode string values.\n */\nconst BYTES_TO_UNICODE = (() => {\n // Returns list of utf-8 byte and a mapping to unicode strings.\n // We specifically avoids mapping to whitespace/control characters\n // the bpe code barfs on.\n\n const bs = [\n ...Array.from({ length: \"~\".charCodeAt(0) - \"!\".charCodeAt(0) + 1 }, (_, i) => i + \"!\".charCodeAt(0)),\n ...Array.from({ length: \"¬\".charCodeAt(0) - \"¡\".charCodeAt(0) + 1 }, (_, i) => i + \"¡\".charCodeAt(0)),\n ...Array.from({ length: \"ÿ\".charCodeAt(0) - \"®\".charCodeAt(0) + 1 }, (_, i) => i + \"®\".charCodeAt(0)),\n ];\n const cs = bs.slice();\n let n = 0;\n for (let b = 0; b < 256; ++b) {\n if (!bs.includes(b)) {\n bs.push(b);\n cs.push(256 + n);\n n += 1;\n }\n }\n const ccs = cs.map(n => String.fromCharCode(n));\n return Object.fromEntries(bs.map((b, i) => [b, ccs[i]]));\n})();\n\nconst UNICODE_TO_BYTES = reverseDictionary(BYTES_TO_UNICODE);\n\n\n/**\n * @typedef {Object} BPENode\n * @property {string} token The token associated with the node\n * @property {number} bias A positional bias for the node.\n * @property {number} [score] The score of the node.\n * @property {BPENode} [prev] The previous node in the linked list.\n * @property {BPENode} [next] The next node in the linked list.\n */\n\n/**\n * BPE class for encoding text into Byte-Pair-Encoding (BPE) tokens.\n * @extends TokenizerModel\n */\nclass BPE extends TokenizerModel {\n /**\n * Create a BPE instance.\n * @param {Object} config The configuration object for BPE.\n * @param {Object} config.vocab A mapping of tokens to ids.\n * @param {string[]|[string, string][]} config.merges An array of BPE merges as strings.\n * @param {string} config.unk_token The unknown token used for out of vocabulary words.\n * @param {string} config.end_of_word_suffix The suffix to place at the end of each word.\n * @param {string} [config.continuing_subword_suffix] The suffix to insert between words.\n * @param {boolean} [config.byte_fallback=false] Whether to use spm byte-fallback trick (defaults to False)\n * @param {boolean} [config.ignore_merges=false] Whether or not to match tokens with the vocab before using merges.\n */\n constructor(config) {\n super(config);\n\n /** @type {Map} */\n this.tokens_to_ids = objectToMap(config.vocab);\n\n this.unk_token_id = this.tokens_to_ids.get(config.unk_token);\n this.unk_token = config.unk_token;\n\n this.vocab = new Array(this.tokens_to_ids.size);\n for (const [key, value] of this.tokens_to_ids) {\n this.vocab[value] = key;\n }\n\n // Tokenizers >= 0.20.0 serializes BPE merges as a [string, string][] instead of a string[],\n // which resolves the ambiguity for merges containing spaces.\n const use_new_merge_format = Array.isArray(config.merges[0]);\n\n /** @type {[string, string][]} */\n this.merges = use_new_merge_format\n ? /** @type {[string, string][]} */(config.merges)\n : (/** @type {string[]} */(config.merges)).map(x => /** @type {[string, string]} */(x.split(' ', 2)));\n this.bpe_ranks = new Map(this.merges.map((x, i) => [JSON.stringify(x), i]));\n\n this.end_of_word_suffix = config.end_of_word_suffix;\n\n // NOTE: `continuing_subword_suffix` is custom (to support `BlenderbotSmallTokenizer`)\n this.continuing_subword_suffix = config.continuing_subword_suffix ?? null;\n\n this.byte_fallback = this.config.byte_fallback ?? false;\n\n if (this.byte_fallback) {\n this.text_encoder = new TextEncoder();\n }\n\n this.ignore_merges = this.config.ignore_merges ?? false;\n\n /** @type {Map} */\n this.cache = new Map();\n }\n\n /**\n * Apply Byte-Pair-Encoding (BPE) to a given token. Efficient heap-based priority\n * queue implementation adapted from https://github.com/belladoreai/llama-tokenizer-js.\n * @param {string} token The token to encode.\n * @returns {string[]} The BPE encoded tokens.\n */\n bpe(token) {\n if (token.length === 0) {\n return [];\n }\n\n const cached = this.cache.get(token);\n if (cached !== undefined) {\n return cached;\n }\n\n const word = Array.from(token);\n if (this.end_of_word_suffix) {\n word[word.length - 1] += this.end_of_word_suffix;\n }\n\n let result = [];\n if (word.length > 1) {\n // Create a priority queue to store the nodes that will be merged.\n // The comparator function compares the scores of the nodes.\n const queue = new PriorityQueue((a, b) => a.score < b.score);\n\n // Construct a doubly-linked list of nodes that will be inserted into the priority queue,\n // starting with the individual characters. We also populate each node with a positional\n // bias to break ties in the priority queue.\n let startingNode = {\n token: word[0],\n bias: 0,\n prev: null,\n next: null,\n }\n\n let previousNode = startingNode\n for (let i = 1; i < word.length; ++i) {\n const currentNode = {\n bias: i / word.length, // Add fractional component to break ties\n token: word[i],\n prev: previousNode,\n next: null,\n }\n previousNode.next = currentNode\n this._add_node(queue, previousNode)\n previousNode = currentNode\n }\n\n while (!queue.isEmpty()) {\n // Get the next node with the highest priority\n const node = queue.pop();\n\n // Check that this merge is still possible\n if (node.deleted || !node.next || node.next.deleted) continue;\n\n // Here, we mark the current node (left side of the merge) and the next node (right side of the merge) as deleted.\n // This is because they will both be replaced by a new node representing the merge result.\n node.deleted = true;\n node.next.deleted = true;\n\n // Next, we fix the node that comes before the current node (i.e., left side of the merge).\n if (node.prev) {\n\n // Make a shallow copy of the previous node\n const newPreviousNode = { ...node.prev };\n\n // Mark the old previous node as deleted. This avoids erroneous merges later,\n // because there may still be references to this node in the priority queue.\n node.prev.deleted = true;\n node.prev = newPreviousNode;\n\n // Update the reference of the previous node, by pointing its previous node to this new previous node.\n if (newPreviousNode.prev) {\n newPreviousNode.prev.next = newPreviousNode;\n } else {\n // If the previous of the previous node does not exist, it means that\n // `newPreviousNode` must be the new `startingNode`.\n startingNode = newPreviousNode;\n }\n }\n\n // Create a new node which represents the result of the merge.\n const merged = {\n token: node.token + node.next.token,\n bias: node.bias,\n prev: node.prev,\n next: node.next.next,\n }\n\n // We now consider where we can add the new merged node to the priority queue:\n // 1. prev <-> merged\n if (merged.prev) {\n merged.prev.next = merged;\n this._add_node(queue, merged.prev);\n } else {\n // If `merged.prev` does not exist, then `merged` must be the new `startingNode`.\n startingNode = merged;\n }\n\n // 2. merged <-> next\n if (merged.next) {\n merged.next.prev = merged;\n this._add_node(queue, merged);\n }\n }\n\n // Traverse the linked list, starting from the `startingNode`, and collect the tokens.\n for (let currentNode = startingNode; currentNode !== null; currentNode = currentNode.next) {\n result.push(currentNode.token);\n }\n } else {\n result = word;\n }\n\n // Possibly append suffix\n if (this.continuing_subword_suffix) {\n // Do not append suffix to the last token\n for (let i = 0; i < result.length - 1; ++i) {\n result[i] += this.continuing_subword_suffix;\n }\n }\n\n // Save the result to the cache\n this.cache.set(token, result);\n\n return result;\n }\n\n\n /**\n * Helper function to add a node to the priority queue.\n * @param {PriorityQueue} queue \n * @param {BPENode} node\n * @private\n */\n _add_node(queue, node) {\n // `score` is a measure of the merge priority: lower means higher priority\n // We use the BPE rank as a measure of priority (i.e., the local of the merge in the merges list)\n // We also add a fractional component to the score to break ties (with the earlier character having higher priority)\n const rank = this.bpe_ranks.get(JSON.stringify([node.token, node.next.token]));\n if (rank !== undefined) {\n node.score = rank + node.bias;\n queue.push(node);\n }\n }\n\n /**\n * Encodes the input sequence of tokens using the BPE algorithm and returns the resulting subword tokens.\n * @param {string[]} tokens The input sequence of tokens to encode.\n * @returns {string[]} The resulting subword tokens after applying the BPE algorithm to the input sequence of tokens.\n */\n encode(tokens) {\n const outputTokens = [];\n\n for (const token of tokens) {\n if (this.ignore_merges && this.tokens_to_ids.has(token)) {\n outputTokens.push(token);\n continue;\n }\n const bpe_token_list = this.bpe(token);\n\n for (const t of bpe_token_list) {\n if (this.tokens_to_ids.has(t)) {\n outputTokens.push(t);\n } else if (this.byte_fallback) {\n const byteTokens = Array.from(this.text_encoder.encode(t))\n .map(x => `<0x${x.toString(16).toUpperCase().padStart(2, '0')}>`);\n if (byteTokens.every(x => this.tokens_to_ids.has(x))) {\n // Ensure the byte tokens are actually in the vocabulary, otherwise\n // we fall back to the unknown token. For more information, see\n // https://github.com/huggingface/transformers/issues/28096.\n outputTokens.push(...byteTokens);\n } else {\n outputTokens.push(this.unk_token);\n }\n } else {\n outputTokens.push(this.unk_token);\n }\n }\n }\n\n return outputTokens;\n }\n\n}\n\n/**\n * Legacy tokenizer class for tokenizers with only a vocabulary.\n */\nclass LegacyTokenizerModel extends TokenizerModel {\n /**\n * Create a LegacyTokenizerModel instance.\n * @param {Object} config The configuration object for LegacyTokenizerModel.\n * @param {Object} config.vocab A (possibly nested) mapping of tokens to ids.\n * @param {Object} moreConfig Additional configuration object for the LegacyTokenizerModel model.\n */\n constructor(config, moreConfig) {\n super(config);\n\n /**@type {Map} */\n this.tokens_to_ids = objectToMap(\n moreConfig.target_lang\n ? config.vocab[moreConfig.target_lang]\n : config.vocab\n );\n\n this.bos_token = moreConfig.bos_token;\n this.bos_token_id = this.tokens_to_ids.get(this.bos_token);\n\n this.eos_token = moreConfig.eos_token;\n this.eos_token_id = this.tokens_to_ids.get(this.eos_token);\n\n this.pad_token = moreConfig.pad_token;\n this.pad_token_id = this.tokens_to_ids.get(this.pad_token);\n\n this.unk_token = moreConfig.unk_token;\n this.unk_token_id = this.tokens_to_ids.get(this.unk_token);\n\n this.vocab = new Array(this.tokens_to_ids.size);\n for (const [key, value] of this.tokens_to_ids) {\n this.vocab[value] = key;\n }\n }\n\n encode(tokens) {\n return tokens;\n }\n}\n\n\n/**\n * A base class for text normalization.\n * @abstract\n */\nclass Normalizer extends Callable {\n /**\n * @param {Object} config The configuration object for the normalizer.\n */\n constructor(config) {\n super();\n this.config = config;\n }\n\n /**\n * Factory method for creating normalizers from config objects.\n * @static\n * @param {Object} config The configuration object for the normalizer.\n * @returns {Normalizer} A Normalizer object.\n * @throws {Error} If an unknown Normalizer type is specified in the config.\n */\n static fromConfig(config) {\n if (config === null) return null;\n switch (config.type) {\n case 'BertNormalizer':\n return new BertNormalizer(config);\n case 'Precompiled':\n return new Precompiled(config);\n case 'Sequence':\n return new NormalizerSequence(config);\n case 'Replace':\n return new Replace(config);\n case 'NFC':\n return new NFC(config);\n case 'NFKC':\n return new NFKC(config);\n case 'NFKD':\n return new NFKD(config);\n case 'Strip':\n return new StripNormalizer(config);\n case 'StripAccents':\n return new StripAccents(config);\n case 'Lowercase':\n return new Lowercase(config);\n case 'Prepend':\n return new Prepend(config);\n default:\n throw new Error(`Unknown Normalizer type: ${config.type}`);\n }\n }\n\n /**\n * Normalize the input text.\n * @abstract\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n * @throws {Error} If this method is not implemented in a subclass.\n */\n normalize(text) {\n throw Error(\"normalize should be implemented in subclass.\")\n }\n\n /**\n * Alias for {@link Normalizer#normalize}.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n _call(text) {\n return this.normalize(text);\n }\n\n}\n\n/**\n * Replace normalizer that replaces occurrences of a pattern with a given string or regular expression.\n * @extends Normalizer\n */\nclass Replace extends Normalizer {\n /**\n * Normalize the input text by replacing the pattern with the content.\n * @param {string} text The input text to be normalized.\n * @returns {string} The normalized text after replacing the pattern with the content.\n */\n normalize(text) {\n const pattern = createPattern(this.config.pattern);\n return pattern === null\n ? text\n : text.replaceAll(pattern, this.config.content);\n }\n}\n\n/**\n * A normalizer that applies Unicode normalization form C (NFC) to the input text.\n * @extends Normalizer\n */\nclass NFC extends Normalizer {\n /**\n * Normalize the input text by applying Unicode normalization form C (NFC).\n * @param {string} text The input text to be normalized.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = text.normalize('NFC')\n return text;\n }\n}\n\n/**\n * NFKC Normalizer.\n * @extends Normalizer\n */\nclass NFKC extends Normalizer {\n /**\n * Normalize text using NFKC normalization.\n * @param {string} text The text to be normalized.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = text.normalize('NFKC')\n return text;\n }\n}\n/**\n * NFKD Normalizer.\n * @extends Normalizer\n */\nclass NFKD extends Normalizer {\n /**\n * Normalize text using NFKD normalization.\n * @param {string} text The text to be normalized.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = text.normalize('NFKD')\n return text;\n }\n}\n\n/**\n * A normalizer that strips leading and/or trailing whitespace from the input text.\n */\nclass StripNormalizer extends Normalizer {\n /**\n * Strip leading and/or trailing whitespace from the input text.\n * @param {string} text The input text.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n if (this.config.strip_left && this.config.strip_right) {\n // Fast path to avoid an extra trim call\n text = text.trim();\n } else {\n if (this.config.strip_left) {\n text = text.trimStart();\n }\n if (this.config.strip_right) {\n text = text.trimEnd();\n }\n }\n return text;\n }\n}\n\n/**\n * StripAccents normalizer removes all accents from the text.\n * @extends Normalizer\n */\nclass StripAccents extends Normalizer {\n /**\n * Remove all accents from the text.\n * @param {string} text The input text.\n * @returns {string} The normalized text without accents.\n */\n normalize(text) {\n text = remove_accents(text);\n return text;\n }\n}\n\n/**\n * A Normalizer that lowercases the input string.\n * @extends Normalizer\n */\nclass Lowercase extends Normalizer {\n /**\n * Lowercases the input string.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = text.toLowerCase();\n return text;\n }\n}\n\n/**\n * A Normalizer that prepends a string to the input string.\n * @extends Normalizer\n */\nclass Prepend extends Normalizer {\n /**\n * Prepends the input string.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = this.config.prepend + text;\n return text;\n }\n}\n\n/**\n * A Normalizer that applies a sequence of Normalizers.\n * @extends Normalizer\n */\nclass NormalizerSequence extends Normalizer {\n /**\n * Create a new instance of NormalizerSequence.\n * @param {Object} config The configuration object.\n * @param {Object[]} config.normalizers An array of Normalizer configuration objects.\n */\n constructor(config) {\n super(config);\n this.normalizers = config.normalizers.map(x => Normalizer.fromConfig(x));\n }\n /**\n * Apply a sequence of Normalizers to the input text.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n return this.normalizers.reduce((t, normalizer) => {\n return normalizer.normalize(t);\n }, text);\n }\n}\n\n/**\n * A class representing a normalizer used in BERT tokenization.\n * @extends Normalizer\n */\nclass BertNormalizer extends Normalizer {\n /**\n * Adds whitespace around any CJK (Chinese, Japanese, or Korean) character in the input text.\n *\n * @param {string} text The input text to tokenize.\n * @returns {string} The tokenized text with whitespace added around CJK characters.\n */\n _tokenize_chinese_chars(text) {\n /* Adds whitespace around any CJK character. */\n const output = [];\n for (let i = 0; i < text.length; ++i) {\n const char = text[i];\n const cp = char.charCodeAt(0);\n if (is_chinese_char(cp)) {\n output.push(\" \");\n output.push(char);\n output.push(\" \");\n } else {\n output.push(char);\n }\n }\n return output.join(\"\");\n }\n\n /**\n * Strips accents from the given text.\n * @param {string} text The text to strip accents from.\n * @returns {string} The text with accents removed.\n */\n stripAccents(text) {\n // \"Mark, Nonspacing\" (Mn)\n return text.normalize('NFD').replace(/\\p{Mn}/gu, '');\n }\n\n\n /**\n * Checks whether `char` is a control character.\n * @param {string} char The character to check.\n * @returns {boolean} Whether `char` is a control character.\n * @private\n */\n _is_control(char) {\n switch (char) {\n case '\\t':\n case '\\n':\n case '\\r':\n // These are technically control characters but we count them as whitespace characters.\n return false;\n\n default:\n // Check if unicode category starts with C:\n // Cc - Control\n // Cf - Format\n // Co - Private Use\n // Cs - Surrogate\n return /^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$/u.test(char);\n }\n }\n\n /**\n * Performs invalid character removal and whitespace cleanup on text.\n * @param {string} text The text to clean.\n * @returns {string} The cleaned text.\n * @private\n */\n _clean_text(text) {\n const output = [];\n for (const char of text) {\n const cp = char.charCodeAt(0);\n if (cp === 0 || cp === 0xFFFD || this._is_control(char)) {\n continue;\n }\n if (/^\\s$/.test(char)) { // is whitespace\n output.push(\" \");\n } else {\n output.push(char);\n }\n }\n return output.join(\"\");\n }\n /**\n * Normalizes the given text based on the configuration.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n if (this.config.clean_text) {\n text = this._clean_text(text);\n }\n\n if (this.config.handle_chinese_chars) {\n text = this._tokenize_chinese_chars(text);\n }\n\n if (this.config.lowercase) {\n text = text.toLowerCase();\n\n if (this.config.strip_accents !== false) {\n text = this.stripAccents(text);\n }\n } else if (this.config.strip_accents) {\n text = this.stripAccents(text);\n }\n\n return text;\n }\n}\n\n/**\n * A callable class representing a pre-tokenizer used in tokenization. Subclasses\n * should implement the `pre_tokenize_text` method to define the specific pre-tokenization logic.\n * @extends Callable\n */\nclass PreTokenizer extends Callable {\n /**\n * Factory method that returns an instance of a subclass of `PreTokenizer` based on the provided configuration.\n *\n * @static\n * @param {Object} config A configuration object for the pre-tokenizer.\n * @returns {PreTokenizer} An instance of a subclass of `PreTokenizer`.\n * @throws {Error} If the provided configuration object does not correspond to any known pre-tokenizer.\n */\n static fromConfig(config) {\n if (config === null) return null;\n\n switch (config.type) {\n case 'BertPreTokenizer':\n return new BertPreTokenizer(config);\n case 'Sequence':\n return new PreTokenizerSequence(config);\n case 'Whitespace':\n return new WhitespacePreTokenizer(config);\n case 'WhitespaceSplit':\n return new WhitespaceSplit(config);\n case 'Metaspace':\n return new MetaspacePreTokenizer(config);\n\n case 'ByteLevel':\n return new ByteLevelPreTokenizer(config);\n case 'Split':\n return new SplitPreTokenizer(config);\n case 'Punctuation':\n return new PunctuationPreTokenizer(config);\n case 'Digits':\n return new DigitsPreTokenizer(config);\n case 'Replace':\n return new ReplacePreTokenizer(config);\n default:\n throw new Error(`Unknown PreTokenizer type: ${config.type}`);\n }\n }\n\n /**\n * Method that should be implemented by subclasses to define the specific pre-tokenization logic.\n *\n * @abstract\n * @param {string} text The text to pre-tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} The pre-tokenized text.\n * @throws {Error} If the method is not implemented in the subclass.\n */\n pre_tokenize_text(text, options) {\n throw Error(\"pre_tokenize_text should be implemented in subclass.\")\n }\n\n /**\n * Tokenizes the given text into pre-tokens.\n * @param {string|string[]} text The text or array of texts to pre-tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of pre-tokens.\n */\n pre_tokenize(text, options) {\n return (Array.isArray(text)\n ? text.map(x => this.pre_tokenize_text(x, options))\n : this.pre_tokenize_text(text, options)\n ).flat();\n }\n\n /**\n * Alias for {@link PreTokenizer#pre_tokenize}.\n * @param {string|string[]} text The text or array of texts to pre-tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of pre-tokens.\n */\n _call(text, options) {\n return this.pre_tokenize(text, options);\n }\n}\n\n/**\n * @extends PreTokenizer\n */\nclass BertPreTokenizer extends PreTokenizer {\n /**\n * A PreTokenizer that splits text into wordpieces using a basic tokenization scheme\n * similar to that used in the original implementation of BERT.\n * \n * @param {Object} config The configuration object.\n */\n constructor(config) {\n super();\n // Construct a pattern which matches the rust implementation:\n // https://github.com/huggingface/tokenizers/blob/b4fcc9ce6e4ad5806e82826f816acfdfdc4fcc67/tokenizers/src/pre_tokenizers/bert.rs#L11\n // Equivalent to removing whitespace and splitting on punctuation (both \\p{P} and other ascii characters)\n this.pattern = new RegExp(`[^\\\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`, 'gu');\n }\n /**\n * Tokenizes a single text using the BERT pre-tokenization scheme.\n * \n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n return text.trim().match(this.pattern) || [];\n }\n}\n\n/**\n * A pre-tokenizer that splits text into Byte-Pair-Encoding (BPE) subwords.\n * @extends PreTokenizer\n */\nclass ByteLevelPreTokenizer extends PreTokenizer {\n /**\n * Creates a new instance of the `ByteLevelPreTokenizer` class.\n * @param {Object} config The configuration object.\n */\n constructor(config) {\n super();\n this.config = config;\n\n /**\n * @type {boolean} Whether to add a leading space to the first word.\n * This allows to treat the leading word just as any other word.\n */\n this.add_prefix_space = this.config.add_prefix_space;\n\n /**\n * @type {boolean} Whether the post processing step should trim offsets\n * to avoid including whitespaces.\n * @todo Use this in the pretokenization step.\n */\n this.trim_offsets = this.config.trim_offsets;\n\n /**\n * @type {boolean} Whether to use the standard GPT2 regex for whitespace splitting.\n * Set it to False if you want to use your own splitting. Defaults to true.\n */\n this.use_regex = this.config.use_regex ?? true;\n this.pattern = /'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+/gu;\n\n this.byte_encoder = BYTES_TO_UNICODE;\n this.text_encoder = new TextEncoder();\n }\n\n /**\n * Tokenizes a single piece of text using byte-level tokenization.\n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n // Add a leading space if the option is enabled\n if (this.add_prefix_space && !text.startsWith(' ')) {\n text = ' ' + text;\n }\n\n // Split on whitespace and punctuation\n const tokens = this.use_regex ? (text.match(this.pattern) || []) : [text];\n\n // Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)\n return tokens.map(\n token => Array.from(this.text_encoder.encode(token), byte => this.byte_encoder[byte]).join('')\n );\n }\n}\n\n/**\n * @typedef {'removed'|'isolated'|'mergedWithPrevious'|'mergedWithNext'|'contiguous'} SplitDelimiterBehavior\n */\n\n/**\n * Splits text using a given pattern.\n * @extends PreTokenizer\n */\nclass SplitPreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration options for the pre-tokenizer.\n * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.\n * @param {string|undefined} config.pattern.String The string to use for splitting. Only defined if the pattern is a string.\n * @param {string|undefined} config.pattern.Regex The regex to use for splitting. Only defined if the pattern is a regex.\n * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.\n * @param {boolean} config.invert Whether to split (invert=false) or match (invert=true) the pattern.\n */\n constructor(config) {\n super();\n this.config = config;\n // TODO support all behaviours (config.behavior)\n\n this.pattern = createPattern(this.config.pattern, this.config.invert);\n }\n\n /**\n * Tokenizes text by splitting it using the given pattern.\n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n if (this.pattern === null) {\n return [];\n }\n\n if (this.config.invert) {\n return text.match(this.pattern) || [];\n } else {\n return regexSplit(text, this.pattern);\n }\n }\n}\n\n/**\n * Splits text based on punctuation.\n * @extends PreTokenizer\n */\nclass PunctuationPreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration options for the pre-tokenizer.\n * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.\n */\n constructor(config) {\n super();\n this.config = config;\n this.pattern = new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`, 'gu');\n }\n\n /**\n * Tokenizes text by splitting it using the given pattern.\n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n return text.match(this.pattern) || [];\n }\n}\n\n\n/**\n * Splits text based on digits.\n * @extends PreTokenizer\n */\nclass DigitsPreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration options for the pre-tokenizer.\n * @param {boolean} config.individual_digits Whether to split on individual digits.\n */\n constructor(config) {\n super();\n this.config = config;\n\n // Construct a pattern which matches the rust implementation:\n const digit_pattern = `[^\\\\d]+|\\\\d${this.config.individual_digits ? '' : '+'}`;\n this.pattern = new RegExp(digit_pattern, 'gu');\n }\n\n /**\n * Tokenizes text by splitting it using the given pattern.\n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n return text.match(this.pattern) || [];\n }\n}\n\n/**\n * @typedef {Object} PostProcessedOutput\n * @property {string[]} tokens List of token produced by the post-processor.\n * @property {number[]} [token_type_ids] List of token type ids produced by the post-processor.\n */\n\n\n/**\n * @typedef {Object} EncodingSingle\n * @property {number[]} input_ids List of token ids to be fed to a model.\n * @property {number[]} attention_mask List of token type ids to be fed to a model\n * @property {number[]} [token_type_ids] List of indices specifying which tokens should be attended to by the model\n */\n\n\n/**\n * @extends Callable\n */\nclass PostProcessor extends Callable {\n\n /**\n * @param {Object} config The configuration for the post-processor.\n */\n constructor(config) {\n super();\n this.config = config;\n }\n\n /**\n * Factory method to create a PostProcessor object from a configuration object.\n *\n * @param {Object} config Configuration object representing a PostProcessor.\n * @returns {PostProcessor} A PostProcessor object created from the given configuration.\n * @throws {Error} If an unknown PostProcessor type is encountered.\n */\n static fromConfig(config) {\n if (config === null) return null;\n switch (config.type) {\n case 'TemplateProcessing':\n return new TemplateProcessing(config);\n\n case 'ByteLevel':\n return new ByteLevelPostProcessor(config);\n\n case 'RobertaProcessing':\n return new RobertaProcessing(config);\n case 'BertProcessing':\n return new BertProcessing(config);\n\n case 'Sequence':\n return new PostProcessorSequence(config);\n default:\n throw new Error(`Unknown PostProcessor type: ${config.type}`);\n }\n }\n\n /**\n * Method to be implemented in subclass to apply post-processing on the given tokens.\n *\n * @param {Array} tokens The input tokens to be post-processed.\n * @param {...*} args Additional arguments required by the post-processing logic.\n * @returns {PostProcessedOutput} The post-processed tokens.\n * @throws {Error} If the method is not implemented in subclass.\n */\n post_process(tokens, ...args) {\n throw Error(\"post_process should be implemented in subclass.\")\n }\n\n /**\n * Alias for {@link PostProcessor#post_process}.\n * @param {Array} tokens The text or array of texts to post-process.\n * @param {...*} args Additional arguments required by the post-processing logic.\n * @returns {PostProcessedOutput} The post-processed tokens.\n */\n _call(tokens, ...args) {\n return this.post_process(tokens, ...args);\n }\n}\n\n/**\n * A post-processor that adds special tokens to the beginning and end of the input.\n */\nclass BertProcessing extends PostProcessor {\n /**\n * @param {Object} config The configuration for the post-processor.\n * @param {string[]} config.cls The special tokens to add to the beginning of the input.\n * @param {string[]} config.sep The special tokens to add to the end of the input.\n */\n constructor(config) {\n super(config);\n // TODO use all of config: add_prefix_space, trim_offsets\n\n this.cls = config.cls[0];\n this.sep = config.sep[0];\n }\n\n /**\n * Adds the special tokens to the beginning and end of the input.\n * @param {string[]} tokens The input tokens.\n * @param {string[]} [tokens_pair=null] An optional second set of input tokens.\n * @returns {PostProcessedOutput} The post-processed tokens with the special tokens added to the beginning and end.\n */\n post_process(tokens, tokens_pair = null, {\n add_special_tokens = true,\n } = {}) {\n if (add_special_tokens) {\n tokens = mergeArrays([this.cls], tokens, [this.sep]);\n }\n\n let token_type_ids = new Array(tokens.length).fill(0);\n if (tokens_pair !== null) {\n // NOTE: It is intended to add 2 EOS tokens after the first set of tokens\n // https://github.com/huggingface/tokenizers/issues/983\n const middle = (add_special_tokens && this instanceof RobertaProcessing)\n ? [this.sep]\n : [];\n const after = add_special_tokens ? [this.sep] : [];\n\n tokens = mergeArrays(tokens, middle, tokens_pair, after);\n token_type_ids = mergeArrays(token_type_ids, new Array(tokens_pair.length + middle.length + after.length).fill(1));\n }\n return { tokens, token_type_ids };\n }\n}\nclass RobertaProcessing extends BertProcessing { } // NOTE: extends BertProcessing\n\n/**\n * Post processor that replaces special tokens in a template with actual tokens.\n * @extends PostProcessor\n */\nclass TemplateProcessing extends PostProcessor {\n /**\n * Creates a new instance of `TemplateProcessing`.\n * @param {Object} config The configuration options for the post processor.\n * @param {Array} config.single The template for a single sequence of tokens.\n * @param {Array} config.pair The template for a pair of sequences of tokens.\n */\n constructor(config) {\n super(config);\n\n this.single = config.single;\n this.pair = config.pair;\n }\n\n /**\n * Replaces special tokens in the template with actual tokens.\n * @param {string[]} tokens The list of tokens for the first sequence.\n * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).\n * @returns {PostProcessedOutput} An object containing the list of tokens with the special tokens replaced with actual tokens.\n */\n post_process(tokens, tokens_pair = null, {\n add_special_tokens = true,\n } = {}) {\n const type = tokens_pair === null ? this.single : this.pair\n\n let processedTokens = [];\n let types = [];\n for (const item of type) {\n if ('SpecialToken' in item) {\n if (add_special_tokens) {\n processedTokens.push(item.SpecialToken.id);\n types.push(item.SpecialToken.type_id);\n }\n } else if ('Sequence' in item) {\n if (item.Sequence.id === 'A') {\n processedTokens = mergeArrays(processedTokens, tokens);\n types = mergeArrays(types, new Array(tokens.length).fill(item.Sequence.type_id));\n\n } else if (item.Sequence.id === 'B') {\n processedTokens = mergeArrays(processedTokens, tokens_pair);\n types = mergeArrays(types, new Array(tokens_pair.length).fill(item.Sequence.type_id));\n }\n }\n }\n return { tokens: processedTokens, token_type_ids: types };\n }\n}\n\n/**\n * A PostProcessor that returns the given tokens as is.\n * @extends PostProcessor\n */\nclass ByteLevelPostProcessor extends PostProcessor {\n /**\n * Post process the given tokens.\n * @param {string[]} tokens The list of tokens for the first sequence.\n * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).\n * @returns {PostProcessedOutput} An object containing the post-processed tokens.\n */\n post_process(tokens, tokens_pair = null) {\n if (tokens_pair) {\n tokens = mergeArrays(tokens, tokens_pair);\n }\n return { tokens };\n }\n}\n\n\n/**\n * A post-processor that applies multiple post-processors in sequence.\n */\nclass PostProcessorSequence extends PostProcessor {\n\n /**\n * Creates a new instance of PostProcessorSequence.\n * @param {Object} config The configuration object.\n * @param {Object[]} config.processors The list of post-processors to apply.\n */\n constructor(config) {\n super(config);\n\n this.processors = config.processors.map(x => PostProcessor.fromConfig(x));\n }\n\n /**\n * Post process the given tokens.\n * @param {string[]} tokens The list of tokens for the first sequence.\n * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).\n * @returns {PostProcessedOutput} An object containing the post-processed tokens.\n */\n post_process(tokens, tokens_pair = null, options = {}) {\n let token_type_ids;\n for (const processor of this.processors) {\n if (processor instanceof ByteLevelPostProcessor) {\n // Special case where we need to pass the tokens_pair to the post-processor\n const output = processor.post_process(tokens);\n tokens = output.tokens;\n if (tokens_pair) {\n const pair_output = processor.post_process(tokens_pair);\n tokens_pair = pair_output.tokens;\n }\n } else {\n const output = processor.post_process(tokens, tokens_pair, options);\n tokens = output.tokens;\n token_type_ids = output.token_type_ids;\n }\n }\n return { tokens, token_type_ids };\n }\n}\n\n/**\n * The base class for token decoders.\n * @extends Callable\n */\nclass Decoder extends Callable {\n\n /**\n * Creates an instance of `Decoder`.\n *\n * @param {Object} config The configuration object.\n */\n constructor(config) {\n super();\n this.config = config;\n\n /** @type {AddedToken[]} */\n this.added_tokens = [];\n this.end_of_word_suffix = null;\n this.trim_offsets = config.trim_offsets;\n }\n\n /**\n * Creates a decoder instance based on the provided configuration.\n *\n * @param {Object} config The configuration object.\n * @returns {Decoder} A decoder instance.\n * @throws {Error} If an unknown decoder type is provided.\n */\n static fromConfig(config) {\n if (config === null) return null;\n switch (config.type) {\n case 'WordPiece':\n return new WordPieceDecoder(config);\n case 'Metaspace':\n return new MetaspaceDecoder(config);\n case 'ByteLevel':\n return new ByteLevelDecoder(config);\n\n case 'Replace':\n return new ReplaceDecoder(config);\n case 'ByteFallback':\n return new ByteFallback(config);\n case 'Fuse':\n return new FuseDecoder(config);\n case 'Strip':\n return new StripDecoder(config);\n\n case 'Sequence':\n return new DecoderSequence(config);\n\n case 'CTC':\n return new CTCDecoder(config);\n case 'BPEDecoder':\n return new BPEDecoder(config);\n default:\n throw new Error(`Unknown Decoder type: ${config.type}`);\n }\n }\n\n /**\n * Calls the `decode` method.\n *\n * @param {string[]} tokens The list of tokens.\n * @returns {string} The decoded string.\n */\n _call(tokens) {\n return this.decode(tokens);\n }\n\n /**\n * Decodes a list of tokens.\n * @param {string[]} tokens The list of tokens.\n * @returns {string} The decoded string.\n */\n decode(tokens) {\n return this.decode_chain(tokens).join('');\n }\n\n /**\n * Apply the decoder to a list of tokens.\n * \n * @param {string[]} tokens The list of tokens.\n * @returns {string[]} The decoded list of tokens.\n * @throws {Error} If the `decode_chain` method is not implemented in the subclass.\n */\n decode_chain(tokens) {\n throw Error(\"`decode_chain` should be implemented in subclass.\")\n }\n\n}\n\nclass ReplaceDecoder extends Decoder {\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n const pattern = createPattern(this.config.pattern);\n return pattern === null\n ? tokens\n : tokens.map(token => token.replaceAll(pattern, this.config.content))\n }\n}\n\n\nclass ByteFallback extends Decoder {\n constructor(config) {\n super(config);\n\n this.text_decoder = new TextDecoder();\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n\n const new_tokens = [];\n let previous_byte_tokens = [];\n\n for (const token of tokens) {\n let bytes = null;\n if (token.length === 6 && token.startsWith('<0x') && token.endsWith('>')) {\n const byte = parseInt(token.slice(3, 5), 16);\n if (!isNaN(byte)) {\n bytes = byte;\n }\n }\n if (bytes !== null) {\n previous_byte_tokens.push(bytes);\n } else {\n if (previous_byte_tokens.length > 0) {\n const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));\n new_tokens.push(string);\n previous_byte_tokens = [];\n }\n new_tokens.push(token);\n }\n }\n if (previous_byte_tokens.length > 0) {\n const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));\n new_tokens.push(string);\n previous_byte_tokens = [];\n }\n\n return new_tokens;\n }\n}\n\n/**\n * Fuse simply fuses all tokens into one big string.\n * It's usually the last decoding step anyway, but this decoder\n * exists incase some decoders need to happen after that step\n */\nclass FuseDecoder extends Decoder {\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return [tokens.join('')];\n }\n}\n\n\nclass StripDecoder extends Decoder {\n constructor(config) {\n super(config);\n\n this.content = this.config.content;\n this.start = this.config.start;\n this.stop = this.config.stop;\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return tokens.map(token => {\n let start_cut = 0;\n for (let i = 0; i < this.start; ++i) {\n if (token[i] === this.content) {\n start_cut = i + 1;\n continue;\n } else {\n break;\n }\n }\n\n let stop_cut = token.length;\n for (let i = 0; i < this.stop; ++i) {\n const index = token.length - i - 1;\n if (token[index] === this.content) {\n stop_cut = index;\n continue;\n } else {\n break;\n }\n }\n\n return token.slice(start_cut, stop_cut)\n });\n }\n}\n\n/**\n * A decoder that decodes a list of WordPiece tokens into a single string.\n * @extends Decoder\n */\nclass WordPieceDecoder extends Decoder {\n\n /**\n * Creates a new instance of WordPieceDecoder.\n * @param {Object} config The configuration object.\n * @param {string} config.prefix The prefix used for WordPiece encoding.\n * @param {boolean} config.cleanup Whether to cleanup the decoded string.\n */\n constructor(config) {\n super(config);\n this.cleanup = config.cleanup;\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return tokens.map((token, i) => {\n if (i !== 0) {\n if (token.startsWith(this.config.prefix)) {\n // NOTE: .replace() is intended; only replace first occurrence\n token = token.replace(this.config.prefix, '');\n } else {\n token = ' ' + token;\n }\n }\n if (this.cleanup) {\n token = clean_up_tokenization(token)\n }\n\n return token;\n });\n }\n}\n\n/**\n * Byte-level decoder for tokenization output. Inherits from the `Decoder` class.\n * @extends Decoder\n */\nclass ByteLevelDecoder extends Decoder {\n\n /**\n * Create a `ByteLevelDecoder` object.\n * @param {Object} config Configuration object.\n */\n constructor(config) {\n super(config);\n\n this.byte_decoder = UNICODE_TO_BYTES;\n this.text_decoder = new TextDecoder(\"utf-8\", {\n fatal: false,\n ignoreBOM: true,\n });\n\n this.end_of_word_suffix = null;\n }\n\n /**\n * Convert an array of tokens to string by decoding each byte.\n * @param {string[]} tokens Array of tokens to be decoded.\n * @returns {string} The decoded string.\n */\n convert_tokens_to_string(tokens) {\n const text = tokens.join('');\n const byteArray = new Uint8Array([...text].map(c => this.byte_decoder[c]));\n const decoded_text = this.text_decoder.decode(byteArray);\n return decoded_text;\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n // TODO move to base class (like HF)\n // tokens === filtered_tokens\n\n // To avoid mixing byte-level and unicode for byte-level BPT\n // we need to build string separately for added tokens and byte-level tokens\n // cf. https://github.com/huggingface/transformers/issues/1133\n const sub_texts = [];\n let current_sub_text = [];\n for (const token of tokens) {\n // tokens sent here are already filtered, so we don't need to do this\n // if (skip_special_tokens && this.all_special_ids.includes(token)) {\n // continue;\n // }\n\n if (this.added_tokens.find(x => x.content === token) !== undefined) {\n if (current_sub_text.length > 0) {\n sub_texts.push(this.convert_tokens_to_string(current_sub_text));\n current_sub_text = [];\n }\n sub_texts.push(token);\n } else {\n current_sub_text.push(token);\n }\n }\n if (current_sub_text.length > 0) {\n sub_texts.push(this.convert_tokens_to_string(current_sub_text));\n }\n\n // TODO add spaces_between_special_tokens and clean_up_tokenization_spaces options\n\n return sub_texts;\n }\n}\n\n/**\n * The CTC (Connectionist Temporal Classification) decoder.\n * See https://github.com/huggingface/tokenizers/blob/bb38f390a61883fc2f29d659af696f428d1cda6b/tokenizers/src/decoders/ctc.rs\n */\nclass CTCDecoder extends Decoder {\n\n constructor(config) {\n super(config);\n\n this.pad_token = this.config.pad_token;\n this.word_delimiter_token = this.config.word_delimiter_token;\n this.cleanup = this.config.cleanup;\n }\n /**\n * Converts a connectionist-temporal-classification (CTC) output tokens into a single string.\n * @param {string[]} tokens Array of tokens to be decoded.\n * @returns {string} The decoded string.\n */\n convert_tokens_to_string(tokens) {\n if (tokens.length === 0) return '';\n\n // group same tokens into non-repeating tokens in CTC style decoding\n const grouped_tokens = [tokens[0]];\n for (let i = 1; i < tokens.length; ++i) {\n if (tokens[i] !== grouped_tokens.at(-1)) {\n grouped_tokens.push(tokens[i]);\n }\n }\n\n // filter self.pad_token which is used as CTC-blank token\n const filtered_tokens = grouped_tokens.filter(token => token !== this.pad_token);\n\n let text = filtered_tokens.join('');\n if (this.cleanup) {\n // cleanup and replace delimiter token\n text = clean_up_tokenization(text)\n .replaceAll(this.word_delimiter_token, ' ')\n .trim();\n }\n return text;\n }\n\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return [this.convert_tokens_to_string(tokens)];\n }\n}\n\n/**\n * Apply a sequence of decoders.\n * @extends Decoder\n */\nclass DecoderSequence extends Decoder {\n\n /**\n * Creates a new instance of DecoderSequence.\n * @param {Object} config The configuration object.\n * @param {Object[]} config.decoders The list of decoders to apply.\n */\n constructor(config) {\n super(config);\n this.decoders = config.decoders.map(x => Decoder.fromConfig(x));\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n // Use reduce to apply each decoder to the tokens\n return this.decoders.reduce((toks, decoder) => {\n return decoder.decode_chain(toks);\n }, tokens);\n }\n\n}\n\nclass BPEDecoder extends Decoder {\n constructor(config) {\n super(config);\n\n this.suffix = this.config.suffix;\n }\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return tokens.map((token, i) => {\n return token.replaceAll(this.suffix, (i === tokens.length - 1) ? '' : ' ')\n });\n }\n}\n\n// Custom decoder for VITS\nclass VitsDecoder extends Decoder {\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n let decoded = '';\n for (let i = 1; i < tokens.length; i += 2) {\n decoded += tokens[i];\n }\n return [decoded];\n }\n}\n\n\n/**\n * This PreTokenizer replaces spaces with the given replacement character, adds a prefix space if requested,\n * and returns a list of tokens.\n * @extends PreTokenizer\n */\nclass MetaspacePreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration object for the MetaspacePreTokenizer.\n * @param {boolean} config.add_prefix_space Whether to add a prefix space to the first token.\n * @param {string} config.replacement The character to replace spaces with.\n * @param {string} [config.str_rep=config.replacement] An optional string representation of the replacement character.\n * @param {'first'|'never'|'always'} [config.prepend_scheme='always'] The metaspace prepending scheme.\n */\n constructor(config) {\n super();\n\n this.addPrefixSpace = config.add_prefix_space;\n this.replacement = config.replacement;\n this.strRep = config.str_rep || this.replacement;\n this.prepend_scheme = config.prepend_scheme ?? 'always';\n }\n\n /**\n * This method takes a string, replaces spaces with the replacement character,\n * adds a prefix space if requested, and returns a new list of tokens.\n * @param {string} text The text to pre-tokenize.\n * @param {Object} [options] The options for the pre-tokenization.\n * @param {number} [options.section_index] The index of the section to pre-tokenize.\n * @returns {string[]} A new list of pre-tokenized tokens.\n */\n pre_tokenize_text(text, {\n section_index = undefined,\n } = {}) {\n\n let normalized = text.replaceAll(' ', this.strRep);\n\n if (\n // We add a prefix space if:\n // (1) The addPrefixSpace option is enabled and the normalized\n // token does not already start with the replacement character.\n (this.addPrefixSpace && !normalized.startsWith(this.replacement))\n\n // and (2) either:\n // (a) prepend_scheme is 'always'\n // (b) prepend_scheme is 'first' and this is the first section\n && (\n this.prepend_scheme === 'always' ||\n (this.prepend_scheme === 'first' && section_index === 0)\n )\n ) {\n normalized = this.strRep + normalized;\n }\n return [normalized];\n }\n}\n\n/**\n * MetaspaceDecoder class extends the Decoder class and decodes Metaspace tokenization.\n * @extends Decoder\n */\nclass MetaspaceDecoder extends Decoder {\n /**\n * Constructs a new MetaspaceDecoder object.\n * @param {Object} config The configuration object for the MetaspaceDecoder.\n * @param {boolean} config.add_prefix_space Whether to add a prefix space to the decoded string.\n * @param {string} config.replacement The string to replace spaces with.\n */\n constructor(config) {\n super(config);\n\n this.addPrefixSpace = config.add_prefix_space;\n this.replacement = config.replacement;\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n const result = [];\n for (let i = 0; i < tokens.length; ++i) {\n let normalized = tokens[i].replaceAll(this.replacement, ' ');\n if (this.addPrefixSpace && i == 0 && normalized.startsWith(' ')) {\n normalized = normalized.substring(1);\n }\n result.push(normalized);\n }\n return result;\n }\n}\n\n/**\n * A normalizer that applies a precompiled charsmap.\n * This is useful for applying complex normalizations in C++ and exposing them to JavaScript.\n * @extends Normalizer\n * @param {Object} config The configuration object for the Precompiled normalizer.\n * @param {Object} config.precompiled_charsmap The precompiled charsmap object.\n */\nclass Precompiled extends Normalizer {\n /**\n * Create a new instance of Precompiled normalizer.\n * @param {Object} config The configuration object.\n * @param {any} config.precompiled_charsmap Precompiled chars mapping.\n */\n constructor(config) {\n super(config);\n this.charsmap = config.precompiled_charsmap;\n }\n\n /**\n * Normalizes the given text by applying the precompiled charsmap.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n // As stated in the sentencepiece normalization docs (https://github.com/google/sentencepiece/blob/master/doc/normalization.md#use-pre-defined-normalization-rule),\n // there are 5 pre-defined normalization rules:\n // 1. nmt_nfkc: NFKC normalization with some additional normalization around spaces. (default)\n // 2. nfkc: original NFKC normalization.\n // 3. nmt_nfkc_cf: nmt_nfkc + Unicode case folding (mostly lower casing)\n // 4. nfkc_cf: nfkc + Unicode case folding.\n // 5. identity: no normalization\n // \n // For now, we only implement the default (nmt_nfkc).\n // See https://raw.githubusercontent.com/google/sentencepiece/master/data/nmt_nfkc.tsv for the full list of rules.\n // TODO: detect when a different `this.charsmap` is used.\n\n text = text.replace(/[\\u0001-\\u0008\\u000B\\u000E-\\u001F\\u007F\\u008F\\u009F]/gm, ''); // Remove control characters\n text = text.replace(/[\\u0009\\u000A\\u000C\\u000D\\u00A0\\u1680\\u2000-\\u200F\\u2028\\u2029\\u202F\\u205F\\u2581\\u3000\\uFEFF\\uFFFD]/gm, '\\u0020'); // Replace certain characters with a space\n\n if (text.includes('\\uFF5E')) {\n // To match the sentencepiece implementation 100%, we must handle a very strange edge-case.\n // For some reason, the \"Fullwidth Tilde\" character (\\uFF5E) should not be converted to the standard Tilde character (\\u007E).\n // However, NFKC normalization does do this conversion. As a result, we split the string on the Fullwidth Tilde character,\n // perform NFKC normalization on each substring, and then join them back together with the Fullwidth Tilde character.\n const parts = text.split('\\uFF5E');\n text = parts.map(part => part.normalize('NFKC')).join('\\uFF5E');\n } else {\n text = text.normalize('NFKC');\n }\n\n return text;\n }\n}\n\n/**\n * A pre-tokenizer that applies a sequence of pre-tokenizers to the input text.\n * @extends PreTokenizer\n */\nclass PreTokenizerSequence extends PreTokenizer {\n /**\n * Creates an instance of PreTokenizerSequence.\n * @param {Object} config The configuration object for the pre-tokenizer sequence.\n * @param {Object[]} config.pretokenizers An array of pre-tokenizer configurations.\n */\n constructor(config) {\n super();\n this.tokenizers = config.pretokenizers.map(x => PreTokenizer.fromConfig(x));\n }\n\n /**\n * Applies each pre-tokenizer in the sequence to the input text in turn.\n * @param {string} text The text to pre-tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} The pre-tokenized text.\n */\n pre_tokenize_text(text, options) {\n // Use reduce to apply each tokenizer to the text\n return this.tokenizers.reduce((preTokenizedText, tokenizer) => {\n return tokenizer.pre_tokenize(preTokenizedText, options);\n }, [text]);\n }\n}\n\n/**\n * Splits on word boundaries (using the following regular expression: `\\w+|[^\\w\\s]+`).\n */\nclass WhitespacePreTokenizer extends PreTokenizer {\n /**\n * Creates an instance of WhitespacePreTokenizer.\n * @param {Object} config The configuration object for the pre-tokenizer.\n */\n constructor(config) {\n super();\n }\n /**\n * Pre-tokenizes the input text by splitting it on word boundaries.\n * @param {string} text The text to be pre-tokenized.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.\n */\n pre_tokenize_text(text, options) {\n return text.match(/\\w+|[^\\w\\s]+/g) || [];\n }\n}\n\n/**\n * Splits a string of text by whitespace characters into individual tokens.\n * @extends PreTokenizer\n */\nclass WhitespaceSplit extends PreTokenizer {\n /**\n * Creates an instance of WhitespaceSplit.\n * @param {Object} config The configuration object for the pre-tokenizer.\n */\n constructor(config) {\n super();\n }\n /**\n * Pre-tokenizes the input text by splitting it on whitespace characters.\n * @param {string} text The text to be pre-tokenized.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.\n */\n pre_tokenize_text(text, options) {\n return whitespace_split(text);\n }\n}\n\n// NOTE: `ReplacePreTokenizer` is custom (to support `BlenderbotSmallTokenizer`)\nclass ReplacePreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration options for the pre-tokenizer.\n * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.\n * @param {string} config.content What to replace the pattern with.\n */\n constructor(config) {\n super();\n this.config = config;\n this.pattern = createPattern(this.config.pattern);\n this.content = this.config.content;\n }\n\n /**\n * Pre-tokenizes the input text by replacing certain characters.\n * @param {string} text The text to be pre-tokenized.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens produced by replacing certain characters.\n */\n pre_tokenize_text(text, options) {\n if (this.pattern === null) {\n return [text];\n }\n return [text.replaceAll(this.pattern, this.config.content)];\n }\n}\n\nconst SPECIAL_TOKEN_ATTRIBUTES = [\n 'bos_token',\n 'eos_token',\n 'unk_token',\n 'sep_token',\n 'pad_token',\n 'cls_token',\n 'mask_token',\n // additional_special_tokens (TODO)\n]\n\n/**\n * \n * Helper function for padding values of an object, which are each arrays.\n * NOTE: No additional checks are made here for validity of arguments.\n * @param {Record} item The input object.\n * @param {number} length The length to pad to.\n * @param {(key: string) => any} value_fn Determine the value to fill the array, based on its key.\n * @param {string} side Which side to pad the array.\n * @private\n */\nfunction padHelper(item, length, value_fn, side) {\n for (const key of Object.keys(item)) {\n const diff = length - item[key].length;\n const value = value_fn(key);\n\n const padData = new Array(diff).fill(value);\n item[key] = side === 'right'\n ? mergeArrays(item[key], padData)\n : mergeArrays(padData, item[key]);\n }\n}\n\n/**\n * Helper function for truncating values of an object, which are each arrays.\n * NOTE: No additional checks are made here for validity of arguments.\n * @param {Record} item The input object.\n * @param {number} length The length to truncate to.\n * @private\n */\nfunction truncateHelper(item, length) {\n // Setting .length to a lower value truncates the array in-place:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length\n for (const key of Object.keys(item)) {\n item[key].length = length;\n }\n}\n\n\n/**\n * @typedef {Object} Message\n * @property {string} role The role of the message (e.g., \"user\" or \"assistant\" or \"system\").\n * @property {string} content The content of the message.\n */\n\nexport class PreTrainedTokenizer extends Callable {\n return_token_type_ids = false;\n\n padding_side = 'right';\n /**\n * Create a new PreTrainedTokenizer instance.\n * @param {Object} tokenizerJSON The JSON of the tokenizer.\n * @param {Object} tokenizerConfig The config of the tokenizer.\n */\n constructor(tokenizerJSON, tokenizerConfig) {\n super();\n\n this._tokenizer_config = tokenizerConfig;\n\n // Construct parts of the tokenizer from the JSON\n this.normalizer = Normalizer.fromConfig(tokenizerJSON.normalizer);\n this.pre_tokenizer = PreTokenizer.fromConfig(tokenizerJSON.pre_tokenizer);\n this.model = TokenizerModel.fromConfig(tokenizerJSON.model, tokenizerConfig);\n this.post_processor = PostProcessor.fromConfig(tokenizerJSON.post_processor);\n this.decoder = Decoder.fromConfig(tokenizerJSON.decoder);\n\n // Add added_tokens to model\n this.special_tokens = [];\n this.all_special_ids = [];\n\n /** @type {AddedToken[]} */\n this.added_tokens = [];\n for (const addedToken of tokenizerJSON.added_tokens) {\n const token = new AddedToken(addedToken);\n this.added_tokens.push(token);\n\n this.model.tokens_to_ids.set(token.content, token.id);\n this.model.vocab[token.id] = token.content;\n\n if (token.special) {\n this.special_tokens.push(token.content);\n this.all_special_ids.push(token.id);\n }\n }\n\n // Update additional_special_tokens\n this.additional_special_tokens = tokenizerConfig.additional_special_tokens ?? [];\n this.special_tokens.push(...this.additional_special_tokens);\n this.special_tokens = [...new Set(this.special_tokens)]; // Remove duplicates\n\n if (this.decoder) {\n // Slight hack, but it prevents code duplication:\n this.decoder.added_tokens = this.added_tokens;\n\n // Another slight hack to add `end_of_word_suffix` (if present) to the decoder\n // This is needed for cases where BPE model and ByteLevel decoder are used\n // For more information, see https://github.com/huggingface/transformers.js/issues/74\n // TODO: save this to the decoder when exporting?\n this.decoder.end_of_word_suffix = this.model.end_of_word_suffix;\n }\n\n this.added_tokens_regex = this.added_tokens.length > 0 ? new RegExp(\n this.added_tokens.slice()\n // Sort by length (desc) to avoid early partial matches\n .sort((a, b) => b.content.length - a.content.length)\n .map(x => `${x.lstrip ? '\\\\s*' : ''}(${escapeRegExp(x.content)})${x.rstrip ? '\\\\s*' : ''}`)\n .join('|')\n ) : null;\n\n // Set mask token if present (otherwise will be undefined, which is fine)\n this.mask_token = this.getToken('mask_token');\n this.mask_token_id = this.model.tokens_to_ids.get(this.mask_token);\n\n this.pad_token = this.getToken('pad_token', 'eos_token');\n this.pad_token_id = this.model.tokens_to_ids.get(this.pad_token);\n\n this.sep_token = this.getToken('sep_token');\n this.sep_token_id = this.model.tokens_to_ids.get(this.sep_token);\n\n this.unk_token = this.getToken('unk_token');\n this.unk_token_id = this.model.tokens_to_ids.get(this.unk_token);\n\n this.model_max_length = tokenizerConfig.model_max_length;\n\n /** @type {boolean} Whether or not to strip the text when tokenizing (removing excess spaces before and after the string). */\n this.remove_space = tokenizerConfig.remove_space;\n\n this.clean_up_tokenization_spaces = tokenizerConfig.clean_up_tokenization_spaces ?? true;\n this.do_lowercase_and_remove_accent = tokenizerConfig.do_lowercase_and_remove_accent ?? false;\n\n if (tokenizerConfig.padding_side) {\n this.padding_side = tokenizerConfig.padding_side;\n }\n\n this.legacy = false;\n\n this.chat_template = tokenizerConfig.chat_template ?? null;\n if (Array.isArray(this.chat_template)) {\n // Chat templates are stored as lists of dicts with fixed key names,\n // we reconstruct that into a single dict while loading them.\n const chat_template = Object.create(null);\n for (const { name, template } of this.chat_template) {\n if (typeof name !== 'string' || typeof template !== 'string') {\n throw new Error('Chat template must be a list of objects with \"name\" and \"template\" properties');\n }\n chat_template[name] = template;\n }\n this.chat_template = chat_template;\n }\n this._compiled_template_cache = new Map();\n }\n\n /**\n * Returns the value of the first matching key in the tokenizer config object.\n * @param {...string} keys One or more keys to search for in the tokenizer config object.\n * @returns {string|null} The value associated with the first matching key, or null if no match is found.\n * @throws {Error} If an object is found for a matching key and its __type property is not \"AddedToken\".\n * @private\n */\n getToken(...keys) {\n for (const key of keys) {\n const item = this._tokenizer_config[key];\n\n if (!item) continue;\n\n if (typeof item === 'object') {\n if (item.__type === 'AddedToken') {\n return item.content;\n } else {\n throw Error(`Unknown token: ${item}`);\n }\n } else {\n return item;\n }\n }\n return null;\n }\n\n /**\n * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`. \n * \n * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer.\n * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.\n * \n * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`.\n * @returns {Promise} A new instance of the `PreTrainedTokenizer` class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n legacy = null,\n } = {}) {\n\n const info = await loadTokenizer(pretrained_model_name_or_path, {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n legacy,\n })\n\n // @ts-ignore\n return new this(...info);\n }\n\n /**\n * @typedef {number[]|number[][]|Tensor} BatchEncodingItem\n * \n * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function.\n * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model.\n * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model.\n * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model.\n */\n\n /**\n * Encode/tokenize the given text(s).\n * @param {string|string[]} text The text to tokenize.\n * @param {Object} options An optional object containing the following properties:\n * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text.\n * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences.\n * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.\n * @param {boolean} [options.truncation=null] Whether to truncate the input sequences.\n * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length.\n * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays.\n * @param {boolean} [options.return_token_type_ids=null] Whether to return the token type ids.\n * @returns {BatchEncoding} Object to be passed to the model.\n */\n _call(\n // Required positional arguments\n text,\n\n // Optional keyword arguments\n {\n text_pair = null,\n add_special_tokens = true,\n padding = false,\n truncation = null,\n max_length = null,\n return_tensor = true, // Different to HF\n return_token_type_ids = null,\n } = {},\n ) {\n\n const isBatched = Array.isArray(text);\n\n /** @type {EncodingSingle[]} */\n let encodedTokens;\n\n if (isBatched) {\n if (text.length === 0) {\n throw Error('text array must be non-empty')\n }\n\n if (text_pair !== null) {\n if (!Array.isArray(text_pair)) {\n throw Error('text_pair must also be an array')\n\n } else if (text.length !== text_pair.length) {\n throw Error('text and text_pair must have the same length')\n }\n\n encodedTokens = text.map(\n (t, i) => this._encode_plus(t, { text_pair: text_pair[i], add_special_tokens, return_token_type_ids })\n )\n\n } else {\n encodedTokens = text.map(x => this._encode_plus(x, { add_special_tokens, return_token_type_ids }));\n }\n\n } else {\n if (text === null || text === undefined) {\n throw Error('text may not be null or undefined')\n }\n\n if (Array.isArray(text_pair)) {\n throw Error('When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).')\n }\n\n // For single input, we just wrap in an array, and then unwrap later.\n encodedTokens = [this._encode_plus(text, { text_pair, add_special_tokens, return_token_type_ids })];\n }\n // At this point, tokens is batched: [batch_size, tokens]\n // However, array may be jagged. So, we pad to max_length\n\n if (max_length === null) {\n if (padding === 'max_length') {\n max_length = this.model_max_length;\n } else {\n // Calculate max length from sequences\n max_length = max(encodedTokens.map(x => x.input_ids.length))[0];\n }\n } else {\n if (!truncation) {\n console.warn(`Truncation was not explicitly activated but \\`max_length\\` is provided a specific value, please use \\`truncation=true\\` to explicitly truncate examples to max length.`)\n }\n }\n\n // Ensure it is less than model max length\n max_length = Math.min(max_length, this.model_max_length ?? Infinity);\n\n if (padding || truncation) {\n\n // Perform padding and/or truncation\n for (let i = 0; i < encodedTokens.length; ++i) {\n if (encodedTokens[i].input_ids.length === max_length) {\n continue;\n\n } else if (encodedTokens[i].input_ids.length > max_length) {\n // possibly truncate\n if (truncation) {\n truncateHelper(encodedTokens[i], max_length);\n }\n\n } else { // t.length < max_length\n // possibly pad\n if (padding) {\n padHelper(\n encodedTokens[i],\n max_length,\n key => key === 'input_ids' ? this.pad_token_id : 0,\n this.padding_side\n );\n }\n }\n }\n }\n\n const result = {};\n\n if (return_tensor) {\n if (!(padding && truncation)) {\n // Not, guaranteed that all items have same length, so\n // we perform additional check\n\n if (\n encodedTokens.some(x => {\n for (const key of Object.keys(x)) {\n if (x[key].length !== encodedTokens[0][key]?.length) {\n return true;\n }\n }\n return false;\n })\n ) {\n throw Error(\n \"Unable to create tensor, you should probably activate truncation and/or padding \" +\n \"with 'padding=true' and 'truncation=true' to have batched tensors with the same length.\"\n )\n }\n }\n\n // Now we actually convert to tensor\n // NOTE: In the same way as the python library, we return a batched tensor, regardless of\n // whether we have a single input or multiple inputs.\n const dims = [encodedTokens.length, encodedTokens[0].input_ids.length];\n\n for (const key of Object.keys(encodedTokens[0])) {\n result[key] = new Tensor('int64',\n BigInt64Array.from(encodedTokens.flatMap(x => x[key]).map(BigInt)),\n dims\n );\n }\n\n } else {\n for (const key of Object.keys(encodedTokens[0])) {\n result[key] = encodedTokens.map(x => x[key]);\n }\n\n // If not returning a tensor, we match the input type\n if (!isBatched) {\n // Input was not batched, so we unwrap\n for (const key of Object.keys(result)) {\n result[key] = result[key][0];\n }\n }\n }\n\n return /** @type {BatchEncoding} */(result);\n }\n\n /**\n * Encodes a single text using the preprocessor pipeline of the tokenizer.\n *\n * @param {string|null} text The text to encode.\n * @returns {string[]|null} The encoded tokens.\n */\n _encode_text(text) {\n if (text === null) return null;\n\n // Actual function which does encoding, for a single text\n // First, we take care of special tokens. Needed to avoid issues arising from\n // normalization and/or pretokenization (which may not preserve special tokens)\n const sections = this.added_tokens_regex ? text.split(this.added_tokens_regex).filter(x => x) : [text];\n\n const tokens = sections.map((x, section_index) => {\n const addedToken = this.added_tokens.find(t => t.content === x);\n if (addedToken !== undefined) {\n // Ignore added tokens\n return x\n } else {\n if (this.remove_space === true) {\n x = x.trim().split(/\\s+/).join(' ');\n }\n if (this.do_lowercase_and_remove_accent) {\n x = lowercase_and_remove_accent(x);\n }\n\n if (this.normalizer !== null) {\n x = this.normalizer(x);\n }\n\n // If, after normalization, this section is empty (e.g., trimming whitespace),\n // we return an empty array\n if (x.length === 0) {\n return [];\n }\n\n const sectionTokens = (this.pre_tokenizer !== null) ? this.pre_tokenizer(x, {\n section_index,\n }) : [x];\n\n const tokens = this.model(sectionTokens);\n\n return tokens;\n }\n }).flat();\n\n return tokens;\n }\n\n /**\n * Encodes a single text or a pair of texts using the model's tokenizer.\n *\n * @param {string} text The text to encode.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.text_pair=null] The optional second text to encode.\n * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.\n * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids.\n * @returns {EncodingSingle} An object containing the encoded text.\n * @private\n */\n _encode_plus(text, {\n text_pair = null,\n add_special_tokens = true,\n return_token_type_ids = null,\n } = {}) {\n\n const { tokens, token_type_ids } = this._tokenize_helper(text, { pair: text_pair, add_special_tokens });\n\n const input_ids = this.model.convert_tokens_to_ids(tokens);\n\n const result = {\n input_ids,\n attention_mask: new Array(input_ids.length).fill(1),\n }\n if ((return_token_type_ids ?? this.return_token_type_ids) && token_type_ids) {\n result.token_type_ids = token_type_ids;\n }\n return result;\n }\n\n /**\n * Internal helper function to tokenize a text, and optionally a pair of texts.\n * @param {string} text The text to tokenize.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.pair=null] The optional second text to tokenize.\n * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model.\n * @returns {{tokens: string[], token_type_ids?: number[]}} An object containing the tokens and optionally the token type IDs.\n */\n _tokenize_helper(text, {\n pair = null,\n add_special_tokens = false,\n } = {}) {\n const tokens = this._encode_text(text);\n const tokens2 = this._encode_text(pair);\n\n return this.post_processor\n ? this.post_processor(tokens, tokens2, { add_special_tokens })\n : { tokens: mergeArrays(tokens ?? [], tokens2 ?? []) };\n }\n\n /**\n * Converts a string into a sequence of tokens.\n * @param {string} text The sequence to be encoded.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.pair] A second sequence to be encoded with the first.\n * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model.\n * @returns {string[]} The list of tokens.\n */\n tokenize(text, {\n pair = null,\n add_special_tokens = false,\n } = {}) {\n return this._tokenize_helper(text, { pair, add_special_tokens }).tokens;\n }\n\n /**\n * Encodes a single text or a pair of texts using the model's tokenizer.\n *\n * @param {string} text The text to encode.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.text_pair=null] The optional second text to encode.\n * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.\n * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids.\n * @returns {number[]} An array of token IDs representing the encoded text(s).\n */\n encode(text, {\n text_pair = null,\n add_special_tokens = true,\n return_token_type_ids = null,\n } = {}) {\n return this._encode_plus(text, {\n text_pair,\n add_special_tokens,\n return_token_type_ids,\n }).input_ids;\n }\n\n /**\n * Decode a batch of tokenized sequences.\n * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences.\n * @param {Object} decode_args (Optional) Object with decoding arguments.\n * @returns {string[]} List of decoded sequences.\n */\n batch_decode(batch, decode_args = {}) {\n if (batch instanceof Tensor) {\n batch = batch.tolist();\n }\n return batch.map(x => this.decode(x, decode_args));\n }\n\n /**\n * Decodes a sequence of token IDs back to a string.\n *\n * @param {number[]|bigint[]|Tensor} token_ids List/Tensor of token IDs to decode.\n * @param {Object} [decode_args={}]\n * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string.\n * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuations and abbreviated forms are removed.\n *\n * @returns {string} The decoded string.\n * @throws {Error} If `token_ids` is not a non-empty array of integers.\n */\n decode(\n token_ids,\n decode_args = {},\n ) {\n if (token_ids instanceof Tensor) {\n token_ids = prepareTensorForDecode(token_ids);\n }\n\n if (!Array.isArray(token_ids) || token_ids.length === 0 || !isIntegralNumber(token_ids[0])) {\n throw Error(\"token_ids must be a non-empty array of integers.\");\n }\n\n return this.decode_single(token_ids, decode_args)\n }\n\n /**\n * Decode a single list of token ids to a string.\n * @param {number[]|bigint[]} token_ids List of token ids to decode\n * @param {Object} decode_args Optional arguments for decoding\n * @param {boolean} [decode_args.skip_special_tokens=false] Whether to skip special tokens during decoding\n * @param {boolean} [decode_args.clean_up_tokenization_spaces=null] Whether to clean up tokenization spaces during decoding.\n * If null, the value is set to `this.decoder.cleanup` if it exists, falling back to `this.clean_up_tokenization_spaces` if it exists, falling back to `true`.\n * @returns {string} The decoded string\n */\n decode_single(\n token_ids,\n {\n skip_special_tokens = false,\n clean_up_tokenization_spaces = null,\n }\n ) {\n let tokens = this.model.convert_ids_to_tokens(token_ids);\n if (skip_special_tokens) {\n tokens = tokens.filter(x => !this.special_tokens.includes(x));\n }\n\n // If `this.decoder` is null, we just join tokens with a space:\n // https://github.com/huggingface/tokenizers/blob/8edec536a737cb04494b454805be16c020abb14f/tokenizers/src/tokenizer/mod.rs#L835\n /** @type {string} */\n let decoded = this.decoder ? this.decoder(tokens) : tokens.join(' ');\n\n // Slight hack, but prevents having to pass `skip_special_tokens` to\n // each call to `decode`, which would lead to code duplication.\n if (this.decoder && this.decoder.end_of_word_suffix) {\n decoded = decoded.replaceAll(this.decoder.end_of_word_suffix, ' ');\n if (skip_special_tokens) {\n decoded = decoded.trim();\n }\n }\n\n if (clean_up_tokenization_spaces ?? this.clean_up_tokenization_spaces) {\n decoded = clean_up_tokenization(decoded);\n }\n\n return decoded;\n }\n\n /**\n * Retrieve the chat template string used for tokenizing chat messages. This template is used\n * internally by the `apply_chat_template` method and can also be used externally to retrieve the model's chat\n * template for better generation tracking.\n * \n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.chat_template=null]\n * A Jinja template or the name of a template to use for this conversion.\n * It is usually not necessary to pass anything to this argument,\n * as the model's template will be used by default.\n * @param {Object[]} [options.tools=null]\n * A list of tools (callable functions) that will be accessible to the model. If the template does not\n * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema,\n * giving the name, description and argument types for the tool. See our\n * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use)\n * for more information.\n * @returns {string} The chat template string.\n */\n get_chat_template({\n chat_template = null,\n tools = null,\n } = {}) {\n\n // First, handle the cases when the model has a dict of multiple templates\n if (this.chat_template && typeof this.chat_template === 'object') {\n const template_dict = this.chat_template;\n\n if (chat_template !== null && Object.hasOwn(template_dict, chat_template)) {\n // The user can pass the name of a template to the chat template argument instead of an entire template\n chat_template = template_dict[chat_template];\n } else if (chat_template === null) {\n if (tools !== null && 'tool_use' in template_dict) {\n chat_template = template_dict['tool_use'];\n } else if ('default' in template_dict) {\n chat_template = template_dict['default'];\n } else {\n throw Error(\n `This model has multiple chat templates with no default specified! Please either pass a chat ` +\n `template or the name of the template you wish to use to the 'chat_template' argument. Available ` +\n `template names are ${Object.keys(template_dict).sort()}.`\n )\n }\n }\n } else if (chat_template === null) {\n // These are the cases when the model has a single template\n // priority: `chat_template` argument > `tokenizer.chat_template`\n if (this.chat_template) {\n chat_template = this.chat_template;\n } else {\n throw Error(\n \"Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template \" +\n \"argument was passed! For information about writing templates and setting the \" +\n \"tokenizer.chat_template attribute, please see the documentation at \" +\n \"https://huggingface.co/docs/transformers/main/en/chat_templating\"\n )\n }\n }\n return chat_template;\n }\n\n /**\n * Converts a list of message objects with `\"role\"` and `\"content\"` keys to a list of token\n * ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to\n * determine the format and control tokens to use when converting.\n * \n * See [here](https://huggingface.co/docs/transformers/chat_templating) for more information.\n * \n * **Example:** Applying a chat template to a conversation.\n * \n * ```javascript\n * import { AutoTokenizer } from \"@huggingface/transformers\";\n * \n * const tokenizer = await AutoTokenizer.from_pretrained(\"Xenova/mistral-tokenizer-v1\");\n * \n * const chat = [\n * { \"role\": \"user\", \"content\": \"Hello, how are you?\" },\n * { \"role\": \"assistant\", \"content\": \"I'm doing great. How can I help you today?\" },\n * { \"role\": \"user\", \"content\": \"I'd like to show off how chat templating works!\" },\n * ]\n * \n * const text = tokenizer.apply_chat_template(chat, { tokenize: false });\n * // \"[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today? [INST] I'd like to show off how chat templating works! [/INST]\"\n * \n * const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false });\n * // [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793]\n * ```\n * \n * @param {Message[]} conversation A list of message objects with `\"role\"` and `\"content\"` keys,\n * representing the chat history so far.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.chat_template=null] A Jinja template to use for this conversion. If\n * this is not passed, the model's chat template will be used instead.\n * @param {Object[]} [options.tools=null]\n * A list of tools (callable functions) that will be accessible to the model. If the template does not\n * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema,\n * giving the name, description and argument types for the tool. See our\n * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use)\n * for more information.\n * @param {Record[]} [options.documents=null]\n * A list of dicts representing documents that will be accessible to the model if it is performing RAG\n * (retrieval-augmented generation). If the template does not support RAG, this argument will have no\n * effect. We recommend that each document should be a dict containing \"title\" and \"text\" keys. Please\n * see the RAG section of the [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#arguments-for-RAG)\n * for examples of passing documents with chat templates.\n * @param {boolean} [options.add_generation_prompt=false] Whether to end the prompt with the token(s) that indicate\n * the start of an assistant message. This is useful when you want to generate a response from the model.\n * Note that this argument will be passed to the chat template, and so it must be supported in the\n * template for this argument to have any effect.\n * @param {boolean} [options.tokenize=true] Whether to tokenize the output. If false, the output will be a string.\n * @param {boolean} [options.padding=false] Whether to pad sequences to the maximum length. Has no effect if tokenize is false.\n * @param {boolean} [options.truncation=false] Whether to truncate sequences to the maximum length. Has no effect if tokenize is false.\n * @param {number} [options.max_length=null] Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is false.\n * If not specified, the tokenizer's `max_length` attribute will be used as a default.\n * @param {boolean} [options.return_tensor=true] Whether to return the output as a Tensor or an Array. Has no effect if tokenize is false.\n * @param {boolean} [options.return_dict=true] Whether to return a dictionary with named outputs. Has no effect if tokenize is false.\n * @param {Object} [options.tokenizer_kwargs={}] Additional options to pass to the tokenizer.\n * @returns {string | Tensor | number[]| number[][]|BatchEncoding} The tokenized output.\n */\n apply_chat_template(conversation, {\n tools = null,\n documents = null,\n chat_template = null,\n add_generation_prompt = false,\n tokenize = true,\n padding = false,\n truncation = false,\n max_length = null,\n return_tensor = true,\n return_dict = false,\n tokenizer_kwargs = {},\n ...kwargs\n } = {}) {\n\n chat_template = this.get_chat_template({ chat_template, tools });\n\n if (typeof chat_template !== 'string') {\n throw Error(`chat_template must be a string, but got ${typeof chat_template}`);\n }\n\n // Compilation function uses a cache to avoid recompiling the same template\n let compiledTemplate = this._compiled_template_cache.get(chat_template);\n if (compiledTemplate === undefined) {\n compiledTemplate = new Template(chat_template);\n this._compiled_template_cache.set(chat_template, compiledTemplate);\n }\n\n const special_tokens_map = Object.create(null);\n for (const key of SPECIAL_TOKEN_ATTRIBUTES) {\n const value = this.getToken(key);\n if (value) {\n special_tokens_map[key] = value;\n }\n }\n\n const rendered = compiledTemplate.render({\n messages: conversation,\n add_generation_prompt,\n tools,\n documents,\n ...special_tokens_map,\n ...kwargs,\n });\n\n if (tokenize) {\n const out = this._call(rendered, {\n add_special_tokens: false,\n padding,\n truncation,\n max_length,\n return_tensor,\n ...tokenizer_kwargs,\n });\n return return_dict ? out : out.input_ids;\n }\n\n return rendered;\n }\n}\n\n/**\n * BertTokenizer is a class used to tokenize text for BERT models.\n * @extends PreTrainedTokenizer\n */\nexport class BertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\n/**\n * Albert tokenizer\n * @extends PreTrainedTokenizer\n */\nexport class AlbertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class MobileBertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class SqueezeBertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class DebertaTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class DebertaV2Tokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class HerbertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class ConvBertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class RoFormerTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class DistilBertTokenizer extends PreTrainedTokenizer { }\nexport class CamembertTokenizer extends PreTrainedTokenizer { }\nexport class XLMTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\\'s \"fast\" tokenizers library. Therefore, you may experience slightly inaccurate results.')\n }\n}\nexport class ElectraTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\n\nexport class T5Tokenizer extends PreTrainedTokenizer { }\nexport class GPT2Tokenizer extends PreTrainedTokenizer { }\nexport class BartTokenizer extends PreTrainedTokenizer { }\nexport class MBartTokenizer extends PreTrainedTokenizer {\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.languageRegex = /^[a-z]{2}_[A-Z]{2}$/;\n this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x));\n this.lang_to_token = x => x; // Identity function\n }\n\n /**\n * Helper function to build translation inputs for an `MBartTokenizer`.\n * @param {string|string[]} raw_inputs The text to tokenize.\n * @param {Object} tokenizer_options Options to be sent to the tokenizer\n * @param {Object} generate_kwargs Generation options.\n * @returns {Object} Object to be passed to the model.\n */\n _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {\n return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);\n }\n}\nexport class MBart50Tokenizer extends MBartTokenizer { } // NOTE: extends MBartTokenizer\n\nexport class RobertaTokenizer extends PreTrainedTokenizer { }\n\nexport class BloomTokenizer extends PreTrainedTokenizer { }\n\nconst SPIECE_UNDERLINE = \"▁\";\n\nexport class LlamaTokenizer extends PreTrainedTokenizer {\n\n padding_side = 'left';\n\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.legacy = tokenizerConfig.legacy ?? true;\n if (!this.legacy) {\n // See https://github.com/huggingface/transformers/pull/24565 for more information\n this.normalizer = null;\n this.pre_tokenizer = new MetaspacePreTokenizer({\n replacement: SPIECE_UNDERLINE,\n add_prefix_space: true,\n prepend_scheme: \"first\",\n });\n }\n }\n\n /**\n * Helper function to handle legacy encoding of SPM tokenizers.\n * Adapted from https://github.com/huggingface/transformers/blob/e6dcf8abd6f65bb4b6dfc1831b20d9ba49ce00e2/src/transformers/models/t5/tokenization_t5.py#L374-L387\n * @param {string} text The text to encode.\n * @returns {string[]} The encoded tokens.\n */\n _encode_text(text) {\n if (text === null) return null;\n\n if (this.legacy || text.length === 0) {\n return super._encode_text(text);\n }\n\n let tokens = super._encode_text(SPIECE_UNDERLINE + text.replaceAll(SPIECE_UNDERLINE, \" \"));\n if (tokens.length > 1 && tokens[0] === SPIECE_UNDERLINE && this.special_tokens.includes(tokens[1])) {\n tokens = tokens.slice(1);\n }\n return tokens;\n }\n}\nexport class CodeLlamaTokenizer extends PreTrainedTokenizer { }\n\nexport class XLMRobertaTokenizer extends PreTrainedTokenizer { }\nexport class MPNetTokenizer extends PreTrainedTokenizer { }\n\nexport class FalconTokenizer extends PreTrainedTokenizer { }\n\nexport class GPTNeoXTokenizer extends PreTrainedTokenizer { }\n\nexport class EsmTokenizer extends PreTrainedTokenizer { }\n\nexport class Qwen2Tokenizer extends PreTrainedTokenizer { }\n\nexport class GemmaTokenizer extends PreTrainedTokenizer { }\n\nexport class Grok1Tokenizer extends PreTrainedTokenizer { }\n\n/**\n * Helper function to build translation inputs for an `NllbTokenizer` or `M2M100Tokenizer`.\n * @param {PreTrainedTokenizer} self The tokenizer instance.\n * @param {string|string[]} raw_inputs The text to tokenize.\n * @param {Object} tokenizer_options Options to be sent to the tokenizer\n * @param {Object} generate_kwargs Generation options.\n * @returns {Object} Object to be passed to the model.\n * @private\n */\nfunction _build_translation_inputs(self, raw_inputs, tokenizer_options, generate_kwargs) {\n if (!('language_codes' in self) || !Array.isArray(self.language_codes)) {\n throw new Error('Tokenizer must have `language_codes` attribute set and it should be an array of language ids.')\n }\n if (!('languageRegex' in self) || !(self.languageRegex instanceof RegExp)) {\n throw new Error('Tokenizer must have `languageRegex` attribute set and it should be a regular expression.')\n }\n if (!('lang_to_token' in self) || typeof self.lang_to_token !== 'function') {\n throw new Error('Tokenizer must have `lang_to_token` attribute set and it should be a function.')\n }\n const src_lang_token = generate_kwargs.src_lang;\n const tgt_lang_token = generate_kwargs.tgt_lang;\n\n // Check that the target language is valid:\n if (!self.language_codes.includes(tgt_lang_token)) {\n throw new Error(`Target language code \"${tgt_lang_token}\" is not valid. Must be one of: {${self.language_codes.join(', ')}}`);\n }\n\n // Allow `src_lang` to be optional. If not set, we'll use the tokenizer's default.\n if (src_lang_token !== undefined) {\n // Check that the source language is valid:\n if (!self.language_codes.includes(src_lang_token)) {\n throw new Error(`Source language code \"${src_lang_token}\" is not valid. Must be one of: {${self.language_codes.join(', ')}}`);\n }\n\n // In the same way as the Python library, we override the post-processor\n // to force the source language to be first:\n for (const item of self.post_processor.config.single) {\n if ('SpecialToken' in item && self.languageRegex.test(item.SpecialToken.id)) {\n item.SpecialToken.id = self.lang_to_token(src_lang_token);\n break;\n }\n }\n // TODO: Do the same for pair?\n }\n\n // Override the `forced_bos_token_id` to force the correct language\n generate_kwargs.forced_bos_token_id = self.model.convert_tokens_to_ids([self.lang_to_token(tgt_lang_token)])[0];\n\n return self._call(raw_inputs, tokenizer_options);\n}\n\n/**\n * The NllbTokenizer class is used to tokenize text for NLLB (\"No Language Left Behind\") models.\n * \n * No Language Left Behind (NLLB) is a first-of-its-kind, AI breakthrough project\n * that open-sources models capable of delivering high-quality translations directly\n * between any pair of 200+ languages — including low-resource languages like Asturian,\n * Luganda, Urdu and more. It aims to help people communicate with anyone, anywhere,\n * regardless of their language preferences. For more information, check out their\n * [paper](https://arxiv.org/abs/2207.04672).\n * \n * For a list of supported languages (along with their language codes),\n * @see {@link https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200}\n */\nexport class NllbTokenizer extends PreTrainedTokenizer {\n\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.languageRegex = /^[a-z]{3}_[A-Z][a-z]{3}$/;\n this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x));\n this.lang_to_token = x => x; // Identity function\n }\n\n /**\n * Helper function to build translation inputs for an `NllbTokenizer`.\n * @param {string|string[]} raw_inputs The text to tokenize.\n * @param {Object} tokenizer_options Options to be sent to the tokenizer\n * @param {Object} generate_kwargs Generation options.\n * @returns {Object} Object to be passed to the model.\n */\n _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {\n return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);\n }\n}\n\n/**\n * The M2M100Tokenizer class is used to tokenize text for M2M100 (\"Many-to-Many\") models.\n * \n * M2M100 is a multilingual encoder-decoder (seq-to-seq) model trained for Many-to-Many\n * multilingual translation. It was introduced in this [paper](https://arxiv.org/abs/2010.11125)\n * and first released in [this](https://github.com/pytorch/fairseq/tree/master/examples/m2m_100) repository.\n * \n * For a list of supported languages (along with their language codes),\n * @see {@link https://huggingface.co/facebook/m2m100_418M#languages-covered}\n */\nexport class M2M100Tokenizer extends PreTrainedTokenizer {\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.languageRegex = /^__[a-z]{2,3}__$/;\n this.language_codes = this.special_tokens\n .filter(x => this.languageRegex.test(x))\n .map(x => x.slice(2, -2));\n this.lang_to_token = x => `__${x}__`;\n }\n\n /**\n * Helper function to build translation inputs for an `M2M100Tokenizer`.\n * @param {string|string[]} raw_inputs The text to tokenize.\n * @param {Object} tokenizer_options Options to be sent to the tokenizer\n * @param {Object} generate_kwargs Generation options.\n * @returns {Object} Object to be passed to the model.\n */\n _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {\n return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);\n }\n}\n\n/**\n * WhisperTokenizer tokenizer\n * @extends PreTrainedTokenizer\n */\nexport class WhisperTokenizer extends PreTrainedTokenizer {\n\n get timestamp_begin() {\n return this.model.convert_tokens_to_ids([\"<|notimestamps|>\"])[0] + 1;\n }\n\n /**\n * Decodes automatic speech recognition (ASR) sequences.\n * @param {Array<{tokens: bigint[], token_timestamps?: number[], stride: number[]}>} sequences The sequences to decode.\n * @param {Object} options The options to use for decoding.\n * @returns {Array, text: string}>}>} The decoded sequences.\n */\n _decode_asr(sequences, {\n return_timestamps = false,\n return_language = false,\n time_precision = null,\n force_full_sequences = true\n } = {}) {\n // Set force_full_sequences=false if you want streaming\n // TODO add support for `return_language`\n\n // Internal method meant to only be used by asr pipeline.\n // Handles all the little quirks specific to whisper to handle\n // the various options not allowed in other seq2seq models\n\n // =========== Overview ============\n // - iterate over all outputs\n // - all tokens within output\n // - Each token can be\n // - language token\n // - special token\n // - timestamp token\n // - text token\n // - We accumulate the text tokens.\n // - We split on end timestamps\n // - Lots of complexity comes from stride and timestamps\n\n if (time_precision === null) {\n throw Error(\"Must specify time_precision\")\n }\n let last_language = null;\n\n const returnWordTimestamps = return_timestamps === \"word\";\n\n function new_chunk() {\n return { \"language\": last_language, \"timestamp\": [null, null], \"text\": \"\" };\n }\n\n // Welcome to the state machine!\n const chunks = [];\n let chunk = new_chunk();\n let time_offset = 0.0;\n const timestamp_begin = this.timestamp_begin;\n\n let previous_tokens = [];\n let previous_token_timestamps = [];\n\n let skip = false;\n let right_stride_start = null;\n\n\n const all_special_ids = new Set(this.all_special_ids);\n\n for (const output of sequences) {\n // NOTE: python version has batches, so it uses [0]\n const token_ids = output.tokens;\n const token_timestamps = returnWordTimestamps ? output.token_timestamps : null;\n\n // These keep track of timestamps within strides, which need\n // to be skipped and resolve all tokens in a single chunk.\n let last_timestamp = null;\n let first_timestamp = timestamp_begin;\n\n if (\"stride\" in output) {\n const [chunk_len, stride_left, stride_right] = output.stride;\n\n // Offset the timings to account for the other `model_outputs`.\n time_offset -= stride_left;\n right_stride_start = chunk_len - stride_right;\n\n // Keeping track of timestamps within strides\n // We're going to NOT split on those, and delay until we're\n // out of BOTH stride. Otherwise lots of issues occur and\n // corner cases\n if (stride_left) {\n first_timestamp = stride_left / time_precision + timestamp_begin;\n }\n\n if (stride_right) {\n for (let i = token_ids.length - 1; i >= 0; --i) {\n const token = Number(token_ids[i]);\n if (token >= timestamp_begin) {\n // There can be several token in the right stride\n // But the last one is ALWAYS going to be skipped\n if (last_timestamp !== null && (token - timestamp_begin) * time_precision < right_stride_start) {\n break;\n }\n last_timestamp = token;\n }\n }\n }\n }\n\n let current_tokens = [];\n let current_token_timestamps = [];\n\n // - all tokens within output\n for (let i = 0; i < token_ids.length; ++i) {\n const token = Number(token_ids[i]);\n // 4 possible states for each token\n // - 1/ Language code\n // - 2/ all other special tokens (which we ignore)\n // - 3/ Timestamp\n // - 4/ Regular text\n\n if (all_special_ids.has(token)) {\n const text = this.decode([token]);\n const language = WHISPER_LANGUAGE_MAPPING.get(text.slice(2, -2));\n\n if (language !== undefined) {\n // 1/ Indeed some language\n // TODO Handle when language is different from the previous\n // one, and we cannot use timestamped tokens to create chunks\n if (last_language !== null && language !== last_language && !return_timestamps) {\n previous_tokens.push(current_tokens);\n const resolved_tokens = this.findLongestCommonSequence(previous_tokens)[0];\n const resolved_text = this.decode(resolved_tokens);\n chunk.text = resolved_text;\n chunks.push(chunk);\n\n // Flush all our temporary context\n previous_tokens = [];\n current_tokens = [];\n chunk = new_chunk();\n }\n\n last_language = chunk.language = language;\n } else {\n // 2/ This is a regular special token, ignoring it\n }\n } else if (token >= timestamp_begin) {\n // 3/ Timestamp token\n const time = (token - timestamp_begin) * time_precision + time_offset;\n const rounded_time = round(time, 2);\n\n if (last_timestamp !== null && token >= last_timestamp) {\n // Whisper outputted a timestamp token, but it falls within\n // our stride, so we're going to skip it for the time being\n // and resolve this later\n // Skip is necessary because timestamp tokens always come\n // by pair, so we need to skip the next one too (which would mark the start of another chunk).\n skip = true;\n } else if (skip || (previous_tokens.length > 0 && token < first_timestamp)) {\n skip = false;\n } else if (chunk.timestamp[0] === null) {\n chunk.timestamp[0] = rounded_time;\n } else {\n // This is the end of the timestamp chunk\n if (rounded_time === chunk.timestamp[0]) {\n // This is a bug in timestamp token output\n // where we're taking the duplicate token\n // as a stop where it should be a start.\n // This is an issue in the underlying model output\n // Let's just skip it so it becomes de-factor a start agin\n } else {\n chunk.timestamp[1] = rounded_time;\n\n // Handling merges\n previous_tokens.push(current_tokens)\n\n if (returnWordTimestamps) {\n previous_token_timestamps.push(current_token_timestamps);\n }\n const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(\n previous_tokens, previous_token_timestamps\n )\n\n const resolved_text = this.decode(resolved_tokens)\n chunk.text = resolved_text\n\n if (returnWordTimestamps) {\n chunk.words = this.collateWordTimestamps(\n resolved_tokens, resolved_token_timestamps, last_language,\n )\n }\n\n chunks.push(chunk)\n\n // Flush all our temporary context\n previous_tokens = []\n current_tokens = []\n previous_token_timestamps = []\n current_token_timestamps = []\n chunk = new_chunk()\n }\n }\n\n } else {\n // 4/ Regular token\n // We just append to the list of all tokens so we can handle\n // merges later and decode into text.\n current_tokens.push(token)\n\n if (returnWordTimestamps) {\n let start_time = round(token_timestamps[i] + time_offset, 2);\n\n let end_time;\n if (i + 1 < token_timestamps.length) {\n end_time = round(token_timestamps[i + 1] + time_offset, 2);\n\n // Do not allow punctuation-only tokens to have a duration.\n // This prevents long pauses from messing up the timestamps.\n const decoded_text = this.decode([token]);\n if (PUNCTUATION_ONLY_REGEX.test(decoded_text)) {\n // Add `time_precision` to avoid overlapping timestamps\n end_time = round(Math.min(start_time + time_precision, end_time), 2);\n }\n } else {\n // should never happen\n end_time = null;\n }\n current_token_timestamps.push([start_time, end_time]);\n }\n\n }\n }\n\n if ('stride' in output) {\n const [chunk_len, stride_left, stride_right] = output.stride;\n time_offset += chunk_len - stride_right\n }\n\n // Leftover tokens\n if (current_tokens.length > 0) {\n previous_tokens.push(current_tokens)\n if (returnWordTimestamps) {\n previous_token_timestamps.push(current_token_timestamps);\n }\n } else if (previous_tokens.every(p => p.length === 0)) {\n // Flushing previous tokens (END)\"\n chunk = new_chunk()\n previous_tokens = []\n current_tokens = []\n previous_token_timestamps = [];\n current_token_timestamps = [];\n }\n\n }\n\n if (previous_tokens.length > 0) {\n if (force_full_sequences && return_timestamps) {\n // Last token should always be timestamps, so there shouldn't be\n // leftover\n throw new Error(\n \"Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. \" +\n \"Also make sure WhisperTimeStampLogitsProcessor was used during generation.\"\n );\n }\n\n // Happens when we don't use timestamps\n const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(previous_tokens, previous_token_timestamps);\n\n // Flushing previous tokens (FINAL)\n const resolved_text = this.decode(resolved_tokens);\n chunk.text = resolved_text;\n if (returnWordTimestamps) {\n chunk.words = this.collateWordTimestamps(\n resolved_tokens, resolved_token_timestamps, last_language,\n )\n }\n chunks.push(chunk);\n }\n\n let optional = Object.create(null);\n\n // Preparing and cleaning up the pipeline output\n const full_text = chunks.map(chunk => chunk.text).join('');\n if (return_timestamps || return_language) {\n for (let i = 0; i < chunks.length; ++i) {\n const chunk = chunks[i];\n if (!return_timestamps) {\n delete chunk[\"timestamp\"];\n }\n\n if (!return_language) {\n delete chunk[\"language\"];\n }\n }\n if (returnWordTimestamps) {\n const new_chunks = [];\n for (const chunk of chunks) {\n for (const word of chunk.words) {\n new_chunks.push(word);\n }\n }\n optional = { \"chunks\": new_chunks };\n } else {\n optional = { \"chunks\": chunks };\n }\n }\n return [full_text, optional];\n\n }\n\n /**\n * Finds the longest common sequence among the provided sequences.\n * @param {number[][]} sequences An array of sequences of token ids to compare.\n * @returns {number[][]} The longest common sequence found.\n * @throws {Error} If there is a bug within the function.\n * @private\n */\n findLongestCommonSequence(sequences, token_timestamp_sequences = null) {\n // It would be much harder to do O(n) because of fault tolerance.\n // We actually have a really good property which is that the total sequence\n // MUST be those subsequences in order.\n // If token_timestamp_sequences is provided, will split those sequences in\n // exactly the same way.\n let leftSequence = sequences[0];\n let leftLength = leftSequence.length;\n let totalSequence = [];\n\n const use_token_timestamp_sequences = Array.isArray(token_timestamp_sequences) && token_timestamp_sequences.length > 0;\n let total_token_timestamp_sequence = use_token_timestamp_sequences ? [] : null;\n let left_token_timestamp_sequence = use_token_timestamp_sequences ? token_timestamp_sequences[0] : null;\n for (let i = 1; i < sequences.length; ++i) {\n const rightSequence = sequences[i];\n let max = 0.0;\n let maxIndices = [leftLength, leftLength, 0, 0];\n // Here we're sliding matches\n // [a, b, c, d]\n // [c, d, f]\n // = [c] == [d]\n\n // [a, b, c, d]\n // [c, d, f]\n // = [c, d] == [c, d]\n\n\n // [a, b, c, d]\n // [c, d, f]\n\n // = [b, c, d] == [c, d, f]\n\n // [a, b, c, d]\n // [c, d, f]\n\n // [a, b, c] == [c, d, f]\n\n // [a, b, c, d]\n // [d, f]\n\n // [a, b] == [d, f]\n\n // [a, b, c, d]\n // [f]\n\n // [a] == [f]\n\n const rightLength = rightSequence.length;\n for (let j = 1; j < leftLength + rightLength; ++j) {\n // Slightly convoluted because we don't want out of bound indices\n // This will be necessary for a small conflict resolution optimization\n // later\n const leftStart = Math.max(0, leftLength - j);\n const leftStop = Math.min(leftLength, leftLength + rightLength - j);\n const left = leftSequence.slice(leftStart, leftStop);\n const rightStart = Math.max(0, j - leftLength);\n const rightStop = Math.min(rightLength, j);\n const right = rightSequence.slice(rightStart, rightStop);\n if (left.length !== right.length) {\n throw new Error(\"There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.\");\n }\n\n let matches;\n if (use_token_timestamp_sequences) {\n // Get length of longest subsequence of tokens that match\n // and have timestamps that are in order\n matches = left.filter((elem, idx) => (\n elem === right[idx]\n && left_token_timestamp_sequence[leftStart + idx] <= token_timestamp_sequences[i][rightStart + idx]\n )).length;\n } else {\n matches = left.filter((elem, idx) => elem === right[idx]).length;\n }\n\n // epsilon to favor long perfect matches\n const eps = j / 10000.0;\n const matching = matches / j + eps;\n if (matches > 1 && matching > max) {\n max = matching;\n maxIndices = [leftStart, leftStop, rightStart, rightStop];\n }\n }\n const [leftStart, leftStop, rightStart, rightStop] = maxIndices;\n const leftMid = Math.floor((leftStop + leftStart) / 2);\n const rightMid = Math.floor((rightStop + rightStart) / 2);\n totalSequence.push(...leftSequence.slice(0, leftMid));\n leftSequence = rightSequence.slice(rightMid);\n leftLength = leftSequence.length;\n\n if (use_token_timestamp_sequences) {\n total_token_timestamp_sequence.push(...left_token_timestamp_sequence.slice(0, leftMid));\n left_token_timestamp_sequence = token_timestamp_sequences[i].slice(rightMid);\n }\n }\n totalSequence.push(...leftSequence);\n\n if (use_token_timestamp_sequences) {\n total_token_timestamp_sequence.push(...left_token_timestamp_sequence);\n return [totalSequence, total_token_timestamp_sequence];\n } else {\n return [totalSequence, []];\n }\n }\n\n /** @private */\n collateWordTimestamps(tokens, token_timestamps, language) {\n\n const [words, _, token_indices] = this.combineTokensIntoWords(tokens, language);\n\n const timings = [];\n for (let i = 0; i < words.length; ++i) {\n const indices = token_indices[i];\n timings.push({\n text: words[i],\n timestamp: [\n token_timestamps[indices.at(0)][0],\n token_timestamps[indices.at(-1)][1],\n ],\n });\n }\n return timings;\n }\n\n /**\n * Groups tokens by word. Returns a tuple containing a list of strings with the words,\n * and a list of `token_id` sequences with the tokens making up each word.\n * @param {number[]} tokens \n * @param {string} [language] \n * @param {string} prepend_punctionations \n * @param {string} append_punctuations \n * \n * @private\n */\n combineTokensIntoWords(tokens, language, prepend_punctionations = \"\\\"'“¡¿([{-\", append_punctuations = \"\\\"'.。,,!!??::”)]}、\") {\n language = language ?? 'english';\n\n let words, word_tokens, token_indices;\n\n if ([\"chinese\", \"japanese\", \"thai\", \"lao\", \"myanmar\"].includes(language)) {\n // These languages don't typically use spaces.\n [words, word_tokens, token_indices] = this.splitTokensOnUnicode(tokens)\n } else {\n [words, word_tokens, token_indices] = this.splitTokensOnSpaces(tokens)\n }\n\n return this.mergePunctuations(words, word_tokens, token_indices, prepend_punctionations, append_punctuations);\n }\n\n /** @type {PreTrainedTokenizer['decode']} */\n decode(\n token_ids,\n decode_args,\n ) {\n let text;\n // @ts-ignore\n if (decode_args?.decode_with_timestamps) {\n if (token_ids instanceof Tensor) {\n token_ids = prepareTensorForDecode(token_ids);\n }\n text = this.decodeWithTimestamps(token_ids, decode_args);\n } else {\n text = super.decode(token_ids, decode_args);\n }\n // TODO: implement offsets\n // if (decode_args.output_offsets) {\n // let offsets = this.computeOffsets\n // }\n return text;\n }\n\n /**\n * @param {number[]|bigint[]} token_ids List of token IDs to decode.\n * @param {Object} decode_args Optional arguments for decoding\n * @private\n */\n decodeWithTimestamps(token_ids, decode_args) {\n const time_precision = decode_args?.time_precision ?? 0.02;\n\n const timestamp_begin = Array.from(this.all_special_ids).at(-1) + 1;\n /**@type {Array} */\n let outputs = [[]];\n for (let token of token_ids) {\n token = Number(token);\n if (token >= timestamp_begin) {\n const timestamp = ((token - timestamp_begin) * time_precision).toFixed(2);\n outputs.push(`<|${timestamp}|>`);\n outputs.push([]);\n } else {\n outputs[outputs.length - 1].push(token);\n }\n }\n outputs = outputs.map(\n s => typeof s === 'string' ? s : super.decode(s, decode_args)\n )\n\n return outputs.join('');\n }\n\n /**\n * Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points.\n * @param {number[]} tokens \n * @returns {*}\n * @private\n */\n splitTokensOnUnicode(tokens) {\n const decoded_full = this.decode(tokens, {\n // @ts-ignore\n decode_with_timestamps: true,\n });\n const replacement_char = '\\uFFFD';\n\n const words = []\n const word_tokens = []\n const token_indices = []\n let current_tokens = []\n let current_indices = []\n let unicode_offset = 0\n\n for (let token_idx = 0; token_idx < tokens.length; ++token_idx) {\n const token = tokens[token_idx];\n\n current_tokens.push(token);\n current_indices.push(token_idx);\n\n const decoded = this.decode(current_tokens, {\n // @ts-ignore\n decode_with_timestamps: true,\n });\n\n if (!decoded.includes(replacement_char) || decoded_full[unicode_offset + decoded.indexOf(replacement_char)] === replacement_char) {\n words.push(decoded)\n word_tokens.push(current_tokens)\n token_indices.push(current_indices)\n current_tokens = []\n current_indices = []\n unicode_offset += decoded.length;\n }\n\n }\n\n return [words, word_tokens, token_indices]\n }\n\n /**\n * Combine tokens into words by splitting at whitespace and punctuation tokens.\n * @param {number[]} tokens \n * @private\n */\n splitTokensOnSpaces(tokens) {\n\n const [subwords, subword_tokens_list, subword_indices_list] = this.splitTokensOnUnicode(tokens);\n\n const words = []\n const word_tokens = []\n const token_indices = []\n\n const punctuationRegex = new RegExp(`^[${PUNCTUATION_REGEX}]$`, 'gu');\n\n for (let i = 0; i < subwords.length; ++i) {\n\n const subword = subwords[i];\n const subword_tokens = subword_tokens_list[i];\n const subword_indices = subword_indices_list[i];\n\n // @ts-ignore\n const special = subword_tokens[0] >= this.model.tokens_to_ids.get('<|endoftext|>');\n const with_space = subword.startsWith(' ');\n const trimmed = subword.trim();\n const punctuation = punctuationRegex.test(trimmed);\n\n if (special || with_space || punctuation || words.length === 0) {\n words.push(subword);\n word_tokens.push(subword_tokens);\n token_indices.push(subword_indices);\n } else {\n const ix = words.length - 1;\n words[ix] += subword;\n word_tokens[ix].push(...subword_tokens);\n token_indices[ix].push(...subword_indices);\n }\n }\n\n return [words, word_tokens, token_indices];\n\n }\n\n /**\n * Merges punctuation tokens with neighboring words.\n * @param {string[]} words \n * @param {number[][]} tokens \n * @param {number[][]} indices \n * @param {string} prepended \n * @param {string} appended \n * @private\n */\n mergePunctuations(words, tokens, indices, prepended, appended) {\n\n const newWords = structuredClone(words);\n const newTokens = structuredClone(tokens);\n const newIndices = structuredClone(indices);\n\n\n // prepend punctuations\n let i = newWords.length - 2;\n let j = newWords.length - 1;\n\n while (i >= 0) {\n if (newWords[i].startsWith(' ') && prepended.includes(newWords[i].trim())) {\n newWords[j] = newWords[i] + newWords[j];\n newTokens[j] = mergeArrays(newTokens[i], newTokens[j]);\n newIndices[j] = mergeArrays(newIndices[i], newIndices[j]);\n newWords[i] = '';\n newTokens[i] = [];\n newIndices[i] = [];\n } else {\n j = i;\n }\n --i;\n }\n\n // append punctuations\n i = 0;\n j = 1;\n while (j < newWords.length) {\n if (!newWords[i].endsWith(' ') && appended.includes(newWords[j])) {\n newWords[i] += newWords[j];\n newTokens[i] = mergeArrays(newTokens[i], newTokens[j]);\n newIndices[i] = mergeArrays(newIndices[i], newIndices[j]);\n newWords[j] = '';\n newTokens[j] = [];\n newIndices[j] = [];\n } else {\n i = j;\n }\n ++j;\n }\n\n return [\n newWords.filter(x => x),\n newTokens.filter(x => x.length > 0),\n newIndices.filter(x => x.length > 0),\n ]\n }\n}\nexport class CodeGenTokenizer extends PreTrainedTokenizer { }\nexport class CLIPTokenizer extends PreTrainedTokenizer { }\nexport class SiglipTokenizer extends PreTrainedTokenizer { }\n\n/**\n * @todo This model is not yet supported by Hugging Face's \"fast\" tokenizers library (https://github.com/huggingface/tokenizers).\n * Therefore, this implementation (which is based on fast tokenizers) may produce slightly inaccurate results.\n */\nexport class MarianTokenizer extends PreTrainedTokenizer {\n /**\n * Create a new MarianTokenizer instance.\n * @param {Object} tokenizerJSON The JSON of the tokenizer.\n * @param {Object} tokenizerConfig The config of the tokenizer.\n */\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.languageRegex = /^(>>\\w+<<)\\s*/g;\n\n this.supported_language_codes = this.model.vocab.filter(\n x => this.languageRegex.test(x)\n );\n\n console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\\'s \"fast\" tokenizers library. Therefore, you may experience slightly inaccurate results.')\n }\n\n /**\n * Encodes a single text. Overriding this method is necessary since the language codes\n * must be removed before encoding with sentencepiece model.\n * @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213\n *\n * @param {string|null} text The text to encode.\n * @returns {Array} The encoded tokens.\n */\n _encode_text(text) {\n if (text === null) return null;\n\n // Check if text starts with language code:\n const [matchInfo, ...remainder] = text.trim().split(this.languageRegex);\n\n if (remainder.length === 0) {\n // No language code, encode normally\n return super._encode_text(matchInfo);\n\n } else if (remainder.length === 2) {\n // Text starts with language code, so we do not encode it with sentencepiece.\n const [language, text] = remainder;\n\n if (!this.supported_language_codes.includes(language)) {\n console.warn(`Unsupported language code \"${language}\" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`)\n }\n return mergeArrays([language], super._encode_text(text));\n }\n }\n\n}\n\nexport class Wav2Vec2CTCTokenizer extends PreTrainedTokenizer { }\n\nexport class BlenderbotTokenizer extends PreTrainedTokenizer { }\nexport class BlenderbotSmallTokenizer extends PreTrainedTokenizer { }\n\nexport class SpeechT5Tokenizer extends PreTrainedTokenizer { }\n\nexport class NougatTokenizer extends PreTrainedTokenizer { }\n\nexport class VitsTokenizer extends PreTrainedTokenizer {\n\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n // Custom decoder function\n this.decoder = new VitsDecoder({});\n }\n}\n\nexport class CohereTokenizer extends PreTrainedTokenizer { }\n\n/**\n * Helper class which is used to instantiate pretrained tokenizers with the `from_pretrained` function.\n * The chosen tokenizer class is determined by the type specified in the tokenizer config.\n * \n * @example\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');\n */\nexport class AutoTokenizer {\n static TOKENIZER_CLASS_MAPPING = {\n T5Tokenizer,\n DistilBertTokenizer,\n CamembertTokenizer,\n DebertaTokenizer,\n DebertaV2Tokenizer,\n BertTokenizer,\n HerbertTokenizer,\n ConvBertTokenizer,\n RoFormerTokenizer,\n XLMTokenizer,\n ElectraTokenizer,\n MobileBertTokenizer,\n SqueezeBertTokenizer,\n AlbertTokenizer,\n GPT2Tokenizer,\n BartTokenizer,\n MBartTokenizer,\n MBart50Tokenizer,\n RobertaTokenizer,\n WhisperTokenizer,\n CodeGenTokenizer,\n CLIPTokenizer,\n SiglipTokenizer,\n MarianTokenizer,\n BloomTokenizer,\n NllbTokenizer,\n M2M100Tokenizer,\n LlamaTokenizer,\n CodeLlamaTokenizer,\n XLMRobertaTokenizer,\n MPNetTokenizer,\n FalconTokenizer,\n GPTNeoXTokenizer,\n EsmTokenizer,\n Wav2Vec2CTCTokenizer,\n BlenderbotTokenizer,\n BlenderbotSmallTokenizer,\n SpeechT5Tokenizer,\n NougatTokenizer,\n VitsTokenizer,\n Qwen2Tokenizer,\n GemmaTokenizer,\n Grok1Tokenizer,\n CohereTokenizer,\n\n // Base case:\n PreTrainedTokenizer,\n }\n\n\n /**\n * Instantiate one of the tokenizer classes of the library from a pretrained model.\n * \n * The tokenizer class to instantiate is selected based on the `tokenizer_class` property of the config object\n * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)\n * \n * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:\n * - A string, the *model id* of a pretrained tokenizer hosted inside a model repo on huggingface.co.\n * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a\n * user or organization name, like `dbmdz/bert-base-german-cased`.\n * - A path to a *directory* containing tokenizer files, e.g., `./my_model_directory/`.\n * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.\n * \n * @returns {Promise} A new instance of the PreTrainedTokenizer class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n legacy = null,\n } = {}) {\n\n const [tokenizerJSON, tokenizerConfig] = await loadTokenizer(pretrained_model_name_or_path, {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n legacy,\n })\n\n // Some tokenizers are saved with the \"Fast\" suffix, so we remove that if present.\n const tokenizerName = tokenizerConfig.tokenizer_class?.replace(/Fast$/, '') ?? 'PreTrainedTokenizer';\n\n let cls = this.TOKENIZER_CLASS_MAPPING[tokenizerName];\n if (!cls) {\n console.warn(`Unknown tokenizer class \"${tokenizerName}\", attempting to construct from base class.`);\n cls = PreTrainedTokenizer;\n }\n return new cls(tokenizerJSON, tokenizerConfig);\n }\n}\n","/**\n * @file Helper module for audio processing. \n * \n * These functions and classes are only used internally, \n * meaning an end-user shouldn't need to access anything here.\n * \n * @module utils/audio\n */\n\nimport {\n getFile,\n} from './hub.js';\nimport { FFT, max } from './maths.js';\nimport {\n calculateReflectOffset,\n} from './core.js';\nimport { Tensor, matmul } from './tensor.js';\n\n\n/**\n * Helper function to read audio from a path/URL.\n * @param {string|URL} url The path/URL to load the audio from.\n * @param {number} sampling_rate The sampling rate to use when decoding the audio.\n * @returns {Promise} The decoded audio as a `Float32Array`.\n */\nexport async function read_audio(url, sampling_rate) {\n if (typeof AudioContext === 'undefined') {\n // Running in node or an environment without AudioContext\n throw Error(\n \"Unable to load audio from path/URL since `AudioContext` is not available in your environment. \" +\n \"Instead, audio data should be passed directly to the pipeline/processor. \" +\n \"For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.\"\n )\n }\n\n const response = await (await getFile(url)).arrayBuffer();\n const audioCTX = new AudioContext({ sampleRate: sampling_rate });\n if (typeof sampling_rate === 'undefined') {\n console.warn(`No sampling rate provided, using default of ${audioCTX.sampleRate}Hz.`)\n }\n const decoded = await audioCTX.decodeAudioData(response);\n\n /** @type {Float32Array} */\n let audio;\n\n // We now replicate HuggingFace's `ffmpeg_read` method:\n if (decoded.numberOfChannels === 2) {\n // When downmixing a stereo audio file to mono using the -ac 1 option in FFmpeg,\n // the audio signal is summed across both channels to create a single mono channel.\n // However, if the audio is at full scale (i.e. the highest possible volume level),\n // the summing of the two channels can cause the audio signal to clip or distort.\n\n // To prevent this clipping, FFmpeg applies a scaling factor of 1/sqrt(2) (~ 0.707)\n // to the audio signal before summing the two channels. This scaling factor ensures\n // that the combined audio signal will not exceed the maximum possible level, even\n // if both channels are at full scale.\n\n // After applying this scaling factor, the audio signal from both channels is summed\n // to create a single mono channel. It's worth noting that this scaling factor is\n // only applied when downmixing stereo audio to mono using the -ac 1 option in FFmpeg.\n // If you're using a different downmixing method, or if you're not downmixing the\n // audio at all, this scaling factor may not be needed.\n const SCALING_FACTOR = Math.sqrt(2);\n\n const left = decoded.getChannelData(0);\n const right = decoded.getChannelData(1);\n\n audio = new Float32Array(left.length);\n for (let i = 0; i < decoded.length; ++i) {\n audio[i] = SCALING_FACTOR * (left[i] + right[i]) / 2;\n }\n\n } else {\n // If the audio is not stereo, we can just use the first channel:\n audio = decoded.getChannelData(0);\n }\n\n return audio;\n}\n\n/**\n * Helper function to generate windows that are special cases of the generalized cosine window.\n * See https://www.mathworks.com/help/signal/ug/generalized-cosine-windows.html for more information.\n * @param {number} M Number of points in the output window. If zero or less, an empty array is returned.\n * @param {number} a_0 Offset for the generalized cosine window.\n * @returns {Float64Array} The generated window.\n */\nfunction generalized_cosine_window(M, a_0) {\n if (M < 1) {\n return new Float64Array();\n }\n if (M === 1) {\n return new Float64Array([1]);\n }\n\n const a_1 = 1 - a_0;\n const factor = 2 * Math.PI / (M - 1);\n\n const cos_vals = new Float64Array(M);\n for (let i = 0; i < M; ++i) {\n cos_vals[i] = a_0 - a_1 * Math.cos(i * factor);\n }\n return cos_vals;\n}\n\n/**\n * Generates a Hanning window of length M.\n * See https://numpy.org/doc/stable/reference/generated/numpy.hanning.html for more information.\n *\n * @param {number} M The length of the Hanning window to generate.\n * @returns {Float64Array} The generated Hanning window.\n */\nexport function hanning(M) {\n return generalized_cosine_window(M, 0.5);\n}\n\n\n/**\n * Generates a Hamming window of length M.\n * See https://numpy.org/doc/stable/reference/generated/numpy.hamming.html for more information.\n *\n * @param {number} M The length of the Hamming window to generate.\n * @returns {Float64Array} The generated Hamming window.\n */\nexport function hamming(M) {\n return generalized_cosine_window(M, 0.54);\n}\n\n\nconst HERTZ_TO_MEL_MAPPING = {\n \"htk\": (/** @type {number} */ freq) => 2595.0 * Math.log10(1.0 + (freq / 700.0)),\n \"kaldi\": (/** @type {number} */ freq) => 1127.0 * Math.log(1.0 + (freq / 700.0)),\n \"slaney\": (/** @type {number} */ freq, min_log_hertz = 1000.0, min_log_mel = 15.0, logstep = 27.0 / Math.log(6.4)) =>\n freq >= min_log_hertz\n ? min_log_mel + Math.log(freq / min_log_hertz) * logstep\n : 3.0 * freq / 200.0,\n}\n\n/**\n * @template {Float32Array|Float64Array|number} T \n * @param {T} freq \n * @param {string} [mel_scale]\n * @returns {T}\n */\nfunction hertz_to_mel(freq, mel_scale = \"htk\") {\n const fn = HERTZ_TO_MEL_MAPPING[mel_scale];\n if (!fn) {\n throw new Error('mel_scale should be one of \"htk\", \"slaney\" or \"kaldi\".');\n }\n\n return typeof freq === 'number' ? fn(freq) : freq.map(x => fn(x));\n}\n\nconst MEL_TO_HERTZ_MAPPING = {\n \"htk\": (/** @type {number} */ mels) => 700.0 * (10.0 ** (mels / 2595.0) - 1.0),\n \"kaldi\": (/** @type {number} */ mels) => 700.0 * (Math.exp(mels / 1127.0) - 1.0),\n \"slaney\": (/** @type {number} */ mels, min_log_hertz = 1000.0, min_log_mel = 15.0, logstep = Math.log(6.4) / 27.0) => mels >= min_log_mel\n ? min_log_hertz * Math.exp(logstep * (mels - min_log_mel))\n : 200.0 * mels / 3.0,\n}\n\n/**\n * @template {Float32Array|Float64Array|number} T \n * @param {T} mels \n * @param {string} [mel_scale]\n * @returns {T}\n */\nfunction mel_to_hertz(mels, mel_scale = \"htk\") {\n const fn = MEL_TO_HERTZ_MAPPING[mel_scale];\n if (!fn) {\n throw new Error('mel_scale should be one of \"htk\", \"slaney\" or \"kaldi\".');\n }\n\n return typeof mels === 'number' ? fn(mels) : mels.map(x => fn(x));\n}\n\n/**\n* Creates a triangular filter bank.\n*\n* Adapted from torchaudio and librosa.\n*\n* @param {Float64Array} fft_freqs Discrete frequencies of the FFT bins in Hz, of shape `(num_frequency_bins,)`.\n* @param {Float64Array} filter_freqs Center frequencies of the triangular filters to create, in Hz, of shape `(num_mel_filters,)`.\n* @returns {number[][]} of shape `(num_frequency_bins, num_mel_filters)`.\n*/\nfunction _create_triangular_filter_bank(fft_freqs, filter_freqs) {\n const filter_diff = Float64Array.from(\n { length: filter_freqs.length - 1 },\n (_, i) => filter_freqs[i + 1] - filter_freqs[i]\n );\n\n const slopes = Array.from({\n length: fft_freqs.length\n }, () => new Array(filter_freqs.length));\n\n for (let j = 0; j < fft_freqs.length; ++j) {\n const slope = slopes[j];\n for (let i = 0; i < filter_freqs.length; ++i) {\n slope[i] = filter_freqs[i] - fft_freqs[j];\n }\n }\n\n const numFreqs = filter_freqs.length - 2;\n const ret = Array.from({ length: numFreqs }, () => new Array(fft_freqs.length));\n\n for (let j = 0; j < fft_freqs.length; ++j) { // 201\n const slope = slopes[j];\n for (let i = 0; i < numFreqs; ++i) { // 80\n const down = -slope[i] / filter_diff[i];\n const up = slope[i + 2] / filter_diff[i + 1];\n ret[i][j] = Math.max(0, Math.min(down, up));\n }\n }\n return ret;\n}\n\n/**\n * Return evenly spaced numbers over a specified interval.\n * @param {number} start The starting value of the sequence.\n * @param {number} end The end value of the sequence.\n * @param {number} num Number of samples to generate.\n * @returns `num` evenly spaced samples, calculated over the interval `[start, stop]`.\n */\nfunction linspace(start, end, num) {\n const step = (end - start) / (num - 1);\n return Float64Array.from({ length: num }, (_, i) => start + step * i);\n}\n\n/**\n * Creates a frequency bin conversion matrix used to obtain a mel spectrogram. This is called a *mel filter bank*, and\n * various implementation exist, which differ in the number of filters, the shape of the filters, the way the filters\n * are spaced, the bandwidth of the filters, and the manner in which the spectrum is warped. The goal of these\n * features is to approximate the non-linear human perception of the variation in pitch with respect to the frequency.\n * @param {number} num_frequency_bins Number of frequencies used to compute the spectrogram (should be the same as in `stft`).\n * @param {number} num_mel_filters Number of mel filters to generate.\n * @param {number} min_frequency Lowest frequency of interest in Hz.\n * @param {number} max_frequency Highest frequency of interest in Hz. This should not exceed `sampling_rate / 2`.\n * @param {number} sampling_rate Sample rate of the audio waveform.\n * @param {string} [norm] If `\"slaney\"`, divide the triangular mel weights by the width of the mel band (area normalization).\n * @param {string} [mel_scale] The mel frequency scale to use, `\"htk\"` or `\"slaney\"`.\n * @param {boolean} [triangularize_in_mel_space] If this option is enabled, the triangular filter is applied in mel space rather than frequency space.\n * This should be set to `true` in order to get the same results as `torchaudio` when computing mel filters.\n * @returns {number[][]} Triangular filter bank matrix, which is a 2D array of shape (`num_frequency_bins`, `num_mel_filters`).\n * This is a projection matrix to go from a spectrogram to a mel spectrogram.\n */\nexport function mel_filter_bank(\n num_frequency_bins,\n num_mel_filters,\n min_frequency,\n max_frequency,\n sampling_rate,\n norm = null,\n mel_scale = \"htk\",\n triangularize_in_mel_space = false,\n) {\n if (norm !== null && norm !== \"slaney\") {\n throw new Error('norm must be one of null or \"slaney\"');\n }\n\n const mel_min = hertz_to_mel(min_frequency, mel_scale);\n const mel_max = hertz_to_mel(max_frequency, mel_scale);\n const mel_freqs = linspace(mel_min, mel_max, num_mel_filters + 2);\n\n let filter_freqs = mel_to_hertz(mel_freqs, mel_scale);\n let fft_freqs; // frequencies of FFT bins in Hz\n\n if (triangularize_in_mel_space) {\n const fft_bin_width = sampling_rate / (num_frequency_bins * 2);\n fft_freqs = hertz_to_mel(Float64Array.from({ length: num_frequency_bins }, (_, i) => i * fft_bin_width), mel_scale);\n filter_freqs = mel_freqs;\n } else {\n fft_freqs = linspace(0, Math.floor(sampling_rate / 2), num_frequency_bins);\n }\n\n const mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs);\n\n if (norm !== null && norm === \"slaney\") {\n // Slaney-style mel is scaled to be approx constant energy per channel\n for (let i = 0; i < num_mel_filters; ++i) {\n const filter = mel_filters[i];\n const enorm = 2.0 / (filter_freqs[i + 2] - filter_freqs[i]);\n for (let j = 0; j < num_frequency_bins; ++j) {\n // Apply this enorm to all frequency bins\n filter[j] *= enorm;\n }\n }\n }\n\n // TODO warn if there is a zero row\n\n return mel_filters;\n\n}\n\n/**\n * @template {Float32Array|Float64Array} T\n * Pads an array with a reflected version of itself on both ends.\n * @param {T} array The array to pad.\n * @param {number} left The amount of padding to add to the left.\n * @param {number} right The amount of padding to add to the right.\n * @returns {T} The padded array.\n */\nfunction padReflect(array, left, right) {\n // @ts-ignore\n const padded = new array.constructor(array.length + left + right);\n const w = array.length - 1;\n\n for (let i = 0; i < array.length; ++i) {\n padded[left + i] = array[i];\n }\n\n for (let i = 1; i <= left; ++i) {\n padded[left - i] = array[calculateReflectOffset(i, w)];\n }\n\n for (let i = 1; i <= right; ++i) {\n padded[w + left + i] = array[calculateReflectOffset(w - i, w)];\n }\n\n return padded;\n}\n\n/**\n * Helper function to compute `amplitude_to_db` and `power_to_db`.\n * @template {Float32Array|Float64Array} T\n * @param {T} spectrogram \n * @param {number} factor \n * @param {number} reference \n * @param {number} min_value \n * @param {number} db_range \n * @returns {T}\n */\nfunction _db_conversion_helper(spectrogram, factor, reference, min_value, db_range) {\n if (reference <= 0) {\n throw new Error('reference must be greater than zero');\n }\n\n if (min_value <= 0) {\n throw new Error('min_value must be greater than zero');\n }\n\n reference = Math.max(min_value, reference);\n\n const logReference = Math.log10(reference);\n for (let i = 0; i < spectrogram.length; ++i) {\n spectrogram[i] = factor * Math.log10(Math.max(min_value, spectrogram[i]) - logReference)\n }\n\n if (db_range !== null) {\n if (db_range <= 0) {\n throw new Error('db_range must be greater than zero');\n }\n const maxValue = max(spectrogram)[0] - db_range;\n for (let i = 0; i < spectrogram.length; ++i) {\n spectrogram[i] = Math.max(spectrogram[i], maxValue);\n }\n }\n\n return spectrogram;\n}\n\n/**\n * Converts an amplitude spectrogram to the decibel scale. This computes `20 * log10(spectrogram / reference)`,\n * using basic logarithm properties for numerical stability. NOTE: Operates in-place.\n * \n * The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a\n * linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.\n * This means that large variations in energy may not sound all that different if the sound is loud to begin with.\n * This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.\n * \n * @template {Float32Array|Float64Array} T\n * @param {T} spectrogram The input amplitude (mel) spectrogram.\n * @param {number} [reference=1.0] Sets the input spectrogram value that corresponds to 0 dB.\n * For example, use `np.max(spectrogram)` to set the loudest part to 0 dB. Must be greater than zero.\n * @param {number} [min_value=1e-5] The spectrogram will be clipped to this minimum value before conversion to decibels,\n * to avoid taking `log(0)`. The default of `1e-5` corresponds to a minimum of -100 dB. Must be greater than zero.\n * @param {number} [db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the\n * difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero.\n * @returns {T} The modified spectrogram in decibels.\n */\nfunction amplitude_to_db(spectrogram, reference = 1.0, min_value = 1e-5, db_range = null) {\n return _db_conversion_helper(spectrogram, 20.0, reference, min_value, db_range);\n}\n\n/**\n * Converts a power spectrogram to the decibel scale. This computes `10 * log10(spectrogram / reference)`,\n * using basic logarithm properties for numerical stability. NOTE: Operates in-place.\n * \n * The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a\n * linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.\n * This means that large variations in energy may not sound all that different if the sound is loud to begin with.\n * This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.\n * \n * Based on the implementation of `librosa.power_to_db`.\n * \n * @template {Float32Array|Float64Array} T\n * @param {T} spectrogram The input power (mel) spectrogram. Note that a power spectrogram has the amplitudes squared!\n * @param {number} [reference=1.0] Sets the input spectrogram value that corresponds to 0 dB.\n * For example, use `np.max(spectrogram)` to set the loudest part to 0 dB. Must be greater than zero.\n * @param {number} [min_value=1e-10] The spectrogram will be clipped to this minimum value before conversion to decibels,\n * to avoid taking `log(0)`. The default of `1e-10` corresponds to a minimum of -100 dB. Must be greater than zero.\n * @param {number} [db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the\n * difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero.\n * @returns {T} The modified spectrogram in decibels.\n */\nfunction power_to_db(spectrogram, reference = 1.0, min_value = 1e-10, db_range = null) {\n return _db_conversion_helper(spectrogram, 10.0, reference, min_value, db_range);\n}\n\n/**\n * Calculates a spectrogram over one waveform using the Short-Time Fourier Transform.\n * \n * This function can create the following kinds of spectrograms:\n * - amplitude spectrogram (`power = 1.0`)\n * - power spectrogram (`power = 2.0`)\n * - complex-valued spectrogram (`power = None`)\n * - log spectrogram (use `log_mel` argument)\n * - mel spectrogram (provide `mel_filters`)\n * - log-mel spectrogram (provide `mel_filters` and `log_mel`)\n *\n * In this implementation, the window is assumed to be zero-padded to have the same size as the analysis frame.\n * A padded window can be obtained from `window_function()`. The FFT input buffer may be larger than the analysis frame, \n * typically the next power of two.\n * \n * @param {Float32Array|Float64Array} waveform The input waveform of shape `(length,)`. This must be a single real-valued, mono waveform.\n * @param {Float32Array|Float64Array} window The windowing function to apply of shape `(frame_length,)`, including zero-padding if necessary. The actual window length may be\n * shorter than `frame_length`, but we're assuming the array has already been zero-padded.\n * @param {number} frame_length The length of the analysis frames in samples (a.k.a., `fft_length`).\n * @param {number} hop_length The stride between successive analysis frames in samples.\n * @param {Object} options\n * @param {number} [options.fft_length=null] The size of the FFT buffer in samples. This determines how many frequency bins the spectrogram will have.\n * For optimal speed, this should be a power of two. If `null`, uses `frame_length`.\n * @param {number} [options.power=1.0] If 1.0, returns the amplitude spectrogram. If 2.0, returns the power spectrogram. If `null`, returns complex numbers.\n * @param {boolean} [options.center=true] Whether to pad the waveform so that frame `t` is centered around time `t * hop_length`. If `false`, frame\n * `t` will start at time `t * hop_length`.\n * @param {string} [options.pad_mode=\"reflect\"] Padding mode used when `center` is `true`. Possible values are: `\"constant\"` (pad with zeros),\n * `\"edge\"` (pad with edge values), `\"reflect\"` (pads with mirrored values).\n * @param {boolean} [options.onesided=true] If `true`, only computes the positive frequencies and returns a spectrogram containing `fft_length // 2 + 1`\n * frequency bins. If `false`, also computes the negative frequencies and returns `fft_length` frequency bins.\n * @param {number} [options.preemphasis=null] Coefficient for a low-pass filter that applies pre-emphasis before the DFT.\n * @param {number[][]} [options.mel_filters=null] The mel filter bank of shape `(num_freq_bins, num_mel_filters)`.\n * If supplied, applies this filter bank to create a mel spectrogram.\n * @param {number} [options.mel_floor=1e-10] Minimum value of mel frequency banks.\n * @param {string} [options.log_mel=null] How to convert the spectrogram to log scale. Possible options are:\n * `null` (don't convert), `\"log\"` (take the natural logarithm) `\"log10\"` (take the base-10 logarithm), `\"dB\"` (convert to decibels).\n * Can only be used when `power` is not `null`.\n * @param {number} [options.reference=1.0] Sets the input spectrogram value that corresponds to 0 dB. For example, use `max(spectrogram)[0]` to set\n * the loudest part to 0 dB. Must be greater than zero.\n * @param {number} [options.min_value=1e-10] The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking `log(0)`.\n * For a power spectrogram, the default of `1e-10` corresponds to a minimum of -100 dB. For an amplitude spectrogram, the value `1e-5` corresponds to -100 dB.\n * Must be greater than zero.\n * @param {number} [options.db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the\n * peak value and the smallest value will never be more than 80 dB. Must be greater than zero.\n * @param {boolean} [options.remove_dc_offset=null] Subtract mean from waveform on each frame, applied before pre-emphasis. This should be set to `true` in\n * order to get the same results as `torchaudio.compliance.kaldi.fbank` when computing mel filters.\n * @param {number} [options.max_num_frames=null] If provided, limits the number of frames to compute to this value.\n * @param {number} [options.min_num_frames=null] If provided, ensures the number of frames to compute is at least this value.\n * @param {boolean} [options.do_pad=true] If `true`, pads the output spectrogram to have `max_num_frames` frames.\n * @param {boolean} [options.transpose=false] If `true`, the returned spectrogram will have shape `(num_frames, num_frequency_bins/num_mel_filters)`. If `false`, the returned spectrogram will have shape `(num_frequency_bins/num_mel_filters, num_frames)`.\n * @returns {Promise} Spectrogram of shape `(num_frequency_bins, length)` (regular spectrogram) or shape `(num_mel_filters, length)` (mel spectrogram).\n */\nexport async function spectrogram(\n waveform,\n window,\n frame_length,\n hop_length,\n {\n fft_length = null,\n power = 1.0,\n center = true,\n pad_mode = \"reflect\",\n onesided = true,\n preemphasis = null,\n mel_filters = null,\n mel_floor = 1e-10,\n log_mel = null,\n reference = 1.0,\n min_value = 1e-10,\n db_range = null,\n remove_dc_offset = null,\n\n // Custom parameters for efficiency reasons\n min_num_frames = null,\n max_num_frames = null,\n do_pad = true,\n transpose = false,\n } = {}\n) {\n const window_length = window.length;\n if (fft_length === null) {\n fft_length = frame_length;\n }\n if (frame_length > fft_length) {\n throw Error(`frame_length (${frame_length}) may not be larger than fft_length (${fft_length})`)\n }\n\n if (window_length !== frame_length) {\n throw new Error(`Length of the window (${window_length}) must equal frame_length (${frame_length})`);\n }\n\n if (hop_length <= 0) {\n throw new Error(\"hop_length must be greater than zero\");\n }\n\n if (power === null && mel_filters !== null) {\n throw new Error(\n \"You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. \" +\n \"Specify `power` to fix this issue.\"\n );\n }\n\n if (center) {\n if (pad_mode !== 'reflect') {\n throw new Error(`pad_mode=\"${pad_mode}\" not implemented yet.`)\n }\n const half_window = Math.floor((fft_length - 1) / 2) + 1;\n waveform = padReflect(waveform, half_window, half_window);\n }\n\n // split waveform into frames of frame_length size\n let num_frames = Math.floor(1 + Math.floor((waveform.length - frame_length) / hop_length))\n if (min_num_frames !== null && num_frames < min_num_frames) {\n num_frames = min_num_frames\n }\n const num_frequency_bins = onesided ? Math.floor(fft_length / 2) + 1 : fft_length\n\n let d1 = num_frames;\n let d1Max = num_frames;\n\n // If maximum number of frames is provided, we must either pad or truncate\n if (max_num_frames !== null) {\n if (max_num_frames > num_frames) { // input is too short, so we pad\n if (do_pad) {\n d1Max = max_num_frames;\n }\n } else { // input is too long, so we truncate\n d1Max = d1 = max_num_frames;\n }\n }\n\n // Preallocate arrays to store output.\n const fft = new FFT(fft_length);\n const inputBuffer = new Float64Array(fft_length);\n const outputBuffer = new Float64Array(fft.outputBufferSize);\n const transposedMagnitudeData = new Float32Array(num_frequency_bins * d1Max);\n\n for (let i = 0; i < d1; ++i) {\n // Populate buffer with waveform data\n const offset = i * hop_length;\n const buffer_size = Math.min(waveform.length - offset, frame_length);\n if (buffer_size !== frame_length) {\n // The full buffer is not needed, so we need to reset it (avoid overflow from previous iterations)\n // NOTE: We don't need to reset the buffer if it's full since we overwrite the first\n // `frame_length` values and the rest (`fft_length - frame_length`) remains zero.\n inputBuffer.fill(0, 0, frame_length);\n }\n\n for (let j = 0; j < buffer_size; ++j) {\n inputBuffer[j] = waveform[offset + j];\n }\n\n if (remove_dc_offset) {\n let sum = 0;\n for (let j = 0; j < buffer_size; ++j) {\n sum += inputBuffer[j];\n }\n const mean = sum / buffer_size;\n for (let j = 0; j < buffer_size; ++j) {\n inputBuffer[j] -= mean;\n }\n }\n\n if (preemphasis !== null) {\n // Done in reverse to avoid copies and distructive modification\n for (let j = buffer_size - 1; j >= 1; --j) {\n inputBuffer[j] -= preemphasis * inputBuffer[j - 1];\n }\n inputBuffer[0] *= 1 - preemphasis;\n }\n\n // Apply window function\n for (let j = 0; j < window.length; ++j) {\n inputBuffer[j] *= window[j];\n }\n\n fft.realTransform(outputBuffer, inputBuffer);\n\n // compute magnitudes\n for (let j = 0; j < num_frequency_bins; ++j) {\n const j2 = j << 1;\n\n // NOTE: We transpose the data here to avoid doing it later\n transposedMagnitudeData[j * d1Max + i] = outputBuffer[j2] ** 2 + outputBuffer[j2 + 1] ** 2;\n }\n }\n\n if (power !== null && power !== 2) {\n // slight optimization to not sqrt\n const pow = 2 / power; // we use 2 since we already squared\n for (let i = 0; i < transposedMagnitudeData.length; ++i) {\n transposedMagnitudeData[i] **= pow;\n }\n }\n\n // TODO: What if `mel_filters` is null?\n const num_mel_filters = mel_filters.length;\n\n // Perform matrix muliplication:\n // mel_spec = mel_filters @ magnitudes.T\n // - mel_filters.shape=(80, 201)\n // - magnitudes.shape=(3000, 201) => magnitudes.T.shape=(201, 3000)\n // - mel_spec.shape=(80, 3000)\n let mel_spec = await matmul(\n // TODO: Make `mel_filters` a Tensor during initialization\n new Tensor('float32', mel_filters.flat(), [num_mel_filters, num_frequency_bins]),\n new Tensor('float32', transposedMagnitudeData, [num_frequency_bins, d1Max]),\n );\n if (transpose) {\n mel_spec = mel_spec.transpose(1, 0);\n }\n\n const mel_spec_data = /** @type {Float32Array} */(mel_spec.data);\n for (let i = 0; i < mel_spec_data.length; ++i) {\n mel_spec_data[i] = Math.max(mel_floor, mel_spec_data[i]);\n }\n\n if (power !== null && log_mel !== null) {\n const o = Math.min(mel_spec_data.length, d1 * num_mel_filters);\n // NOTE: operates in-place\n switch (log_mel) {\n case 'log':\n for (let i = 0; i < o; ++i) {\n mel_spec_data[i] = Math.log(mel_spec_data[i]);\n }\n break;\n case 'log10':\n for (let i = 0; i < o; ++i) {\n mel_spec_data[i] = Math.log10(mel_spec_data[i]);\n }\n break;\n case 'dB':\n if (power === 1.0) {\n amplitude_to_db(mel_spec_data, reference, min_value, db_range);\n } else if (power === 2.0) {\n power_to_db(mel_spec_data, reference, min_value, db_range);\n } else {\n throw new Error(`Cannot use log_mel option '${log_mel}' with power ${power}`)\n }\n break;\n default:\n throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${log_mel}'`);\n }\n }\n\n return mel_spec;\n}\n\n/**\n * Returns an array containing the specified window.\n * @param {number} window_length The length of the window in samples.\n * @param {string} name The name of the window function.\n * @param {Object} options Additional options.\n * @param {boolean} [options.periodic=true] Whether the window is periodic or symmetric.\n * @param {number} [options.frame_length=null] The length of the analysis frames in samples.\n * Provide a value for `frame_length` if the window is smaller than the frame length, so that it will be zero-padded.\n * @param {boolean} [options.center=true] Whether to center the window inside the FFT buffer. Only used when `frame_length` is provided.\n * @returns {Float64Array} The window of shape `(window_length,)` or `(frame_length,)`.\n */\nexport function window_function(window_length, name, {\n periodic = true,\n frame_length = null,\n center = true,\n} = {}) {\n const length = periodic ? window_length + 1 : window_length;\n let window;\n switch (name) {\n case 'boxcar':\n window = new Float64Array(length).fill(1.0);\n break;\n case 'hann':\n case 'hann_window':\n window = hanning(length);\n break;\n case 'hamming':\n window = hamming(length);\n break;\n case 'povey':\n window = hanning(length).map(x => Math.pow(x, 0.85));\n break;\n default:\n throw new Error(`Unknown window type ${name}.`);\n }\n if (periodic) {\n window = window.subarray(0, window_length);\n }\n if (frame_length === null) {\n return window;\n }\n if (window_length > frame_length) {\n throw new Error(`Length of the window (${window_length}) may not be larger than frame_length (${frame_length})`);\n }\n\n return window;\n}\n","\nexport const GITHUB_ISSUE_URL = 'https://github.com/huggingface/transformers.js/issues/new/choose';","\n/**\n * @file Core utility functions/classes for Transformers.js.\n * \n * These are only used internally, meaning an end-user shouldn't\n * need to access anything here.\n * \n * @module utils/core\n */\n\n/**\n * Helper function to dispatch progress callbacks.\n *\n * @param {Function} progress_callback The progress callback function to dispatch.\n * @param {any} data The data to pass to the progress callback function.\n * @returns {void}\n * @private\n */\nexport function dispatchCallback(progress_callback, data) {\n if (progress_callback) progress_callback(data);\n}\n\n/**\n * Reverses the keys and values of an object.\n *\n * @param {Object} data The object to reverse.\n * @returns {Object} The reversed object.\n * @see https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript\n */\nexport function reverseDictionary(data) {\n // https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript\n return Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key]));\n}\n\n/**\n * Escapes regular expression special characters from a string by replacing them with their escaped counterparts.\n *\n * @param {string} string The string to escape.\n * @returns {string} The escaped string.\n */\nexport function escapeRegExp(string) {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); // $& means the whole matched string\n}\n\n/**\n * Check if a value is a typed array.\n * @param {*} val The value to check.\n * @returns {boolean} True if the value is a `TypedArray`, false otherwise.\n * \n * Adapted from https://stackoverflow.com/a/71091338/13989043\n */\nexport function isTypedArray(val) {\n return val?.prototype?.__proto__?.constructor?.name === 'TypedArray';\n}\n\n\n/**\n * Check if a value is an integer.\n * @param {*} x The value to check.\n * @returns {boolean} True if the value is a string, false otherwise.\n */\nexport function isIntegralNumber(x) {\n return Number.isInteger(x) || typeof x === 'bigint'\n}\n\n/**\n * Calculates the dimensions of a nested array.\n *\n * @param {any[]} arr The nested array to calculate dimensions for.\n * @returns {number[]} An array containing the dimensions of the input array.\n */\nexport function calculateDimensions(arr) {\n const dimensions = [];\n let current = arr;\n while (Array.isArray(current)) {\n dimensions.push(current.length);\n current = current[0];\n }\n return dimensions;\n}\n\n/**\n * Replicate python's .pop() method for objects.\n * @param {Object} obj The object to pop from.\n * @param {string} key The key to pop.\n * @param {*} defaultValue The default value to return if the key does not exist.\n * @returns {*} The value of the popped key.\n * @throws {Error} If the key does not exist and no default value is provided.\n */\nexport function pop(obj, key, defaultValue = undefined) {\n const value = obj[key];\n if (value !== undefined) {\n delete obj[key];\n return value;\n }\n if (defaultValue === undefined) {\n throw Error(`Key ${key} does not exist in object.`)\n }\n return defaultValue;\n}\n\n/**\n * Efficiently merge arrays, creating a new copy.\n * Adapted from https://stackoverflow.com/a/6768642/13989043\n * @param {Array[]} arrs Arrays to merge.\n * @returns {Array} The merged array.\n */\nexport function mergeArrays(...arrs) {\n return Array.prototype.concat.apply([], arrs);\n}\n\n/**\n * Compute the Cartesian product of given arrays\n * @param {...Array} a Arrays to compute the product\n * @returns {Array} Returns the computed Cartesian product as an array\n * @private\n */\nexport function product(...a) {\n // Cartesian product of items\n // Adapted from https://stackoverflow.com/a/43053803\n return a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e])));\n}\n\n/**\n * Calculates the index offset for a given index and window size.\n * @param {number} i The index.\n * @param {number} w The window size.\n * @returns {number} The index offset.\n */\nexport function calculateReflectOffset(i, w) {\n return Math.abs((i + w) % (2 * w) - w);\n}\n\n/**\n * \n * @param {Object} o \n * @param {string[]} props \n * @returns {Object}\n */\nexport function pick(o, props) {\n return Object.assign(\n {},\n ...props.map((prop) => {\n if (o[prop] !== undefined) {\n return { [prop]: o[prop] };\n }\n })\n );\n}\n\n/**\n * Calculate the length of a string, taking multi-byte characters into account.\n * This mimics the behavior of Python's `len` function.\n * @param {string} s The string to calculate the length of. \n * @returns {number} The length of the string.\n */\nexport function len(s) {\n let length = 0;\n for (const c of s) ++length;\n return length;\n}\n","\n/**\n * @file Custom data structures.\n * \n * These are only used internally, meaning an end-user shouldn't\n * need to access anything here.\n * \n * @module utils/data-structures\n */\n\n\n/**\n * Efficient Heap-based Implementation of a Priority Queue.\n * It uses an array-based binary heap, where the root is at index `0`, and the\n * children of node `i` are located at indices `2i + 1` and `2i + 2`, respectively.\n * \n * Adapted from the following sources:\n * - https://stackoverflow.com/a/42919752/13989043 (original)\n * - https://github.com/belladoreai/llama-tokenizer-js (minor improvements)\n */\nexport class PriorityQueue {\n\n /**\n * Create a new PriorityQueue.\n * @param {function(any, any): boolean} comparator Comparator function to determine priority. Defaults to a MaxHeap.\n */\n constructor(comparator = (a, b) => a > b, maxSize = Infinity) {\n this._heap = [];\n this._comparator = comparator;\n this._maxSize = maxSize;\n }\n\n /**\n * The size of the queue\n */\n get size() {\n return this._heap.length;\n }\n\n /**\n * Check if the queue is empty.\n * @returns {boolean} `true` if the queue is empty, `false` otherwise.\n */\n isEmpty() {\n return this.size === 0;\n }\n\n /**\n * Return the element with the highest priority in the queue.\n * @returns {any} The highest priority element in the queue.\n */\n peek() {\n return this._heap[0];\n }\n\n /**\n * Add one or more elements to the queue.\n * @param {...any} values The values to push into the queue.\n * @returns {number} The new size of the queue.\n */\n push(...values) {\n return this.extend(values);\n }\n\n /**\n * Add multiple elements to the queue.\n * @param {any[]} values The values to push into the queue.\n * @returns {number} The new size of the queue.\n */\n extend(values) {\n for (const value of values) {\n if (this.size < this._maxSize) {\n this._heap.push(value);\n this._siftUp();\n } else {\n // Get index of value with the lowest priority\n const smallest = this._smallest();\n\n // If the new value has higher priority than the smallest value in the heap\n // then replace the smallest value with the new value and update the heap\n if (this._comparator(value, this._heap[smallest])) {\n this._heap[smallest] = value;\n this._siftUpFrom(smallest);\n }\n }\n }\n return this.size;\n }\n\n /**\n * Remove and return the element with the highest priority in the queue.\n * @returns {any} The element with the highest priority in the queue.\n */\n pop() {\n const poppedValue = this.peek();\n const bottom = this.size - 1;\n if (bottom > 0) {\n this._swap(0, bottom);\n }\n this._heap.pop();\n this._siftDown();\n return poppedValue;\n }\n\n /**\n * Replace the element with the highest priority in the queue with a new value.\n * @param {*} value The new value.\n * @returns {*} The replaced value.\n */\n replace(value) {\n const replacedValue = this.peek();\n this._heap[0] = value;\n this._siftDown();\n return replacedValue;\n }\n\n /**\n * Compute the index for the parent of the node at index `i`.\n * @param {number} i The index of the node to get the parent of.\n * @returns {number} The index of the parent node.\n * @private\n */\n _parent(i) {\n return ((i + 1) >>> 1) - 1;\n }\n\n /**\n * Compute the index for the left child of the node at index `i`.\n * @param {number} i The index of the node to get the left child of.\n * @returns {number} The index of the left child.\n * @private\n */\n _left(i) {\n return (i << 1) + 1;\n }\n\n /**\n * Compute the index for the right child of the node at index `i`.\n * @param {number} i The index of the node to get the right child of.\n * @returns {number} The index of the right child.\n * @private\n */\n _right(i) {\n return (i + 1) << 1;\n }\n\n /**\n * Check if the element at index `i` is greater than the element at index `j`.\n * @param {number} i The index of the first element to compare.\n * @param {number} j The index of the second element to compare.\n * @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.\n * @private\n */\n _greater(i, j) {\n return this._comparator(this._heap[i], this._heap[j]);\n }\n\n /**\n * Swap the elements at indices `i` and `j`.\n * @param {number} i The index of the first element to swap.\n * @param {number} j The index of the second element to swap.\n * @private\n */\n _swap(i, j) {\n const temp = this._heap[i];\n this._heap[i] = this._heap[j];\n this._heap[j] = temp;\n }\n\n /**\n * Maintain the heap property by updating positions in the heap,\n * starting at the last element and moving up the heap.\n * @private\n */\n _siftUp() {\n this._siftUpFrom(this.size - 1);\n }\n\n /**\n * Helper function to sift up from a given node.\n * @param {number} node The index of the node to start sifting up from.\n */\n _siftUpFrom(node) {\n while (node > 0 && this._greater(node, this._parent(node))) {\n this._swap(node, this._parent(node));\n node = this._parent(node);\n }\n }\n\n /**\n * Maintain the heap property by updating positions in the heap,\n * starting at the first element and moving down the heap.\n * @private\n */\n _siftDown() {\n let node = 0;\n while (\n (this._left(node) < this.size && this._greater(this._left(node), node)) ||\n (this._right(node) < this.size && this._greater(this._right(node), node))\n ) {\n const maxChild = (this._right(node) < this.size && this._greater(this._right(node), this._left(node)))\n ? this._right(node)\n : this._left(node);\n this._swap(node, maxChild);\n node = maxChild;\n }\n }\n\n /**\n * Get the index of the smallest element in the heap. Since we use an array-based heap,\n * the index can be computed without needing to traverse the heap.\n * @private\n */\n _smallest() {\n return (2 ** (Math.floor(Math.log2(this.size))) - 1);\n }\n}\n\n/**\n * A trie structure to efficiently store and search for strings.\n */\nexport class CharTrie {\n constructor() {\n this.root = CharTrieNode.default();\n }\n\n /**\n * Adds one or more `texts` to the trie.\n * @param {string[]} texts The strings to add to the trie.\n */\n extend(texts) {\n for (const text of texts) {\n this.push(text);\n }\n }\n\n /**\n * Adds text to the trie.\n * @param {string} text The string to add to the trie.\n */\n push(text) {\n let node = this.root;\n for (const ch of text) {\n let child = node.children.get(ch);\n if (child === undefined) {\n child = CharTrieNode.default();\n node.children.set(ch, child);\n }\n node = child;\n }\n node.isLeaf = true;\n }\n\n /**\n * Searches the trie for all strings with a common prefix of `text`.\n * @param {string} text The common prefix to search for.\n * @yields {string} Each string in the trie that has `text` as a prefix.\n */\n *commonPrefixSearch(text) {\n let node = this.root;\n if (node === undefined) return;\n\n let prefix = \"\";\n for (const ch of text) {\n prefix += ch;\n node = node.children.get(ch);\n if (node === undefined) return;\n if (node.isLeaf) {\n yield prefix;\n }\n }\n }\n}\n\n/**\n * Represents a node in a character trie.\n */\nclass CharTrieNode {\n /**\n * Create a new CharTrieNode.\n * @param {boolean} isLeaf Whether the node is a leaf node or not.\n * @param {Map} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.\n */\n constructor(isLeaf, children) {\n this.isLeaf = isLeaf;\n this.children = children;\n }\n\n /**\n * Returns a new `CharTrieNode` instance with default values.\n * @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map.\n */\n static default() {\n return new CharTrieNode(false, new Map());\n }\n}\n\n/**\n * A lattice data structure to be used for tokenization.\n */\nexport class TokenLattice {\n /**\n * Creates a new TokenLattice instance.\n *\n * @param {string} sentence The input sentence to be tokenized.\n * @param {number} bosTokenId The beginning-of-sequence token ID.\n * @param {number} eosTokenId The end-of-sequence token ID.\n */\n constructor(sentence, bosTokenId, eosTokenId) {\n this.chars = Array.from(sentence);\n this.len = this.chars.length;\n this.bosTokenId = bosTokenId;\n this.eosTokenId = eosTokenId;\n this.nodes = [];\n this.beginNodes = Array.from({ length: this.len + 1 }, () => []);\n this.endNodes = Array.from({ length: this.len + 1 }, () => []);\n\n const bos = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0.0);\n const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0.0);\n this.nodes.push(bos.clone());\n this.nodes.push(eos.clone());\n this.beginNodes[this.len].push(eos);\n this.endNodes[0].push(bos);\n }\n\n /**\n * Inserts a new token node into the token lattice.\n *\n * @param {number} pos The starting position of the token.\n * @param {number} length The length of the token.\n * @param {number} score The score of the token.\n * @param {number} tokenId The token ID of the token.\n */\n insert(pos, length, score, tokenId) {\n const nodeId = this.nodes.length;\n const node = new TokenLatticeNode(tokenId, nodeId, pos, length, score);\n this.beginNodes[pos].push(node);\n this.endNodes[pos + length].push(node);\n this.nodes.push(node);\n }\n\n /**\n * Implements the Viterbi algorithm to compute the most likely sequence of tokens.\n *\n * @returns {TokenLatticeNode[]} The most likely sequence of tokens.\n */\n viterbi() {\n const len = this.len;\n let pos = 0;\n while (pos <= len) {\n if (this.beginNodes[pos].length == 0) {\n return [];\n }\n for (let rnode of this.beginNodes[pos]) {\n rnode.prev = null;\n let bestScore = 0.0;\n let bestNode = null;\n for (let lnode of this.endNodes[pos]) {\n const score = lnode.backtraceScore + rnode.score;\n if (bestNode === null || score > bestScore) {\n bestNode = lnode.clone();\n bestScore = score;\n }\n }\n\n if (bestNode !== null) {\n rnode.prev = bestNode;\n rnode.backtraceScore = bestScore;\n } else {\n return [];\n }\n }\n ++pos;\n }\n\n const results = [];\n const root = this.beginNodes[len][0];\n const prev = root.prev;\n if (prev === null) {\n return [];\n }\n\n let node = prev.clone();\n while (node.prev !== null) {\n results.push(node.clone());\n const n = node.clone();\n node = n.prev.clone();\n }\n\n results.reverse();\n return results;\n }\n\n /**\n * @param {TokenLatticeNode} node\n * @returns {string} The array of nodes representing the most likely sequence of tokens.\n */\n piece(node) {\n return this.chars.slice(node.pos, node.pos + node.length).join('');\n }\n\n /**\n * @returns {string[]} The most likely sequence of tokens.\n */\n tokens() {\n const nodes = this.viterbi();\n return nodes.map(x => this.piece(x));\n }\n\n /**\n * @returns {number[]} The most likely sequence of token ids.\n */\n tokenIds() {\n const nodes = this.viterbi();\n return nodes.map(x => x.tokenId);\n }\n}\nclass TokenLatticeNode {\n /**\n * Represents a node in a token lattice for a given sentence.\n * @param {number} tokenId The ID of the token associated with this node.\n * @param {number} nodeId The ID of this node.\n * @param {number} pos The starting position of the token in the sentence.\n * @param {number} length The length of the token.\n * @param {number} score The score associated with the token.\n */\n constructor(tokenId, nodeId, pos, length, score) {\n this.tokenId = tokenId;\n this.nodeId = nodeId;\n this.pos = pos;\n this.length = length;\n this.score = score;\n this.prev = null;\n this.backtraceScore = 0.0;\n }\n\n /**\n * Returns a clone of this node.\n * @returns {TokenLatticeNode} A clone of this node.\n */\n clone() {\n const n = new TokenLatticeNode(this.tokenId, this.nodeId, this.pos, this.length, this.score);\n n.prev = this.prev;\n n.backtraceScore = this.backtraceScore;\n return n;\n }\n}\n","\n/**\n * The list of devices supported by Transformers.js\n */\nexport const DEVICE_TYPES = Object.freeze({\n auto: 'auto', // Auto-detect based on device and environment\n gpu: 'gpu', // Auto-detect GPU\n cpu: 'cpu', // CPU\n wasm: 'wasm', // WebAssembly\n webgpu: 'webgpu', // WebGPU\n cuda: 'cuda', // CUDA\n dml: 'dml', // DirectML\n\n webnn: 'webnn', // WebNN (default)\n 'webnn-npu': 'webnn-npu', // WebNN NPU\n 'webnn-gpu': 'webnn-gpu', // WebNN GPU\n 'webnn-cpu': 'webnn-cpu', // WebNN CPU\n});\n\n/**\n * @typedef {keyof typeof DEVICE_TYPES} DeviceType\n */\n","import { apis } from \"../env.js\";\n\nimport { DEVICE_TYPES } from \"./devices.js\";\n\n// TODO: Use the adapter from `env.backends.onnx.webgpu.adapter` to check for `shader-f16` support,\n// when available in https://github.com/microsoft/onnxruntime/pull/19940.\n// For more information, see https://github.com/microsoft/onnxruntime/pull/19857#issuecomment-1999984753\n\n/**\n * Checks if WebGPU fp16 support is available in the current environment.\n */\nexport const isWebGpuFp16Supported = (function () {\n /** @type {boolean} */\n let cachedResult;\n\n return async function () {\n if (cachedResult === undefined) {\n if (!apis.IS_WEBGPU_AVAILABLE) {\n cachedResult = false;\n } else {\n try {\n const adapter = await navigator.gpu.requestAdapter();\n cachedResult = adapter.features.has('shader-f16');\n } catch (e) {\n cachedResult = false;\n }\n }\n }\n return cachedResult;\n };\n})();\n\nexport const DATA_TYPES = Object.freeze({\n fp32: 'fp32',\n fp16: 'fp16',\n q8: 'q8',\n int8: 'int8',\n uint8: 'uint8',\n q4: 'q4',\n bnb4: 'bnb4',\n q4f16: 'q4f16', // fp16 model with int4 block weight quantization\n});\n/** @typedef {keyof typeof DATA_TYPES} DataType */\n\nexport const DEFAULT_DEVICE_DTYPE_MAPPING = Object.freeze({\n // NOTE: If not specified, will default to fp32\n [DEVICE_TYPES.wasm]: DATA_TYPES.q8,\n});\n\n/** @type {Record} */\nexport const DEFAULT_DTYPE_SUFFIX_MAPPING = Object.freeze({\n [DATA_TYPES.fp32]: '',\n [DATA_TYPES.fp16]: '_fp16',\n [DATA_TYPES.int8]: '_int8',\n [DATA_TYPES.uint8]: '_uint8',\n [DATA_TYPES.q8]: '_quantized',\n [DATA_TYPES.q4]: '_q4',\n [DATA_TYPES.q4f16]: '_q4f16',\n [DATA_TYPES.bnb4]: '_bnb4',\n});\n","\n/**\n * A base class for creating callable objects.\n * See [here](https://stackoverflow.com/q/76073890) for more information.\n * \n * @type {new () => {(...args: any[]): any, _call(...args: any[]): any}}\n */\nexport const Callable = /** @type {any} */ (class {\n /**\n * Creates a new instance of the Callable class.\n */\n constructor() {\n /**\n * Creates a closure that delegates to a private method '_call' with the given arguments.\n * @type {any}\n * @param {...any} args Zero or more arguments to pass to the '_call' method.\n * @returns {*} The result of calling the '_call' method.\n */\n let closure = function (...args) {\n return closure._call(...args)\n }\n return Object.setPrototypeOf(closure, new.target.prototype)\n }\n\n /**\n * This method should be implemented in subclasses to provide the\n * functionality of the callable object.\n *\n * @param {any[]} args\n * @throws {Error} If the subclass does not implement the `_call` method.\n */\n _call(...args) {\n throw Error('Must implement _call method in subclass')\n }\n});\n","\n/**\n * @file Utility functions to interact with the Hugging Face Hub (https://huggingface.co/models)\n * \n * @module utils/hub\n */\n\nimport fs from 'fs';\nimport path from 'path';\n\nimport { env } from '../env.js';\nimport { dispatchCallback } from './core.js';\n\n/**\n * @typedef {Object} PretrainedOptions Options for loading a pretrained model. \n * @property {function} [progress_callback=null] If specified, this function will be called during model construction, to provide the user with progress updates.\n * @property {import('../configs.js').PretrainedConfig} [config=null] Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when:\n * - The model is a model provided by the library (loaded with the *model id* string of a pretrained model).\n * - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a configuration JSON file named *config.json* is found in the directory.\n * @property {string} [cache_dir=null] Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.\n * @property {boolean} [local_files_only=false] Whether or not to only look at local files (e.g., not try downloading the model).\n * @property {string} [revision='main'] The specific model version to use. It can be a branch name, a tag name, or a commit id,\n * since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git.\n * NOTE: This setting is ignored for local requests.\n */\n\n/**\n * @typedef {Object} ModelSpecificPretrainedOptions Options for loading a pretrained model.\n * @property {string} [subfolder='onnx'] In case the relevant files are located inside a subfolder of the model repo on huggingface.co,\n * you can specify the folder name here.\n * @property {string} [model_file_name=null] If specified, load the model with this name (excluding the .onnx suffix). Currently only valid for encoder- or decoder-only models.\n * @property {import(\"./devices.js\").DeviceType|Record} [device=null] The device to run the model on. If not specified, the device will be chosen from the environment settings.\n * @property {import(\"./dtypes.js\").DataType|Record} [dtype=null] The data type to use for the model. If not specified, the data type will be chosen from the environment settings.\n * @property {boolean|Record} [use_external_data_format=false] Whether to load the model using the external data format (used for models >= 2GB in size).\n * @property {import('onnxruntime-common').InferenceSession.SessionOptions} [session_options] (Optional) User-specified session options passed to the runtime. If not provided, suitable defaults will be chosen.\n */\n\n/**\n * @typedef {PretrainedOptions & ModelSpecificPretrainedOptions} PretrainedModelOptions Options for loading a pretrained model.\n */\n\n/**\n * Mapping from file extensions to MIME types.\n */\nconst CONTENT_TYPE_MAP = {\n 'txt': 'text/plain',\n 'html': 'text/html',\n 'css': 'text/css',\n 'js': 'text/javascript',\n 'json': 'application/json',\n 'png': 'image/png',\n 'jpg': 'image/jpeg',\n 'jpeg': 'image/jpeg',\n 'gif': 'image/gif',\n}\nclass FileResponse {\n\n /**\n * Creates a new `FileResponse` object.\n * @param {string|URL} filePath\n */\n constructor(filePath) {\n this.filePath = filePath;\n this.headers = new Headers();\n\n this.exists = fs.existsSync(filePath);\n if (this.exists) {\n this.status = 200;\n this.statusText = 'OK';\n\n let stats = fs.statSync(filePath);\n this.headers.set('content-length', stats.size.toString());\n\n this.updateContentType();\n\n let self = this;\n this.body = new ReadableStream({\n start(controller) {\n self.arrayBuffer().then(buffer => {\n controller.enqueue(new Uint8Array(buffer));\n controller.close();\n })\n }\n });\n } else {\n this.status = 404;\n this.statusText = 'Not Found';\n this.body = null;\n }\n }\n\n /**\n * Updates the 'content-type' header property of the response based on the extension of\n * the file specified by the filePath property of the current object.\n * @returns {void}\n */\n updateContentType() {\n // Set content-type header based on file extension\n const extension = this.filePath.toString().split('.').pop().toLowerCase();\n this.headers.set('content-type', CONTENT_TYPE_MAP[extension] ?? 'application/octet-stream');\n }\n\n /**\n * Clone the current FileResponse object.\n * @returns {FileResponse} A new FileResponse object with the same properties as the current object.\n */\n clone() {\n let response = new FileResponse(this.filePath);\n response.exists = this.exists;\n response.status = this.status;\n response.statusText = this.statusText;\n response.headers = new Headers(this.headers);\n return response;\n }\n\n /**\n * Reads the contents of the file specified by the filePath property and returns a Promise that\n * resolves with an ArrayBuffer containing the file's contents.\n * @returns {Promise} A Promise that resolves with an ArrayBuffer containing the file's contents.\n * @throws {Error} If the file cannot be read.\n */\n async arrayBuffer() {\n const data = await fs.promises.readFile(this.filePath);\n return data.buffer;\n }\n\n /**\n * Reads the contents of the file specified by the filePath property and returns a Promise that\n * resolves with a Blob containing the file's contents.\n * @returns {Promise} A Promise that resolves with a Blob containing the file's contents.\n * @throws {Error} If the file cannot be read.\n */\n async blob() {\n const data = await fs.promises.readFile(this.filePath);\n return new Blob([data], { type: this.headers.get('content-type') });\n }\n\n /**\n * Reads the contents of the file specified by the filePath property and returns a Promise that\n * resolves with a string containing the file's contents.\n * @returns {Promise} A Promise that resolves with a string containing the file's contents.\n * @throws {Error} If the file cannot be read.\n */\n async text() {\n const data = await fs.promises.readFile(this.filePath, 'utf8');\n return data;\n }\n\n /**\n * Reads the contents of the file specified by the filePath property and returns a Promise that\n * resolves with a parsed JavaScript object containing the file's contents.\n * \n * @returns {Promise} A Promise that resolves with a parsed JavaScript object containing the file's contents.\n * @throws {Error} If the file cannot be read.\n */\n async json() {\n return JSON.parse(await this.text());\n }\n}\n\n/**\n * Determines whether the given string is a valid URL.\n * @param {string|URL} string The string to test for validity as an URL.\n * @param {string[]} [protocols=null] A list of valid protocols. If specified, the protocol must be in this list.\n * @param {string[]} [validHosts=null] A list of valid hostnames. If specified, the URL's hostname must be in this list.\n * @returns {boolean} True if the string is a valid URL, false otherwise.\n */\nfunction isValidUrl(string, protocols = null, validHosts = null) {\n let url;\n try {\n url = new URL(string);\n } catch (_) {\n return false;\n }\n if (protocols && !protocols.includes(url.protocol)) {\n return false;\n }\n if (validHosts && !validHosts.includes(url.hostname)) {\n return false;\n }\n return true;\n}\n\n/**\n * Helper function to get a file, using either the Fetch API or FileSystem API.\n *\n * @param {URL|string} urlOrPath The URL/path of the file to get.\n * @returns {Promise} A promise that resolves to a FileResponse object (if the file is retrieved using the FileSystem API), or a Response object (if the file is retrieved using the Fetch API).\n */\nexport async function getFile(urlOrPath) {\n\n if (env.useFS && !isValidUrl(urlOrPath, ['http:', 'https:', 'blob:'])) {\n return new FileResponse(urlOrPath);\n\n } else if (typeof process !== 'undefined' && process?.release?.name === 'node') {\n const IS_CI = !!process.env?.TESTING_REMOTELY;\n const version = env.version;\n\n const headers = new Headers();\n headers.set('User-Agent', `transformers.js/${version}; is_ci/${IS_CI};`);\n\n // Check whether we are making a request to the Hugging Face Hub.\n const isHFURL = isValidUrl(urlOrPath, ['http:', 'https:'], ['huggingface.co', 'hf.co']);\n if (isHFURL) {\n // If an access token is present in the environment variables,\n // we add it to the request headers.\n // NOTE: We keep `HF_ACCESS_TOKEN` for backwards compatibility (as a fallback).\n const token = process.env?.HF_TOKEN ?? process.env?.HF_ACCESS_TOKEN;\n if (token) {\n headers.set('Authorization', `Bearer ${token}`);\n }\n }\n return fetch(urlOrPath, { headers });\n } else {\n // Running in a browser-environment, so we use default headers\n // NOTE: We do not allow passing authorization headers in the browser,\n // since this would require exposing the token to the client.\n return fetch(urlOrPath);\n }\n}\n\nconst ERROR_MAPPING = {\n // 4xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses)\n 400: 'Bad request error occurred while trying to load file',\n 401: 'Unauthorized access to file',\n 403: 'Forbidden access to file',\n 404: 'Could not locate file',\n 408: 'Request timeout error occurred while trying to load file',\n\n // 5xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses)\n 500: 'Internal server error error occurred while trying to load file',\n 502: 'Bad gateway error occurred while trying to load file',\n 503: 'Service unavailable error occurred while trying to load file',\n 504: 'Gateway timeout error occurred while trying to load file',\n}\n/**\n * Helper method to handle fatal errors that occur while trying to load a file from the Hugging Face Hub.\n * @param {number} status The HTTP status code of the error.\n * @param {string} remoteURL The URL of the file that could not be loaded.\n * @param {boolean} fatal Whether to raise an error if the file could not be loaded.\n * @returns {null} Returns `null` if `fatal = true`.\n * @throws {Error} If `fatal = false`.\n */\nfunction handleError(status, remoteURL, fatal) {\n if (!fatal) {\n // File was not loaded correctly, but it is optional.\n // TODO in future, cache the response?\n return null;\n }\n\n const message = ERROR_MAPPING[status] ?? `Error (${status}) occurred while trying to load file`;\n throw Error(`${message}: \"${remoteURL}\".`);\n}\n\nclass FileCache {\n /**\n * Instantiate a `FileCache` object.\n * @param {string} path \n */\n constructor(path) {\n this.path = path;\n }\n\n /**\n * Checks whether the given request is in the cache.\n * @param {string} request \n * @returns {Promise}\n */\n async match(request) {\n\n let filePath = path.join(this.path, request);\n let file = new FileResponse(filePath);\n\n if (file.exists) {\n return file;\n } else {\n return undefined;\n }\n }\n\n /**\n * Adds the given response to the cache.\n * @param {string} request \n * @param {Response|FileResponse} response \n * @returns {Promise}\n */\n async put(request, response) {\n const buffer = Buffer.from(await response.arrayBuffer());\n\n let outputPath = path.join(this.path, request);\n\n try {\n await fs.promises.mkdir(path.dirname(outputPath), { recursive: true });\n await fs.promises.writeFile(outputPath, buffer);\n\n } catch (err) {\n console.warn('An error occurred while writing the file to cache:', err)\n }\n }\n\n // TODO add the rest?\n // addAll(requests: RequestInfo[]): Promise;\n // delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise;\n // keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>;\n // match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise;\n // matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>;\n}\n\n/**\n * \n * @param {FileCache|Cache} cache The cache to search\n * @param {string[]} names The names of the item to search for\n * @returns {Promise} The item from the cache, or undefined if not found.\n */\nasync function tryCache(cache, ...names) {\n for (let name of names) {\n try {\n let result = await cache.match(name);\n if (result) return result;\n } catch (e) {\n continue;\n }\n }\n return undefined;\n}\n\n/**\n * \n * Retrieves a file from either a remote URL using the Fetch API or from the local file system using the FileSystem API.\n * If the filesystem is available and `env.useCache = true`, the file will be downloaded and cached.\n * \n * @param {string} path_or_repo_id This can be either:\n * - a string, the *model id* of a model repo on huggingface.co.\n * - a path to a *directory* potentially containing the file.\n * @param {string} filename The name of the file to locate in `path_or_repo`.\n * @param {boolean} [fatal=true] Whether to throw an error if the file is not found.\n * @param {PretrainedOptions} [options] An object containing optional parameters.\n * \n * @throws Will throw an error if the file is not found and `fatal` is true.\n * @returns {Promise} A Promise that resolves with the file content as a buffer.\n */\nexport async function getModelFile(path_or_repo_id, filename, fatal = true, options = {}) {\n\n if (!env.allowLocalModels) {\n // User has disabled local models, so we just make sure other settings are correct.\n\n if (options.local_files_only) {\n throw Error(\"Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).\")\n } else if (!env.allowRemoteModels) {\n throw Error(\"Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.\")\n }\n }\n\n // Initiate file retrieval\n dispatchCallback(options.progress_callback, {\n status: 'initiate',\n name: path_or_repo_id,\n file: filename\n })\n\n // First, check if the a caching backend is available\n // If no caching mechanism available, will download the file every time\n let cache;\n if (!cache && env.useBrowserCache) {\n if (typeof caches === 'undefined') {\n throw Error('Browser cache is not available in this environment.')\n }\n try {\n // In some cases, the browser cache may be visible, but not accessible due to security restrictions.\n // For example, when running an application in an iframe, if a user attempts to load the page in\n // incognito mode, the following error is thrown: `DOMException: Failed to execute 'open' on 'CacheStorage':\n // An attempt was made to break through the security policy of the user agent.`\n // So, instead of crashing, we just ignore the error and continue without using the cache.\n cache = await caches.open('transformers-cache');\n } catch (e) {\n console.warn('An error occurred while opening the browser cache:', e);\n }\n }\n\n if (!cache && env.useFSCache) {\n // TODO throw error if not available\n\n // If `cache_dir` is not specified, use the default cache directory\n cache = new FileCache(options.cache_dir ?? env.cacheDir);\n }\n\n if (!cache && env.useCustomCache) {\n // Allow the user to specify a custom cache system.\n if (!env.customCache) {\n throw Error('`env.useCustomCache=true`, but `env.customCache` is not defined.')\n }\n\n // Check that the required methods are defined:\n if (!env.customCache.match || !env.customCache.put) {\n throw new Error(\n \"`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. \" +\n \"For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache\"\n )\n }\n cache = env.customCache;\n }\n\n const revision = options.revision ?? 'main';\n\n let requestURL = pathJoin(path_or_repo_id, filename);\n let localPath = pathJoin(env.localModelPath, requestURL);\n\n let remoteURL = pathJoin(\n env.remoteHost,\n env.remotePathTemplate\n .replaceAll('{model}', path_or_repo_id)\n .replaceAll('{revision}', encodeURIComponent(revision)),\n filename\n );\n\n // Choose cache key for filesystem cache\n // When using the main revision (default), we use the request URL as the cache key.\n // If a specific revision is requested, we account for this in the cache key.\n let fsCacheKey = revision === 'main' ? requestURL : pathJoin(path_or_repo_id, revision, filename);\n\n /** @type {string} */\n let cacheKey;\n let proposedCacheKey = cache instanceof FileCache ? fsCacheKey : remoteURL;\n\n // Whether to cache the final response in the end.\n let toCacheResponse = false;\n\n /** @type {Response|FileResponse|undefined} */\n let response;\n\n if (cache) {\n // A caching system is available, so we try to get the file from it.\n // 1. We first try to get from cache using the local path. In some environments (like deno),\n // non-URL cache keys are not allowed. In these cases, `response` will be undefined.\n // 2. If no response is found, we try to get from cache using the remote URL or file system cache.\n response = await tryCache(cache, localPath, proposedCacheKey);\n }\n\n const cacheHit = response !== undefined;\n\n if (response === undefined) {\n // Caching not available, or file is not cached, so we perform the request\n\n if (env.allowLocalModels) {\n // Accessing local models is enabled, so we try to get the file locally.\n // If request is a valid HTTP URL, we skip the local file check. Otherwise, we try to get the file locally.\n const isURL = isValidUrl(requestURL, ['http:', 'https:']);\n if (!isURL) {\n try {\n response = await getFile(localPath);\n cacheKey = localPath; // Update the cache key to be the local path\n } catch (e) {\n // Something went wrong while trying to get the file locally.\n // NOTE: error handling is done in the next step (since `response` will be undefined)\n console.warn(`Unable to load from local path \"${localPath}\": \"${e}\"`);\n }\n } else if (options.local_files_only) {\n throw new Error(`\\`local_files_only=true\\`, but attempted to load a remote file from: ${requestURL}.`);\n } else if (!env.allowRemoteModels) {\n throw new Error(`\\`env.allowRemoteModels=false\\`, but attempted to load a remote file from: ${requestURL}.`);\n }\n }\n\n if (response === undefined || response.status === 404) {\n // File not found locally. This means either:\n // - The user has disabled local file access (`env.allowLocalModels=false`)\n // - the path is a valid HTTP url (`response === undefined`)\n // - the path is not a valid HTTP url and the file is not present on the file system or local server (`response.status === 404`)\n\n if (options.local_files_only || !env.allowRemoteModels) {\n // User requested local files only, but the file is not found locally.\n if (fatal) {\n throw Error(`\\`local_files_only=true\\` or \\`env.allowRemoteModels=false\\` and file was not found locally at \"${localPath}\".`);\n } else {\n // File not found, but this file is optional.\n // TODO in future, cache the response?\n return null;\n }\n }\n\n // File not found locally, so we try to download it from the remote server\n response = await getFile(remoteURL);\n\n if (response.status !== 200) {\n return handleError(response.status, remoteURL, fatal);\n }\n\n // Success! We use the proposed cache key from earlier\n cacheKey = proposedCacheKey;\n }\n\n // Only cache the response if:\n toCacheResponse =\n cache // 1. A caching system is available\n && typeof Response !== 'undefined' // 2. `Response` is defined (i.e., we are in a browser-like environment)\n && response instanceof Response // 3. result is a `Response` object (i.e., not a `FileResponse`)\n && response.status === 200 // 4. request was successful (status code 200)\n }\n\n // Start downloading\n dispatchCallback(options.progress_callback, {\n status: 'download',\n name: path_or_repo_id,\n file: filename\n })\n\n const progressInfo = {\n status: 'progress',\n name: path_or_repo_id,\n file: filename\n }\n\n /** @type {Uint8Array} */\n let buffer;\n\n if (!options.progress_callback) {\n // If no progress callback is specified, we can use the `.arrayBuffer()`\n // method to read the response.\n buffer = new Uint8Array(await response.arrayBuffer());\n\n } else if (\n cacheHit // The item is being read from the cache\n &&\n typeof navigator !== 'undefined' && /firefox/i.test(navigator.userAgent) // We are in Firefox\n ) {\n // Due to bug in Firefox, we cannot display progress when loading from cache.\n // Fortunately, since this should be instantaneous, this should not impact users too much.\n buffer = new Uint8Array(await response.arrayBuffer());\n\n // For completeness, we still fire the final progress callback\n dispatchCallback(options.progress_callback, {\n ...progressInfo,\n progress: 100,\n loaded: buffer.length,\n total: buffer.length,\n })\n } else {\n buffer = await readResponse(response, data => {\n dispatchCallback(options.progress_callback, {\n ...progressInfo,\n ...data,\n })\n })\n }\n\n if (\n // Only cache web responses\n // i.e., do not cache FileResponses (prevents duplication)\n toCacheResponse && cacheKey\n &&\n // Check again whether request is in cache. If not, we add the response to the cache\n (await cache.match(cacheKey) === undefined)\n ) {\n // NOTE: We use `new Response(buffer, ...)` instead of `response.clone()` to handle LFS files\n await cache.put(cacheKey, new Response(buffer, {\n headers: response.headers\n }))\n .catch(err => {\n // Do not crash if unable to add to cache (e.g., QuotaExceededError).\n // Rather, log a warning and proceed with execution.\n console.warn(`Unable to add response to browser cache: ${err}.`);\n });\n\n }\n\n dispatchCallback(options.progress_callback, {\n status: 'done',\n name: path_or_repo_id,\n file: filename\n });\n\n return buffer;\n}\n\n/**\n * Fetches a JSON file from a given path and file name.\n *\n * @param {string} modelPath The path to the directory containing the file.\n * @param {string} fileName The name of the file to fetch.\n * @param {boolean} [fatal=true] Whether to throw an error if the file is not found.\n * @param {PretrainedOptions} [options] An object containing optional parameters.\n * @returns {Promise} The JSON data parsed into a JavaScript object.\n * @throws Will throw an error if the file is not found and `fatal` is true.\n */\nexport async function getModelJSON(modelPath, fileName, fatal = true, options = {}) {\n let buffer = await getModelFile(modelPath, fileName, fatal, options);\n if (buffer === null) {\n // Return empty object\n return {}\n }\n\n let decoder = new TextDecoder('utf-8');\n let jsonData = decoder.decode(buffer);\n\n return JSON.parse(jsonData);\n}\n\n/**\n * Read and track progress when reading a Response object\n *\n * @param {any} response The Response object to read\n * @param {function} progress_callback The function to call with progress updates\n * @returns {Promise} A Promise that resolves with the Uint8Array buffer\n */\nasync function readResponse(response, progress_callback) {\n\n const contentLength = response.headers.get('Content-Length');\n if (contentLength === null) {\n console.warn('Unable to determine content-length from response headers. Will expand buffer when needed.')\n }\n let total = parseInt(contentLength ?? '0');\n let buffer = new Uint8Array(total);\n let loaded = 0;\n\n const reader = response.body.getReader();\n async function read() {\n const { done, value } = await reader.read();\n if (done) return;\n\n let newLoaded = loaded + value.length;\n if (newLoaded > total) {\n total = newLoaded;\n\n // Adding the new data will overflow buffer.\n // In this case, we extend the buffer\n let newBuffer = new Uint8Array(total);\n\n // copy contents\n newBuffer.set(buffer);\n\n buffer = newBuffer;\n }\n buffer.set(value, loaded)\n loaded = newLoaded;\n\n const progress = (loaded / total) * 100;\n\n // Call your function here\n progress_callback({\n progress: progress,\n loaded: loaded,\n total: total,\n })\n\n return read();\n }\n\n // Actually read\n await read();\n\n return buffer;\n}\n\n/**\n * Joins multiple parts of a path into a single path, while handling leading and trailing slashes.\n *\n * @param {...string} parts Multiple parts of a path.\n * @returns {string} A string representing the joined path.\n */\nfunction pathJoin(...parts) {\n // https://stackoverflow.com/a/55142565\n parts = parts.map((part, index) => {\n if (index) {\n part = part.replace(new RegExp('^/'), '');\n }\n if (index !== parts.length - 1) {\n part = part.replace(new RegExp('/$'), '');\n }\n return part;\n })\n return parts.join('/');\n}\n","\n/**\n * @file Helper module for image processing. \n * \n * These functions and classes are only used internally, \n * meaning an end-user shouldn't need to access anything here.\n * \n * @module utils/image\n */\n\nimport { getFile } from './hub.js';\nimport { env } from '../env.js';\nimport { Tensor } from './tensor.js';\n\n// Will be empty (or not used) if running in browser or web-worker\nimport sharp from 'sharp';\n\nconst BROWSER_ENV = typeof self !== 'undefined';\nconst WEBWORKER_ENV = BROWSER_ENV && self.constructor.name === 'DedicatedWorkerGlobalScope';\n\nlet createCanvasFunction;\nlet ImageDataClass;\nlet loadImageFunction;\nif (BROWSER_ENV) {\n // Running in browser or web-worker\n createCanvasFunction = (/** @type {number} */ width, /** @type {number} */ height) => {\n if (!self.OffscreenCanvas) {\n throw new Error('OffscreenCanvas not supported by this browser.');\n }\n return new self.OffscreenCanvas(width, height)\n };\n loadImageFunction = self.createImageBitmap;\n ImageDataClass = self.ImageData;\n\n} else if (sharp) {\n // Running in Node.js, electron, or other non-browser environment\n\n loadImageFunction = async (/**@type {sharp.Sharp}*/img) => {\n const metadata = await img.metadata();\n const rawChannels = metadata.channels;\n\n const { data, info } = await img.rotate().raw().toBuffer({ resolveWithObject: true });\n\n const newImage = new RawImage(new Uint8ClampedArray(data), info.width, info.height, info.channels);\n if (rawChannels !== undefined && rawChannels !== info.channels) {\n // Make sure the new image has the same number of channels as the input image.\n // This is necessary for grayscale images.\n newImage.convert(rawChannels);\n }\n return newImage;\n }\n\n} else {\n throw new Error('Unable to load image processing library.');\n}\n\n\n// Defined here: https://github.com/python-pillow/Pillow/blob/a405e8406b83f8bfb8916e93971edc7407b8b1ff/src/libImaging/Imaging.h#L262-L268\nconst RESAMPLING_MAPPING = {\n 0: 'nearest',\n 1: 'lanczos',\n 2: 'bilinear',\n 3: 'bicubic',\n 4: 'box',\n 5: 'hamming',\n}\n\n/**\n * Mapping from file extensions to MIME types.\n */\nconst CONTENT_TYPE_MAP = new Map([\n ['png', 'image/png'],\n ['jpg', 'image/jpeg'],\n ['jpeg', 'image/jpeg'],\n ['gif', 'image/gif'],\n]);\n\nexport class RawImage {\n\n /**\n * Create a new `RawImage` object.\n * @param {Uint8ClampedArray|Uint8Array} data The pixel data.\n * @param {number} width The width of the image.\n * @param {number} height The height of the image.\n * @param {1|2|3|4} channels The number of channels.\n */\n constructor(data, width, height, channels) {\n this.data = data;\n this.width = width;\n this.height = height;\n this.channels = channels;\n }\n\n /** \n * Returns the size of the image (width, height).\n * @returns {[number, number]} The size of the image (width, height).\n */\n get size() {\n return [this.width, this.height];\n }\n\n /**\n * Helper method for reading an image from a variety of input types.\n * @param {RawImage|string|URL} input \n * @returns The image object.\n * \n * **Example:** Read image from a URL.\n * ```javascript\n * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * // RawImage {\n * // \"data\": Uint8ClampedArray [ 25, 25, 25, 19, 19, 19, ... ],\n * // \"width\": 800,\n * // \"height\": 533,\n * // \"channels\": 3\n * // }\n * ```\n */\n static async read(input) {\n if (input instanceof RawImage) {\n return input;\n } else if (typeof input === 'string' || input instanceof URL) {\n return await this.fromURL(input);\n } else {\n throw new Error(`Unsupported input type: ${typeof input}`);\n }\n }\n\n /**\n * Read an image from a canvas.\n * @param {HTMLCanvasElement|OffscreenCanvas} canvas The canvas to read the image from.\n * @returns {RawImage} The image object.\n */\n static fromCanvas(canvas) {\n if (!BROWSER_ENV) {\n throw new Error('fromCanvas() is only supported in browser environments.')\n }\n\n const ctx = canvas.getContext('2d');\n const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;\n return new RawImage(data, canvas.width, canvas.height, 4);\n }\n\n /**\n * Read an image from a URL or file path.\n * @param {string|URL} url The URL or file path to read the image from.\n * @returns {Promise} The image object.\n */\n static async fromURL(url) {\n const response = await getFile(url);\n if (response.status !== 200) {\n throw new Error(`Unable to read image from \"${url}\" (${response.status} ${response.statusText})`);\n }\n const blob = await response.blob();\n return this.fromBlob(blob);\n }\n\n /**\n * Helper method to create a new Image from a blob.\n * @param {Blob} blob The blob to read the image from.\n * @returns {Promise} The image object.\n */\n static async fromBlob(blob) {\n if (BROWSER_ENV) {\n // Running in environment with canvas\n const img = await loadImageFunction(blob);\n\n const ctx = createCanvasFunction(img.width, img.height).getContext('2d');\n\n // Draw image to context\n ctx.drawImage(img, 0, 0);\n\n return new this(ctx.getImageData(0, 0, img.width, img.height).data, img.width, img.height, 4);\n\n } else {\n // Use sharp.js to read (and possible resize) the image.\n const img = sharp(await blob.arrayBuffer());\n\n return await loadImageFunction(img);\n }\n }\n\n /**\n * Helper method to create a new Image from a tensor\n * @param {Tensor} tensor \n */\n static fromTensor(tensor, channel_format = 'CHW') {\n if (tensor.dims.length !== 3) {\n throw new Error(`Tensor should have 3 dimensions, but has ${tensor.dims.length} dimensions.`);\n }\n\n if (channel_format === 'CHW') {\n tensor = tensor.transpose(1, 2, 0);\n } else if (channel_format === 'HWC') {\n // Do nothing\n } else {\n throw new Error(`Unsupported channel format: ${channel_format}`);\n }\n if (!(tensor.data instanceof Uint8ClampedArray || tensor.data instanceof Uint8Array)) {\n throw new Error(`Unsupported tensor type: ${tensor.type}`);\n }\n switch (tensor.dims[2]) {\n case 1:\n case 2:\n case 3:\n case 4:\n return new RawImage(tensor.data, tensor.dims[1], tensor.dims[0], tensor.dims[2]);\n default:\n throw new Error(`Unsupported number of channels: ${tensor.dims[2]}`);\n }\n }\n\n /**\n * Convert the image to grayscale format.\n * @returns {RawImage} `this` to support chaining.\n */\n grayscale() {\n if (this.channels === 1) {\n return this;\n }\n\n const newData = new Uint8ClampedArray(this.width * this.height * 1);\n switch (this.channels) {\n case 3: // rgb to grayscale\n case 4: // rgba to grayscale\n for (let i = 0, offset = 0; i < this.data.length; i += this.channels) {\n const red = this.data[i];\n const green = this.data[i + 1];\n const blue = this.data[i + 2];\n\n newData[offset++] = Math.round(0.2989 * red + 0.5870 * green + 0.1140 * blue);\n }\n break;\n default:\n throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);\n }\n return this._update(newData, this.width, this.height, 1);\n }\n\n /**\n * Convert the image to RGB format.\n * @returns {RawImage} `this` to support chaining.\n */\n rgb() {\n if (this.channels === 3) {\n return this;\n }\n\n const newData = new Uint8ClampedArray(this.width * this.height * 3);\n\n switch (this.channels) {\n case 1: // grayscale to rgb\n for (let i = 0, offset = 0; i < this.data.length; ++i) {\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i];\n }\n break;\n case 4: // rgba to rgb\n for (let i = 0, offset = 0; i < this.data.length; i += 4) {\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i + 1];\n newData[offset++] = this.data[i + 2];\n }\n break;\n default:\n throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);\n }\n return this._update(newData, this.width, this.height, 3);\n\n }\n\n /**\n * Convert the image to RGBA format.\n * @returns {RawImage} `this` to support chaining.\n */\n rgba() {\n if (this.channels === 4) {\n return this;\n }\n\n const newData = new Uint8ClampedArray(this.width * this.height * 4);\n\n switch (this.channels) {\n case 1: // grayscale to rgba\n for (let i = 0, offset = 0; i < this.data.length; ++i) {\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i];\n newData[offset++] = 255;\n }\n break;\n case 3: // rgb to rgba\n for (let i = 0, offset = 0; i < this.data.length; i += 3) {\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i + 1];\n newData[offset++] = this.data[i + 2];\n newData[offset++] = 255;\n }\n break;\n default:\n throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);\n }\n\n return this._update(newData, this.width, this.height, 4);\n }\n\n /**\n * Resize the image to the given dimensions. This method uses the canvas API to perform the resizing.\n * @param {number} width The width of the new image.\n * @param {number} height The height of the new image.\n * @param {Object} options Additional options for resizing.\n * @param {0|1|2|3|4|5|string} [options.resample] The resampling method to use.\n * @returns {Promise} `this` to support chaining.\n */\n async resize(width, height, {\n resample = 2,\n } = {}) {\n\n // Ensure resample method is a string\n let resampleMethod = RESAMPLING_MAPPING[resample] ?? resample;\n\n if (BROWSER_ENV) {\n // TODO use `resample` in browser environment\n\n // Store number of channels before resizing\n const numChannels = this.channels;\n\n // Create canvas object for this image\n const canvas = this.toCanvas();\n\n // Actually perform resizing using the canvas API\n const ctx = createCanvasFunction(width, height).getContext('2d');\n\n // Draw image to context, resizing in the process\n ctx.drawImage(canvas, 0, 0, width, height);\n\n // Create image from the resized data\n const resizedImage = new RawImage(ctx.getImageData(0, 0, width, height).data, width, height, 4);\n\n // Convert back so that image has the same number of channels as before\n return resizedImage.convert(numChannels);\n\n } else {\n // Create sharp image from raw data, and resize\n let img = this.toSharp();\n\n switch (resampleMethod) {\n case 'box':\n case 'hamming':\n if (resampleMethod === 'box' || resampleMethod === 'hamming') {\n console.warn(`Resampling method ${resampleMethod} is not yet supported. Using bilinear instead.`);\n resampleMethod = 'bilinear';\n }\n\n case 'nearest':\n case 'bilinear':\n case 'bicubic':\n // Perform resizing using affine transform. \n // This matches how the python Pillow library does it.\n img = img.affine([width / this.width, 0, 0, height / this.height], {\n interpolator: resampleMethod\n });\n break;\n\n case 'lanczos':\n // https://github.com/python-pillow/Pillow/discussions/5519\n // https://github.com/lovell/sharp/blob/main/docs/api-resize.md\n img = img.resize({\n width, height,\n fit: 'fill',\n kernel: 'lanczos3', // PIL Lanczos uses a kernel size of 3 \n });\n break;\n\n default:\n throw new Error(`Resampling method ${resampleMethod} is not supported.`);\n }\n\n return await loadImageFunction(img);\n }\n\n }\n\n async pad([left, right, top, bottom]) {\n left = Math.max(left, 0);\n right = Math.max(right, 0);\n top = Math.max(top, 0);\n bottom = Math.max(bottom, 0);\n\n if (left === 0 && right === 0 && top === 0 && bottom === 0) {\n // No padding needed\n return this;\n }\n\n if (BROWSER_ENV) {\n // Store number of channels before padding\n const numChannels = this.channels;\n\n // Create canvas object for this image\n const canvas = this.toCanvas();\n\n const newWidth = this.width + left + right;\n const newHeight = this.height + top + bottom;\n\n // Create a new canvas of the desired size.\n const ctx = createCanvasFunction(newWidth, newHeight).getContext('2d');\n\n // Draw image to context, padding in the process\n ctx.drawImage(canvas,\n 0, 0, this.width, this.height,\n left, top, newWidth, newHeight\n );\n\n // Create image from the padded data\n const paddedImage = new RawImage(\n ctx.getImageData(0, 0, newWidth, newHeight).data,\n newWidth, newHeight, 4);\n\n // Convert back so that image has the same number of channels as before\n return paddedImage.convert(numChannels);\n\n } else {\n const img = this.toSharp().extend({ left, right, top, bottom });\n return await loadImageFunction(img);\n }\n }\n\n async crop([x_min, y_min, x_max, y_max]) {\n // Ensure crop bounds are within the image\n x_min = Math.max(x_min, 0);\n y_min = Math.max(y_min, 0);\n x_max = Math.min(x_max, this.width - 1);\n y_max = Math.min(y_max, this.height - 1);\n\n // Do nothing if the crop is the entire image\n if (x_min === 0 && y_min === 0 && x_max === this.width - 1 && y_max === this.height - 1) {\n return this;\n }\n\n const crop_width = x_max - x_min + 1;\n const crop_height = y_max - y_min + 1;\n\n if (BROWSER_ENV) {\n // Store number of channels before resizing\n const numChannels = this.channels;\n\n // Create canvas object for this image\n const canvas = this.toCanvas();\n\n // Create a new canvas of the desired size. This is needed since if the \n // image is too small, we need to pad it with black pixels.\n const ctx = createCanvasFunction(crop_width, crop_height).getContext('2d');\n\n // Draw image to context, cropping in the process\n ctx.drawImage(canvas,\n x_min, y_min, crop_width, crop_height,\n 0, 0, crop_width, crop_height\n );\n\n // Create image from the resized data\n const resizedImage = new RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4);\n\n // Convert back so that image has the same number of channels as before\n return resizedImage.convert(numChannels);\n\n } else {\n // Create sharp image from raw data\n const img = this.toSharp().extract({\n left: x_min,\n top: y_min,\n width: crop_width,\n height: crop_height,\n });\n\n return await loadImageFunction(img);\n }\n\n }\n\n async center_crop(crop_width, crop_height) {\n // If the image is already the desired size, return it\n if (this.width === crop_width && this.height === crop_height) {\n return this;\n }\n\n // Determine bounds of the image in the new canvas\n const width_offset = (this.width - crop_width) / 2;\n const height_offset = (this.height - crop_height) / 2;\n\n\n if (BROWSER_ENV) {\n // Store number of channels before resizing\n const numChannels = this.channels;\n\n // Create canvas object for this image\n const canvas = this.toCanvas();\n\n // Create a new canvas of the desired size. This is needed since if the \n // image is too small, we need to pad it with black pixels.\n const ctx = createCanvasFunction(crop_width, crop_height).getContext('2d');\n\n let sourceX = 0;\n let sourceY = 0;\n let destX = 0;\n let destY = 0;\n\n if (width_offset >= 0) {\n sourceX = width_offset;\n } else {\n destX = -width_offset;\n }\n\n if (height_offset >= 0) {\n sourceY = height_offset;\n } else {\n destY = -height_offset;\n }\n\n // Draw image to context, cropping in the process\n ctx.drawImage(canvas,\n sourceX, sourceY, crop_width, crop_height,\n destX, destY, crop_width, crop_height\n );\n\n // Create image from the resized data\n const resizedImage = new RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4);\n\n // Convert back so that image has the same number of channels as before\n return resizedImage.convert(numChannels);\n\n } else {\n // Create sharp image from raw data\n let img = this.toSharp();\n\n if (width_offset >= 0 && height_offset >= 0) {\n // Cropped image lies entirely within the original image\n img = img.extract({\n left: Math.floor(width_offset),\n top: Math.floor(height_offset),\n width: crop_width,\n height: crop_height,\n })\n } else if (width_offset <= 0 && height_offset <= 0) {\n // Cropped image lies entirely outside the original image,\n // so we add padding\n const top = Math.floor(-height_offset);\n const left = Math.floor(-width_offset);\n img = img.extend({\n top: top,\n left: left,\n\n // Ensures the resulting image has the desired dimensions\n right: crop_width - this.width - left,\n bottom: crop_height - this.height - top,\n });\n } else {\n // Cropped image lies partially outside the original image.\n // We first pad, then crop.\n\n let y_padding = [0, 0];\n let y_extract = 0;\n if (height_offset < 0) {\n y_padding[0] = Math.floor(-height_offset);\n y_padding[1] = crop_height - this.height - y_padding[0];\n } else {\n y_extract = Math.floor(height_offset);\n }\n\n let x_padding = [0, 0];\n let x_extract = 0;\n if (width_offset < 0) {\n x_padding[0] = Math.floor(-width_offset);\n x_padding[1] = crop_width - this.width - x_padding[0];\n } else {\n x_extract = Math.floor(width_offset);\n }\n\n img = img.extend({\n top: y_padding[0],\n bottom: y_padding[1],\n left: x_padding[0],\n right: x_padding[1],\n }).extract({\n left: x_extract,\n top: y_extract,\n width: crop_width,\n height: crop_height,\n })\n }\n\n return await loadImageFunction(img);\n }\n }\n\n async toBlob(type = 'image/png', quality = 1) {\n if (!BROWSER_ENV) {\n throw new Error('toBlob() is only supported in browser environments.')\n }\n\n const canvas = this.toCanvas();\n return await canvas.convertToBlob({ type, quality });\n }\n\n toTensor(channel_format = 'CHW') {\n let tensor = new Tensor(\n 'uint8',\n new Uint8Array(this.data),\n [this.height, this.width, this.channels]\n );\n\n if (channel_format === 'HWC') {\n // Do nothing\n } else if (channel_format === 'CHW') { // hwc -> chw\n tensor = tensor.permute(2, 0, 1);\n } else {\n throw new Error(`Unsupported channel format: ${channel_format}`);\n }\n return tensor;\n }\n\n toCanvas() {\n if (!BROWSER_ENV) {\n throw new Error('toCanvas() is only supported in browser environments.')\n }\n\n // Clone, and convert data to RGBA before drawing to canvas.\n // This is because the canvas API only supports RGBA\n const cloned = this.clone().rgba();\n\n // Create canvas object for the cloned image\n const clonedCanvas = createCanvasFunction(cloned.width, cloned.height);\n\n // Draw image to context\n const data = new ImageDataClass(cloned.data, cloned.width, cloned.height);\n clonedCanvas.getContext('2d').putImageData(data, 0, 0);\n\n return clonedCanvas;\n }\n\n /**\n * Helper method to update the image data.\n * @param {Uint8ClampedArray} data The new image data.\n * @param {number} width The new width of the image.\n * @param {number} height The new height of the image.\n * @param {1|2|3|4|null} [channels] The new number of channels of the image.\n * @private\n */\n _update(data, width, height, channels = null) {\n this.data = data;\n this.width = width;\n this.height = height;\n if (channels !== null) {\n this.channels = channels;\n }\n return this;\n }\n\n /**\n * Clone the image\n * @returns {RawImage} The cloned image\n */\n clone() {\n return new RawImage(this.data.slice(), this.width, this.height, this.channels);\n }\n\n /**\n * Helper method for converting image to have a certain number of channels\n * @param {number} numChannels The number of channels. Must be 1, 3, or 4.\n * @returns {RawImage} `this` to support chaining.\n */\n convert(numChannels) {\n if (this.channels === numChannels) return this; // Already correct number of channels\n\n switch (numChannels) {\n case 1:\n this.grayscale();\n break;\n case 3:\n this.rgb();\n break;\n case 4:\n this.rgba();\n break;\n default:\n throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);\n }\n return this;\n }\n\n /**\n * Save the image to the given path.\n * @param {string} path The path to save the image to.\n */\n async save(path) {\n\n if (BROWSER_ENV) {\n if (WEBWORKER_ENV) {\n throw new Error('Unable to save an image from a Web Worker.')\n }\n\n const extension = path.split('.').pop().toLowerCase();\n const mime = CONTENT_TYPE_MAP.get(extension) ?? 'image/png';\n\n // Convert image to Blob\n const blob = await this.toBlob(mime);\n\n // Convert the canvas content to a data URL\n const dataURL = URL.createObjectURL(blob);\n\n // Create an anchor element with the data URL as the href attribute\n const downloadLink = document.createElement('a');\n downloadLink.href = dataURL;\n\n // Set the download attribute to specify the desired filename for the downloaded image\n downloadLink.download = path;\n\n // Trigger the download\n downloadLink.click();\n\n // Clean up: remove the anchor element from the DOM\n downloadLink.remove();\n\n } else if (!env.useFS) {\n throw new Error('Unable to save the image because filesystem is disabled in this environment.')\n\n } else {\n const img = this.toSharp();\n return await img.toFile(path);\n }\n }\n\n toSharp() {\n if (BROWSER_ENV) {\n throw new Error('toSharp() is only supported in server-side environments.')\n }\n\n return sharp(this.data, {\n raw: {\n width: this.width,\n height: this.height,\n channels: this.channels\n }\n });\n }\n}","\n/**\n * @file Helper module for mathematical processing. \n * \n * These functions and classes are only used internally, \n * meaning an end-user shouldn't need to access anything here.\n * \n * @module utils/maths\n */\n\n/**\n * @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array} TypedArray\n * @typedef {BigInt64Array | BigUint64Array} BigTypedArray\n * @typedef {TypedArray | BigTypedArray} AnyTypedArray\n */\n\n/**\n * @param {TypedArray} input\n */\nexport function interpolate_data(input, [in_channels, in_height, in_width], [out_height, out_width], mode = 'bilinear', align_corners = false) {\n // TODO use mode and align_corners\n\n // Output image dimensions\n const x_scale = out_width / in_width;\n const y_scale = out_height / in_height;\n\n // Output image\n // @ts-ignore\n const out_img = new input.constructor(out_height * out_width * in_channels);\n\n // Pre-calculate strides\n const inStride = in_height * in_width;\n const outStride = out_height * out_width;\n\n for (let i = 0; i < out_height; ++i) {\n for (let j = 0; j < out_width; ++j) {\n // Calculate output offset\n const outOffset = i * out_width + j;\n\n // Calculate input pixel coordinates\n const x = (j + 0.5) / x_scale - 0.5;\n const y = (i + 0.5) / y_scale - 0.5;\n\n // Calculate the four nearest input pixels\n // We also check if the input pixel coordinates are within the image bounds\n let x1 = Math.floor(x);\n let y1 = Math.floor(y);\n const x2 = Math.min(x1 + 1, in_width - 1);\n const y2 = Math.min(y1 + 1, in_height - 1);\n\n x1 = Math.max(x1, 0);\n y1 = Math.max(y1, 0);\n\n\n // Calculate the fractional distances between the input pixel and the four nearest pixels\n const s = x - x1;\n const t = y - y1;\n\n // Perform bilinear interpolation\n const w1 = (1 - s) * (1 - t);\n const w2 = s * (1 - t);\n const w3 = (1 - s) * t;\n const w4 = s * t;\n\n // Calculate the four nearest input pixel indices\n const yStride = y1 * in_width;\n const xStride = y2 * in_width;\n const idx1 = yStride + x1;\n const idx2 = yStride + x2;\n const idx3 = xStride + x1;\n const idx4 = xStride + x2;\n\n for (let k = 0; k < in_channels; ++k) {\n // Calculate channel offset\n const cOffset = k * inStride;\n\n out_img[k * outStride + outOffset] =\n w1 * input[cOffset + idx1] +\n w2 * input[cOffset + idx2] +\n w3 * input[cOffset + idx3] +\n w4 * input[cOffset + idx4];\n }\n }\n }\n\n return out_img;\n}\n\n\n/**\n * Helper method to permute a `AnyTypedArray` directly\n * @template {AnyTypedArray} T \n * @param {T} array \n * @param {number[]} dims \n * @param {number[]} axes \n * @returns {[T, number[]]} The permuted array and the new shape.\n */\nexport function permute_data(array, dims, axes) {\n // Calculate the new shape of the permuted array\n // and the stride of the original array\n const shape = new Array(axes.length);\n const stride = new Array(axes.length);\n\n for (let i = axes.length - 1, s = 1; i >= 0; --i) {\n stride[i] = s;\n shape[i] = dims[axes[i]];\n s *= shape[i];\n }\n\n // Precompute inverse mapping of stride\n const invStride = axes.map((_, i) => stride[axes.indexOf(i)]);\n\n // Create the permuted array with the new shape\n // @ts-ignore\n const permutedData = new array.constructor(array.length);\n\n // Permute the original array to the new array\n for (let i = 0; i < array.length; ++i) {\n let newIndex = 0;\n for (let j = dims.length - 1, k = i; j >= 0; --j) {\n newIndex += (k % dims[j]) * invStride[j];\n k = Math.floor(k / dims[j]);\n }\n permutedData[newIndex] = array[i];\n }\n\n return [permutedData, shape];\n}\n\n\n/**\n * Compute the softmax of an array of numbers.\n * @template {TypedArray|number[]} T\n * @param {T} arr The array of numbers to compute the softmax of.\n * @returns {T} The softmax array.\n */\nexport function softmax(arr) {\n // Compute the maximum value in the array\n const maxVal = max(arr)[0];\n\n // Compute the exponentials of the array values\n const exps = arr.map(x => Math.exp(x - maxVal));\n\n // Compute the sum of the exponentials\n // @ts-ignore\n const sumExps = exps.reduce((acc, val) => acc + val, 0);\n\n // Compute the softmax values\n const softmaxArr = exps.map(x => x / sumExps);\n\n return /** @type {T} */(softmaxArr);\n}\n\n/**\n * Calculates the logarithm of the softmax function for the input array.\n * @template {TypedArray|number[]} T\n * @param {T} arr The input array to calculate the log_softmax function for.\n * @returns {T} The resulting log_softmax array.\n */\nexport function log_softmax(arr) {\n // Compute the maximum value in the array\n const maxVal = max(arr)[0];\n\n // Compute the sum of the exponentials\n let sumExps = 0;\n for(let i = 0; i < arr.length; ++i) {\n sumExps += Math.exp(arr[i] - maxVal);\n }\n\n // Compute the log of the sum\n const logSum = Math.log(sumExps);\n\n // Compute the softmax values\n const logSoftmaxArr = arr.map(x => x - maxVal - logSum);\n\n return /** @type {T} */(logSoftmaxArr);\n}\n\n/**\n * Calculates the dot product of two arrays.\n * @param {number[]} arr1 The first array.\n * @param {number[]} arr2 The second array.\n * @returns {number} The dot product of arr1 and arr2.\n */\nexport function dot(arr1, arr2) {\n let result = 0;\n for (let i = 0; i < arr1.length; ++i) {\n result += arr1[i] * arr2[i];\n }\n return result;\n}\n\n/**\n * Computes the cosine similarity between two arrays.\n *\n * @param {number[]} arr1 The first array.\n * @param {number[]} arr2 The second array.\n * @returns {number} The cosine similarity between the two arrays.\n */\nexport function cos_sim(arr1, arr2) {\n // Calculate dot product of the two arrays\n const dotProduct = dot(arr1, arr2);\n\n // Calculate the magnitude of the first array\n const magnitudeA = magnitude(arr1);\n\n // Calculate the magnitude of the second array\n const magnitudeB = magnitude(arr2);\n\n // Calculate the cosine similarity\n const cosineSimilarity = dotProduct / (magnitudeA * magnitudeB);\n\n return cosineSimilarity;\n}\n\n/**\n * Calculates the magnitude of a given array.\n * @param {number[]} arr The array to calculate the magnitude of.\n * @returns {number} The magnitude of the array.\n */\nexport function magnitude(arr) {\n return Math.sqrt(arr.reduce((acc, val) => acc + val * val, 0));\n}\n\n\n/**\n * Returns the value and index of the minimum element in an array.\n * @param {number[]|TypedArray} arr array of numbers.\n * @returns {[number, number]} the value and index of the minimum element, of the form: [valueOfMin, indexOfMin]\n * @throws {Error} If array is empty.\n */\nexport function min(arr) {\n if (arr.length === 0) throw Error('Array must not be empty');\n let min = arr[0];\n let indexOfMin = 0;\n for (let i = 1; i < arr.length; ++i) {\n if (arr[i] < min) {\n min = arr[i];\n indexOfMin = i;\n }\n }\n return [min, indexOfMin];\n}\n\n\n/**\n * Returns the value and index of the maximum element in an array.\n * @param {number[]|AnyTypedArray} arr array of numbers.\n * @returns {[number, number]} the value and index of the maximum element, of the form: [valueOfMax, indexOfMax]\n * @throws {Error} If array is empty.\n */\nexport function max(arr) {\n if (arr.length === 0) throw Error('Array must not be empty');\n let max = arr[0];\n let indexOfMax = 0;\n for (let i = 1; i < arr.length; ++i) {\n if (arr[i] > max) {\n max = arr[i];\n indexOfMax = i;\n }\n }\n return [Number(max), indexOfMax];\n}\n\nfunction isPowerOfTwo(number) {\n // Check if the number is greater than 0 and has only one bit set to 1\n return (number > 0) && ((number & (number - 1)) === 0);\n}\n\n/**\n * Implementation of Radix-4 FFT.\n * \n * P2FFT class provides functionality for performing Fast Fourier Transform on arrays\n * which are a power of two in length.\n * Code adapted from https://www.npmjs.com/package/fft.js\n */\nclass P2FFT {\n /**\n * @param {number} size The size of the input array. Must be a power of two larger than 1.\n * @throws {Error} FFT size must be a power of two larger than 1.\n */\n constructor(size) {\n this.size = size | 0; // convert to a 32-bit signed integer\n if (this.size <= 1 || !isPowerOfTwo(this.size))\n throw new Error('FFT size must be a power of two larger than 1');\n\n this._csize = size << 1;\n\n this.table = new Float64Array(this.size * 2);\n for (let i = 0; i < this.table.length; i += 2) {\n const angle = Math.PI * i / this.size;\n this.table[i] = Math.cos(angle);\n this.table[i + 1] = -Math.sin(angle);\n }\n\n // Find size's power of two\n let power = 0;\n for (let t = 1; this.size > t; t <<= 1)\n ++power;\n\n // Calculate initial step's width:\n // * If we are full radix-4, it is 2x smaller to give inital len=8\n // * Otherwise it is the same as `power` to give len=4\n this._width = power % 2 === 0 ? power - 1 : power;\n\n // Pre-compute bit-reversal patterns\n this._bitrev = new Int32Array(1 << this._width);\n for (let j = 0; j < this._bitrev.length; ++j) {\n this._bitrev[j] = 0;\n for (let shift = 0; shift < this._width; shift += 2) {\n const revShift = this._width - shift - 2;\n this._bitrev[j] |= ((j >>> shift) & 3) << revShift;\n }\n }\n }\n\n /**\n * Create a complex number array with size `2 * size`\n *\n * @returns {Float64Array} A complex number array with size `2 * size`\n */\n createComplexArray() {\n return new Float64Array(this._csize);\n }\n\n /**\n * Converts a complex number representation stored in a Float64Array to an array of real numbers.\n * \n * @param {Float64Array} complex The complex number representation to be converted.\n * @param {number[]} [storage] An optional array to store the result in.\n * @returns {number[]} An array of real numbers representing the input complex number representation.\n */\n fromComplexArray(complex, storage) {\n const res = storage || new Array(complex.length >>> 1);\n for (let i = 0; i < complex.length; i += 2)\n res[i >>> 1] = complex[i];\n return res;\n }\n\n /**\n * Convert a real-valued input array to a complex-valued output array.\n * @param {Float64Array} input The real-valued input array.\n * @param {Float64Array} [storage] Optional buffer to store the output array.\n * @returns {Float64Array} The complex-valued output array.\n */\n toComplexArray(input, storage) {\n const res = storage || this.createComplexArray();\n for (let i = 0; i < res.length; i += 2) {\n res[i] = input[i >>> 1];\n res[i + 1] = 0;\n }\n return res;\n }\n\n /**\n * Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer.\n * \n * @param {Float64Array} out The output buffer to store the result.\n * @param {Float64Array} data The input data to transform.\n * \n * @throws {Error} Input and output buffers must be different.\n * \n * @returns {void}\n */\n transform(out, data) {\n if (out === data)\n throw new Error('Input and output buffers must be different');\n\n this._transform4(out, data, 1 /* DONE */);\n }\n\n /**\n * Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer.\n * The input buffer must contain real values only, while the output buffer will contain complex values. The input and\n * output buffers must be different.\n *\n * @param {Float64Array} out The output buffer.\n * @param {Float64Array} data The input buffer containing real values.\n *\n * @throws {Error} If the input and output buffers are the same.\n */\n realTransform(out, data) {\n if (out === data)\n throw new Error('Input and output buffers must be different');\n\n this._realTransform4(out, data, 1 /* DONE */);\n }\n\n /**\n * Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`.\n * The `out` array must be a different buffer than the `data` array. The `out` array will contain the\n * result of the transformation. The `data` array will not be modified.\n * \n * @param {Float64Array} out The output buffer for the transformed data.\n * @param {Float64Array} data The input data to transform.\n * @throws {Error} If `out` and `data` refer to the same buffer.\n * @returns {void}\n */\n inverseTransform(out, data) {\n if (out === data)\n throw new Error('Input and output buffers must be different');\n\n this._transform4(out, data, -1 /* DONE */);\n for (let i = 0; i < out.length; ++i)\n out[i] /= this.size;\n }\n\n /**\n * Performs a radix-4 implementation of a discrete Fourier transform on a given set of data.\n *\n * @param {Float64Array} out The output buffer for the transformed data.\n * @param {Float64Array} data The input buffer of data to be transformed.\n * @param {number} inv A scaling factor to apply to the transform.\n * @returns {void}\n */\n _transform4(out, data, inv) {\n // radix-4 implementation\n\n const size = this._csize;\n\n // Initial step (permute and transform)\n const width = this._width;\n let step = 1 << width;\n let len = (size / step) << 1;\n\n let outOff;\n let t;\n const bitrev = this._bitrev;\n if (len === 4) {\n for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n const off = bitrev[t];\n this._singleTransform2(data, out, outOff, off, step);\n }\n } else {\n // len === 8\n for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n const off = bitrev[t];\n this._singleTransform4(data, out, outOff, off, step, inv);\n }\n }\n\n // Loop through steps in decreasing order\n const table = this.table;\n for (step >>= 2; step >= 2; step >>= 2) {\n len = (size / step) << 1;\n const quarterLen = len >>> 2;\n\n // Loop through offsets in the data\n for (outOff = 0; outOff < size; outOff += len) {\n // Full case\n const limit = outOff + quarterLen - 1;\n for (let i = outOff, k = 0; i < limit; i += 2, k += step) {\n const A = i;\n const B = A + quarterLen;\n const C = B + quarterLen;\n const D = C + quarterLen;\n\n // Original values\n const Ar = out[A];\n const Ai = out[A + 1];\n const Br = out[B];\n const Bi = out[B + 1];\n const Cr = out[C];\n const Ci = out[C + 1];\n const Dr = out[D];\n const Di = out[D + 1];\n\n const tableBr = table[k];\n const tableBi = inv * table[k + 1];\n const MBr = Br * tableBr - Bi * tableBi;\n const MBi = Br * tableBi + Bi * tableBr;\n\n const tableCr = table[2 * k];\n const tableCi = inv * table[2 * k + 1];\n const MCr = Cr * tableCr - Ci * tableCi;\n const MCi = Cr * tableCi + Ci * tableCr;\n\n const tableDr = table[3 * k];\n const tableDi = inv * table[3 * k + 1];\n const MDr = Dr * tableDr - Di * tableDi;\n const MDi = Dr * tableDi + Di * tableDr;\n\n // Pre-Final values\n const T0r = Ar + MCr;\n const T0i = Ai + MCi;\n const T1r = Ar - MCr;\n const T1i = Ai - MCi;\n const T2r = MBr + MDr;\n const T2i = MBi + MDi;\n const T3r = inv * (MBr - MDr);\n const T3i = inv * (MBi - MDi);\n\n // Final values\n out[A] = T0r + T2r;\n out[A + 1] = T0i + T2i;\n out[B] = T1r + T3i;\n out[B + 1] = T1i - T3r;\n out[C] = T0r - T2r;\n out[C + 1] = T0i - T2i;\n out[D] = T1r - T3i;\n out[D + 1] = T1i + T3r;\n }\n }\n }\n }\n\n /**\n * Performs a radix-2 implementation of a discrete Fourier transform on a given set of data.\n *\n * @param {Float64Array} data The input buffer of data to be transformed.\n * @param {Float64Array} out The output buffer for the transformed data.\n * @param {number} outOff The offset at which to write the output data.\n * @param {number} off The offset at which to begin reading the input data.\n * @param {number} step The step size for indexing the input data.\n * @returns {void}\n */\n _singleTransform2(data, out, outOff, off, step) {\n // radix-2 implementation\n // NOTE: Only called for len=4\n\n const evenR = data[off];\n const evenI = data[off + 1];\n const oddR = data[off + step];\n const oddI = data[off + step + 1];\n\n out[outOff] = evenR + oddR;\n out[outOff + 1] = evenI + oddI;\n out[outOff + 2] = evenR - oddR;\n out[outOff + 3] = evenI - oddI;\n }\n\n /**\n * Performs radix-4 transformation on input data of length 8\n *\n * @param {Float64Array} data Input data array of length 8\n * @param {Float64Array} out Output data array of length 8\n * @param {number} outOff Index of output array to start writing from\n * @param {number} off Index of input array to start reading from\n * @param {number} step Step size between elements in input array\n * @param {number} inv Scaling factor for inverse transform\n * \n * @returns {void}\n */\n _singleTransform4(data, out, outOff, off, step, inv) {\n // radix-4\n // NOTE: Only called for len=8\n const step2 = step * 2;\n const step3 = step * 3;\n\n // Original values\n const Ar = data[off];\n const Ai = data[off + 1];\n const Br = data[off + step];\n const Bi = data[off + step + 1];\n const Cr = data[off + step2];\n const Ci = data[off + step2 + 1];\n const Dr = data[off + step3];\n const Di = data[off + step3 + 1];\n\n // Pre-Final values\n const T0r = Ar + Cr;\n const T0i = Ai + Ci;\n const T1r = Ar - Cr;\n const T1i = Ai - Ci;\n const T2r = Br + Dr;\n const T2i = Bi + Di;\n const T3r = inv * (Br - Dr);\n const T3i = inv * (Bi - Di);\n\n // Final values\n out[outOff] = T0r + T2r;\n out[outOff + 1] = T0i + T2i;\n out[outOff + 2] = T1r + T3i;\n out[outOff + 3] = T1i - T3r;\n out[outOff + 4] = T0r - T2r;\n out[outOff + 5] = T0i - T2i;\n out[outOff + 6] = T1r - T3i;\n out[outOff + 7] = T1i + T3r;\n }\n\n /**\n * Real input radix-4 implementation\n * @param {Float64Array} out Output array for the transformed data\n * @param {Float64Array} data Input array of real data to be transformed\n * @param {number} inv The scale factor used to normalize the inverse transform\n */\n _realTransform4(out, data, inv) {\n // Real input radix-4 implementation\n const size = this._csize;\n\n // Initial step (permute and transform)\n const width = this._width;\n let step = 1 << width;\n let len = (size / step) << 1;\n\n let outOff;\n let t;\n const bitrev = this._bitrev;\n if (len === 4) {\n for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n const off = bitrev[t];\n this._singleRealTransform2(data, out, outOff, off >>> 1, step >>> 1);\n }\n } else {\n // len === 8\n for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n const off = bitrev[t];\n this._singleRealTransform4(data, out, outOff, off >>> 1, step >>> 1, inv);\n }\n }\n\n // Loop through steps in decreasing order\n const table = this.table;\n for (step >>= 2; step >= 2; step >>= 2) {\n len = (size / step) << 1;\n const halfLen = len >>> 1;\n const quarterLen = halfLen >>> 1;\n const hquarterLen = quarterLen >>> 1;\n\n // Loop through offsets in the data\n for (outOff = 0; outOff < size; outOff += len) {\n for (let i = 0, k = 0; i <= hquarterLen; i += 2, k += step) {\n const A = outOff + i;\n const B = A + quarterLen;\n const C = B + quarterLen;\n const D = C + quarterLen;\n\n // Original values\n const Ar = out[A];\n const Ai = out[A + 1];\n const Br = out[B];\n const Bi = out[B + 1];\n const Cr = out[C];\n const Ci = out[C + 1];\n const Dr = out[D];\n const Di = out[D + 1];\n\n // Middle values\n const MAr = Ar;\n const MAi = Ai;\n\n const tableBr = table[k];\n const tableBi = inv * table[k + 1];\n const MBr = Br * tableBr - Bi * tableBi;\n const MBi = Br * tableBi + Bi * tableBr;\n\n const tableCr = table[2 * k];\n const tableCi = inv * table[2 * k + 1];\n const MCr = Cr * tableCr - Ci * tableCi;\n const MCi = Cr * tableCi + Ci * tableCr;\n\n const tableDr = table[3 * k];\n const tableDi = inv * table[3 * k + 1];\n const MDr = Dr * tableDr - Di * tableDi;\n const MDi = Dr * tableDi + Di * tableDr;\n\n // Pre-Final values\n const T0r = MAr + MCr;\n const T0i = MAi + MCi;\n const T1r = MAr - MCr;\n const T1i = MAi - MCi;\n const T2r = MBr + MDr;\n const T2i = MBi + MDi;\n const T3r = inv * (MBr - MDr);\n const T3i = inv * (MBi - MDi);\n\n // Final values\n out[A] = T0r + T2r;\n out[A + 1] = T0i + T2i;\n out[B] = T1r + T3i;\n out[B + 1] = T1i - T3r;\n\n // Output final middle point\n if (i === 0) {\n out[C] = T0r - T2r;\n out[C + 1] = T0i - T2i;\n continue;\n }\n\n // Do not overwrite ourselves\n if (i === hquarterLen)\n continue;\n\n const SA = outOff + quarterLen - i;\n const SB = outOff + halfLen - i;\n\n out[SA] = T1r - inv * T3i;\n out[SA + 1] = -T1i - inv * T3r;\n out[SB] = T0r - inv * T2r;\n out[SB + 1] = -T0i + inv * T2i;\n }\n }\n }\n\n // Complete the spectrum by adding its mirrored negative frequency components.\n const half = size >>> 1;\n for (let i = 2; i < half; i += 2) {\n out[size - i] = out[i];\n out[size - i + 1] = -out[i + 1];\n }\n }\n\n /**\n * Performs a single real input radix-2 transformation on the provided data\n * \n * @param {Float64Array} data The input data array\n * @param {Float64Array} out The output data array\n * @param {number} outOff The output offset\n * @param {number} off The input offset\n * @param {number} step The step\n * \n * @returns {void}\n */\n _singleRealTransform2(data, out, outOff, off, step) {\n // radix-2 implementation\n // NOTE: Only called for len=4\n\n const evenR = data[off];\n const oddR = data[off + step];\n\n out[outOff] = evenR + oddR;\n out[outOff + 1] = 0;\n out[outOff + 2] = evenR - oddR;\n out[outOff + 3] = 0;\n }\n\n /**\n * Computes a single real-valued transform using radix-4 algorithm.\n * This method is only called for len=8.\n *\n * @param {Float64Array} data The input data array.\n * @param {Float64Array} out The output data array.\n * @param {number} outOff The offset into the output array.\n * @param {number} off The offset into the input array.\n * @param {number} step The step size for the input array.\n * @param {number} inv The value of inverse.\n */\n _singleRealTransform4(data, out, outOff, off, step, inv) {\n // radix-4\n // NOTE: Only called for len=8\n const step2 = step * 2;\n const step3 = step * 3;\n\n // Original values\n const Ar = data[off];\n const Br = data[off + step];\n const Cr = data[off + step2];\n const Dr = data[off + step3];\n\n // Pre-Final values\n const T0r = Ar + Cr;\n const T1r = Ar - Cr;\n const T2r = Br + Dr;\n const T3r = inv * (Br - Dr);\n\n // Final values\n out[outOff] = T0r + T2r;\n out[outOff + 1] = 0;\n out[outOff + 2] = T1r;\n out[outOff + 3] = -T3r;\n out[outOff + 4] = T0r - T2r;\n out[outOff + 5] = 0;\n out[outOff + 6] = T1r;\n out[outOff + 7] = T3r;\n }\n}\n\n/**\n * NP2FFT class provides functionality for performing Fast Fourier Transform on arrays\n * which are not a power of two in length. In such cases, the chirp-z transform is used.\n * \n * For more information, see: https://math.stackexchange.com/questions/77118/non-power-of-2-ffts/77156#77156\n */\nclass NP2FFT {\n\n /**\n * Constructs a new NP2FFT object.\n * @param {number} fft_length The length of the FFT\n */\n constructor(fft_length) {\n // Helper variables\n const a = 2 * (fft_length - 1);\n const b = 2 * (2 * fft_length - 1);\n const nextP2 = 2 ** (Math.ceil(Math.log2(b)))\n this.bufferSize = nextP2;\n this._a = a;\n\n // Define buffers\n // Compute chirp for transform\n const chirp = new Float64Array(b);\n const ichirp = new Float64Array(nextP2);\n this._chirpBuffer = new Float64Array(nextP2);\n this._buffer1 = new Float64Array(nextP2);\n this._buffer2 = new Float64Array(nextP2);\n this._outBuffer1 = new Float64Array(nextP2);\n this._outBuffer2 = new Float64Array(nextP2);\n\n // Compute complex exponentiation\n const theta = -2 * Math.PI / fft_length;\n const baseR = Math.cos(theta);\n const baseI = Math.sin(theta);\n\n // Precompute helper for chirp-z transform\n for (let i = 0; i < b >> 1; ++i) {\n // Compute complex power:\n const e = (i + 1 - fft_length) ** 2 / 2.0;\n\n // Compute the modulus and argument of the result\n const result_mod = Math.sqrt(baseR ** 2 + baseI ** 2) ** e;\n const result_arg = e * Math.atan2(baseI, baseR);\n\n // Convert the result back to rectangular form\n // and assign to chirp and ichirp\n const i2 = 2 * i;\n chirp[i2] = result_mod * Math.cos(result_arg);\n chirp[i2 + 1] = result_mod * Math.sin(result_arg);\n\n // conjugate\n ichirp[i2] = chirp[i2];\n ichirp[i2 + 1] = - chirp[i2 + 1];\n }\n this._slicedChirpBuffer = chirp.subarray(a, b);\n\n // create object to perform Fast Fourier Transforms\n // with `nextP2` complex numbers\n this._f = new P2FFT(nextP2 >> 1);\n this._f.transform(this._chirpBuffer, ichirp);\n }\n\n _transform(output, input, real) {\n const ib1 = this._buffer1;\n const ib2 = this._buffer2;\n const ob2 = this._outBuffer1;\n const ob3 = this._outBuffer2;\n const cb = this._chirpBuffer;\n const sb = this._slicedChirpBuffer;\n const a = this._a;\n\n if (real) {\n // Real multiplication\n for (let j = 0; j < sb.length; j += 2) {\n const j2 = j + 1\n const j3 = j >> 1;\n\n const a_real = input[j3];\n ib1[j] = a_real * sb[j];\n ib1[j2] = a_real * sb[j2];\n }\n } else {\n // Complex multiplication\n for (let j = 0; j < sb.length; j += 2) {\n const j2 = j + 1\n ib1[j] = input[j] * sb[j] - input[j2] * sb[j2];\n ib1[j2] = input[j] * sb[j2] + input[j2] * sb[j];\n }\n }\n this._f.transform(ob2, ib1);\n\n for (let j = 0; j < cb.length; j += 2) {\n const j2 = j + 1;\n\n ib2[j] = ob2[j] * cb[j] - ob2[j2] * cb[j2];\n ib2[j2] = ob2[j] * cb[j2] + ob2[j2] * cb[j];\n }\n this._f.inverseTransform(ob3, ib2);\n\n for (let j = 0; j < ob3.length; j += 2) {\n const a_real = ob3[j + a];\n const a_imag = ob3[j + a + 1];\n const b_real = sb[j];\n const b_imag = sb[j + 1];\n\n output[j] = a_real * b_real - a_imag * b_imag;\n output[j + 1] = a_real * b_imag + a_imag * b_real;\n }\n }\n\n transform(output, input) {\n this._transform(output, input, false);\n }\n\n realTransform(output, input) {\n this._transform(output, input, true);\n }\n}\n\nexport class FFT {\n constructor(fft_length) {\n this.fft_length = fft_length;\n this.isPowerOfTwo = isPowerOfTwo(fft_length);\n if (this.isPowerOfTwo) {\n this.fft = new P2FFT(fft_length);\n this.outputBufferSize = 2 * fft_length;\n } else {\n this.fft = new NP2FFT(fft_length);\n this.outputBufferSize = this.fft.bufferSize;\n }\n }\n\n realTransform(out, input) {\n this.fft.realTransform(out, input);\n }\n\n transform(out, input) {\n this.fft.transform(out, input);\n }\n}\n\n\n/**\n * Performs median filter on the provided data. Padding is done by mirroring the data.\n * @param {AnyTypedArray} data The input array\n * @param {number} windowSize The window size\n */\nexport function medianFilter(data, windowSize) {\n\n if (windowSize % 2 === 0 || windowSize <= 0) {\n throw new Error('Window size must be a positive odd number');\n }\n\n // @ts-ignore\n const outputArray = new data.constructor(data.length);\n\n // @ts-ignore\n const buffer = new data.constructor(windowSize); // Reusable array for storing values\n\n const halfWindowSize = Math.floor(windowSize / 2);\n\n for (let i = 0; i < data.length; ++i) {\n let valuesIndex = 0;\n\n for (let j = -halfWindowSize; j <= halfWindowSize; ++j) {\n let index = i + j;\n if (index < 0) {\n index = Math.abs(index);\n } else if (index >= data.length) {\n index = 2 * (data.length - 1) - index;\n }\n\n buffer[valuesIndex++] = data[index];\n }\n\n buffer.sort();\n outputArray[i] = buffer[halfWindowSize];\n }\n\n return outputArray;\n}\n\n/**\n * Helper function to round a number to a given number of decimals\n * @param {number} num The number to round\n * @param {number} decimals The number of decimals\n * @returns {number} The rounded number\n */\nexport function round(num, decimals) {\n const pow = Math.pow(10, decimals);\n return Math.round(num * pow) / pow;\n}\n\n/**\n * Helper function to round a number to the nearest integer, with ties rounded to the nearest even number.\n * Also known as \"bankers' rounding\". This is the default rounding mode in python. For example:\n * 1.5 rounds to 2 and 2.5 rounds to 2.\n * \n * @param {number} x The number to round\n * @returns {number} The rounded number\n */\nexport function bankers_round(x) {\n const r = Math.round(x);\n const br = Math.abs(x) % 1 === 0.5 ? (r % 2 === 0 ? r : r - 1) : r;\n return br;\n}\n\n\n/**\n * Measures similarity between two temporal sequences (e.g., input audio and output tokens\n * to generate token-level timestamps).\n * @param {number[][]} matrix \n * @returns {number[][]}\n */\nexport function dynamic_time_warping(matrix) {\n const output_length = matrix.length;\n const input_length = matrix[0].length;\n\n const outputShape = [output_length + 1, input_length + 1];\n\n const cost = Array.from(\n { length: outputShape[0] },\n () => Array(outputShape[1]).fill(Infinity)\n );\n cost[0][0] = 0;\n\n const trace = Array.from(\n { length: outputShape[0] },\n () => Array(outputShape[1]).fill(-1)\n );\n\n for (let j = 1; j < outputShape[1]; ++j) {\n for (let i = 1; i < outputShape[0]; ++i) {\n const c0 = cost[i - 1][j - 1];\n const c1 = cost[i - 1][j];\n const c2 = cost[i][j - 1];\n\n let c, t;\n if (c0 < c1 && c0 < c2) {\n c = c0;\n t = 0;\n } else if (c1 < c0 && c1 < c2) {\n c = c1;\n t = 1;\n } else {\n c = c2;\n t = 2;\n }\n cost[i][j] = matrix[i - 1][j - 1] + c;\n trace[i][j] = t;\n }\n }\n\n for (let i = 0; i < outputShape[1]; ++i) { // trace[0, :] = 2\n trace[0][i] = 2;\n }\n for (let i = 0; i < outputShape[0]; ++i) { // trace[:, 0] = 1\n trace[i][0] = 1;\n }\n\n // backtrace\n let i = output_length;\n let j = input_length;\n let text_indices = [];\n let time_indices = [];\n while (i > 0 || j > 0) {\n text_indices.push(i - 1);\n time_indices.push(j - 1);\n\n switch (trace[i][j]) {\n case 0:\n --i; --j;\n break;\n case 1:\n --i;\n break;\n case 2:\n --j;\n break;\n default:\n throw new Error(\n `Internal error in dynamic time warping. Unexpected trace[${i}, ${j}]. Please file a bug report.`\n )\n }\n }\n\n text_indices.reverse();\n time_indices.reverse();\n\n return [text_indices, time_indices];\n\n}\n","/**\n * @file Helper module for `Tensor` processing.\n *\n * These functions and classes are only used internally,\n * meaning an end-user shouldn't need to access anything here.\n *\n * @module utils/tensor\n */\n\nimport {\n interpolate_data,\n permute_data\n} from './maths.js';\n\nimport {\n Tensor as ONNXTensor, isONNXTensor,\n} from '../backends/onnx.js';\n\nimport { TensorOpRegistry } from '../ops/registry.js';\n\nconst DataTypeMap = Object.freeze({\n float32: Float32Array,\n float16: Uint16Array,\n float64: Float64Array,\n string: Array, // string[]\n int8: Int8Array,\n uint8: Uint8Array,\n int16: Int16Array,\n uint16: Uint16Array,\n int32: Int32Array,\n uint32: Uint32Array,\n int64: BigInt64Array,\n uint64: BigUint64Array,\n bool: Uint8Array,\n});\n\n/**\n * @typedef {keyof typeof DataTypeMap} DataType\n * @typedef {import('./maths.js').AnyTypedArray | any[]} DataArray\n */\n\n\nexport class Tensor {\n /** @type {number[]} Dimensions of the tensor. */\n get dims() {\n // @ts-ignore\n return this.ort_tensor.dims;\n }\n set dims(value) {\n // FIXME: ONNXTensor declares dims as readonly so one needs to use the constructor() if dims change.\n // @ts-ignore\n this.ort_tensor.dims = value;\n }\n\n /** @type {DataType} Type of the tensor. */\n get type() {\n return this.ort_tensor.type;\n };\n\n /** @type {DataArray} The data stored in the tensor. */\n get data() {\n return this.ort_tensor.data;\n }\n\n /** @type {number} The number of elements in the tensor. */\n get size() {\n return this.ort_tensor.size;\n };\n\n /** @type {string} The location of the tensor data. */\n get location() {\n return this.ort_tensor.location;\n };\n\n ort_tensor;\n\n /**\n * Create a new Tensor or copy an existing Tensor.\n * @param {[DataType, DataArray, number[]]|[ONNXTensor]} args\n */\n constructor(...args) {\n if (isONNXTensor(args[0])) {\n this.ort_tensor = /** @type {ONNXTensor} */ (args[0]);\n } else {\n // Create new tensor\n this.ort_tensor = new ONNXTensor(\n /** @type {DataType} */(args[0]),\n /** @type {Exclude} */(args[1]),\n args[2]\n );\n }\n\n return new Proxy(this, {\n get: (obj, key) => {\n if (typeof key === 'string') {\n let index = Number(key);\n if (Number.isInteger(index)) {\n // key is an integer (i.e., index)\n return obj._getitem(index);\n }\n }\n // @ts-ignore\n return obj[key];\n },\n set: (obj, key, value) => {\n // TODO allow setting of data\n\n // @ts-ignore\n return obj[key] = value;\n }\n });\n }\n\n dispose() {\n this.ort_tensor.dispose();\n // this.ort_tensor = undefined;\n }\n\n /**\n * Returns an iterator object for iterating over the tensor data in row-major order.\n * If the tensor has more than one dimension, the iterator will yield subarrays.\n * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order.\n */\n *[Symbol.iterator]() {\n const [iterLength, ...iterDims] = this.dims;\n\n if (iterDims.length > 0) {\n const iterSize = iterDims.reduce((a, b) => a * b);\n for (let i = 0; i < iterLength; ++i) {\n yield this._subarray(i, iterSize, iterDims);\n }\n } else {\n yield* this.data\n }\n\n }\n\n /**\n * Index into a Tensor object.\n * @param {number} index The index to access.\n * @returns {Tensor} The data at the specified index.\n */\n _getitem(index) {\n const [iterLength, ...iterDims] = this.dims;\n\n index = safeIndex(index, iterLength);\n\n if (iterDims.length > 0) {\n const iterSize = iterDims.reduce((a, b) => a * b);\n return this._subarray(index, iterSize, iterDims);\n } else {\n return new Tensor(this.type, [this.data[index]], iterDims);\n }\n }\n\n /**\n * @param {number|bigint} item The item to search for in the tensor\n * @returns {number} The index of the first occurrence of item in the tensor data.\n */\n indexOf(item) {\n const this_data = this.data;\n for (let index = 0; index < this_data.length; ++index) {\n // Note: == instead of === so we can match Ints with BigInts\n if (this_data[index] == item) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * @param {number} index\n * @param {number} iterSize\n * @param {any} iterDims\n * @returns {Tensor}\n */\n _subarray(index, iterSize, iterDims) {\n const o1 = index * iterSize;\n const o2 = (index + 1) * iterSize;\n\n // We use subarray if available (typed array), otherwise we use slice (normal array)\n const data =\n ('subarray' in this.data)\n ? this.data.subarray(o1, o2)\n : this.data.slice(o1, o2);\n return new Tensor(this.type, data, iterDims);\n }\n\n /**\n * Returns the value of this tensor as a standard JavaScript Number. This only works\n * for tensors with one element. For other cases, see `Tensor.tolist()`.\n * @returns {number|bigint} The value of this tensor as a standard JavaScript Number.\n * @throws {Error} If the tensor has more than one element.\n */\n item() {\n const this_data = this.data;\n if (this_data.length !== 1) {\n throw new Error(`a Tensor with ${this_data.length} elements cannot be converted to Scalar`);\n }\n return this_data[0];\n }\n\n /**\n * Convert tensor data to a n-dimensional JS list\n * @returns {Array}\n */\n tolist() {\n return reshape(this.data, this.dims)\n }\n\n /**\n * Return a new Tensor with the sigmoid function applied to each element.\n * @returns {Tensor} The tensor with the sigmoid function applied.\n */\n sigmoid() {\n return this.clone().sigmoid_();\n }\n\n /**\n * Applies the sigmoid function to the tensor in place.\n * @returns {Tensor} Returns `this`.\n */\n sigmoid_() {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = 1 / (1 + Math.exp(-this_data[i]));\n }\n return this;\n }\n\n /**\n * Return a new Tensor with a callback function applied to each element.\n * @param {Function} callback - The function to apply to each element. It should take three arguments:\n * the current element, its index, and the tensor's data array.\n * @returns {Tensor} A new Tensor with the callback function applied to each element.\n */\n map(callback) {\n return this.clone().map_(callback);\n }\n\n /**\n * Apply a callback function to each element of the tensor in place.\n * @param {Function} callback - The function to apply to each element. It should take three arguments:\n * the current element, its index, and the tensor's data array.\n * @returns {Tensor} Returns `this`.\n */\n map_(callback) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = callback(this_data[i], i, this_data);\n }\n return this;\n }\n\n /**\n * Return a new Tensor with every element multiplied by a constant.\n * @param {number} val The value to multiply by.\n * @returns {Tensor} The new tensor.\n */\n mul(val) {\n return this.clone().mul_(val);\n }\n\n /**\n * Multiply the tensor by a constant in place.\n * @param {number} val The value to multiply by.\n * @returns {Tensor} Returns `this`.\n */\n mul_(val) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] *= val;\n }\n return this;\n }\n\n /**\n * Return a new Tensor with every element divided by a constant.\n * @param {number} val The value to divide by.\n * @returns {Tensor} The new tensor.\n */\n div(val) {\n return this.clone().div_(val);\n }\n\n /**\n * Divide the tensor by a constant in place.\n * @param {number} val The value to divide by.\n * @returns {Tensor} Returns `this`.\n */\n div_(val) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] /= val;\n }\n return this;\n }\n\n /**\n * Return a new Tensor with every element added by a constant.\n * @param {number} val The value to add by.\n * @returns {Tensor} The new tensor.\n */\n add(val) {\n return this.clone().add_(val);\n }\n\n /**\n * Add the tensor by a constant in place.\n * @param {number} val The value to add by.\n * @returns {Tensor} Returns `this`.\n */\n add_(val) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] += val;\n }\n return this;\n }\n\n /**\n * Return a new Tensor with every element subtracted by a constant.\n * @param {number} val The value to subtract by.\n * @returns {Tensor} The new tensor.\n */\n sub(val) {\n return this.clone().sub_(val);\n }\n\n /**\n * Subtract the tensor by a constant in place.\n * @param {number} val The value to subtract by.\n * @returns {Tensor} Returns `this`.\n */\n sub_(val) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] -= val;\n }\n return this;\n }\n\n clone() {\n return new Tensor(this.type, this.data.slice(), this.dims.slice());\n }\n\n slice(...slices) {\n // This allows for slicing with ranges and numbers\n const newTensorDims = [];\n const newOffsets = [];\n\n // slices is an array of numbers or arrays of numbers\n // e.g., slices = [0, [1, 3], null, [0, 3]]\n for (let sliceIndex = 0; sliceIndex < this.dims.length; ++sliceIndex) {\n let slice = slices[sliceIndex];\n\n if (slice === null || slice === undefined) {\n // null or undefined means take the whole dimension\n newOffsets.push([0, this.dims[sliceIndex]]);\n newTensorDims.push(this.dims[sliceIndex]);\n\n } else if (typeof slice === 'number') {\n slice = safeIndex(slice, this.dims[sliceIndex], sliceIndex);\n\n // A number means take a single element\n newOffsets.push([slice, slice + 1]);\n\n } else if (Array.isArray(slice) && slice.length === 2) {\n // An array of length 2 means take a range of elements\n let [start, end] = slice;\n start = start === null\n ? 0\n : safeIndex(start, this.dims[sliceIndex], sliceIndex, false);\n end = end === null\n ? this.dims[sliceIndex]\n : safeIndex(end, this.dims[sliceIndex], sliceIndex, false);\n\n if (start > end) {\n throw new Error(`Invalid slice: ${slice}`);\n }\n\n const offsets = [\n Math.max(start, 0),\n Math.min(end, this.dims[sliceIndex])\n ];\n\n newOffsets.push(offsets);\n newTensorDims.push(offsets[1] - offsets[0]);\n\n } else {\n throw new Error(`Invalid slice: ${slice}`);\n }\n }\n\n const newDims = newOffsets.map(([start, end]) => end - start);\n const newBufferSize = newDims.reduce((a, b) => a * b);\n\n const this_data = this.data;\n // Allocate memory\n // @ts-ignore\n const data = new this_data.constructor(newBufferSize);\n\n // Precompute strides\n const stride = this.stride();\n\n for (let i = 0; i < newBufferSize; ++i) {\n let originalIndex = 0;\n for (let j = newDims.length - 1, num = i; j >= 0; --j) {\n const size = newDims[j];\n originalIndex += ((num % size) + newOffsets[j][0]) * stride[j];\n num = Math.floor(num / size);\n }\n data[i] = this_data[originalIndex];\n }\n return new Tensor(this.type, data, newTensorDims);\n\n }\n\n /**\n * Return a permuted version of this Tensor, according to the provided dimensions.\n * @param {...number} dims Dimensions to permute.\n * @returns {Tensor} The permuted tensor.\n */\n permute(...dims) {\n return permute(this, dims);\n }\n\n // TODO: implement transpose. For now (backwards compatibility), it's just an alias for permute()\n transpose(...dims) {\n return this.permute(...dims);\n }\n\n // TODO add .max() and .min() methods\n\n /**\n * Returns the sum of each row of the input tensor in the given dimension dim.\n *\n * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced.\n * @param {boolean} keepdim Whether the output tensor has `dim` retained or not.\n * @returns The summed tensor\n */\n sum(dim = null, keepdim = false) {\n return this.norm(1, dim, keepdim);\n }\n\n /**\n * Returns the matrix norm or vector norm of a given tensor.\n * @param {number|string} [p='fro'] The order of norm\n * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across.\n * If dim is None, the norm will be calculated across all dimensions of input.\n * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not.\n * @returns {Tensor} The norm of the tensor.\n */\n norm(p = 'fro', dim = null, keepdim = false) {\n if (p === 'fro') {\n // NOTE: Since we only support integer dims, Frobenius norm produces the same result as p=2.\n p = 2;\n } else if (typeof p === 'string') {\n throw Error(`Unsupported norm: ${p}`);\n }\n\n const this_data = this.data;\n\n if (dim === null) {\n // @ts-ignore\n let val = this_data.reduce((a, b) => a + (b ** p), 0) ** (1 / p);\n return new Tensor(this.type, [val], []);\n }\n\n // Negative indexing\n dim = safeIndex(dim, this.dims.length);\n\n // Calculate the shape of the resulting array after summation\n const resultDims = this.dims.slice(); // Copy the original dimensions\n resultDims[dim] = 1; // Remove the specified axis\n\n // Create a new array to store the accumulated values\n // @ts-ignore\n const result = new this_data.constructor(this_data.length / this.dims[dim]);\n\n // Iterate over the data array\n for (let i = 0; i < this_data.length; ++i) {\n\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = this.dims[j];\n if (j !== dim) {\n const index = num % size;\n resultIndex += index * resultMultiplier;\n resultMultiplier *= resultDims[j];\n }\n num = Math.floor(num / size);\n }\n\n // Accumulate the value at the current index\n result[resultIndex] += (this_data[i]) ** p;\n }\n\n if (p !== 1) {\n for (let i = 0; i < result.length; ++i) {\n result[i] = result[i] ** (1 / p);\n }\n }\n\n if (!keepdim) {\n resultDims.splice(dim, 1);\n }\n\n return new Tensor(this.type, result, resultDims);\n }\n\n /**\n * Performs `L_p` normalization of inputs over specified dimension. Operates in place.\n * @param {number} [p=2] The exponent value in the norm formulation\n * @param {number} [dim=1] The dimension to reduce\n * @returns {Tensor} `this` for operation chaining.\n */\n normalize_(p = 2.0, dim = 1) {\n dim = safeIndex(dim, this.dims.length);\n\n const norm = this.norm(p, dim, true);\n\n const this_data = this.data;\n const norm_data = norm.data;\n for (let i = 0; i < this_data.length; ++i) {\n\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = this.dims[j];\n if (j !== dim) {\n const index = num % size;\n resultIndex += index * resultMultiplier;\n resultMultiplier *= this.dims[j];\n }\n num = Math.floor(num / size);\n }\n\n // Divide by normalized value\n this_data[i] /= norm_data[resultIndex];\n }\n\n return this;\n }\n\n /**\n * Performs `L_p` normalization of inputs over specified dimension.\n * @param {number} [p=2] The exponent value in the norm formulation\n * @param {number} [dim=1] The dimension to reduce\n * @returns {Tensor} The normalized tensor.\n */\n normalize(p = 2.0, dim = 1) {\n return this.clone().normalize_(p, dim);\n }\n\n /**\n * Compute and return the stride of this tensor.\n * Stride is the jump necessary to go from one element to the next one in the specified dimension dim.\n * @returns {number[]} The stride of this tensor.\n */\n stride() {\n return dimsToStride(this.dims);\n }\n\n /**\n * Returns a tensor with all specified dimensions of input of size 1 removed.\n *\n * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other.\n * If you would like a copy, use `tensor.clone()` before squeezing.\n *\n * @param {number} [dim=null] If given, the input will be squeezed only in the specified dimensions.\n * @returns {Tensor} The squeezed tensor\n */\n squeeze(dim = null) {\n return new Tensor(\n this.type,\n this.data,\n calc_squeeze_dims(this.dims, dim)\n )\n }\n\n /**\n * In-place version of @see {@link Tensor.squeeze}\n */\n squeeze_(dim = null) {\n this.dims = calc_squeeze_dims(this.dims, dim);\n return this;\n }\n\n /**\n * Returns a new tensor with a dimension of size one inserted at the specified position.\n *\n * NOTE: The returned tensor shares the same underlying data with this tensor.\n *\n * @param {number} dim The index at which to insert the singleton dimension\n * @returns {Tensor} The unsqueezed tensor\n */\n unsqueeze(dim = null) {\n return new Tensor(\n this.type,\n this.data,\n calc_unsqueeze_dims(this.dims, dim)\n );\n }\n\n /**\n * In-place version of @see {@link Tensor.unsqueeze}\n */\n unsqueeze_(dim = null) {\n this.dims = calc_unsqueeze_dims(this.dims, dim);\n return this;\n }\n\n /**\n * In-place version of @see {@link Tensor.flatten}\n */\n flatten_(start_dim = 0, end_dim = -1) {\n // TODO validate inputs\n end_dim = (end_dim + this.dims.length) % this.dims.length;\n\n let dimsToKeepBefore = this.dims.slice(0, start_dim);\n let dimsToFlatten = this.dims.slice(start_dim, end_dim + 1);\n let dimsToKeepAfter = this.dims.slice(end_dim + 1);\n\n this.dims = [...dimsToKeepBefore, dimsToFlatten.reduce((a, b) => a * b, 1), ...dimsToKeepAfter]\n return this;\n }\n\n /**\n * Flattens input by reshaping it into a one-dimensional tensor.\n * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim`\n * and ending with `end_dim` are flattened. The order of elements in input is unchanged.\n * @param {number} start_dim the first dim to flatten\n * @param {number} end_dim the last dim to flatten\n * @returns {Tensor} The flattened tensor.\n */\n flatten(start_dim = 0, end_dim = -1) {\n return this.clone().flatten_(start_dim, end_dim);\n }\n\n /**\n * Returns a new tensor with the same data as the `self` tensor but of a different `shape`.\n * @param {...number} dims the desired size\n * @returns {Tensor} The tensor with the same data but different shape\n */\n view(...dims) {\n // TODO: validate dims\n let inferredIndex = -1;\n for (let i = 0; i < dims.length; ++i) {\n if (dims[i] === -1) {\n if (inferredIndex !== -1) {\n throw new Error(\"Only one dimension can be inferred\");\n }\n inferredIndex = i;\n }\n }\n\n const this_data = this.data;\n if (inferredIndex !== -1) {\n // Some dimension must be inferred\n const productOther = dims.reduce((product, curr, index) => {\n return index !== inferredIndex ? product * curr : product\n }, 1);\n\n dims[inferredIndex] = this_data.length / productOther;\n }\n return new Tensor(this.type, this_data, dims); // NOTE: uses same underlying storage\n }\n\n neg_() {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = -this_data[i];\n }\n return this;\n }\n neg() {\n return this.clone().neg_();\n }\n\n /**\n * In-place version of @see {@link Tensor.clamp}\n */\n clamp_(min, max) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = Math.min(Math.max(this_data[i], min), max);\n }\n return this;\n }\n\n /**\n * Clamps all elements in input into the range [ min, max ]\n * @param {number} min lower-bound of the range to be clamped to\n * @param {number} max upper-bound of the range to be clamped to\n * @returns {Tensor} the output tensor.\n */\n clamp(min, max) {\n return this.clone().clamp_(min, max);\n }\n\n /**\n * In-place version of @see {@link Tensor.round}\n */\n round_() {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = Math.round(this_data[i]);\n }\n return this;\n }\n\n /**\n * Rounds elements of input to the nearest integer.\n * @returns {Tensor} the output tensor.\n */\n round() {\n return this.clone().round_();\n }\n\n mean(dim = null, keepdim = false) {\n return mean(this, dim, keepdim);\n }\n\n /**\n * Performs Tensor dtype conversion.\n * @param {DataType} type The desired data type.\n * @returns {Tensor} The converted tensor.\n */\n to(type) {\n // If the self Tensor already has the correct dtype, then self is returned.\n if (this.type === type) return this;\n\n // Otherwise, the returned tensor is a copy of self with the desired dtype.\n if (!DataTypeMap.hasOwnProperty(type)) {\n throw new Error(`Unsupported type: ${type}`);\n }\n // @ts-ignore\n return new Tensor(type, DataTypeMap[type].from(this.data), this.dims);\n }\n}\n\n/**\n * This creates a nested array of a given type and depth (see examples).\n *\n * @example\n * NestArray; // string[]\n * @example\n * NestArray; // number[][]\n * @example\n * NestArray; // string[][][] etc.\n * @template T\n * @template {number} Depth\n * @template {never[]} [Acc=[]]\n * @typedef {Acc['length'] extends Depth ? T : NestArray} NestArray\n */\n\n/**\n * Reshapes a 1-dimensional array into an n-dimensional array, according to the provided dimensions.\n *\n * @example\n * reshape([10 ], [1 ]); // Type: number[] Value: [10]\n * reshape([1, 2, 3, 4 ], [2, 2 ]); // Type: number[][] Value: [[1, 2], [3, 4]]\n * reshape([1, 2, 3, 4, 5, 6, 7, 8], [2, 2, 2]); // Type: number[][][] Value: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]\n * reshape([1, 2, 3, 4, 5, 6, 7, 8], [4, 2 ]); // Type: number[][] Value: [[1, 2], [3, 4], [5, 6], [7, 8]]\n * @param {T[]|DataArray} data The input array to reshape.\n * @param {DIM} dimensions The target shape/dimensions.\n * @template T\n * @template {[number]|number[]} DIM\n * @returns {NestArray} The reshaped array.\n */\nfunction reshape(data, dimensions) {\n\n const totalElements = data.length;\n const dimensionSize = dimensions.reduce((a, b) => a * b);\n\n if (totalElements !== dimensionSize) {\n throw Error(`cannot reshape array of size ${totalElements} into shape (${dimensions})`);\n }\n\n /** @type {any} */\n let reshapedArray = data;\n\n for (let i = dimensions.length - 1; i >= 0; i--) {\n reshapedArray = reshapedArray.reduce((acc, val) => {\n let lastArray = acc[acc.length - 1];\n\n if (lastArray.length < dimensions[i]) {\n lastArray.push(val);\n } else {\n acc.push([val]);\n }\n\n return acc;\n }, [[]]);\n }\n\n return reshapedArray[0];\n}\n\n/**\n * Permutes a tensor according to the provided axes.\n * @param {any} tensor The input tensor to permute.\n * @param {Array} axes The axes to permute the tensor along.\n * @returns {Tensor} The permuted tensor.\n */\nexport function permute(tensor, axes) {\n const [permutedData, shape] = permute_data(tensor.data, tensor.dims, axes);\n return new Tensor(tensor.type, permutedData, shape);\n}\n\n\n/**\n * Interpolates an Tensor to the given size.\n * @param {Tensor} input The input tensor to interpolate. Data must be channel-first (i.e., [c, h, w])\n * @param {number[]} size The output size of the image\n * @param {string} mode The interpolation mode\n * @param {boolean} align_corners Whether to align corners.\n * @returns {Tensor} The interpolated tensor.\n */\nexport function interpolate(input, [out_height, out_width], mode = 'bilinear', align_corners = false) {\n\n // Input image dimensions\n const in_channels = input.dims.at(-3) ?? 1;\n const in_height = input.dims.at(-2);\n const in_width = input.dims.at(-1);\n\n let output = interpolate_data(\n /** @type {import('./maths.js').TypedArray}*/(input.data),\n [in_channels, in_height, in_width],\n [out_height, out_width],\n mode,\n align_corners\n );\n return new Tensor(input.type, output, [in_channels, out_height, out_width]);\n}\n\n\n/**\n * Down/up samples the input.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html.\n * @param {Tensor} input the input tensor\n * @param {Object} options the options for the interpolation\n * @param {[number, number]|[number, number, number]|[number, number, number, number]} [options.size=null] output spatial size.\n * @param {\"bilinear\"|\"bicubic\"} [options.mode='bilinear'] algorithm used for upsampling\n * @returns {Promise} The interpolated tensor.\n */\nexport async function interpolate_4d(input, {\n size = null,\n mode = 'bilinear',\n} = {}) {\n\n // Error checking\n if (input.dims.length !== 4) {\n throw new Error('`interpolate_4d` currently only supports 4D input.');\n }\n if (!size) {\n // TODO: support scale_factor\n throw new Error('`interpolate_4d` requires a `size` argument.');\n }\n\n // Fill in missing dimensions\n let targetDims;\n if (size.length === 2) {\n targetDims = [...input.dims.slice(0, 2), ...size];\n } else if (size.length === 3) {\n targetDims = [input.dims[0], ...size];\n } else if (size.length === 4) {\n targetDims = size;\n } else {\n throw new Error('`size` must be of length 2, 3, or 4.');\n }\n\n let op;\n if (mode === 'bilinear') {\n op = await TensorOpRegistry.bilinear_interpolate_4d;\n } else if (mode === 'bicubic') {\n op = await TensorOpRegistry.bicubic_interpolate_4d;\n } else {\n throw new Error(`Unsupported mode: ${mode}`);\n }\n\n const sizeTensor = new Tensor('int64', new BigInt64Array(targetDims.map(BigInt)), [targetDims.length]);\n return await op({ x: input, s: sizeTensor });\n}\n\n/**\n * Matrix product of two tensors.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.matmul.html\n * @param {Tensor} a the first tensor to be multiplied\n * @param {Tensor} b the second tensor to be multiplied\n * @returns {Promise} The matrix product of the two tensors.\n */\nexport async function matmul(a, b) {\n const op = await TensorOpRegistry.matmul;\n return await op({ a, b });\n}\n\n/**\n * Computes the one dimensional Fourier transform of real-valued input.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.fft.rfft.html\n * @param {Tensor} x the real input tensor\n * @param {Tensor} a The dimension along which to take the one dimensional real FFT.\n * @returns {Promise} the output tensor.\n */\nexport async function rfft(x, a) {\n const op = await TensorOpRegistry.rfft;\n return await op({ x, a });\n}\n\n\n/**\n * Returns the k largest elements of the given input tensor.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.topk.html\n * @param {Tensor} x the input tensor\n * @param {number} k the k in \"top-k\"\n * @returns {Promise<[Tensor, Tensor]>} the output tuple of (Tensor, LongTensor) of top-k elements and their indices.\n */\nexport async function topk(x, k) {\n const op = await TensorOpRegistry.top_k;\n\n if (k === null) {\n k = x.dims.at(-1);\n } else {\n k = Math.min(k, x.dims.at(-1));\n }\n return await op({\n x,\n k: new Tensor(\n 'int64',\n [BigInt(k)],\n [1]\n )\n });\n}\n\n/**\n * Perform mean pooling of the last hidden state followed by a normalization step.\n * @param {Tensor} last_hidden_state Tensor of shape [batchSize, seqLength, embedDim]\n * @param {Tensor} attention_mask Tensor of shape [batchSize, seqLength]\n * @returns {Tensor} Returns a new Tensor of shape [batchSize, embedDim].\n */\nexport function mean_pooling(last_hidden_state, attention_mask) {\n // last_hidden_state: [batchSize, seqLength, embedDim]\n // attention_mask: [batchSize, seqLength]\n const lastHiddenStateData = last_hidden_state.data;\n const attentionMaskData = attention_mask.data;\n\n const shape = [last_hidden_state.dims[0], last_hidden_state.dims[2]];\n\n // @ts-ignore\n const returnedData = new lastHiddenStateData.constructor(shape[0] * shape[1]);\n const [batchSize, seqLength, embedDim] = last_hidden_state.dims;\n\n let outIndex = 0;\n for (let i = 0; i < batchSize; ++i) {\n const offset = i * embedDim * seqLength;\n\n for (let k = 0; k < embedDim; ++k) {\n let sum = 0;\n let count = 0;\n\n const attnMaskOffset = i * seqLength;\n const offset2 = offset + k;\n // Pool over all words in sequence\n for (let j = 0; j < seqLength; ++j) {\n // index into attention mask\n const attn = Number(attentionMaskData[attnMaskOffset + j]);\n\n count += attn;\n sum += lastHiddenStateData[offset2 + j * embedDim] * attn;\n }\n\n const avg = sum / count;\n returnedData[outIndex++] = avg;\n }\n }\n\n return new Tensor(\n last_hidden_state.type,\n returnedData,\n shape\n )\n}\n\n/**\n * Apply Layer Normalization for last certain number of dimensions.\n * @param {Tensor} input The input tensor\n * @param {number[]} normalized_shape input shape from an expected input of size\n * @param {Object} options The options for the layer normalization\n * @param {number} [options.eps=1e-5] A value added to the denominator for numerical stability.\n * @returns {Tensor} The normalized tensor.\n */\nexport function layer_norm(input, normalized_shape, {\n eps = 1e-5,\n} = {}) {\n if (input.dims.length !== 2) {\n throw new Error('`layer_norm` currently only supports 2D input.');\n }\n\n const [batchSize, featureDim] = input.dims;\n\n if (normalized_shape.length !== 1 && normalized_shape[0] !== featureDim) {\n throw new Error('`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.');\n }\n\n const [std, mean] = std_mean(input, 1, 0, true);\n const stdData = /** @type {Float32Array} */(std.data);\n const meanData = /** @type {Float32Array} */(mean.data);\n\n const inputData = /** @type {Float32Array} */(input.data);\n\n // @ts-ignore\n const returnedData = new inputData.constructor(inputData.length);\n\n for (let i = 0; i < batchSize; ++i) {\n const offset = i * featureDim;\n for (let j = 0; j < featureDim; ++j) {\n const offset2 = offset + j;\n returnedData[offset2] = (inputData[offset2] - meanData[i]) / (stdData[i] + eps);\n }\n }\n return new Tensor(input.type, returnedData, input.dims);\n}\n\n/**\n * Helper function to calculate new dimensions when performing a squeeze operation.\n * @param {number[]} dims The dimensions of the tensor.\n * @param {number|number[]|null} dim The dimension(s) to squeeze.\n * @returns {number[]} The new dimensions.\n * @private\n */\nfunction calc_squeeze_dims(dims, dim) {\n dims = dims.slice();\n if (dim === null) {\n dims = dims.filter((d) => d !== 1);\n } else if (typeof dim === 'number') {\n if (dims[dim] === 1) {\n dims.splice(dim, 1);\n }\n } else if (Array.isArray(dim)) {\n dims = dims.filter((x, i) => {\n return x !== 1 || !dim.includes(i);\n });\n }\n return dims;\n}\n\n/**\n * Helper function to calculate new dimensions when performing an unsqueeze operation.\n * @param {number[]} dims The dimensions of the tensor.\n * @param {number} dim The dimension to unsqueeze.\n * @returns {number[]} The new dimensions.\n * @private\n */\nfunction calc_unsqueeze_dims(dims, dim) {\n // Dimension out of range (e.g., \"expected to be in range of [-4, 3], but got 4\")\n // + 1 since we allow inserting at the end (i.e. dim = -1)\n dim = safeIndex(dim, dims.length + 1);\n dims = dims.slice();\n // Insert 1 into specified dimension\n dims.splice(dim, 0, 1);\n return dims;\n}\n\n/**\n * Safely calculate the index for an array of a given size, allowing negative indexing.\n * @param {number} index The index that will be used.\n * @param {number} size The size of the array.\n * @param {number} [dimension=null] The dimension that the index is for (optional).\n * @returns {number} The index, guaranteed to be non-negative and less than `arrayLength`.\n *\n * @throws {Error} If the index is out of range.\n * @private\n */\nfunction safeIndex(index, size, dimension = null, boundsCheck = true) {\n if (boundsCheck && (index < -size || index >= size)) {\n throw new Error(`IndexError: index ${index} is out of bounds for dimension${dimension === null ? '' : ' ' + dimension} with size ${size}`);\n }\n\n if (index < 0) {\n // Negative indexing, ensuring positive index\n index = ((index % size) + size) % size;\n }\n return index;\n}\n\n/**\n * Concatenates an array of tensors along a specified dimension.\n * @param {Tensor[]} tensors The array of tensors to concatenate.\n * @param {number} dim The dimension to concatenate along.\n * @returns {Tensor} The concatenated tensor.\n */\nexport function cat(tensors, dim = 0) {\n dim = safeIndex(dim, tensors[0].dims.length);\n\n // TODO do validation of shapes\n\n const resultDims = tensors[0].dims.slice();\n resultDims[dim] = tensors.reduce((a, b) => a + b.dims[dim], 0);\n\n // Create a new array to store the accumulated values\n const resultSize = resultDims.reduce((a, b) => a * b, 1);\n // @ts-ignore\n const result = new tensors[0].data.constructor(resultSize);\n\n // Create output tensor of same type as first\n const resultType = tensors[0].type;\n\n if (dim === 0) {\n // Handle special case for performance reasons\n\n let offset = 0;\n for (const tensor of tensors) {\n const tensorData = tensor.data;\n result.set(tensorData, offset);\n offset += tensorData.length;\n }\n\n } else {\n\n let currentDim = 0;\n\n for (let t = 0; t < tensors.length; ++t) {\n const { data, dims } = tensors[t];\n\n // Iterate over the data array\n for (let i = 0; i < data.length; ++i) {\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = dims[j];\n let index = num % size;\n if (j === dim) {\n index += currentDim;\n }\n resultIndex += index * resultMultiplier;\n resultMultiplier *= resultDims[j];\n num = Math.floor(num / size);\n }\n // Accumulate the value at the current index\n result[resultIndex] = data[i];\n }\n\n currentDim += dims[dim];\n }\n }\n return new Tensor(resultType, result, resultDims);\n}\n\n/**\n * Stack an array of tensors along a specified dimension.\n * @param {Tensor[]} tensors The array of tensors to stack.\n * @param {number} dim The dimension to stack along.\n * @returns {Tensor} The stacked tensor.\n */\nexport function stack(tensors, dim = 0) {\n // TODO do validation of shapes\n // NOTE: stack expects each tensor to be equal size\n return cat(tensors.map(t => t.unsqueeze(dim)), dim);\n}\n\n\n/**\n * Calculates the standard deviation and mean over the dimensions specified by dim. dim can be a single dimension or `null` to reduce over all dimensions.\n * @param {Tensor} input the input tenso\n * @param {number|null} dim the dimension to reduce. If None, all dimensions are reduced.\n * @param {number} correction difference between the sample size and sample degrees of freedom. Defaults to Bessel's correction, correction=1.\n * @param {boolean} keepdim whether the output tensor has dim retained or not.\n * @returns {Tensor[]} A tuple of (std, mean) tensors.\n */\nexport function std_mean(input, dim = null, correction = 1, keepdim = false) {\n const inputData = /** @type {Float32Array} */(input.data);\n const inputDims = input.dims;\n\n if (dim === null) {\n // None to reduce over all dimensions.\n const sum = inputData.reduce((a, b) => a + b, 0);\n const mean = sum / inputData.length;\n const std = Math.sqrt(inputData.reduce((a, b) => a + (b - mean) ** 2, 0) / (inputData.length - correction));\n\n const meanTensor = new Tensor(input.type, [mean], [/* scalar */]);\n const stdTensor = new Tensor(input.type, [std], [/* scalar */]);\n\n return [stdTensor, meanTensor];\n }\n\n // Negative indexing\n dim = safeIndex(dim, inputDims.length);\n\n const meanTensor = mean(input, dim, keepdim);\n const meanTensorData = meanTensor.data;\n\n // Calculate the shape of the resulting array after summation\n const resultDims = inputDims.slice(); // Copy the original dimensions\n resultDims[dim] = 1; // Remove the specified axis\n\n // Create a new array to store the accumulated values\n // @ts-ignore\n const result = new inputData.constructor(inputData.length / inputDims[dim]);\n\n // Iterate over the data array\n for (let i = 0; i < inputData.length; ++i) {\n\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = inputDims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = inputDims[j];\n if (j !== dim) {\n const index = num % size;\n resultIndex += index * resultMultiplier;\n resultMultiplier *= resultDims[j];\n }\n num = Math.floor(num / size);\n }\n\n // Accumulate the value at the current index\n result[resultIndex] += (inputData[i] - meanTensorData[resultIndex]) ** 2;\n }\n\n for (let i = 0; i < result.length; ++i) {\n result[i] = Math.sqrt(result[i] / (inputDims[dim] - correction));\n }\n\n if (!keepdim) {\n resultDims.splice(dim, 1);\n }\n\n const stdTensor = new Tensor(input.type, result, resultDims);\n\n return [stdTensor, meanTensor];\n}\n\n\n/**\n * Returns the mean value of each row of the input tensor in the given dimension dim.\n * @param {Tensor} input the input tensor.\n * @param {number|null} dim the dimension to reduce.\n * @param {boolean} keepdim whether the output tensor has dim retained or not.\n * @returns {Tensor} A new tensor with means taken along the specified dimension.\n */\nexport function mean(input, dim = null, keepdim = false) {\n const inputData = /** @type {Float32Array} */(input.data);\n\n if (dim === null) {\n // None to reduce over all dimensions.\n // @ts-ignore\n const val = inputData.reduce((a, b) => a + b, 0);\n return new Tensor(input.type, [val / inputData.length], [/* scalar */]);\n }\n const inputDims = input.dims;\n\n // Negative indexing\n dim = safeIndex(dim, inputDims.length);\n\n // Calculate the shape of the resulting array after summation\n const resultDims = inputDims.slice(); // Copy the original dimensions\n resultDims[dim] = 1; // Remove the specified axis\n\n // Create a new array to store the accumulated values\n // @ts-ignore\n const result = new inputData.constructor(inputData.length / inputDims[dim]);\n\n // Iterate over the data array\n for (let i = 0; i < inputData.length; ++i) {\n\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = inputDims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = inputDims[j];\n if (j !== dim) {\n const index = num % size;\n resultIndex += index * resultMultiplier;\n resultMultiplier *= resultDims[j];\n }\n num = Math.floor(num / size);\n }\n\n // Accumulate the value at the current index\n result[resultIndex] += inputData[i];\n }\n\n if (inputDims[dim] !== 1) {\n for (let i = 0; i < result.length; ++i) {\n result[i] = result[i] / inputDims[dim];\n }\n }\n\n if (!keepdim) {\n resultDims.splice(dim, 1);\n }\n\n return new Tensor(input.type, result, resultDims);\n}\n\n\nfunction dimsToStride(dims) {\n const stride = new Array(dims.length);\n for (let i = dims.length - 1, s2 = 1; i >= 0; --i) {\n stride[i] = s2;\n s2 *= dims[i];\n }\n return stride;\n}\n\nfunction fullHelper(size, fill_value, dtype, cls) {\n const numElements = size.reduce((a, b) => a * b, 1);\n return new Tensor(\n dtype,\n new cls(numElements).fill(fill_value),\n size\n )\n}\n\n/**\n * Creates a tensor of size size filled with fill_value. The tensor's dtype is inferred from fill_value.\n * @param {number[]} size A sequence of integers defining the shape of the output tensor.\n * @param {number|bigint} fill_value The value to fill the output tensor with.\n * @returns {Tensor} The filled tensor.\n */\nexport function full(size, fill_value) {\n let dtype;\n let typedArrayCls;\n if (typeof fill_value === 'number') {\n dtype = 'float32';\n typedArrayCls = Float32Array;\n } else if (typeof fill_value === 'bigint') {\n dtype = 'int64';\n typedArrayCls = BigInt64Array;\n } else {\n // TODO: support other dtypes\n throw new Error(`Unsupported data type: ${typeof fill_value}`);\n }\n return fullHelper(size, fill_value, dtype, typedArrayCls);\n}\n\nexport function full_like(tensor, fill_value) {\n return full(tensor.dims, fill_value);\n}\n\n/**\n * Returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size.\n * @param {number[]} size A sequence of integers defining the shape of the output tensor.\n * @returns {Tensor} The ones tensor.\n */\nexport function ones(size) {\n return fullHelper(size, 1n, 'int64', BigInt64Array);\n}\n\n/**\n * Returns a tensor filled with the scalar value 1, with the same size as input.\n * @param {Tensor} tensor The size of input will determine size of the output tensor.\n * @returns {Tensor} The ones tensor.\n */\nexport function ones_like(tensor) {\n return ones(tensor.dims);\n}\n\n/**\n * Returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size.\n * @param {number[]} size A sequence of integers defining the shape of the output tensor.\n * @returns {Tensor} The zeros tensor.\n */\nexport function zeros(size) {\n return fullHelper(size, 0n, 'int64', BigInt64Array);\n}\n\n/**\n * Returns a tensor filled with the scalar value 0, with the same size as input.\n * @param {Tensor} tensor The size of input will determine size of the output tensor.\n * @returns {Tensor} The zeros tensor.\n */\nexport function zeros_like(tensor) {\n return zeros(tensor.dims);\n}\n\n/**\n * Quantizes the embeddings tensor to binary or unsigned binary precision.\n * @param {Tensor} tensor The tensor to quantize.\n * @param {'binary'|'ubinary'} precision The precision to use for quantization.\n * @returns {Tensor} The quantized tensor.\n */\nexport function quantize_embeddings(tensor, precision) {\n if (tensor.dims.length !== 2) {\n throw new Error(\"The tensor must have 2 dimensions\");\n }\n if (tensor.dims.at(-1) % 8 !== 0) {\n throw new Error(\"The last dimension of the tensor must be a multiple of 8\");\n }\n if (!['binary', 'ubinary'].includes(precision)) {\n throw new Error(\"The precision must be either 'binary' or 'ubinary'\");\n }\n\n const signed = precision === 'binary';\n const dtype = signed ? 'int8' : 'uint8';\n\n // Create a typed array to store the packed bits\n const cls = signed ? Int8Array : Uint8Array;\n const inputData = tensor.data;\n const outputData = new cls(inputData.length / 8);\n\n // Iterate over each number in the array\n for (let i = 0; i < inputData.length; ++i) {\n // Determine if the number is greater than 0\n const bit = inputData[i] > 0 ? 1 : 0;\n\n // Calculate the index in the typed array and the position within the byte\n const arrayIndex = Math.floor(i / 8);\n const bitPosition = i % 8;\n\n // Pack the bit into the typed array\n outputData[arrayIndex] |= bit << (7 - bitPosition);\n if (signed && bitPosition === 0) {\n outputData[arrayIndex] -= 128;\n }\n };\n\n return new Tensor(dtype, outputData, [tensor.dims[0], tensor.dims[1] / 8]);\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","var scriptUrl;\nif (typeof import.meta.url === \"string\") scriptUrl = import.meta.url\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl;","__webpack_require__.b = new URL(\"./\", import.meta.url);\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t\"transformers.min\": 0\n};\n\n// no install chunk\n\n// no chunk on demand loading\n\n// no prefetching\n\n// no preloaded\n\n// no external install chunk\n\n// no on chunks loaded"],"names":["leafPrototypes","getProto","TOKEN_TYPES","Object","freeze","Text","NumericLiteral","BooleanLiteral","StringLiteral","Identifier","Equals","OpenParen","CloseParen","OpenStatement","CloseStatement","OpenExpression","CloseExpression","OpenSquareBracket","CloseSquareBracket","OpenCurlyBracket","CloseCurlyBracket","Comma","Dot","Colon","Pipe","CallOperator","AdditiveBinaryOperator","MultiplicativeBinaryOperator","ComparisonBinaryOperator","UnaryOperator","Set","If","For","In","Is","NotIn","Else","EndIf","ElseIf","EndFor","And","Or","Not","Macro","EndMacro","KEYWORDS","set","for","in","is","if","else","endif","elif","endfor","and","or","not","macro","endmacro","true","false","True","False","Token","constructor","value","type","this","isWord","char","test","isInteger","ORDERED_MAPPING_TABLE","ESCAPE_CHARACTERS","Map","tokenize","source","options","tokens","src","template","endsWith","slice","replace","lstrip_blocks","trim_blocks","preprocess","cursorPosition","consumeWhile","predicate","str","length","SyntaxError","escaped","unescaped","get","main","lastTokenType","at","text","push","char2","lastTokenType2","num","token","word","hasOwn","pop","c","Statement","Program","body","super","alternate","loopvar","iterable","defaultBlock","SetStatement","assignee","name","args","Expression","MemberExpression","object","property","computed","CallExpression","callee","Literal","ArrayLiteral","TupleLiteral","ObjectLiteral","BinaryExpression","operator","left","right","FilterExpression","operand","filter","SelectExpression","TestExpression","negate","UnaryExpression","argument","SliceExpression","start","stop","step","KeywordArgumentExpression","key","parse","program","current","expect","error","prev","Error","parseAny","result","parseSetStatement","parseIfStatement","parsePrimaryExpression","parseArgs","parseMacroStatement","loopVariable","parseExpressionSequence","parseExpression","alternative","parseForStatement","parseJinjaStatement","parseJinjaExpression","types","some","i","every","primary","fn","expressions","isTuple","a","parseLogicalOrExpression","b","parseIfExpression","parseLogicalAndExpression","parseLogicalNegationExpression","arg","parseAdditiveExpression","parseComparisonExpression","parseMultiplicativeExpression","parseCallMemberExpression","member","parseMemberExpressionArgumentsList","parseMemberExpression","parseCallExpression","callExpression","parseArgumentsList","slices","isSlice","parseTestExpression","parseFilterExpression","toString","Number","toLowerCase","expression","values","range","array","direction","Math","sign","max","min","titleCase","toUpperCase","RuntimeValue","builtins","__bool__","BooleanValue","NumericValue","StringValue","FunctionValue","trim","ObjectValue","size","defaultValue","NullValue","ArrayValue","Array","from","entries","map","KeywordArgumentsValue","TupleValue","UndefinedValue","Environment","parent","variables","tests","declareVariable","convertToRuntimeValues","has","setVariable","resolve","lookupVariable","Interpreter","global","env","run","evaluate","evaluateBinaryExpression","node","environment","concat","find","x","includes","evaluateArguments","positionalArguments","keywordArguments","kwarg","evaluateFilterExpression","toJSON","reverse","sort","localeCompare","charAt","split","join","abs","filterName","kwargs","indent","attr","testName","testFunction","filtered","item","mapped","width","first","blank","lines","repeat","indented","evaluateTestExpression","evaluateUnaryExpression","evalProgram","evaluateBlock","statements","statement","lastEvaluated","evaluateIdentifier","evaluateCallExpression","expr","evaluateSliceExpression","evaluateMemberExpression","evaluateSet","rhs","variableName","JSON","stringify","evaluateIf","evaluateFor","scope","select","items","scopeUpdateFunctions","loopScope","scopeUpdateFunction","scope2","j","noIteration","loop","evaluateMacro","macroScope","nodeArg","passedArg","identifier","mapping","evaluatedKey","input","isArray","_scope","depth","currentDepth","indentValue","basePadding","childrenPadding","core","v","Template","parsed","render","backends","backendsSortedByPriority","registerBackend","backend","priority","init","createInferenceSessionHandler","TypeError","currentBackend","undefined","indexOf","splice","tryResolveAndInitializeBackend","async","backendName","backendInfo","initialized","aborted","isInitializing","initPromise","e","resolveBackendAndExecutionProviders","eps","executionProviders","backendHints","backendNames","errors","availableBackendNames","resolveResult","err","add","console","warn","filteredEps","Proxy","target","prop","Reflect","logLevelValue","wasm","webgl","webgpu","versions","common","version","logLevel","defineProperty","enumerable","InferenceSession","handler","feeds","arg1","arg2","TRACE_FUNC_BEGIN","fetches","Tensor","isFetchesEmpty","outputNames","RangeError","isFetches","arg1Keys","getOwnPropertyNames","inputNames","results","returnValue","hasOwnProperty","call","data","dims","TRACE_FUNC_END","release","dispose","create","arg0","arg3","filePathOrUint8Array","Uint8Array","ArrayBuffer","SharedArrayBuffer","buffer","byteOffset","byteLength","isSafeInteger","optionsWithValidatedEPs","startProfiling","endProfiling","tensorToDataURL","tensor","canvas","document","createElement","OffscreenCanvas","height","pixels2DContext","getContext","tensorLayout","inputformat","format","norm","normMean","normBias","mean","bias","stride","rTensorPointer","gTensorPointer","bTensorPointer","aTensorPointer","R","G","B","A","fillStyle","fillRect","toDataURL","tensorToImageData","image","channels","rImagePointer","gImagePointer","bImagePointer","aImagePointer","createImageData","bufferToTensor","outputformat","tensorFormat","float32Data","Float32Array","tensorFromImage","isHTMLImageEle","HTMLImageElement","isImageDataEle","ImageData","isImageBitmap","ImageBitmap","isString","bufferToTensorOptions","createCanvas","createCanvasContext","HTMLCanvasElement","resizedHeight","resizedWidth","drawImage","getImageData","Promise","reject","context","newImage","Image","crossOrigin","onload","img","tempCanvas","putImageData","tensorFromTexture","texture","download","location","tensorFromGpuBuffer","gpuBuffer","dataType","tensorFromPinnedBuffer","NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP","Int8Array","Uint16Array","Int16Array","Int32Array","Float64Array","Uint32Array","NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP","isTypedArrayChecked","checkTypedArray","isBigInt64ArrayAvailable","BigInt64Array","isBigUint64ArrayAvailable","BigUint64Array","isFloat16ArrayAvailable","Float16Array","dataLocation","expectedTypedArrayConstructor","cpuData","gpuTextureData","downloader","disposer","gpuBufferData","maybeDims","typedArrayConstructor","BigInt","firstElementType","mappedType","calculateSize","fromImage","fromTexture","fromGpuBuffer","fromPinnedBuffer","toImageData","ensureValid","getData","releaseData","isDownloading","reshape","tensorReshape","dim","TRACE","deviceType","label","trace","timeStamp","TRACE_FUNC","msg","extraMsg","stack","hasTraceFunc","TrainingSession","hasOptimizerModel","hasEvalModel","trainingInputNames","trainingOutputNames","evalInputNames","evalOutputNames","trainingOptions","sessionOptions","evalModel","optimizerModel","createTrainingSessionHandler","checkpointState","trainModel","typeNarrowingForRunStep","convertHandlerReturnTypeToMapOfTensors","lazyResetGrad","runTrainStep","runOptimizerStep","runEvalStep","getParametersSize","trainableOnly","loadParametersBuffer","paramsSize","getContiguousParameters","$r","$t","xt","Bp","xr","ia","sa","Re","ve","la","da","Kn","pa","ma","fa","ha","ga","St","qt","ya","wa","va","$a","Oe","De","Cr","Sa","Ue","Be","Ar","Mp","kr","Up","Fn","Pp","getOwnPropertyDescriptor","zp","Op","prototype","qn","require","apply","arguments","t","r","Ft","vr","n","o","Dp","Sr","d","l","oa","aa","jn","ua","ca","m","u","h","w","y","g","$","S","T","C","ba","Tr","mlTensor","_a","xa","mlTensorData","Uint8ClampedArray","ceil","fromMLTensor","Ir","Yn","Ta","Ia","Ca","Aa","ka","Ea","Pa","za","Zn","He","Er","Ma","default","Vp","Da","Ba","Ra","Xn","gt","jt","globalThis","self","onmessage","Pr","then","zr","postMessage","epName","Kt","out","model","Dr","Br","sessionId","inputIndices","inputs","outputIndices","Mr","fill","Ur","Rr","Worker","Bt","Va","Np","Qn","Ua","Wp","Lp","Gp","Wa","La","Hp","Ga","Jn","eo","Vr","Ha","Fp","qp","Te","ke","Yt","pe","Fa","jp","Kp","Yp","Zp","ja","Zt","bt","Tt","Wr","Xt","Lr","Gr","to","Qt","Xp","Qp","Ya","Za","Hr","Jp","se","Fr","Xa","oo","io","em","tm","Qa","so","ao","es","uo","re","lo","et","k","It","jr","rs","ns","Ct","po","me","Ee","V","ye","mo","At","Ke","F","fo","E","M","Kr","co","os","rm","nm","om","im","Pe","as","ss","am","sm","um","lm","dm","cm","pm","mm","fm","hm","tt","us","ls","ds","cs","ps","ms","fs","hs","gs","bs","rt","gm","Zr","ho","nt","bm","ym","wm","_m","vm","$m","xm","Sm","Tm","Im","ot","ws","_s","vs","$s","xs","Ss","Ts","Cs","As","ks","Es","Ps","go","Cm","bo","Am","km","Em","Rt","Pm","Os","zm","Om","Dm","Ds","Bm","Mm","Ms","Rm","fe","Us","Vs","Ns","Ws","Ls","Gs","Hs","Fs","qs","Um","js","Ks","Ys","Zs","Jt","Xs","Qr","Qs","Js","eu","tu","ru","nu","ou","iu","au","su","uu","lu","du","cu","pu","mu","fu","hu","yo","wo","gu","bu","yu","Vm","Nm","wu","Wm","Lm","vu","Gm","Hm","it","xu","Su","Tu","Iu","Cu","Au","ku","Eu","Pu","zu","qm","jm","Km","Ym","Du","Bu","Ve","Ne","We","en","ze","tn","rn","tr","nn","Zm","Xm","rr","Ru","Qm","nr","Jm","ef","Uu","tf","Nu","an","rf","Wu","nf","Lu","Gu","Fu","qu","of","vo","af","$o","xo","Ku","sf","uf","So","lf","Zu","df","To","cf","pf","mf","Ju","el","ff","hf","gf","bf","tl","yf","nl","ol","wf","_f","vf","al","sl","Io","sn","ll","xf","Co","Ao","dl","Sf","cl","pl","Tf","fl","Cf","hl","Af","bl","kf","Ef","wl","_l","Pf","zf","$l","xl","Of","Df","Tl","Il","Bf","Mf","Al","kl","dt","yt","Ut","Vt","Rf","Vf","Nf","Wf","Lf","Gf","Hf","Pl","zl","Me","jf","Bl","Dl","Kf","ar","Ml","Yf","Zf","Xf","Qf","Eo","Rl","Ul","Jf","eh","Vl","Nl","Ll","th","rh","Gl","nh","oh","Fl","ih","jl","ah","sh","uh","Yl","Zl","lh","dh","ch","ph","mh","fh","hh","gh","Ql","un","ed","td","rd","nd","bh","yh","od","id","ad","sd","ud","ld","dd","cd","pd","md","fd","hd","_h","vh","bd","yd","$h","xh","_d","Sh","Th","Ih","Ch","Ah","kh","Eh","Ph","zh","Oh","Dh","$d","Bh","Mh","Rh","Uh","Vh","xd","Sd","Nh","Wh","Id","Lh","Gh","Ad","Hh","ln","Fh","Ed","qh","jh","Pd","zd","Kh","Yh","Dd","Bd","Rd","Zh","Xh","Qh","Ud","Jh","eg","Nd","Ld","dn","tg","rg","zo","Oo","cn","ng","qd","og","jd","pn","mn","Do","Kd","Zd","ig","Na","url","ue","Q","be","ne","we","Ae","$e","de","N","qe","assign","s","p","window","importScripts","mountExternalData","startsWith","substring","Eb","unmountExternalData","WebAssembly","Memory","initial","maximum","shared","f","_","I","D","Qe","H","X","Rn","Fb","fc","Gb","flush","all","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput","jsepInit","Ub","Yb","Nb","Xb","jb","Zb","bc","Vb","Wb","$b","jsepRegisterBuffer","registerBuffer","jsepGetBuffer","getBuffer","jsepCreateDownloader","createDownloader","jsepOnCreateSession","onCreateSession","jsepOnReleaseSession","onReleaseSession","jsepOnRunStart","onRunStart","cc","upload","ac","Ob","jsepEnsureTensor","dc","jsepDownloadTensor","jsepReleaseTensorId","jsepRegisterMLContext","registerMLContext","jsepCreateMLTensorDownloader","createMLTensorDownloader","jsepRegisterMLTensor","registerMLTensor","jsepCreateMLContext","createMLContext","qc","registerMLConstant","P","href","currentScript","substr","lastIndexOf","XMLHttpRequest","open","responseType","send","response","status","onerror","O","U","log","bind","L","K","cmd","startWorker","handlers","proxy","Mb","oc","wasmMemory","W","wasmModule","Wn","pthread_ptr","Dn","hc","Yo","ee","qi","gc","start_routine","Dt","wr","dr","ji","alert","rc","instantiateWasm","Instance","Ho","onunhandledrejection","reason","wasmBinary","Z","J","q","he","_e","HEAP8","HEAP16","HEAPU8","HEAPU16","HEAP32","HEAPU32","HEAPF32","HEAPF64","HEAP64","HEAPU64","Ye","Lt","_n","Gt","vn","Ht","Vo","clearInterval","ct","RuntimeError","$n","No","Wo","Lo","Go","fetch","credentials","ok","arrayBuffer","catch","instantiate","mc","yc","Jo","ri","qa","ni","Y","ii","ai","ra","si","ui","li","na","di","ci","pi","mi","fi","hi","wc","vc","$c","Sc","Ic","Cc","Ac","kc","Mc","Rc","Uc","Vc","Nc","Wc","Lc","ta","Gc","Hc","jc","Kc","Zc","zn","Xc","ep","tp","rp","np","op","ip","ap","sp","up","lp","dp","ea","cp","pp","mp","ki","Ei","fp","hp","gp","bp","yp","wp","_p","vp","zi","z","$p","xp","Sp","Tp","Ip","Bi","Mi","Cn","Ri","Ui","Vi","Ni","Gi","kp","xn","Ce","subarray","wasmOffsetConverter","alpha","beta","keepDims","noopWithEmptyAxes","axes","perm","blocksize","mode","ce","ge","le","autoPad","dilations","group","kernelShape","pads","strides","wIsConst","outputPadding","outputShape","activation","auto_pad","ceil_mode","count_include_pad","storage_order","kernel_shape","transA","transB","selectLastIndex","axis","numOutputs","splitSizes","antialias","coordinateTransformMode","cubicCoeffA","excludeOutside","extrapolationValue","keepAspectRatioPolicy","nearestMode","starts","ends","epsilon","equation","momentum","spatial","trainingMode","exclusive","blockSize","align_corners","padding_mode","numHeads","isUnidirectional","maskFilterValue","scale","doRotary","qkvHiddenSizes","pastPresentShareBuffer","Se","w_is_const","activation_params","kvNumHeads","softcap","rotaryInterleaved","smoothSoftmax","localWindowSize","simplified","accuracyLevel","bits","interleaved","rotaryEmbeddingDim","gatherAxis","quantizeAxis","Si","Sn","message","Tn","terminate","Fo","pt","Xo","Zo","_t","Ze","Ab","Qb","wt","xe","Hn","Gn","Ki","_r","qo","jo","Ko","Ln","forEach","targetThread","transferList","thread","loaded","threadId","filename","lineno","URL","workerData","lr","shift","Zi","Xi","Jb","Qo","ei","TextDecoder","ti","decode","String","fromCharCode","An","charCodeAt","oi","Pt","gi","mt","Xe","kn","En","_c","Sb","bi","fromWireType","toWireType","argPackAdvance","ft","readValueFromPointer","Db","Pn","st","Le","Ge","On","xc","Tc","Je","yr","yi","Ec","Pc","zc","Oc","Dc","Bc","Tb","wi","Atomics","nc","store","Yi","setTimeout","Bn","Ep","Mn","Fi","_i","cr","ht","vi","pr","$i","xi","Fc","Browser","Kb","Rb","resume","pause","Qi","mr","Yc","fr","Ti","Function","Qc","Jc","Ii","NaN","Date","getUTCSeconds","getUTCMinutes","getUTCHours","getUTCDate","getUTCMonth","getUTCFullYear","getUTCDay","getTime","UTC","zt","Ci","Ai","getSeconds","getMinutes","getHours","getDate","getMonth","getFullYear","getDay","getTimezoneOffset","setTime","getYear","isNaN","toLocaleTimeString","hour12","timeZoneName","Un","Pi","now","performance","timeOrigin","navigator","hardwareConcurrency","grow","hr","Ot","Oi","Pb","ec","Vn","Nn","Di","USER","LOGNAME","PATH","PWD","HOME","LANG","languages","Cp","Wi","Li","Ap","vt","Bb","Cb","setDate","setMonth","setFullYear","Hb","Lb","Ib","ub","sc","ic","lc","RegExp","floor","numThreads","unshift","Hi","gr","BindingError","InternalError","count_emval_handles","exports","Ji","Fibers","tc","fb","hb","emscripten_main_runtime_thread_id","sb","tb","ib","locateFile","instance","module","instantiateStreaming","_OrtInit","_OrtGetLastError","_OrtCreateSessionOptions","_OrtAppendExecutionProvider","_OrtAddFreeDimensionOverride","_OrtAddSessionConfigEntry","Ja","_OrtReleaseSessionOptions","Ka","_OrtReleaseSession","_OrtGetInputOutputCount","_OrtGetInputName","Oa","_OrtGetOutputName","_OrtFree","_OrtCreateTensor","_OrtGetTensorData","_OrtReleaseTensor","_OrtCreateRunOptions","_OrtAddRunConfigEntry","_OrtReleaseRunOptions","_OrtCreateBinding","_OrtBindOutput","_OrtClearBoundOutputs","_OrtReleaseBinding","ab","bb","_OrtEndProfiling","cb","_JsepOutput","db","_JsepGetNodeName","eb","br","_free","gb","_malloc","kb","lb","mb","nb","ob","pb","qb","rb","dynCall_ii","vb","wb","xb","yb","zb","calledRun","___start_em_js","___stop_em_js","stackSave","stackRestore","stackAlloc","setValue","getValue","UTF8ToString","stringToUTF8","lengthBytesUTF8","PTR_SIZE","origin","blob","createObjectURL","MessageChannel","port1","validate","initTimeout","crossOriginIsolated","wasmPaths","mjs","revokeObjectURL","race","Nr","logSeverityLevel","logVerbosityLevel","tag","extra","WeakSet","session","use_ort_model_bytes_directly","enableMemPattern","preferredLayout","graphOptimizationLevel","executionMode","logId","optimizedModelFilePath","enableCpuMemArena","enableProfiling","enableGraphCapture","freeDimensionOverrides","te","reduce","ro","headers","parseInt","getReader","done","read","Blob","je","toISOString","no","qr","ts","device","createBuffer","usage","GPUBufferUsage","COPY_DST","MAP_READ","getCommandEncoder","endComputePass","copyBufferToBuffer","mapAsync","GPUMapMode","READ","getMappedRange","destroy","storageCache","freeBuffers","freeUniformBuffers","buffersPending","capturedPendingBuffers","sessionCount","originalSize","mappedAtCreation","MAP_WRITE","COPY_SRC","unmap","createCommandEncoder","gpuData","queue","submit","finish","memcpy","registerExternalBuffer","capturedCommandList","currentSessionId","unregisterExternalBuffer","delete","STORAGE","UNIFORM","refreshPendingBuffers","sessionStatus","Ie","cacheKey","oe","calcMatMulShape","calcShape","isValidBroadcast","getSizeFromDimensionRange","convertShape","sizeFromDimension","sizeToDimension","computeStrides","normalizeAxis","normalizeAxes","sortBasedOnPerm","padShape","areEqual","adjustPoolAttributes","adjustPadsBasedOnAutoPad","adjustPadAndReturnShape","computePoolOutputShape","computeShapeHelper","computeConvOutputShape","getShapeOfGemmResult","ae","keys","indices","storage","offsetToIndices","indicesToOffset","broadcastedIndicesToOffset","setByIndices","getByIndices","impl","indicesGet","rank","indicesSet","setByOffset","getByOffset","shape","normalizedDispatchGroup","limits","internalVariables","uniforms","variableIndex","guardAgainstOutOfBoundsWorkgroupSizes","mainStart","maxComputeWorkgroupSizeX","maxComputeWorkgroupSizeY","maxComputeWorkgroupSizeZ","maxComputeInvocationsPerWorkgroup","appendVariableUniforms","declareVariables","registerInternalVariable","registerInternalVariables","registerUniform","registerUniforms","uniformDeclaration","additionalImplementations","variablesInfo","ut","newShape","newPerm","shaderCache","hint","inputDependencies","getRunData","outputs","dispatchGroup","programUniforms","getShaderSource","compute","ys","Yr","sum","prod","sumSquare","logSumExp","l1","l2","logSum","getBigInt64Array","zs","Xr","batchSize","sequenceLength","pastSequenceLength","kvSequenceLength","totalSequenceLength","maxSequenceLength","inputHiddenSize","hiddenSize","vHiddenSize","headSize","vHeadSize","maskType","broadcastResPosBias","passPastInKv","qkvFormat","nReps","sqrt","gpuDataType","outputCount","Bs","validateInputContent","Rs","Jr","getFloat32Array","getUint16Array","$u","Ou","scalar","vector","Mu","lt","clipMax","clipMin","er","_o","on","ir","Vu","Hu","trunc","top","bottom","front","back","padInfo","outDepth","outHeight","outWidth","dataFormat","inDepth","inHeight","inWidth","inChannels","outChannels","strideDepth","strideHeight","strideWidth","filterDepth","filterHeight","filterWidth","effectiveFilterDepth","effectiveFilterHeight","effectiveFilterWidth","dilationDepth","dilationHeight","dilationWidth","inShape","outShape","filterShape","ju","Yu","kernelCustomData","wT","adapterInfo","isArchitecture","Xu","Qu","rl","il","getInt32Array","ul","ml","symbolToIndices","inputIndex","addSymbol","hasEllipsis","symbolToInfo","lhs","outputDims","match","processTerm","count","ellipsisDims","dimValue","gl","yl","vl","Sl","Cl","El","Ol","alignCorners","paddingMode","ko","Po","Wl","Hl","ql","Kl","Xl","isVendor","Jl","gd","ceilMode","countIncludePad","storageOrder","wd","vd","Td","round","MAX_VALUE","MIN_VALUE","customDataBuffer","Cd","kd","Od","Md","Vd","Wd","Gd","Hd","repo","attributesBound","getArtifact","setArtifact","programInfo","getComputePassEncoder","writeTimestamp","pendingDispatchNumber","binding","resource","createBindGroup","layout","computePipeline","getBindGroupLayout","kernelId","currentKernelId","bindGroup","setPipeline","setBindGroup","dispatchWorkgroups","maxDispatchNumber","queryType","build","feature","extension","features","createShaderModule","code","createComputePipeline","entryPoint","uniformVariablesInfo","normalizeDispatchGroupSize","maxComputeWorkgroupsPerDimension","cbrt","Fd","architecture","vendor","subgroupsSupported","subgroupsF16Supported","minSubgroupSize","maxSubgroupSize","subgroupSizeRange","commandEncoder","computePassEncoder","pendingKernels","pendingQueries","capturedPendingKernels","sessionExternalDataMapping","currentKernelCustomData","initialize","requiredLimits","maxComputeWorkgroupStorageSize","maxStorageBufferBindingSize","maxBufferSize","requiredFeatures","requestDevice","deviceInfo","info","requestAdapterInfo","gpuDataManager","programManager","kernels","kernelPersistentData","debug","onuncapturederror","GPUValidationError","writable","configurable","setQueryType","querySet","timestampWrites","beginningOfPassWriteIndex","endOfPassWriteIndex","beginComputePass","end","resolveQuerySet","queryResolveBuffer","kernelType","kernelName","programName","inputTensorViews","outputTensorViews","queryTimeBase","profiling","ondata","inputsMetadata","outputsMetadata","startTime","endTime","temporaryData","writeBuffer","offset","alloc","free","createKernel","kernelEntry","attributes","releaseKernel","computeKernel","pushErrorScope","popErrorScope","unregisterBuffers","createQuerySet","QUERY_RESOLVE","captureBegin","captureEnd","replay","Yd","mlContext","tensorShape","write","writeTensor","readTensor","sameTypeAndShape","tensorManager","wrapper","tensorWrapper","releaseTensor","ensureTensor","activeUpload","MLTensorUsage","WRITE","getCachedTensor","tensorTrackersById","freeTensors","externalTensors","reserveTensorId","releaseTensorId","releaseTensorsForSession","registerTensor","currentContext","createTensor","dimensions","readable","Xd","mlContextBySessionId","sessionIdsByMLContext","mlContextCache","activeSessionId","GPUDevice","findIndex","gpuDevice","createContext","getMLContext","uploadTensor","shouldTransferToMLTensor","downloadTensor","constant","Qd","ag","sr","Bo","sg","kt","ug","Et","Fe","ur","gn","bn","hn","Mo","Ro","Nt","Wt","dg","uc","cg","yn","Jd","customDataOffset","customDataSize","opKernelContext","output","gpu","adapter","powerPreference","forceFallbackAdapter","requestAdapter","externalData","path","preferredOutputLocation","handle","outputPreferredLocations","outputPreferredLocationsEncoded","Uo","fetchModelAndCopyToWasmMemory","loadModel","OnnxruntimeWebAssemblyBackend","wn","initializeFlags","wasmBackend","pg","pc","simd","cpus","y1","DEVICE_TO_EXECUTION_PROVIDER_MAPPING","auto","cpu","cuda","dml","webnn","supportedDevices","defaultDevices","ONNX","ORT_SYMBOL","Symbol","apis","IS_NODE_ENV","process","platform","arch","IS_WEBNN_AVAILABLE","IS_WEBGPU_AVAILABLE","deviceToExecutionProviders","wasmInitPromise","createInferenceSession","session_options","session_config","sessionPromise","config","isONNXTensor","ONNX_ENV","isONNXProxy","onnx","getNormalizedConfig","init_normalized_config","model_type","text_config","phi_config","decoder","decoderConfig","add_encoder_pkv","pick","num_decoder_layers","num_decoder_heads","decoder_hidden_size","num_encoder_layers","num_encoder_heads","encoder_hidden_size","num_layers","num_heads","hidden_size","normalized_config","getKeyValueShapes","prefix","decoderFeeds","is_encoder_decoder","encoder_dim_kv","decoder_dim_kv","encoder_dims","decoder_dims","dim_kv","num_attention_heads","multi_query","keyDims","valueDims","PretrainedConfig","max_position_embeddings","configJSON","from_pretrained","pretrained_model_name_or_path","progress_callback","cache_dir","local_files_only","revision","getModelJSON","loadConfig","AutoConfig","IS_BROWSER_ENV","IS_WEBWORKER_ENV","IS_WEB_CACHE_AVAILABLE","IS_PROCESS_AVAILABLE","IS_FS_AVAILABLE","isEmpty","IS_PATH_AVAILABLE","RUNNING_LOCALLY","dirname__","DEFAULT_CACHE_DIR","DEFAULT_LOCAL_MODEL_PATH","allowRemoteModels","remoteHost","remotePathTemplate","allowLocalModels","localModelPath","useFS","useBrowserCache","useFSCache","cacheDir","useCustomCache","customCache","obj","GenerationConfig","max_length","max_new_tokens","min_length","min_new_tokens","early_stopping","max_time","do_sample","num_beams","num_beam_groups","penalty_alpha","use_cache","temperature","top_k","top_p","typical_p","epsilon_cutoff","eta_cutoff","diversity_penalty","repetition_penalty","encoder_repetition_penalty","length_penalty","no_repeat_ngram_size","bad_words_ids","force_words_ids","renormalize_logits","constraints","forced_bos_token_id","forced_eos_token_id","remove_invalid_values","exponential_decay_length_penalty","suppress_tokens","begin_suppress_tokens","forced_decoder_ids","guidance_scale","num_return_sequences","output_attentions","output_hidden_states","output_scores","return_dict_in_generate","pad_token_id","bos_token_id","eos_token_id","encoder_no_repeat_ngram_size","decoder_start_token_id","generation_kwargs","LogitsProcessor","Callable","_call","input_ids","logits","LogitsWarper","LogitsProcessorList","processors","extend","toReturn","processor","iterator","ForcedBOSTokenLogitsProcessor","batch_logits_data","Infinity","ForcedEOSTokenLogitsProcessor","eos_token","SuppressTokensAtBeginLogitsProcessor","begin_index","token_id","WhisperTimeStampLogitsProcessor","generate_config","init_tokens","no_timestamps_token_id","timestamp_begin","max_initial_timestamp_index","seq","last_was_timestamp","penultimate_was_timestamp","last_allowed","logprobs","log_softmax","exp","NoRepeatNGramLogitsProcessor","getNgrams","prevInputIds","curLen","ngrams","ngram","generatedNgram","prevNgram","prevNgramKey","prevNgramValue","getGeneratedNgrams","bannedNgrams","ngramIdx","calcBannedNgramTokens","bannedTokens","generatedNgrams","RepetitionPenaltyLogitsProcessor","penalty","input_id","MinLengthLogitsProcessor","MinNewTokensLengthLogitsProcessor","prompt_length_to_skip","NoBadWordsLogitsProcessor","ids","bad_word_ids","mark","ClassifierFreeGuidanceLogitsProcessor","unguided_bsz","cond_logits","uncond_logits","TemperatureLogitsWarper","errorMessage","TopPLogitsWarper","filter_value","min_tokens_to_keep","TopKLogitsWarper","LogitsSampler","generation_config","sample","getLogits","index","vocabSize","logs","startIndex","randomSelect","probabilities","sumProbabilities","random","getSampler","MultinomialSampler","BeamSearchSampler","GreedySampler","argmax","topk","softmax","sampledIndex","StoppingCriteria","scores","StoppingCriteriaList","criteria","is_done","criterion","criterion_done","MaxLengthCriteria","EosTokenCriteria","last","eos_id","InterruptableStoppingCriteria","interrupted","interrupt","reset","BaseStreamer","put","stdout_write","stdout","TextStreamer","tokenizer","skip_prompt","callback_function","token_callback_function","decode_kwargs","token_cache","print_len","next_tokens_are_prompt","mergeArrays","printable_text","is_chinese_char","on_finalized_text","stream_end","WhisperTextStreamer","on_chunk_start","on_chunk_end","on_finalize","time_precision","skip_special_tokens","waiting_for_timestamp","time","MODEL_TYPES","MODEL_TYPE_MAPPING","MODEL_NAME_TO_CLASS_MAPPING","MODEL_CLASS_TO_NAME_MAPPING","constructSessions","names","fromEntries","fileName","custom_config","selectedDevice","dtype","DEFAULT_DEVICE_DTYPE_MAPPING","DATA_TYPES","fp32","selectedDtype","DEFAULT_DTYPE_SUFFIX_MAPPING","fp16","isWebGpuFp16Supported","kv_cache_dtype","suffix","modelFileName","subfolder","free_dimension_overrides","bufferPromise","getModelFile","use_external_data_format","externalDataPromises","fullPath","ext","ext_buffer","shapes","getSession","getOptionalConfigs","getQueryValue","URLSearchParams","search","runs","perf","warmup","inference","throughput","getPerf","sessionRun","checkedInputs","missingInputs","inputName","clone","numInputsProvided","numInputsNeeded","ignored","validateInputs","ortFeed","ort_tensor","numOfWarmups","loopStart","arrayInference","parseFloat","toFixed","replaceTensors","toI64Tensor","flat","boolTensor","seq2seqForward","model_inputs","encoder_outputs","decoder_input_ids","other_decoder_inputs","encoder_inputs","sessions","encoderForward","last_hidden_state","encoder_hidden_states","encoder_attention_mask","attention_mask","decoderForward","encoderFeeds","inputs_embeds","encode_text","token_type_ids","past_key_values","new_model_inputs","use_cache_branch","position_ids","bz","seq_len","createPositionIds","addPastKeyValues","fixed","imageTextToTextForward","pixel_values","logits_processor","image_features","encode_image","_merge_input_ids_with_image_features","target_length","past_length","cat","ones","decoder_prepare_inputs_for_generation","image_token_index","num_image_tokens","num_new_tokens","encoder_decoder_prepare_inputs_for_generation","image_text_to_text_prepare_inputs_for_generation","PreTrainedModel","main_input_name","forward_params","configs","modelName","modelType","can_generate","_forward","_prepare_inputs_for_generation","promises","model_file_name","decoder_model_merged","prompt_encoder_mask_decoder","embed_tokens","vision_encoder","encodec_decode","GITHUB_ISSUE_URL","forward","_get_logits_warper","warpers","_get_logits_processor","input_ids_seq_length","_prepare_generation_config","cls","gen_config","_get_stopping_criteria","stopping_criteria","_validate_model_class","generate_compatible_mappings","MODEL_FOR_CAUSAL_LM_MAPPING_NAMES","MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES","MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES","MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES","generate_compatible_classes","model_mapping","supported_models","prepare_inputs_for_generation","_update_model_kwargs_for_generation","generated_input_ids","getPastKeyValues","_prepare_model_inputs","model_kwargs","input_name","inputs_tensor","model_input_name","_prepare_encoder_decoder_kwargs_for_generation","prepared_inputs","_prepare_inputs_embeds","full_like","zeros_like","decoder_input_ids_batch_size","_prepare_decoder_input_ids_for_generation","batch_size","num_codebooks","ones_like","generate","streamer","input_ids_length","prepared_logits_processor","prepared_stopping_criteria","numInputs","sampler","all_input_ids","tolist","attentions","token_attentions","getAttentions","next_tokens_scores","batch_idx","sampledTokens","newTokenId","logProb","bigint","sequences","decoderResults","pastKeyValues","disposeEncoderPKVs","pkvs","newName","is_encoder_pkv","model_output","attnName","empty","ModelOutput","BaseModelOutput","hidden_states","BertPreTrainedModel","BertModel","BertForMaskedLM","MaskedLMOutput","BertForSequenceClassification","SequenceClassifierOutput","BertForTokenClassification","TokenClassifierOutput","BertForQuestionAnswering","QuestionAnsweringModelOutput","NomicBertPreTrainedModel","NomicBertModel","RoFormerPreTrainedModel","RoFormerModel","RoFormerForMaskedLM","RoFormerForSequenceClassification","RoFormerForTokenClassification","RoFormerForQuestionAnswering","ConvBertPreTrainedModel","ConvBertModel","ConvBertForMaskedLM","ConvBertForSequenceClassification","ConvBertForTokenClassification","ConvBertForQuestionAnswering","ElectraPreTrainedModel","ElectraModel","ElectraForMaskedLM","ElectraForSequenceClassification","ElectraForTokenClassification","ElectraForQuestionAnswering","CamembertPreTrainedModel","CamembertModel","CamembertForMaskedLM","CamembertForSequenceClassification","CamembertForTokenClassification","CamembertForQuestionAnswering","DebertaPreTrainedModel","DebertaModel","DebertaForMaskedLM","DebertaForSequenceClassification","DebertaForTokenClassification","DebertaForQuestionAnswering","DebertaV2PreTrainedModel","DebertaV2Model","DebertaV2ForMaskedLM","DebertaV2ForSequenceClassification","DebertaV2ForTokenClassification","DebertaV2ForQuestionAnswering","DistilBertPreTrainedModel","DistilBertModel","DistilBertForSequenceClassification","DistilBertForTokenClassification","DistilBertForQuestionAnswering","DistilBertForMaskedLM","EsmPreTrainedModel","EsmModel","EsmForMaskedLM","EsmForSequenceClassification","EsmForTokenClassification","MobileBertPreTrainedModel","MobileBertModel","MobileBertForMaskedLM","MobileBertForSequenceClassification","MobileBertForQuestionAnswering","MPNetPreTrainedModel","MPNetModel","MPNetForMaskedLM","MPNetForSequenceClassification","MPNetForTokenClassification","MPNetForQuestionAnswering","SqueezeBertPreTrainedModel","SqueezeBertModel","SqueezeBertForMaskedLM","SqueezeBertForSequenceClassification","SqueezeBertForQuestionAnswering","AlbertPreTrainedModel","AlbertModel","AlbertForSequenceClassification","AlbertForQuestionAnswering","AlbertForMaskedLM","T5PreTrainedModel","T5Model","T5ForConditionalGeneration","LongT5PreTrainedModel","LongT5Model","LongT5ForConditionalGeneration","MT5PreTrainedModel","MT5Model","MT5ForConditionalGeneration","BartPretrainedModel","BartModel","BartForConditionalGeneration","BartForSequenceClassification","MBartPreTrainedModel","MBartModel","MBartForConditionalGeneration","MBartForSequenceClassification","MBartForCausalLM","BlenderbotPreTrainedModel","BlenderbotModel","BlenderbotForConditionalGeneration","BlenderbotSmallPreTrainedModel","BlenderbotSmallModel","BlenderbotSmallForConditionalGeneration","RobertaPreTrainedModel","RobertaModel","RobertaForMaskedLM","RobertaForSequenceClassification","RobertaForTokenClassification","RobertaForQuestionAnswering","XLMPreTrainedModel","XLMModel","XLMWithLMHeadModel","XLMForSequenceClassification","XLMForTokenClassification","XLMForQuestionAnswering","XLMRobertaPreTrainedModel","XLMRobertaModel","XLMRobertaForMaskedLM","XLMRobertaForSequenceClassification","XLMRobertaForTokenClassification","XLMRobertaForQuestionAnswering","ASTPreTrainedModel","ASTModel","ASTForAudioClassification","WhisperPreTrainedModel","requires_attention_mask","WhisperModel","WhisperForConditionalGeneration","WhisperGenerationConfig","_retrieve_init_tokens","language","task","is_multilingual","language_token","whisper_language_to_code","lang_to_id","task_to_id","return_timestamps","return_token_timestamps","alignment_heads","_extract_token_timestamps","num_frames","generate_outputs","cross_attentions","median_filter_width","batch","decoder_layers","weights","transpose","std","calculatedMean","std_mean","smoothedWeights","aTensor","bTensor","stdTensorData","meanTensorData","cTensorData","medianFilter","batchedMatrices","timestampsShape","timestamps","matrix","neg","squeeze_","text_indices","time_indices","dynamic_time_warping","diffs","jumps","jump_times","VisionEncoderDecoderModel","LlavaPreTrainedModel","LlavaForConditionalGeneration","indexOfImage","noImages","allImages","stacked","stacked_attention_mask","Moondream1ForConditionalGeneration","Florence2PreTrainedModel","Florence2ForConditionalGeneration","text_features","decoder_attention_mask","decoder_inputs_embeds","CLIPPreTrainedModel","CLIPModel","CLIPTextModel","CLIPTextModelWithProjection","CLIPVisionModel","CLIPVisionModelWithProjection","SiglipPreTrainedModel","SiglipModel","SiglipTextModel","SiglipVisionModel","ChineseCLIPPreTrainedModel","ChineseCLIPModel","CLIPSegPreTrainedModel","CLIPSegModel","CLIPSegForImageSegmentation","GPT2PreTrainedModel","GPT2Model","GPT2LMHeadModel","JAISPreTrainedModel","JAISModel","JAISLMHeadModel","GPTNeoPreTrainedModel","GPTNeoModel","GPTNeoForCausalLM","GPTNeoXPreTrainedModel","GPTNeoXModel","GPTNeoXForCausalLM","GPTJPreTrainedModel","GPTJModel","GPTJForCausalLM","GPTBigCodePreTrainedModel","GPTBigCodeModel","GPTBigCodeForCausalLM","CodeGenPreTrainedModel","CodeGenModel","CodeGenForCausalLM","LlamaPreTrainedModel","LlamaModel","LlamaForCausalLM","GranitePreTrainedModel","GraniteModel","GraniteForCausalLM","CoherePreTrainedModel","CohereModel","CohereForCausalLM","GemmaPreTrainedModel","GemmaModel","GemmaForCausalLM","Gemma2PreTrainedModel","Gemma2Model","Gemma2ForCausalLM","OpenELMPreTrainedModel","OpenELMModel","OpenELMForCausalLM","Qwen2PreTrainedModel","Qwen2Model","Qwen2ForCausalLM","PhiPreTrainedModel","PhiModel","PhiForCausalLM","Phi3PreTrainedModel","Phi3Model","Phi3ForCausalLM","BloomPreTrainedModel","BloomModel","BloomForCausalLM","MptPreTrainedModel","MptModel","MptForCausalLM","OPTPreTrainedModel","OPTModel","OPTForCausalLM","ViTPreTrainedModel","ViTModel","ViTForImageClassification","PvtPreTrainedModel","PvtModel","PvtForImageClassification","ViTMAEPreTrainedModel","ViTMAEModel","ViTMSNPreTrainedModel","ViTMSNModel","ViTMSNForImageClassification","GroupViTPreTrainedModel","GroupViTModel","FastViTPreTrainedModel","FastViTModel","FastViTForImageClassification","VitMattePreTrainedModel","VitMatteForImageMatting","ImageMattingOutput","MobileViTPreTrainedModel","MobileViTModel","MobileViTForImageClassification","MobileViTV2PreTrainedModel","MobileViTV2Model","MobileViTV2ForImageClassification","OwlViTPreTrainedModel","OwlViTModel","OwlViTForObjectDetection","Owlv2PreTrainedModel","Owlv2Model","Owlv2ForObjectDetection","BeitPreTrainedModel","BeitModel","BeitForImageClassification","DetrPreTrainedModel","DetrModel","DetrForObjectDetection","DetrObjectDetectionOutput","DetrForSegmentation","DetrSegmentationOutput","pred_boxes","pred_masks","RTDetrPreTrainedModel","RTDetrModel","RTDetrForObjectDetection","RTDetrObjectDetectionOutput","TableTransformerPreTrainedModel","TableTransformerModel","TableTransformerForObjectDetection","TableTransformerObjectDetectionOutput","DeiTPreTrainedModel","DeiTModel","DeiTForImageClassification","HieraPreTrainedModel","HieraModel","HieraForImageClassification","ResNetPreTrainedModel","ResNetModel","ResNetForImageClassification","SwinPreTrainedModel","SwinModel","SwinForImageClassification","Swin2SRPreTrainedModel","Swin2SRModel","Swin2SRForImageSuperResolution","DPTPreTrainedModel","DPTModel","DPTForDepthEstimation","DepthAnythingPreTrainedModel","DepthAnythingForDepthEstimation","SapiensPreTrainedModel","SapiensForSemanticSegmentation","SapiensForDepthEstimation","SapiensForNormalEstimation","DepthProPreTrainedModel","DepthProForDepthEstimation","MaskFormerPreTrainedModel","MaskFormerModel","MaskFormerForInstanceSegmentation","GLPNPreTrainedModel","GLPNModel","GLPNForDepthEstimation","DonutSwinPreTrainedModel","DonutSwinModel","ConvNextPreTrainedModel","ConvNextModel","ConvNextForImageClassification","ConvNextV2PreTrainedModel","ConvNextV2Model","ConvNextV2ForImageClassification","Dinov2PreTrainedModel","Dinov2Model","Dinov2ForImageClassification","YolosPreTrainedModel","YolosModel","YolosForObjectDetection","YolosObjectDetectionOutput","SamPreTrainedModel","SamModel","get_image_embeddings","image_embeddings","image_positional_embeddings","input_labels","input_points","numElements","decoder_inputs","input_boxes","SamImageSegmentationOutput","iou_scores","MarianPreTrainedModel","MarianModel","MarianMTModel","M2M100PreTrainedModel","M2M100Model","M2M100ForConditionalGeneration","Wav2Vec2PreTrainedModel","Wav2Vec2Model","Wav2Vec2ForCTC","CausalLMOutput","Wav2Vec2ForSequenceClassification","Wav2Vec2ForAudioFrameClassification","PyAnnotePreTrainedModel","PyAnnoteModel","PyAnnoteForAudioFrameClassification","WeSpeakerResNetPreTrainedModel","WeSpeakerResNetModel","UniSpeechPreTrainedModel","UniSpeechModel","UniSpeechForCTC","UniSpeechForSequenceClassification","UniSpeechSatPreTrainedModel","UniSpeechSatModel","UniSpeechSatForCTC","UniSpeechSatForSequenceClassification","UniSpeechSatForAudioFrameClassification","Wav2Vec2BertPreTrainedModel","Wav2Vec2BertModel","Wav2Vec2BertForCTC","Wav2Vec2BertForSequenceClassification","HubertPreTrainedModel","HubertModel","HubertForCTC","HubertForSequenceClassification","WavLMPreTrainedModel","WavLMModel","WavLMForCTC","WavLMForSequenceClassification","WavLMForXVector","XVectorOutput","WavLMForAudioFrameClassification","SpeechT5PreTrainedModel","SpeechT5Model","SpeechT5ForSpeechToText","SpeechT5ForTextToSpeech","generate_speech","input_values","speaker_embeddings","threshold","minlenratio","maxlenratio","vocoder","reduction_factor","maxlen","minlen","num_mel_bins","spectrogramParts","decoder_outputs","idx","output_sequence","output_sequence_out","prob","spectrum","spectrogram","waveform","SpeechT5HifiGan","TrOCRPreTrainedModel","TrOCRForCausalLM","MistralPreTrainedModel","MistralModel","MistralForCausalLM","Starcoder2PreTrainedModel","Starcoder2Model","Starcoder2ForCausalLM","FalconPreTrainedModel","FalconModel","FalconForCausalLM","ClapPreTrainedModel","ClapModel","ClapTextModelWithProjection","ClapAudioModelWithProjection","VitsPreTrainedModel","VitsModel","VitsModelOutput","SegformerPreTrainedModel","SegformerModel","SegformerForImageClassification","SegformerForSemanticSegmentation","StableLmPreTrainedModel","StableLmModel","StableLmForCausalLM","EfficientNetPreTrainedModel","EfficientNetModel","EfficientNetForImageClassification","MusicgenPreTrainedModel","MusicgenModel","MusicgenForCausalLM","MusicgenForConditionalGeneration","_apply_and_filter_by_delay_pattern_mask","bs_x_codebooks","seqLength","upperBound","newDataSize","diff","inferred","clonedInputIds","structuredClone","output_ids","audio_codes","unsqueeze_","audio_values","MobileNetV1PreTrainedModel","MobileNetV1Model","MobileNetV1ForImageClassification","MobileNetV2PreTrainedModel","MobileNetV2Model","MobileNetV2ForImageClassification","MobileNetV3PreTrainedModel","MobileNetV3Model","MobileNetV3ForImageClassification","MobileNetV4PreTrainedModel","MobileNetV4Model","MobileNetV4ForImageClassification","DecisionTransformerPreTrainedModel","DecisionTransformerModel","PretrainedMixin","static","MODEL_CLASS_MAPPINGS","MODEL_CLASS_MAPPING","modelInfo","BASE_IF_FAIL","MODEL_MAPPING_NAMES_ENCODER_ONLY","MODEL_MAPPING_NAMES_ENCODER_DECODER","MODEL_MAPPING_NAMES_DECODER_ONLY","MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES","MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES","MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES","MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES","MODEL_FOR_MASKED_LM_MAPPING_NAMES","MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES","MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES","MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES","MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES","MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES","MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES","MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES","MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES","MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES","MODEL_FOR_MASK_GENERATION_MAPPING_NAMES","MODEL_FOR_CTC_MAPPING_NAMES","MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES","MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES","MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES","MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES","MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES","MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES","MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES","MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES","MODEL_CLASS_TYPE_MAPPING","mappings","CUSTOM_MAPPING","AutoModel","AutoModelForSequenceClassification","AutoModelForTokenClassification","AutoModelForSeq2SeqLM","AutoModelForSpeechSeq2Seq","AutoModelForTextToSpectrogram","AutoModelForTextToWaveform","AutoModelForCausalLM","AutoModelForMaskedLM","AutoModelForQuestionAnswering","AutoModelForVision2Seq","AutoModelForImageClassification","AutoModelForImageSegmentation","AutoModelForSemanticSegmentation","AutoModelForUniversalSegmentation","AutoModelForObjectDetection","AutoModelForZeroShotObjectDetection","AutoModelForMaskGeneration","AutoModelForCTC","AutoModelForAudioClassification","AutoModelForXVector","AutoModelForAudioFrameClassification","AutoModelForDocumentQuestionAnswering","AutoModelForImageMatting","AutoModelForImageToImage","AutoModelForDepthEstimation","AutoModelForNormalEstimation","AutoModelForImageFeatureExtraction","Seq2SeqLMOutput","decoder_attentions","embeddings","start_logits","end_logits","CausalLMOutputWithPast","alphas","WHISPER_LANGUAGES","WHISPER_LANGUAGE_MAPPING","WHISPER_TO_LANGUAGE_CODE_MAPPING","language_code","langs","prompt_ids","wrap","session_bytes","TensorOpRegistry","bilinear_interpolate_4d","_bilinear_interpolate_4d","bicubic_interpolate_4d","_bicubic_interpolate_4d","matmul","_matmul","stft","_stft","rfft","_rfft","_top_k","prepareImages","images","RawImage","prepareAudios","audios","sampling_rate","read_audio","get_bounding_box","box","asInteger","xmin","ymin","xmax","ymax","Pipeline","TextClassificationPipeline","texts","padding","truncation","function_to_apply","problem_type","sigmoid","id2label","vals","score","TokenClassificationPipeline","ignore_labels","isBatched","tokenData","topScoreIndex","entity","QuestionAnsweringPipeline","question","text_pair","special_tokens","all_special_ids","sepIndex","sep_token_id","ix","start_scores","end_scores","product","answer_tokens","answer","FillMaskPipeline","mask_token_index","mask_token_id","mask_token","itemLogits","sequence","token_str","vocab","Text2TextGenerationPipeline","_key","generate_kwargs","task_specific_params","tokenizer_options","TranslationPipeline","_build_translation_inputs","outputTokenIds","batch_decode","SummarizationPipeline","isChat","TextGenerationPipeline","isChatInput","apply_chat_template","add_generation_prompt","add_special_tokens","return_full_text","padding_side","text_inputs","decoded","promptLengths","textIndex","generated_text","role","content","ZeroShotClassificationPipeline","label2id","entailment_id","contradiction_id","candidate_labels","hypothesis_template","multi_label","hypotheses","softmaxEach","premise","entails_logits","hypothesis","scores_sorted","labels","FeatureExtractionPipeline","pooling","normalize","quantize","precision","token_embeddings","mean_pooling","quantize_embeddings","ImageFeatureExtractionPipeline","pool","preparedImages","pooler_output","image_embeds","AudioClassificationPipeline","audio","feature_extractor","preparedAudios","aud","ZeroShotAudioClassificationPipeline","single","audio_inputs","probs","logits_per_audio","AutomaticSpeechRecognitionPipeline","_call_whisper","_call_wav2vec2","predicted_ids","predicted_sentences","chunk_length_s","force_full_sequences","stride_length_s","chunk_length","max_source_positions","hop_length","chunks","jump","offset_end","subarr","is_first","is_last","input_features","chunk","token_timestamps","full_text","optional","_decode_asr","ImageToTextPipeline","ImageClassificationPipeline","ImageSegmentationPipeline","subtasks_mapping","panoptic","semantic","mask_threshold","overlap_mask_area_threshold","label_ids_to_fuse","target_sizes","subtask","imageSizes","pixel_mask","func","annotation","processed","segmentation","segment","segments_info","maskData","mask","label_id","ZeroShotImageClassificationPipeline","logits_per_image","ObjectDetectionPipeline","percentage","post_process_object_detection","boxes","classes","ZeroShotObjectDetectionPipeline","imageSize","DocumentQuestionAnsweringPipeline","TextToAudioPipeline","DEFAULT_VOCODER_ID","_call_text_to_spectrogram","_call_text_to_waveform","ImageToImagePipeline","reconstruction","squeeze","clamp_","mul_","round_","fromTensor","DepthEstimationPipeline","predicted_depth","prediction","interpolate","formatted","SUPPORTED_TASKS","AutoTokenizer","AutoProcessor","TASK_ALIASES","pipeline","pipelineInfo","pretrainedOptions","promise","loadItems","dispatchCallback","pipelineClass","center_to_corners_format","centerX","centerY","is_zero_shot","out_logits","out_bbox","num_boxes","num_classes","target_size","bbox","logit","maxIndex","post_process_semantic_segmentation","segmentation_data","row","hasLabel","remove_low_and_no_objects","class_logits","mask_logits","object_mask_threshold","num_labels","mask_probs_item","pred_scores_item","pred_labels_item","pred_label","pred_score","check_segment_validity","mask_labels","mask_probs","mask_k","mask_k_area","original_area","mask_probs_k_data","mask_exists","compute_segments","pred_scores","pred_labels","segments","bestScores","mask_probs_i_data","current_segment_id","pred_class","post_process_panoptic_segmentation","class_queries_logits","masks_queries_logits","num_queries","validate_audio_inputs","constraint_to_multiple_of","val","multiple","minVal","maxVal","bankers_round","enforce_size_divisibility","divisor","FeatureExtractor","ImageFeatureExtractor","image_mean","image_std","resample","do_rescale","rescale_factor","do_normalize","do_resize","do_thumbnail","size_divisibility","size_divisor","do_center_crop","crop_size","do_convert_rgb","do_crop_margin","pad_size","do_pad","do_flip_channel_order","thumbnail","input_height","input_width","output_height","output_width","resize","crop_margin","gray_threshold","gray_image","grayscale","minValue","x_min","y_min","x_max","y_max","gray_image_data","crop","pad_image","pixelData","imgDims","padSize","center","constant_values","imageHeight","imageWidth","imageChannels","paddedImageWidth","paddedImageHeight","paddedPixelData","h1","w1","calculateReflectOffset","rescale","get_resize_output_image_size","srcWidth","srcHeight","shortest_edge","longest_edge","max_size","shortResizeFactor","newWidth","newHeight","longResizeFactor","finalWidth","finalHeight","keep_aspect_ratio","ensure_multiple_of","scale_height","scale_width","do_convert_grayscale","rgb","crop_width","crop_height","center_crop","reshaped_input_size","padded","paddedWidth","paddedHeight","temp","original_size","permute","imageData","original_sizes","reshaped_input_sizes","SapiensFeatureExtractor","SegformerFeatureExtractor","PvtImageProcessor","DPTFeatureExtractor","DPTImageProcessor","BitImageProcessor","GLPNFeatureExtractor","CLIPFeatureExtractor","CLIPImageProcessor","ChineseCLIPFeatureExtractor","SiglipImageProcessor","ConvNextFeatureExtractor","crop_pct","resize_shortest_edge","ConvNextImageProcessor","ViTFeatureExtractor","ViTImageProcessor","EfficientNetImageProcessor","include_top","MobileNetV1FeatureExtractor","MobileNetV2FeatureExtractor","MobileNetV3FeatureExtractor","MobileNetV4FeatureExtractor","MobileViTFeatureExtractor","MobileViTImageProcessor","OwlViTFeatureExtractor","Owlv2ImageProcessor","RTDetrImageProcessor","DeiTFeatureExtractor","BeitFeatureExtractor","DonutFeatureExtractor","NougatImageProcessor","DetrFeatureExtractor","maskSize","full","post_process_instance_segmentation","MaskFormerFeatureExtractor","YolosFeatureExtractor","SamImageProcessor","reshape_input_points","is_bounding_box","calculateDimensions","originalImageSize","reshapedImageSize","resizeFactors","add_input_labels","post_process_masks","masks","binarize","output_masks","target_image_size","interpolated_mask","interpolate_4d","binarizedMaskData","generate_crop_boxes","crop_n_layers","overlap_ratio","points_per_crop","crop_n_points_downscale_factor","Swin2SRImageProcessor","VitMatteImageProcessor","trimaps","trimapData","WhisperFeatureExtractor","mel_filters","mel_filter_bank","n_fft","feature_size","window_function","_extract_fbank_features","power","log_mel","max_num_frames","nb_max_frames","maxValue","n_samples","Wav2Vec2FeatureExtractor","_zero_mean_unit_var_norm","variance","SeamlessM4TFeatureExtractor","periodic","fft_length","preemphasis","mel_floor","remove_dc_offset","pad_to_multiple_of","do_normalize_per_mel_bins","return_attention_mask","padded_attention_mask","num_features","num_channels","padded_data","padding_value","numPaddedFrames","view","reshapedNumFrames","attention_mask_data","padded_attention_mask_data","ASTFeatureExtractor","denom","features_data","ClapFeatureExtractor","nb_frequency_bins","frequency_min","frequency_max","mel_filters_slaney","fft_window_size","_get_input_mel","input_mel","longer","nb_max_samples","PyAnnoteFeatureExtractor","samples_to_frames","samples","post_process_speaker_diarization","num_samples","ratio","accumulated_segments","current_speaker","confidence","WeSpeakerFeatureExtractor","min_num_frames","fbank_centering_span","meanData","featuresData","offset1","offset2","offset3","SpeechT5FeatureExtractor","Processor","SamProcessor","WhisperProcessor","Wav2Vec2ProcessorWithLM","PyAnnoteProcessor","SpeechT5Processor","OwlViTProcessor","Florence2Processor","tasks_answer_post_processing_type","task_prompts_without_inputs","task_prompts_with_input","regexes","quad_boxes","bboxes","size_per_bin","construct_prompts","prompts","prompt","replaceAll","post_process_generation","image_size","task_answer_post_processing_type","final_answer","matches","matchAll","locations","preprocessorConfig","feature_extractor_type","image_processor_type","feature_extractor_class","FEATURE_EXTRACTOR_CLASS_MAPPING","PROCESSOR_CLASS_MAPPING","processor_class","loadTokenizer","legacy","createPattern","pattern","invert","Regex","regex","PROBLEMATIC_REGEX_MAP","escapeRegExp","objectToMap","prepareTensorForDecode","clean_up_tokenization","remove_accents","PUNCTUATION_REGEX","PUNCTUATION_ONLY_REGEX","BLOOM_SPLIT_CHARS","AddedToken","single_word","lstrip","rstrip","special","normalized","TokenizerModel","tokens_to_ids","unk_token_id","unk_token","end_of_word_suffix","fuse_unk","fromConfig","WordPieceTokenizer","Unigram","BPE","LegacyTokenizerModel","encode","arr","fused","convert_tokens_to_ids","convert_ids_to_tokens","max_input_chars_per_word","outputTokens","chars","isUnknown","subTokens","currentSubstring","continuing_subword_prefix","moreConfig","piece","unk_id","bos_token","minScore","unk_score","trie","CharTrie","populateNodes","lattice","beginPos","hasSingleNode","sliced","prefixedTokens","commonPrefixSearch","tokenId","tokenScore","len","insert","TokenLattice","tokenized","BYTES_TO_UNICODE","ccs","UNICODE_TO_BYTES","reverseDictionary","use_new_merge_format","merges","bpe_ranks","continuing_subword_suffix","byte_fallback","text_encoder","TextEncoder","ignore_merges","cache","bpe","cached","PriorityQueue","startingNode","next","previousNode","currentNode","_add_node","deleted","newPreviousNode","merged","bpe_token_list","byteTokens","padStart","target_lang","pad_token","Normalizer","BertNormalizer","Precompiled","NormalizerSequence","Replace","NFC","NFKC","NFKD","StripNormalizer","StripAccents","Lowercase","Prepend","strip_left","strip_right","trimStart","trimEnd","prepend","normalizers","normalizer","_tokenize_chinese_chars","stripAccents","_is_control","_clean_text","clean_text","handle_chinese_chars","lowercase","strip_accents","PreTokenizer","BertPreTokenizer","PreTokenizerSequence","WhitespacePreTokenizer","WhitespaceSplit","MetaspacePreTokenizer","ByteLevelPreTokenizer","SplitPreTokenizer","PunctuationPreTokenizer","DigitsPreTokenizer","ReplacePreTokenizer","pre_tokenize_text","pre_tokenize","add_prefix_space","trim_offsets","use_regex","byte_encoder","byte","fullMatch","regexSplit","digit_pattern","individual_digits","PostProcessor","TemplateProcessing","ByteLevelPostProcessor","RobertaProcessing","BertProcessing","PostProcessorSequence","post_process","sep","tokens_pair","middle","after","pair","processedTokens","SpecialToken","type_id","Sequence","Decoder","added_tokens","WordPieceDecoder","MetaspaceDecoder","ByteLevelDecoder","ReplaceDecoder","ByteFallback","FuseDecoder","StripDecoder","DecoderSequence","CTCDecoder","BPEDecoder","decode_chain","text_decoder","new_tokens","previous_byte_tokens","bytes","string","start_cut","stop_cut","cleanup","byte_decoder","fatal","ignoreBOM","convert_tokens_to_string","byteArray","sub_texts","current_sub_text","word_delimiter_token","grouped_tokens","decoders","toks","VitsDecoder","addPrefixSpace","replacement","strRep","str_rep","prepend_scheme","section_index","charsmap","precompiled_charsmap","parts","part","tokenizers","pretokenizers","preTokenizedText","whitespace_split","SPECIAL_TOKEN_ATTRIBUTES","padHelper","value_fn","side","padData","truncateHelper","PreTrainedTokenizer","return_token_type_ids","tokenizerJSON","tokenizerConfig","_tokenizer_config","pre_tokenizer","post_processor","addedToken","additional_special_tokens","added_tokens_regex","getToken","sep_token","model_max_length","remove_space","clean_up_tokenization_spaces","do_lowercase_and_remove_accent","chat_template","_compiled_template_cache","__type","return_tensor","encodedTokens","_encode_plus","flatMap","_encode_text","lowercase_and_remove_accent","sectionTokens","_tokenize_helper","tokens2","decode_args","token_ids","isIntegralNumber","decode_single","get_chat_template","tools","template_dict","conversation","documents","return_dict","tokenizer_kwargs","compiledTemplate","special_tokens_map","rendered","messages","BertTokenizer","AlbertTokenizer","MobileBertTokenizer","SqueezeBertTokenizer","DebertaTokenizer","DebertaV2Tokenizer","HerbertTokenizer","ConvBertTokenizer","RoFormerTokenizer","DistilBertTokenizer","CamembertTokenizer","XLMTokenizer","ElectraTokenizer","T5Tokenizer","GPT2Tokenizer","BartTokenizer","MBartTokenizer","languageRegex","language_codes","lang_to_token","raw_inputs","MBart50Tokenizer","RobertaTokenizer","BloomTokenizer","SPIECE_UNDERLINE","LlamaTokenizer","CodeLlamaTokenizer","XLMRobertaTokenizer","MPNetTokenizer","FalconTokenizer","GPTNeoXTokenizer","EsmTokenizer","Qwen2Tokenizer","GemmaTokenizer","Grok1Tokenizer","src_lang_token","src_lang","tgt_lang_token","tgt_lang","NllbTokenizer","M2M100Tokenizer","WhisperTokenizer","return_language","last_language","returnWordTimestamps","new_chunk","time_offset","previous_tokens","previous_token_timestamps","skip","right_stride_start","last_timestamp","first_timestamp","chunk_len","stride_left","stride_right","current_tokens","current_token_timestamps","resolved_tokens","findLongestCommonSequence","resolved_text","rounded_time","timestamp","resolved_token_timestamps","words","collateWordTimestamps","end_time","start_time","decoded_text","new_chunks","token_timestamp_sequences","leftSequence","leftLength","totalSequence","use_token_timestamp_sequences","total_token_timestamp_sequence","left_token_timestamp_sequence","rightSequence","maxIndices","rightLength","leftStart","leftStop","rightStart","rightStop","elem","matching","leftMid","rightMid","token_indices","combineTokensIntoWords","timings","prepend_punctionations","append_punctuations","word_tokens","splitTokensOnUnicode","splitTokensOnSpaces","mergePunctuations","decode_with_timestamps","decodeWithTimestamps","decoded_full","current_indices","unicode_offset","token_idx","subwords","subword_tokens_list","subword_indices_list","punctuationRegex","subword","subword_tokens","subword_indices","with_space","trimmed","punctuation","prepended","appended","newWords","newTokens","newIndices","CodeGenTokenizer","CLIPTokenizer","SiglipTokenizer","MarianTokenizer","supported_language_codes","matchInfo","remainder","Wav2Vec2CTCTokenizer","BlenderbotTokenizer","BlenderbotSmallTokenizer","SpeechT5Tokenizer","NougatTokenizer","VitsTokenizer","CohereTokenizer","tokenizerName","tokenizer_class","TOKENIZER_CLASS_MAPPING","AudioContext","getFile","audioCTX","sampleRate","decodeAudioData","numberOfChannels","SCALING_FACTOR","getChannelData","generalized_cosine_window","a_0","a_1","factor","PI","cos_vals","cos","hanning","hamming","HERTZ_TO_MEL_MAPPING","freq","log10","min_log_hertz","min_log_mel","logstep","hertz_to_mel","mel_scale","MEL_TO_HERTZ_MAPPING","mels","linspace","num_frequency_bins","num_mel_filters","min_frequency","max_frequency","triangularize_in_mel_space","mel_freqs","fft_freqs","filter_freqs","mel_to_hertz","fft_bin_width","filter_diff","slopes","slope","numFreqs","ret","down","_create_triangular_filter_bank","enorm","_db_conversion_helper","reference","min_value","db_range","logReference","frame_length","pad_mode","onesided","window_length","half_window","padReflect","d1","d1Max","fft","FFT","inputBuffer","outputBuffer","outputBufferSize","transposedMagnitudeData","buffer_size","realTransform","j2","pow","mel_spec","mel_spec_data","amplitude_to_db","power_to_db","isTypedArray","__proto__","arrs","props","comparator","maxSize","_heap","_comparator","_maxSize","peek","_siftUp","smallest","_smallest","_siftUpFrom","poppedValue","_swap","_siftDown","replacedValue","_parent","_left","_right","_greater","maxChild","log2","root","CharTrieNode","child","children","isLeaf","sentence","bosTokenId","eosTokenId","nodes","beginNodes","endNodes","bos","TokenLatticeNode","eos","pos","nodeId","viterbi","rnode","bestScore","bestNode","lnode","backtraceScore","tokenIds","DEVICE_TYPES","cachedResult","q8","int8","uint8","q4","bnb4","q4f16","closure","setPrototypeOf","CONTENT_TYPE_MAP","FileResponse","filePath","Headers","exists","statusText","stats","updateContentType","ReadableStream","controller","enqueue","close","readFile","json","isValidUrl","protocols","validHosts","protocol","hostname","urlOrPath","IS_CI","TESTING_REMOTELY","HF_TOKEN","HF_ACCESS_TOKEN","ERROR_MAPPING","FileCache","request","file","Buffer","outputPath","mkdir","recursive","writeFile","path_or_repo_id","caches","requestURL","pathJoin","localPath","remoteURL","encodeURIComponent","fsCacheKey","proposedCacheKey","toCacheResponse","tryCache","cacheHit","handleError","Response","progressInfo","userAgent","progress","total","contentLength","reader","newLoaded","newBuffer","readResponse","modelPath","jsonData","BROWSER_ENV","WEBWORKER_ENV","createCanvasFunction","ImageDataClass","loadImageFunction","createImageBitmap","rawChannels","metadata","rotate","raw","toBuffer","resolveWithObject","convert","RESAMPLING_MAPPING","fromURL","fromCanvas","fromBlob","ctx","channel_format","newData","red","green","blue","_update","rgba","resampleMethod","numChannels","toCanvas","toSharp","affine","interpolator","fit","kernel","pad","extract","width_offset","height_offset","sourceX","sourceY","destX","destY","y_padding","y_extract","x_padding","x_extract","toBlob","quality","convertToBlob","toTensor","cloned","clonedCanvas","save","toFile","mime","dataURL","downloadLink","click","remove","interpolate_data","in_channels","in_height","in_width","out_height","out_width","x_scale","y_scale","out_img","inStride","outStride","outOffset","x1","x2","y2","w2","w3","w4","yStride","xStride","idx1","idx2","idx3","idx4","cOffset","permute_data","invStride","permutedData","newIndex","exps","sumExps","acc","dot","arr1","arr2","cos_sim","magnitude","indexOfMin","indexOfMax","isPowerOfTwo","number","P2FFT","_csize","table","angle","sin","_width","_bitrev","revShift","createComplexArray","fromComplexArray","complex","res","toComplexArray","transform","_transform4","_realTransform4","inverseTransform","inv","outOff","bitrev","off","_singleTransform2","_singleTransform4","quarterLen","limit","tableBr","tableBi","MBr","MBi","tableCr","tableCi","MCr","MCi","tableDr","tableDi","MDr","MDi","T0r","T0i","T1r","T1i","T2r","T2i","T3r","T3i","evenR","evenI","oddR","oddI","step2","step3","_singleRealTransform2","_singleRealTransform4","halfLen","hquarterLen","MAr","MAi","SA","SB","half","NP2FFT","nextP2","bufferSize","chirp","ichirp","_chirpBuffer","_buffer1","_buffer2","_outBuffer1","_outBuffer2","theta","baseR","baseI","result_mod","result_arg","atan2","i2","_slicedChirpBuffer","_transform","real","ib1","ib2","ob2","ob3","a_real","a_imag","b_real","b_imag","windowSize","outputArray","halfWindowSize","valuesIndex","decimals","output_length","input_length","cost","c0","c1","c2","DataTypeMap","float32","float16","float64","int16","uint16","int32","uint32","int64","uint64","bool","_getitem","iterLength","iterDims","iterSize","_subarray","safeIndex","this_data","o1","o2","totalElements","dimensionSize","reshapedArray","lastArray","sigmoid_","callback","map_","mul","div","div_","add_","sub","sub_","newTensorDims","newOffsets","sliceIndex","offsets","newDims","newBufferSize","originalIndex","keepdim","resultDims","resultIndex","resultMultiplier","normalize_","norm_data","s2","dimsToStride","calc_squeeze_dims","unsqueeze","calc_unsqueeze_dims","flatten_","start_dim","end_dim","dimsToKeepBefore","dimsToFlatten","dimsToKeepAfter","flatten","inferredIndex","productOther","curr","neg_","clamp","targetDims","sizeTensor","lastHiddenStateData","attentionMaskData","returnedData","embedDim","outIndex","attnMaskOffset","attn","avg","layer_norm","normalized_shape","featureDim","stdData","inputData","dimension","boundsCheck","tensors","resultSize","resultType","tensorData","currentDim","correction","inputDims","meanTensor","fullHelper","fill_value","typedArrayCls","zeros","signed","outputData","bit","arrayIndex","bitPosition","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","getPrototypeOf","__esModule","def","definition","toStringTag","scriptUrl"],"sourceRoot":""} \ No newline at end of file diff --git a/assets/dist_transformers/1.21.0-dev.20241109/ort-wasm-simd-threaded.jsep.wasm b/assets/dist_transformers/1.21.0-dev.20241122/ort-wasm-simd-threaded.jsep.wasm similarity index 77% rename from assets/dist_transformers/1.21.0-dev.20241109/ort-wasm-simd-threaded.jsep.wasm rename to assets/dist_transformers/1.21.0-dev.20241122/ort-wasm-simd-threaded.jsep.wasm index a6437ca..83b13d1 100644 Binary files a/assets/dist_transformers/1.21.0-dev.20241109/ort-wasm-simd-threaded.jsep.wasm and b/assets/dist_transformers/1.21.0-dev.20241122/ort-wasm-simd-threaded.jsep.wasm differ diff --git a/assets/dist_transformers/1.21.0-dev.20241109/transformers.cjs b/assets/dist_transformers/1.21.0-dev.20241122/transformers.cjs similarity index 100% rename from assets/dist_transformers/1.21.0-dev.20241109/transformers.cjs rename to assets/dist_transformers/1.21.0-dev.20241122/transformers.cjs diff --git a/assets/dist_transformers/1.21.0-dev.20241109/transformers.cjs.map b/assets/dist_transformers/1.21.0-dev.20241122/transformers.cjs.map similarity index 100% rename from assets/dist_transformers/1.21.0-dev.20241109/transformers.cjs.map rename to assets/dist_transformers/1.21.0-dev.20241122/transformers.cjs.map diff --git a/assets/dist_transformers/1.21.0-dev.20241109/transformers.js b/assets/dist_transformers/1.21.0-dev.20241122/transformers.js similarity index 88% rename from assets/dist_transformers/1.21.0-dev.20241109/transformers.js rename to assets/dist_transformers/1.21.0-dev.20241122/transformers.js index 94c3b95..09bdc82 100644 --- a/assets/dist_transformers/1.21.0-dev.20241109/transformers.js +++ b/assets/dist_transformers/1.21.0-dev.20241122/transformers.js @@ -3784,61 +3784,61 @@ const version = '1.19.2'; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ InferenceSession: () => (/* binding */ Mp), -/* harmony export */ TRACE: () => (/* binding */ Cr), +/* harmony export */ InferenceSession: () => (/* binding */ Np), +/* harmony export */ TRACE: () => (/* binding */ xr), /* harmony export */ TRACE_FUNC_BEGIN: () => (/* binding */ Ue), -/* harmony export */ TRACE_FUNC_END: () => (/* binding */ Be), -/* harmony export */ Tensor: () => (/* binding */ De), -/* harmony export */ TrainingSession: () => (/* binding */ Up), -/* harmony export */ "default": () => (/* binding */ y1), -/* harmony export */ env: () => (/* binding */ ve), +/* harmony export */ TRACE_FUNC_END: () => (/* binding */ De), +/* harmony export */ Tensor: () => (/* binding */ Oe), +/* harmony export */ TrainingSession: () => (/* binding */ Wp), +/* harmony export */ "default": () => (/* binding */ bS), +/* harmony export */ env: () => (/* binding */ we), /* harmony export */ registerBackend: () => (/* binding */ xt) /* harmony export */ }); /*! - * ONNX Runtime Web v1.21.0-dev.20241109-d3ad76b2cf + * ONNX Runtime Web v1.21.0-dev.20241122-a2ba3cb547 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ -var Fn=Object.defineProperty;var Pp=Object.getOwnPropertyDescriptor;var zp=Object.getOwnPropertyNames;var Op=Object.prototype.hasOwnProperty;var qn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var R=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ft=(e,t)=>{for(var r in t)Fn(e,r,{get:t[r],enumerable:!0})},Dp=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of zp(t))!Op.call(e,o)&&o!==r&&Fn(e,o,{get:()=>t[o],enumerable:!(n=Pp(t,o))||n.enumerable});return e};var vr=e=>Dp(Fn({},"__esModule",{value:!0}),e);var $r,$t,xt,Bp,xr,Sr=R(()=>{"use strict";$r=new Map,$t=[],xt=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=$r.get(e);if(n===void 0)$r.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let o=$t.indexOf(e);o!==-1&&$t.splice(o,1);for(let i=0;i<$t.length;i++)if($r.get($t[i]).priority<=r){$t.splice(i,0,e);return}$t.push(e)}return}throw new TypeError("not a valid backend")},Bp=async e=>{let t=$r.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},xr=async e=>{let t=e.executionProviders||[],r=t.map(d=>typeof d=="string"?d:d.name),n=r.length===0?$t:r,o,i=[],a=new Set;for(let d of n){let c=await Bp(d);typeof c=="string"?i.push({name:d,err:c}):(o||(o=c),o===c&&a.add(d))}if(!o)throw new Error(`no available backend found. ERR: ${i.map(d=>`[${d.name}] ${d.err}`).join(", ")}`);for(let{name:d,err:c}of i)r.includes(d)&&console.warn(`removing requested execution provider "${d}" from session options because it is not available: ${c}`);let l=t.filter(d=>a.has(typeof d=="string"?d:d.name));return[o,new Proxy(e,{get:(d,c)=>c==="executionProviders"?l:Reflect.get(d,c)})]}});var oa=R(()=>{"use strict";Sr()});var ia,aa=R(()=>{"use strict";ia="1.21.0-dev.20241026-05fbb43b34"});var sa,Re,jn=R(()=>{"use strict";aa();sa="warning",Re={wasm:{},webgl:{},webgpu:{},versions:{common:ia},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);sa=e}},get logLevel(){return sa}};Object.defineProperty(Re,"logLevel",{enumerable:!0})});var ve,ua=R(()=>{"use strict";jn();ve=Re});var la,da,ca=R(()=>{"use strict";la=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let o,i;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],i=e.dims[3]):(o=e.dims[3],i=e.dims[2]);let a=t?.format!==void 0?t.format:"RGB",l=t?.norm,d,c;l===void 0||l.mean===void 0?d=[255,255,255,255]:typeof l.mean=="number"?d=[l.mean,l.mean,l.mean,l.mean]:(d=[l.mean[0],l.mean[1],l.mean[2],0],l.mean[3]!==void 0&&(d[3]=l.mean[3])),l===void 0||l.bias===void 0?c=[0,0,0,0]:typeof l.bias=="number"?c=[l.bias,l.bias,l.bias,l.bias]:(c=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(c[3]=l.bias[3]));let m=i*o,u=0,h=m,w=m*2,y=-1;a==="RGBA"?(u=0,h=m,w=m*2,y=m*3):a==="RGB"?(u=0,h=m,w=m*2):a==="RBG"&&(u=0,w=m,h=m*2);for(let g=0;g{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let o,i,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],i=e.dims[1],a=e.dims[3]):(o=e.dims[3],i=e.dims[2],a=e.dims[1]);let l=t!==void 0&&t.format!==void 0?t.format:"RGB",d=t?.norm,c,m;d===void 0||d.mean===void 0?c=[255,255,255,255]:typeof d.mean=="number"?c=[d.mean,d.mean,d.mean,d.mean]:(c=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(c[3]=d.mean[3])),d===void 0||d.bias===void 0?m=[0,0,0,0]:typeof d.bias=="number"?m=[d.bias,d.bias,d.bias,d.bias]:(m=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(m[3]=d.bias[3]));let u=i*o;if(t!==void 0&&(t.format!==void 0&&a===4&&t.format!=="RGBA"||a===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let h=4,w=0,y=1,g=2,x=3,$=0,v=u,S=u*2,T=-1;l==="RGBA"?($=0,v=u,S=u*2,T=u*3):l==="RGB"?($=0,v=u,S=u*2):l==="RBG"&&($=0,S=u,v=u*2),n=r.createImageData(o,i);for(let C=0;C{"use strict";Tr();Kn=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,o=t.norm??{mean:255,bias:0},i,a;typeof o.mean=="number"?i=[o.mean,o.mean,o.mean,o.mean]:i=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?a=[o.bias,o.bias,o.bias,o.bias]:a=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let l=t.format!==void 0?t.format:"RGBA",d=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",c=r*n,m=d==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),u=4,h=0,w=1,y=2,g=3,x=0,$=c,v=c*2,S=-1;l==="RGB"&&(u=3,h=0,w=1,y=2,g=-1),d==="RGBA"?S=c*3:d==="RBG"?(x=0,v=c,$=c*2):d==="BGR"&&(v=0,$=c,x=c*2);for(let C=0;C{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,i=typeof e=="string",a,l=t??{},d=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=m=>typeof HTMLCanvasElement<"u"&&m instanceof HTMLCanvasElement||m instanceof OffscreenCanvas?m.getContext("2d"):null;if(r){let m=d();m.width=e.width,m.height=e.height;let u=c(m);if(u!=null){let h=e.height,w=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(h=t.resizedHeight,w=t.resizedWidth),t!==void 0){if(l=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");l.tensorFormat="RGBA",l.height=h,l.width=w}else l.tensorFormat="RGBA",l.height=h,l.width=w;u.drawImage(e,0,0),a=u.getImageData(0,0,w,h).data}else throw new Error("Can not access image data")}else if(n){let m,u;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(m=t.resizedHeight,u=t.resizedWidth):(m=e.height,u=e.width),t!==void 0&&(l=t),l.format="RGBA",l.height=m,l.width=u,t!==void 0){let h=d();h.width=u,h.height=m;let w=c(h);if(w!=null)w.putImageData(e,0,0),a=w.getImageData(0,0,u,m).data;else throw new Error("Can not access image data")}else a=e.data}else if(o){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let m=d();m.width=e.width,m.height=e.height;let u=c(m);if(u!=null){let h=e.height,w=e.width;return u.drawImage(e,0,0,w,h),a=u.getImageData(0,0,w,h).data,l.height=h,l.width=w,Kn(a,l)}else throw new Error("Can not access image data")}else{if(i)return new Promise((m,u)=>{let h=d(),w=c(h);if(!e||!w)return u();let y=new Image;y.crossOrigin="Anonymous",y.src=e,y.onload=()=>{h.width=y.width,h.height=y.height,w.drawImage(y,0,0,h.width,h.height);let g=w.getImageData(0,0,h.width,h.height);l.height=h.height,l.width=h.width,m(Kn(g.data,l))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Kn(a,l);throw new Error("Input data provided is not supported - aborted tensor creation")},ma=(e,t)=>{let{width:r,height:n,download:o,dispose:i}=t,a=[1,n,r,4];return new Oe({location:"texture",type:"float32",texture:e,dims:a,download:o,dispose:i})},fa=(e,t)=>{let{dataType:r,dims:n,download:o,dispose:i}=t;return new Oe({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:o,dispose:i})},ha=(e,t)=>{let{dataType:r,dims:n,download:o,dispose:i}=t;return new Oe({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:o,dispose:i})},ga=(e,t,r)=>new Oe({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})});var St,qt,ya,wa,_a=R(()=>{"use strict";St=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),qt=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ya=!1,wa=()=>{if(!ya){ya=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&(St.set("int64",BigInt64Array),qt.set(BigInt64Array,"int64")),t&&(St.set("uint64",BigUint64Array),qt.set(BigUint64Array,"uint64")),r?(St.set("float16",Float16Array),qt.set(Float16Array,"float16")):St.set("float16",Uint16Array)}}});var va,$a,xa=R(()=>{"use strict";Tr();va=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new Oe(e.type,e.data,t);case"cpu-pinned":return new Oe({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Oe({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Oe({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Oe({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}});var Oe,Tr=R(()=>{"use strict";ca();ba();_a();xa();Oe=class{constructor(t,r,n){wa();let o,i;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,o=t.type,i=t.dims,t.location){case"cpu-pinned":{let l=St.get(o);if(!l)throw new TypeError(`unsupported type "${o}" to create tensor from pinned buffer`);if(!(t.data instanceof l))throw new TypeError(`buffer should be of type ${l.name}`);this.cpuData=t.data;break}case"texture":{if(o!=="float32")throw new TypeError(`unsupported type "${o}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint64"&&o!=="int8"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let l,d;if(typeof t=="string")if(o=t,d=n,t==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");l=r}else{let c=St.get(t);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t==="float16"&&c===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${c.name} as data.`);t==="uint64"||t==="int64"?l=c.from(r,BigInt):l=c.from(r)}else if(r instanceof c)l=r;else if(r instanceof Uint8ClampedArray)if(t==="uint8")l=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${o} tensor's data must be type of ${c}`)}else if(d=r,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof t[0];if(c==="string")o="string",l=t;else if(c==="boolean")o="bool",l=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(t instanceof Uint8ClampedArray)o="uint8",l=Uint8Array.from(t);else{let c=qt.get(t.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);o=c,l=t}if(d===void 0)d=[l.length];else if(!Array.isArray(d))throw new TypeError("A tensor's dims must be a number array");i=d,this.cpuData=l,this.dataLocation="cpu"}let a=va(i);if(this.cpuData&&a!==this.cpuData.length&&!((o==="uint4"||o==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=i,this.size=a}static async fromImage(t,r){return pa(t,r)}static fromTexture(t,r){return ma(t,r)}static fromGpuBuffer(t,r){return fa(t,r)}static fromMLTensor(t,r){return ha(t,r)}static fromPinnedBuffer(t,r,n){return ga(t,r,n)}toDataURL(t){return la(this,t)}toImageData(t){return da(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,t&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return $a(this,t)}}});var De,Ir=R(()=>{"use strict";Tr();De=Oe});var Cr,Sa,Ue,Be,Yn=R(()=>{"use strict";jn();Cr=(e,t)=>{(typeof Re.trace>"u"?!Re.wasm.trace:!Re.trace)||console.timeStamp(`${e}::ORT::${t}`)},Sa=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],n=!1;for(let o=0;o{(typeof Re.trace>"u"?!Re.wasm.trace:!Re.trace)||Sa("BEGIN",e)},Be=e=>{(typeof Re.trace>"u"?!Re.wasm.trace:!Re.trace)||Sa("END",e)}});var Ar,Ta=R(()=>{"use strict";Sr();Ir();Yn();Ar=class e{constructor(t){this.handler=t}async run(t,r,n){Ue();let o={},i={};if(typeof t!="object"||t===null||t instanceof De||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof De)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);o[c]=null}if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,m=Object.getOwnPropertyNames(r);for(let u of this.outputNames)if(m.indexOf(u)!==-1){let h=r[u];(h===null||h instanceof De)&&(c=!0,a=!1,o[u]=h)}if(c){if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else i=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof t[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)o[c]=null;let l=await this.handler.run(t,o,i),d={};for(let c in l)if(Object.hasOwnProperty.call(l,c)){let m=l[c];m instanceof De?d[c]=m:d[c]=new De(m.type,m.data,m.dims)}return Be(),d}async release(){return this.handler.dispose()}static async create(t,r,n,o){Ue();let i,a={};if(typeof t=="string"){if(i=t,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(i=t,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let m=t,u=0,h=t.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(u=r,!Number.isSafeInteger(u))throw new RangeError("'byteOffset' must be an integer.");if(u<0||u>=m.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${m.byteLength}).`);if(h=t.byteLength-u,typeof n=="number"){if(h=n,!Number.isSafeInteger(h))throw new RangeError("'byteLength' must be an integer.");if(h<=0||u+h>m.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${m.byteLength-u}].`);if(typeof o=="object"&&o!==null)a=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");i=new Uint8Array(m,u,h)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[l,d]=await xr(a),c=await l.createInferenceSessionHandler(i,d);return Be(),new e(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}});var Mp,Ia=R(()=>{"use strict";Ta();Mp=Ar});var Ca=R(()=>{"use strict"});var Aa=R(()=>{"use strict"});var ka=R(()=>{"use strict"});var Ea=R(()=>{"use strict"});var Rp,kr,Pa=R(()=>{"use strict";Sr();Ir();Rp="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",kr=class e{constructor(t,r,n){this.handler=t,this.hasOptimizerModel=r,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(t,r){let n=t.evalModel||"",o=t.optimizerModel||"",i=r||{},[a,l]=await xr(i);if(a.createTrainingSessionHandler){let d=await a.createTrainingSessionHandler(t.checkpointState,t.trainModel,n,o,l);return new e(d,!!t.optimizerModel,!!t.evalModel)}else throw new Error(Rp)}typeNarrowingForRunStep(t,r,n,o,i){let a={},l={};if(typeof n!="object"||n===null||n instanceof De||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let d=!0;if(typeof o=="object"){if(o===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(o instanceof De)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(o)){if(o.length===0)throw new TypeError("'fetches' cannot be an empty array.");d=!1;for(let c of o){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);a[c]=null}if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,m=Object.getOwnPropertyNames(o);for(let u of r)if(m.indexOf(u)!==-1){let h=o[u];(h===null||h instanceof De)&&(c=!0,d=!1,a[u]=h)}if(c){if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else l=o}}else if(typeof o<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of t)if(typeof n[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(d)for(let c of r)a[c]=null;return[a,l]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let n in t)if(Object.hasOwnProperty.call(t,n)){let o=t[n];o instanceof De?r[n]=o:r[n]=new De(o.type,o.data,o.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,n){let[o,i]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,n),a=await this.handler.runTrainStep(t,o,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}async runOptimizerStep(t){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(t||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(t,r,n){if(this.hasEvalModel){let[o,i]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,n),a=await this.handler.runEvalStep(t,o,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(t=!0){return this.handler.getParametersSize(t)}async loadParametersBuffer(t,r=!0){let n=await this.getParametersSize(r);if(t.length!==4*n)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(t,r)}async getContiguousParameters(t=!0){return this.handler.getContiguousParameters(t)}async release(){return this.handler.dispose()}}});var Up,za=R(()=>{"use strict";Pa();Up=kr});var Zn={};Ft(Zn,{InferenceSession:()=>Mp,TRACE:()=>Cr,TRACE_FUNC_BEGIN:()=>Ue,TRACE_FUNC_END:()=>Be,Tensor:()=>De,TrainingSession:()=>Up,env:()=>ve,registerBackend:()=>xt});var He=R(()=>{"use strict";oa();ua();Ia();Ir();Ca();Aa();Yn();ka();Ea();za()});var Er=R(()=>{"use strict"});var Ma={};Ft(Ma,{default:()=>Vp});var Da,Ba,Vp,Ra=R(()=>{"use strict";Xn();gt();jt();Da="ort-wasm-proxy-worker",Ba=globalThis.self?.name===Da;Ba&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":Pr(r.wasm).then(()=>{zr(r).then(()=>{postMessage({type:t})},n=>{postMessage({type:t,err:n})})},n=>{postMessage({type:t,err:n})});break;case"init-ep":{let{epName:n,env:o}=r;Or(o,n).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case"copy-from":{let{buffer:n}=r,o=Kt(n);postMessage({type:t,out:o});break}case"create":{let{model:n,options:o}=r;Dr(n,o).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case"release":Br(r),postMessage({type:t});break;case"run":{let{sessionId:n,inputIndices:o,inputs:i,outputIndices:a,options:l}=r;Mr(n,o,i,a,new Array(a.length).fill(null),l).then(d=>{d.some(c=>c[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:d},Ur([...i,...d]))},d=>{postMessage({type:t,err:d})});break}case"end-profiling":Rr(r),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}});Vp=Ba?null:e=>new Worker(e??Bt,{type:"module",name:Da})});var Va={};Ft(Va,{default:()=>Np});var Qn,Ua,Np,Na=R(()=>{"use strict";Ua=(Qn=import.meta.url,async function(e={}){function t(){return ue.buffer!=Q.buffer&&be(),Q}function r(){return ue.buffer!=Q.buffer&&be(),ne}function n(){return ue.buffer!=Q.buffer&&be(),we}function o(){return ue.buffer!=Q.buffer&&be(),Ae}function i(){return ue.buffer!=Q.buffer&&be(),$e}function a(){return ue.buffer!=Q.buffer&&be(),de}function l(){return ue.buffer!=Q.buffer&&be(),N}function d(){return ue.buffer!=Q.buffer&&be(),qe}var c,m,u=Object.assign({},e),h=new Promise((s,p)=>{c=s,m=p}),w=typeof window=="object",y=typeof importScripts=="function",g=y&&self.name=="em-pthread";u.mountExternalData=(s,p)=>{s.startsWith("./")&&(s=s.substring(2)),(u.Eb||(u.Eb=new Map)).set(s,p)},u.unmountExternalData=()=>{delete u.Eb};var x=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let $=()=>{let s=(f,b,_)=>(...I)=>{let D=Qe,B=b?.();I=f(...I);let G=b?.();return B!==G&&(f=G,_(B),b=_=null),Qe!=D?new Promise((H,X)=>{Rn={resolve:H,reject:X}}):I},p=f=>async(...b)=>{try{if(u.Fb)throw Error("Session already started");let _=u.Fb={fc:b[0],errors:[]},I=await f(...b);if(u.Fb!==_)throw Error("Session mismatch");u.Gb?.flush();let D=_.errors;if(0G),0u._OrtCreateSession,f=>u._OrtCreateSession=f),u._OrtRun=p(s(u._OrtRun,()=>u._OrtRun,f=>u._OrtRun=f)),u._OrtRunWithBinding=p(s(u._OrtRunWithBinding,()=>u._OrtRunWithBinding,f=>u._OrtRunWithBinding=f)),u._OrtBindInput=s(u._OrtBindInput,()=>u._OrtBindInput,f=>u._OrtBindInput=f),$=void 0};u.jsepInit=(s,p)=>{if($?.(),s==="webgpu"){[u.Gb,u.Ub,u.Yb,u.Nb,u.Xb,u.jb,u.Zb,u.bc,u.Vb,u.Wb,u.$b]=p;let f=u.Gb;u.jsepRegisterBuffer=(b,_,I,D)=>f.registerBuffer(b,_,I,D),u.jsepGetBuffer=b=>f.getBuffer(b),u.jsepCreateDownloader=(b,_,I)=>f.createDownloader(b,_,I),u.jsepOnCreateSession=b=>{f.onCreateSession(b)},u.jsepOnReleaseSession=b=>{f.onReleaseSession(b)},u.jsepOnRunStart=b=>f.onRunStart(b),u.cc=(b,_)=>{f.upload(b,_)}}else if(s==="webnn"){[u.Gb,u.ac,u.Ob,u.jsepEnsureTensor,u.dc,u.jsepDownloadTensor]=p,u.jsepReleaseTensorId=u.Ob;let f=u.Gb;u.jsepOnRunStart=b=>f.onRunStart(b),u.jsepRegisterMLContext=(b,_)=>{f.registerMLContext(b,_)},u.jsepOnReleaseSession=b=>{f.onReleaseSession(b)},u.jsepCreateMLTensorDownloader=(b,_)=>f.createMLTensorDownloader(b,_),u.jsepRegisterMLTensor=(b,_,I)=>f.registerMLTensor(b,_,I),u.jsepCreateMLContext=b=>f.createMLContext(b),u.qc=(b,_,I,D,B)=>f.registerMLConstant(b,_,I,D,B,u.Eb)}};var v,S,T=Object.assign({},u),C="./this.program",A=(s,p)=>{throw p},P="";(w||y)&&(y?P=self.location.href:typeof document<"u"&&document.currentScript&&(P=document.currentScript.src),Qn&&(P=Qn),P=P.startsWith("blob:")?"":P.substr(0,P.replace(/[?#].*/,"").lastIndexOf("/")+1),y&&(S=s=>{var p=new XMLHttpRequest;return p.open("GET",s,!1),p.responseType="arraybuffer",p.send(null),new Uint8Array(p.response)}),v=(s,p,f)=>{var b=new XMLHttpRequest;b.open("GET",s,!0),b.responseType="arraybuffer",b.onload=()=>{b.status==200||b.status==0&&b.response?p(b.response):f()},b.onerror=f,b.send(null)});var O,U=console.log.bind(console),L=console.error.bind(console),j=U,K=L;if(Object.assign(u,T),T=null,g){let s=function(p){try{var f=p.data,b=f.cmd;if(b==="load"){let _=[];self.onmessage=I=>_.push(I),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let I of _)s(I);self.onmessage=s};for(let I of f.handlers)u[I]&&!u[I].proxy||(u[I]=(...D)=>{postMessage({Mb:"callHandler",oc:I,args:D})},I=="print"&&(j=u[I]),I=="printErr"&&(K=u[I]));ue=f.wasmMemory,be(),W(f.wasmModule)}else if(b==="run"){Wn(f.pthread_ptr,0,0,1,0,0),Dn(f.pthread_ptr),hc(),Yo(),ee||(qi(),ee=!0);try{gc(f.start_routine,f.arg)}catch(_){if(_!="unwind")throw _}}else b==="cancel"?Dt()&&wr(-1):f.target!=="setimmediate"&&(b==="checkMailbox"?ee&&dr():b&&(K(`worker: received unknown command ${b}`),K(f)))}catch(_){throw ji(),_}};var mg=s,W,ee=!1;K=function(...p){p=p.join(" "),console.error(p)},self.alert=function(...p){postMessage({Mb:"alert",text:p.join(" "),rc:Dt()})},u.instantiateWasm=(p,f)=>new Promise(b=>{W=_=>{_=new WebAssembly.Instance(_,Ho()),f(_),b()}}),self.onunhandledrejection=p=>{throw p.reason||p},self.onmessage=s}u.wasmBinary&&(O=u.wasmBinary);var ue,Z,J,Q,ne,we,Ae,$e,de,N,q,he,qe,_e=!1;function be(){var s=ue.buffer;u.HEAP8=Q=new Int8Array(s),u.HEAP16=we=new Int16Array(s),u.HEAPU8=ne=new Uint8Array(s),u.HEAPU16=Ae=new Uint16Array(s),u.HEAP32=$e=new Int32Array(s),u.HEAPU32=de=new Uint32Array(s),u.HEAPF32=N=new Float32Array(s),u.HEAPF64=qe=new Float64Array(s),u.HEAP64=q=new BigInt64Array(s),u.HEAPU64=he=new BigUint64Array(s)}if(!g){if(!((ue=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof x))throw K("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),Error("bad memory");be()}var Ye=[],Lt=[],_n=[],Gt=0,vn=null,Ht=null;function Vo(){if(--Gt==0&&(vn!==null&&(clearInterval(vn),vn=null),Ht)){var s=Ht;Ht=null,s()}}function ct(s){throw K(s="Aborted("+s+")"),_e=!0,J=1,s=new WebAssembly.RuntimeError(s+". Build with -sASSERTIONS for more info."),m(s),s}var $n,No=s=>s.startsWith("data:application/octet-stream;base64,"),Wo=s=>s.startsWith("file://");function Lo(s){if(s==$n&&O)return new Uint8Array(O);if(S)return S(s);throw"both async and sync fetching of the wasm failed"}function Go(s,p,f){return function(b){if(!O&&(w||y)){if(typeof fetch=="function"&&!Wo(b))return fetch(b,{credentials:"same-origin"}).then(_=>{if(!_.ok)throw`failed to load wasm binary file at '${b}'`;return _.arrayBuffer()}).catch(()=>Lo(b));if(v)return new Promise((_,I)=>{v(b,D=>_(new Uint8Array(D)),I)})}return Promise.resolve().then(()=>Lo(b))}(s).then(b=>WebAssembly.instantiate(b,p)).then(f,b=>{K(`failed to asynchronously prepare wasm: ${b}`),ct(b)})}function Ho(){return{a:{O:fc,Aa:mc,b:yc,aa:Jo,B:ri,qa:ni,Y:ii,_:ai,ra:si,oa:ui,ha:li,na:di,L:ci,Z:pi,W:mi,pa:fi,X:hi,wa:wc,F:vc,Q:$c,P:Sc,E:Ic,u:Cc,q:Ac,G:kc,A:Mc,R:Rc,ua:Uc,ka:Vc,U:Nc,ba:Wc,H:Lc,ja:Dn,ta:Gc,t:Hc,x:jc,o:Kc,l:Zc,c:zn,n:Xc,j:ep,w:tp,p:rp,g:np,s:op,m:ip,e:ap,k:sp,i:up,h:lp,d:dp,ea:cp,fa:pp,ga:mp,ca:ki,da:Ei,T:fp,f:hp,D:gp,I:bp,M:yp,y:wp,sa:_p,V:vp,v:zi,z:$p,N:xp,S:Sp,za:Tp,ya:Ip,la:Bi,ma:Mi,$:Cn,C:Ri,K:Ui,ia:Vi,J:Ni,a:ue,xa:In,va:Gi,r:kp}}}var xn={874964:(s,p,f,b,_)=>{if(u===void 0||!u.Eb)return 1;if((s=Ce(Number(s>>>0))).startsWith("./")&&(s=s.substring(2)),!(s=u.Eb.get(s)))return 2;if(p=Number(p>>>0),f=Number(f>>>0),b=Number(b>>>0),p+f>s.byteLength)return 3;try{let I=s.subarray(p,p+f);switch(_){case 0:r().set(I,b>>>0);break;case 1:u.cc(b,I);break;default:return 4}return 0}catch{return 4}},875679:(s,p,f)=>{u.dc(s,r().subarray(p>>>0,p+f>>>0))},875742:()=>u.ac(),875783:s=>{u.Ob(s)},875819:()=>{u.Vb()},875850:()=>{u.Wb()},875879:()=>{u.$b()},875904:s=>u.Ub(s),875937:s=>u.Yb(s),875969:(s,p,f)=>{u.Nb(Number(s),Number(p),Number(f),!0)},876032:(s,p,f)=>{u.Nb(Number(s),Number(p),Number(f))},876089:()=>typeof wasmOffsetConverter<"u",876146:s=>{u.jb("Abs",s,void 0)},876197:s=>{u.jb("Neg",s,void 0)},876248:s=>{u.jb("Floor",s,void 0)},876301:s=>{u.jb("Ceil",s,void 0)},876353:s=>{u.jb("Reciprocal",s,void 0)},876411:s=>{u.jb("Sqrt",s,void 0)},876463:s=>{u.jb("Exp",s,void 0)},876514:s=>{u.jb("Erf",s,void 0)},876565:s=>{u.jb("Sigmoid",s,void 0)},876620:(s,p,f)=>{u.jb("HardSigmoid",s,{alpha:p,beta:f})},876699:s=>{u.jb("Log",s,void 0)},876750:s=>{u.jb("Sin",s,void 0)},876801:s=>{u.jb("Cos",s,void 0)},876852:s=>{u.jb("Tan",s,void 0)},876903:s=>{u.jb("Asin",s,void 0)},876955:s=>{u.jb("Acos",s,void 0)},877007:s=>{u.jb("Atan",s,void 0)},877059:s=>{u.jb("Sinh",s,void 0)},877111:s=>{u.jb("Cosh",s,void 0)},877163:s=>{u.jb("Asinh",s,void 0)},877216:s=>{u.jb("Acosh",s,void 0)},877269:s=>{u.jb("Atanh",s,void 0)},877322:s=>{u.jb("Tanh",s,void 0)},877374:s=>{u.jb("Not",s,void 0)},877425:(s,p,f)=>{u.jb("Clip",s,{min:p,max:f})},877494:s=>{u.jb("Clip",s,void 0)},877546:(s,p)=>{u.jb("Elu",s,{alpha:p})},877604:s=>{u.jb("Gelu",s,void 0)},877656:s=>{u.jb("Relu",s,void 0)},877708:(s,p)=>{u.jb("LeakyRelu",s,{alpha:p})},877772:(s,p)=>{u.jb("ThresholdedRelu",s,{alpha:p})},877842:(s,p)=>{u.jb("Cast",s,{to:p})},877900:s=>{u.jb("Add",s,void 0)},877951:s=>{u.jb("Sub",s,void 0)},878002:s=>{u.jb("Mul",s,void 0)},878053:s=>{u.jb("Div",s,void 0)},878104:s=>{u.jb("Pow",s,void 0)},878155:s=>{u.jb("Equal",s,void 0)},878208:s=>{u.jb("Greater",s,void 0)},878263:s=>{u.jb("GreaterOrEqual",s,void 0)},878325:s=>{u.jb("Less",s,void 0)},878377:s=>{u.jb("LessOrEqual",s,void 0)},878436:(s,p,f,b,_)=>{u.jb("ReduceMean",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},878611:(s,p,f,b,_)=>{u.jb("ReduceMax",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},878785:(s,p,f,b,_)=>{u.jb("ReduceMin",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},878959:(s,p,f,b,_)=>{u.jb("ReduceProd",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},879134:(s,p,f,b,_)=>{u.jb("ReduceSum",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},879308:(s,p,f,b,_)=>{u.jb("ReduceL1",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},879481:(s,p,f,b,_)=>{u.jb("ReduceL2",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},879654:(s,p,f,b,_)=>{u.jb("ReduceLogSum",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},879831:(s,p,f,b,_)=>{u.jb("ReduceSumSquare",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},880011:(s,p,f,b,_)=>{u.jb("ReduceLogSumExp",s,{keepDims:!!p,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},880191:s=>{u.jb("Where",s,void 0)},880244:(s,p,f)=>{u.jb("Transpose",s,{perm:p?Array.from(i().subarray(Number(p)>>>0,Number(f)>>>0)):[]})},880368:(s,p,f,b)=>{u.jb("DepthToSpace",s,{blocksize:p,mode:Ce(f),format:b?"NHWC":"NCHW"})},880501:(s,p,f,b)=>{u.jb("DepthToSpace",s,{blocksize:p,mode:Ce(f),format:b?"NHWC":"NCHW"})},880634:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z,le)=>{u.jb("ConvTranspose",s,{format:G?"NHWC":"NCHW",autoPad:p,dilations:[f],group:b,kernelShape:[_],pads:[I,D],strides:[B],wIsConst:()=>!!t()[H>>>0],outputPadding:X?Array.from(i().subarray(Number(X)>>>0,Number(ce)>>>0)):[],outputShape:ge?Array.from(i().subarray(Number(ge)>>>0,Number(z)>>>0)):[],activation:Ce(le)})},881067:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z)=>{u.jb("ConvTranspose",s,{format:B?"NHWC":"NCHW",autoPad:p,dilations:Array.from(i().subarray(Number(f)>>>0,2+(Number(f)>>>0)>>>0)),group:b,kernelShape:Array.from(i().subarray(Number(_)>>>0,2+(Number(_)>>>0)>>>0)),pads:Array.from(i().subarray(Number(I)>>>0,4+(Number(I)>>>0)>>>0)),strides:Array.from(i().subarray(Number(D)>>>0,2+(Number(D)>>>0)>>>0)),wIsConst:()=>!!t()[G>>>0],outputPadding:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],outputShape:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[],activation:Ce(z)})},881728:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z,le)=>{u.jb("ConvTranspose",s,{format:G?"NHWC":"NCHW",autoPad:p,dilations:[f],group:b,kernelShape:[_],pads:[I,D],strides:[B],wIsConst:()=>!!t()[H>>>0],outputPadding:X?Array.from(i().subarray(Number(X)>>>0,Number(ce)>>>0)):[],outputShape:ge?Array.from(i().subarray(Number(ge)>>>0,Number(z)>>>0)):[],activation:Ce(le)})},882161:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z)=>{u.jb("ConvTranspose",s,{format:B?"NHWC":"NCHW",autoPad:p,dilations:Array.from(i().subarray(Number(f)>>>0,2+(Number(f)>>>0)>>>0)),group:b,kernelShape:Array.from(i().subarray(Number(_)>>>0,2+(Number(_)>>>0)>>>0)),pads:Array.from(i().subarray(Number(I)>>>0,4+(Number(I)>>>0)>>>0)),strides:Array.from(i().subarray(Number(D)>>>0,2+(Number(D)>>>0)>>>0)),wIsConst:()=>!!t()[G>>>0],outputPadding:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],outputShape:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[],activation:Ce(z)})},882822:(s,p)=>{u.jb("GlobalAveragePool",s,{format:p?"NHWC":"NCHW"})},882913:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z)=>{u.jb("AveragePool",s,{format:z?"NHWC":"NCHW",auto_pad:p,ceil_mode:f,count_include_pad:b,storage_order:_,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(D)>>>0)):[],kernel_shape:B?Array.from(i().subarray(Number(B)>>>0,Number(G)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},883392:(s,p)=>{u.jb("GlobalAveragePool",s,{format:p?"NHWC":"NCHW"})},883483:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z)=>{u.jb("AveragePool",s,{format:z?"NHWC":"NCHW",auto_pad:p,ceil_mode:f,count_include_pad:b,storage_order:_,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(D)>>>0)):[],kernel_shape:B?Array.from(i().subarray(Number(B)>>>0,Number(G)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},883962:(s,p)=>{u.jb("GlobalMaxPool",s,{format:p?"NHWC":"NCHW"})},884049:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z)=>{u.jb("MaxPool",s,{format:z?"NHWC":"NCHW",auto_pad:p,ceil_mode:f,count_include_pad:b,storage_order:_,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(D)>>>0)):[],kernel_shape:B?Array.from(i().subarray(Number(B)>>>0,Number(G)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},884524:(s,p)=>{u.jb("GlobalMaxPool",s,{format:p?"NHWC":"NCHW"})},884611:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z)=>{u.jb("MaxPool",s,{format:z?"NHWC":"NCHW",auto_pad:p,ceil_mode:f,count_include_pad:b,storage_order:_,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(D)>>>0)):[],kernel_shape:B?Array.from(i().subarray(Number(B)>>>0,Number(G)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},885086:(s,p,f,b,_)=>{u.jb("Gemm",s,{alpha:p,beta:f,transA:b,transB:_})},885190:s=>{u.jb("MatMul",s,void 0)},885244:(s,p,f,b)=>{u.jb("ArgMax",s,{keepDims:!!p,selectLastIndex:!!f,axis:b})},885352:(s,p,f,b)=>{u.jb("ArgMin",s,{keepDims:!!p,selectLastIndex:!!f,axis:b})},885460:(s,p)=>{u.jb("Softmax",s,{axis:p})},885523:(s,p)=>{u.jb("Concat",s,{axis:p})},885583:(s,p,f,b,_)=>{u.jb("Split",s,{axis:p,numOutputs:f,splitSizes:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},885739:s=>{u.jb("Expand",s,void 0)},885793:(s,p)=>{u.jb("Gather",s,{axis:Number(p)})},885864:(s,p)=>{u.jb("GatherElements",s,{axis:Number(p)})},885943:(s,p,f,b,_,I,D,B,G,H,X)=>{u.jb("Resize",s,{antialias:p,axes:f?Array.from(i().subarray(Number(f)>>>0,Number(b)>>>0)):[],coordinateTransformMode:Ce(_),cubicCoeffA:I,excludeOutside:D,extrapolationValue:B,keepAspectRatioPolicy:Ce(G),mode:Ce(H),nearestMode:Ce(X)})},886305:(s,p,f,b,_,I,D)=>{u.jb("Slice",s,{starts:p?Array.from(i().subarray(Number(p)>>>0,Number(f)>>>0)):[],ends:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[],axes:I?Array.from(i().subarray(Number(I)>>>0,Number(D)>>>0)):[]})},886569:s=>{u.jb("Tile",s,void 0)},886621:(s,p,f)=>{u.jb("InstanceNormalization",s,{epsilon:p,format:f?"NHWC":"NCHW"})},886735:(s,p,f)=>{u.jb("InstanceNormalization",s,{epsilon:p,format:f?"NHWC":"NCHW"})},886849:s=>{u.jb("Range",s,void 0)},886902:(s,p)=>{u.jb("Einsum",s,{equation:Ce(p)})},886983:(s,p,f,b,_)=>{u.jb("Pad",s,{mode:p,value:f,pads:b?Array.from(i().subarray(Number(b)>>>0,Number(_)>>>0)):[]})},887126:(s,p,f,b,_,I)=>{u.jb("BatchNormalization",s,{epsilon:p,momentum:f,spatial:!!_,trainingMode:!!b,format:I?"NHWC":"NCHW"})},887295:(s,p,f,b,_,I)=>{u.jb("BatchNormalization",s,{epsilon:p,momentum:f,spatial:!!_,trainingMode:!!b,format:I?"NHWC":"NCHW"})},887464:(s,p,f)=>{u.jb("CumSum",s,{exclusive:Number(p),reverse:Number(f)})},887561:(s,p,f)=>{u.jb("DequantizeLinear",s,{axis:p,blockSize:f})},887651:(s,p,f,b,_)=>{u.jb("GridSample",s,{align_corners:p,mode:Ce(f),padding_mode:Ce(b),format:_?"NHWC":"NCHW"})},887821:(s,p,f,b,_)=>{u.jb("GridSample",s,{align_corners:p,mode:Ce(f),padding_mode:Ce(b),format:_?"NHWC":"NCHW"})},887991:(s,p,f,b,_,I,D,B,G)=>{u.jb("Attention",s,{numHeads:p,isUnidirectional:f,maskFilterValue:b,scale:_,doRotary:I,qkvHiddenSizes:D?Array.from(i().subarray(Number(B)>>>0,Number(B)+D>>>0)):[],pastPresentShareBuffer:!!G})},888263:s=>{u.jb("BiasAdd",s,void 0)},888318:s=>{u.jb("BiasSplitGelu",s,void 0)},888379:s=>{u.jb("FastGelu",s,void 0)},888435:(s,p,f,b,_,I,D,B,G,H,X,ce,ge,z,le,Se)=>{u.jb("Conv",s,{format:ce?"NHWC":"NCHW",auto_pad:p,dilations:f?Array.from(i().subarray(Number(f)>>>0,Number(b)>>>0)):[],group:_,kernel_shape:I?Array.from(i().subarray(Number(I)>>>0,Number(D)>>>0)):[],pads:B?Array.from(i().subarray(Number(B)>>>0,Number(G)>>>0)):[],strides:H?Array.from(i().subarray(Number(H)>>>0,Number(X)>>>0)):[],w_is_const:()=>!!t()[Number(ge)>>>0],activation:Ce(z),activation_params:le?Array.from(l().subarray(Number(le)>>>0,Number(Se)>>>0)):[]})},889019:s=>{u.jb("Gelu",s,void 0)},889071:(s,p,f,b,_,I,D,B,G)=>{u.jb("GroupQueryAttention",s,{numHeads:p,kvNumHeads:f,scale:b,softcap:_,doRotary:I,rotaryInterleaved:D,smoothSoftmax:B,localWindowSize:G})},889288:(s,p,f,b)=>{u.jb("LayerNormalization",s,{axis:p,epsilon:f,simplified:!!b})},889399:(s,p,f,b)=>{u.jb("LayerNormalization",s,{axis:p,epsilon:f,simplified:!!b})},889510:(s,p,f,b,_,I)=>{u.jb("MatMulNBits",s,{k:p,n:f,accuracyLevel:b,bits:_,blockSize:I})},889637:(s,p,f,b,_,I)=>{u.jb("MultiHeadAttention",s,{numHeads:p,isUnidirectional:f,maskFilterValue:b,scale:_,doRotary:I})},889796:(s,p)=>{u.jb("QuickGelu",s,{alpha:p})},889860:(s,p,f,b,_)=>{u.jb("RotaryEmbedding",s,{interleaved:!!p,numHeads:f,rotaryEmbeddingDim:b,scale:_})},889999:(s,p,f)=>{u.jb("SkipLayerNormalization",s,{epsilon:p,simplified:!!f})},890101:(s,p,f)=>{u.jb("SkipLayerNormalization",s,{epsilon:p,simplified:!!f})},890203:(s,p,f,b)=>{u.jb("GatherBlockQuantized",s,{gatherAxis:p,quantizeAxis:f,blockSize:b})},890324:s=>{u.Zb(s)},890358:(s,p)=>u.bc(Number(s),Number(p),u.Fb.fc,u.Fb.errors)};function mc(s,p,f){return Si(async()=>{await u.Xb(Number(s),Number(p),Number(f))})}function fc(){return typeof wasmOffsetConverter<"u"}function Sn(s){this.name="ExitStatus",this.message=`Program terminated with exit(${s})`,this.status=s}var Tn=s=>{s.terminate(),s.onmessage=()=>{}},Fo=s=>{pt.length==0&&(Xo(),Zo(pt[0]));var p=pt.pop();if(!p)return 6;_t.push(p),Ze[s.Ab]=p,p.Ab=s.Ab;var f={cmd:"run",start_routine:s.hc,arg:s.Qb,pthread_ptr:s.Ab};return p.postMessage(f,s.mc),0},wt=0,xe=(s,p,...f)=>{for(var b=2*f.length,_=Hn(),I=Gn(8*b),D=I>>>3,B=0;B>>0]=G)}return s=Ki(s,0,b,I,p),_r(_),s};function In(s){if(g)return xe(0,1,s);if(J=s,!(0{if(J=s,g)throw qo(s),"unwind";In(s)},pt=[],_t=[],jo=[],Ze={},Ko=s=>{var p=s.Ab;delete Ze[p],pt.push(s),_t.splice(_t.indexOf(s),1),s.Ab=0,Ln(p)};function Yo(){jo.forEach(s=>s())}var Zo=s=>new Promise(p=>{s.onmessage=_=>{var I=(_=_.data).cmd;if(_.targetThread&&_.targetThread!=Dt()){var D=Ze[_.targetThread];D?D.postMessage(_,_.transferList):K(`Internal error! Worker sent a message "${I}" to target pthread ${_.targetThread}, but that thread no longer exists!`)}else I==="checkMailbox"?dr():I==="spawnThread"?Fo(_):I==="cleanupThread"?Ko(Ze[_.thread]):I==="killThread"?(_=_.thread,I=Ze[_],delete Ze[_],Tn(I),Ln(_),_t.splice(_t.indexOf(I),1),I.Ab=0):I==="cancelThread"?Ze[_.thread].postMessage({cmd:"cancel"}):I==="loaded"?(s.loaded=!0,p(s)):I==="alert"?alert(`Thread ${_.threadId}: ${_.text}`):_.target==="setimmediate"?s.postMessage(_):I==="callHandler"?u[_.handler](..._.args):I&&K(`worker sent an unknown command ${I}`)},s.onerror=_=>{throw K(`worker sent an error! ${_.filename}:${_.lineno}: ${_.message}`),_};var f,b=[];for(f of[])u.hasOwnProperty(f)&&b.push(f);s.postMessage({cmd:"load",handlers:b,wasmMemory:ue,wasmModule:Z})});function Xo(){var s=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});pt.push(s)}var lr=s=>{for(;0{var s=Dt(),p=a()[s+52>>>2>>>0];s=a()[s+56>>>2>>>0],Zi(p,p-s),_r(p)},gc=(s,p)=>{wt=0,s=Xi(s,p),0>>=0);throw p>>>=0,f>>>=0,a()[b.Jb+16>>>2>>>0]=0,a()[b.Jb+4>>>2>>>0]=p,a()[b.Jb+8>>>2>>>0]=f,s}function Qo(s,p,f,b){return g?xe(2,1,s,p,f,b):Jo(s,p,f,b)}function Jo(s,p,f,b){if(s>>>=0,p>>>=0,f>>>=0,b>>>=0,x===void 0)return K("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var _=[];return g&&_.length===0?Qo(s,p,f,b):(s={hc:f,Ab:s,Qb:b,mc:_},g?(s.Mb="spawnThread",postMessage(s,_),0):Fo(s))}var ei=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,ti=(s,p,f)=>{var b=(p>>>=0)+f;for(f=p;s[f]&&!(f>=b);)++f;if(16(_=(240&_)==224?(15&_)<<12|I<<6|D:(7&_)<<18|I<<12|D<<6|63&s[p++])?b+=String.fromCharCode(_):(_-=65536,b+=String.fromCharCode(55296|_>>10,56320|1023&_))}}else b+=String.fromCharCode(_)}return b},Ce=(s,p)=>(s>>>=0)?ti(r(),s,p):"";function ri(s,p,f){return g?xe(3,1,s,p,f):0}function ni(s,p){if(g)return xe(4,1,s,p)}var An=s=>{for(var p=0,f=0;f=b?p++:2047>=b?p+=2:55296<=b&&57343>=b?(p+=4,++f):p+=3}return p},oi=(s,p,f,b)=>{if(!(0>>=0;b=f+b-1;for(var I=0;I=D&&(D=65536+((1023&D)<<10)|1023&s.charCodeAt(++I)),127>=D){if(f>=b)break;p[f++>>>0]=D}else{if(2047>=D){if(f+1>=b)break;p[f++>>>0]=192|D>>6}else{if(65535>=D){if(f+2>=b)break;p[f++>>>0]=224|D>>12}else{if(f+3>=b)break;p[f++>>>0]=240|D>>18,p[f++>>>0]=128|D>>12&63}p[f++>>>0]=128|D>>6&63}p[f++>>>0]=128|63&D}}return p[f>>>0]=0,f-_},Pt=(s,p,f)=>oi(s,r(),p,f);function ii(s,p){if(g)return xe(5,1,s,p)}function ai(s,p,f){if(g)return xe(6,1,s,p,f)}function si(s,p,f){return g?xe(7,1,s,p,f):0}function ui(s,p){if(g)return xe(8,1,s,p)}function li(s,p,f){if(g)return xe(9,1,s,p,f)}function di(s,p,f,b){if(g)return xe(10,1,s,p,f,b)}function ci(s,p,f,b){if(g)return xe(11,1,s,p,f,b)}function pi(s,p,f,b){if(g)return xe(12,1,s,p,f,b)}function mi(s){if(g)return xe(13,1,s)}function fi(s,p){if(g)return xe(14,1,s,p)}function hi(s,p,f){if(g)return xe(15,1,s,p,f)}var gi,mt,wc=()=>{ct("")},Xe=s=>{for(var p="";r()[s>>>0];)p+=gi[r()[s++>>>0]];return p},kn={},En={},_c={};function at(s,p,f={}){if(!("argPackAdvance"in p))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(b,_,I={}){var D=_.name;if(!b)throw new mt(`type "${D}" must have a positive integer typeid pointer`);if(En.hasOwnProperty(b)){if(I.Sb)return;throw new mt(`Cannot register type '${D}' twice`)}En[b]=_,delete _c[b],kn.hasOwnProperty(b)&&(_=kn[b],delete kn[b],_.forEach(B=>B()))}(s,p,f)}var bi=(s,p,f)=>{switch(p){case 1:return f?b=>t()[b>>>0]:b=>r()[b>>>0];case 2:return f?b=>n()[b>>>1>>>0]:b=>o()[b>>>1>>>0];case 4:return f?b=>i()[b>>>2>>>0]:b=>a()[b>>>2>>>0];case 8:return f?b=>q[b>>>3]:b=>he[b>>>3];default:throw new TypeError(`invalid integer width (${p}): ${s}`)}};function vc(s,p,f){f>>>=0,at(s>>>=0,{name:p=Xe(p>>>0),fromWireType:b=>b,toWireType:function(b,_){if(typeof _!="bigint"&&typeof _!="number")throw _=_===null?"null":(b=typeof _)=="object"||b==="array"||b==="function"?_.toString():""+_,new TypeError(`Cannot convert "${_}" to ${this.name}`);return typeof _=="number"&&(_=BigInt(_)),_},argPackAdvance:ft,readValueFromPointer:bi(p,f,p.indexOf("u")==-1),Db:null})}var ft=8;function $c(s,p,f,b){at(s>>>=0,{name:p=Xe(p>>>0),fromWireType:function(_){return!!_},toWireType:function(_,I){return I?f:b},argPackAdvance:ft,readValueFromPointer:function(_){return this.fromWireType(r()[_>>>0])},Db:null})}var Pn=[],st=[];function zn(s){9<(s>>>=0)&&--st[s+1]==0&&(st[s]=void 0,Pn.push(s))}var Le=s=>{if(!s)throw new mt("Cannot use deleted val. handle = "+s);return st[s]},Ge=s=>{switch(s){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let p=Pn.pop()||st.length;return st[p]=s,st[p+1]=1,p}};function On(s){return this.fromWireType(a()[s>>>2>>>0])}var xc={name:"emscripten::val",fromWireType:s=>{var p=Le(s);return zn(s),p},toWireType:(s,p)=>Ge(p),argPackAdvance:ft,readValueFromPointer:On,Db:null};function Sc(s){return at(s>>>0,xc)}var Tc=(s,p)=>{switch(p){case 4:return function(f){return this.fromWireType(l()[f>>>2>>>0])};case 8:return function(f){return this.fromWireType(d()[f>>>3>>>0])};default:throw new TypeError(`invalid float width (${p}): ${s}`)}};function Ic(s,p,f){f>>>=0,at(s>>>=0,{name:p=Xe(p>>>0),fromWireType:b=>b,toWireType:(b,_)=>_,argPackAdvance:ft,readValueFromPointer:Tc(p,f),Db:null})}function Cc(s,p,f,b,_){if(s>>>=0,f>>>=0,p=Xe(p>>>0),_===-1&&(_=4294967295),_=B=>B,b===0){var I=32-8*f;_=B=>B<>>I}var D=p.includes("unsigned")?function(B,G){return G>>>0}:function(B,G){return G};at(s,{name:p,fromWireType:_,toWireType:D,argPackAdvance:ft,readValueFromPointer:bi(p,f,b!==0),Db:null})}function Ac(s,p,f){function b(I){var D=a()[I>>>2>>>0];return I=a()[I+4>>>2>>>0],new _(t().buffer,I,D)}var _=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][p];at(s>>>=0,{name:f=Xe(f>>>0),fromWireType:b,argPackAdvance:ft,readValueFromPointer:b},{Sb:!0})}function kc(s,p){s>>>=0;var f=(p=Xe(p>>>0))==="std::string";at(s,{name:p,fromWireType:function(b){var _=a()[b>>>2>>>0],I=b+4;if(f)for(var D=I,B=0;B<=_;++B){var G=I+B;if(B==_||r()[G>>>0]==0){if(D=Ce(D,G-D),H===void 0)var H=D;else H+=String.fromCharCode(0),H+=D;D=G+1}}else{for(H=Array(_),B=0;B<_;++B)H[B]=String.fromCharCode(r()[I+B>>>0]);H=H.join("")}return Je(b),H},toWireType:function(b,_){_ instanceof ArrayBuffer&&(_=new Uint8Array(_));var I=typeof _=="string";if(!(I||_ instanceof Uint8Array||_ instanceof Uint8ClampedArray||_ instanceof Int8Array))throw new mt("Cannot pass non-string to std::string");var D=f&&I?An(_):_.length,B=yr(4+D+1),G=B+4;if(a()[B>>>2>>>0]=D,f&&I)Pt(_,G,D+1);else if(I)for(I=0;I>>0]=H}else for(I=0;I>>0]=_[I];return b!==null&&b.push(Je,B),B},argPackAdvance:ft,readValueFromPointer:On,Db(b){Je(b)}})}var yi=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Ec=(s,p)=>{for(var f=s>>1,b=f+p/2;!(f>=b)&&o()[f>>>0];)++f;if(32<(f<<=1)-s&&yi)return yi.decode(r().slice(s,f));for(f="",b=0;!(b>=p/2);++b){var _=n()[s+2*b>>>1>>>0];if(_==0)break;f+=String.fromCharCode(_)}return f},Pc=(s,p,f)=>{if(f??=2147483647,2>f)return 0;var b=p;f=(f-=2)<2*s.length?f/2:s.length;for(var _=0;_>>1>>>0]=I,p+=2}return n()[p>>>1>>>0]=0,p-b},zc=s=>2*s.length,Oc=(s,p)=>{for(var f=0,b="";!(f>=p/4);){var _=i()[s+4*f>>>2>>>0];if(_==0)break;++f,65536<=_?(_-=65536,b+=String.fromCharCode(55296|_>>10,56320|1023&_)):b+=String.fromCharCode(_)}return b},Dc=(s,p,f)=>{if(p>>>=0,f??=2147483647,4>f)return 0;var b=p;f=b+f-4;for(var _=0;_=I&&(I=65536+((1023&I)<<10)|1023&s.charCodeAt(++_)),i()[p>>>2>>>0]=I,(p+=4)+4>f)break}return i()[p>>>2>>>0]=0,p-b},Bc=s=>{for(var p=0,f=0;f=b&&++f,p+=4}return p};function Mc(s,p,f){if(s>>>=0,p>>>=0,f=Xe(f>>>=0),p===2)var b=Ec,_=Pc,I=zc,D=B=>o()[B>>>1>>>0];else p===4&&(b=Oc,_=Dc,I=Bc,D=B=>a()[B>>>2>>>0]);at(s,{name:f,fromWireType:B=>{for(var G,H=a()[B>>>2>>>0],X=B+4,ce=0;ce<=H;++ce){var ge=B+4+ce*p;ce!=H&&D(ge)!=0||(X=b(X,ge-X),G===void 0?G=X:(G+=String.fromCharCode(0),G+=X),X=ge+p)}return Je(B),G},toWireType:(B,G)=>{if(typeof G!="string")throw new mt(`Cannot pass non-string to C++ string type ${f}`);var H=I(G),X=yr(4+H+p);return a()[X>>>2>>>0]=H/p,_(G,X+4,H+p),B!==null&&B.push(Je,X),X},argPackAdvance:ft,readValueFromPointer:On,Db(B){Je(B)}})}function Rc(s,p){at(s>>>=0,{Tb:!0,name:p=Xe(p>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Uc=()=>1;function Vc(s){Wn(s>>>0,!y,1,!w,131072,!1),Yo()}var wi=s=>{if(!_e)try{if(s(),!(0>>=0,typeof Atomics.nc=="function"&&(Atomics.nc(i(),s>>>2,s).value.then(dr),s+=128,Atomics.store(i(),s>>>2,1))}var dr=()=>{var s=Dt();s&&(Dn(s),wi(Yi))};function Nc(s,p){(s>>>=0)==p>>>0?setTimeout(dr):g?postMessage({targetThread:s,cmd:"checkMailbox"}):(s=Ze[s])&&s.postMessage({cmd:"checkMailbox"})}var Bn=[];function Wc(s,p,f,b,_){for(p>>>=0,b/=2,Bn.length=b,f=_>>>0>>>3,_=0;_>>0];return(p?xn[p]:Ep[s])(...Bn)}function Lc(s){s>>>=0,g?postMessage({cmd:"cleanupThread",thread:s}):Ko(Ze[s])}function Gc(s){}var Mn=(s,p)=>{var f=En[s];if(f===void 0)throw s=Fi(s),f=Xe(s),Je(s),new mt(`${p} has unknown type ${f}`);return f},_i=(s,p,f)=>{var b=[];return s=s.toWireType(b,f),b.length&&(a()[p>>>2>>>0]=Ge(b)),s};function Hc(s,p,f){return p>>>=0,f>>>=0,s=Le(s>>>0),p=Mn(p,"emval::as"),_i(p,f,s)}var cr=s=>{try{s()}catch(p){ct(p)}},ht=0,Qe=null,vi=0,pr=[],$i={},xi={},Fc=0,Rn=null,qc=[];function Si(s){return function(p){if(!_e){if(ht===0){var f=!1,b=!1;p((_=0)=>{if(!_e&&(vi=_,f=!0,b)){ht=2,cr(()=>ea(Qe)),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.resume(),_=!1;try{var I=function(){var G=i()[Qe+8>>>2>>>0];return G=Y[xi[G]],--wt,G()}()}catch(G){I=G,_=!0}var D=!1;if(!Qe){var B=Rn;B&&(Rn=null,(_?B.reject:B.resolve)(I),D=!0)}if(_&&!D)throw I}}),b=!0,f||(ht=1,Qe=function(){var _=yr(65548),I=_+12;a()[_>>>2>>>0]=I,a()[_+4>>>2>>>0]=I+65536,I=pr[0];var D=$i[I];return D===void 0&&(D=Fc++,$i[I]=D,xi[D]=I),I=D,i()[_+8>>>2>>>0]=I,_}(),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.pause(),cr(()=>Qi(Qe)))}else ht===2?(ht=0,cr(ta),Je(Qe),Qe=null,qc.forEach(wi)):ct(`invalid state: ${ht}`);return vi}}(p=>{s().then(p)})}function jc(s){return s>>>=0,Si(()=>(s=Le(s)).then(Ge))}var mr=[];function Kc(s,p,f,b){return f>>>=0,b>>>=0,(s=mr[s>>>0])(null,p=Le(p>>>0),f,b)}var Yc={},fr=s=>{var p=Yc[s];return p===void 0?Xe(s):p};function Zc(s,p,f,b,_){return f>>>=0,b>>>=0,_>>>=0,(s=mr[s>>>0])(p=Le(p>>>0),p[f=fr(f)],b,_)}var Ti=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Xc(s){return(s>>>=0)==0?Ge(Ti()):(s=fr(s),Ge(Ti()[s]))}var Qc=s=>{var p=mr.length;return mr.push(s),p},Jc=(s,p)=>{for(var f=Array(s),b=0;b>>2>>>0],"parameter "+b);return f},Ii=(s,p)=>Object.defineProperty(p,"name",{value:s});function ep(s,p,f){var b=(p=Jc(s,p>>>0)).shift();s--;var _=`return function (obj, func, destructorsRef, args) { -`,I=0,D=[];f===0&&D.push("obj");for(var B=["retType"],G=[b],H=0;HX.name).join(", ")}) => ${b.name}>`,Qc(Ii(f,s))}function tp(s){return s=fr(s>>>0),Ge(u[s])}function rp(s,p){return p>>>=0,s=Le(s>>>0),p=Le(p),Ge(s[p])}function np(s){9<(s>>>=0)&&(st[s+1]+=1)}function op(){return Ge([])}function ip(s){s=Le(s>>>0);for(var p=Array(s.length),f=0;f>>0))}function sp(){return Ge({})}function up(s){for(var p=Le(s>>>=0);p.length;){var f=p.pop();p.pop()(f)}zn(s)}function lp(s,p,f){p>>>=0,f>>>=0,s=Le(s>>>0),p=Le(p),f=Le(f),s[p]=f}function dp(s,p){return p>>>=0,s=(s=Mn(s>>>0,"_emval_take_value")).readValueFromPointer(p),Ge(s)}function cp(s,p){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),i()[p>>>2>>>0]=s.getUTCSeconds(),i()[p+4>>>2>>>0]=s.getUTCMinutes(),i()[p+8>>>2>>>0]=s.getUTCHours(),i()[p+12>>>2>>>0]=s.getUTCDate(),i()[p+16>>>2>>>0]=s.getUTCMonth(),i()[p+20>>>2>>>0]=s.getUTCFullYear()-1900,i()[p+24>>>2>>>0]=s.getUTCDay(),s=(s.getTime()-Date.UTC(s.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[p+28>>>2>>>0]=s}var zt=s=>s%4==0&&(s%100!=0||s%400==0),Ci=[0,31,60,91,121,152,182,213,244,274,305,335],Ai=[0,31,59,90,120,151,181,212,243,273,304,334];function pp(s,p){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),i()[p>>>2>>>0]=s.getSeconds(),i()[p+4>>>2>>>0]=s.getMinutes(),i()[p+8>>>2>>>0]=s.getHours(),i()[p+12>>>2>>>0]=s.getDate(),i()[p+16>>>2>>>0]=s.getMonth(),i()[p+20>>>2>>>0]=s.getFullYear()-1900,i()[p+24>>>2>>>0]=s.getDay();var f=(zt(s.getFullYear())?Ci:Ai)[s.getMonth()]+s.getDate()-1|0;i()[p+28>>>2>>>0]=f,i()[p+36>>>2>>>0]=-60*s.getTimezoneOffset(),f=new Date(s.getFullYear(),6,1).getTimezoneOffset();var b=new Date(s.getFullYear(),0,1).getTimezoneOffset();s=0|(f!=b&&s.getTimezoneOffset()==Math.min(b,f)),i()[p+32>>>2>>>0]=s}function mp(s){s>>>=0;var p=new Date(i()[s+20>>>2>>>0]+1900,i()[s+16>>>2>>>0],i()[s+12>>>2>>>0],i()[s+8>>>2>>>0],i()[s+4>>>2>>>0],i()[s>>>2>>>0],0),f=i()[s+32>>>2>>>0],b=p.getTimezoneOffset(),_=new Date(p.getFullYear(),6,1).getTimezoneOffset(),I=new Date(p.getFullYear(),0,1).getTimezoneOffset(),D=Math.min(I,_);return 0>f?i()[s+32>>>2>>>0]=+(_!=I&&D==b):0>>2>>>0]=p.getDay(),f=(zt(p.getFullYear())?Ci:Ai)[p.getMonth()]+p.getDate()-1|0,i()[s+28>>>2>>>0]=f,i()[s>>>2>>>0]=p.getSeconds(),i()[s+4>>>2>>>0]=p.getMinutes(),i()[s+8>>>2>>>0]=p.getHours(),i()[s+12>>>2>>>0]=p.getDate(),i()[s+16>>>2>>>0]=p.getMonth(),i()[s+20>>>2>>>0]=p.getYear(),s=p.getTime(),BigInt(isNaN(s)?-1:s/1e3)}function ki(s,p,f,b,_,I,D){return g?xe(16,1,s,p,f,b,_,I,D):-52}function Ei(s,p,f,b,_,I){if(g)return xe(17,1,s,p,f,b,_,I)}function fp(s,p,f,b){s>>>=0,p>>>=0,f>>>=0,b>>>=0;var _=new Date().getFullYear(),I=new Date(_,0,1),D=new Date(_,6,1);_=I.getTimezoneOffset();var B=D.getTimezoneOffset(),G=Math.max(_,B);a()[s>>>2>>>0]=60*G,i()[p>>>2>>>0]=+(_!=B),I=(s=H=>H.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(I),D=s(D),B<_?(Pt(I,f,17),Pt(D,b,17)):(Pt(I,b,17),Pt(D,f,17))}var Un=[],Pi=(s,p)=>{Un.length=0;for(var f;f=r()[s++>>>0];){var b=f!=105;p+=(b&=f!=112)&&p%8?4:0,Un.push(f==112?a()[p>>>2>>>0]:f==106?q[p>>>3]:f==105?i()[p>>>2>>>0]:d()[p>>>3>>>0]),p+=b?8:4}return Un};function hp(s,p,f){return s>>>=0,p=Pi(p>>>0,f>>>0),xn[s](...p)}function gp(s,p,f){return s>>>=0,p=Pi(p>>>0,f>>>0),xn[s](...p)}var bp=()=>{},yp=()=>Date.now();function wp(s,p){return K(Ce(s>>>0,p>>>0))}var zi,_p=()=>{throw wt+=1,"unwind"};function vp(){return 4294901760}zi=()=>performance.timeOrigin+performance.now();var $p=()=>navigator.hardwareConcurrency;function xp(){return ct("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Sp(s){s>>>=0;var p=r().length;if(s<=p||4294901760=f;f*=2){var b=p*(1+.2/f);b=Math.min(b,s+100663296);var _=Math;b=Math.max(s,b);e:{_=(_.min.call(_,4294901760,b+(65536-b%65536)%65536)-ue.buffer.byteLength+65535)/65536;try{ue.grow(_),be();var I=1;break e}catch{}I=void 0}if(I)return!0}return!1}var hr=()=>(ct("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Ot={},Oi=s=>{s.forEach(p=>{var f=hr();f&&(Ot[f]=p)})};function Tp(){var s=Error().stack.toString().split(` -`);return s[0]=="Error"&&s.shift(),Oi(s),Ot.Pb=hr(),Ot.ec=s,Ot.Pb}function Ip(s,p,f){if(s>>>=0,p>>>=0,Ot.Pb==s)var b=Ot.ec;else(b=Error().stack.toString().split(` -`))[0]=="Error"&&b.shift(),Oi(b);for(var _=3;b[_]&&hr()!=s;)++_;for(s=0;s>>2>>>0]=hr();return s}var Vn,Nn={},Di=()=>{if(!Vn){var s,p={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:C||"./this.program"};for(s in Nn)Nn[s]===void 0?delete p[s]:p[s]=Nn[s];var f=[];for(s in p)f.push(`${s}=${p[s]}`);Vn=f}return Vn};function Bi(s,p){if(g)return xe(18,1,s,p);s>>>=0,p>>>=0;var f=0;return Di().forEach((b,_)=>{var I=p+f;for(_=a()[s+4*_>>>2>>>0]=I,I=0;I>>0]=b.charCodeAt(I);t()[_>>>0]=0,f+=b.length+1}),0}function Mi(s,p){if(g)return xe(19,1,s,p);s>>>=0,p>>>=0;var f=Di();a()[s>>>2>>>0]=f.length;var b=0;return f.forEach(_=>b+=_.length+1),a()[p>>>2>>>0]=b,0}function Ri(s){return g?xe(20,1,s):52}function Ui(s,p,f,b){return g?xe(21,1,s,p,f,b):52}function Vi(s,p,f,b){return g?xe(22,1,s,p,f,b):70}var Cp=[null,[],[]];function Ni(s,p,f,b){if(g)return xe(23,1,s,p,f,b);p>>>=0,f>>>=0,b>>>=0;for(var _=0,I=0;I>>2>>>0],B=a()[p+4>>>2>>>0];p+=8;for(var G=0;G>>0],X=Cp[s];H===0||H===10?((s===1?j:K)(ti(X,0)),X.length=0):X.push(H)}_+=B}return a()[b>>>2>>>0]=_,0}var Wi=[31,29,31,30,31,30,31,31,30,31,30,31],Li=[31,28,31,30,31,30,31,31,30,31,30,31],Ap=(s,p)=>{t().set(s,p>>>0)};function Gi(s,p,f,b){function _(z,le,Se){for(z=typeof z=="number"?z.toString():z||"";z.lengthna?-1:0vt-z.getDate())){z.setDate(z.getDate()+le);break}le-=vt-z.getDate()+1,z.setDate(1),11>Se?z.setMonth(Se+1):(z.setMonth(0),z.setFullYear(z.getFullYear()+1))}return Se=new Date(z.getFullYear()+1,0,4),le=B(new Date(z.getFullYear(),0,4)),Se=B(Se),0>=D(le,z)?0>=D(Se,z)?z.getFullYear()+1:z.getFullYear():z.getFullYear()-1}s>>>=0,p>>>=0,f>>>=0,b>>>=0;var H=a()[b+40>>>2>>>0];for(var X in b={kc:i()[b>>>2>>>0],jc:i()[b+4>>>2>>>0],Hb:i()[b+8>>>2>>>0],Lb:i()[b+12>>>2>>>0],Ib:i()[b+16>>>2>>>0],Cb:i()[b+20>>>2>>>0],ub:i()[b+24>>>2>>>0],Bb:i()[b+28>>>2>>>0],sc:i()[b+32>>>2>>>0],ic:i()[b+36>>>2>>>0],lc:H?Ce(H):""},f=Ce(f),H={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})f=f.replace(new RegExp(X,"g"),H[X]);var ce="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),ge="January February March April May June July August September October November December".split(" ");for(X in H={"%a":z=>ce[z.ub].substring(0,3),"%A":z=>ce[z.ub],"%b":z=>ge[z.Ib].substring(0,3),"%B":z=>ge[z.Ib],"%C":z=>I((z.Cb+1900)/100|0,2),"%d":z=>I(z.Lb,2),"%e":z=>_(z.Lb,2," "),"%g":z=>G(z).toString().substring(2),"%G":G,"%H":z=>I(z.Hb,2),"%I":z=>((z=z.Hb)==0?z=12:12{for(var le=0,Se=0;Se<=z.Ib-1;le+=(zt(z.Cb+1900)?Wi:Li)[Se++]);return I(z.Lb+le,3)},"%m":z=>I(z.Ib+1,2),"%M":z=>I(z.jc,2),"%n":()=>` -`,"%p":z=>0<=z.Hb&&12>z.Hb?"AM":"PM","%S":z=>I(z.kc,2),"%t":()=>" ","%u":z=>z.ub||7,"%U":z=>I(Math.floor((z.Bb+7-z.ub)/7),2),"%V":z=>{var le=Math.floor((z.Bb+7-(z.ub+6)%7)/7);if(2>=(z.ub+371-z.Bb-2)%7&&le++,le)le==53&&((Se=(z.ub+371-z.Bb)%7)==4||Se==3&&zt(z.Cb)||(le=1));else{le=52;var Se=(z.ub+7-z.Bb-1)%7;(Se==4||Se==5&&zt(z.Cb%400-1))&&le++}return I(le,2)},"%w":z=>z.ub,"%W":z=>I(Math.floor((z.Bb+7-(z.ub+6)%7)/7),2),"%y":z=>(z.Cb+1900).toString().substring(2),"%Y":z=>z.Cb+1900,"%z":z=>{var le=0<=(z=z.ic);return z=Math.abs(z)/60,(le?"+":"-")+("0000"+(z/60*100+z%60)).slice(-4)},"%Z":z=>z.lc,"%%":()=>"%"},f=f.replace(/%%/g,"\0\0"),H)f.includes(X)&&(f=f.replace(new RegExp(X,"g"),H[X](b)));return X=function(z){var le=Array(An(z)+1);return oi(z,le,0,le.length),le}(f=f.replace(/\0\0/g,"%")),X.length>p?0:(Ap(X,s),X.length-1)}function kp(s,p,f,b){return Gi(s>>>0,p>>>0,f>>>0,b>>>0)}g||function(){for(var s=u.numThreads-1;s--;)Xo();Ye.unshift(()=>{Gt++,function(p){g?p():Promise.all(pt.map(Zo)).then(p)}(()=>Vo())})}();for(var Hi=Array(256),gr=0;256>gr;++gr)Hi[gr]=String.fromCharCode(gr);gi=Hi,mt=u.BindingError=class extends Error{constructor(s){super(s),this.name="BindingError"}},u.InternalError=class extends Error{constructor(s){super(s),this.name="InternalError"}},st.push(0,1,void 0,1,null,1,!0,1,!1,1),u.count_emval_handles=()=>st.length/2-5-Pn.length;var Ep=[In,qo,Qo,ri,ni,ii,ai,si,ui,li,di,ci,pi,mi,fi,hi,ki,Ei,Bi,Mi,Ri,Ui,Vi,Ni],Y=function(){function s(f,b){return Y=f.exports,Y=function(){var _=Y,I={};for(let[D,B]of Object.entries(_))I[D]=typeof B=="function"?(...G)=>{pr.push(D);try{return B(...G)}finally{_e||(pr.pop(),Qe&&ht===1&&pr.length===0&&(ht=0,wt+=1,cr(Ji),typeof Fibers<"u"&&Fibers.tc()))}}:B;return I}(),Y=function(){var _=Y,I=B=>G=>B(G)>>>0,D=B=>()=>B()>>>0;return(_=Object.assign({},_)).Ca=I(_.Ca),_.fb=D(_.fb),_.hb=I(_.hb),_.emscripten_main_runtime_thread_id=D(_.emscripten_main_runtime_thread_id),_.sb=I(_.sb),_.tb=D(_.tb),_}(),jo.push(Y.ib),Lt.unshift(Y.Ba),Z=b,Vo(),Y}var p=Ho();if(Gt++,u.instantiateWasm)try{return u.instantiateWasm(p,s)}catch(f){K(`Module.instantiateWasm callback failed with error: ${f}`),m(f)}return $n||=u.locateFile?No("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":u.locateFile?u.locateFile("ort-wasm-simd-threaded.jsep.wasm",P):P+"ort-wasm-simd-threaded.jsep.wasm":new URL(/* asset import */ __webpack_require__(/*! ort-wasm-simd-threaded.jsep.wasm */ "./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"), __webpack_require__.b).href,function(f,b){var _=$n;return O||typeof WebAssembly.instantiateStreaming!="function"||No(_)||Wo(_)||typeof fetch!="function"?Go(_,f,b):fetch(_,{credentials:"same-origin"}).then(I=>WebAssembly.instantiateStreaming(I,f).then(b,function(D){return K(`wasm streaming compile failed: ${D}`),K("falling back to ArrayBuffer instantiation"),Go(_,f,b)}))}(p,function(f){s(f.instance,f.module)}).catch(m),{}}(),Fi=s=>(Fi=Y.Ca)(s),qi=()=>(qi=Y.Da)();u._OrtInit=(s,p)=>(u._OrtInit=Y.Ea)(s,p),u._OrtGetLastError=(s,p)=>(u._OrtGetLastError=Y.Fa)(s,p),u._OrtCreateSessionOptions=(s,p,f,b,_,I,D,B,G,H)=>(u._OrtCreateSessionOptions=Y.Ga)(s,p,f,b,_,I,D,B,G,H),u._OrtAppendExecutionProvider=(s,p)=>(u._OrtAppendExecutionProvider=Y.Ha)(s,p),u._OrtAddFreeDimensionOverride=(s,p,f)=>(u._OrtAddFreeDimensionOverride=Y.Ia)(s,p,f),u._OrtAddSessionConfigEntry=(s,p,f)=>(u._OrtAddSessionConfigEntry=Y.Ja)(s,p,f),u._OrtReleaseSessionOptions=s=>(u._OrtReleaseSessionOptions=Y.Ka)(s),u._OrtCreateSession=(s,p,f)=>(u._OrtCreateSession=Y.La)(s,p,f),u._OrtReleaseSession=s=>(u._OrtReleaseSession=Y.Ma)(s),u._OrtGetInputOutputCount=(s,p,f)=>(u._OrtGetInputOutputCount=Y.Na)(s,p,f),u._OrtGetInputName=(s,p)=>(u._OrtGetInputName=Y.Oa)(s,p),u._OrtGetOutputName=(s,p)=>(u._OrtGetOutputName=Y.Pa)(s,p),u._OrtFree=s=>(u._OrtFree=Y.Qa)(s),u._OrtCreateTensor=(s,p,f,b,_,I)=>(u._OrtCreateTensor=Y.Ra)(s,p,f,b,_,I),u._OrtGetTensorData=(s,p,f,b,_)=>(u._OrtGetTensorData=Y.Sa)(s,p,f,b,_),u._OrtReleaseTensor=s=>(u._OrtReleaseTensor=Y.Ta)(s),u._OrtCreateRunOptions=(s,p,f,b)=>(u._OrtCreateRunOptions=Y.Ua)(s,p,f,b),u._OrtAddRunConfigEntry=(s,p,f)=>(u._OrtAddRunConfigEntry=Y.Va)(s,p,f),u._OrtReleaseRunOptions=s=>(u._OrtReleaseRunOptions=Y.Wa)(s),u._OrtCreateBinding=s=>(u._OrtCreateBinding=Y.Xa)(s),u._OrtBindInput=(s,p,f)=>(u._OrtBindInput=Y.Ya)(s,p,f),u._OrtBindOutput=(s,p,f,b)=>(u._OrtBindOutput=Y.Za)(s,p,f,b),u._OrtClearBoundOutputs=s=>(u._OrtClearBoundOutputs=Y._a)(s),u._OrtReleaseBinding=s=>(u._OrtReleaseBinding=Y.$a)(s),u._OrtRunWithBinding=(s,p,f,b,_)=>(u._OrtRunWithBinding=Y.ab)(s,p,f,b,_),u._OrtRun=(s,p,f,b,_,I,D,B)=>(u._OrtRun=Y.bb)(s,p,f,b,_,I,D,B),u._OrtEndProfiling=s=>(u._OrtEndProfiling=Y.cb)(s),u._JsepOutput=(s,p,f)=>(u._JsepOutput=Y.db)(s,p,f),u._JsepGetNodeName=s=>(u._JsepGetNodeName=Y.eb)(s);var br,Dt=()=>(Dt=Y.fb)(),Je=u._free=s=>(Je=u._free=Y.gb)(s),yr=u._malloc=s=>(yr=u._malloc=Y.hb)(s),Wn=(s,p,f,b,_,I)=>(Wn=Y.kb)(s,p,f,b,_,I),ji=()=>(ji=Y.lb)(),Ki=(s,p,f,b,_)=>(Ki=Y.mb)(s,p,f,b,_),Ln=s=>(Ln=Y.nb)(s),wr=s=>(wr=Y.ob)(s),Yi=()=>(Yi=Y.pb)(),Zi=(s,p)=>(Zi=Y.qb)(s,p),_r=s=>(_r=Y.rb)(s),Gn=s=>(Gn=Y.sb)(s),Hn=()=>(Hn=Y.tb)(),Xi=u.dynCall_ii=(s,p)=>(Xi=u.dynCall_ii=Y.vb)(s,p),Qi=s=>(Qi=Y.wb)(s),Ji=()=>(Ji=Y.xb)(),ea=s=>(ea=Y.yb)(s),ta=()=>(ta=Y.zb)();function ra(){0Hn(),u.stackRestore=s=>_r(s),u.stackAlloc=s=>Gn(s),u.setValue=function(s,p,f="i8"){switch(f.endsWith("*")&&(f="*"),f){case"i1":case"i8":t()[s>>>0]=p;break;case"i16":n()[s>>>1>>>0]=p;break;case"i32":i()[s>>>2>>>0]=p;break;case"i64":q[s>>>3]=BigInt(p);break;case"float":l()[s>>>2>>>0]=p;break;case"double":d()[s>>>3>>>0]=p;break;case"*":a()[s>>>2>>>0]=p;break;default:ct(`invalid type for setValue: ${f}`)}},u.getValue=function(s,p="i8"){switch(p.endsWith("*")&&(p="*"),p){case"i1":case"i8":return t()[s>>>0];case"i16":return n()[s>>>1>>>0];case"i32":return i()[s>>>2>>>0];case"i64":return q[s>>>3];case"float":return l()[s>>>2>>>0];case"double":return d()[s>>>3>>>0];case"*":return a()[s>>>2>>>0];default:ct(`invalid type for getValue: ${p}`)}},u.UTF8ToString=Ce,u.stringToUTF8=Pt,u.lengthBytesUTF8=An,Ht=function s(){br||ra(),br||(Ht=s)},ra(),u.PTR_SIZE=4,h}),Np=Ua;globalThis.self?.name==="em-pthread"&&Ua()});var Bt,Wp,Lp,Gp,Wa,La,Hp,Ga,jt=R(()=>{"use strict";Er();Bt= false?0:import.meta.url??(typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0),Wp= false||typeof location>"u"?void 0:location.origin,Lp=(e,t)=>{try{let r=t??Bt;return(r?new URL(e,r):new URL(e)).origin===Wp}catch{return!1}},Gp=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},Wa=(Ra(),vr(Ma)).default,La=async()=>{if(!Bt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Lp(Bt))return[void 0,Wa()];let e=await Gp(Bt);return[e,Wa(e)]},Hp=(Na(),vr(Va)).default,Ga=async(e,t,r)=>[void 0,Hp]});var Jn,eo,Vr,Ha,Fp,qp,Pr,Te,gt=R(()=>{"use strict";jt();eo=!1,Vr=!1,Ha=!1,Fp=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},qp=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Pr=async e=>{if(eo)return Promise.resolve();if(Vr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ha)throw new Error("previous call to 'initializeWebAssembly()' failed.");Vr=!0;let t=e.initTimeout,r=e.numThreads;if(!qp())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=Fp();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let o=e.wasmPaths,i=typeof o=="string"?o:void 0,a=o?.mjs,l=a?.href??a,d=o?.wasm,c=d?.href??d,m=e.wasmBinary,[u,h]=await Ga(l,i,r>1),w=!1,y=[];if(t>0&&y.push(new Promise(g=>{setTimeout(()=>{w=!0,g()},t)})),y.push(new Promise((g,x)=>{let $={numThreads:r};m?$.wasmBinary=m:(c||i)&&($.locateFile=(v,S)=>c??(i??S)+v),h($).then(v=>{Vr=!1,eo=!0,Jn=v,g(),u&&URL.revokeObjectURL(u)},v=>{Vr=!1,Ha=!0,x(v)})})),await Promise.race(y),w)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Te=()=>{if(eo&&Jn)return Jn;throw new Error("WebAssembly is not initialized yet.")}});var ke,Yt,pe,Nr=R(()=>{"use strict";gt();ke=(e,t)=>{let r=Te(),n=r.lengthBytesUTF8(e)+1,o=r._malloc(n);return r.stringToUTF8(e,o,n),t.push(o),o},Yt=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([o,i])=>{let a=t?t+o:o;if(typeof i=="object")Yt(i,a+".",r,n);else if(typeof i=="string"||typeof i=="number")n(a,i.toString());else if(typeof i=="boolean")n(a,i?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof i}`)})},pe=e=>{let t=Te(),r=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetLastError(o,o+n);let i=Number(t.getValue(o,n===4?"i32":"i64")),a=t.getValue(o+n,"*"),l=a?t.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${l}`)}finally{t.stackRestore(r)}}});var Fa,qa=R(()=>{"use strict";gt();Nr();Fa=e=>{let t=Te(),r=0,n=[],o=e||{};try{if(e?.logSeverityLevel===void 0)o.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)o.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(o.terminate=!1);let i=0;return e?.tag!==void 0&&(i=ke(e.tag,n)),r=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,i),r===0&&pe("Can't create run options."),e?.extra!==void 0&&Yt(e.extra,"",new WeakSet,(a,l)=>{let d=ke(a,n),c=ke(l,n);t._OrtAddRunConfigEntry(r,d,c)!==0&&pe(`Can't set a run config entry: ${a} - ${l}.`)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(a=>t._free(a)),i}}});var jp,Kp,Yp,Zp,ja,Ka=R(()=>{"use strict";gt();Nr();jp=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},Kp=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Yp=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},Zp=(e,t,r)=>{for(let n of t){let o=typeof n=="string"?n:n.name;switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let l=n?.deviceType;if(l){let d=ke("deviceType",r),c=ke(l,r);Te()._OrtAddSessionConfigEntry(e,d,c)!==0&&pe(`Can't set a session config entry: 'deviceType' - ${l}.`)}}break;case"webgpu":if(o="JS",typeof n!="string"){let a=n;if(a?.preferredLayout){if(a.preferredLayout!=="NCHW"&&a.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${a.preferredLayout}`);let l=ke("preferredLayout",r),d=ke(a.preferredLayout,r);Te()._OrtAddSessionConfigEntry(e,l,d)!==0&&pe(`Can't set a session config entry: 'preferredLayout' - ${a.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=ke(o,r);Te()._OrtAppendExecutionProvider(e,i)!==0&&pe(`Can't append execution provider: ${o}.`)}},ja=e=>{let t=Te(),r=0,n=[],o=e||{};Yp(o);try{let i=jp(o.graphOptimizationLevel??"all"),a=Kp(o.executionMode??"sequential"),l=typeof o.logId=="string"?ke(o.logId,n):0,d=o.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let c=o.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let m=typeof o.optimizedModelFilePath=="string"?ke(o.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(i,!!o.enableCpuMemArena,!!o.enableMemPattern,a,!!o.enableProfiling,0,l,d,c,m),r===0&&pe("Can't create session options."),o.executionProviders&&Zp(r,o.executionProviders,n),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);let u=ke("enableGraphCapture",n),h=ke(o.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,u,h)!==0&&pe(`Can't set a session config entry: 'enableGraphCapture' - ${o.enableGraphCapture}.`)}if(o.freeDimensionOverrides)for(let[u,h]of Object.entries(o.freeDimensionOverrides)){if(typeof u!="string")throw new Error(`free dimension override name must be a string: ${u}`);if(typeof h!="number"||!Number.isInteger(h)||h<0)throw new Error(`free dimension override value must be a non-negative integer: ${h}`);let w=ke(u,n);t._OrtAddFreeDimensionOverride(r,w,h)!==0&&pe(`Can't set a free dimension override: ${u} - ${h}.`)}return o.extra!==void 0&&Yt(o.extra,"",new WeakSet,(u,h)=>{let w=ke(u,n),y=ke(h,n);t._OrtAddSessionConfigEntry(r,w,y)!==0&&pe(`Can't set a session config entry: ${u} - ${h}.`)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&pe("Can't release session options."),n.forEach(a=>t._free(a)),i}}});var Zt,bt,Tt,Wr,Xt,Lr,Gr,to,te=R(()=>{"use strict";Zt=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},bt=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},Tt=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((o,i)=>o*i,1);return r>0?Math.ceil(n*r):void 0},Wr=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Xt=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},Lr=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Gr=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",to=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}});var Qt,ro=R(()=>{"use strict";Er();Qt=async e=>{if(typeof e=="string")if(false){}else{let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=t.body.getReader(),i;try{i=new ArrayBuffer(n)}catch(l){if(l instanceof RangeError){let d=Math.ceil(n/65536);i=new WebAssembly.Memory({initial:d,maximum:d}).buffer}else throw l}let a=0;for(;;){let{done:l,value:d}=await o.read();if(l)break;let c=d.byteLength;new Uint8Array(i,a,c).set(d),a+=c}return new Uint8Array(i,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}});var Xp,Qp,Ya,Za,Hr,Jp,se,je=R(()=>{"use strict";te();Xp=["V","I","W","E","F"],Qp=(e,t)=>{console.log(`[${Xp[e]},${new Date().toISOString()}]${t}`)},Hr=(e,t)=>{Ya=e,Za=t},Jp=(e,t)=>{let r=Xt(e),n=Xt(Ya);r>=n&&Qp(r,typeof t=="function"?t():t)},se=(...e)=>{Za&&Jp(...e)}});var Fr,no=R(()=>{"use strict";te();Fr=(e,t)=>new(Wr(t))(e)});var qr=R(()=>{"use strict"});var Xa,oo,io,em,tm,Qa,so,ao,es,ts=R(()=>{"use strict";je();qr();Xa=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),oo=[],io=e=>Math.ceil(Number(e)/16)*16,em=e=>{for(let t=0;ttm++,so=async(e,t,r,n)=>{let o=io(r),i=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=e.getCommandEncoder();e.endComputePass(),a.copyBufferToBuffer(t,0,i,0,o),e.flush(),await i.mapAsync(GPUMapMode.READ);let l=i.getMappedRange();if(n){let d=n();return d.set(new Uint8Array(l,0,r)),d}else return new Uint8Array(l.slice(0,r))}finally{i.destroy()}},ao=class{constructor(t){this.backend=t;this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[r]of Xa)oo.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(t,r){let n=r.buffer,o=r.byteOffset,i=r.byteLength,a=io(i),l=this.storageCache.get(t);if(!l)throw new Error("gpu data for uploading does not exist");if(Number(l.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${l.originalSize}, data size=${i}`);let d=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),c=d.getMappedRange();new Uint8Array(c).set(new Uint8Array(n,o,i)),d.unmap();let m=this.backend.device.createCommandEncoder();m.copyBufferToBuffer(d,0,l.gpuData.buffer,0,a),this.backend.device.queue.submit([m.finish()]),d.destroy(),se("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${t})`)}memcpy(t,r){let n=this.storageCache.get(t);if(!n)throw new Error("source gpu data for memcpy does not exist");let o=this.storageCache.get(r);if(!o)throw new Error("destination gpu data for memcpy does not exist");if(n.originalSize!==o.originalSize)throw new Error("inconsistent source and destination gpu data size");let i=io(n.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(n.gpuData.buffer,0,o.gpuData.buffer,0,i)}registerExternalBuffer(t,r,n){let o;if(n){if(o=n[0],t===n[1])return se("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, buffer is the same, skip.`),o;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. - Please use the previous external buffer!`)}else o=Qa();return this.storageCache.set(o,{gpuData:{id:o,type:0,buffer:t},originalSize:r}),se("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, registered.`),o}unregisterExternalBuffer(t){t!==void 0&&(this.storageCache.delete(t),se("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`))}create(t,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=em(t),o,i=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let c=(i?this.freeBuffers:this.freeUniformBuffers).get(n);c?c.length>0?o=c.pop():o=this.backend.device.createBuffer({size:n,usage:r}):o=this.backend.device.createBuffer({size:n,usage:r})}else o=this.backend.device.createBuffer({size:n,usage:r});let l={id:Qa(),type:0,buffer:o};return this.storageCache.set(l.id,{gpuData:l,originalSize:Number(t)}),se("verbose",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${l.id}`),l}get(t){return this.storageCache.get(t)?.gpuData}release(t){let r=typeof t=="bigint"?Number(t):t,n=this.storageCache.get(r);if(!n){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return se("verbose",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${n.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(t,r){let n=this.storageCache.get(Number(t));if(!n)throw new Error("data does not exist");await so(this.backend,n.gpuData.buffer,n.originalSize,r)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let t of this.buffersPending){let r=Xa.get(t.size);if((t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(t.size)||[];r===void 0||n.length>=r?t.destroy():n.push(t)}else if((t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(t.size)||[];r===void 0||n.length>=r?t.destroy():n.push(t)}else t.destroy()}this.buffersPending=[]}else{let t=this.capturedPendingBuffers.get(this.backend.currentSessionId);t||(t=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,t));for(let r of this.buffersPending)t.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(t){let r=this.capturedPendingBuffers.get(t);r&&(r.forEach(n=>{n.destroy()}),this.capturedPendingBuffers.delete(t)),this.sessionCount-=1,this.sessionCount===0&&(se("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(n=>{n.gpuData.buffer.destroy()}),this.storageCache=new Map)}},es=(...e)=>new ao(...e)});var uo,re,Ie=R(()=>{"use strict";uo=class{constructor(t){Object.assign(this,t)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(t=>`${this[t]}`).join(";")),this.key}},re=e=>new uo(e)});var lo,et,k,It,jr,rs,ns,oe=R(()=>{"use strict";lo=class{static calcMatMulShape(t,r){return t[1]!==r[0]?void 0:[t[0],r[1]]}},et=class{static calcShape(t,r,n=!1){let o=t.length,i=r.length;if(o===0)return r;if(i===0)return t;let a=Math.max(t.length,r.length),l=new Array(a);if(n){if(o<2||i<2)return;let d=lo.calcMatMulShape([t[o-2],t[o-1]],[r[i-2],r[i-1]]);if(d===void 0)return;[l[a-2],l[a-1]]=d}for(let d=n?3:1;d<=a;d++){let c=o-d<0?1:t[o-d],m=i-d<0?1:r[i-d];if(c!==m&&c>1&&m>1)return;let u=Math.max(c,m);if(c&&m)l[a-d]=Math.max(c,m);else{if(u>1)return;l[a-d]=0}}return l}static isValidBroadcast(t,r){let n=t.length,o=r.length;if(n>o)return!1;for(let i=1;i<=n;i++)if(t[n-i]!==1&&t[n-i]!==r[o-i])return!1;return!0}},k=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let o=new Array(n),i=n-1;for(;i>=0;){if(t[i]%r===0){o[i]=t[i]/r;break}if(r%t[i]!==0)throw new Error("cannot convert shape");o[i]=1,r/=t[i],i--}for(i--;i>=0;i--)o[i]=t[i];return o}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let o=1;for(let i=r;i=0;--o)n[o]=n[o+1]*t[o+1];return n}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(n=>this.normalizeAxis(n,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(n=>t[n]):t.slice().reverse()}static padShape(t,r){let n=t.length;return t.map((o,i)=>o+r[i]+r[i+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,o)=>n===r[o])}},It=class e{static adjustPoolAttributes(t,r,n,o,i,a){if(!t&&n.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let l=0;l=n.length?n.push(r[l+2]):n[l]=r[l+2];for(let l=0;l=n[l]||a[l+n.length]>=n[l])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,n,o,i,a,l){if(l){if(i.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(o.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let d=0;d{"use strict";te();oe();Ct=64,po=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},me=(e,t=1)=>{let r=po(e,t);return typeof r=="string"?r:r[0]},Ee=(e,t=1)=>{let r=po(e,t);return typeof r=="string"?r:r[1]},V=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:k.computeStrides(r)})}),t},ye=e=>e%4===0?4:e%2===0?2:1,mo=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,At=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,Ke=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,F=(e,t,r,n)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,fo=(e,t,r,n,o)=>{let i=typeof r=="number",a=i?r:r.length,l=[...new Array(a).keys()],d=a<2?"u32":a<=4?`vec${a}`:`array`,c=po(t,o),m=typeof c=="string"?c:c[1],u=typeof c=="string"?c:c[0],h={indices:d,value:m,storage:u,tensor:t},w=N=>typeof N=="string"?N:`${N}u`,y={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},g=i?"uniforms.":"",x=`${g}${e}_shape`,$=`${g}${e}_strides`,v="";for(let N=0;Ntypeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var R=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ft=(e,t)=>{for(var r in t)Ln(e,r,{get:t[r],enumerable:!0})},Rp=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Dp(t))!Mp.call(e,o)&&o!==r&&Ln(e,o,{get:()=>t[o],enumerable:!(n=Bp(t,o))||n.enumerable});return e};var br=e=>Rp(Ln({},"__esModule",{value:!0}),e);var yr,$t,xt,Up,_r,wr=R(()=>{"use strict";yr=new Map,$t=[],xt=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=yr.get(e);if(n===void 0)yr.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let o=$t.indexOf(e);o!==-1&&$t.splice(o,1);for(let i=0;i<$t.length;i++)if(yr.get($t[i]).priority<=r){$t.splice(i,0,e);return}$t.push(e)}return}throw new TypeError("not a valid backend")},Up=async e=>{let t=yr.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},_r=async e=>{let t=e.executionProviders||[],r=t.map(d=>typeof d=="string"?d:d.name),n=r.length===0?$t:r,o,i=[],a=new Set;for(let d of n){let p=await Up(d);typeof p=="string"?i.push({name:d,err:p}):(o||(o=p),o===p&&a.add(d))}if(!o)throw new Error(`no available backend found. ERR: ${i.map(d=>`[${d.name}] ${d.err}`).join(", ")}`);for(let{name:d,err:p}of i)r.includes(d)&&console.warn(`removing requested execution provider "${d}" from session options because it is not available: ${p}`);let l=t.filter(d=>a.has(typeof d=="string"?d:d.name));return[o,new Proxy(e,{get:(d,p)=>p==="executionProviders"?l:Reflect.get(d,p)})]}});var ea=R(()=>{"use strict";wr()});var ta,ra=R(()=>{"use strict";ta="1.21.0-dev.20241026-05fbb43b34"});var na,Re,Hn=R(()=>{"use strict";ra();na="warning",Re={wasm:{},webgl:{},webgpu:{},versions:{common:ta},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);na=e}},get logLevel(){return na}};Object.defineProperty(Re,"logLevel",{enumerable:!0})});var we,oa=R(()=>{"use strict";Hn();we=Re});var ia,aa,sa=R(()=>{"use strict";ia=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let o,i;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],i=e.dims[3]):(o=e.dims[3],i=e.dims[2]);let a=t?.format!==void 0?t.format:"RGB",l=t?.norm,d,p;l===void 0||l.mean===void 0?d=[255,255,255,255]:typeof l.mean=="number"?d=[l.mean,l.mean,l.mean,l.mean]:(d=[l.mean[0],l.mean[1],l.mean[2],0],l.mean[3]!==void 0&&(d[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let m=i*o,u=0,h=m,_=m*2,y=-1;a==="RGBA"?(u=0,h=m,_=m*2,y=m*3):a==="RGB"?(u=0,h=m,_=m*2):a==="RBG"&&(u=0,_=m,h=m*2);for(let g=0;g{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let o,i,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],i=e.dims[1],a=e.dims[3]):(o=e.dims[3],i=e.dims[2],a=e.dims[1]);let l=t!==void 0&&t.format!==void 0?t.format:"RGB",d=t?.norm,p,m;d===void 0||d.mean===void 0?p=[255,255,255,255]:typeof d.mean=="number"?p=[d.mean,d.mean,d.mean,d.mean]:(p=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(p[3]=d.mean[3])),d===void 0||d.bias===void 0?m=[0,0,0,0]:typeof d.bias=="number"?m=[d.bias,d.bias,d.bias,d.bias]:(m=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(m[3]=d.bias[3]));let u=i*o;if(t!==void 0&&(t.format!==void 0&&a===4&&t.format!=="RGBA"||a===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let h=4,_=0,y=1,g=2,x=3,$=0,v=u,S=u*2,T=-1;l==="RGBA"?($=0,v=u,S=u*2,T=u*3):l==="RGB"?($=0,v=u,S=u*2):l==="RBG"&&($=0,S=u,v=u*2),n=r.createImageData(o,i);for(let C=0;C{"use strict";vr();Fn=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,o=t.norm??{mean:255,bias:0},i,a;typeof o.mean=="number"?i=[o.mean,o.mean,o.mean,o.mean]:i=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?a=[o.bias,o.bias,o.bias,o.bias]:a=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let l=t.format!==void 0?t.format:"RGBA",d=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",p=r*n,m=d==="RGBA"?new Float32Array(p*4):new Float32Array(p*3),u=4,h=0,_=1,y=2,g=3,x=0,$=p,v=p*2,S=-1;l==="RGB"&&(u=3,h=0,_=1,y=2,g=-1),d==="RGBA"?S=p*3:d==="RBG"?(x=0,v=p,$=p*2):d==="BGR"&&(v=0,$=p,x=p*2);for(let C=0;C{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,i=typeof e=="string",a,l=t??{},d=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},p=m=>typeof HTMLCanvasElement<"u"&&m instanceof HTMLCanvasElement||m instanceof OffscreenCanvas?m.getContext("2d"):null;if(r){let m=d();m.width=e.width,m.height=e.height;let u=p(m);if(u!=null){let h=e.height,_=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(h=t.resizedHeight,_=t.resizedWidth),t!==void 0){if(l=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");l.tensorFormat="RGBA",l.height=h,l.width=_}else l.tensorFormat="RGBA",l.height=h,l.width=_;u.drawImage(e,0,0),a=u.getImageData(0,0,_,h).data}else throw new Error("Can not access image data")}else if(n){let m,u;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(m=t.resizedHeight,u=t.resizedWidth):(m=e.height,u=e.width),t!==void 0&&(l=t),l.format="RGBA",l.height=m,l.width=u,t!==void 0){let h=d();h.width=u,h.height=m;let _=p(h);if(_!=null)_.putImageData(e,0,0),a=_.getImageData(0,0,u,m).data;else throw new Error("Can not access image data")}else a=e.data}else if(o){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let m=d();m.width=e.width,m.height=e.height;let u=p(m);if(u!=null){let h=e.height,_=e.width;return u.drawImage(e,0,0,_,h),a=u.getImageData(0,0,_,h).data,l.height=h,l.width=_,Fn(a,l)}else throw new Error("Can not access image data")}else{if(i)return new Promise((m,u)=>{let h=d(),_=p(h);if(!e||!_)return u();let y=new Image;y.crossOrigin="Anonymous",y.src=e,y.onload=()=>{h.width=y.width,h.height=y.height,_.drawImage(y,0,0,h.width,h.height);let g=_.getImageData(0,0,h.width,h.height);l.height=h.height,l.width=h.width,m(Fn(g.data,l))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Fn(a,l);throw new Error("Input data provided is not supported - aborted tensor creation")},la=(e,t)=>{let{width:r,height:n,download:o,dispose:i}=t,a=[1,n,r,4];return new ze({location:"texture",type:"float32",texture:e,dims:a,download:o,dispose:i})},da=(e,t)=>{let{dataType:r,dims:n,download:o,dispose:i}=t;return new ze({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:o,dispose:i})},ca=(e,t)=>{let{dataType:r,dims:n,download:o,dispose:i}=t;return new ze({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:o,dispose:i})},pa=(e,t,r)=>new ze({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})});var St,qt,fa,ha,ga=R(()=>{"use strict";St=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),qt=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),fa=!1,ha=()=>{if(!fa){fa=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&(St.set("int64",BigInt64Array),qt.set(BigInt64Array,"int64")),t&&(St.set("uint64",BigUint64Array),qt.set(BigUint64Array,"uint64")),r?(St.set("float16",Float16Array),qt.set(Float16Array,"float16")):St.set("float16",Uint16Array)}}});var ba,ya,_a=R(()=>{"use strict";vr();ba=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new ze(e.type,e.data,t);case"cpu-pinned":return new ze({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new ze({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new ze({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new ze({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}});var ze,vr=R(()=>{"use strict";sa();ma();ga();_a();ze=class{constructor(t,r,n){ha();let o,i;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,o=t.type,i=t.dims,t.location){case"cpu-pinned":{let l=St.get(o);if(!l)throw new TypeError(`unsupported type "${o}" to create tensor from pinned buffer`);if(!(t.data instanceof l))throw new TypeError(`buffer should be of type ${l.name}`);this.cpuData=t.data;break}case"texture":{if(o!=="float32")throw new TypeError(`unsupported type "${o}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint64"&&o!=="int8"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let l,d;if(typeof t=="string")if(o=t,d=n,t==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");l=r}else{let p=St.get(t);if(p===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t==="float16"&&p===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${p.name} as data.`);t==="uint64"||t==="int64"?l=p.from(r,BigInt):l=p.from(r)}else if(r instanceof p)l=r;else if(r instanceof Uint8ClampedArray)if(t==="uint8")l=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${o} tensor's data must be type of ${p}`)}else if(d=r,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let p=typeof t[0];if(p==="string")o="string",l=t;else if(p==="boolean")o="bool",l=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${p}.`)}else if(t instanceof Uint8ClampedArray)o="uint8",l=Uint8Array.from(t);else{let p=qt.get(t.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);o=p,l=t}if(d===void 0)d=[l.length];else if(!Array.isArray(d))throw new TypeError("A tensor's dims must be a number array");i=d,this.cpuData=l,this.dataLocation="cpu"}let a=ba(i);if(this.cpuData&&a!==this.cpuData.length&&!((o==="uint4"||o==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=i,this.size=a}static async fromImage(t,r){return ua(t,r)}static fromTexture(t,r){return la(t,r)}static fromGpuBuffer(t,r){return da(t,r)}static fromMLTensor(t,r){return ca(t,r)}static fromPinnedBuffer(t,r,n){return pa(t,r,n)}toDataURL(t){return ia(this,t)}toImageData(t){return aa(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,t&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return ya(this,t)}}});var Oe,$r=R(()=>{"use strict";vr();Oe=ze});var xr,wa,Ue,De,qn=R(()=>{"use strict";Hn();xr=(e,t)=>{(typeof Re.trace>"u"?!Re.wasm.trace:!Re.trace)||console.timeStamp(`${e}::ORT::${t}`)},wa=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],n=!1;for(let o=0;o{(typeof Re.trace>"u"?!Re.wasm.trace:!Re.trace)||wa("BEGIN",e)},De=e=>{(typeof Re.trace>"u"?!Re.wasm.trace:!Re.trace)||wa("END",e)}});var Sr,va=R(()=>{"use strict";wr();$r();qn();Sr=class e{constructor(t){this.handler=t}async run(t,r,n){Ue();let o={},i={};if(typeof t!="object"||t===null||t instanceof Oe||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Oe)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let p of r){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);o[p]=null}if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,m=Object.getOwnPropertyNames(r);for(let u of this.outputNames)if(m.indexOf(u)!==-1){let h=r[u];(h===null||h instanceof Oe)&&(p=!0,a=!1,o[u]=h)}if(p){if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else i=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of this.inputNames)if(typeof t[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(a)for(let p of this.outputNames)o[p]=null;let l=await this.handler.run(t,o,i),d={};for(let p in l)if(Object.hasOwnProperty.call(l,p)){let m=l[p];m instanceof Oe?d[p]=m:d[p]=new Oe(m.type,m.data,m.dims)}return De(),d}async release(){return this.handler.dispose()}static async create(t,r,n,o){Ue();let i,a={};if(typeof t=="string"){if(i=t,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(i=t,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let m=t,u=0,h=t.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(u=r,!Number.isSafeInteger(u))throw new RangeError("'byteOffset' must be an integer.");if(u<0||u>=m.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${m.byteLength}).`);if(h=t.byteLength-u,typeof n=="number"){if(h=n,!Number.isSafeInteger(h))throw new RangeError("'byteLength' must be an integer.");if(h<=0||u+h>m.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${m.byteLength-u}].`);if(typeof o=="object"&&o!==null)a=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");i=new Uint8Array(m,u,h)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[l,d]=await _r(a),p=await l.createInferenceSessionHandler(i,d);return De(),new e(p)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}});var Np,$a=R(()=>{"use strict";va();Np=Sr});var xa=R(()=>{"use strict"});var Sa=R(()=>{"use strict"});var Ta=R(()=>{"use strict"});var Ia=R(()=>{"use strict"});var Vp,Tr,Ca=R(()=>{"use strict";wr();$r();Vp="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Tr=class e{constructor(t,r,n){this.handler=t,this.hasOptimizerModel=r,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(t,r){let n=t.evalModel||"",o=t.optimizerModel||"",i=r||{},[a,l]=await _r(i);if(a.createTrainingSessionHandler){let d=await a.createTrainingSessionHandler(t.checkpointState,t.trainModel,n,o,l);return new e(d,!!t.optimizerModel,!!t.evalModel)}else throw new Error(Vp)}typeNarrowingForRunStep(t,r,n,o,i){let a={},l={};if(typeof n!="object"||n===null||n instanceof Oe||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let d=!0;if(typeof o=="object"){if(o===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(o instanceof Oe)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(o)){if(o.length===0)throw new TypeError("'fetches' cannot be an empty array.");d=!1;for(let p of o){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);a[p]=null}if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,m=Object.getOwnPropertyNames(o);for(let u of r)if(m.indexOf(u)!==-1){let h=o[u];(h===null||h instanceof Oe)&&(p=!0,d=!1,a[u]=h)}if(p){if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else l=o}}else if(typeof o<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of t)if(typeof n[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(d)for(let p of r)a[p]=null;return[a,l]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let n in t)if(Object.hasOwnProperty.call(t,n)){let o=t[n];o instanceof Oe?r[n]=o:r[n]=new Oe(o.type,o.data,o.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,n){let[o,i]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,n),a=await this.handler.runTrainStep(t,o,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}async runOptimizerStep(t){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(t||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(t,r,n){if(this.hasEvalModel){let[o,i]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,n),a=await this.handler.runEvalStep(t,o,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(t=!0){return this.handler.getParametersSize(t)}async loadParametersBuffer(t,r=!0){let n=await this.getParametersSize(r);if(t.length!==4*n)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(t,r)}async getContiguousParameters(t=!0){return this.handler.getContiguousParameters(t)}async release(){return this.handler.dispose()}}});var Wp,Aa=R(()=>{"use strict";Ca();Wp=Tr});var jn={};Ft(jn,{InferenceSession:()=>Np,TRACE:()=>xr,TRACE_FUNC_BEGIN:()=>Ue,TRACE_FUNC_END:()=>De,Tensor:()=>Oe,TrainingSession:()=>Wp,env:()=>we,registerBackend:()=>xt});var We=R(()=>{"use strict";ea();oa();$a();$r();xa();Sa();qn();Ta();Ia();Aa()});var Ir=R(()=>{"use strict"});var za={};Ft(za,{default:()=>Lp});var Ea,Pa,Lp,Oa=R(()=>{"use strict";Kn();ht();jt();Ea="ort-wasm-proxy-worker",Pa=globalThis.self?.name===Ea;Pa&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":Cr(r.wasm).then(()=>{Ar(r).then(()=>{postMessage({type:t})},n=>{postMessage({type:t,err:n})})},n=>{postMessage({type:t,err:n})});break;case"init-ep":{let{epName:n,env:o}=r;kr(o,n).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case"copy-from":{let{buffer:n}=r,o=Kt(n);postMessage({type:t,out:o});break}case"create":{let{model:n,options:o}=r;Er(n,o).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case"release":Pr(r),postMessage({type:t});break;case"run":{let{sessionId:n,inputIndices:o,inputs:i,outputIndices:a,options:l}=r;zr(n,o,i,a,new Array(a.length).fill(null),l).then(d=>{d.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:d},Br([...i,...d]))},d=>{postMessage({type:t,err:d})});break}case"end-profiling":Or(r),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}});Lp=Pa?null:e=>new Worker(e??Dt,{type:"module",name:Ea})});var Da={};Ft(Da,{default:()=>Gp});var Yn,Ba,Gp,Ma=R(()=>{"use strict";Ba=(Yn=import.meta.url,async function(e={}){function t(){return se.buffer!=ee.buffer&&be(),ee}function r(){return se.buffer!=ee.buffer&&be(),ne}function n(){return se.buffer!=ee.buffer&&be(),ve}function o(){return se.buffer!=ee.buffer&&be(),Be}function i(){return se.buffer!=ee.buffer&&be(),$e}function a(){return se.buffer!=ee.buffer&&be(),de}function l(){return se.buffer!=ee.buffer&&be(),V}function d(){return se.buffer!=ee.buffer&&be(),Ge}var p,m,u=Object.assign({},e),h=new Promise((s,c)=>{p=s,m=c}),_=typeof window=="object",y=typeof importScripts=="function",g=y&&self.name=="em-pthread";u.mountExternalData=(s,c)=>{s.startsWith("./")&&(s=s.substring(2)),(u.Eb||(u.Eb=new Map)).set(s,c)},u.unmountExternalData=()=>{delete u.Eb};var x=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let $=()=>{let s=(f,b,w)=>(...I)=>{let B=Qe,D=b?.();I=f(...I);let L=b?.();return D!==L&&(f=L,w(D),b=w=null),Qe!=B?new Promise((H,Q)=>{Bn={resolve:H,reject:Q}}):I},c=f=>async(...b)=>{try{if(u.Fb)throw Error("Session already started");let w=u.Fb={fc:b[0],errors:[]},I=await f(...b);if(u.Fb!==w)throw Error("Session mismatch");u.Gb?.flush();let B=w.errors;if(0L),0u._OrtCreateSession,f=>u._OrtCreateSession=f),u._OrtRun=c(s(u._OrtRun,()=>u._OrtRun,f=>u._OrtRun=f)),u._OrtRunWithBinding=c(s(u._OrtRunWithBinding,()=>u._OrtRunWithBinding,f=>u._OrtRunWithBinding=f)),u._OrtBindInput=s(u._OrtBindInput,()=>u._OrtBindInput,f=>u._OrtBindInput=f),$=void 0};u.jsepInit=(s,c)=>{if($?.(),s==="webgpu"){[u.Gb,u.Ub,u.Yb,u.Nb,u.Xb,u.jb,u.Zb,u.bc,u.Vb,u.Wb,u.$b]=c;let f=u.Gb;u.jsepRegisterBuffer=(b,w,I,B)=>f.registerBuffer(b,w,I,B),u.jsepGetBuffer=b=>f.getBuffer(b),u.jsepCreateDownloader=(b,w,I)=>f.createDownloader(b,w,I),u.jsepOnCreateSession=b=>{f.onCreateSession(b)},u.jsepOnReleaseSession=b=>{f.onReleaseSession(b)},u.jsepOnRunStart=b=>f.onRunStart(b),u.cc=(b,w)=>{f.upload(b,w)}}else if(s==="webnn"){[u.Gb,u.ac,u.Ob,u.jsepEnsureTensor,u.dc,u.jsepDownloadTensor]=c,u.jsepReleaseTensorId=u.Ob;let f=u.Gb;u.jsepOnRunStart=b=>f.onRunStart(b),u.jsepRegisterMLContext=(b,w)=>{f.registerMLContext(b,w)},u.jsepOnReleaseSession=b=>{f.onReleaseSession(b)},u.jsepCreateMLTensorDownloader=(b,w)=>f.createMLTensorDownloader(b,w),u.jsepRegisterMLTensor=(b,w,I)=>f.registerMLTensor(b,w,I),u.jsepCreateMLContext=b=>f.createMLContext(b),u.jsepRegisterMLConstant=(b,w,I,B,D)=>f.registerMLConstant(b,w,I,B,D,u.Eb)}};var v,S,T=Object.assign({},u),C="./this.program",A=(s,c)=>{throw c},P="";(_||y)&&(y?P=self.location.href:typeof document<"u"&&document.currentScript&&(P=document.currentScript.src),Yn&&(P=Yn),P=P.startsWith("blob:")?"":P.substr(0,P.replace(/[?#].*/,"").lastIndexOf("/")+1),y&&(S=s=>{var c=new XMLHttpRequest;return c.open("GET",s,!1),c.responseType="arraybuffer",c.send(null),new Uint8Array(c.response)}),v=(s,c,f)=>{var b=new XMLHttpRequest;b.open("GET",s,!0),b.responseType="arraybuffer",b.onload=()=>{b.status==200||b.status==0&&b.response?c(b.response):f()},b.onerror=f,b.send(null)});var O,U=console.log.bind(console),G=console.error.bind(console),q=U,K=G;if(Object.assign(u,T),T=null,g){let s=function(c){try{var f=c.data,b=f.cmd;if(b==="load"){let w=[];self.onmessage=I=>w.push(I),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let I of w)s(I);self.onmessage=s};for(let I of f.handlers)u[I]&&!u[I].proxy||(u[I]=(...B)=>{postMessage({Mb:"callHandler",oc:I,args:B})},I=="print"&&(q=u[I]),I=="printErr"&&(K=u[I]));se=f.wasmMemory,be(),W(f.wasmModule)}else if(b==="run"){Un(f.pthread_ptr,0,0,1,0,0),Pn(f.pthread_ptr),yc(),Fo(),Y||(Li(),Y=!0);try{_c(f.start_routine,f.arg)}catch(w){if(w!="unwind")throw w}}else b==="cancel"?Bt()&&hr(-1):f.target!=="setimmediate"&&(b==="checkMailbox"?Y&&ar():b&&(K(`worker: received unknown command ${b}`),K(f)))}catch(w){throw Gi(),w}};var hg=s,W,Y=!1;K=function(...c){c=c.join(" "),console.error(c)},self.alert=function(...c){postMessage({Mb:"alert",text:c.join(" "),qc:Bt()})},u.instantiateWasm=(c,f)=>new Promise(b=>{W=w=>{w=new WebAssembly.Instance(w,Vo()),f(w),b()}}),self.onunhandledrejection=c=>{throw c.reason||c},self.onmessage=s}u.wasmBinary&&(O=u.wasmBinary);var se,X,re,ee,ne,ve,Be,$e,de,V,j,he,Ge,_e=!1;function be(){var s=se.buffer;u.HEAP8=ee=new Int8Array(s),u.HEAP16=ve=new Int16Array(s),u.HEAPU8=ne=new Uint8Array(s),u.HEAPU16=Be=new Uint16Array(s),u.HEAP32=$e=new Int32Array(s),u.HEAPU32=de=new Uint32Array(s),u.HEAPF32=V=new Float32Array(s),u.HEAPF64=Ge=new Float64Array(s),u.HEAP64=j=new BigInt64Array(s),u.HEAPU64=he=new BigUint64Array(s)}if(!g){if(!((se=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof x))throw K("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),Error("bad memory");be()}var Ke=[],Lt=[],bn=[],Gt=0,yn=null,Ht=null;function Do(){if(--Gt==0&&(yn!==null&&(clearInterval(yn),yn=null),Ht)){var s=Ht;Ht=null,s()}}function dt(s){throw K(s="Aborted("+s+")"),_e=!0,re=1,s=new WebAssembly.RuntimeError(s+". Build with -sASSERTIONS for more info."),m(s),s}var _n,Mo=s=>s.startsWith("data:application/octet-stream;base64,"),Ro=s=>s.startsWith("file://");function Uo(s){if(s==_n&&O)return new Uint8Array(O);if(S)return S(s);throw"both async and sync fetching of the wasm failed"}function No(s,c,f){return function(b){if(!O&&(_||y)){if(typeof fetch=="function"&&!Ro(b))return fetch(b,{credentials:"same-origin"}).then(w=>{if(!w.ok)throw`failed to load wasm binary file at '${b}'`;return w.arrayBuffer()}).catch(()=>Uo(b));if(v)return new Promise((w,I)=>{v(b,B=>w(new Uint8Array(B)),I)})}return Promise.resolve().then(()=>Uo(b))}(s).then(b=>WebAssembly.instantiate(b,c)).then(f,b=>{K(`failed to asynchronously prepare wasm: ${b}`),dt(b)})}function Vo(){return{a:{O:bc,Aa:gc,b:vc,aa:Yo,B:Xo,qa:Jo,Y:ti,_:ri,ra:ni,oa:oi,ha:ii,na:ai,L:si,Z:ui,W:li,pa:di,X:ci,wa:$c,F:Sc,Q:Tc,P:Cc,E:kc,u:Ec,q:Pc,G:zc,A:Nc,R:Vc,ua:Wc,ka:Lc,U:Gc,ba:Hc,H:Fc,ja:Pn,ta:qc,t:jc,x:Zc,o:Qc,m:Jc,c:kn,n:ep,k:np,w:op,p:ip,f:ap,s:sp,l:up,e:lp,j:dp,i:cp,h:pp,d:mp,ea:fp,fa:hp,ga:gp,ca:Ti,da:Ii,T:bp,g:yp,D:_p,I:wp,M:vp,y:$p,sa:xp,V:Sp,v:Ai,z:Tp,N:Ip,S:Cp,za:Ap,ya:kp,la:Pi,ma:zi,$:Sn,C:Oi,K:Bi,ia:Di,J:Mi,a:se,xa:xn,va:Ni,r:zp}}}var wn={873844:(s,c,f,b,w)=>{if(u===void 0||!u.Eb)return 1;if((s=Te(Number(s>>>0))).startsWith("./")&&(s=s.substring(2)),!(s=u.Eb.get(s)))return 2;if(c=Number(c>>>0),f=Number(f>>>0),b=Number(b>>>0),c+f>s.byteLength)return 3;try{let I=s.subarray(c,c+f);switch(w){case 0:r().set(I,b>>>0);break;case 1:u.cc(b,I);break;default:return 4}return 0}catch{return 4}},874559:(s,c,f)=>{u.dc(s,r().subarray(c>>>0,c+f>>>0))},874622:()=>u.ac(),874663:s=>{u.Ob(s)},874699:()=>{u.Vb()},874730:()=>{u.Wb()},874759:()=>{u.$b()},874784:s=>u.Ub(s),874817:s=>u.Yb(s),874849:(s,c,f)=>{u.Nb(Number(s),Number(c),Number(f),!0)},874912:(s,c,f)=>{u.Nb(Number(s),Number(c),Number(f))},874969:()=>typeof wasmOffsetConverter<"u",875026:s=>{u.jb("Abs",s,void 0)},875077:s=>{u.jb("Neg",s,void 0)},875128:s=>{u.jb("Floor",s,void 0)},875181:s=>{u.jb("Ceil",s,void 0)},875233:s=>{u.jb("Reciprocal",s,void 0)},875291:s=>{u.jb("Sqrt",s,void 0)},875343:s=>{u.jb("Exp",s,void 0)},875394:s=>{u.jb("Erf",s,void 0)},875445:s=>{u.jb("Sigmoid",s,void 0)},875500:(s,c,f)=>{u.jb("HardSigmoid",s,{alpha:c,beta:f})},875579:s=>{u.jb("Log",s,void 0)},875630:s=>{u.jb("Sin",s,void 0)},875681:s=>{u.jb("Cos",s,void 0)},875732:s=>{u.jb("Tan",s,void 0)},875783:s=>{u.jb("Asin",s,void 0)},875835:s=>{u.jb("Acos",s,void 0)},875887:s=>{u.jb("Atan",s,void 0)},875939:s=>{u.jb("Sinh",s,void 0)},875991:s=>{u.jb("Cosh",s,void 0)},876043:s=>{u.jb("Asinh",s,void 0)},876096:s=>{u.jb("Acosh",s,void 0)},876149:s=>{u.jb("Atanh",s,void 0)},876202:s=>{u.jb("Tanh",s,void 0)},876254:s=>{u.jb("Not",s,void 0)},876305:(s,c,f)=>{u.jb("Clip",s,{min:c,max:f})},876374:s=>{u.jb("Clip",s,void 0)},876426:(s,c)=>{u.jb("Elu",s,{alpha:c})},876484:s=>{u.jb("Gelu",s,void 0)},876536:s=>{u.jb("Relu",s,void 0)},876588:(s,c)=>{u.jb("LeakyRelu",s,{alpha:c})},876652:(s,c)=>{u.jb("ThresholdedRelu",s,{alpha:c})},876722:(s,c)=>{u.jb("Cast",s,{to:c})},876780:s=>{u.jb("Add",s,void 0)},876831:s=>{u.jb("Sub",s,void 0)},876882:s=>{u.jb("Mul",s,void 0)},876933:s=>{u.jb("Div",s,void 0)},876984:s=>{u.jb("Pow",s,void 0)},877035:s=>{u.jb("Equal",s,void 0)},877088:s=>{u.jb("Greater",s,void 0)},877143:s=>{u.jb("GreaterOrEqual",s,void 0)},877205:s=>{u.jb("Less",s,void 0)},877257:s=>{u.jb("LessOrEqual",s,void 0)},877316:(s,c,f,b,w)=>{u.jb("ReduceMean",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},877491:(s,c,f,b,w)=>{u.jb("ReduceMax",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},877665:(s,c,f,b,w)=>{u.jb("ReduceMin",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},877839:(s,c,f,b,w)=>{u.jb("ReduceProd",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},878014:(s,c,f,b,w)=>{u.jb("ReduceSum",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},878188:(s,c,f,b,w)=>{u.jb("ReduceL1",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},878361:(s,c,f,b,w)=>{u.jb("ReduceL2",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},878534:(s,c,f,b,w)=>{u.jb("ReduceLogSum",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},878711:(s,c,f,b,w)=>{u.jb("ReduceSumSquare",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},878891:(s,c,f,b,w)=>{u.jb("ReduceLogSumExp",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},879071:s=>{u.jb("Where",s,void 0)},879124:(s,c,f)=>{u.jb("Transpose",s,{perm:c?Array.from(i().subarray(Number(c)>>>0,Number(f)>>>0)):[]})},879248:(s,c,f,b)=>{u.jb("DepthToSpace",s,{blocksize:c,mode:Te(f),format:b?"NHWC":"NCHW"})},879381:(s,c,f,b)=>{u.jb("DepthToSpace",s,{blocksize:c,mode:Te(f),format:b?"NHWC":"NCHW"})},879514:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z,le)=>{u.jb("ConvTranspose",s,{format:L?"NHWC":"NCHW",autoPad:c,dilations:[f],group:b,kernelShape:[w],pads:[I,B],strides:[D],wIsConst:()=>!!t()[H>>>0],outputPadding:Q?Array.from(i().subarray(Number(Q)>>>0,Number(ce)>>>0)):[],outputShape:ge?Array.from(i().subarray(Number(ge)>>>0,Number(z)>>>0)):[],activation:Te(le)})},879947:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z)=>{u.jb("ConvTranspose",s,{format:D?"NHWC":"NCHW",autoPad:c,dilations:Array.from(i().subarray(Number(f)>>>0,2+(Number(f)>>>0)>>>0)),group:b,kernelShape:Array.from(i().subarray(Number(w)>>>0,2+(Number(w)>>>0)>>>0)),pads:Array.from(i().subarray(Number(I)>>>0,4+(Number(I)>>>0)>>>0)),strides:Array.from(i().subarray(Number(B)>>>0,2+(Number(B)>>>0)>>>0)),wIsConst:()=>!!t()[L>>>0],outputPadding:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],outputShape:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[],activation:Te(z)})},880608:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z,le)=>{u.jb("ConvTranspose",s,{format:L?"NHWC":"NCHW",autoPad:c,dilations:[f],group:b,kernelShape:[w],pads:[I,B],strides:[D],wIsConst:()=>!!t()[H>>>0],outputPadding:Q?Array.from(i().subarray(Number(Q)>>>0,Number(ce)>>>0)):[],outputShape:ge?Array.from(i().subarray(Number(ge)>>>0,Number(z)>>>0)):[],activation:Te(le)})},881041:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z)=>{u.jb("ConvTranspose",s,{format:D?"NHWC":"NCHW",autoPad:c,dilations:Array.from(i().subarray(Number(f)>>>0,2+(Number(f)>>>0)>>>0)),group:b,kernelShape:Array.from(i().subarray(Number(w)>>>0,2+(Number(w)>>>0)>>>0)),pads:Array.from(i().subarray(Number(I)>>>0,4+(Number(I)>>>0)>>>0)),strides:Array.from(i().subarray(Number(B)>>>0,2+(Number(B)>>>0)>>>0)),wIsConst:()=>!!t()[L>>>0],outputPadding:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],outputShape:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[],activation:Te(z)})},881702:(s,c)=>{u.jb("GlobalAveragePool",s,{format:c?"NHWC":"NCHW"})},881793:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z)=>{u.jb("AveragePool",s,{format:z?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:b,storage_order:w,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(B)>>>0)):[],kernel_shape:D?Array.from(i().subarray(Number(D)>>>0,Number(L)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},882272:(s,c)=>{u.jb("GlobalAveragePool",s,{format:c?"NHWC":"NCHW"})},882363:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z)=>{u.jb("AveragePool",s,{format:z?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:b,storage_order:w,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(B)>>>0)):[],kernel_shape:D?Array.from(i().subarray(Number(D)>>>0,Number(L)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},882842:(s,c)=>{u.jb("GlobalMaxPool",s,{format:c?"NHWC":"NCHW"})},882929:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z)=>{u.jb("MaxPool",s,{format:z?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:b,storage_order:w,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(B)>>>0)):[],kernel_shape:D?Array.from(i().subarray(Number(D)>>>0,Number(L)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},883404:(s,c)=>{u.jb("GlobalMaxPool",s,{format:c?"NHWC":"NCHW"})},883491:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z)=>{u.jb("MaxPool",s,{format:z?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:b,storage_order:w,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(B)>>>0)):[],kernel_shape:D?Array.from(i().subarray(Number(D)>>>0,Number(L)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},883966:(s,c,f,b,w)=>{u.jb("Gemm",s,{alpha:c,beta:f,transA:b,transB:w})},884070:s=>{u.jb("MatMul",s,void 0)},884124:(s,c,f,b)=>{u.jb("ArgMax",s,{keepDims:!!c,selectLastIndex:!!f,axis:b})},884232:(s,c,f,b)=>{u.jb("ArgMin",s,{keepDims:!!c,selectLastIndex:!!f,axis:b})},884340:(s,c)=>{u.jb("Softmax",s,{axis:c})},884403:(s,c)=>{u.jb("Concat",s,{axis:c})},884463:(s,c,f,b,w)=>{u.jb("Split",s,{axis:c,numOutputs:f,splitSizes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},884619:s=>{u.jb("Expand",s,void 0)},884673:(s,c)=>{u.jb("Gather",s,{axis:Number(c)})},884744:(s,c)=>{u.jb("GatherElements",s,{axis:Number(c)})},884823:(s,c,f,b,w,I,B,D,L,H,Q)=>{u.jb("Resize",s,{antialias:c,axes:f?Array.from(i().subarray(Number(f)>>>0,Number(b)>>>0)):[],coordinateTransformMode:Te(w),cubicCoeffA:I,excludeOutside:B,extrapolationValue:D,keepAspectRatioPolicy:Te(L),mode:Te(H),nearestMode:Te(Q)})},885185:(s,c,f,b,w,I,B)=>{u.jb("Slice",s,{starts:c?Array.from(i().subarray(Number(c)>>>0,Number(f)>>>0)):[],ends:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[],axes:I?Array.from(i().subarray(Number(I)>>>0,Number(B)>>>0)):[]})},885449:s=>{u.jb("Tile",s,void 0)},885501:(s,c,f)=>{u.jb("InstanceNormalization",s,{epsilon:c,format:f?"NHWC":"NCHW"})},885615:(s,c,f)=>{u.jb("InstanceNormalization",s,{epsilon:c,format:f?"NHWC":"NCHW"})},885729:s=>{u.jb("Range",s,void 0)},885782:(s,c)=>{u.jb("Einsum",s,{equation:Te(c)})},885863:(s,c,f,b,w)=>{u.jb("Pad",s,{mode:c,value:f,pads:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},886006:(s,c,f,b,w,I)=>{u.jb("BatchNormalization",s,{epsilon:c,momentum:f,spatial:!!w,trainingMode:!!b,format:I?"NHWC":"NCHW"})},886175:(s,c,f,b,w,I)=>{u.jb("BatchNormalization",s,{epsilon:c,momentum:f,spatial:!!w,trainingMode:!!b,format:I?"NHWC":"NCHW"})},886344:(s,c,f)=>{u.jb("CumSum",s,{exclusive:Number(c),reverse:Number(f)})},886441:(s,c,f)=>{u.jb("DequantizeLinear",s,{axis:c,blockSize:f})},886531:(s,c,f,b,w)=>{u.jb("GridSample",s,{align_corners:c,mode:Te(f),padding_mode:Te(b),format:w?"NHWC":"NCHW"})},886701:(s,c,f,b,w)=>{u.jb("GridSample",s,{align_corners:c,mode:Te(f),padding_mode:Te(b),format:w?"NHWC":"NCHW"})},886871:(s,c)=>{u.jb("ScatterND",s,{reduction:Te(c)})},886956:(s,c,f,b,w,I,B,D,L)=>{u.jb("Attention",s,{numHeads:c,isUnidirectional:f,maskFilterValue:b,scale:w,doRotary:I,qkvHiddenSizes:B?Array.from(i().subarray(Number(D)>>>0,Number(D)+B>>>0)):[],pastPresentShareBuffer:!!L})},887228:s=>{u.jb("BiasAdd",s,void 0)},887283:s=>{u.jb("BiasSplitGelu",s,void 0)},887344:s=>{u.jb("FastGelu",s,void 0)},887400:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z,le,Ie)=>{u.jb("Conv",s,{format:ce?"NHWC":"NCHW",auto_pad:c,dilations:f?Array.from(i().subarray(Number(f)>>>0,Number(b)>>>0)):[],group:w,kernel_shape:I?Array.from(i().subarray(Number(I)>>>0,Number(B)>>>0)):[],pads:D?Array.from(i().subarray(Number(D)>>>0,Number(L)>>>0)):[],strides:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],w_is_const:()=>!!t()[Number(ge)>>>0],activation:Te(z),activation_params:le?Array.from(l().subarray(Number(le)>>>0,Number(Ie)>>>0)):[]})},887984:s=>{u.jb("Gelu",s,void 0)},888036:(s,c,f,b,w,I,B,D,L)=>{u.jb("GroupQueryAttention",s,{numHeads:c,kvNumHeads:f,scale:b,softcap:w,doRotary:I,rotaryInterleaved:B,smoothSoftmax:D,localWindowSize:L})},888253:(s,c,f,b)=>{u.jb("LayerNormalization",s,{axis:c,epsilon:f,simplified:!!b})},888364:(s,c,f,b)=>{u.jb("LayerNormalization",s,{axis:c,epsilon:f,simplified:!!b})},888475:(s,c,f,b,w,I)=>{u.jb("MatMulNBits",s,{k:c,n:f,accuracyLevel:b,bits:w,blockSize:I})},888602:(s,c,f,b,w,I)=>{u.jb("MultiHeadAttention",s,{numHeads:c,isUnidirectional:f,maskFilterValue:b,scale:w,doRotary:I})},888761:(s,c)=>{u.jb("QuickGelu",s,{alpha:c})},888825:(s,c,f,b,w)=>{u.jb("RotaryEmbedding",s,{interleaved:!!c,numHeads:f,rotaryEmbeddingDim:b,scale:w})},888964:(s,c,f)=>{u.jb("SkipLayerNormalization",s,{epsilon:c,simplified:!!f})},889066:(s,c,f)=>{u.jb("SkipLayerNormalization",s,{epsilon:c,simplified:!!f})},889168:(s,c,f,b)=>{u.jb("GatherBlockQuantized",s,{gatherAxis:c,quantizeAxis:f,blockSize:b})},889289:s=>{u.Zb(s)},889323:(s,c)=>u.bc(Number(s),Number(c),u.Fb.fc,u.Fb.errors)};function gc(s,c,f){return wi(async()=>{await u.Xb(Number(s),Number(c),Number(f))})}function bc(){return typeof wasmOffsetConverter<"u"}function vn(s){this.name="ExitStatus",this.message=`Program terminated with exit(${s})`,this.status=s}var $n=s=>{s.terminate(),s.onmessage=()=>{}},Wo=s=>{ct.length==0&&(jo(),qo(ct[0]));var c=ct.pop();if(!c)return 6;wt.push(c),Ye[s.Ab]=c,c.Ab=s.Ab;var f={cmd:"run",start_routine:s.hc,arg:s.Qb,pthread_ptr:s.Ab};return c.postMessage(f,s.mc),0},_t=0,xe=(s,c,...f)=>{for(var b=2*f.length,w=Wn(),I=Vn(8*b),B=I>>>3,D=0;D>>0]=L)}return s=Hi(s,0,b,I,c),gr(w),s};function xn(s){if(g)return xe(0,1,s);if(re=s,!(0<_t)){for(var c of wt)$n(c);for(c of ct)$n(c);ct=[],wt=[],Ye=[],_e=!0}A(s,new vn(s))}function Lo(s){if(g)return xe(1,0,s);Sn(s)}var Sn=s=>{if(re=s,g)throw Lo(s),"unwind";xn(s)},ct=[],wt=[],Go=[],Ye={},Ho=s=>{var c=s.Ab;delete Ye[c],ct.push(s),wt.splice(wt.indexOf(s),1),s.Ab=0,Nn(c)};function Fo(){Go.forEach(s=>s())}var qo=s=>new Promise(c=>{s.onmessage=w=>{var I=(w=w.data).cmd;if(w.targetThread&&w.targetThread!=Bt()){var B=Ye[w.targetThread];B?B.postMessage(w,w.transferList):K(`Internal error! Worker sent a message "${I}" to target pthread ${w.targetThread}, but that thread no longer exists!`)}else I==="checkMailbox"?ar():I==="spawnThread"?Wo(w):I==="cleanupThread"?Ho(Ye[w.thread]):I==="killThread"?(w=w.thread,I=Ye[w],delete Ye[w],$n(I),Nn(w),wt.splice(wt.indexOf(I),1),I.Ab=0):I==="cancelThread"?Ye[w.thread].postMessage({cmd:"cancel"}):I==="loaded"?(s.loaded=!0,c(s)):I==="alert"?alert(`Thread ${w.threadId}: ${w.text}`):w.target==="setimmediate"?s.postMessage(w):I==="callHandler"?u[w.handler](...w.args):I&&K(`worker sent an unknown command ${I}`)},s.onerror=w=>{throw K(`worker sent an error! ${w.filename}:${w.lineno}: ${w.message}`),w};var f,b=[];for(f of[])u.hasOwnProperty(f)&&b.push(f);s.postMessage({cmd:"load",handlers:b,wasmMemory:se,wasmModule:X})});function jo(){var s=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});ct.push(s)}var ir=s=>{for(;0{var s=Bt(),c=a()[s+52>>>2>>>0];s=a()[s+56>>>2>>>0],qi(c,c-s),gr(c)},_c=(s,c)=>{_t=0,s=ji(s,c),0<_t?re=s:hr(s)};class wc{constructor(c){this.Jb=c-24}}function vc(s,c,f){var b=new wc(s>>>=0);throw c>>>=0,f>>>=0,a()[b.Jb+16>>>2>>>0]=0,a()[b.Jb+4>>>2>>>0]=c,a()[b.Jb+8>>>2>>>0]=f,s}function Ko(s,c,f,b){return g?xe(2,1,s,c,f,b):Yo(s,c,f,b)}function Yo(s,c,f,b){if(s>>>=0,c>>>=0,f>>>=0,b>>>=0,x===void 0)return K("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var w=[];return g&&w.length===0?Ko(s,c,f,b):(s={hc:f,Ab:s,Qb:b,mc:w},g?(s.Mb="spawnThread",postMessage(s,w),0):Wo(s))}var Zo=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Qo=(s,c,f)=>{var b=(c>>>=0)+f;for(f=c;s[f]&&!(f>=b);)++f;if(16(w=(240&w)==224?(15&w)<<12|I<<6|B:(7&w)<<18|I<<12|B<<6|63&s[c++])?b+=String.fromCharCode(w):(w-=65536,b+=String.fromCharCode(55296|w>>10,56320|1023&w))}}else b+=String.fromCharCode(w)}return b},Te=(s,c)=>(s>>>=0)?Qo(r(),s,c):"";function Xo(s,c,f){return g?xe(3,1,s,c,f):0}function Jo(s,c){if(g)return xe(4,1,s,c)}var Tn=s=>{for(var c=0,f=0;f=b?c++:2047>=b?c+=2:55296<=b&&57343>=b?(c+=4,++f):c+=3}return c},ei=(s,c,f,b)=>{if(!(0>>=0;b=f+b-1;for(var I=0;I=B&&(B=65536+((1023&B)<<10)|1023&s.charCodeAt(++I)),127>=B){if(f>=b)break;c[f++>>>0]=B}else{if(2047>=B){if(f+1>=b)break;c[f++>>>0]=192|B>>6}else{if(65535>=B){if(f+2>=b)break;c[f++>>>0]=224|B>>12}else{if(f+3>=b)break;c[f++>>>0]=240|B>>18,c[f++>>>0]=128|B>>12&63}c[f++>>>0]=128|B>>6&63}c[f++>>>0]=128|63&B}}return c[f>>>0]=0,f-w},Pt=(s,c,f)=>ei(s,r(),c,f);function ti(s,c){if(g)return xe(5,1,s,c)}function ri(s,c,f){if(g)return xe(6,1,s,c,f)}function ni(s,c,f){return g?xe(7,1,s,c,f):0}function oi(s,c){if(g)return xe(8,1,s,c)}function ii(s,c,f){if(g)return xe(9,1,s,c,f)}function ai(s,c,f,b){if(g)return xe(10,1,s,c,f,b)}function si(s,c,f,b){if(g)return xe(11,1,s,c,f,b)}function ui(s,c,f,b){if(g)return xe(12,1,s,c,f,b)}function li(s){if(g)return xe(13,1,s)}function di(s,c){if(g)return xe(14,1,s,c)}function ci(s,c,f){if(g)return xe(15,1,s,c,f)}var pi,pt,$c=()=>{dt("")},Ze=s=>{for(var c="";r()[s>>>0];)c+=pi[r()[s++>>>0]];return c},In={},Cn={},xc={};function at(s,c,f={}){if(!("argPackAdvance"in c))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(b,w,I={}){var B=w.name;if(!b)throw new pt(`type "${B}" must have a positive integer typeid pointer`);if(Cn.hasOwnProperty(b)){if(I.Sb)return;throw new pt(`Cannot register type '${B}' twice`)}Cn[b]=w,delete xc[b],In.hasOwnProperty(b)&&(w=In[b],delete In[b],w.forEach(D=>D()))}(s,c,f)}var mi=(s,c,f)=>{switch(c){case 1:return f?b=>t()[b>>>0]:b=>r()[b>>>0];case 2:return f?b=>n()[b>>>1>>>0]:b=>o()[b>>>1>>>0];case 4:return f?b=>i()[b>>>2>>>0]:b=>a()[b>>>2>>>0];case 8:return f?b=>j[b>>>3]:b=>he[b>>>3];default:throw new TypeError(`invalid integer width (${c}): ${s}`)}};function Sc(s,c,f){f>>>=0,at(s>>>=0,{name:c=Ze(c>>>0),fromWireType:b=>b,toWireType:function(b,w){if(typeof w!="bigint"&&typeof w!="number")throw w=w===null?"null":(b=typeof w)=="object"||b==="array"||b==="function"?w.toString():""+w,new TypeError(`Cannot convert "${w}" to ${this.name}`);return typeof w=="number"&&(w=BigInt(w)),w},argPackAdvance:mt,readValueFromPointer:mi(c,f,c.indexOf("u")==-1),Db:null})}var mt=8;function Tc(s,c,f,b){at(s>>>=0,{name:c=Ze(c>>>0),fromWireType:function(w){return!!w},toWireType:function(w,I){return I?f:b},argPackAdvance:mt,readValueFromPointer:function(w){return this.fromWireType(r()[w>>>0])},Db:null})}var An=[],st=[];function kn(s){9<(s>>>=0)&&--st[s+1]==0&&(st[s]=void 0,An.push(s))}var Ne=s=>{if(!s)throw new pt("Cannot use deleted val. handle = "+s);return st[s]},Ve=s=>{switch(s){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let c=An.pop()||st.length;return st[c]=s,st[c+1]=1,c}};function En(s){return this.fromWireType(a()[s>>>2>>>0])}var Ic={name:"emscripten::val",fromWireType:s=>{var c=Ne(s);return kn(s),c},toWireType:(s,c)=>Ve(c),argPackAdvance:mt,readValueFromPointer:En,Db:null};function Cc(s){return at(s>>>0,Ic)}var Ac=(s,c)=>{switch(c){case 4:return function(f){return this.fromWireType(l()[f>>>2>>>0])};case 8:return function(f){return this.fromWireType(d()[f>>>3>>>0])};default:throw new TypeError(`invalid float width (${c}): ${s}`)}};function kc(s,c,f){f>>>=0,at(s>>>=0,{name:c=Ze(c>>>0),fromWireType:b=>b,toWireType:(b,w)=>w,argPackAdvance:mt,readValueFromPointer:Ac(c,f),Db:null})}function Ec(s,c,f,b,w){if(s>>>=0,f>>>=0,c=Ze(c>>>0),w===-1&&(w=4294967295),w=D=>D,b===0){var I=32-8*f;w=D=>D<>>I}var B=c.includes("unsigned")?function(D,L){return L>>>0}:function(D,L){return L};at(s,{name:c,fromWireType:w,toWireType:B,argPackAdvance:mt,readValueFromPointer:mi(c,f,b!==0),Db:null})}function Pc(s,c,f){function b(I){var B=a()[I>>>2>>>0];return I=a()[I+4>>>2>>>0],new w(t().buffer,I,B)}var w=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][c];at(s>>>=0,{name:f=Ze(f>>>0),fromWireType:b,argPackAdvance:mt,readValueFromPointer:b},{Sb:!0})}function zc(s,c){s>>>=0;var f=(c=Ze(c>>>0))==="std::string";at(s,{name:c,fromWireType:function(b){var w=a()[b>>>2>>>0],I=b+4;if(f)for(var B=I,D=0;D<=w;++D){var L=I+D;if(D==w||r()[L>>>0]==0){if(B=Te(B,L-B),H===void 0)var H=B;else H+=String.fromCharCode(0),H+=B;B=L+1}}else{for(H=Array(w),D=0;D>>0]);H=H.join("")}return Xe(b),H},toWireType:function(b,w){w instanceof ArrayBuffer&&(w=new Uint8Array(w));var I=typeof w=="string";if(!(I||w instanceof Uint8Array||w instanceof Uint8ClampedArray||w instanceof Int8Array))throw new pt("Cannot pass non-string to std::string");var B=f&&I?Tn(w):w.length,D=fr(4+B+1),L=D+4;if(a()[D>>>2>>>0]=B,f&&I)Pt(w,L,B+1);else if(I)for(I=0;I>>0]=H}else for(I=0;I>>0]=w[I];return b!==null&&b.push(Xe,D),D},argPackAdvance:mt,readValueFromPointer:En,Db(b){Xe(b)}})}var fi=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Oc=(s,c)=>{for(var f=s>>1,b=f+c/2;!(f>=b)&&o()[f>>>0];)++f;if(32<(f<<=1)-s&&fi)return fi.decode(r().slice(s,f));for(f="",b=0;!(b>=c/2);++b){var w=n()[s+2*b>>>1>>>0];if(w==0)break;f+=String.fromCharCode(w)}return f},Bc=(s,c,f)=>{if(f??=2147483647,2>f)return 0;var b=c;f=(f-=2)<2*s.length?f/2:s.length;for(var w=0;w>>1>>>0]=I,c+=2}return n()[c>>>1>>>0]=0,c-b},Dc=s=>2*s.length,Mc=(s,c)=>{for(var f=0,b="";!(f>=c/4);){var w=i()[s+4*f>>>2>>>0];if(w==0)break;++f,65536<=w?(w-=65536,b+=String.fromCharCode(55296|w>>10,56320|1023&w)):b+=String.fromCharCode(w)}return b},Rc=(s,c,f)=>{if(c>>>=0,f??=2147483647,4>f)return 0;var b=c;f=b+f-4;for(var w=0;w=I&&(I=65536+((1023&I)<<10)|1023&s.charCodeAt(++w)),i()[c>>>2>>>0]=I,(c+=4)+4>f)break}return i()[c>>>2>>>0]=0,c-b},Uc=s=>{for(var c=0,f=0;f=b&&++f,c+=4}return c};function Nc(s,c,f){if(s>>>=0,c>>>=0,f=Ze(f>>>=0),c===2)var b=Oc,w=Bc,I=Dc,B=D=>o()[D>>>1>>>0];else c===4&&(b=Mc,w=Rc,I=Uc,B=D=>a()[D>>>2>>>0]);at(s,{name:f,fromWireType:D=>{for(var L,H=a()[D>>>2>>>0],Q=D+4,ce=0;ce<=H;++ce){var ge=D+4+ce*c;ce!=H&&B(ge)!=0||(Q=b(Q,ge-Q),L===void 0?L=Q:(L+=String.fromCharCode(0),L+=Q),Q=ge+c)}return Xe(D),L},toWireType:(D,L)=>{if(typeof L!="string")throw new pt(`Cannot pass non-string to C++ string type ${f}`);var H=I(L),Q=fr(4+H+c);return a()[Q>>>2>>>0]=H/c,w(L,Q+4,H+c),D!==null&&D.push(Xe,Q),Q},argPackAdvance:mt,readValueFromPointer:En,Db(D){Xe(D)}})}function Vc(s,c){at(s>>>=0,{Tb:!0,name:c=Ze(c>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Wc=()=>1;function Lc(s){Un(s>>>0,!y,1,!_,131072,!1),Fo()}var hi=s=>{if(!_e)try{if(s(),!(0<_t))try{g?hr(re):Sn(re)}catch(c){c instanceof vn||c=="unwind"||A(1,c)}}catch(c){c instanceof vn||c=="unwind"||A(1,c)}};function Pn(s){s>>>=0,typeof Atomics.nc=="function"&&(Atomics.nc(i(),s>>>2,s).value.then(ar),s+=128,Atomics.store(i(),s>>>2,1))}var ar=()=>{var s=Bt();s&&(Pn(s),hi(Fi))};function Gc(s,c){(s>>>=0)==c>>>0?setTimeout(ar):g?postMessage({targetThread:s,cmd:"checkMailbox"}):(s=Ye[s])&&s.postMessage({cmd:"checkMailbox"})}var zn=[];function Hc(s,c,f,b,w){for(c>>>=0,b/=2,zn.length=b,f=w>>>0>>>3,w=0;w>>0];return(c?wn[c]:Op[s])(...zn)}function Fc(s){s>>>=0,g?postMessage({cmd:"cleanupThread",thread:s}):Ho(Ye[s])}function qc(s){}var On=(s,c)=>{var f=Cn[s];if(f===void 0)throw s=Wi(s),f=Ze(s),Xe(s),new pt(`${c} has unknown type ${f}`);return f},gi=(s,c,f)=>{var b=[];return s=s.toWireType(b,f),b.length&&(a()[c>>>2>>>0]=Ve(b)),s};function jc(s,c,f){return c>>>=0,f>>>=0,s=Ne(s>>>0),c=On(c,"emval::as"),gi(c,f,s)}var sr=s=>{try{s()}catch(c){dt(c)}},ft=0,Qe=null,bi=0,ur=[],yi={},_i={},Kc=0,Bn=null,Yc=[];function wi(s){return function(c){if(!_e){if(ft===0){var f=!1,b=!1;c((w=0)=>{if(!_e&&(bi=w,f=!0,b)){ft=2,sr(()=>Zi(Qe)),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.resume(),w=!1;try{var I=function(){var L=i()[Qe+8>>>2>>>0];return L=Z[_i[L]],--_t,L()}()}catch(L){I=L,w=!0}var B=!1;if(!Qe){var D=Bn;D&&(Bn=null,(w?D.reject:D.resolve)(I),B=!0)}if(w&&!B)throw I}}),b=!0,f||(ft=1,Qe=function(){var w=fr(65548),I=w+12;a()[w>>>2>>>0]=I,a()[w+4>>>2>>>0]=I+65536,I=ur[0];var B=yi[I];return B===void 0&&(B=Kc++,yi[I]=B,_i[B]=I),I=B,i()[w+8>>>2>>>0]=I,w}(),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.pause(),sr(()=>Ki(Qe)))}else ft===2?(ft=0,sr(Qi),Xe(Qe),Qe=null,Yc.forEach(hi)):dt(`invalid state: ${ft}`);return bi}}(c=>{s().then(c)})}function Zc(s){return s>>>=0,wi(()=>(s=Ne(s)).then(Ve))}var lr=[];function Qc(s,c,f,b){return f>>>=0,b>>>=0,(s=lr[s>>>0])(null,c=Ne(c>>>0),f,b)}var Xc={},dr=s=>{var c=Xc[s];return c===void 0?Ze(s):c};function Jc(s,c,f,b,w){return f>>>=0,b>>>=0,w>>>=0,(s=lr[s>>>0])(c=Ne(c>>>0),c[f=dr(f)],b,w)}var vi=()=>typeof globalThis=="object"?globalThis:Function("return this")();function ep(s){return(s>>>=0)==0?Ve(vi()):(s=dr(s),Ve(vi()[s]))}var tp=s=>{var c=lr.length;return lr.push(s),c},rp=(s,c)=>{for(var f=Array(s),b=0;b>>2>>>0],"parameter "+b);return f},$i=(s,c)=>Object.defineProperty(c,"name",{value:s});function np(s,c,f){var b=(c=rp(s,c>>>0)).shift();s--;var w=`return function (obj, func, destructorsRef, args) { +`,I=0,B=[];f===0&&B.push("obj");for(var D=["retType"],L=[b],H=0;HQ.name).join(", ")}) => ${b.name}>`,tp($i(f,s))}function op(s){return s=dr(s>>>0),Ve(u[s])}function ip(s,c){return c>>>=0,s=Ne(s>>>0),c=Ne(c),Ve(s[c])}function ap(s){9<(s>>>=0)&&(st[s+1]+=1)}function sp(){return Ve([])}function up(s){s=Ne(s>>>0);for(var c=Array(s.length),f=0;f>>0))}function dp(){return Ve({})}function cp(s){for(var c=Ne(s>>>=0);c.length;){var f=c.pop();c.pop()(f)}kn(s)}function pp(s,c,f){c>>>=0,f>>>=0,s=Ne(s>>>0),c=Ne(c),f=Ne(f),s[c]=f}function mp(s,c){return c>>>=0,s=(s=On(s>>>0,"_emval_take_value")).readValueFromPointer(c),Ve(s)}function fp(s,c){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),i()[c>>>2>>>0]=s.getUTCSeconds(),i()[c+4>>>2>>>0]=s.getUTCMinutes(),i()[c+8>>>2>>>0]=s.getUTCHours(),i()[c+12>>>2>>>0]=s.getUTCDate(),i()[c+16>>>2>>>0]=s.getUTCMonth(),i()[c+20>>>2>>>0]=s.getUTCFullYear()-1900,i()[c+24>>>2>>>0]=s.getUTCDay(),s=(s.getTime()-Date.UTC(s.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[c+28>>>2>>>0]=s}var zt=s=>s%4==0&&(s%100!=0||s%400==0),xi=[0,31,60,91,121,152,182,213,244,274,305,335],Si=[0,31,59,90,120,151,181,212,243,273,304,334];function hp(s,c){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),i()[c>>>2>>>0]=s.getSeconds(),i()[c+4>>>2>>>0]=s.getMinutes(),i()[c+8>>>2>>>0]=s.getHours(),i()[c+12>>>2>>>0]=s.getDate(),i()[c+16>>>2>>>0]=s.getMonth(),i()[c+20>>>2>>>0]=s.getFullYear()-1900,i()[c+24>>>2>>>0]=s.getDay();var f=(zt(s.getFullYear())?xi:Si)[s.getMonth()]+s.getDate()-1|0;i()[c+28>>>2>>>0]=f,i()[c+36>>>2>>>0]=-60*s.getTimezoneOffset(),f=new Date(s.getFullYear(),6,1).getTimezoneOffset();var b=new Date(s.getFullYear(),0,1).getTimezoneOffset();s=0|(f!=b&&s.getTimezoneOffset()==Math.min(b,f)),i()[c+32>>>2>>>0]=s}function gp(s){s>>>=0;var c=new Date(i()[s+20>>>2>>>0]+1900,i()[s+16>>>2>>>0],i()[s+12>>>2>>>0],i()[s+8>>>2>>>0],i()[s+4>>>2>>>0],i()[s>>>2>>>0],0),f=i()[s+32>>>2>>>0],b=c.getTimezoneOffset(),w=new Date(c.getFullYear(),6,1).getTimezoneOffset(),I=new Date(c.getFullYear(),0,1).getTimezoneOffset(),B=Math.min(I,w);return 0>f?i()[s+32>>>2>>>0]=+(w!=I&&B==b):0>>2>>>0]=c.getDay(),f=(zt(c.getFullYear())?xi:Si)[c.getMonth()]+c.getDate()-1|0,i()[s+28>>>2>>>0]=f,i()[s>>>2>>>0]=c.getSeconds(),i()[s+4>>>2>>>0]=c.getMinutes(),i()[s+8>>>2>>>0]=c.getHours(),i()[s+12>>>2>>>0]=c.getDate(),i()[s+16>>>2>>>0]=c.getMonth(),i()[s+20>>>2>>>0]=c.getYear(),s=c.getTime(),BigInt(isNaN(s)?-1:s/1e3)}function Ti(s,c,f,b,w,I,B){return g?xe(16,1,s,c,f,b,w,I,B):-52}function Ii(s,c,f,b,w,I){if(g)return xe(17,1,s,c,f,b,w,I)}function bp(s,c,f,b){s>>>=0,c>>>=0,f>>>=0,b>>>=0;var w=new Date().getFullYear(),I=new Date(w,0,1),B=new Date(w,6,1);w=I.getTimezoneOffset();var D=B.getTimezoneOffset(),L=Math.max(w,D);a()[s>>>2>>>0]=60*L,i()[c>>>2>>>0]=+(w!=D),I=(s=H=>H.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(I),B=s(B),D{Dn.length=0;for(var f;f=r()[s++>>>0];){var b=f!=105;c+=(b&=f!=112)&&c%8?4:0,Dn.push(f==112?a()[c>>>2>>>0]:f==106?j[c>>>3]:f==105?i()[c>>>2>>>0]:d()[c>>>3>>>0]),c+=b?8:4}return Dn};function yp(s,c,f){return s>>>=0,c=Ci(c>>>0,f>>>0),wn[s](...c)}function _p(s,c,f){return s>>>=0,c=Ci(c>>>0,f>>>0),wn[s](...c)}var wp=()=>{},vp=()=>Date.now();function $p(s,c){return K(Te(s>>>0,c>>>0))}var Ai,xp=()=>{throw _t+=1,"unwind"};function Sp(){return 4294901760}Ai=()=>performance.timeOrigin+performance.now();var Tp=()=>navigator.hardwareConcurrency;function Ip(){return dt("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Cp(s){s>>>=0;var c=r().length;if(s<=c||4294901760=f;f*=2){var b=c*(1+.2/f);b=Math.min(b,s+100663296);var w=Math;b=Math.max(s,b);e:{w=(w.min.call(w,4294901760,b+(65536-b%65536)%65536)-se.buffer.byteLength+65535)/65536;try{se.grow(w),be();var I=1;break e}catch{}I=void 0}if(I)return!0}return!1}var cr=()=>(dt("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Ot={},ki=s=>{s.forEach(c=>{var f=cr();f&&(Ot[f]=c)})};function Ap(){var s=Error().stack.toString().split(` +`);return s[0]=="Error"&&s.shift(),ki(s),Ot.Pb=cr(),Ot.ec=s,Ot.Pb}function kp(s,c,f){if(s>>>=0,c>>>=0,Ot.Pb==s)var b=Ot.ec;else(b=Error().stack.toString().split(` +`))[0]=="Error"&&b.shift(),ki(b);for(var w=3;b[w]&&cr()!=s;)++w;for(s=0;s>>2>>>0]=cr();return s}var Mn,Rn={},Ei=()=>{if(!Mn){var s,c={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:C||"./this.program"};for(s in Rn)Rn[s]===void 0?delete c[s]:c[s]=Rn[s];var f=[];for(s in c)f.push(`${s}=${c[s]}`);Mn=f}return Mn};function Pi(s,c){if(g)return xe(18,1,s,c);s>>>=0,c>>>=0;var f=0;return Ei().forEach((b,w)=>{var I=c+f;for(w=a()[s+4*w>>>2>>>0]=I,I=0;I>>0]=b.charCodeAt(I);t()[w>>>0]=0,f+=b.length+1}),0}function zi(s,c){if(g)return xe(19,1,s,c);s>>>=0,c>>>=0;var f=Ei();a()[s>>>2>>>0]=f.length;var b=0;return f.forEach(w=>b+=w.length+1),a()[c>>>2>>>0]=b,0}function Oi(s){return g?xe(20,1,s):52}function Bi(s,c,f,b){return g?xe(21,1,s,c,f,b):52}function Di(s,c,f,b){return g?xe(22,1,s,c,f,b):70}var Ep=[null,[],[]];function Mi(s,c,f,b){if(g)return xe(23,1,s,c,f,b);c>>>=0,f>>>=0,b>>>=0;for(var w=0,I=0;I>>2>>>0],D=a()[c+4>>>2>>>0];c+=8;for(var L=0;L>>0],Q=Ep[s];H===0||H===10?((s===1?q:K)(Qo(Q,0)),Q.length=0):Q.push(H)}w+=D}return a()[b>>>2>>>0]=w,0}var Ri=[31,29,31,30,31,30,31,31,30,31,30,31],Ui=[31,28,31,30,31,30,31,31,30,31,30,31],Pp=(s,c)=>{t().set(s,c>>>0)};function Ni(s,c,f,b){function w(z,le,Ie){for(z=typeof z=="number"?z.toString():z||"";z.lengthJi?-1:0vt-z.getDate())){z.setDate(z.getDate()+le);break}le-=vt-z.getDate()+1,z.setDate(1),11>Ie?z.setMonth(Ie+1):(z.setMonth(0),z.setFullYear(z.getFullYear()+1))}return Ie=new Date(z.getFullYear()+1,0,4),le=D(new Date(z.getFullYear(),0,4)),Ie=D(Ie),0>=B(le,z)?0>=B(Ie,z)?z.getFullYear()+1:z.getFullYear():z.getFullYear()-1}s>>>=0,c>>>=0,f>>>=0,b>>>=0;var H=a()[b+40>>>2>>>0];for(var Q in b={kc:i()[b>>>2>>>0],jc:i()[b+4>>>2>>>0],Hb:i()[b+8>>>2>>>0],Lb:i()[b+12>>>2>>>0],Ib:i()[b+16>>>2>>>0],Cb:i()[b+20>>>2>>>0],ub:i()[b+24>>>2>>>0],Bb:i()[b+28>>>2>>>0],rc:i()[b+32>>>2>>>0],ic:i()[b+36>>>2>>>0],lc:H?Te(H):""},f=Te(f),H={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})f=f.replace(new RegExp(Q,"g"),H[Q]);var ce="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),ge="January February March April May June July August September October November December".split(" ");for(Q in H={"%a":z=>ce[z.ub].substring(0,3),"%A":z=>ce[z.ub],"%b":z=>ge[z.Ib].substring(0,3),"%B":z=>ge[z.Ib],"%C":z=>I((z.Cb+1900)/100|0,2),"%d":z=>I(z.Lb,2),"%e":z=>w(z.Lb,2," "),"%g":z=>L(z).toString().substring(2),"%G":L,"%H":z=>I(z.Hb,2),"%I":z=>((z=z.Hb)==0?z=12:12{for(var le=0,Ie=0;Ie<=z.Ib-1;le+=(zt(z.Cb+1900)?Ri:Ui)[Ie++]);return I(z.Lb+le,3)},"%m":z=>I(z.Ib+1,2),"%M":z=>I(z.jc,2),"%n":()=>` +`,"%p":z=>0<=z.Hb&&12>z.Hb?"AM":"PM","%S":z=>I(z.kc,2),"%t":()=>" ","%u":z=>z.ub||7,"%U":z=>I(Math.floor((z.Bb+7-z.ub)/7),2),"%V":z=>{var le=Math.floor((z.Bb+7-(z.ub+6)%7)/7);if(2>=(z.ub+371-z.Bb-2)%7&&le++,le)le==53&&((Ie=(z.ub+371-z.Bb)%7)==4||Ie==3&&zt(z.Cb)||(le=1));else{le=52;var Ie=(z.ub+7-z.Bb-1)%7;(Ie==4||Ie==5&&zt(z.Cb%400-1))&&le++}return I(le,2)},"%w":z=>z.ub,"%W":z=>I(Math.floor((z.Bb+7-(z.ub+6)%7)/7),2),"%y":z=>(z.Cb+1900).toString().substring(2),"%Y":z=>z.Cb+1900,"%z":z=>{var le=0<=(z=z.ic);return z=Math.abs(z)/60,(le?"+":"-")+("0000"+(z/60*100+z%60)).slice(-4)},"%Z":z=>z.lc,"%%":()=>"%"},f=f.replace(/%%/g,"\0\0"),H)f.includes(Q)&&(f=f.replace(new RegExp(Q,"g"),H[Q](b)));return Q=function(z){var le=Array(Tn(z)+1);return ei(z,le,0,le.length),le}(f=f.replace(/\0\0/g,"%")),Q.length>c?0:(Pp(Q,s),Q.length-1)}function zp(s,c,f,b){return Ni(s>>>0,c>>>0,f>>>0,b>>>0)}g||function(){for(var s=u.numThreads-1;s--;)jo();Ke.unshift(()=>{Gt++,function(c){g?c():Promise.all(ct.map(qo)).then(c)}(()=>Do())})}();for(var Vi=Array(256),pr=0;256>pr;++pr)Vi[pr]=String.fromCharCode(pr);pi=Vi,pt=u.BindingError=class extends Error{constructor(s){super(s),this.name="BindingError"}},u.InternalError=class extends Error{constructor(s){super(s),this.name="InternalError"}},st.push(0,1,void 0,1,null,1,!0,1,!1,1),u.count_emval_handles=()=>st.length/2-5-An.length;var Op=[xn,Lo,Ko,Xo,Jo,ti,ri,ni,oi,ii,ai,si,ui,li,di,ci,Ti,Ii,Pi,zi,Oi,Bi,Di,Mi],Z=function(){function s(f,b){return Z=f.exports,Z=function(){var w=Z,I={};for(let[B,D]of Object.entries(w))I[B]=typeof D=="function"?(...L)=>{ur.push(B);try{return D(...L)}finally{_e||(ur.pop(),Qe&&ft===1&&ur.length===0&&(ft=0,_t+=1,sr(Yi),typeof Fibers<"u"&&Fibers.sc()))}}:D;return I}(),Z=function(){var w=Z,I=D=>L=>D(L)>>>0,B=D=>()=>D()>>>0;return(w=Object.assign({},w)).Ca=I(w.Ca),w.fb=B(w.fb),w.hb=I(w.hb),w.emscripten_main_runtime_thread_id=B(w.emscripten_main_runtime_thread_id),w.sb=I(w.sb),w.tb=B(w.tb),w}(),Go.push(Z.ib),Lt.unshift(Z.Ba),X=b,Do(),Z}var c=Vo();if(Gt++,u.instantiateWasm)try{return u.instantiateWasm(c,s)}catch(f){K(`Module.instantiateWasm callback failed with error: ${f}`),m(f)}return _n||=u.locateFile?Mo("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":u.locateFile?u.locateFile("ort-wasm-simd-threaded.jsep.wasm",P):P+"ort-wasm-simd-threaded.jsep.wasm":new URL(/* asset import */ __webpack_require__(/*! ort-wasm-simd-threaded.jsep.wasm */ "./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"), __webpack_require__.b).href,function(f,b){var w=_n;return O||typeof WebAssembly.instantiateStreaming!="function"||Mo(w)||Ro(w)||typeof fetch!="function"?No(w,f,b):fetch(w,{credentials:"same-origin"}).then(I=>WebAssembly.instantiateStreaming(I,f).then(b,function(B){return K(`wasm streaming compile failed: ${B}`),K("falling back to ArrayBuffer instantiation"),No(w,f,b)}))}(c,function(f){s(f.instance,f.module)}).catch(m),{}}(),Wi=s=>(Wi=Z.Ca)(s),Li=()=>(Li=Z.Da)();u._OrtInit=(s,c)=>(u._OrtInit=Z.Ea)(s,c),u._OrtGetLastError=(s,c)=>(u._OrtGetLastError=Z.Fa)(s,c),u._OrtCreateSessionOptions=(s,c,f,b,w,I,B,D,L,H)=>(u._OrtCreateSessionOptions=Z.Ga)(s,c,f,b,w,I,B,D,L,H),u._OrtAppendExecutionProvider=(s,c)=>(u._OrtAppendExecutionProvider=Z.Ha)(s,c),u._OrtAddFreeDimensionOverride=(s,c,f)=>(u._OrtAddFreeDimensionOverride=Z.Ia)(s,c,f),u._OrtAddSessionConfigEntry=(s,c,f)=>(u._OrtAddSessionConfigEntry=Z.Ja)(s,c,f),u._OrtReleaseSessionOptions=s=>(u._OrtReleaseSessionOptions=Z.Ka)(s),u._OrtCreateSession=(s,c,f)=>(u._OrtCreateSession=Z.La)(s,c,f),u._OrtReleaseSession=s=>(u._OrtReleaseSession=Z.Ma)(s),u._OrtGetInputOutputCount=(s,c,f)=>(u._OrtGetInputOutputCount=Z.Na)(s,c,f),u._OrtGetInputName=(s,c)=>(u._OrtGetInputName=Z.Oa)(s,c),u._OrtGetOutputName=(s,c)=>(u._OrtGetOutputName=Z.Pa)(s,c),u._OrtFree=s=>(u._OrtFree=Z.Qa)(s),u._OrtCreateTensor=(s,c,f,b,w,I)=>(u._OrtCreateTensor=Z.Ra)(s,c,f,b,w,I),u._OrtGetTensorData=(s,c,f,b,w)=>(u._OrtGetTensorData=Z.Sa)(s,c,f,b,w),u._OrtReleaseTensor=s=>(u._OrtReleaseTensor=Z.Ta)(s),u._OrtCreateRunOptions=(s,c,f,b)=>(u._OrtCreateRunOptions=Z.Ua)(s,c,f,b),u._OrtAddRunConfigEntry=(s,c,f)=>(u._OrtAddRunConfigEntry=Z.Va)(s,c,f),u._OrtReleaseRunOptions=s=>(u._OrtReleaseRunOptions=Z.Wa)(s),u._OrtCreateBinding=s=>(u._OrtCreateBinding=Z.Xa)(s),u._OrtBindInput=(s,c,f)=>(u._OrtBindInput=Z.Ya)(s,c,f),u._OrtBindOutput=(s,c,f,b)=>(u._OrtBindOutput=Z.Za)(s,c,f,b),u._OrtClearBoundOutputs=s=>(u._OrtClearBoundOutputs=Z._a)(s),u._OrtReleaseBinding=s=>(u._OrtReleaseBinding=Z.$a)(s),u._OrtRunWithBinding=(s,c,f,b,w)=>(u._OrtRunWithBinding=Z.ab)(s,c,f,b,w),u._OrtRun=(s,c,f,b,w,I,B,D)=>(u._OrtRun=Z.bb)(s,c,f,b,w,I,B,D),u._OrtEndProfiling=s=>(u._OrtEndProfiling=Z.cb)(s),u._JsepOutput=(s,c,f)=>(u._JsepOutput=Z.db)(s,c,f),u._JsepGetNodeName=s=>(u._JsepGetNodeName=Z.eb)(s);var mr,Bt=()=>(Bt=Z.fb)(),Xe=u._free=s=>(Xe=u._free=Z.gb)(s),fr=u._malloc=s=>(fr=u._malloc=Z.hb)(s),Un=(s,c,f,b,w,I)=>(Un=Z.kb)(s,c,f,b,w,I),Gi=()=>(Gi=Z.lb)(),Hi=(s,c,f,b,w)=>(Hi=Z.mb)(s,c,f,b,w),Nn=s=>(Nn=Z.nb)(s),hr=s=>(hr=Z.ob)(s),Fi=()=>(Fi=Z.pb)(),qi=(s,c)=>(qi=Z.qb)(s,c),gr=s=>(gr=Z.rb)(s),Vn=s=>(Vn=Z.sb)(s),Wn=()=>(Wn=Z.tb)(),ji=u.dynCall_ii=(s,c)=>(ji=u.dynCall_ii=Z.vb)(s,c),Ki=s=>(Ki=Z.wb)(s),Yi=()=>(Yi=Z.xb)(),Zi=s=>(Zi=Z.yb)(s),Qi=()=>(Qi=Z.zb)();function Xi(){0Wn(),u.stackRestore=s=>gr(s),u.stackAlloc=s=>Vn(s),u.setValue=function(s,c,f="i8"){switch(f.endsWith("*")&&(f="*"),f){case"i1":case"i8":t()[s>>>0]=c;break;case"i16":n()[s>>>1>>>0]=c;break;case"i32":i()[s>>>2>>>0]=c;break;case"i64":j[s>>>3]=BigInt(c);break;case"float":l()[s>>>2>>>0]=c;break;case"double":d()[s>>>3>>>0]=c;break;case"*":a()[s>>>2>>>0]=c;break;default:dt(`invalid type for setValue: ${f}`)}},u.getValue=function(s,c="i8"){switch(c.endsWith("*")&&(c="*"),c){case"i1":case"i8":return t()[s>>>0];case"i16":return n()[s>>>1>>>0];case"i32":return i()[s>>>2>>>0];case"i64":return j[s>>>3];case"float":return l()[s>>>2>>>0];case"double":return d()[s>>>3>>>0];case"*":return a()[s>>>2>>>0];default:dt(`invalid type for getValue: ${c}`)}},u.UTF8ToString=Te,u.stringToUTF8=Pt,u.lengthBytesUTF8=Tn,Ht=function s(){mr||Xi(),mr||(Ht=s)},Xi(),u.PTR_SIZE=4,h}),Gp=Ba;globalThis.self?.name==="em-pthread"&&Ba()});var Dt,Hp,Fp,qp,Ra,Ua,jp,Na,jt=R(()=>{"use strict";Ir();Dt= false?0:import.meta.url??(typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0),Hp= false||typeof location>"u"?void 0:location.origin,Fp=(e,t)=>{try{let r=t??Dt;return(r?new URL(e,r):new URL(e)).origin===Hp}catch{return!1}},qp=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},Ra=(Oa(),br(za)).default,Ua=async()=>{if(!Dt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Fp(Dt))return[void 0,Ra()];let e=await qp(Dt);return[e,Ra(e)]},jp=(Ma(),br(Da)).default,Na=async(e,t,r)=>[void 0,jp]});var Zn,Qn,Dr,Va,Kp,Yp,Cr,Ce,ht=R(()=>{"use strict";jt();Qn=!1,Dr=!1,Va=!1,Kp=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Yp=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Cr=async e=>{if(Qn)return Promise.resolve();if(Dr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Va)throw new Error("previous call to 'initializeWebAssembly()' failed.");Dr=!0;let t=e.initTimeout,r=e.numThreads;if(!Yp())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=Kp();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let o=e.wasmPaths,i=typeof o=="string"?o:void 0,a=o?.mjs,l=a?.href??a,d=o?.wasm,p=d?.href??d,m=e.wasmBinary,[u,h]=await Na(l,i,r>1),_=!1,y=[];if(t>0&&y.push(new Promise(g=>{setTimeout(()=>{_=!0,g()},t)})),y.push(new Promise((g,x)=>{let $={numThreads:r};m?$.wasmBinary=m:(p||i)&&($.locateFile=(v,S)=>p??(i??S)+v),h($).then(v=>{Dr=!1,Qn=!0,Zn=v,g(),u&&URL.revokeObjectURL(u)},v=>{Dr=!1,Va=!0,x(v)})})),await Promise.race(y),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ce=()=>{if(Qn&&Zn)return Zn;throw new Error("WebAssembly is not initialized yet.")}});var Ae,Yt,pe,Mr=R(()=>{"use strict";ht();Ae=(e,t)=>{let r=Ce(),n=r.lengthBytesUTF8(e)+1,o=r._malloc(n);return r.stringToUTF8(e,o,n),t.push(o),o},Yt=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([o,i])=>{let a=t?t+o:o;if(typeof i=="object")Yt(i,a+".",r,n);else if(typeof i=="string"||typeof i=="number")n(a,i.toString());else if(typeof i=="boolean")n(a,i?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof i}`)})},pe=e=>{let t=Ce(),r=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetLastError(o,o+n);let i=Number(t.getValue(o,n===4?"i32":"i64")),a=t.getValue(o+n,"*"),l=a?t.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${l}`)}finally{t.stackRestore(r)}}});var Wa,La=R(()=>{"use strict";ht();Mr();Wa=e=>{let t=Ce(),r=0,n=[],o=e||{};try{if(e?.logSeverityLevel===void 0)o.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)o.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(o.terminate=!1);let i=0;return e?.tag!==void 0&&(i=Ae(e.tag,n)),r=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,i),r===0&&pe("Can't create run options."),e?.extra!==void 0&&Yt(e.extra,"",new WeakSet,(a,l)=>{let d=Ae(a,n),p=Ae(l,n);t._OrtAddRunConfigEntry(r,d,p)!==0&&pe(`Can't set a run config entry: ${a} - ${l}.`)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(a=>t._free(a)),i}}});var Zp,Qp,Xp,Jp,Ga,Ha=R(()=>{"use strict";ht();Mr();Zp=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},Qp=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Xp=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},Jp=(e,t,r)=>{for(let n of t){let o=typeof n=="string"?n:n.name;switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let l=n?.deviceType;if(l){let d=Ae("deviceType",r),p=Ae(l,r);Ce()._OrtAddSessionConfigEntry(e,d,p)!==0&&pe(`Can't set a session config entry: 'deviceType' - ${l}.`)}}break;case"webgpu":if(o="JS",typeof n!="string"){let a=n;if(a?.preferredLayout){if(a.preferredLayout!=="NCHW"&&a.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${a.preferredLayout}`);let l=Ae("preferredLayout",r),d=Ae(a.preferredLayout,r);Ce()._OrtAddSessionConfigEntry(e,l,d)!==0&&pe(`Can't set a session config entry: 'preferredLayout' - ${a.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=Ae(o,r);Ce()._OrtAppendExecutionProvider(e,i)!==0&&pe(`Can't append execution provider: ${o}.`)}},Ga=e=>{let t=Ce(),r=0,n=[],o=e||{};Xp(o);try{let i=Zp(o.graphOptimizationLevel??"all"),a=Qp(o.executionMode??"sequential"),l=typeof o.logId=="string"?Ae(o.logId,n):0,d=o.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let p=o.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let m=typeof o.optimizedModelFilePath=="string"?Ae(o.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(i,!!o.enableCpuMemArena,!!o.enableMemPattern,a,!!o.enableProfiling,0,l,d,p,m),r===0&&pe("Can't create session options."),o.executionProviders&&Jp(r,o.executionProviders,n),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);let u=Ae("enableGraphCapture",n),h=Ae(o.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,u,h)!==0&&pe(`Can't set a session config entry: 'enableGraphCapture' - ${o.enableGraphCapture}.`)}if(o.freeDimensionOverrides)for(let[u,h]of Object.entries(o.freeDimensionOverrides)){if(typeof u!="string")throw new Error(`free dimension override name must be a string: ${u}`);if(typeof h!="number"||!Number.isInteger(h)||h<0)throw new Error(`free dimension override value must be a non-negative integer: ${h}`);let _=Ae(u,n);t._OrtAddFreeDimensionOverride(r,_,h)!==0&&pe(`Can't set a free dimension override: ${u} - ${h}.`)}return o.extra!==void 0&&Yt(o.extra,"",new WeakSet,(u,h)=>{let _=Ae(u,n),y=Ae(h,n);t._OrtAddSessionConfigEntry(r,_,y)!==0&&pe(`Can't set a session config entry: ${u} - ${h}.`)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&pe("Can't release session options."),n.forEach(a=>t._free(a)),i}}});var Zt,gt,Tt,Rr,Qt,Ur,Nr,Xn,te=R(()=>{"use strict";Zt=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},gt=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},Tt=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((o,i)=>o*i,1);return r>0?Math.ceil(n*r):void 0},Rr=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Qt=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},Ur=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Nr=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Xn=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}});var Xt,Jn=R(()=>{"use strict";Ir();Xt=async e=>{if(typeof e=="string")if(false){}else{let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=t.body.getReader(),i;try{i=new ArrayBuffer(n)}catch(l){if(l instanceof RangeError){let d=Math.ceil(n/65536);i=new WebAssembly.Memory({initial:d,maximum:d}).buffer}else throw l}let a=0;for(;;){let{done:l,value:d}=await o.read();if(l)break;let p=d.byteLength;new Uint8Array(i,a,p).set(d),a+=p}return new Uint8Array(i,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}});var em,tm,Fa,qa,Vr,rm,ue,Je=R(()=>{"use strict";te();em=["V","I","W","E","F"],tm=(e,t)=>{console.log(`[${em[e]},${new Date().toISOString()}]${t}`)},Vr=(e,t)=>{Fa=e,qa=t},rm=(e,t)=>{let r=Qt(e),n=Qt(Fa);r>=n&&tm(r,typeof t=="function"?t():t)},ue=(...e)=>{qa&&rm(...e)}});var Wr,eo=R(()=>{"use strict";te();Wr=(e,t)=>new(Rr(t))(e)});var Lr=R(()=>{"use strict"});var ja,to,ro,nm,om,Ka,oo,no,Za,Qa=R(()=>{"use strict";Je();Lr();ja=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),to=[],ro=e=>Math.ceil(Number(e)/16)*16,nm=e=>{for(let t=0;tom++,oo=async(e,t,r,n)=>{let o=ro(r),i=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=e.getCommandEncoder();e.endComputePass(),a.copyBufferToBuffer(t,0,i,0,o),e.flush(),await i.mapAsync(GPUMapMode.READ);let l=i.getMappedRange();if(n){let d=n();return d.set(new Uint8Array(l,0,r)),d}else return new Uint8Array(l.slice(0,r))}finally{i.destroy()}},no=class{constructor(t){this.backend=t;this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[r]of ja)to.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(t,r){let n=r.buffer,o=r.byteOffset,i=r.byteLength,a=ro(i),l=this.storageCache.get(t);if(!l)throw new Error("gpu data for uploading does not exist");if(Number(l.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${l.originalSize}, data size=${i}`);let d=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=d.getMappedRange();new Uint8Array(p).set(new Uint8Array(n,o,i)),d.unmap();let m=this.backend.device.createCommandEncoder();m.copyBufferToBuffer(d,0,l.gpuData.buffer,0,a),this.backend.device.queue.submit([m.finish()]),d.destroy(),ue("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${t})`)}memcpy(t,r){let n=this.storageCache.get(t);if(!n)throw new Error("source gpu data for memcpy does not exist");let o=this.storageCache.get(r);if(!o)throw new Error("destination gpu data for memcpy does not exist");if(n.originalSize!==o.originalSize)throw new Error("inconsistent source and destination gpu data size");let i=ro(n.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(n.gpuData.buffer,0,o.gpuData.buffer,0,i)}registerExternalBuffer(t,r,n){let o;if(n){if(o=n[0],t===n[1])return ue("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, buffer is the same, skip.`),o;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. + Please use the previous external buffer!`)}else o=Ka();return this.storageCache.set(o,{gpuData:{id:o,type:0,buffer:t},originalSize:r}),ue("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, registered.`),o}unregisterExternalBuffer(t){t!==void 0&&(this.storageCache.delete(t),ue("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`))}create(t,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=nm(t),o,i=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let p=(i?this.freeBuffers:this.freeUniformBuffers).get(n);p?p.length>0?o=p.pop():o=this.backend.device.createBuffer({size:n,usage:r}):o=this.backend.device.createBuffer({size:n,usage:r})}else o=this.backend.device.createBuffer({size:n,usage:r});let l={id:Ka(),type:0,buffer:o};return this.storageCache.set(l.id,{gpuData:l,originalSize:Number(t)}),ue("verbose",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${l.id}`),l}get(t){return this.storageCache.get(t)?.gpuData}release(t){let r=typeof t=="bigint"?Number(t):t,n=this.storageCache.get(r);if(!n){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return ue("verbose",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${n.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(t,r){let n=this.storageCache.get(Number(t));if(!n)throw new Error("data does not exist");await oo(this.backend,n.gpuData.buffer,n.originalSize,r)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let t of this.buffersPending){let r=ja.get(t.size);if((t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(t.size)||[];r===void 0||n.length>=r?t.destroy():n.push(t)}else if((t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(t.size)||[];r===void 0||n.length>=r?t.destroy():n.push(t)}else t.destroy()}this.buffersPending=[]}else{let t=this.capturedPendingBuffers.get(this.backend.currentSessionId);t||(t=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,t));for(let r of this.buffersPending)t.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(t){let r=this.capturedPendingBuffers.get(t);r&&(r.forEach(n=>{n.destroy()}),this.capturedPendingBuffers.delete(t)),this.sessionCount-=1,this.sessionCount===0&&(ue("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(n=>{n.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Za=(...e)=>new no(...e)});var io,J,Se=R(()=>{"use strict";io=class{constructor(t){Object.assign(this,t)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(t=>`${this[t]}`).join(";")),this.key}},J=e=>new io(e)});var ao,et,k,It,Gr,Xa,Ja,oe=R(()=>{"use strict";ao=class{static calcMatMulShape(t,r){return t[1]!==r[0]?void 0:[t[0],r[1]]}},et=class{static calcShape(t,r,n=!1){let o=t.length,i=r.length;if(o===0)return r;if(i===0)return t;let a=Math.max(t.length,r.length),l=new Array(a);if(n){if(o<2||i<2)return;let d=ao.calcMatMulShape([t[o-2],t[o-1]],[r[i-2],r[i-1]]);if(d===void 0)return;[l[a-2],l[a-1]]=d}for(let d=n?3:1;d<=a;d++){let p=o-d<0?1:t[o-d],m=i-d<0?1:r[i-d];if(p!==m&&p>1&&m>1)return;let u=Math.max(p,m);if(p&&m)l[a-d]=Math.max(p,m);else{if(u>1)return;l[a-d]=0}}return l}static isValidBroadcast(t,r){let n=t.length,o=r.length;if(n>o)return!1;for(let i=1;i<=n;i++)if(t[n-i]!==1&&t[n-i]!==r[o-i])return!1;return!0}},k=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let o=new Array(n),i=n-1;for(;i>=0;){if(t[i]%r===0){o[i]=t[i]/r;break}if(r%t[i]!==0)throw new Error("cannot convert shape");o[i]=1,r/=t[i],i--}for(i--;i>=0;i--)o[i]=t[i];return o}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let o=1;for(let i=r;i=0;--o)n[o]=n[o+1]*t[o+1];return n}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(n=>this.normalizeAxis(n,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(n=>t[n]):t.slice().reverse()}static padShape(t,r){let n=t.length;return t.map((o,i)=>o+r[i]+r[i+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,o)=>n===r[o])}},It=class e{static adjustPoolAttributes(t,r,n,o,i,a){if(!t&&n.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let l=0;l=n.length?n.push(r[l+2]):n[l]=r[l+2];for(let l=0;l=n[l]||a[l+n.length]>=n[l])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,n,o,i,a,l){if(l){if(i.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(o.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let d=0;d{"use strict";te();oe();Ct=64,uo=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},ye=(e,t=1)=>{let r=uo(e,t);return typeof r=="string"?r:r[0]},ke=(e,t=1)=>{let r=uo(e,t);return typeof r=="string"?r:r[1]},N=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:k.computeStrides(r)})}),t},me=e=>e%4===0?4:e%2===0?2:1,lo=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,At=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,He=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,F=(e,t,r,n)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Hr=(e,t,r,n,o)=>{let i=typeof r=="number",a=i?r:r.length,l=[...new Array(a).keys()],d=a<2?"u32":a<=4?`vec${a}`:`array`,p=uo(t,o),m=typeof p=="string"?p:p[1],u=typeof p=="string"?p:p[0],h={indices:d,value:m,storage:u,tensor:t},_=V=>typeof V=="string"?V:`${V}u`,y={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},g=i?"uniforms.":"",x=`${g}${e}_shape`,$=`${g}${e}_strides`,v="";for(let V=0;V ${h.indices} { var indices: ${h.indices}; var current = offset; ${v} return indices; - }`,T=N=>(y.offsetToIndices=!0,a<2?N:`o2i_${e}(${N})`),C=[];if(a>=2)for(let N=a-1;N>=0;N--)C.push(`${F($,N,a)} * (indices[${N}])`);let A=a<2?"":` + }`,T=V=>(y.offsetToIndices=!0,a<2?V:`o2i_${e}(${V})`),C=[];if(a>=2)for(let V=a-1;V>=0;V--)C.push(`${F($,V,a)} * (indices[${V}])`);let A=a<2?"":` fn i2o_${e}(indices: ${h.indices}) -> u32 { return ${C.join("+")}; - }`,P=N=>(y.indicesToOffset=!0,a<2?N:`i2o_${e}(${N})`),O=(...N)=>a===0?"0u":`${h.indices}(${N.map(w).join(",")})`,U=(N,q)=>a<2?`${N}`:`${F(N,q,a)}`,L=(N,q,he)=>a<2?`${N}=${he};`:`${F(N,q,a)}=${he};`,j={},K=(N,q)=>{y.broadcastedIndicesToOffset=!0;let he=`${q.name}broadcastedIndicesTo${e}Offset`;if(he in j)return`${he}(${N})`;let qe=[];for(let _e=a-1;_e>=0;_e--){let be=q.indicesGet("outputIndices",_e+q.rank-a);qe.push(`${U($,_e)} * (${be} % ${U(x,_e)})`)}return j[he]=`fn ${he}(outputIndices: ${q.type.indices}) -> u32 { - return ${qe.length>0?qe.join("+"):"0u"}; - }`,`${he}(${N})`},W=(N,q)=>(()=>{if(h.storage===h.value)return`${e}[${N}]=${q};`;if(h.storage==="vec2"&&h.value==="i32")return`${e}[${N}]=vec2(u32(${q}), select(0u, 0xFFFFFFFFu, ${q} < 0));`;if(h.storage==="vec2"&&h.value==="u32")return`${e}[${N}]=vec2(u32(${q}), 0u);`;if(h.storage==="u32"&&h.value==="vec4")return`${e}[${N}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${q}));`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),ee=N=>(()=>{if(h.storage===h.value)return`${e}[${N}]`;if(h.storage==="vec2"&&h.value==="i32")return`i32(${e}[${N}].x)`;if(h.storage==="vec2"&&h.value==="u32")return`u32(${e}[${N}].x)`;if(h.storage==="u32"&&h.value==="vec4")return`vec4(bool(${e}[${N}] & 0xFFu), bool(${e}[${N}] & 0xFF00u), bool(${e}[${N}] & 0xFF0000u), bool(${e}[${N}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),ue=a<2?"":` + }`,P=V=>(y.indicesToOffset=!0,a<2?V:`i2o_${e}(${V})`),O=(...V)=>a===0?"0u":`${h.indices}(${V.map(_).join(",")})`,U=(V,j)=>a<2?`${V}`:`${F(V,j,a)}`,G=(V,j,he)=>a<2?`${V}=${he};`:`${F(V,j,a)}=${he};`,q={},K=(V,j)=>{y.broadcastedIndicesToOffset=!0;let he=`${j.name}broadcastedIndicesTo${e}Offset`;if(he in q)return`${he}(${V})`;let Ge=[];for(let _e=a-1;_e>=0;_e--){let be=j.indicesGet("outputIndices",_e+j.rank-a);Ge.push(`${U($,_e)} * (${be} % ${U(x,_e)})`)}return q[he]=`fn ${he}(outputIndices: ${j.type.indices}) -> u32 { + return ${Ge.length>0?Ge.join("+"):"0u"}; + }`,`${he}(${V})`},W=(V,j)=>(()=>{if(h.storage===h.value)return`${e}[${V}]=${j};`;if(h.storage==="vec2"&&h.value==="i32")return`${e}[${V}]=vec2(u32(${j}), select(0u, 0xFFFFFFFFu, ${j} < 0));`;if(h.storage==="vec2"&&h.value==="u32")return`${e}[${V}]=vec2(u32(${j}), 0u);`;if(h.storage==="u32"&&h.value==="vec4")return`${e}[${V}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${j}));`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),Y=V=>(()=>{if(h.storage===h.value)return`${e}[${V}]`;if(h.storage==="vec2"&&h.value==="i32")return`i32(${e}[${V}].x)`;if(h.storage==="vec2"&&h.value==="u32")return`u32(${e}[${V}].x)`;if(h.storage==="u32"&&h.value==="vec4")return`vec4(bool(${e}[${V}] & 0xFFu), bool(${e}[${V}] & 0xFF00u), bool(${e}[${V}] & 0xFF0000u), bool(${e}[${V}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),se=a<2?"":` fn get_${e}ByIndices(indices: ${h.indices}) -> ${m} { - return ${ee(`i2o_${e}(indices)`)}; - }`,Z=a<2?"":(()=>{let N=l.map(he=>`d${he}: u32`).join(", "),q=l.map(he=>`d${he}`).join(", ");return` - fn get_${e}(${N}) -> ${m} { - return get_${e}ByIndices(${O(q)}); - }`})(),J=(...N)=>{if(N.length!==a)throw new Error(`indices length must be ${a}`);let q=N.map(w).join(",");return a===0?ee("0u"):a===1?ee(q[0]):(y.get=!0,y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}(${q})`)},Q=N=>a<2?ee(N):(y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}ByIndices(${N})`),ne=a<2?"":` + return ${Y(`i2o_${e}(indices)`)}; + }`,X=a<2?"":(()=>{let V=l.map(he=>`d${he}: u32`).join(", "),j=l.map(he=>`d${he}`).join(", ");return` + fn get_${e}(${V}) -> ${m} { + return get_${e}ByIndices(${O(j)}); + }`})(),re=(...V)=>{if(V.length!==a)throw new Error(`indices length must be ${a}`);let j=V.map(_).join(",");return a===0?Y("0u"):a===1?Y(j[0]):(y.get=!0,y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}(${j})`)},ee=V=>a<2?Y(V):(y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}ByIndices(${V})`),ne=a<2?"":` fn set_${e}ByIndices(indices: ${h.indices}, value: ${m}) { ${W(`i2o_${e}(indices)`,"value")} - }`,we=a<2?"":(()=>{let N=l.map(he=>`d${he}: u32`).join(", "),q=l.map(he=>`d${he}`).join(", ");return` - fn set_${e}(${N}, value: ${m}) { - set_${e}ByIndices(${O(q)}, value); - }`})();return{impl:()=>{let N=[],q=!1;return y.offsetToIndices&&(N.push(S),q=!0),y.indicesToOffset&&(N.push(A),q=!0),y.broadcastedIndicesToOffset&&(Object.values(j).forEach(he=>N.push(he)),q=!0),y.set&&(N.push(we),q=!0),y.setByIndices&&(N.push(ne),q=!0),y.get&&(N.push(Z),q=!0),y.getByIndices&&(N.push(ue),q=!0),!i&&q&&N.unshift(`const ${x} = ${h.indices}(${r.join(",")});`,`const ${$} = ${h.indices}(${k.computeStrides(r).join(",")});`),N.join(` -`)},type:h,offsetToIndices:T,indicesToOffset:P,broadcastedIndicesToOffset:K,indices:O,indicesGet:U,indicesSet:L,set:(...N)=>{if(N.length!==a+1)throw new Error(`indices length must be ${a}`);let q=N[a];if(typeof q!="string")throw new Error("value must be string");let he=N.slice(0,a).map(w).join(",");return a===0?W("0u",q):a===1?W(he[0],q):(y.set=!0,y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}(${he}, ${q})`)},setByOffset:W,setByIndices:(N,q)=>a<2?W(N,q):(y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}ByIndices(${N}, ${q});`),get:J,getByOffset:ee,getByIndices:Q,usage:n,name:e,strides:$,shape:x,rank:a}},E=(e,t,r,n=1)=>fo(e,t,r,"input",n),M=(e,t,r,n=1)=>fo(e,t,r,"output",n),Kr=(e,t,r,n=1)=>fo(e,t,r,"internal",n),co=class{constructor(t,r){this.normalizedDispatchGroup=t;this.limits=r;this.internalVariables=[];this.variables=[];this.uniforms=[];this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t=="number"?`${t}u`:t}) { return; }`}mainStart(t=Ct){let r=typeof t=="number"?t:t[0],n=typeof t=="number"?1:t[1],o=typeof t=="number"?1:t[2];if(r>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||o>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*n*o>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=i?`@builtin(global_invocation_id) global_id : vec3, + }`,ve=a<2?"":(()=>{let V=l.map(he=>`d${he}: u32`).join(", "),j=l.map(he=>`d${he}`).join(", ");return` + fn set_${e}(${V}, value: ${m}) { + set_${e}ByIndices(${O(j)}, value); + }`})();return{impl:()=>{let V=[],j=!1;return y.offsetToIndices&&(V.push(S),j=!0),y.indicesToOffset&&(V.push(A),j=!0),y.broadcastedIndicesToOffset&&(Object.values(q).forEach(he=>V.push(he)),j=!0),y.set&&(V.push(ve),j=!0),y.setByIndices&&(V.push(ne),j=!0),y.get&&(V.push(X),j=!0),y.getByIndices&&(V.push(se),j=!0),!i&&j&&V.unshift(`const ${x} = ${h.indices}(${r.join(",")});`,`const ${$} = ${h.indices}(${k.computeStrides(r).join(",")});`),V.join(` +`)},type:h,offsetToIndices:T,indicesToOffset:P,broadcastedIndicesToOffset:K,indices:O,indicesGet:U,indicesSet:G,set:(...V)=>{if(V.length!==a+1)throw new Error(`indices length must be ${a}`);let j=V[a];if(typeof j!="string")throw new Error("value must be string");let he=V.slice(0,a).map(_).join(",");return a===0?W("0u",j):a===1?W(he[0],j):(y.set=!0,y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}(${he}, ${j})`)},setByOffset:W,setByIndices:(V,j)=>a<2?W(V,j):(y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}ByIndices(${V}, ${j});`),get:re,getByOffset:Y,getByIndices:ee,usage:n,name:e,strides:$,shape:x,rank:a}},E=(e,t,r,n=1)=>Hr(e,t,r,"input",n),M=(e,t,r,n=1)=>Hr(e,t,r,"output",n),es=(e,t,r)=>Hr(e,t,r,"atomicOutput",1),Fr=(e,t,r,n=1)=>Hr(e,t,r,"internal",n),so=class{constructor(t,r){this.normalizedDispatchGroup=t;this.limits=r;this.internalVariables=[];this.variables=[];this.uniforms=[];this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t=="number"?`${t}u`:t}) { return; }`}mainStart(t=Ct){let r=typeof t=="number"?t:t[0],n=typeof t=="number"?1:t[1],o=typeof t=="number"?1:t[2];if(r>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||o>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*n*o>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=i?`@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, @@ -3851,48 +3851,53 @@ var Fn=Object.defineProperty;var Pp=Object.getOwnPropertyDescriptor;var zp=Objec let global_idx = workgroup_index * ${r*n*o}u + local_idx;`;return`@compute @workgroup_size(${r}, ${n}, ${o}) fn main(${a}) { ${l} - `}appendVariableUniforms(t){t.rank!==0&&(t.shape.startsWith("uniforms.")&&this.uniforms.push({name:t.shape.replace("uniforms.",""),type:"u32",length:t.rank}),t.strides.startsWith("uniforms.")&&this.uniforms.push({name:t.strides.replace("uniforms.",""),type:"u32",length:t.rank}))}declareVariable(t,r){if(t.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(t),this.appendVariableUniforms(t);let n=t.usage==="input"?"read":"read_write",o=t.type.storage;return`@group(0) @binding(${r}) var ${t.name}: array<${o}>;`}declareVariables(...t){return t.map(r=>this.declareVariable(r,this.variableIndex++)).join(` + `}appendVariableUniforms(t){t.rank!==0&&(t.shape.startsWith("uniforms.")&&this.uniforms.push({name:t.shape.replace("uniforms.",""),type:"u32",length:t.rank}),t.strides.startsWith("uniforms.")&&this.uniforms.push({name:t.strides.replace("uniforms.",""),type:"u32",length:t.rank}))}declareVariable(t,r){if(t.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(t),this.appendVariableUniforms(t);let n=t.usage==="input"?"read":"read_write",o=t.usage==="atomicOutput"?"atomic":t.type.storage;return`@group(0) @binding(${r}) var ${t.name}: array<${o}>;`}declareVariables(...t){return t.map(r=>this.declareVariable(r,this.variableIndex++)).join(` `)}registerInternalVariable(t){if(t.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(t),this.appendVariableUniforms(t)}registerInternalVariables(...t){return t.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(t,r,n=1){return this.uniforms.push({name:t,type:r,length:n}),this}registerUniforms(t){return this.uniforms=this.uniforms.concat(t),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let t=[];for(let{name:r,type:n,length:o}of this.uniforms)if(o&&o>4)n==="f16"?t.push(`@align(16) ${r}:array, ${Math.ceil(o/8)}>`):t.push(`${r}:array, ${Math.ceil(o/4)}>`);else{let i=o==null||o===1?n:`vec${o}<${n}>`;t.push(`${r}:${i}`)}return` struct Uniforms { ${t.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(t=>t.impl()).join(` `)+this.internalVariables.map(t=>t.impl()).join(` -`)}get variablesInfo(){if(this.uniforms.length===0)return;let t=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[t(r.type),r.length??1])}},os=(e,t)=>new co(e,t)});var rm,is,nm,om,im,Pe,as,ss,ut=R(()=>{"use strict";te();oe();Ie();ae();rm=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},is=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,nm=(e,t)=>k.sortBasedOnPerm(e,is(e.length,t)),om=(e,t,r,n)=>{let o=`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { - var a: ${r.type.indices};`;for(let i=0;i{let r=[],n=[];for(let o=0;o{let r=e.dataType,n=e.dims.length,o=is(n,t),i=nm(e.dims,o),{newShape:a,newPerm:l}=im(e.dims,o),d=k.areEqual(l,[2,3,1]),c=k.areEqual(l,[3,1,2]),m=a.length===2&&l[0]>l[1]||d||c,u=m?a:e.dims,h=i;m&&(u=d?[a[0],a[1]*a[2]]:c?[a[0]*a[1],a[2]]:a,h=[u[1],u[0]]);let w=E("a",r,u.length),y=M("output",r,h.length),g=16,x;return m?x=$=>` - ${$.registerUniform("output_size","u32").declareVariables(w,y)} - var tile : array, ${g}>; - ${$.mainStart([g,g,1])} +`)}get variablesInfo(){if(this.uniforms.length===0)return;let t=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[t(r.type),r.length??1])}},ts=(e,t)=>new so(e,t)});var im,rs,am,sm,um,lm,Ee,ns,os,ut=R(()=>{"use strict";te();oe();Se();ae();im=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},rs=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,am=(e,t)=>k.sortBasedOnPerm(e,rs(e.length,t)),sm=(e,t,r,n)=>{let o=`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`;for(let i=0;i{let r=[],n=[];for(let o=0;o{let r=0;for(let n=0;n{let r=e.dataType,n=e.dims.length,o=rs(n,t),i=am(e.dims,o),a=e.dims,l=i,d=lm(o,e.dims),p;if(d)return p=g=>{let x=E("input",r,a,4),$=M("output",r,l,4);return` + ${g.registerUniform("output_size","u32").declareVariables(x,$)} + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let g=k.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(g/64/4)},programUniforms:[{type:12,data:Math.ceil(g/4)}]}},getShaderSource:p};let{newShape:m,newPerm:u}=um(e.dims,o),h=k.areEqual(u,[2,3,1]),_=k.areEqual(u,[3,1,2]);if(m.length===2||h||_){a=h?[m[0],m[1]*m[2]]:_?[m[0]*m[1],m[2]]:m,l=[a[1],a[0]];let g=16;return p=x=>{let $=E("a",r,a.length),v=M("output",r,l.length);return` + ${x.registerUniform("output_size","u32").declareVariables($,v)} + var tile : array, ${g}>; + ${x.mainStart([g,g,1])} let stride = (uniforms.output_shape[1] - 1) / ${g} + 1; let workgroup_id_x = workgroup_index % stride; let workgroup_id_y = workgroup_index / stride; let input_col = workgroup_id_y * ${g}u + local_id.x; let input_row = workgroup_id_x * ${g}u + local_id.y; if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { - tile[local_id.y][local_id.x] = ${w.getByIndices(`${w.type.indices}(input_row, input_col)`)}; + tile[local_id.y][local_id.x] = ${$.getByIndices(`${$.type.indices}(input_row, input_col)`)}; } workgroupBarrier(); let output_col = workgroup_id_x * ${g}u + local_id.x; let output_row = workgroup_id_y * ${g}u + local_id.y; if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { - ${y.setByIndices(`${y.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + ${v.setByIndices(`${v.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} } - }`:x=$=>` - ${$.registerUniform("output_size","u32").declareVariables(w,y)} + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let x=k.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(l[1]/g),y:Math.ceil(l[0]/g)},programUniforms:[{type:12,data:x},...N(a,l)]}},getShaderSource:p}}return p=g=>{let x=E("a",r,a.length),$=M("output",r,l.length);return` + ${g.registerUniform("output_size","u32").declareVariables(x,$)} - ${om(o,n,w,y)} + ${sm(o,n,x,$)} - ${$.mainStart()} - ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let indices = ${y.offsetToIndices("global_idx")}; + let indices = ${$.offsetToIndices("global_idx")}; let aIndices = perm(indices); - ${y.setByOffset("global_idx",w.getByIndices("aIndices"))} - }`,{name:m?"TransposeShared":"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let $=k.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:m?{x:Math.ceil(h[1]/g),y:Math.ceil(h[0]/g)}:{x:Math.ceil($/64)},programUniforms:[{type:12,data:$},...V(u,h)]}},getShaderSource:x}},as=(e,t)=>{rm(e.inputs),e.compute(Pe(e.inputs[0],t.perm))},ss=e=>re({perm:e.perm})});var am,sm,um,lm,dm,cm,pm,mm,fm,hm,tt,us,ls,ds,cs,ps,ms,fs,hs,gs,bs,ys=R(()=>{"use strict";te();oe();ae();Yr();ut();am={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},sm={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},um={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},lm={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},dm=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let i=0;ie[i]);return[r,o]},pm=(e,t)=>{let r=e.length+t.length,n=[],o=0;for(let i=0;i{for(let r=0;r{let r=[];if(!mm(e,t)){for(let n=0;nr.push(n))}return r},hm=(e,t,r,n,o,i,a)=>{let l=r[0].dims,d=k.size(i),c=k.size(a),m=E("_A",r[0].dataType,l),u=M("output",o,i),h=64;d===1&&(h=256);let w=` + ${$.setByOffset("global_idx",x.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let g=k.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:[{type:12,data:g},...N(a,l)]}},getShaderSource:p}},ns=(e,t)=>{im(e.inputs),e.compute(Ee(e.inputs[0],t.perm))},os=e=>J({perm:e.perm})});var dm,cm,pm,mm,fm,hm,gm,bm,ym,_m,tt,is,as,ss,us,ls,ds,cs,ps,ms,fs,hs=R(()=>{"use strict";te();oe();ae();qr();ut();dm={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},cm={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},pm={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},mm={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},fm=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let i=0;ie[i]);return[r,o]},gm=(e,t)=>{let r=e.length+t.length,n=[],o=0;for(let i=0;i{for(let r=0;r{let r=[];if(!bm(e,t)){for(let n=0;nr.push(n))}return r},_m=(e,t,r,n,o,i,a)=>{let l=r[0].dims,d=k.size(i),p=k.size(a),m=E("_A",r[0].dataType,l),u=M("output",o,i),h=64;d===1&&(h=256);let _=` var aBestValues : array; `,y=g=>` ${g.registerUniform("reduceSize","u32").declareVariables(m,u)} - ${w} + ${_} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } @@ -3901,11 +3906,11 @@ var Fn=Object.defineProperty;var Pp=Object.getOwnPropertyDescriptor;var zp=Objec let outputIndex = global_idx / ${h}; let offset = outputIndex * uniforms.reduceSize; - var bestValue = f32(${um[n]}); + var bestValue = f32(${pm[n]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${h}) { let candidate = f32(${m.getByOffset("offset + k")}); - bestValue = ${am[n]}; + bestValue = ${dm[n]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); @@ -3916,7 +3921,7 @@ var Fn=Object.defineProperty;var Pp=Object.getOwnPropertyDescriptor;var zp=Objec let interval = DIV_CEIL(reduceSize, 2u); if (local_idx < currentSize) { let candidate = aBestValues[local_idx + interval]; - bestValue = ${sm[n]}; + bestValue = ${cm[n]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; @@ -3924,9 +3929,9 @@ var Fn=Object.defineProperty;var Pp=Object.getOwnPropertyDescriptor;var zp=Objec } if (local_idx == 0u) { - ${u.setByOffset("outputIndex",`${n==="mean"?`${u.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${u.type.storage}(${lm[n]})`}`)}; + ${u.setByOffset("outputIndex",`${n==="mean"?`${u.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${u.type.storage}(${mm[n]})`}`)}; } - }`;return{name:e,shaderCache:{hint:`${t};${h}`,inputDependencies:["type"]},getShaderSource:y,getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:d},programUniforms:[{type:12,data:c}]})}},tt=(e,t,r,n)=>{let o=e.inputs.length===1?r:ho(e.inputs,r),i=o.axes;i.length===0&&!o.noopWithEmptyAxes&&(i=e.inputs[0].dims.map((w,y)=>y));let a=k.normalizeAxes(i,e.inputs[0].dims.length),l=a,d=e.inputs[0],c=fm(l,e.inputs[0].dims.length);c.length>0&&(d=e.compute(Pe(e.inputs[0],c),{inputs:[0],outputs:[-1]})[0],l=dm(l.length,d.dims.length));let[m,u]=cm(d.dims,l),h=m;o.keepDims&&(h=pm(m,a)),e.compute(hm(t,o.cacheKey,[d],n,e.inputs[0].dataType,h,u),{inputs:[d]})},us=(e,t)=>{tt(e,"ReduceMeanShared",t,"mean")},ls=(e,t)=>{tt(e,"ReduceL1Shared",t,"l1")},ds=(e,t)=>{tt(e,"ReduceL2Shared",t,"l2")},cs=(e,t)=>{tt(e,"ReduceLogSumExpShared",t,"logSumExp")},ps=(e,t)=>{tt(e,"ReduceMaxShared",t,"max")},ms=(e,t)=>{tt(e,"ReduceMinShared",t,"min")},fs=(e,t)=>{tt(e,"ReduceProdShared",t,"prod")},hs=(e,t)=>{tt(e,"ReduceSumShared",t,"sum")},gs=(e,t)=>{tt(e,"ReduceSumSquareShared",t,"sumSquare")},bs=(e,t)=>{tt(e,"ReduceLogSumShared",t,"logSum")}});var rt,gm,Zr,ho,nt,bm,ym,wm,_m,vm,$m,xm,Sm,Tm,Im,ot,ws,_s,vs,$s,xs,Ss,Ts,Is,Cs,As,Yr=R(()=>{"use strict";te();oe();Ie();ae();ys();rt=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},gm=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Zr=(e,t,r,n,o,i,a=!1,l=!1)=>{let d=[],c=r[0].dims,m=c.length,u=k.normalizeAxes(o,m),h=!l&&u.length===0;c.forEach((x,$)=>{h||u.indexOf($)>=0?a&&d.push(1):d.push(x)});let w=d.length,y=k.size(d);return{name:e,shaderCache:t,getShaderSource:x=>{let $=[],v=E("_A",r[0].dataType,m),S=M("output",i,w),T=n(v,S,u),C=T[2];for(let A=0,P=0;A=0?(a&&P++,C=`for(var j${A}: u32 = 0; j${A} < ${c[A]}; j${A}++) { + }`;return{name:e,shaderCache:{hint:`${t};${h}`,inputDependencies:["type"]},getShaderSource:y,getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:d},programUniforms:[{type:12,data:p}]})}},tt=(e,t,r,n)=>{let o=e.inputs.length===1?r:co(e.inputs,r),i=o.axes;i.length===0&&!o.noopWithEmptyAxes&&(i=e.inputs[0].dims.map((_,y)=>y));let a=k.normalizeAxes(i,e.inputs[0].dims.length),l=a,d=e.inputs[0],p=ym(l,e.inputs[0].dims.length);p.length>0&&(d=e.compute(Ee(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],l=fm(l.length,d.dims.length));let[m,u]=hm(d.dims,l),h=m;o.keepDims&&(h=gm(m,a)),e.compute(_m(t,o.cacheKey,[d],n,e.inputs[0].dataType,h,u),{inputs:[d]})},is=(e,t)=>{tt(e,"ReduceMeanShared",t,"mean")},as=(e,t)=>{tt(e,"ReduceL1Shared",t,"l1")},ss=(e,t)=>{tt(e,"ReduceL2Shared",t,"l2")},us=(e,t)=>{tt(e,"ReduceLogSumExpShared",t,"logSumExp")},ls=(e,t)=>{tt(e,"ReduceMaxShared",t,"max")},ds=(e,t)=>{tt(e,"ReduceMinShared",t,"min")},cs=(e,t)=>{tt(e,"ReduceProdShared",t,"prod")},ps=(e,t)=>{tt(e,"ReduceSumShared",t,"sum")},ms=(e,t)=>{tt(e,"ReduceSumSquareShared",t,"sumSquare")},fs=(e,t)=>{tt(e,"ReduceLogSumShared",t,"logSum")}});var rt,wm,jr,co,nt,vm,$m,xm,Sm,Tm,Im,Cm,Am,km,Em,ot,gs,bs,ys,_s,ws,vs,$s,xs,Ss,Ts,qr=R(()=>{"use strict";te();oe();Se();ae();hs();rt=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},wm=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],jr=(e,t,r,n,o,i,a=!1,l=!1)=>{let d=[],p=r[0].dims,m=p.length,u=k.normalizeAxes(o,m),h=!l&&u.length===0;p.forEach((x,$)=>{h||u.indexOf($)>=0?a&&d.push(1):d.push(x)});let _=d.length,y=k.size(d);return{name:e,shaderCache:t,getShaderSource:x=>{let $=[],v=E("_A",r[0].dataType,m),S=M("output",i,_),T=n(v,S,u),C=T[2];for(let A=0,P=0;A=0?(a&&P++,C=`for(var j${A}: u32 = 0; j${A} < ${p[A]}; j${A}++) { ${T[2].includes("last_index")?`let last_index = j${A};`:""} ${v.indicesSet("input_indices",A,`j${A}`)} ${C} @@ -3947,19 +3952,19 @@ var Fn=Object.defineProperty;var Pp=Object.getOwnPropertyDescriptor;var zp=Objec ${T[3]} ${T.length===4?S.setByOffset("global_idx","value"):T.slice(4).join(` `)} - }`},getRunData:()=>({outputs:[{dims:d,dataType:i}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:[{type:12,data:y},...V(c,d)]})}},ho=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),re({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},nt=(e,t,r,n)=>{let o=e.inputs,i=o.length===1?r:ho(o,r);e.compute(Zr(t,{hint:i.cacheKey,inputDependencies:["rank"]},[o[0]],i.noopWithEmptyAxes&&i.axes.length===0?gm:n,i.axes,o[0].dataType,i.keepDims,i.noopWithEmptyAxes),{inputs:[0]})},bm=(e,t)=>{rt(e.inputs),nt(e,"ReduceLogSum",t,(n,o)=>[`var value = ${o.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,"value = log(value);"])},ym=(e,t)=>{rt(e.inputs),nt(e,"ReduceL1",t,(n,o)=>[`var value = ${o.type.storage}(0);`,"",`value += abs(${n.getByIndices("input_indices")});`,""])},wm=(e,t)=>{rt(e.inputs),nt(e,"ReduceL2",t,(n,o)=>[`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`,"",`t = ${n.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},_m=(e,t)=>{rt(e.inputs),nt(e,"ReduceLogSumExp",t,(n,o)=>[`var value = ${o.type.storage}(0);`,"",`value += exp(${n.getByIndices("input_indices")});`,"value = log(value);"])},vm=(e,t)=>{rt(e.inputs),nt(e,"ReduceMax",t,(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(n.indicesSet("input_indices",l,0));return[`${a.join(` -`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = max(value, ${n.getByIndices("input_indices")});`,""]})},$m=(e,t)=>{rt(e.inputs),nt(e,"ReduceMean",t,(n,o,i)=>{let a=1;for(let l=0;l=0||i.length===0)&&(a*=e.inputs[0].dims[l]);return["var sum = f32(0);","",`sum += f32(${n.getByIndices("input_indices")});`,`let value = ${o.type.value}(sum / ${a});`]})},xm=(e,t)=>{rt(e.inputs),nt(e,"ReduceMin",t,(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(`input_indices[${l}] = 0;`);return[`${a.join(` -`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = min(value, ${n.getByIndices("input_indices")});`,""]})},Sm=(e,t)=>{rt(e.inputs),nt(e,"ReduceProd",t,(n,o)=>[`var value = ${o.type.storage}(1);`,"",`value *= ${n.getByIndices("input_indices")};`,""])},Tm=(e,t)=>{rt(e.inputs),nt(e,"ReduceSum",t,(n,o)=>[`var value = ${o.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,""])},Im=(e,t)=>{rt(e.inputs),nt(e,"ReduceSumSquare",t,(n,o)=>[`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`,"",`t = ${n.getByIndices("input_indices")}; value += t * t;`,""])},ot=(e,t,r)=>{if(t.length===0)return r;let n=1,o=1;for(let i=0;i1024},ws=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?$m(e,t):us(e,t)},_s=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ym(e,t):ls(e,t)},vs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?wm(e,t):ds(e,t)},$s=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?_m(e,t):cs(e,t)},xs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?vm(e,t):ps(e,t)},Ss=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?xm(e,t):ms(e,t)},Ts=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Sm(e,t):fs(e,t)},Is=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Tm(e,t):hs(e,t)},Cs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Im(e,t):gs(e,t)},As=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?bm(e,t):bs(e,t)}});var ks,Es,Ps,go,zs=R(()=>{"use strict";te();Ie();Yr();ks=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},Es=(e,t)=>{ks(e.inputs);let r=(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(`input_indices[${l}] = 0;`);return[`${a.join(` + }`},getRunData:()=>({outputs:[{dims:d,dataType:i}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:[{type:12,data:y},...N(p,d)]})}},co=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),J({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},nt=(e,t,r,n)=>{let o=e.inputs,i=o.length===1?r:co(o,r);e.compute(jr(t,{hint:i.cacheKey,inputDependencies:["rank"]},[o[0]],i.noopWithEmptyAxes&&i.axes.length===0?wm:n,i.axes,o[0].dataType,i.keepDims,i.noopWithEmptyAxes),{inputs:[0]})},vm=(e,t)=>{rt(e.inputs),nt(e,"ReduceLogSum",t,(n,o)=>[`var value = ${o.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,"value = log(value);"])},$m=(e,t)=>{rt(e.inputs),nt(e,"ReduceL1",t,(n,o)=>[`var value = ${o.type.storage}(0);`,"",`value += abs(${n.getByIndices("input_indices")});`,""])},xm=(e,t)=>{rt(e.inputs),nt(e,"ReduceL2",t,(n,o)=>[`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`,"",`t = ${n.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Sm=(e,t)=>{rt(e.inputs),nt(e,"ReduceLogSumExp",t,(n,o)=>[`var value = ${o.type.storage}(0);`,"",`value += exp(${n.getByIndices("input_indices")});`,"value = log(value);"])},Tm=(e,t)=>{rt(e.inputs),nt(e,"ReduceMax",t,(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(n.indicesSet("input_indices",l,0));return[`${a.join(` +`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = max(value, ${n.getByIndices("input_indices")});`,""]})},Im=(e,t)=>{rt(e.inputs),nt(e,"ReduceMean",t,(n,o,i)=>{let a=1;for(let l=0;l=0||i.length===0)&&(a*=e.inputs[0].dims[l]);return["var sum = f32(0);","",`sum += f32(${n.getByIndices("input_indices")});`,`let value = ${o.type.value}(sum / ${a});`]})},Cm=(e,t)=>{rt(e.inputs),nt(e,"ReduceMin",t,(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(`input_indices[${l}] = 0;`);return[`${a.join(` +`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = min(value, ${n.getByIndices("input_indices")});`,""]})},Am=(e,t)=>{rt(e.inputs),nt(e,"ReduceProd",t,(n,o)=>[`var value = ${o.type.storage}(1);`,"",`value *= ${n.getByIndices("input_indices")};`,""])},km=(e,t)=>{rt(e.inputs),nt(e,"ReduceSum",t,(n,o)=>[`var value = ${o.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,""])},Em=(e,t)=>{rt(e.inputs),nt(e,"ReduceSumSquare",t,(n,o)=>[`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`,"",`t = ${n.getByIndices("input_indices")}; value += t * t;`,""])},ot=(e,t,r)=>{if(t.length===0)return r;let n=1,o=1;for(let i=0;i1024},gs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Im(e,t):is(e,t)},bs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?$m(e,t):as(e,t)},ys=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?xm(e,t):ss(e,t)},_s=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Sm(e,t):us(e,t)},ws=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Tm(e,t):ls(e,t)},vs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Cm(e,t):ds(e,t)},$s=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Am(e,t):cs(e,t)},xs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?km(e,t):ps(e,t)},Ss=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Em(e,t):ms(e,t)},Ts=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?vm(e,t):fs(e,t)}});var Is,Cs,As,po,ks=R(()=>{"use strict";te();Se();qr();Is=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},Cs=(e,t)=>{Is(e.inputs);let r=(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(`input_indices[${l}] = 0;`);return[`${a.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); - }`,"",o.setByOffset("global_idx","best_index")]};e.compute(Zr("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Ps=(e,t)=>{ks(e.inputs);let r=(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(`input_indices[${l}] = 0;`);return[`${a.join(` + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(jr("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},As=(e,t)=>{Is(e.inputs);let r=(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(`input_indices[${l}] = 0;`);return[`${a.join(` `)}`,`var value = ${n.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { value = ${n.getByIndices("input_indices")}; best_index = i32(last_index); - }`,"",o.setByOffset("global_idx","best_index")]};e.compute(Zr("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},go=e=>re(e)});var Cm,bo,Am,km,Em,Rt,Pm,Os,Xr=R(()=>{"use strict";te();oe();qr();ae();Cm=(e,t)=>{let r=e[0],n=e[1],o=e[2],i=e[3],a=e[4],l=e[5];if(a&&l)throw new Error("Attention cannot have both past and attention_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let d=r.dims[0],c=r.dims[1],m=r.dims[2];if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==m)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(o.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let u=o.dims[0]/3,h=u,w=h;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let S of t.qkvHiddenSizes)if(S%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");u=t.qkvHiddenSizes[0],h=t.qkvHiddenSizes[1],w=t.qkvHiddenSizes[2]}let y=c;if(u!==h)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==u+h+w)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let g=0;if(a){if(h!==w)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(a.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(a.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(a.dims[1]!==d)throw new Error('Input "past" second dimension must be batch_size');if(a.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(a.dims[4]!==h/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(g=a.dims[3])}let x=y+g,$=-1,v=0;if(i)throw new Error("Mask not supported");if(a)throw new Error("past is not supported");if(l){if(l.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(l.dims[0]!==d||l.dims[1]!==t.numHeads||l.dims[2]!==c||l.dims[3]!==x)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:d,sequenceLength:c,pastSequenceLength:g,kvSequenceLength:y,totalSequenceLength:x,maxSequenceLength:$,inputHiddenSize:m,hiddenSize:u,vHiddenSize:w,headSize:Math.floor(u/t.numHeads),vHeadSize:Math.floor(w/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:v,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},bo=(e,t,r)=>t&&e?` + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(jr("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},po=e=>J(e)});var Pm,mo,zm,Om,Bm,Rt,Dm,Es,Kr=R(()=>{"use strict";te();oe();Lr();ae();Pm=(e,t)=>{let r=e[0],n=e[1],o=e[2],i=e[3],a=e[4],l=e[5];if(a&&l)throw new Error("Attention cannot have both past and attention_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let d=r.dims[0],p=r.dims[1],m=r.dims[2];if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==m)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(o.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let u=o.dims[0]/3,h=u,_=h;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let S of t.qkvHiddenSizes)if(S%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");u=t.qkvHiddenSizes[0],h=t.qkvHiddenSizes[1],_=t.qkvHiddenSizes[2]}let y=p;if(u!==h)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==u+h+_)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let g=0;if(a){if(h!==_)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(a.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(a.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(a.dims[1]!==d)throw new Error('Input "past" second dimension must be batch_size');if(a.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(a.dims[4]!==h/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(g=a.dims[3])}let x=y+g,$=-1,v=0;if(i)throw new Error("Mask not supported");if(a)throw new Error("past is not supported");if(l){if(l.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(l.dims[0]!==d||l.dims[1]!==t.numHeads||l.dims[2]!==p||l.dims[3]!==x)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:d,sequenceLength:p,pastSequenceLength:g,kvSequenceLength:y,totalSequenceLength:x,maxSequenceLength:$,inputHiddenSize:m,hiddenSize:u,vHiddenSize:_,headSize:Math.floor(u/t.numHeads),vHeadSize:Math.floor(_/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:v,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},mo=(e,t,r)=>t&&e?` let total_sequence_length_input = u32(${t.getByOffset("0")}); let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; @@ -3972,18 +3977,18 @@ var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLas `:` ${r?"let past_sequence_length = uniforms.past_sequence_length":""}; let present_sequence_length = total_sequence_length; - `,Am=(e,t,r,n,o,i,a,l)=>{let d=ye(a?1:i),c=64,m=i/d;m{let v=M("x",e.dataType,e.dims,d),S=[v],T=a?E("seq_lens",a.dataType,a.dims):void 0;T&&S.push(T);let C=l?E("total_sequence_length_input",l.dataType,l.dims):void 0;C&&S.push(C);let A=Ee(e.dataType),P=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` - var thread_max: array; - var thread_sum: array; + `,zm=(e,t,r,n,o,i,a,l)=>{let d=me(a?1:i),p=64,m=i/d;m{let v=M("x",e.dataType,e.dims,d),S=[v],T=a?E("seq_lens",a.dataType,a.dims):void 0;T&&S.push(T);let C=l?E("total_sequence_length_input",l.dataType,l.dims):void 0;C&&S.push(C);let A=ke(e.dataType),P=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; ${$.registerUniforms(P).declareVariables(...S)} - ${$.mainStart([c,1,1])} + ${$.mainStart([p,1,1])} let batchIdx = workgroup_id.z / uniforms.num_heads; let headIdx = workgroup_id.z % uniforms.num_heads; let sequence_length = uniforms.sequence_length; var total_sequence_length = uniforms.total_sequence_length; - ${bo(T,C,!1)} + ${mo(T,C,!1)} let local_offset = local_idx * uniforms.elements_per_thread; - let offset = (global_idx / ${c}) * uniforms.total_sequence_length + local_offset; + let offset = (global_idx / ${p}) * uniforms.total_sequence_length + local_offset; let seq_causal_length = ${a?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; var thread_max_vector = ${y}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { @@ -3993,7 +3998,7 @@ var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLas workgroupBarrier(); var max_value = f32(-3.402823e+38f); - for (var i = 0u; i < ${c}; i++) { + for (var i = 0u; i < ${p}; i++) { max_value = max(thread_max[i], max_value); } @@ -4005,7 +4010,7 @@ var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLas workgroupBarrier(); var sum: f32 = 0; - for (var i = 0u; i < ${c}; i++) { + for (var i = 0u; i < ${p}; i++) { sum += thread_sum[i]; } @@ -4023,12 +4028,12 @@ var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLas for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { x[offset + total_seq_id] = ${v.type.value}(${A}(0)); }`:""}; - }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${c};${w};${d}`,inputDependencies:g},getShaderSource:x,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(i/c),y:o,z:t*r},programUniforms:h})}},km=(e,t,r,n,o,i,a,l,d)=>{let c=a+i.kvSequenceLength,m=[i.batchSize,i.numHeads,i.sequenceLength,c],u=e>1&&n,h=i.kvNumHeads?i.kvNumHeads:i.numHeads,w=u?[i.batchSize,h,c,i.headSize]:void 0,y=i.nReps?i.nReps:1,g=i.scale===0?1/Math.sqrt(i.headSize):i.scale,x=ye(i.headSize),$=i.headSize/x,v=12,S={x:Math.ceil(c/v),y:Math.ceil(i.sequenceLength/v),z:i.batchSize*i.numHeads},T=[{type:12,data:i.sequenceLength},{type:12,data:$},{type:12,data:c},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:1,data:g},{type:12,data:a},{type:12,data:i.kvSequenceLength},{type:12,data:y}],C=u&&n&&k.size(n.dims)>0,A=["type","type"];C&&A.push("type"),o&&A.push("type"),l&&A.push("type"),d&&A.push("type");let P=[{dims:m,dataType:t.dataType,gpuDataType:0}];u&&P.push({dims:w,dataType:t.dataType,gpuDataType:0});let O=U=>{let L=E("q",t.dataType,t.dims,x),j=E("key",r.dataType,r.dims,x),K=[L,j];if(C){let ne=E("past_key",n.dataType,n.dims,x);K.push(ne)}o&&K.push(E("attention_bias",o.dataType,o.dims));let W=l?E("seq_lens",l.dataType,l.dims):void 0;W&&K.push(W);let ee=d?E("total_sequence_length_input",d.dataType,d.dims):void 0;ee&&K.push(ee);let ue=M("output",t.dataType,m),Z=[ue];u&&Z.push(M("present_key",t.dataType,w,x));let J=Ee(1,x),Q=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${p};${_};${d}`,inputDependencies:g},getShaderSource:x,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(i/p),y:o,z:t*r},programUniforms:h})}},Om=(e,t,r,n,o,i,a,l,d)=>{let p=a+i.kvSequenceLength,m=[i.batchSize,i.numHeads,i.sequenceLength,p],u=e>1&&n,h=i.kvNumHeads?i.kvNumHeads:i.numHeads,_=u?[i.batchSize,h,p,i.headSize]:void 0,y=i.nReps?i.nReps:1,g=i.scale===0?1/Math.sqrt(i.headSize):i.scale,x=me(i.headSize),$=i.headSize/x,v=12,S={x:Math.ceil(p/v),y:Math.ceil(i.sequenceLength/v),z:i.batchSize*i.numHeads},T=[{type:12,data:i.sequenceLength},{type:12,data:$},{type:12,data:p},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:1,data:g},{type:12,data:a},{type:12,data:i.kvSequenceLength},{type:12,data:y}],C=u&&n&&k.size(n.dims)>0,A=["type","type"];C&&A.push("type"),o&&A.push("type"),l&&A.push("type"),d&&A.push("type");let P=[{dims:m,dataType:t.dataType,gpuDataType:0}];u&&P.push({dims:_,dataType:t.dataType,gpuDataType:0});let O=U=>{let G=E("q",t.dataType,t.dims,x),q=E("key",r.dataType,r.dims,x),K=[G,q];if(C){let ne=E("past_key",n.dataType,n.dims,x);K.push(ne)}o&&K.push(E("attention_bias",o.dataType,o.dims));let W=l?E("seq_lens",l.dataType,l.dims):void 0;W&&K.push(W);let Y=d?E("total_sequence_length_input",d.dataType,d.dims):void 0;Y&&K.push(Y);let se=M("output",t.dataType,m),X=[se];u&&X.push(M("present_key",t.dataType,_,x));let re=ke(1,x),ee=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${v}u; - var tileQ: array<${L.type.storage}, ${v*v}>; - var tileK: array<${L.type.storage}, ${v*v}>; - ${U.registerUniforms(Q).declareVariables(...K,...Z)} + var tileQ: array<${G.type.storage}, ${v*v}>; + var tileK: array<${G.type.storage}, ${v*v}>; + ${U.registerUniforms(ee).declareVariables(...K,...X)} ${U.mainStart([v,v,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z % uniforms.num_heads; @@ -4039,13 +4044,13 @@ var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLas let n = workgroup_id.x * TILE_SIZE; let sequence_length = uniforms.M; var total_sequence_length = uniforms.N; - ${bo(W,ee,!0)} + ${mo(W,Y,!0)} let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; ${C&&u?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; ${u?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} - var value = ${J}(0); + var value = ${re}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; @@ -4068,7 +4073,7 @@ var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLas workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { - value += ${J}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + value += ${re}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); } workgroupBarrier(); @@ -4078,23 +4083,23 @@ var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLas let headOffset = workgroup_id.z * uniforms.M * uniforms.N; let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; var sum: f32 = ${(()=>{switch(x){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${x}`)}})()}; - output[outputIdx] = ${ue.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"}; + output[outputIdx] = ${se.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"}; } - }`};return{name:"AttentionProbs",shaderCache:{hint:`${x};${o!==void 0};${n!==void 0};${e}`,inputDependencies:A},getRunData:()=>({outputs:P,dispatchGroup:S,programUniforms:T}),getShaderSource:O}},Em=(e,t,r,n,o,i,a=void 0,l=void 0)=>{let d=i+o.kvSequenceLength,c=o.nReps?o.nReps:1,m=o.vHiddenSize*c,u=e>1&&n,h=o.kvNumHeads?o.kvNumHeads:o.numHeads,w=u?[o.batchSize,h,d,o.headSize]:void 0,y=[o.batchSize,o.sequenceLength,m],g=12,x={x:Math.ceil(o.vHeadSize/g),y:Math.ceil(o.sequenceLength/g),z:o.batchSize*o.numHeads},$=[{type:12,data:o.sequenceLength},{type:12,data:d},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:m},{type:12,data:i},{type:12,data:o.kvSequenceLength},{type:12,data:c}],v=u&&n&&k.size(n.dims)>0,S=["type","type"];v&&S.push("type"),a&&S.push("type"),l&&S.push("type");let T=[{dims:y,dataType:t.dataType,gpuDataType:0}];u&&T.push({dims:w,dataType:t.dataType,gpuDataType:0});let C=A=>{let P=E("probs",t.dataType,t.dims),O=E("v",r.dataType,r.dims),U=[P,O];v&&U.push(E("past_value",n.dataType,n.dims));let L=a?E("seq_lens",a.dataType,a.dims):void 0;a&&U.push(L);let j=l?E("total_sequence_length_input",l.dataType,l.dims):void 0;l&&U.push(j);let W=[M("output",t.dataType,y)];u&&W.push(M("present_value",t.dataType,w));let ee=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + }`};return{name:"AttentionProbs",shaderCache:{hint:`${x};${o!==void 0};${n!==void 0};${e}`,inputDependencies:A},getRunData:()=>({outputs:P,dispatchGroup:S,programUniforms:T}),getShaderSource:O}},Bm=(e,t,r,n,o,i,a=void 0,l=void 0)=>{let d=i+o.kvSequenceLength,p=o.nReps?o.nReps:1,m=o.vHiddenSize*p,u=e>1&&n,h=o.kvNumHeads?o.kvNumHeads:o.numHeads,_=u?[o.batchSize,h,d,o.headSize]:void 0,y=[o.batchSize,o.sequenceLength,m],g=12,x={x:Math.ceil(o.vHeadSize/g),y:Math.ceil(o.sequenceLength/g),z:o.batchSize*o.numHeads},$=[{type:12,data:o.sequenceLength},{type:12,data:d},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:m},{type:12,data:i},{type:12,data:o.kvSequenceLength},{type:12,data:p}],v=u&&n&&k.size(n.dims)>0,S=["type","type"];v&&S.push("type"),a&&S.push("type"),l&&S.push("type");let T=[{dims:y,dataType:t.dataType,gpuDataType:0}];u&&T.push({dims:_,dataType:t.dataType,gpuDataType:0});let C=A=>{let P=E("probs",t.dataType,t.dims),O=E("v",r.dataType,r.dims),U=[P,O];v&&U.push(E("past_value",n.dataType,n.dims));let G=a?E("seq_lens",a.dataType,a.dims):void 0;a&&U.push(G);let q=l?E("total_sequence_length_input",l.dataType,l.dims):void 0;l&&U.push(q);let W=[M("output",t.dataType,y)];u&&W.push(M("present_value",t.dataType,_));let Y=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${g}u; var tileQ: array<${P.type.value}, ${g*g}>; var tileV: array<${P.type.value}, ${g*g}>; - ${A.registerUniforms(ee).declareVariables(...U,...W)} + ${A.registerUniforms(Y).declareVariables(...U,...W)} ${A.mainStart([g,g,1])} let headIdx = workgroup_id.z % uniforms.num_heads; let batchIdx = workgroup_id.z / uniforms.num_heads; - let kvHeadIdx = ${c===1?"headIdx":"headIdx / uniforms.n_reps"}; - let kv_num_heads = ${c===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let kvHeadIdx = ${p===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${p===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; let m = global_id.y; let n = global_id.x; let sequence_length = uniforms.M; var total_sequence_length = uniforms.K; - ${bo(L,j,!0)} + ${mo(G,q,!0)} let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch ${v&&u?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; @@ -4135,13 +4140,13 @@ var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLas + headIdx * uniforms.N + n; output[outputIdx] = value; } - }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:S},getRunData:()=>({outputs:T,dispatchGroup:x,programUniforms:$}),getShaderSource:C}},Rt=(e,t,r,n,o,i,a,l,d,c,m=void 0,u=void 0)=>{let h=Math.min(e.outputCount,1+(a?1:0)+(l?1:0)),w=h>1?c.pastSequenceLength:0,y=w+c.kvSequenceLength,g=d&&k.size(d.dims)>0?d:void 0,x=[t,r];h>1&&a&&k.size(a.dims)>0&&x.push(a),g&&x.push(g),m&&x.push(m),u&&x.push(u);let $=e.compute(km(h,t,r,a,g,c,w,m,u),{inputs:x,outputs:h>1?[-1,1]:[-1]})[0];e.compute(Am($,c.batchSize,c.numHeads,w,c.sequenceLength,y,m,u),{inputs:m&&u?[$,m,u]:[$],outputs:[]});let v=[$,n];h>1&&l&&k.size(l.dims)>0&&v.push(l),m&&v.push(m),u&&v.push(u),e.compute(Em(h,$,n,l,c,w,m,u),{inputs:v,outputs:h>1?[0,2]:[0]})},Pm=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,o=t.inputHiddenSize,i=t.headSize,a=12,l={x:Math.ceil(t.headSize/a),y:Math.ceil(t.sequenceLength/a),z:t.batchSize*t.numHeads},d=[e.inputs[0],e.inputs[1],e.inputs[2]],c=[{type:12,data:n},{type:12,data:o},{type:12,data:i},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],m=u=>{let h=M("output_q",d[0].dataType,r),w=M("output_k",d[0].dataType,r),y=M("output_v",d[0].dataType,r),g=E("input",d[0].dataType,d[0].dims),x=E("weight",d[1].dataType,d[1].dims),$=E("bias",d[2].dataType,d[2].dims),v=g.type.storage,S=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:S},getRunData:()=>({outputs:T,dispatchGroup:x,programUniforms:$}),getShaderSource:C}},Rt=(e,t,r,n,o,i,a,l,d,p,m=void 0,u=void 0)=>{let h=Math.min(e.outputCount,1+(a?1:0)+(l?1:0)),_=h>1?p.pastSequenceLength:0,y=_+p.kvSequenceLength,g=d&&k.size(d.dims)>0?d:void 0,x=[t,r];h>1&&a&&k.size(a.dims)>0&&x.push(a),g&&x.push(g),m&&x.push(m),u&&x.push(u);let $=e.compute(Om(h,t,r,a,g,p,_,m,u),{inputs:x,outputs:h>1?[-1,1]:[-1]})[0];e.compute(zm($,p.batchSize,p.numHeads,_,p.sequenceLength,y,m,u),{inputs:m&&u?[$,m,u]:[$],outputs:[]});let v=[$,n];h>1&&l&&k.size(l.dims)>0&&v.push(l),m&&v.push(m),u&&v.push(u),e.compute(Bm(h,$,n,l,p,_,m,u),{inputs:v,outputs:h>1?[0,2]:[0]})},Dm=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,o=t.inputHiddenSize,i=t.headSize,a=12,l={x:Math.ceil(t.headSize/a),y:Math.ceil(t.sequenceLength/a),z:t.batchSize*t.numHeads},d=[e.inputs[0],e.inputs[1],e.inputs[2]],p=[{type:12,data:n},{type:12,data:o},{type:12,data:i},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],m=u=>{let h=M("output_q",d[0].dataType,r),_=M("output_k",d[0].dataType,r),y=M("output_v",d[0].dataType,r),g=E("input",d[0].dataType,d[0].dims),x=E("weight",d[1].dataType,d[1].dims),$=E("bias",d[2].dataType,d[2].dims),v=g.type.storage,S=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` const TILE_SIZE = ${a}u; var tileInput: array<${v}, ${a*a}>; var tileWeightQ: array<${v}, ${a*a}>; var tileWeightK: array<${v}, ${a*a}>; var tileWeightV: array<${v}, ${a*a}>; - ${u.registerUniforms(S).declareVariables(g,x,$,h,w,y)} + ${u.registerUniforms(S).declareVariables(g,x,$,h,_,y)} ${u.mainStart([a,a,1])} let batchIndex = workgroup_id.z / uniforms.num_heads; let headNumber = workgroup_id.z % uniforms.num_heads; @@ -4190,24 +4195,24 @@ var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLas output_k[outputIdx] = valueK; output_v[outputIdx] = valueV; } - }`};return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:l,programUniforms:c}),getShaderSource:m},{inputs:d,outputs:[-1,-1,-1]})},Os=(e,t)=>{let r=Cm(e.inputs,t),[n,o,i]=Pm(e,r);return Rt(e,n,o,i,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r)}});var zm,Om,Dm,Ds,Bs=R(()=>{"use strict";He();te();oe();Ie();ae();zm=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,o,i)=>{let a=o.length;if(a!==n.length)throw new Error(`${i}: num dimensions != ${a}`);o.forEach((l,d)=>{if(l!==n[d])throw new Error(`${i}: dim[${d}] do not match`)})};if(e[0].dims.length>1){let n=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,n,"Invalid input scale"),r(e[2].dims,n,"Invalid input B"),r(e[3].dims,n,"Invalid input mean"),r(e[4].dims,n,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},Om=(e,t)=>{let{epsilon:r,spatial:n,format:o}=t,i=e[0].dims,a=n?ye(i[i.length-1]):1,l=o==="NHWC"&&i.length>1?a:1,d=k.size(i)/a,c=n,m=c?i.length:i,u=E("x",e[0].dataType,e[0].dims,a),h=E("scale",e[1].dataType,e[1].dims,l),w=E("bias",e[2].dataType,e[2].dims,l),y=E("inputMean",e[3].dataType,e[3].dims,l),g=E("inputVar",e[4].dataType,e[4].dims,l),x=M("y",e[0].dataType,m,a),$=()=>{let S="";if(n)S=`let cOffset = ${i.length===1?"0u":o==="NHWC"?`outputIndices[${i.length-1}] / ${a}`:"outputIndices[1]"};`;else if(o==="NCHW")S=` + }`};return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:l,programUniforms:p}),getShaderSource:m},{inputs:d,outputs:[-1,-1,-1]})},Es=(e,t)=>{let r=Pm(e.inputs,t),[n,o,i]=Dm(e,r);return Rt(e,n,o,i,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r)}});var Mm,Rm,Um,Ps,zs=R(()=>{"use strict";We();te();oe();Se();ae();Mm=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,o,i)=>{let a=o.length;if(a!==n.length)throw new Error(`${i}: num dimensions != ${a}`);o.forEach((l,d)=>{if(l!==n[d])throw new Error(`${i}: dim[${d}] do not match`)})};if(e[0].dims.length>1){let n=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,n,"Invalid input scale"),r(e[2].dims,n,"Invalid input B"),r(e[3].dims,n,"Invalid input mean"),r(e[4].dims,n,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},Rm=(e,t)=>{let{epsilon:r,spatial:n,format:o}=t,i=e[0].dims,a=n?me(i[i.length-1]):1,l=o==="NHWC"&&i.length>1?a:1,d=k.size(i)/a,p=n,m=p?i.length:i,u=E("x",e[0].dataType,e[0].dims,a),h=E("scale",e[1].dataType,e[1].dims,l),_=E("bias",e[2].dataType,e[2].dims,l),y=E("inputMean",e[3].dataType,e[3].dims,l),g=E("inputVar",e[4].dataType,e[4].dims,l),x=M("y",e[0].dataType,m,a),$=()=>{let S="";if(n)S=`let cOffset = ${i.length===1?"0u":o==="NHWC"?`outputIndices[${i.length-1}] / ${a}`:"outputIndices[1]"};`;else if(o==="NCHW")S=` ${x.indicesSet("outputIndices","0","0")} let cOffset = ${x.indicesToOffset("outputIndices")};`;else{S=`var cIndices = ${h.type.indices}(0); cIndices[0] = outputIndices[${i.length-1}];`;for(let T=1;T` const epsilon = ${r}; - ${S.registerUniform("outputSize","u32").declareVariables(u,h,w,y,g,x)} + ${S.registerUniform("outputSize","u32").declareVariables(u,h,_,y,g,x)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${x.offsetToIndices(`global_idx * ${a}`)}; ${$()} let scale = ${h.getByOffset("cOffset")}; - let bias = ${w.getByOffset("cOffset")}; + let bias = ${_.getByOffset("cOffset")}; let inputMean = ${y.getByOffset("cOffset")}; let inputVar = ${g.getByOffset("cOffset")}; let x = ${u.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${x.setByOffset("global_idx","value")} - }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${a}`,inputDependencies:c?["rank","type","type","type","type"]:void 0},getShaderSource:v,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c?[{type:12,data:d},...V(i)]:[{type:12,data:d}]})}},Dm=e=>re(e),Ds=(e,t)=>{let{inputs:r,outputCount:n}=e,o=Dm({...t,outputCount:n});if(ve.webgpu.validateInputContent&&zm(r,o),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Om(r,o))}});var Bm,Mm,Ms,Rs=R(()=>{"use strict";oe();ae();Bm=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Mm=e=>{let t=e[0].dims,r=e[0].dims[2],n=k.size(t)/4,o=e[0].dataType,i=E("input",o,t,4),a=E("bias",o,[r],4),l=E("residual",o,t,4),d=M("output",o,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:m=>` + }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${a}`,inputDependencies:p?["rank","type","type","type","type"]:void 0},getShaderSource:v,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p?[{type:12,data:d},...N(i)]:[{type:12,data:d}]})}},Um=e=>J(e),Ps=(e,t)=>{let{inputs:r,outputCount:n}=e,o=Um({...t,outputCount:n});if(we.webgpu.validateInputContent&&Mm(r,o),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Rm(r,o))}});var Nm,Vm,Os,Bs=R(()=>{"use strict";oe();ae();Nm=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Vm=e=>{let t=e[0].dims,r=e[0].dims[2],n=k.size(t)/4,o=e[0].dataType,i=E("input",o,t,4),a=E("bias",o,[r],4),l=E("residual",o,t,4),d=M("output",o,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:m=>` const channels = ${r}u / 4; ${m.declareVariables(i,a,l,d)} @@ -4216,17 +4221,17 @@ var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLas let value = ${i.getByOffset("global_idx")} + ${a.getByOffset("global_idx % channels")} + ${l.getByOffset("global_idx")}; ${d.setByOffset("global_idx","value")} - }`}},Ms=e=>{Bm(e.inputs),e.compute(Mm(e.inputs))}});var Rm,fe,Us,Vs,Ns,Ws,Ls,Gs,Hs,Fs,qs,Um,js,Ks,Ys,Zs,Jt,Xs,Qr,Qs,Js,eu,tu,ru,nu,ou,iu,au,su,uu,lu,du,cu,pu,mu,fu,hu,yo,wo,gu,bu,yu,Vm,Nm,wu,Jr=R(()=>{"use strict";te();oe();Ie();ae();Rm=(e,t,r,n,o,i,a)=>{let l=Math.ceil(t/4),d="";typeof o=="string"?d=`${o}(a)`:d=o("a");let c=E("inputData",r,[l],4),m=M("outputData",n,[l],4),u=[{name:"vec_size",type:"u32"}];return a&&u.push(...a),` - ${e.registerUniforms(u).declareVariables(c,m)} + }`}},Os=e=>{Nm(e.inputs),e.compute(Vm(e.inputs))}});var Wm,fe,Ds,Ms,Rs,Us,Ns,Vs,Ws,Ls,Gs,Lm,Hs,Fs,qs,js,Jt,Ks,Yr,Ys,Zs,Qs,Xs,Js,eu,tu,ru,nu,ou,iu,au,su,uu,lu,du,cu,pu,fo,ho,mu,fu,hu,Gm,Hm,gu,Zr=R(()=>{"use strict";te();oe();Se();ae();Wm=(e,t,r,n,o,i,a)=>{let l=Math.ceil(t/4),d="";typeof o=="string"?d=`${o}(a)`:d=o("a");let p=E("inputData",r,[l],4),m=M("outputData",n,[l],4),u=[{name:"vec_size",type:"u32"}];return a&&u.push(...a),` + ${e.registerUniforms(u).declareVariables(p,m)} ${i??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - let a = ${c.getByOffset("global_idx")}; + let a = ${p.getByOffset("global_idx")}; ${m.setByOffset("global_idx",d)} - }`},fe=(e,t,r,n,o,i=e.dataType,a,l)=>{let d=[{type:12,data:Math.ceil(k.size(e.dims)/4)}];return a&&d.push(...a),{name:t,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:c=>Rm(c,k.size(e.dims),e.dataType,i,r,n,l),getRunData:c=>({outputs:[{dims:e.dims,dataType:i}],dispatchGroup:{x:Math.ceil(k.size(c[0].dims)/64/4)},programUniforms:d})}},Us=e=>{e.compute(fe(e.inputs[0],"Abs","abs"))},Vs=e=>{e.compute(fe(e.inputs[0],"Acos","acos"))},Ns=e=>{e.compute(fe(e.inputs[0],"Acosh","acosh"))},Ws=e=>{e.compute(fe(e.inputs[0],"Asin","asin"))},Ls=e=>{e.compute(fe(e.inputs[0],"Asinh","asinh"))},Gs=e=>{e.compute(fe(e.inputs[0],"Atan","atan"))},Hs=e=>{e.compute(fe(e.inputs[0],"Atanh","atanh"))},Fs=e=>re(e),qs=(e,t)=>{let r;switch(t.to){case 10:r="vec4";break;case 1:r="vec4";break;case 12:r="vec4";break;case 6:r="vec4";break;case 9:r="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(fe(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},Um=e=>{let t,r,n=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,r=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,r=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return re({min:t,max:r})},js=(e,t)=>{let r=t||Um(e.inputs),n=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],"Clip",o=>`clamp(${o}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,r.cacheKey,void 0,[{type:e.inputs[0].dataType,data:r.min},{type:e.inputs[0].dataType,data:r.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},Ks=e=>{e.compute(fe(e.inputs[0],"Ceil","ceil"))},Ys=e=>{e.compute(fe(e.inputs[0],"Cos","cos"))},Zs=e=>{e.compute(fe(e.inputs[0],"Cosh","cosh"))},Jt=e=>re(e),Xs=(e,t)=>{let r=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],"Elu",n=>`elu_vf32(${n})`,` + }`},fe=(e,t,r,n,o,i=e.dataType,a,l)=>{let d=[{type:12,data:Math.ceil(k.size(e.dims)/4)}];return a&&d.push(...a),{name:t,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:p=>Wm(p,k.size(e.dims),e.dataType,i,r,n,l),getRunData:p=>({outputs:[{dims:e.dims,dataType:i}],dispatchGroup:{x:Math.ceil(k.size(p[0].dims)/64/4)},programUniforms:d})}},Ds=e=>{e.compute(fe(e.inputs[0],"Abs","abs"))},Ms=e=>{e.compute(fe(e.inputs[0],"Acos","acos"))},Rs=e=>{e.compute(fe(e.inputs[0],"Acosh","acosh"))},Us=e=>{e.compute(fe(e.inputs[0],"Asin","asin"))},Ns=e=>{e.compute(fe(e.inputs[0],"Asinh","asinh"))},Vs=e=>{e.compute(fe(e.inputs[0],"Atan","atan"))},Ws=e=>{e.compute(fe(e.inputs[0],"Atanh","atanh"))},Ls=e=>J(e),Gs=(e,t)=>{let r;switch(t.to){case 10:r="vec4";break;case 1:r="vec4";break;case 12:r="vec4";break;case 6:r="vec4";break;case 9:r="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(fe(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},Lm=e=>{let t,r,n=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,r=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,r=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return J({min:t,max:r})},Hs=(e,t)=>{let r=t||Lm(e.inputs),n=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],"Clip",o=>`clamp(${o}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,r.cacheKey,void 0,[{type:e.inputs[0].dataType,data:r.min},{type:e.inputs[0].dataType,data:r.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},Fs=e=>{e.compute(fe(e.inputs[0],"Ceil","ceil"))},qs=e=>{e.compute(fe(e.inputs[0],"Cos","cos"))},js=e=>{e.compute(fe(e.inputs[0],"Cosh","cosh"))},Jt=e=>J(e),Ks=(e,t)=>{let r=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],"Elu",n=>`elu_vf32(${n})`,` const elu_alpha_ = ${r}(${t.alpha}); fn elu_f32(a: ${r}) -> ${r} { @@ -4235,7 +4240,7 @@ var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLas fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> { return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); - }`,t.cacheKey))},Qr=(e="f32")=>` + }`,t.cacheKey))},Yr=(e="f32")=>` const r0: ${e} = 0.3275911; const r1: ${e} = 0.254829592; const r2: ${e} = -0.284496736; @@ -4247,15 +4252,15 @@ fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> { let absv = abs(v); let x = 1.0 / (1.0 + r0 * absv); return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv)); -}`,Qs=e=>{let t=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Qr(t)))},Js=e=>{e.compute(fe(e.inputs[0],"Exp","exp"))},eu=e=>{e.compute(fe(e.inputs[0],"Floor","floor"))},tu=e=>{let t=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Qr(t)))},ru=(e,t)=>{let r=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},nu=e=>{e.compute(fe(e.inputs[0],"Not",t=>`!${t}`))},ou=e=>{e.compute(fe(e.inputs[0],"Neg",t=>`-${t}`))},iu=e=>{e.compute(fe(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},au=e=>{let t=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},su=e=>{e.compute(fe(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},uu=e=>re(e),lu=(e,t)=>{let r=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],"HardSigmoid",n=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${n} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},du=e=>{e.compute(fe(e.inputs[0],"Sin","sin"))},cu=e=>{e.compute(fe(e.inputs[0],"Sinh","sinh"))},pu=e=>{e.compute(fe(e.inputs[0],"Sqrt","sqrt"))},mu=e=>{e.compute(fe(e.inputs[0],"Tan","tan"))},fu=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,hu=e=>{e.compute(fe(e.inputs[0],"Tanh",fu))},yo=(e="f32")=>` +}`,Ys=e=>{let t=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Yr(t)))},Zs=e=>{e.compute(fe(e.inputs[0],"Exp","exp"))},Qs=e=>{e.compute(fe(e.inputs[0],"Floor","floor"))},Xs=e=>{let t=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Yr(t)))},Js=(e,t)=>{let r=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},eu=e=>{e.compute(fe(e.inputs[0],"Not",t=>`!${t}`))},tu=e=>{e.compute(fe(e.inputs[0],"Neg",t=>`-${t}`))},ru=e=>{e.compute(fe(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},nu=e=>{let t=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},ou=e=>{e.compute(fe(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},iu=e=>J(e),au=(e,t)=>{let r=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],"HardSigmoid",n=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${n} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},su=e=>{e.compute(fe(e.inputs[0],"Sin","sin"))},uu=e=>{e.compute(fe(e.inputs[0],"Sinh","sinh"))},lu=e=>{e.compute(fe(e.inputs[0],"Sqrt","sqrt"))},du=e=>{e.compute(fe(e.inputs[0],"Tan","tan"))},cu=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,pu=e=>{e.compute(fe(e.inputs[0],"Tanh",cu))},fo=(e="f32")=>` const fast_gelu_a: ${e} = 0.5; const fast_gelu_b: ${e} = 0.7978845608028654; const fast_gelu_c: ${e} = 0.035677408136300125; fn tanh_v(v: vec4<${e}>) -> vec4<${e}> { - return ${fu("v")}; + return ${cu("v")}; } -`,wo=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,gu=e=>{let t=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],"FastGelu",wo,yo(t),void 0,e.inputs[0].dataType))},bu=(e,t)=>{let r=Ee(e.inputs[0].dataType);return e.compute(fe(e.inputs[0],"ThresholdedRelu",n=>`select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},yu=e=>{e.compute(fe(e.inputs[0],"Log","log"))},Vm=(e,t)=>` +`,ho=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,mu=e=>{let t=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],"FastGelu",ho,fo(t),void 0,e.inputs[0].dataType))},fu=(e,t)=>{let r=ke(e.inputs[0].dataType);return e.compute(fe(e.inputs[0],"ThresholdedRelu",n=>`select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},hu=e=>{e.compute(fe(e.inputs[0],"Log","log"))},Gm=(e,t)=>` const alpha = vec4<${e}>(${t}); const one = ${e}(1.0); const zero = ${e}(0.0); @@ -4272,13 +4277,13 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { } return x * x1; } -`,Nm=e=>`quick_gelu_impl(${e})`,wu=(e,t)=>{let r=Ee(e.inputs[0].dataType);e.compute(fe(e.inputs[0],"QuickGelu",Nm,Vm(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}});var Wm,Lm,vu,$u=R(()=>{"use strict";oe();ae();Jr();Wm=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Lm=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=E("input",e[0].dataType,e[0].dims,4),n=E("bias",e[0].dataType,[e[0].dims[2]],4),o=M("output",e[0].dataType,t,4),i=k.size(t)/4,a=me(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:d=>` +`,Hm=e=>`quick_gelu_impl(${e})`,gu=(e,t)=>{let r=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],"QuickGelu",Hm,Gm(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}});var Fm,qm,yu,_u=R(()=>{"use strict";oe();ae();Zr();Fm=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},qm=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=E("input",e[0].dataType,e[0].dims,4),n=E("bias",e[0].dataType,[e[0].dims[2]],4),o=M("output",e[0].dataType,t,4),i=k.size(t)/4,a=ye(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:d=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2]/4/2}u; ${d.declareVariables(r,n,o)} - ${Qr(a)} + ${Yr(a)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes(i)} @@ -4290,12 +4295,12 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${o.setByOffset("global_idx","valueLeft * geluRight")} - }`}},vu=e=>{Wm(e.inputs),e.compute(Lm(e.inputs))}});var Gm,Hm,it,xu,Su,Tu,Iu,Cu,Au,ku,Eu,Pu,zu,Ou=R(()=>{"use strict";te();oe();ae();Gm=(e,t,r,n,o,i,a,l,d,c,m,u)=>{let h,w;typeof l=="string"?h=w=(v,S)=>`${l}((${v}),(${S}))`:typeof l=="function"?h=w=l:(h=l.scalar,w=l.vector);let y=M("outputData",m,n.length,4),g=E("aData",d,t.length,4),x=E("bData",c,r.length,4),$;if(o)if(i){let v=k.size(t)===1,S=k.size(r)===1,T=t.length>0&&t[t.length-1]%4===0,C=r.length>0&&r[r.length-1]%4===0;v||S?$=y.setByOffset("global_idx",w(v?`${g.type.value}(${g.getByOffset("0")}.x)`:g.getByOffset("global_idx"),S?`${x.type.value}(${x.getByOffset("0")}.x)`:x.getByOffset("global_idx"))):$=` + }`}},yu=e=>{Fm(e.inputs),e.compute(qm(e.inputs))}});var jm,Km,it,wu,vu,$u,xu,Su,Tu,Iu,Cu,Au,ku,Eu=R(()=>{"use strict";te();oe();ae();jm=(e,t,r,n,o,i,a,l,d,p,m,u)=>{let h,_;typeof l=="string"?h=_=(v,S)=>`${l}((${v}),(${S}))`:typeof l=="function"?h=_=l:(h=l.scalar,_=l.vector);let y=M("outputData",m,n.length,4),g=E("aData",d,t.length,4),x=E("bData",p,r.length,4),$;if(o)if(i){let v=k.size(t)===1,S=k.size(r)===1,T=t.length>0&&t[t.length-1]%4===0,C=r.length>0&&r[r.length-1]%4===0;v||S?$=y.setByOffset("global_idx",_(v?`${g.type.value}(${g.getByOffset("0")}.x)`:g.getByOffset("global_idx"),S?`${x.type.value}(${x.getByOffset("0")}.x)`:x.getByOffset("global_idx"))):$=` let outputIndices = ${y.offsetToIndices("global_idx * 4u")}; let offsetA = ${g.broadcastedIndicesToOffset("outputIndices",y)}; let offsetB = ${x.broadcastedIndicesToOffset("outputIndices",y)}; - ${y.setByOffset("global_idx",w(a||T?g.getByOffset("offsetA / 4u"):`${g.type.value}(${g.getByOffset("offsetA / 4u")}[offsetA % 4u])`,a||C?x.getByOffset("offsetB / 4u"):`${x.type.value}(${x.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} - `}else $=y.setByOffset("global_idx",w(g.getByOffset("global_idx"),x.getByOffset("global_idx")));else{if(!i)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let v=(S,T,C="")=>{let A=`aData[indexA${T}][componentA${T}]`,P=`bData[indexB${T}][componentB${T}]`;return` + ${y.setByOffset("global_idx",_(a||T?g.getByOffset("offsetA / 4u"):`${g.type.value}(${g.getByOffset("offsetA / 4u")}[offsetA % 4u])`,a||C?x.getByOffset("offsetB / 4u"):`${x.type.value}(${x.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else $=y.setByOffset("global_idx",_(g.getByOffset("global_idx"),x.getByOffset("global_idx")));else{if(!i)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let v=(S,T,C="")=>{let A=`aData[indexA${T}][componentA${T}]`,P=`bData[indexB${T}][componentB${T}]`;return` let outputIndices${T} = ${y.offsetToIndices(`global_idx * 4u + ${T}u`)}; let offsetA${T} = ${g.broadcastedIndicesToOffset(`outputIndices${T}`,y)}; let offsetB${T} = ${x.broadcastedIndicesToOffset(`outputIndices${T}`,y)}; @@ -4323,7 +4328,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${$} - }`},Hm=(e,t,r,n,o,i,a=r.dataType)=>{let l=r.dims.map(g=>Number(g)??1),d=n.dims.map(g=>Number(g)??1),c=!k.areEqual(l,d),m=l,u=k.size(l),h=!1,w=!1,y=[c];if(c){let g=et.calcShape(l,d,!1);if(!g)throw new Error("Can't perform binary op on the given tensors");m=g.slice(),u=k.size(m);let x=k.size(l)===1,$=k.size(d)===1,v=l.length>0&&l[l.length-1]%4===0,S=d.length>0&&d[d.length-1]%4===0;y.push(x),y.push($),y.push(v),y.push(S);let T=1;for(let C=1;Cg.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:g=>Gm(g,l,d,m,h,c,w,o,r.dataType,n.dataType,a,i),getRunData:()=>({outputs:[{dims:m,dataType:a}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:Math.ceil(k.size(m)/4)},...V(l,d,m)]})}},it=(e,t,r,n,o,i)=>{e.compute(Hm(t,o??"",e.inputs[0],e.inputs[1],r,n,i))},xu=e=>{it(e,"Add",(t,r)=>`${t}+${r}`)},Su=e=>{it(e,"Div",(t,r)=>`${t}/${r}`)},Tu=e=>{it(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},Iu=e=>{it(e,"Mul",(t,r)=>`${t}*${r}`)},Cu=e=>{let t=E("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;it(e,"Pow",{scalar:(n,o)=>`pow_custom(${n},${o})`,vector:(n,o)=>`pow_vector_custom(${n},${o})`},` + }`},Km=(e,t,r,n,o,i,a=r.dataType)=>{let l=r.dims.map(g=>Number(g)??1),d=n.dims.map(g=>Number(g)??1),p=!k.areEqual(l,d),m=l,u=k.size(l),h=!1,_=!1,y=[p];if(p){let g=et.calcShape(l,d,!1);if(!g)throw new Error("Can't perform binary op on the given tensors");m=g.slice(),u=k.size(m);let x=k.size(l)===1,$=k.size(d)===1,v=l.length>0&&l[l.length-1]%4===0,S=d.length>0&&d[d.length-1]%4===0;y.push(x),y.push($),y.push(v),y.push(S);let T=1;for(let C=1;Cg.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:g=>jm(g,l,d,m,h,p,_,o,r.dataType,n.dataType,a,i),getRunData:()=>({outputs:[{dims:m,dataType:a}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:Math.ceil(k.size(m)/4)},...N(l,d,m)]})}},it=(e,t,r,n,o,i)=>{e.compute(Km(t,o??"",e.inputs[0],e.inputs[1],r,n,i))},wu=e=>{it(e,"Add",(t,r)=>`${t}+${r}`)},vu=e=>{it(e,"Div",(t,r)=>`${t}/${r}`)},$u=e=>{it(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},xu=e=>{it(e,"Mul",(t,r)=>`${t}*${r}`)},Su=e=>{let t=E("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;it(e,"Pow",{scalar:(n,o)=>`pow_custom(${n},${o})`,vector:(n,o)=>`pow_vector_custom(${n},${o})`},` fn pow_custom(a : ${t}, b : ${t}) -> ${t} { if (b == ${t}(0.0)) { return ${t}(1.0); @@ -4336,7 +4341,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { // TODO: implement vectorized pow return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); } - `)},Au=e=>{it(e,"Sub",(t,r)=>`${t}-${r}`)},ku=e=>{it(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},Eu=e=>{it(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Pu=e=>{it(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},zu=e=>{it(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}});var qm,jm,Km,Ym,Du,Bu,Mu=R(()=>{"use strict";te();oe();Ie();ae();qm=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,n=e[r],o=n.dataType,i=n.dims.length;e.forEach((a,l)=>{if(l!==r){if(a.dataType!==o)throw new Error("input tensors should be one type");if(a.dims.length!==i)throw new Error("input tensors should have the same shape");a.dims.forEach((d,c)=>{if(c!==t&&d!==n.dims[c])throw new Error("non concat dimensions must match")})}})},jm=(e,t)=>` + `)},Tu=e=>{it(e,"Sub",(t,r)=>`${t}-${r}`)},Iu=e=>{it(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},Cu=e=>{it(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Au=e=>{it(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},ku=e=>{it(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}});var Zm,Qm,Xm,Jm,Pu,zu,Ou=R(()=>{"use strict";te();oe();Se();ae();Zm=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,n=e[r],o=n.dataType,i=n.dims.length;e.forEach((a,l)=>{if(l!==r){if(a.dataType!==o)throw new Error("input tensors should be one type");if(a.dims.length!==i)throw new Error("input tensors should have the same shape");a.dims.forEach((d,p)=>{if(p!==t&&d!==n.dims[p])throw new Error("non concat dimensions must match")})}})},Qm=(e,t)=>` fn calculateInputIndex(index: u32) -> u32 { let sizeInConcatAxis = array(${t}); for (var i: u32 = 0u; i < ${e}; i += 1u ) { @@ -4345,12 +4350,12 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { } } return ${e}u; - }`,Km=(e,t)=>{let r=e.length,n=[];for(let o=0;o{let o=k.size(r),i=new Array(e.length),a=new Array(e.length),l=0,d=[],c=[],m=[{type:12,data:o}];for(let g=0;g`uniforms.sizeInConcatAxis${g}`).join(","),y=g=>` + }`,Xm=(e,t)=>{let r=e.length,n=[];for(let o=0;o{let o=k.size(r),i=new Array(e.length),a=new Array(e.length),l=0,d=[],p=[],m=[{type:12,data:o}];for(let g=0;g`uniforms.sizeInConcatAxis${g}`).join(","),y=g=>` ${(()=>{g.registerUniform("outputSize","u32");for(let x=0;x) -> vec4<${e}> { let inputIndex = calculateInputIndex(${h}); if (inputIndex != 0u) { - let sizeInConcatAxis = array(${w}); + let sizeInConcatAxis = array(${_}); ${h} -= sizeInConcatAxis[inputIndex - 1u]; } - ${Km(a,u)} - }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:m}),getShaderSource:y}},Du=(e,t)=>{let r=e.inputs,n=r[0].dims,o=k.normalizeAxis(t.axis,n.length);qm(r,o);let i=n.slice();i[o]=r.reduce((l,d)=>l+(d.dims.length>o?d.dims[o]:0),0);let a=r.filter(l=>k.size(l.dims)>0);e.compute(Ym(a,o,i,r[0].dataType),{inputs:a})},Bu=e=>re({axis:e.axis})});var Ve,Ne,We,en,lt=R(()=>{"use strict";te();oe();Ve=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); + ${Xm(a,u)} + }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:m}),getShaderSource:y}},Pu=(e,t)=>{let r=e.inputs,n=r[0].dims,o=k.normalizeAxis(t.axis,n.length);Zm(r,o);let i=n.slice();i[o]=r.reduce((l,d)=>l+(d.dims.length>o?d.dims[o]:0),0);let a=r.filter(l=>k.size(l.dims)>0);e.compute(Jm(a,o,i,r[0].dataType),{inputs:a})},zu=e=>J({axis:e.axis})});var Fe,qe,je,Qr,bt=R(()=>{"use strict";te();oe();Fe=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); value = sign(value) * (1.0 - e2x) / (1.0 + e2x); - `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},Ne=(e,t)=>{e.activation==="Clip"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&t.push({type:1,data:e.alpha})},We=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},en=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[r,n]=e?.activation_params||[.2,.5];return{activation:t,alpha:r,beta:n}}else if(t==="Clip"){let[r,n]=e?.activation_params||[rs,ns];return{activation:t,clipMax:n,clipMin:r}}else if(t==="LeakyRelu"){let[r]=e?.activation_params||[.01];return{activation:t,alpha:r}}return{activation:t}}});var ze,tn,er=R(()=>{"use strict";ze=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},tn=e=>` + `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},qe=(e,t)=>{e.activation==="Clip"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&t.push({type:1,data:e.alpha})},je=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},Qr=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[r,n]=e?.activation_params||[.2,.5];return{activation:t,alpha:r,beta:n}}else if(t==="Clip"){let[r,n]=e?.activation_params||[Xa,Ja];return{activation:t,clipMax:n,clipMin:r}}else if(t==="LeakyRelu"){let[r]=e?.activation_params||[.01];return{activation:t,alpha:r}}return{activation:t}}});var Pe,Bu,Xr=R(()=>{"use strict";Pe=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},Bu=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} - `});var rn,_o=R(()=>{"use strict";rn=e=>` + `});var Du,Mu=R(()=>{"use strict";Du=e=>` fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 { return dot(coords, vec4( shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1)); @@ -4377,53 +4382,53 @@ fn getOutputIndexFromCoords(coords : vec4) -> i32 { return dot(coords, vec4( i32(${e}.x), i32(${e}.y), i32(${e}.z), 1)); } -`});var tr,nn,on=R(()=>{"use strict";te();oe();ae();lt();tr=(e,t,r,n,o)=>{let i=n-r;return` +`});var er,Jr,en=R(()=>{"use strict";te();oe();ae();bt();er=(e,t,r,n,o)=>{let i=n-r;return` ${Array.from({length:r}).map((a,l)=>` if (${F(t.shape,l,t.rank)} != 1) { ${t.indicesSet(e,l,F(o,l+i,n))} } else { ${t.indicesSet(e,l,0)} }`).join("")} -`},nn=(e,t,r,n,o=!1,i)=>{let a=e[0].dims,l=e[1].dims,d=a[a.length-2],c=l[l.length-1],m=a[a.length-1],u=ye(c),h=ye(m),w=ye(d),y=k.size(r)/u/w,g=e.length>2,x=n?n.slice(0,-2):r.slice(0,-2),v=[k.size(x),d,c],S=[{type:12,data:y},{type:12,data:d},{type:12,data:c},{type:12,data:m}];Ne(t,S),S.push(...V(x,a,l)),g&&S.push(...V(e[2].dims)),S.push(...V(v));let T=C=>{let A=Kr("batch_dims",e[0].dataType,x.length),P=E("a",e[0].dataType,a.length,h),O=E("b",e[1].dataType,l.length,u),U=M("output",e[0].dataType,v.length,u),L=me(U.type.tensor),j=Ve(t,U.type.value,L),K=[P,O],W="";if(g){let Z=o?u:1;K.push(E("bias",e[2].dataType,e[2].dims.length,Z)),W=`${o?`value += bias[col / ${Z}];`:`value += ${U.type.value}(bias[row + i]);`}`}let ee=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];We(t,ee);let ue=()=>{let Z=`var a_data: ${P.type.value};`;for(let J=0;J{let a=e[0].dims,l=e[1].dims,d=a[a.length-2],p=l[l.length-1],m=a[a.length-1],u=me(p),h=me(m),_=me(d),y=k.size(r)/u/_,g=e.length>2,x=n?n.slice(0,-2):r.slice(0,-2),v=[k.size(x),d,p],S=[{type:12,data:y},{type:12,data:d},{type:12,data:p},{type:12,data:m}];qe(t,S),S.push(...N(x,a,l)),g&&S.push(...N(e[2].dims)),S.push(...N(v));let T=C=>{let A=Fr("batch_dims",e[0].dataType,x.length),P=E("a",e[0].dataType,a.length,h),O=E("b",e[1].dataType,l.length,u),U=M("output",e[0].dataType,v.length,u),G=ye(U.type.tensor),q=Fe(t,U.type.value,G),K=[P,O],W="";if(g){let X=o?u:1;K.push(E("bias",e[2].dataType,e[2].dims.length,X)),W=`${o?`value += bias[col / ${X}];`:`value += ${U.type.value}(bias[row + i]);`}`}let Y=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];je(t,Y);let se=()=>{let X=`var a_data: ${P.type.value};`;for(let re=0;re; + var values: array<${U.type.value}, ${_}>; for (var k: u32 = 0u; k < uniforms.K; k = k + ${h}) { - ${ue()} + ${se()} } - for (var i = 0u; i < ${w}u; i++) { + for (var i = 0u; i < ${_}u; i++) { var value = values[i]; ${W} - ${j} + ${q} let cur_indices = ${U.type.indices}(batch, row + i, col); let offset = ${U.indicesToOffset("cur_indices")}; ${U.setByOffset(`offset / ${u}`,"value")}; } } - `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${u};${h};${w};${o}`,inputDependencies:g?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:S}),getShaderSource:T}}});var Zm,Xm,rr,Ru,Qm,nr,Jm,or,ir=R(()=>{"use strict";te();oe();ae();lt();on();er();Zm=(e,t)=>e?` + `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${u};${h};${_};${o}`,inputDependencies:g?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:S}),getShaderSource:T}}});var ef,tf,go,Ru,rf,bo,nf,tr,tn=R(()=>{"use strict";te();oe();ae();bt();en();Xr();ef=(e,t)=>e?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart / innerElementSize + inputCol${t?", batchIndices":""}); @@ -4431,7 +4436,7 @@ fn getOutputIndexFromCoords(coords : vec4) -> i32 { mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRow + innerRow, kStart / innerElementSize + inputCol${t?", batchIndices":""}); - `,Xm=(e,t)=>e?` + `,tf=(e,t)=>e?` let ACached0 = mm_Asub[k * innerElementSize][localRow]; let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; @@ -4448,11 +4453,11 @@ fn getOutputIndexFromCoords(coords : vec4) -> i32 { acc[i] = BCached1 * ACached.y + acc[i]; acc[i] = BCached2 * ACached.z + acc[i]; ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} - }`,rr=(e,t,r="f32",n,o=!1,i=32,a=!1,l=32)=>{let d=t[1]*e[1],c=t[0]*e[0],m=o?d:i,u=o?i:d,h=m/t[0],w=i/t[1];if(!((o&&h===4&&e[1]===4||!o&&(h===3||h===4))&&m%t[0]===0&&i%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${h} and workPerThread[1] ${e[1]} must be 4. + }`,go=(e,t,r="f32",n,o=!1,i=32,a=!1,l=32)=>{let d=t[1]*e[1],p=t[0]*e[0],m=o?d:i,u=o?i:d,h=m/t[0],_=i/t[1];if(!((o&&h===4&&e[1]===4||!o&&(h===3||h===4))&&m%t[0]===0&&i%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${h} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${h} must be 3 or 4. tileAWidth ${m} must be divisible by workgroupSize[0]${t[0]}. tileInner ${i} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` var mm_Asub: array, ${m/h}>, ${u}>; -var mm_Bsub: array, ${c/e[0]}>, ${i}>; +var mm_Bsub: array, ${p/e[0]}>, ${i}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; @@ -4479,17 +4484,17 @@ fn main(@builtin(local_invocation_id) localId : vec3, var acc: array, rowPerThread>; // Loop over shared dimension. - let tileRowB = localRow * ${w}; + let tileRowB = localRow * ${_}; for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let inputRow = tileRow + innerRow; let inputCol = tileCol; - ${Zm(o,n)} + ${ef(o,n)} } // Load one tile of B into local memory. - for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) { + for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", batchIndices":""}); @@ -4504,7 +4509,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${h===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} - ${Xm(o,h)} + ${tf(o,h)} } workgroupBarrier(); @@ -4521,10 +4526,10 @@ fn main(@builtin(local_invocation_id) localId : vec3, mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRowStart + inputRow, kStart + inputCol${t?", batchIndices":""}); - `,Qm=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",nr=(e,t,r="f32",n,o=!1,i=32,a=!1,l=32,d=!1)=>{let c=e[1]*t[1],m=e[0]*t[0],u=o?c:i,h=o?i:c;if(!(h%t[1]===0&&u%t[0]===0&&i%t[1]===0))throw new Error(`tileAHight ${h} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${u} must be divisible by workgroupSize[0]${t[0]}, tileInner ${i} must be divisible by workgroupSize[1]${t[1]}`);let w=h/t[1],y=u/t[0],g=i/t[1],x=d?` + `,rf=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",bo=(e,t,r="f32",n,o=!1,i=32,a=!1,l=32,d=!1)=>{let p=e[1]*t[1],m=e[0]*t[0],u=o?p:i,h=o?i:p;if(!(h%t[1]===0&&u%t[0]===0&&i%t[1]===0))throw new Error(`tileAHight ${h} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${u} must be divisible by workgroupSize[0]${t[0]}, tileInner ${i} must be divisible by workgroupSize[1]${t[1]}`);let _=h/t[1],y=u/t[0],g=i/t[1],x=d?` let localRow = i32(localId.y); let localCol = i32(localId.x); - let globalRowStart = i32(workgroupId.y) * ${c}; + let globalRowStart = i32(workgroupId.y) * ${p}; let globalColStart = i32(workgroupId.x) * ${m}; // Loop over shared dimension. @@ -4575,15 +4580,15 @@ let tileCol = i32(localId.x) * colPerThread; let globalRow = i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x) * colPerThread; -let globalRowStart = i32(workgroupId.y) * ${c}; +let globalRowStart = i32(workgroupId.y) * ${p}; -let tileRowA = i32(localId.y) * ${w}; +let tileRowA = i32(localId.y) * ${_}; let tileColA = i32(localId.x) * ${y}; let tileRowB = i32(localId.y) * ${g}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. - for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) { + for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${y}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; @@ -4612,7 +4617,7 @@ for (var t = 0; t < num_tiles; t = t + 1) { } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - ${Qm(o)} + ${rf(o)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } @@ -4647,14 +4652,14 @@ fn main(@builtin(local_invocation_id) localId : vec3, var acc : array, rowPerThread>; ${x} } -`},Jm=(e,t,r,n,o=!1)=>{let[i,a,l,d]=n,c=me(n[0].type.tensor);return` - fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${ze(e,c)} { - var value = ${ze(e,c)}(0.0); +`},nf=(e,t,r,n,o=!1)=>{let[i,a,l,d]=n,p=ye(n[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${Pe(e,p)} { + var value = ${Pe(e,p)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { var aIndices: ${a.type.indices}; - ${tr("aIndices",a,a.rank-2,i.rank,"batchIndices")} + ${er("aIndices",a,a.rank-2,i.rank,"batchIndices")} ${a.indicesSet("aIndices",a.rank-2,"u32(row)")} ${a.indicesSet("aIndices",a.rank-1,"u32(colIn)")} value = ${a.getByIndices("aIndices")}; @@ -4662,13 +4667,13 @@ fn main(@builtin(local_invocation_id) localId : vec3, return value; } - fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${ze(e,c)} { - var value = ${ze(e,c)}(0.0); + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${Pe(e,p)} { + var value = ${Pe(e,p)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { var bIndices: ${l.type.indices}; - ${tr("bIndices",l,l.rank-2,i.rank,"batchIndices")} + ${er("bIndices",l,l.rank-2,i.rank,"batchIndices")} ${l.indicesSet("bIndices",l.rank-2,"u32(row)")} ${l.indicesSet("bIndices",l.rank-1,"u32(colIn)")} value = ${l.getByIndices("bIndices")}; @@ -4676,25 +4681,25 @@ fn main(@builtin(local_invocation_id) localId : vec3, return value; } - fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${ze(e,c)}) { + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Pe(e,p)}) { let col = colIn * ${e}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let coords = vec3(batch, row, colIn); - ${t?`value = value + ${o?"bias[colIn]":`${ze(e,c)}(bias[row])`};`:""} + ${t?`value = value + ${o?"bias[colIn]":`${Pe(e,p)}(bias[row])`};`:""} ${r} ${d.setByIndices("vec3(coords)","value")} } } - `},or=(e,t,r,n,o=!1,i)=>{let a=e[0].dims,l=e[1].dims,d=a.slice(0,-2),c=l.slice(0,-2),m=n?n.slice(0,-2):r.slice(0,-2),u=k.size(m),h=a[a.length-2],w=a[a.length-1],y=l[l.length-1],g=w%4===0&&y%4===0,x=h<=8?[4,1,1]:[4,4,1],$=[8,8,1],v=[Math.ceil(y/$[0]/x[0]),Math.ceil(h/$[1]/x[1]),Math.ceil(u/$[2]/x[2])],S=g?4:1,T=[...d,h,w/S],C=T.length,A=[...c,w,y/S],P=A.length,O=[u,h,y/S],U=[{type:6,data:h},{type:6,data:y},{type:6,data:w}];Ne(t,U),U.push(...V(m,T,A));let L=["rank","rank"],j=e.length>2;j&&(U.push(...V(e[2].dims)),L.push("rank")),U.push(...V(O));let K=W=>{let ee=m.length,ue=Kr("batchDims",e[0].dataType,ee,1),Z=me(e[0].dataType),J=E("a",e[0].dataType,C,S),Q=E("b",e[1].dataType,P,S),ne=M("result",e[0].dataType,O.length,S),we=[J,Q];if(j){let q=o?S:1;we.push(E("bias",e[2].dataType,e[2].dims.length,q))}let Ae=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];We(t,Ae);let $e=me(ne.type.tensor),de=Ve(t,ne.type.value,$e),N=Jm(S,j,de,[ue,J,Q,ne],o);return` - ${W.registerUniforms(Ae).registerInternalVariables(ue).declareVariables(...we,ne)} - ${N} - ${g?rr(x,$,Z,ue):nr(x,$,Z,ue)} - `};return{name:"MatMul",shaderCache:{hint:`${x};${t.activation};${g};${o}`,inputDependencies:L},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:v[0],y:v[1],z:v[2]},programUniforms:U}),getShaderSource:K}}});var ef,Uu,Vu=R(()=>{"use strict";te();je();ae();lt();er();_o();ir();ef=(e,t,r,n,o=!1,i,a=4,l=4,d=4,c="f32")=>{let m=L=>{switch(L){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${c}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${L} is not supported.`)}},u=L=>{switch(L){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${L} is not supported.`)}},h=e?` + `},tr=(e,t,r,n,o=!1,i)=>{let a=e[0].dims,l=e[1].dims,d=a.slice(0,-2),p=l.slice(0,-2),m=n?n.slice(0,-2):r.slice(0,-2),u=k.size(m),h=a[a.length-2],_=a[a.length-1],y=l[l.length-1],g=_%4===0&&y%4===0,x=h<=8?[4,1,1]:[4,4,1],$=[8,8,1],v=[Math.ceil(y/$[0]/x[0]),Math.ceil(h/$[1]/x[1]),Math.ceil(u/$[2]/x[2])],S=g?4:1,T=[...d,h,_/S],C=T.length,A=[...p,_,y/S],P=A.length,O=[u,h,y/S],U=[{type:6,data:h},{type:6,data:y},{type:6,data:_}];qe(t,U),U.push(...N(m,T,A));let G=["rank","rank"],q=e.length>2;q&&(U.push(...N(e[2].dims)),G.push("rank")),U.push(...N(O));let K=W=>{let Y=m.length,se=Fr("batchDims",e[0].dataType,Y,1),X=ye(e[0].dataType),re=E("a",e[0].dataType,C,S),ee=E("b",e[1].dataType,P,S),ne=M("result",e[0].dataType,O.length,S),ve=[re,ee];if(q){let j=o?S:1;ve.push(E("bias",e[2].dataType,e[2].dims.length,j))}let Be=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];je(t,Be);let $e=ye(ne.type.tensor),de=Fe(t,ne.type.value,$e),V=nf(S,q,de,[se,re,ee,ne],o);return` + ${W.registerUniforms(Be).registerInternalVariables(se).declareVariables(...ve,ne)} + ${V} + ${g?go(x,$,X,se):bo(x,$,X,se)} + `};return{name:"MatMul",shaderCache:{hint:`${x};${t.activation};${g};${o}`,inputDependencies:G},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:v[0],y:v[1],z:v[2]},programUniforms:U}),getShaderSource:K}}});var of,Uu,Nu=R(()=>{"use strict";te();Je();ae();bt();Xr();Mu();tn();of=(e,t,r,n,o=!1,i,a=4,l=4,d=4,p="f32")=>{let m=G=>{switch(G){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${p}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${G} is not supported.`)}},u=G=>{switch(G){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${G} is not supported.`)}},h=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); - `,w=e?` + `,_=e?` let coords = vec4( batch, row / outWidth, @@ -4717,7 +4722,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; let xCh = ${$} % inChannels; - var resData = ${ze(a,c)}(0.0); + var resData = ${Pe(a,p)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${y} && xCol >= 0 && xCol < ${g}) { @@ -4732,14 +4737,14 @@ fn main(@builtin(local_invocation_id) localId : vec3, if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${v} } - return ${ze(a,c)}(0.0);`:n&&r?` + return ${Pe(a,p)}(0.0);`:n&&r?` let col = colIn * ${a}; ${v}`:` let col = colIn * ${a}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${v} } - return ${ze(a,c)}(0.0);`,T=`${u(l)}`,C=ze(d,c),A=e?ze(a,c):ze(l,c),P=e?ze(l,c):ze(a,c),O=Ve(i,C,c);return` + return ${Pe(a,p)}(0.0);`,T=`${u(l)}`,C=Pe(d,p),A=e?Pe(a,p):Pe(l,p),P=e?Pe(l,p):Pe(a,p),O=Fe(i,C,p);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${A} { ${e?S:T} } @@ -4754,34 +4759,34 @@ fn main(@builtin(local_invocation_id) localId : vec3, { var value = valueIn; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; - ${w} - ${tn(o)} + ${_} + ${Bu(o)} ${O} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } - }`},Uu=(e,t,r,n,o,i,a,l,d)=>{let c=t.format==="NHWC",m=c?e[0].dims[3]:e[0].dims[1],u=r[0],h=c?r[2]:r[3],w=c?r[1]:r[2],y=c?r[3]:r[1],g=c&&(m%4===0||m%3===0)&&y%4===0,x=c?y:h*w,$=c?h*w:y,v=[8,8,1],S=n<=8?[4,1,1]:[4,4,1],T=[Math.ceil(x/v[0]/S[0]),Math.ceil($/v[1]/S[1]),Math.ceil(u/v[2]/S[2])];se("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${T}`);let C=g?c&&m%4!==0?3:4:1,A=v[1]*S[1],P=v[0]*S[0],O=Math.max(v[0]*C,v[1]),U=n%A===0,L=o%P===0,j=i%O===0,K=g?[C,4,4]:[1,1,1],W=[{type:6,data:n},{type:6,data:o},{type:6,data:i},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Ne(t,W),W.push(...V(e[0].dims,e[1].dims));let ee=["rank","rank"];a&&(W.push(...V(e[2].dims)),ee.push("rank")),W.push(...V(r));let ue=Z=>{let J=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];We(t,J);let Q=g?4:1,ne=me(e[0].dataType),we=` + }`},Uu=(e,t,r,n,o,i,a,l,d)=>{let p=t.format==="NHWC",m=p?e[0].dims[3]:e[0].dims[1],u=r[0],h=p?r[2]:r[3],_=p?r[1]:r[2],y=p?r[3]:r[1],g=p&&(m%4===0||m%3===0)&&y%4===0,x=p?y:h*_,$=p?h*_:y,v=[8,8,1],S=n<=8?[4,1,1]:[4,4,1],T=[Math.ceil(x/v[0]/S[0]),Math.ceil($/v[1]/S[1]),Math.ceil(u/v[2]/S[2])];ue("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${T}`);let C=g?p&&m%4!==0?3:4:1,A=v[1]*S[1],P=v[0]*S[0],O=Math.max(v[0]*C,v[1]),U=n%A===0,G=o%P===0,q=i%O===0,K=g?[C,4,4]:[1,1,1],W=[{type:6,data:n},{type:6,data:o},{type:6,data:i},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];qe(t,W),W.push(...N(e[0].dims,e[1].dims));let Y=["rank","rank"];a&&(W.push(...N(e[2].dims)),Y.push("rank")),W.push(...N(r));let se=X=>{let re=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];je(t,re);let ee=g?4:1,ne=ye(e[0].dataType),ve=` fn setOutputAtIndex(flatIndex : i32, value : ${g?`vec4<${ne}>`:ne}) { result[flatIndex] = ${g?`vec4<${ne}>`:ne}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${g?`vec4<${ne}>`:ne}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${g?"/ 4":""}, value); - }`,Ae=E("x",e[0].dataType,e[0].dims.length,C===3?1:C),$e=E("w",e[1].dataType,e[1].dims.length,Q),de=[Ae,$e],N=M("result",e[0].dataType,r.length,Q);if(a){let q=E("bias",e[2].dataType,e[2].dims.length,Q);de.push(q),we+=` + }`,Be=E("x",e[0].dataType,e[0].dims.length,C===3?1:C),$e=E("w",e[1].dataType,e[1].dims.length,ee),de=[Be,$e],V=M("result",e[0].dataType,r.length,ee);if(a){let j=E("bias",e[2].dataType,e[2].dims.length,ee);de.push(j),ve+=` fn getBiasByOutputCoords(coords : vec4) -> ${g?`vec4<${ne}>`:ne} { - return bias[coords.${c?"w":"y"}${g?"/ 4":""}]; + return bias[coords.${p?"w":"y"}${g?"/ 4":""}]; }`}return` - ${rn("uniforms.result_strides")} + ${Du("uniforms.result_strides")} //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; - ${Z.registerUniforms(J).declareVariables(...de,N)} - ${we} - ${ef(c,U,L,j,a,t,K[0],K[1],K[2],ne)} - ${g?rr(S,v,ne,void 0,!c,O):nr(S,v,ne,void 0,!c,O,!1,void 0,l)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${C};${g};${U};${L};${j};${A};${P};${O}`,inputDependencies:ee},getRunData:()=>({outputs:[{dims:d?d(r):r,dataType:e[0].dataType}],dispatchGroup:{x:T[0],y:T[1],z:T[2]},programUniforms:W}),getShaderSource:ue}}});var tf,Nu,an,rf,Wu,nf,Lu,Gu,Hu=R(()=>{"use strict";te();je();oe();ae();lt();er();tf=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,an=(e,t)=>t<=1?e:e+(e-1)*(t-1),rf=(e,t,r,n=1)=>{let o=an(t,n);return Math.floor((e[0]*(r-1)-r+o)/2)},Wu=(e,t,r,n,o)=>{o==null&&(o=rf(e,t[0],n[0]));let i=[0,0,0,r];for(let a=0;a<3;a++)e[a]+2*o>=t[a]&&(i[a]=Math.trunc((e[a]-t[a]+2*o)/n[a]+1));return i},nf=(e,t,r,n,o,i,a,l,d,c)=>{let m,u,h,w;if(e==="VALID"&&(e=0),typeof e=="number"){m={top:e,bottom:e,left:e,right:e,front:e,back:e};let y=Wu([t,r,n,1],[l,d,c],1,[o,i,a],e);u=y[0],h=y[1],w=y[2]}else if(Array.isArray(e)){if(!e.every((g,x,$)=>g===$[0]))throw Error(`Unsupported padding parameter: ${e}`);m={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let y=Wu([t,r,n,1],[l,d,c],1,[o,i,a],e[0]);u=y[0],h=y[1],w=y[2]}else if(e==="SAME_UPPER"){u=Math.ceil(t/o),h=Math.ceil(r/i),w=Math.ceil(n/a);let y=(u-1)*o+l-t,g=(h-1)*i+d-r,x=(w-1)*a+c-n,$=Math.floor(y/2),v=y-$,S=Math.floor(g/2),T=g-S,C=Math.floor(x/2),A=x-C;m={top:S,bottom:T,left:C,right:A,front:$,back:v}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:m,outDepth:u,outHeight:h,outWidth:w}},Lu=(e,t,r,n,o,i=!1,a="channelsLast")=>{let l,d,c,m,u;if(a==="channelsLast")[l,d,c,m,u]=e;else if(a==="channelsFirst")[l,u,d,c,m]=e;else throw new Error(`Unknown dataFormat ${a}`);let[h,,w,y,g]=t,[x,$,v]=Nu(r),[S,T,C]=Nu(n),A=an(w,S),P=an(y,T),O=an(g,C),{padInfo:U,outDepth:L,outHeight:j,outWidth:K}=nf(o,d,c,m,x,$,v,A,P,O),W=i?h*u:h,ee=[0,0,0,0,0];return a==="channelsFirst"?ee=[l,W,L,j,K]:a==="channelsLast"&&(ee=[l,L,j,K,W]),{batchSize:l,dataFormat:a,inDepth:d,inHeight:c,inWidth:m,inChannels:u,outDepth:L,outHeight:j,outWidth:K,outChannels:W,padInfo:U,strideDepth:x,strideHeight:$,strideWidth:v,filterDepth:w,filterHeight:y,filterWidth:g,effectiveFilterDepth:A,effectiveFilterHeight:P,effectiveFilterWidth:O,dilationDepth:S,dilationHeight:T,dilationWidth:C,inShape:e,outShape:ee,filterShape:t}},Gu=(e,t,r,n,o,i)=>{let a=i==="channelsLast",l=a?e[0].dims[3]:e[0].dims[1],d=!1,c=[64,1,1],m={x:r.map((v,S)=>S)},u=[Math.ceil(tf(m.x.map(v=>r[v]))/c[0]),1,1];se("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${u}`);let h=d?a&&l%4!==0?3:4:1,w=k.size(r),y=[{type:12,data:w},{type:12,data:n},{type:12,data:o},{type:12,data:t.strides},{type:12,data:t.dilations}];Ne(t,y),y.push(...V(e[0].dims,e[1].dims));let g=["rank","rank"],x=e.length===3;x&&(y.push(...V(e[2].dims)),g.push("rank")),y.push(...V(r));let $=v=>{let S=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];We(t,S);let T=d?4:1,C=me(e[0].dataType),A=E("x",e[0].dataType,e[0].dims.length,h===3?1:h),P=E("W",e[1].dataType,e[1].dims.length,T),O=[A,P],U=M("result",e[0].dataType,r.length,T),L="";if(x){let W=E("bias",e[2].dataType,e[2].dims.length,T);O.push(W),L+=` + ${X.registerUniforms(re).declareVariables(...de,V)} + ${ve} + ${of(p,U,G,q,a,t,K[0],K[1],K[2],ne)} + ${g?go(S,v,ne,void 0,!p,O):bo(S,v,ne,void 0,!p,O,!1,void 0,l)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${C};${g};${U};${G};${q};${A};${P};${O}`,inputDependencies:Y},getRunData:()=>({outputs:[{dims:d?d(r):r,dataType:e[0].dataType}],dispatchGroup:{x:T[0],y:T[1],z:T[2]},programUniforms:W}),getShaderSource:se}}});var af,Vu,rn,sf,Wu,uf,Lu,Gu,Hu=R(()=>{"use strict";te();Je();oe();ae();bt();Xr();af=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,rn=(e,t)=>t<=1?e:e+(e-1)*(t-1),sf=(e,t,r,n=1)=>{let o=rn(t,n);return Math.floor((e[0]*(r-1)-r+o)/2)},Wu=(e,t,r,n,o)=>{o==null&&(o=sf(e,t[0],n[0]));let i=[0,0,0,r];for(let a=0;a<3;a++)e[a]+2*o>=t[a]&&(i[a]=Math.trunc((e[a]-t[a]+2*o)/n[a]+1));return i},uf=(e,t,r,n,o,i,a,l,d,p)=>{let m,u,h,_;if(e==="VALID"&&(e=0),typeof e=="number"){m={top:e,bottom:e,left:e,right:e,front:e,back:e};let y=Wu([t,r,n,1],[l,d,p],1,[o,i,a],e);u=y[0],h=y[1],_=y[2]}else if(Array.isArray(e)){if(!e.every((g,x,$)=>g===$[0]))throw Error(`Unsupported padding parameter: ${e}`);m={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let y=Wu([t,r,n,1],[l,d,p],1,[o,i,a],e[0]);u=y[0],h=y[1],_=y[2]}else if(e==="SAME_UPPER"){u=Math.ceil(t/o),h=Math.ceil(r/i),_=Math.ceil(n/a);let y=(u-1)*o+l-t,g=(h-1)*i+d-r,x=(_-1)*a+p-n,$=Math.floor(y/2),v=y-$,S=Math.floor(g/2),T=g-S,C=Math.floor(x/2),A=x-C;m={top:S,bottom:T,left:C,right:A,front:$,back:v}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:m,outDepth:u,outHeight:h,outWidth:_}},Lu=(e,t,r,n,o,i=!1,a="channelsLast")=>{let l,d,p,m,u;if(a==="channelsLast")[l,d,p,m,u]=e;else if(a==="channelsFirst")[l,u,d,p,m]=e;else throw new Error(`Unknown dataFormat ${a}`);let[h,,_,y,g]=t,[x,$,v]=Vu(r),[S,T,C]=Vu(n),A=rn(_,S),P=rn(y,T),O=rn(g,C),{padInfo:U,outDepth:G,outHeight:q,outWidth:K}=uf(o,d,p,m,x,$,v,A,P,O),W=i?h*u:h,Y=[0,0,0,0,0];return a==="channelsFirst"?Y=[l,W,G,q,K]:a==="channelsLast"&&(Y=[l,G,q,K,W]),{batchSize:l,dataFormat:a,inDepth:d,inHeight:p,inWidth:m,inChannels:u,outDepth:G,outHeight:q,outWidth:K,outChannels:W,padInfo:U,strideDepth:x,strideHeight:$,strideWidth:v,filterDepth:_,filterHeight:y,filterWidth:g,effectiveFilterDepth:A,effectiveFilterHeight:P,effectiveFilterWidth:O,dilationDepth:S,dilationHeight:T,dilationWidth:C,inShape:e,outShape:Y,filterShape:t}},Gu=(e,t,r,n,o,i)=>{let a=i==="channelsLast",l=a?e[0].dims[3]:e[0].dims[1],d=!1,p=[64,1,1],m={x:r.map((v,S)=>S)},u=[Math.ceil(af(m.x.map(v=>r[v]))/p[0]),1,1];ue("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${u}`);let h=d?a&&l%4!==0?3:4:1,_=k.size(r),y=[{type:12,data:_},{type:12,data:n},{type:12,data:o},{type:12,data:t.strides},{type:12,data:t.dilations}];qe(t,y),y.push(...N(e[0].dims,e[1].dims));let g=["rank","rank"],x=e.length===3;x&&(y.push(...N(e[2].dims)),g.push("rank")),y.push(...N(r));let $=v=>{let S=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];je(t,S);let T=d?4:1,C=ye(e[0].dataType),A=E("x",e[0].dataType,e[0].dims.length,h===3?1:h),P=E("W",e[1].dataType,e[1].dims.length,T),O=[A,P],U=M("result",e[0].dataType,r.length,T),G="";if(x){let W=E("bias",e[2].dataType,e[2].dims.length,T);O.push(W),G+=` fn getBiasByOutputCoords(coords : array) -> ${d?`vec4<${C}>`:C} { return bias[${a?F("coords",4,5):F("coords",1,5)}${d?"/ 4":""}]; - }`}let j=ze(h,C),K=Ve(t,j,C);return` - ${L} + }`}let q=Pe(h,C),K=Fe(t,q,C);return` + ${G} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${A.getByIndices("aIndices")}; @@ -4885,7 +4890,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${x?"value = value + getBiasByOutputCoords(coords)":""}; ${K} result[global_idx] = f32(value); - }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${a};${h};${x}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:u[0],y:u[1],z:u[2]},programUniforms:y}),getShaderSource:$}}});var Fu,qu,ju=R(()=>{"use strict";te();oe();ae();lt();Fu=(e,t,r,n)=>{let o=e.length>2,i=o?"value += b[output_channel];":"",a=e[0].dims,l=e[1].dims,d=t.format==="NHWC",c=d?r[3]:r[1],m=c/t.group,u=d&&m>=4?ye(c):1,h=k.size(r)/u,w=[{type:12,data:h},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:m}];Ne(t,w),w.push(...V(a,[l[0],l[1],l[2],l[3]/u]));let y=o?["rank","rank","rank"]:["rank","rank"];w.push(...V([r[0],r[1],r[2],r[3]/u]));let g=x=>{let $=M("output",e[0].dataType,r.length,u),v=me($.type.tensor),S=Ve(t,$.type.value,v),T=E("x",e[0].dataType,a.length),C=E("w",e[1].dataType,l.length,u),A=[T,C];o&&A.push(E("b",e[2].dataType,e[2].dims,u));let P=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];We(t,P);let O=d?` + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${a};${h};${x}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:u[0],y:u[1],z:u[2]},programUniforms:y}),getShaderSource:$}}});var Fu,qu,ju=R(()=>{"use strict";te();oe();ae();bt();Fu=(e,t,r,n)=>{let o=e.length>2,i=o?"value += b[output_channel];":"",a=e[0].dims,l=e[1].dims,d=t.format==="NHWC",p=d?r[3]:r[1],m=p/t.group,u=d&&m>=4?me(p):1,h=k.size(r)/u,_=[{type:12,data:h},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:m}];qe(t,_),_.push(...N(a,[l[0],l[1],l[2],l[3]/u]));let y=o?["rank","rank","rank"]:["rank","rank"];_.push(...N([r[0],r[1],r[2],r[3]/u]));let g=x=>{let $=M("output",e[0].dataType,r.length,u),v=ye($.type.tensor),S=Fe(t,$.type.value,v),T=E("x",e[0].dataType,a.length),C=E("w",e[1].dataType,l.length,u),A=[T,C];o&&A.push(E("b",e[2].dataType,e[2].dims,u));let P=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];je(t,P);let O=d?` for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; @@ -4947,7 +4952,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${i} ${S} ${$.setByOffset("global_idx","value")} - }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${u}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:w}),getShaderSource:g}},qu=(e,t,r,n)=>{let o=e.length>2,i=ye(r[3]),a=ye(r[2]),l=k.size(r)/i/a,d=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/i],c=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/i],m=[r[0],r[1],r[2],r[3]/i],u=[{type:12,data:l},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Ne(t,u),u.push(...V(d,c,m));let h=(a-1)*t.strides[1]+c[1],w=y=>{let g=M("output",e[0].dataType,m.length,i),x=me(g.type.tensor),$=Ve(t,g.type.value,x),v=E("x",e[0].dataType,d.length,i),S=E("w",e[1].dataType,c.length,i),T=[v,S];o&&T.push(E("b",e[2].dataType,e[2].dims,i));let C=o?"value += b[output_channel];":"",A=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return We(t,A),` + }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${u}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:_}),getShaderSource:g}},qu=(e,t,r,n)=>{let o=e.length>2,i=me(r[3]),a=me(r[2]),l=k.size(r)/i/a,d=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/i],p=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/i],m=[r[0],r[1],r[2],r[3]/i],u=[{type:12,data:l},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];qe(t,u),u.push(...N(d,p,m));let h=(a-1)*t.strides[1]+p[1],_=y=>{let g=M("output",e[0].dataType,m.length,i),x=ye(g.type.tensor),$=Fe(t,g.type.value,x),v=E("x",e[0].dataType,d.length,i),S=E("w",e[1].dataType,p.length,i),T=[v,S];o&&T.push(E("b",e[2].dataType,e[2].dims,i));let C=o?"value += b[output_channel];":"",A=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return je(t,A),` ${y.registerUniforms(A).declareVariables(...T,g)} ${y.mainStart()} ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -4966,7 +4971,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, var values: array<${g.type.value}, ${a}>; let input_channel = output_channel; // Use constant instead of uniform can give better performance for w's height/width. - for (var w_height: u32 = 0u; w_height < ${c[0]}; w_height++) { + for (var w_height: u32 = 0u; w_height < ${p[0]}; w_height++) { let x_height = x_corner.x + i32(w_height); if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { for (var i = 0; i < ${h}; i++) { @@ -4977,7 +4982,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, x_vals[i] = ${v.type.value}(0); } } - for (var w_width: u32 = 0u; w_width < ${c[1]}; w_width++) { + for (var w_width: u32 = 0u; w_width < ${p[1]}; w_width++) { let w_val = ${S.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${a}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); @@ -4992,263 +4997,60 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${$} ${g.set("batch","row","col + i","output_channel","value")}; } - }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${i};${a};${h};${c[0]};${c[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:w}}});var of,vo,af,$o,xo,Ku,sf,uf,So,Yu=R(()=>{"use strict";oe();Vu();Hu();ir();ju();lt();on();ut();of=(e,t,r,n,o,i)=>{let a=e[0],l=e.slice(i?1:2,i?3:4),d=l.length,c=t[0],u=t.slice(2).map((y,g)=>y+(y-1)*(r[g]-1)),w=l.map((y,g)=>y+n[g]+n[g+d]).map((y,g)=>Math.floor((y-u[g]+o[g])/o[g]));return w.splice(0,0,a),w.splice(i?3:1,0,c),w},vo=[2,3,1,0],af=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let o=e[0].dims.length-2;if(t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},$o=(e,t)=>{let r=e.kernelShape.slice();r.length{let t=en(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,i=e.group,a=e.kernel_shape,l=e.pads,d=e.strides,c=e.w_is_const();return{autoPad:n,format:r,dilations:o,group:i,kernelShape:a,pads:l,strides:d,wIsConst:c,...t,cacheKey:`${e.format};${t.activation};`}},Ku=(e,t,r,n)=>{let o=r.format==="NHWC",i=of(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,o);if(r.group!==1){let A=[t[0]];if(o){let O=e.kernelCustomData.wT??e.compute(Pe(t[1],vo),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=O),A.push(O)}else A.push(t[1]);t.length===3&&A.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(qu(A,r,i,n),{inputs:A}):e.compute(Fu(A,r,i,n),{inputs:A});return}let a=t.length===3,l=t[0].dims[o?1:2],d=t[0].dims[o?2:3],c=t[0].dims[o?3:1],m=t[1].dims[2],u=t[1].dims[3],h=i[o?1:2],w=i[o?2:3],y=i[o?3:1],g=o&&m===l&&u===d&&r.pads[0]===0&&r.pads[1]===0;if(g||m===1&&u===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let A=i[0],P,O,U,L=[];if(o){let W=e.kernelCustomData.wT??e.compute(Pe(t[1],vo),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=W),g){let ee=l*d*c;P=t[0].reshape([1,A,ee]),O=W.reshape([1,ee,y]),U=[1,A,y]}else P=t[0].reshape([A,l*d,c]),O=W.reshape([1,c,y]),U=[A,h*w,y];L.push(P),L.push(O)}else P=t[0].reshape([A,c,l*d]),O=t[1].reshape([1,y,c]),U=[A,y,h*w],L.push(O),L.push(P);a&&L.push(t[2]);let j=U[2],K=L[0].dims[L[0].dims.length-1];j<8&&K<8?e.compute(nn(L,r,i,U,o,n),{inputs:L}):e.compute(or(L,r,i,U,o,n),{inputs:L});return}let x=!0,$=e.kernelCustomData.wT??e.compute(Pe(t[1],vo),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=$);let v=[t[0],$];a&&v.push(t[2]);let S=o?h*w:y,T=o?y:h*w,C=m*u*c;e.compute(Uu(v,r,i,S,T,C,a,x,n),{inputs:v})},sf=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=[0,t.pads[0],0,t.pads[1]],i=[1].concat(t.strides),a=[1].concat(t.dilations),l=[1].concat(t.kernelShape),d=$o({...t,pads:o,strides:i,dilations:a,kernelShape:l},n);Ku(e,n,d,c=>r?[c[0],c[2],c[3]]:[c[0],c[1],c[3]])},uf=(e,t,r)=>{let n=r.format==="NHWC"?"channelsLast":"channelsFirst",o=$o(r,t),i=r.autoPad==="NOTSET"?r.pads:r.autoPad,a=Lu(t[0].dims,t[1].dims,r.strides,r.dilations,i,!1,n);e.compute(Gu(t,o,a.outShape,[a.filterDepth,a.filterHeight,a.filterWidth],[a.padInfo.front,a.padInfo.top,a.padInfo.left],n))},So=(e,t)=>{if(af(e.inputs,t),e.inputs[0].dims.length===3)sf(e,t);else if(e.inputs[0].dims.length===5)uf(e,e.inputs,t);else{let r=$o(t,e.inputs);Ku(e,e.inputs,r)}}});var lf,Zu,Xu=R(()=>{"use strict";te();je();ae();lt();er();_o();ir();lf=(e,t=!1,r,n,o=4)=>{let i=$=>{switch($){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return` - let coord1 = vec4(coordX, coordY, col + 1, rowInner); - let coord2 = vec4(coordX, coordY, col + 2, rowInner); - let coord3 = vec4(coordX, coordY, col + 3, rowInner); - let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))]; - let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))]; - let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))]; - let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))]; - return ${n}(v0, v1, v2, v3); - `;default:throw new Error(`innerElementSize ${$} is not supported.`)}},a=e?` - let coord = vec4(batch, iXR, iXC, xCh); - `:` - let coord = vec4(batch, xCh, iXR, iXC); - `,l=e?` - let coords = vec4( - batch, - row / outWidth, - row % outWidth, - col); - `:` - let coords = vec4( - batch, - row, - col / outWidth, - col % outWidth); - `,d=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",c=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",m=e?"row":"col",u=e?"col":"row",h=` - let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; - let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; - let outRow = ${m} / outWidth; - let outCol = ${m} % outWidth; - - let WRow = ${u} / (uniforms.filter_dims[1] * inChannels); - let WCol = ${u} / inChannels % uniforms.filter_dims[1]; - let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); - let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); - if (xR < 0.0 || xR >= f32(${d}) || fract(xR) > 0.0) { - return ${n}(0.0); - } - if (xC < 0.0 || xC >= f32(${c}) || fract(xC) > 0.0) { - return ${n}(0.0); - } - let iXR = i32(xR); - let iXC = i32(xC); - let xCh = ${u} % inChannels; - ${a} - return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${o}];`,w=e?` - let col = colIn * ${o}; - if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { - ${h} - } - return ${n}(0.0);`:` - let col = colIn * ${o}; - if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { - ${h} - } - return ${n}(0.0);`,y=` - let col = colIn * ${o}; - let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; - let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); - let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; - if (${e?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { - let rowInner = row % inChannels; - let coord = vec4(coordX, coordY, col, rowInner); - ${i(o)} - } - return ${n}(0.0); - `,g=Ve(r,n);return` - fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} { - ${e?w:y} - } - - fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} { - ${e?y:w} - } - - fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) { - let col = colIn * ${o}; - if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { - var value = valueInput; - let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; - ${l} - ${tn(t)} - ${g} - result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${o}] = value; - } - }`},Zu=(e,t,r,n,o,i,a,l)=>{let d=t.format==="NHWC",c=d?e[0].dims[3]:e[0].dims[1],m=r[0],u=d?r[2]:r[3],h=d?r[1]:r[2],w=d?r[3]:r[1],y=d&&c%4===0&&c%3&&w%4===0,g=d?w:u*h,x=d?u*h:w,$=[8,8,1],v=n<=8?[4,1,1]:[4,4,1],S=[Math.ceil(g/$[0]/v[0]),Math.ceil(x/$[1]/v[1]),Math.ceil(m/$[2]/v[2])];se("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${S}`);let T=y?4:1,C=Math.max($[0]*T,$[1]),A=y?4:1,P=[t.kernelShape[d?1:2],t.kernelShape[d?2:3]],O=[P[0]+(t.dilations[0]<=1?0:(P[0]-1)*(t.dilations[0]-1)),P[1]+(t.dilations[1]<=1?0:(P[1]-1)*(t.dilations[1]-1))],U=[O[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),O[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],L=[{type:6,data:n},{type:6,data:o},{type:6,data:i},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:P},{type:6,data:U}];Ne(t,L),L.push(...V(e[0].dims,e[1].dims));let j=["rank","rank"];a&&(L.push(...V(e[2].dims)),j.push("rank")),L.push(...V(r));let K=W=>{let ee=E("x",e[0].dataType,e[0].dims.length,A),ue=E("w",e[1].dataType,e[1].dims.length,1),Z=M("result",e[0].dataType,r.length,A),J=[ee,ue],Q="";if(a){let Ae=E("bias",e[2].dataType,e[2].dims.length,A);J.push(Ae),Q+=` - fn getBiasByOutputCoords(coords : vec4) -> ${Ae.type.value} { - return bias[coords.${d?"w":"y"}${y?"/ 4":""}]; - }`}let ne=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:P.length},{name:"pads",type:"i32",length:U.length}];We(t,ne);let we=me(e[0].dataType,1);if(we!=="f16"&&we!=="f32")throw new Error(`elemType ${we} is not supported.`);return` - ${rn("uniforms.result_strides")} - ${W.registerUniforms(ne).declareVariables(...J,Z)}; - ${Q} - ${lf(d,a,t,ee.type.value,T)} - ${y?rr(v,$,we,void 0,!d,C):nr(v,$,we,void 0,!d,C,!1,void 0,l)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${v};${$};${y}`,inputDependencies:j},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:S[0],y:S[1],z:S[2]},programUniforms:L}),getShaderSource:K}}});var df,To,Qu=R(()=>{"use strict";te();je();oe();ae();df=(e,t,r,n,o,i=!1,a,l,d=!1)=>{let c=d?1:2,m=d?2:3,u=d?3:1,h=i?2:1,w=` - fn setOutputAtIndex(flatIndex : u32, value : ${i?`vec4<${a}>`:a}) { - result[flatIndex] = ${i?`vec4<${a}>`:a}(value); - }`;n&&(w+=` - fn getBiasByOutputCoords(coords : vec4) -> ${i?`vec4<${a}>`:a} { - return bias[coords.${d?"w":"y"}${i?"/ 4":""}]; - }`);let y=i?4:1,g=E("W",t[1].dataType,t[1].dims.length,y),x=E("Dy",t[0].dataType,t[0].dims.length,y),$=[x,g];n&&$.push(E("bias",t[2].dataType,[r[u]].length,y));let v=M("result",t[0].dataType,r.length,y),S=`{ - let batch: u32 = ${o?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; - let r = ${o?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; - let c = ${o?"global_id.y":"workgroup_id.y"} * ${h}; - let d1: u32 = ${o?"global_id.x":"workgroup_id.x"} * 4; - - let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads); - - // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). - // ? = to be determined. : = across all values in that axis. - var dotProd: array, ${h}>; - for (var i = 0; i < ${h}; i++) { - dotProd[i] = vec4<${a}>(0.0); - } - for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { - var dyR = (${a}(dyCorner.x) + ${a}(wR)) / ${a}(uniforms.strides.x); - let wRPerm = uniforms.filter_dims[0] - 1 - wR; - if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[1]) || - fract(dyR) > 0.0 || wRPerm < 0) { - continue; - } - let idyR: u32 = u32(dyR); - - for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) { - let dyC = (${a}(dyCorner.y) + ${a}(wC)) / ${a}(uniforms.strides.y); - let dyC2 = (${a}(dyCorner.y) + 1.0 + ${a}(wC)) / ${a}(uniforms.strides.y); - let wCPerm = uniforms.filter_dims[1] - 1 - wC; - if (wCPerm < 0) { - continue; - } - var bDyCVal = true; - var bDyCVal2 = true; - if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[2]) || - fract(dyC) > 0.0) { - bDyCVal = false; - } - if (dyC2 < 0.0 || dyC2 >= ${a}(uniforms.Dy_shape[2]) || - fract(dyC2) > 0.0) { - bDyCVal2 = false; - } - - let idyC: u32 = u32(dyC); - let idyC2: u32 = u32(dyC2); - if (bDyCVal && bDyCVal2) { - let d2Length = uniforms.Dy_shape[3]; - for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { - let wValue0 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; - let wValue1 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; - let wValue2 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; - let wValue3 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; - - var xValue = ${x.get("batch","idyR","idyC","d2")}; - let tmpval = vec4<${a}>(dot(xValue, wValue0), - dot(xValue, wValue1), - dot(xValue, wValue2), - dot(xValue, wValue3)); - dotProd[0] = dotProd[0] + tmpval; - - xValue = ${x.get("batch","idyR","idyC2","d2")}; - - dotProd[1] = dotProd[1] + vec4<${a}>(dot(xValue, wValue0), - dot(xValue, wValue1), - dot(xValue, wValue2), - dot(xValue, wValue3)); - } - } else if (bDyCVal) { - let d2Length = uniforms.Dy_shape[${u}]; - for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { - let wValue0 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; - let wValue1 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; - let wValue2 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; - let wValue3 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; - - var xValue = ${x.get("batch","idyR","idyC","d2")}; - let tmpval = vec4<${a}>(dot(xValue, wValue0), - dot(xValue, wValue1), - dot(xValue, wValue2), - dot(xValue, wValue3)); - dotProd[0] = dotProd[0] + tmpval; - } - } else if (bDyCVal2) { - let d2Length = uniforms.Dy_shape[3]; - for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { - let wValue0 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; - let wValue1 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; - let wValue2 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; - let wValue3 = ${g.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; - - var xValue = ${x.get("batch","idyR","idyC2","d2")}; - let tmpval = vec4<${a}>(dot(xValue, wValue0), - dot(xValue, wValue1), - dot(xValue, wValue2), - dot(xValue, wValue3)); - dotProd[1] = dotProd[1] + tmpval; - } - } - } - } - - for (var i: u32 = 0; i < ${h}; i = i + 1) { - let value = dotProd[i] + ${n?"bias[c+i]":`vec4<${a}>(0.0)`}; - ${v.set("batch","r","c + i","d1","value")}; - } - }`,T=` - let outputIndices = ${v.offsetToIndices("global_idx")}; - let batch = ${v.indicesGet("outputIndices",0)}; - let d1 = ${v.indicesGet("outputIndices",u)}; - let r = ${v.indicesGet("outputIndices",c)}; - let c = ${v.indicesGet("outputIndices",m)}; - let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; - let dyRCorner = dyCorner.x; - let dyCCorner = dyCorner.y; - let groupId = d1 / uniforms.output_channels_per_group; - let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; - // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). - // ? = to be determined. : = across all values in that axis. - var dotProd = ${a}(0.0); - for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { - if (wR % uniforms.dilations.x != 0) { - continue; - } - let dyR = (${a}(dyRCorner) + ${a}(wR)) / ${a}(uniforms.strides[0]); - let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; - if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[${c}]) || fract(dyR) > 0.0 || - wRPerm < 0) { - continue; - } - let idyR: u32 = u32(dyR); - - for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { - if (wC % uniforms.dilations.y != 0) { + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${i};${a};${h};${p[0]};${p[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:_}}});var lf,yo,df,_o,wo,Ku,cf,pf,vo,Yu=R(()=>{"use strict";oe();Nu();Hu();tn();ju();bt();en();ut();lf=(e,t,r,n,o,i)=>{let a=e[0],l=e.slice(i?1:2,i?3:4),d=l.length,p=t[0],u=t.slice(2).map((y,g)=>y+(y-1)*(r[g]-1)),_=l.map((y,g)=>y+n[g]+n[g+d]).map((y,g)=>Math.floor((y-u[g]+o[g])/o[g]));return _.splice(0,0,a),_.splice(i?3:1,0,p),_},yo=[2,3,1,0],df=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let o=e[0].dims.length-2;if(t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},_o=(e,t)=>{let r=e.kernelShape.slice();r.length{let t=Qr(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,i=e.group,a=e.kernel_shape,l=e.pads,d=e.strides,p=e.w_is_const();return{autoPad:n,format:r,dilations:o,group:i,kernelShape:a,pads:l,strides:d,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},Ku=(e,t,r,n)=>{let o=r.format==="NHWC",i=lf(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,o);if(r.group!==1){let A=[t[0]];if(o){let O=e.kernelCustomData.wT??e.compute(Ee(t[1],yo),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=O),A.push(O)}else A.push(t[1]);t.length===3&&A.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(qu(A,r,i,n),{inputs:A}):e.compute(Fu(A,r,i,n),{inputs:A});return}let a=t.length===3,l=t[0].dims[o?1:2],d=t[0].dims[o?2:3],p=t[0].dims[o?3:1],m=t[1].dims[2],u=t[1].dims[3],h=i[o?1:2],_=i[o?2:3],y=i[o?3:1],g=o&&m===l&&u===d&&r.pads[0]===0&&r.pads[1]===0;if(g||m===1&&u===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let A=i[0],P,O,U,G=[];if(o){let W=e.kernelCustomData.wT??e.compute(Ee(t[1],yo),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=W),g){let Y=l*d*p;P=t[0].reshape([1,A,Y]),O=W.reshape([1,Y,y]),U=[1,A,y]}else P=t[0].reshape([A,l*d,p]),O=W.reshape([1,p,y]),U=[A,h*_,y];G.push(P),G.push(O)}else P=t[0].reshape([A,p,l*d]),O=t[1].reshape([1,y,p]),U=[A,y,h*_],G.push(O),G.push(P);a&&G.push(t[2]);let q=U[2],K=G[0].dims[G[0].dims.length-1];q<8&&K<8?e.compute(Jr(G,r,i,U,o,n),{inputs:G}):e.compute(tr(G,r,i,U,o,n),{inputs:G});return}let x=!0,$=e.kernelCustomData.wT??e.compute(Ee(t[1],yo),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=$);let v=[t[0],$];a&&v.push(t[2]);let S=o?h*_:y,T=o?y:h*_,C=m*u*p;e.compute(Uu(v,r,i,S,T,C,a,x,n),{inputs:v})},cf=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=[0,t.pads[0],0,t.pads[1]],i=[1].concat(t.strides),a=[1].concat(t.dilations),l=[1].concat(t.kernelShape),d=_o({...t,pads:o,strides:i,dilations:a,kernelShape:l},n);Ku(e,n,d,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},pf=(e,t,r)=>{let n=r.format==="NHWC"?"channelsLast":"channelsFirst",o=_o(r,t),i=r.autoPad==="NOTSET"?r.pads:r.autoPad,a=Lu(t[0].dims,t[1].dims,r.strides,r.dilations,i,!1,n);e.compute(Gu(t,o,a.outShape,[a.filterDepth,a.filterHeight,a.filterWidth],[a.padInfo.front,a.padInfo.top,a.padInfo.left],n))},vo=(e,t)=>{if(df(e.inputs,t),e.inputs[0].dims.length===3)cf(e,t);else if(e.inputs[0].dims.length===5)pf(e,e.inputs,t);else{let r=_o(t,e.inputs);Ku(e,e.inputs,r)}}});var Zu,Qu=R(()=>{"use strict";te();Je();oe();ae();Zu=(e,t,r)=>{let n=e.length>2,o=t.outputShape,i=t.format==="NHWC",a=t.group,l=e[1].dims,d=l[2]/a,p=l[3],m=i?me(p):1,u=k.size(o)/m,h=[Math.ceil(u/64),1,1];ue("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${h}`);let _=["rank","rank"],y=[t.strides[0],t.strides[1]],g=[t.kernelShape[i?1:2],t.kernelShape[i?2:3]],x=[t.dilations[0],t.dilations[1]],$=[g[0]+(t.dilations[0]<=1?0:(t.kernelShape[i?1:2]-1)*(t.dilations[0]-1)),g[1]+(t.dilations[1]<=1?0:(t.kernelShape[i?2:3]-1)*(t.dilations[1]-1))],v=[$[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),$[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],S=[{type:12,data:u},{type:12,data:y},{type:12,data:g},{type:12,data:x},{type:12,data:$},{type:6,data:v},{type:12,data:d},{type:12,data:p},...N(e[0].dims,e[1].dims)];n&&(S.push(...N(e[2].dims)),_.push("rank")),S.push(...N(o));let T=C=>{let A=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:y.length},{name:"filter_dims",type:"u32",length:g.length},{name:"dilations",type:"u32",length:g.length},{name:"effective_filter_dims",type:"u32",length:$.length},{name:"pads",type:"i32",length:v.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],P=ye(e[0].dataType),O=i?1:2,U=i?2:3,G=i?3:1,q=E("W",e[1].dataType,e[1].dims.length,m),K=E("Dy",e[0].dataType,e[0].dims.length),W=[K,q];n&&W.push(E("bias",e[2].dataType,[o[G]].length,m));let Y=M("result",e[0].dataType,o.length,m),se=` + let outputIndices = ${Y.offsetToIndices(`global_idx * ${m}`)}; + let batch = ${Y.indicesGet("outputIndices",0)}; + let d1 = ${Y.indicesGet("outputIndices",G)}; + let r = ${Y.indicesGet("outputIndices",O)}; + let c = ${Y.indicesGet("outputIndices",U)}; + let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; + let dyRCorner = dyCorner.x; + let dyCCorner = dyCorner.y; + let groupId = d1 / uniforms.output_channels_per_group; + let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd = ${Y.type.value}(0.0); + for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { continue; } - let dyC = (${a}(dyCCorner) + ${a}(wC)) / ${a}(uniforms.strides.y); - let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; - if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[${m}]) || - fract(dyC) > 0.0 || wCPerm < 0) { + let dyR = (${P}(dyRCorner) + ${P}(wR)) / ${P}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${P}(uniforms.Dy_shape[${O}]) || fract(dyR) > 0.0 || + wRPerm < 0) { continue; } - let idyC: u32 = u32(dyC); - var inputChannel = groupId * uniforms.input_channels_per_group; - for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { - let xValue = ${d?x.get("batch","idyR","idyC","inputChannel"):x.get("batch","inputChannel","idyR","idyC")}; - let wValue = ${g.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; - dotProd = dotProd + xValue * wValue; - inputChannel = inputChannel + 1; + let idyR: u32 = u32(dyR); + + for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${P}(dyCCorner) + ${P}(wC)) / ${P}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${P}(uniforms.Dy_shape[${U}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { + let xValue = ${i?K.get("batch","idyR","idyC","inputChannel"):K.get("batch","inputChannel","idyR","idyC")}; + let w_offset = ${q.indicesToOffset(`${q.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${q.getByOffset(`w_offset / ${m}`)}; + dotProd = dotProd + xValue * wValue; + inputChannel = inputChannel + 1; + } } } - } - let value = dotProd + ${n?"bias[d1]":`${a}(0.0)`}; - ${v.setByOffset("global_idx","value")}; - `;return` - ${e.registerUniforms(l).declareVariables(...$,v)} - ${w} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; - ${i?S:T}}`},To=(e,t,r)=>{let n=e.length>2,o=t.outputShape,i=k.size(o),a=[Math.ceil(i/64),1,1];se("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${a}`);let l=t.format==="NHWC",d=["rank","rank"],c=[t.strides[0],t.strides[1]],m=[t.kernelShape[l?1:2],t.kernelShape[l?2:3]],u=[t.dilations[0],t.dilations[1]],h=[m[0]+(t.dilations[0]<=1?0:(t.kernelShape[l?1:2]-1)*(t.dilations[0]-1)),m[1]+(t.dilations[1]<=1?0:(t.kernelShape[l?2:3]-1)*(t.dilations[1]-1))],w=[h[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),h[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],y=!1,g=t.group,x=e[1].dims,$=x[0]/g,v=x[1],S=[{type:12,data:i},{type:12,data:c},{type:12,data:m},{type:12,data:u},{type:12,data:h},{type:6,data:w},{type:12,data:$},{type:12,data:v},...V(e[0].dims,e[1].dims)];n&&(S.push(...V(e[2].dims)),d.push("rank")),S.push(...V(o));let T=a[1]===1&&a[2]===1,C=A=>{let P=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:c.length},{name:"filter_dims",type:"u32",length:m.length},{name:"dilations",type:"u32",length:m.length},{name:"effective_filter_dims",type:"u32",length:h.length},{name:"pads",type:"i32",length:w.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],O=me(e[0].dataType);return`${df(A,e,o,n,T,y,O,P,l)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:d},getRunData:()=>({dispatchGroup:{x:a[0],y:a[1],z:a[2]},outputs:[{dims:r?r(o):o,dataType:e[0].dataType}],programUniforms:S}),getShaderSource:C}}});var cf,pf,mf,Ju,el,ff,hf,gf,bf,tl,rl=R(()=>{"use strict";Xu();Qu();lt();ut();cf=(e,t,r,n,o,i)=>(e-1)*t+r+(n-1)*o+1-i,pf=(e,t,r,n,o)=>{let i=Math.floor(e/2);t==="SAME_UPPER"?(r[n]=i,r[o]=e-i):t==="SAME_LOWER"&&(r[n]=e-i,r[o]=i)},mf=(e,t,r,n,o,i,a,l,d,c)=>{let m=e.length-2,u=c.length===0;d.length{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((u,h)=>u*h,1)===0){r.length=0;for(let u=2;uu+h,0)===0){let u=t[0].dims.length-2;d=new Array(u).fill(1)}let c=e.strides.slice();if(c.reduce((u,h)=>u+h,0)===0){let u=t[0].dims.length-2;c=new Array(u).fill(1)}mf(l,r,d,e.autoPad,e.group,o,c,n,a,i);let m=Object.assign({},e);return Object.assign(m,{kernelShape:r,pads:o,outputPadding:a,outputShape:i,dilations:d,strides:c}),m},el=e=>{let t=en(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,i=e.group,a=e.kernelShape,l=e.pads,d=e.strides,c=e.wIsConst(),m=e.outputPadding,u=e.outputShape;return{autoPad:n,format:r,dilations:o,group:i,kernelShape:a,outputPadding:m,outputShape:u,pads:l,strides:d,wIsConst:c,...t,cacheKey:`${e.format};${t.activation};`}},ff=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let o=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let i=e[0].dims.length-2;if(t.dilations.reduce((m,u)=>m+u,0)>0&&t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.reduce((m,u)=>m+u,0)>0&&t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.reduce((m,u)=>m+u,0)>0&&t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.outputPadding.length!==i&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${i}D`);if(t.kernelShape.reduce((m,u)=>m+u,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},hf=[2,3,1,0],gf=(e,t,r)=>{let n=Ju(r,t),o=r.format==="NHWC",i=n.outputShape,a=i[o?3:1],l=t[0].dims[o?3:1];if(n.group!==1||a===1&&l===1){e.compute(To(t,n));return}let d=i[o?1:2],c=i[o?2:3],m=t[1].dims[2],u=t[1].dims[3],h=o?d*c:a,w=o?a:d*c,y=m*u*l,g=!0,x=e.kernelCustomData.wT??e.compute(Pe(t[1],hf),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=x);let $=[t[0],x],v=t.length===3;v&&(!o&&t[2].dims.length===1?$.push(t[2].reshape([t[2].dims[0],1,1])):$.push(t[2])),e.compute(Zu($,n,i,h,w,y,v,g),{inputs:$})},bf=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=t.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let i=t.dilations;(i.length===0||i[0]===0)&&(i=[1]);let a=t.strides;(a.length===0||a[0]===0)&&(a=[1]);let l=t.pads;l.length===0&&(l=[0,0]),l=[0,l[0],0,l[1]],a=[1].concat(a),i=[1].concat(i),o=[1].concat(o);let d=Ju({...t,pads:l,strides:a,dilations:i,kernelShape:o},n);e.compute(To(n,d,c=>r?[c[0],c[2],c[3]]:[c[0],c[1],c[3]]))},tl=(e,t)=>{ff(e.inputs,t),e.inputs[0].dims.length===3?bf(e,t):gf(e,e.inputs,t)}});var yf,nl,ol,il=R(()=>{"use strict";te();oe();Ie();ae();yf=(e,t,r,n)=>{let o=k.size(t),i=t.length,a=E("input",e,i),l=M("output",e,i),d=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),c=k.normalizeAxis(d,i),m=u=>{let h=` i32(${a.indicesGet("inputIndices","uniforms.axis")}) `,w=F("uniforms.input_shape","uniforms.axis",i),y=n.reverse?h+(n.exclusive?" + 1":""):"0",g=n.reverse?w:h+(n.exclusive?"":" + 1");return` + let value = dotProd${n?` + bias[d1 / ${m}]`:""}; + ${Y.setByOffset("global_idx","value")}; + `;return` + ${C.registerUniforms(A).declareVariables(...W,Y)} + ${C.mainStart()} + ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${se}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${m}`,inputDependencies:_},getRunData:()=>({dispatchGroup:{x:h[0],y:h[1],z:h[2]},outputs:[{dims:r?r(o):o,dataType:e[0].dataType}],programUniforms:S}),getShaderSource:T}}});var mf,ff,hf,Xu,Ju,gf,el,bf,tl,rl=R(()=>{"use strict";Qu();bt();ut();mf=(e,t,r,n,o,i)=>(e-1)*t+r+(n-1)*o+1-i,ff=(e,t,r,n,o)=>{let i=Math.floor(e/2);t==="SAME_UPPER"?(r[n]=i,r[o]=e-i):t==="SAME_LOWER"&&(r[n]=e-i,r[o]=i)},hf=(e,t,r,n,o,i,a,l,d,p)=>{let m=e.length-2,u=p.length===0;d.length{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((u,h)=>u*h,1)===0){r.length=0;for(let u=2;uu+h,0)===0){let u=t[0].dims.length-2;d=new Array(u).fill(1)}let p=e.strides.slice();if(p.reduce((u,h)=>u+h,0)===0){let u=t[0].dims.length-2;p=new Array(u).fill(1)}hf(l,r,d,e.autoPad,e.group,o,p,n,a,i);let m=Object.assign({},e);return Object.assign(m,{kernelShape:r,pads:o,outputPadding:a,outputShape:i,dilations:d,strides:p}),m},Ju=e=>{let t=Qr(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,i=e.group,a=e.kernelShape,l=e.pads,d=e.strides,p=e.wIsConst(),m=e.outputPadding,u=e.outputShape;return{autoPad:n,format:r,dilations:o,group:i,kernelShape:a,outputPadding:m,outputShape:u,pads:l,strides:d,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},gf=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let o=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let i=e[0].dims.length-2;if(t.dilations.reduce((m,u)=>m+u,0)>0&&t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.reduce((m,u)=>m+u,0)>0&&t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.reduce((m,u)=>m+u,0)>0&&t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.outputPadding.length!==i&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${i}D`);if(t.kernelShape.reduce((m,u)=>m+u,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},el=(e,t,r,n)=>{let o=e.kernelCustomData.wT??e.compute(Ee(t[1],[2,3,0,1]),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let i=[t[0],o];t.length===3&&i.push(t[2]),e.compute(Zu(i,r,n),{inputs:i})},bf=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=t.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let i=t.dilations;(i.length===0||i[0]===0)&&(i=[1]);let a=t.strides;(a.length===0||a[0]===0)&&(a=[1]);let l=t.pads;l.length===0&&(l=[0,0]),l=[0,l[0],0,l[1]],a=[1].concat(a),i=[1].concat(i),o=[1].concat(o);let d=Xu({...t,pads:l,strides:a,dilations:i,kernelShape:o},n);el(e,n,d,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},tl=(e,t)=>{if(gf(e.inputs,t),e.inputs[0].dims.length===3)bf(e,t);else{let r=Xu(t,e.inputs);el(e,e.inputs,r)}}});var yf,nl,ol,il=R(()=>{"use strict";te();oe();Se();ae();yf=(e,t,r,n)=>{let o=k.size(t),i=t.length,a=E("input",e,i),l=M("output",e,i),d=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),p=k.normalizeAxis(d,i),m=u=>{let h=` i32(${a.indicesGet("inputIndices","uniforms.axis")}) `,_=F("uniforms.input_shape","uniforms.axis",i),y=n.reverse?h+(n.exclusive?" + 1":""):"0",g=n.reverse?_:h+(n.exclusive?"":" + 1");return` ${u.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(a,l)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} @@ -5261,12 +5063,12 @@ fn main(@builtin(local_invocation_id) localId : vec3, sum = sum + ${a.getByIndices("inputIndices")}; } ${l.setByOffset("global_idx","sum")}; - }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:c},...V(t,t)]}),getShaderSource:m}},nl=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,o=e.inputs[1];e.compute(yf(n,r,o,t),{inputs:[0]})},ol=e=>{let t=e.exclusive===1,r=e.reverse===1;return re({exclusive:t,reverse:r})}});var wf,_f,vf,al,sl,ul=R(()=>{"use strict";te();oe();Ie();ae();wf=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},_f=(e,t,r,n)=>{let o=[];o.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { + }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:p},...N(t,t)]}),getShaderSource:m}},nl=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,o=e.inputs[1];e.compute(yf(n,r,o,t),{inputs:[0]})},ol=e=>{let t=e.exclusive===1,r=e.reverse===1;return J({exclusive:t,reverse:r})}});var _f,wf,vf,al,sl,ul=R(()=>{"use strict";te();oe();Se();ae();_f=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},wf=(e,t,r,n)=>{let o=[];o.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { var a: ${r.type.indices};`);for(let i=0;i{let r,n,o,i,a,l,d=t.format==="NHWC",c=t.blocksize,m=t.mode==="DCR";d?([r,n,o,i]=e.dims,a=m?[r,n,o,c,c,i/c**2]:[r,n,o,i/c**2,c,c],l=m?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,o,i]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],a=m?[r,c,c,i/c**2,n,o]:[r,i/c**2,c,c,n,o],l=m?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let u=e.reshape(a),h=u.dims.length,w=e.dataType,y=E("a",w,h),g=M("output",w,h),x=$=>` +`)},vf=(e,t)=>{let r,n,o,i,a,l,d=t.format==="NHWC",p=t.blocksize,m=t.mode==="DCR";d?([r,n,o,i]=e.dims,a=m?[r,n,o,p,p,i/p**2]:[r,n,o,i/p**2,p,p],l=m?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,o,i]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],a=m?[r,p,p,i/p**2,n,o]:[r,i/p**2,p,p,n,o],l=m?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let u=e.reshape(a),h=u.dims.length,_=e.dataType,y=E("a",_,h),g=M("output",_,h),x=$=>` ${$.registerUniform("output_size","u32").declareVariables(y,g)} - ${_f(l,h,y,g)} + ${wf(l,h,y,g)} ${$.mainStart()} ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -5275,7 +5077,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, let aIndices = perm(indices); ${g.setByOffset("global_idx",y.getByIndices("aIndices"))} - }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:$=>{let v=d?[r,n*c,o*c,i/c**2]:[r,i/c**2,n*c,o*c],S=k.size(v),T=u.dims,C=k.sortBasedOnPerm(T,l);return{outputs:[{dims:v,dataType:$[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...V(T,C)]}},getShaderSource:x}},al=(e,t)=>{wf(e.inputs),e.compute(vf(e.inputs[0],t))},sl=e=>re({blocksize:e.blocksize,mode:e.mode,format:e.format})});var Io,sn,ll,$f,xf,Co,Ao,dl,Sf,cl,pl,ml=R(()=>{"use strict";te();oe();Ie();ae();Io="[a-zA-Z]|\\.\\.\\.",sn="("+Io+")+",ll="^"+sn+"$",$f="("+sn+",)*"+sn,xf="^"+$f+"$",Co=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,r){let n=this.symbolToIndices.get(t);n===void 0?n=[r]:n.push(r),this.symbolToIndices.set(t,n)}},Ao=class{constructor(t,r){this.equation=r;this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[n,o]=r.includes("->")?r.split("->",2):[r,""];if(!n.match(RegExp(xf)))throw new Error("Invalid LHS term");if(n.split(",").forEach((l,d)=>{let c=t[d].dims.slice();if(!l.match(RegExp(ll)))throw new Error("Invalid LHS term");let m=this.processTerm(l,!0,c,d);this.lhs.push(m)}),o==="")o+=[...this.symbolToInfo.entries()].filter(([l,d])=>d.count===1||l==="...").map(([l])=>l).join("");else if(!o.match(RegExp(sn)))throw new Error("Invalid RHS");o.match(RegExp(Io,"g"))?.forEach(l=>{if(l==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let d=this.symbolToInfo.get(l);if(d===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(d.dimValue)}}),this.rhs=this.processTerm(o,!1,this.outputDims)}addSymbol(t,r,n){let o=this.symbolToInfo.get(t);if(o!==void 0){if(o.dimValue!==r&&o.count!==1)throw new Error("Dimension mismatch");o.count++,o.inputIndices.push(n)}else o={count:1,dimValue:r,inputIndices:[n]};this.symbolToInfo.set(t,o)}processTerm(t,r,n,o=-1){let i=n.length,a=!1,l=[],d=0;if(!t.match(RegExp(ll))&&!r&&t!=="")throw new Error("Invalid LHS term");let c=t.match(RegExp(Io,"g")),m=new Co(o);return c?.forEach((u,h)=>{if(u==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let w=i-c.length+1;if(w<0)throw new Error("Ellipsis out of bounds");if(l=n.slice(d,d+w),this.hasEllipsis){if(this.ellipsisDims.length!==l.length||this.ellipsisDims.toString()!==l.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=l;else throw new Error("Ellipsis must be specified in the LHS");for(let y=0;ye+"_max",Sf=(e,t,r,n)=>{let i=e.map(m=>m.length).map((m,u)=>E(`input${u}`,t,m)),a=k.size(n),l=M("output",t,n.length),d=[...r.symbolToInfo.keys()].filter(m=>!r.rhs.symbolToIndices.has(m)),c=m=>{let u=[],h="var prod = 1.0;",w="var sum = 0.0;",y="sum += prod;",g=[],x=[],$=[],v=[],S=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((C,A)=>{if(r.rhs.symbolToIndices.has(A)){let P=r.rhs.symbolToIndices.get(A)?.[0];P!==void 0&&r.lhs.forEach((O,U)=>{if(C.inputIndices.includes(U)){let L=O.symbolToIndices.get(A);if(L===void 0)throw new Error("Invalid symbol error");L.forEach(j=>{u.push(`${i[U].indicesSet(`input${U}Indices`,j,l.indicesGet("outputIndices",P))}`)})}})}else r.lhs.forEach((P,O)=>{if(C.inputIndices.includes(O)){let U=P.symbolToIndices.get(A);if(U===void 0)throw new Error("Invalid symbol error");U.forEach(L=>{g.push(`${i[O].indicesSet(`input${O}Indices`,L,`${A}`)}`)}),v.push(`prod *= ${i[O].getByIndices(`input${O}Indices`)};`)}}),x.push(`for(var ${A}: u32 = 0; ${A} < uniforms.${dl(A)}; ${A}++) {`),$.push("}")});let T=S?[...u,`let sum = ${i.map((C,A)=>C.getByIndices(`input${A}Indices`)).join(" * ")};`]:[...u,w,...x,...g,h,...v,y,...$];return` + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:$=>{let v=d?[r,n*p,o*p,i/p**2]:[r,i/p**2,n*p,o*p],S=k.size(v),T=u.dims,C=k.sortBasedOnPerm(T,l);return{outputs:[{dims:v,dataType:$[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...N(T,C)]}},getShaderSource:x}},al=(e,t)=>{_f(e.inputs),e.compute(vf(e.inputs[0],t))},sl=e=>J({blocksize:e.blocksize,mode:e.mode,format:e.format})});var $o,nn,ll,$f,xf,xo,So,dl,Sf,cl,pl,ml=R(()=>{"use strict";te();oe();Se();ae();$o="[a-zA-Z]|\\.\\.\\.",nn="("+$o+")+",ll="^"+nn+"$",$f="("+nn+",)*"+nn,xf="^"+$f+"$",xo=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,r){let n=this.symbolToIndices.get(t);n===void 0?n=[r]:n.push(r),this.symbolToIndices.set(t,n)}},So=class{constructor(t,r){this.equation=r;this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[n,o]=r.includes("->")?r.split("->",2):[r,""];if(!n.match(RegExp(xf)))throw new Error("Invalid LHS term");if(n.split(",").forEach((l,d)=>{let p=t[d].dims.slice();if(!l.match(RegExp(ll)))throw new Error("Invalid LHS term");let m=this.processTerm(l,!0,p,d);this.lhs.push(m)}),o==="")o+=[...this.symbolToInfo.entries()].filter(([l,d])=>d.count===1||l==="...").map(([l])=>l).join("");else if(!o.match(RegExp(nn)))throw new Error("Invalid RHS");o.match(RegExp($o,"g"))?.forEach(l=>{if(l==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let d=this.symbolToInfo.get(l);if(d===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(d.dimValue)}}),this.rhs=this.processTerm(o,!1,this.outputDims)}addSymbol(t,r,n){let o=this.symbolToInfo.get(t);if(o!==void 0){if(o.dimValue!==r&&o.count!==1)throw new Error("Dimension mismatch");o.count++,o.inputIndices.push(n)}else o={count:1,dimValue:r,inputIndices:[n]};this.symbolToInfo.set(t,o)}processTerm(t,r,n,o=-1){let i=n.length,a=!1,l=[],d=0;if(!t.match(RegExp(ll))&&!r&&t!=="")throw new Error("Invalid LHS term");let p=t.match(RegExp($o,"g")),m=new xo(o);return p?.forEach((u,h)=>{if(u==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let _=i-p.length+1;if(_<0)throw new Error("Ellipsis out of bounds");if(l=n.slice(d,d+_),this.hasEllipsis){if(this.ellipsisDims.length!==l.length||this.ellipsisDims.toString()!==l.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=l;else throw new Error("Ellipsis must be specified in the LHS");for(let y=0;ye+"_max",Sf=(e,t,r,n)=>{let i=e.map(m=>m.length).map((m,u)=>E(`input${u}`,t,m)),a=k.size(n),l=M("output",t,n.length),d=[...r.symbolToInfo.keys()].filter(m=>!r.rhs.symbolToIndices.has(m)),p=m=>{let u=[],h="var prod = 1.0;",_="var sum = 0.0;",y="sum += prod;",g=[],x=[],$=[],v=[],S=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((C,A)=>{if(r.rhs.symbolToIndices.has(A)){let P=r.rhs.symbolToIndices.get(A)?.[0];P!==void 0&&r.lhs.forEach((O,U)=>{if(C.inputIndices.includes(U)){let G=O.symbolToIndices.get(A);if(G===void 0)throw new Error("Invalid symbol error");G.forEach(q=>{u.push(`${i[U].indicesSet(`input${U}Indices`,q,l.indicesGet("outputIndices",P))}`)})}})}else r.lhs.forEach((P,O)=>{if(C.inputIndices.includes(O)){let U=P.symbolToIndices.get(A);if(U===void 0)throw new Error("Invalid symbol error");U.forEach(G=>{g.push(`${i[O].indicesSet(`input${O}Indices`,G,`${A}`)}`)}),v.push(`prod *= ${i[O].getByIndices(`input${O}Indices`)};`)}}),x.push(`for(var ${A}: u32 = 0; ${A} < uniforms.${dl(A)}; ${A}++) {`),$.push("}")});let T=S?[...u,`let sum = ${i.map((C,A)=>C.getByIndices(`input${A}Indices`)).join(" * ")};`]:[...u,_,...x,...g,h,...v,y,...$];return` ${m.registerUniforms(d.map(C=>({name:`${dl(C)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...i,l)} ${m.mainStart()} @@ -5286,35 +5088,36 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${T.join(` `)}; ${l.setByOffset("global_idx","sum")}; - }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let m=d.filter(h=>r.symbolToInfo.has(h)).map(h=>({type:12,data:r.symbolToInfo.get(h)?.dimValue||0}));m.push({type:12,data:a});let u=e.map((h,w)=>[...V(h)]).reduce((h,w)=>h.concat(w),m);return u.push(...V(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:u}},getShaderSource:c}},cl=(e,t)=>{let r=new Ao(e.inputs,t.equation),n=r.outputDims,o=e.inputs.map((i,a)=>i.dims);e.compute(Sf(o,e.inputs[0].dataType,r,n))},pl=e=>{let t=e.equation.replace(/\s+/g,"");return re({equation:t})}});var Tf,fl,If,Cf,hl,gl=R(()=>{"use strict";te();oe();ae();Tf=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=r.length{let r=e.length-t.length,n=[];for(let o=0;oe.length>t.length?fl(e,t):fl(t,e),Cf=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=If(t,r),o=e[0].dataType,i=o===9?4:1,a=Math.ceil(k.size(n)/i),l=c=>{let m=E("input",o,t.length,i),u=M("output",o,n.length,i),h;if(o===9){let w=(y,g,x="")=>` - let outputIndices${g} = ${u.offsetToIndices(`outputOffset + ${g}u`)}; - let offset${g} = ${m.broadcastedIndicesToOffset(`outputIndices${g}`,u)}; - let index${g} = offset${g} / 4u; - let component${g} = offset${g} % 4u; - ${y}[${g}] = ${x}(${m.getByOffset(`index${g}`)}[component${g}]); - `;h=` - let outputOffset = global_idx * ${i}; + }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let m=d.filter(h=>r.symbolToInfo.has(h)).map(h=>({type:12,data:r.symbolToInfo.get(h)?.dimValue||0}));m.push({type:12,data:a});let u=e.map((h,_)=>[...N(h)]).reduce((h,_)=>h.concat(_),m);return u.push(...N(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:u}},getShaderSource:p}},cl=(e,t)=>{let r=new So(e.inputs,t.equation),n=r.outputDims,o=e.inputs.map((i,a)=>i.dims);e.compute(Sf(o,e.inputs[0].dataType,r,n))},pl=e=>{let t=e.equation.replace(/\s+/g,"");return J({equation:t})}});var Tf,fl,If,Cf,hl,gl=R(()=>{"use strict";te();oe();ae();Tf=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=r.length{let r=e.length-t.length,n=[];for(let o=0;oe.length>t.length?fl(e,t):fl(t,e),Cf=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=If(t,r),o=e[0].dataType,i=o===9||k.size(t)===1,a=o===9||t.length>0&&t[t.length-1]%4===0?4:1,l=i||n.length>0&&n[n.length-1]%4===0?4:1,d=Math.ceil(k.size(n)/l),p=u=>{let h=E("input",o,t.length,a),_=M("output",o,n.length,l),y;if(o===9){let g=(x,$,v="")=>` + let outputIndices${$} = ${_.offsetToIndices(`outputOffset + ${$}u`)}; + let offset${$} = ${h.broadcastedIndicesToOffset(`outputIndices${$}`,_)}; + let index${$} = offset${$} / 4u; + let component${$} = offset${$} % 4u; + ${x}[${$}] = ${v}(${h.getByOffset(`index${$}`)}[component${$}]); + `;y=` + let outputOffset = global_idx * ${l}; var data = vec4(0); - ${w("data",0,"u32")} - ${w("data",1,"u32")} - ${w("data",2,"u32")} - ${w("data",3,"u32")} - ${u.setByOffset("global_idx","data")} - }`}else h=` - let outputIndices = ${u.offsetToIndices("global_idx")}; - let inputOffset = ${m.broadcastedIndicesToOffset("outputIndices",u)}; - ${u.setByOffset("global_idx",m.getByOffset("inputOffset"))} + ${g("data",0,"u32")} + ${g("data",1,"u32")} + ${g("data",2,"u32")} + ${g("data",3,"u32")} + ${_.setByOffset("global_idx","data")} + }`}else y=` + let outputIndices = ${_.offsetToIndices(`global_idx * ${l}`)}; + let inputOffset = ${h.broadcastedIndicesToOffset("outputIndices",_)}; + let data = ${_.type.value}(${h.getByOffset(`inputOffset / ${a}`)}); + ${_.setByOffset("global_idx","data")} }`;return` - ${c.registerUniform("vec_size","u32").declareVariables(m,u)} - ${c.mainStart()} - ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${h}`},d=[{type:12,data:a},...V(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length}`,inputDependencies:["rank"]},getShaderSource:l,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:d})}},hl=e=>{Tf(e.inputs),e.compute(Cf(e.inputs),{inputs:[0]})}});var Af,bl,yl=R(()=>{"use strict";te();oe();ae();Jr();Af=e=>{let t=e[0].dataType,r=k.size(e[0].dims),n=k.size(e[1].dims),o=n%4===0,i=a=>{let l=E("x",t,[1],4),d=E("bias",t,[1],4),c=M("y",t,[1],4),m=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],u=w=>` - let bias${w}_offset: u32 = (global_idx * 4 + ${w}) % uniforms.bias_size; - let bias${w} = ${d.getByOffset(`bias${w}_offset / 4`)}[bias${w}_offset % 4];`,h=o?` + ${u.registerUniform("vec_size","u32").declareVariables(h,_)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${y}`},m=[{type:12,data:d},...N(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length};${a}${l}`,inputDependencies:["rank"]},getShaderSource:p,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:m})}},hl=e=>{Tf(e.inputs),e.compute(Cf(e.inputs),{inputs:[0]})}});var Af,bl,yl=R(()=>{"use strict";te();oe();ae();Zr();Af=e=>{let t=e[0].dataType,r=k.size(e[0].dims),n=k.size(e[1].dims),o=n%4===0,i=a=>{let l=E("x",t,[1],4),d=E("bias",t,[1],4),p=M("y",t,[1],4),m=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],u=_=>` + let bias${_}_offset: u32 = (global_idx * 4 + ${_}) % uniforms.bias_size; + let bias${_} = ${d.getByOffset(`bias${_}_offset / 4`)}[bias${_}_offset % 4];`,h=o?` let bias = ${d.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${u(0)}${u(1)}${u(2)}${u(3)} - let bias = ${l.type.value}(bias0, bias1, bias2, bias3);`;return`${a.registerUniforms(m).declareVariables(l,d,c)} + let bias = ${l.type.value}(bias0, bias1, bias2, bias3);`;return`${a.registerUniforms(m).declareVariables(l,d,p)} - ${yo(Ee(t))} + ${fo(ke(t))} ${a.mainStart(Ct)} ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} @@ -5322,20 +5125,20 @@ fn main(@builtin(local_invocation_id) localId : vec3, let x = ${l.getByOffset("global_idx")}; ${h} let x_in = x + bias; - ${c.setByOffset("global_idx",wo("x_in"))} - }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:i,getRunData:a=>({outputs:[{dims:a[0].dims,dataType:a[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/Ct/4)}})}},bl=e=>{e.inputs.length<2||k.size(e.inputs[1].dims)===0?gu(e):e.compute(Af(e.inputs))}});var kf,Ef,wl,_l,vl=R(()=>{"use strict";te();oe();Ie();ae();kf=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Ef=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r.length,i=k.normalizeAxis(t.axis,o),a=r.slice(0);a.splice(i,1,...n);let l=r[i],d=e[0].dataType===9?4:1,c=Math.ceil(k.size(a)/d),m=[{type:12,data:c},{type:6,data:l},{type:12,data:i},...V(e[0].dims,e[1].dims,a)],u=h=>{let w=E("data",e[0].dataType,e[0].dims.length,d),y=E("inputIndices",e[1].dataType,e[1].dims.length),g=M("output",e[0].dataType,a.length,d),x=v=>{let S=n.length,T=`var indicesIndices${v} = ${y.type.indices}(0);`;for(let C=0;C1?`indicesIndices${v}[${C}]`:`indicesIndices${v}`} = ${a.length>1?`outputIndices${v}[uniforms.axis + ${C}]`:`outputIndices${v}`};`;T+=` + ${p.setByOffset("global_idx",ho("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:i,getRunData:a=>({outputs:[{dims:a[0].dims,dataType:a[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/Ct/4)}})}},bl=e=>{e.inputs.length<2||k.size(e.inputs[1].dims)===0?mu(e):e.compute(Af(e.inputs))}});var kf,Ef,_l,wl,vl=R(()=>{"use strict";te();oe();Se();ae();kf=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Ef=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r.length,i=k.normalizeAxis(t.axis,o),a=r.slice(0);a.splice(i,1,...n);let l=r[i],d=e[0].dataType===9?4:1,p=Math.ceil(k.size(a)/d),m=[{type:12,data:p},{type:6,data:l},{type:12,data:i},...N(e[0].dims,e[1].dims,a)],u=h=>{let _=E("data",e[0].dataType,e[0].dims.length,d),y=E("inputIndices",e[1].dataType,e[1].dims.length),g=M("output",e[0].dataType,a.length,d),x=v=>{let S=n.length,T=`var indicesIndices${v} = ${y.type.indices}(0);`;for(let C=0;C1?`indicesIndices${v}[${C}]`:`indicesIndices${v}`} = ${a.length>1?`outputIndices${v}[uniforms.axis + ${C}]`:`outputIndices${v}`};`;T+=` var idx${v} = ${y.getByIndices(`indicesIndices${v}`)}; if (idx${v} < 0) { idx${v} = idx${v} + uniforms.axisDimLimit; } - var dataIndices${v} : ${w.type.indices}; + var dataIndices${v} : ${_.type.indices}; `;for(let C=0,A=0;C1?`dataIndices${v}[${C}]`:`dataIndices${v}`} = u32(idx${v});`,A+=S):(T+=`${o>1?`dataIndices${v}[${C}]`:`dataIndices${v}`} = ${a.length>1?`outputIndices${v}[${A}]`:`outputIndices${v}`};`,A++);return T},$;if(e[0].dataType===9){let v=(S,T,C="")=>` let outputIndices${T} = ${g.offsetToIndices(`outputOffset + ${T}u`)}; ${x(T)}; - let offset${T} = ${w.indicesToOffset(`dataIndices${T}`)}; + let offset${T} = ${_.indicesToOffset(`dataIndices${T}`)}; let index${T} = offset${T} / 4u; let component${T} = offset${T} % 4u; - ${S}[${T}] = ${C}(${w.getByOffset(`index${T}`)}[component${T}]); + ${S}[${T}] = ${C}(${_.getByOffset(`index${T}`)}[component${T}]); `;$=` let outputOffset = global_idx * ${d}; var value = vec4(0); @@ -5347,14 +5150,14 @@ fn main(@builtin(local_invocation_id) localId : vec3, `}else $=` let outputIndices = ${g.offsetToIndices("global_idx")}; ${x("")}; - let value = ${w.getByIndices("dataIndices")}; + let value = ${_.getByIndices("dataIndices")}; ${g.setByOffset("global_idx","value")}; `;return` - ${h.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(w,y,g)} + ${h.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(_,y,g)} ${h.mainStart()} ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${$} - }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:m}),getShaderSource:u}},wl=e=>re({axis:e.axis}),_l=(e,t)=>{let r=e.inputs;kf(r),e.compute(Ef(e.inputs,t))}});var Pf,zf,$l,xl,Sl=R(()=>{"use strict";te();oe();Ie();ae();Pf=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let r=k.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,o=e[0],i=e[2],a=e.length===4?e[3]:void 0;if(i.dims.length!==o.dims.length||!o.dims.map((l,d)=>d===r?Math.ceil(l/n)===i.dims[d]:l===i.dims[d]).reduce((l,d)=>l&&d,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(a){if(a.dataType!==o.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(a.dims.length!==i.dims.length||!a.dims.map((l,d)=>l===i.dims[d]).reduce((l,d)=>l&&d,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},zf=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r.length,i=k.normalizeAxis(t.gatherAxis,o),a=k.normalizeAxis(t.quantizeAxis,o),l=r.slice(0);l.splice(i,1,...n);let d=k.size(l),c=e[2].dataType,u=e[0].dataType===22,h=[{type:12,data:d},{type:12,data:a},{type:12,data:i},{type:12,data:t.blockSize},...V(...e.map((y,g)=>y.dims),l)],w=y=>{let g=E("data",e[0].dataType,e[0].dims.length),x=E("inputIndices",e[1].dataType,e[1].dims.length),$=E("scales",e[2].dataType,e[2].dims.length),v=e.length>3?E("zeroPoint",e[3].dataType,e[3].dims.length):void 0,S=M("output",c,l.length),T=[g,x,$];v&&T.push(v);let C=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:m}),getShaderSource:u}},_l=e=>J({axis:e.axis}),wl=(e,t)=>{let r=e.inputs;kf(r),e.compute(Ef(e.inputs,t))}});var Pf,zf,$l,xl,Sl=R(()=>{"use strict";te();oe();Se();ae();Pf=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let r=k.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,o=e[0],i=e[2],a=e.length===4?e[3]:void 0;if(i.dims.length!==o.dims.length||!o.dims.map((l,d)=>d===r?Math.ceil(l/n)===i.dims[d]:l===i.dims[d]).reduce((l,d)=>l&&d,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(a){if(a.dataType!==o.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(a.dims.length!==i.dims.length||!a.dims.map((l,d)=>l===i.dims[d]).reduce((l,d)=>l&&d,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},zf=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r.length,i=k.normalizeAxis(t.gatherAxis,o),a=k.normalizeAxis(t.quantizeAxis,o),l=r.slice(0);l.splice(i,1,...n);let d=k.size(l),p=e[2].dataType,u=e[0].dataType===22,h=[{type:12,data:d},{type:12,data:a},{type:12,data:i},{type:12,data:t.blockSize},...N(...e.map((y,g)=>y.dims),l)],_=y=>{let g=E("data",e[0].dataType,e[0].dims.length),x=E("inputIndices",e[1].dataType,e[1].dims.length),$=E("scales",e[2].dataType,e[2].dims.length),v=e.length>3?E("zeroPoint",e[3].dataType,e[3].dims.length):void 0,S=M("output",p,l.length),T=[g,x,$];v&&T.push(v);let C=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${y.registerUniforms(C).declareVariables(...T,S)} ${y.mainStart()} let output_indices = ${S.offsetToIndices("global_idx")}; @@ -5397,15 +5200,15 @@ fn main(@builtin(local_invocation_id) localId : vec3, let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; let zero_point_vec = ${u?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0")()}; - let dequantized_data = ${Ee(c)}(quantized_data - zero_point) * scale; + let dequantized_data = ${ke(p)}(quantized_data - zero_point) * scale; ${S.setByOffset("global_idx","dequantized_data")}; - }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((y,g)=>g!==1).map(y=>y.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(y,g)=>"rank")},getRunData:()=>({outputs:[{dims:l,dataType:c}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:h}),getShaderSource:w}},$l=(e,t)=>{let r=e.inputs;Pf(r,t),e.compute(zf(e.inputs,t))},xl=e=>re({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})});var Of,Df,Tl,Il,Cl=R(()=>{"use strict";te();oe();Ie();ae();Of=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and - indices input tensors be of same rank.`)},Df=(e,t)=>{let r=e[0].dims,n=e[0].dataType,o=r.length,i=e[1].dims,a=e[1].dataType,l=k.normalizeAxis(t.axis,o),d=r[l],c=i.slice(0),m=k.size(c),u=E("input",n,o),h=E("indicesInput",a,i.length),w=M("output",n,c.length),y=[{type:12,data:m},{type:6,data:d},{type:12,data:l}];return y.push(...V(r,i,c)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:y}),getShaderSource:$=>` - ${$.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(u,h,w)} + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((y,g)=>g!==1).map(y=>y.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(y,g)=>"rank")},getRunData:()=>({outputs:[{dims:l,dataType:p}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:h}),getShaderSource:_}},$l=(e,t)=>{let r=e.inputs;Pf(r,t),e.compute(zf(e.inputs,t))},xl=e=>J({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})});var Of,Bf,Tl,Il,Cl=R(()=>{"use strict";te();oe();Se();ae();Of=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and + indices input tensors be of same rank.`)},Bf=(e,t)=>{let r=e[0].dims,n=e[0].dataType,o=r.length,i=e[1].dims,a=e[1].dataType,l=k.normalizeAxis(t.axis,o),d=r[l],p=i.slice(0),m=k.size(p),u=E("input",n,o),h=E("indicesInput",a,i.length),_=M("output",n,p.length),y=[{type:12,data:m},{type:6,data:d},{type:12,data:l}];return y.push(...N(r,i,p)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:y}),getShaderSource:$=>` + ${$.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(u,h,_)} ${$.mainStart()} ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - let outputIndices = ${w.offsetToIndices("global_idx")}; + let outputIndices = ${_.offsetToIndices("global_idx")}; var idx = ${h.getByOffset("global_idx")}; if (idx < 0) { @@ -5415,9 +5218,9 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${u.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${u.getByIndices("inputIndices")}; - ${w.setByOffset("global_idx","value")}; - }`}},Tl=e=>re({axis:e.axis}),Il=(e,t)=>{let r=e.inputs;Of(r),e.compute(Df(e.inputs,t))}});var Bf,Mf,Al,kl,El=R(()=>{"use strict";te();oe();ae();Bf=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},Mf=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[o,i,a]=jr.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),l=[o,i];if(!l)throw new Error("Can't use gemm on the given tensors");let d=16,c=Math.ceil(i/d),m=Math.ceil(o/d),u=!0,h=k.size(l),w=[{type:12,data:u?c:h},{type:12,data:o},{type:12,data:i},{type:12,data:a},{type:1,data:t.alpha},{type:1,data:t.beta}],y=["type","type"];e.length===3&&(w.push(...V(e[2].dims)),y.push("rank")),w.push(...V(l));let g=$=>{let v="";t.transA&&t.transB?v="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?v="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?v="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(v="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let S=t.alpha===1?"":"value *= uniforms.alpha;",T=E("a",e[0].dataType,e[0].dims),C=E("b",e[1].dataType,e[1].dims),A=T.type.value,P=null,O=[T,C];e.length===3&&(P=E("c",e[2].dataType,e[2].dims.length),O.push(P));let U=M("output",e[0].dataType,l.length);O.push(U);let L=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` - ${$.registerUniforms(L).declareVariables(...O)} + ${_.setByOffset("global_idx","value")}; + }`}},Tl=e=>J({axis:e.axis}),Il=(e,t)=>{let r=e.inputs;Of(r),e.compute(Bf(e.inputs,t))}});var Df,Mf,Al,kl,El=R(()=>{"use strict";te();oe();ae();Df=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},Mf=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[o,i,a]=Gr.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),l=[o,i];if(!l)throw new Error("Can't use gemm on the given tensors");let d=16,p=Math.ceil(i/d),m=Math.ceil(o/d),u=!0,h=k.size(l),_=[{type:12,data:u?p:h},{type:12,data:o},{type:12,data:i},{type:12,data:a},{type:1,data:t.alpha},{type:1,data:t.beta}],y=["type","type"];e.length===3&&(_.push(...N(e[2].dims)),y.push("rank")),_.push(...N(l));let g=$=>{let v="";t.transA&&t.transB?v="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?v="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?v="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(v="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let S=t.alpha===1?"":"value *= uniforms.alpha;",T=E("a",e[0].dataType,e[0].dims),C=E("b",e[1].dataType,e[1].dims),A=T.type.value,P=null,O=[T,C];e.length===3&&(P=E("c",e[2].dataType,e[2].dims.length),O.push(P));let U=M("output",e[0].dataType,l.length);O.push(U);let G=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` + ${$.registerUniforms(G).declareVariables(...O)} ${$.mainStart()} ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -5497,7 +5300,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, } else { tile_b[local_id.y][local_id.x] = ${S.type.value}(0); } - `,O="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let L=t.alpha===1?"":"value *= uniforms.alpha;";return` + `,O="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let G=t.alpha===1?"":"value *= uniforms.alpha;";return` ${$.registerUniforms(P).declareVariables(...C)} var tile_a: array, ${d}>; var tile_b: array, ${d}>; @@ -5518,14 +5321,14 @@ fn main(@builtin(local_invocation_id) localId : vec3, workgroupBarrier(); } - ${L} + ${G} let m = tile_row_start + local_id.y; let n = tile_col_start + local_id.x; ${(()=>T!=null?`let cOffset = ${T.broadcastedIndicesToOffset("vec2(m, n)",A)}; value += ${A.type.value}(uniforms.beta) * ${T.getByOffset("cOffset")};`:"")()} if (m < uniforms.M && n < uniforms.N) { output[m * uniforms.N + n] = value; } - }`};return u?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:c*m},programUniforms:w}),getShaderSource:x}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:w}),getShaderSource:g}},Al=e=>{let t=e.transA,r=e.transB,n=e.alpha,o=e.beta;return{transA:t,transB:r,alpha:n,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},kl=(e,t)=>{Bf(e.inputs),e.compute(Mf(e.inputs,t))}});var dt,yt,Ut,Vt,Rf,Uf,Vf,Nf,Wf,Lf,Gf,Hf,Pl,zl,Ol=R(()=>{"use strict";te();oe();Ie();ae();[dt,yt,Ut,Vt]=[0,1,2,3],Rf=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},Uf=` + }`};return u?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:p*m},programUniforms:_}),getShaderSource:x}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:_}),getShaderSource:g}},Al=e=>{let t=e.transA,r=e.transB,n=e.alpha,o=e.beta;return{transA:t,transB:r,alpha:n,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},kl=(e,t)=>{Df(e.inputs),e.compute(Mf(e.inputs,t))}});var lt,yt,Ut,Nt,Rf,Uf,Nf,Vf,Wf,Lf,Gf,Hf,Pl,zl,Ol=R(()=>{"use strict";te();oe();Se();ae();[lt,yt,Ut,Nt]=[0,1,2,3],Rf=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},Uf=` fn gs_get_cubic_coeffs(x: f32) -> vec4 { let cubic_alpha = -0.75f; let x_abs = abs(x); @@ -5536,7 +5339,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); return coeffs; } -`,Vf=e=>` +`,Nf=e=>` fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { var v: vec4; var coeffs = gs_get_cubic_coeffs(x); @@ -5547,7 +5350,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); return pixel; } -`,Nf=e=>` +`,Vf=e=>` fn gs_denormalize(n: f32, length: i32) -> f32 { ${e.alignCorners===0?` // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] @@ -5588,33 +5391,33 @@ fn main(@builtin(local_invocation_id) localId : vec3, fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} { var pixel = ${t}(0); var indices = vec4(0); - indices[${dt}] = batch; + indices[${lt}] = batch; indices[${yt}] = channel;`+(()=>{switch(r.paddingMode){case"zeros":return` if (r >= 0 && r < H && c >=0 && c < W) { indices[${Ut}] = u32(r); - indices[${Vt}] = u32(c); + indices[${Nt}] = u32(c); } `;case"border":return` indices[${Ut}] = u32(clamp(r, 0, H - 1)); - indices[${Vt}] = u32(clamp(c, 0, W - 1)); + indices[${Nt}] = u32(clamp(c, 0, W - 1)); `;case"reflection":return` indices[${Ut}] = gs_reflect(r, border[1], border[3]); - indices[${Vt}] = gs_reflect(c, border[0], border[2]); + indices[${Nt}] = gs_reflect(c, border[0], border[2]); `;default:throw new Error(`padding mode ${r.paddingMode} is not supported`)}})()+` return ${e.getByIndices("indices")}; } `,Gf=(e,t,r)=>(()=>{switch(r.mode){case"nearest":return` - let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${dt}], indices[${yt}], border); + let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${lt}], indices[${yt}], border); `;case"bilinear":return` let x1 = i32(floor(x)); let y1 = i32(floor(y)); let x2 = x1 + 1; let y2 = y1 + 1; - let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${dt}], indices[${yt}], border); - let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${dt}], indices[${yt}], border); - let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${dt}], indices[${yt}], border); - let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${dt}], indices[${yt}], border); + let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${lt}], indices[${yt}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${lt}], indices[${yt}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${lt}], indices[${yt}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${lt}], indices[${yt}], border); let dx2 = ${t}(f32(x2) - x); let dx1 = ${t}(x - f32(x1)); @@ -5627,25 +5430,25 @@ fn main(@builtin(local_invocation_id) localId : vec3, var p: mat4x4<${t}>; for (var h = 0; h < 4; h++) { for (var w = 0; w < 4; w++) { - p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${dt}], indices[${yt}], border); + p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${lt}], indices[${yt}], border); } } let dx = x - f32(x0 + 1); let dy = y - f32(y0 + 1); let result = gs_bicubic_interpolate(p, dx, dy); - `;default:throw new Error(`mode ${r.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,Hf=(e,t)=>{let r=E("x",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=E("grid",e[1].dataType,n.length,2),i=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(i=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[dt,yt,Ut,Vt]=[0,3,1,2]);let a=M("output",e[0].dataType,i.length),l=r.type.value,d=k.size(i),c=[{type:12,data:d},...V(e[0].dims,n,i)],m=u=>` + `;default:throw new Error(`mode ${r.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,Hf=(e,t)=>{let r=E("x",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=E("grid",e[1].dataType,n.length,2),i=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(i=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[lt,yt,Ut,Nt]=[0,3,1,2]);let a=M("output",e[0].dataType,i.length),l=r.type.value,d=k.size(i),p=[{type:12,data:d},...N(e[0].dims,n,i)],m=u=>` ${u.registerUniform("output_size","u32").declareVariables(r,o,a)} ${Uf} - ${Vf(l)} - ${Nf(t)} + ${Nf(l)} + ${Vf(t)} ${Wf(t)} ${Lf(r,l,t)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let H_in = i32(uniforms.x_shape[${Ut}]); - let W_in = i32(uniforms.x_shape[${Vt}]); + let W_in = i32(uniforms.x_shape[${Nt}]); ${t.alignCorners===0?` let x_min = -0.5; @@ -5661,20 +5464,20 @@ fn main(@builtin(local_invocation_id) localId : vec3, let border = vec4(x_min, y_min, x_max, y_max); let indices = ${a.offsetToIndices("global_idx")}; - var grid_indices = vec3(indices[${dt}], indices[${Ut}], indices[${Vt}]); + var grid_indices = vec3(indices[${lt}], indices[${Ut}], indices[${Nt}]); let nxy = ${o.getByIndices("grid_indices")}; var x = gs_denormalize(f32(nxy[0]), W_in); var y = gs_denormalize(f32(nxy[1]), H_in); ${Gf(a,l,t)} - }`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:u=>{let h=k.size(i);return{outputs:[{dims:i,dataType:u[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:c}},getShaderSource:m}},Pl=(e,t)=>{Rf(e.inputs),e.compute(Hf(e.inputs,t))},zl=e=>re({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})});var Me,jf,Bl,Dl,Kf,ar,Ml,ko=R(()=>{"use strict";te();oe();Ie();qr();Xr();ae();ut();Me=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,jf=(e,t)=>{let r=e[0],n=Me(e,1),o=Me(e,2),i=Me(e,3),a=Me(e,4),l=Me(e,5),d=Me(e,6),c=Me(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let m=r.dims[0],u=r.dims[1],h=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],w=u,y=0,g=0,x=Math.floor(h/t.numHeads);if(d&&c&&k.size(d.dims)&&k.size(c.dims)){if(d.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(d.dims[0]!==m||d.dims[1]!==t.numHeads||d.dims[3]!==x)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(c.dims[0]!==m||c.dims[1]!==t.numHeads||c.dims[3]!==x)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.dims[2]!==c.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(c.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');y=d.dims[2],g=d.dims[2]}else if(d&&k.size(d.dims)||c&&k.size(c.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let $;if(n&&k.size(n.dims)>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');$=2,w=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==x)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');$=5,w=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==x)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');$=0,w=n.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(r.dims[2]!==t.numHeads||r.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');$=3}if(i&&k.size(i.dims)>0){if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let v=y+w,S=0;if(a&&k.size(a.dims)>0){S=8;let P=a.dims;throw P.length===1?P[0]===m?S=1:P[0]===3*m+2&&(S=3):P.length===2&&P[0]===m&&P[1]===v&&(S=5),S===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let T=!1,C=h;if(o&&k.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(w!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');C=o.dims[2]}else{if(w!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');C=o.dims[1]*o.dims[3],T=!0}}let A=!1;if(a&&k.size(a.dims)>0)throw new Error("Key padding mask is not supported");if(l&&k.size(l.dims)>0){if(l.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(l.dims[0]!==m||l.dims[1]!==t.numHeads||l.dims[2]!==u||l.dims[3]!==v)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:m,sequenceLength:u,pastSequenceLength:y,kvSequenceLength:w,totalSequenceLength:v,maxSequenceLength:g,inputHiddenSize:0,hiddenSize:h,vHiddenSize:C,headSize:x,vHeadSize:Math.floor(C/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:S,scale:t.scale,broadcastResPosBias:A,passPastInKv:T,qkvFormat:$}},Bl=e=>re({...e}),Dl=re({perm:[0,2,1,3]}),Kf=(e,t,r,n,o,i,a)=>{let l=[n,o,i],d=k.size(l),c=[{type:12,data:d},{type:12,data:a},{type:12,data:i}],m=u=>{let h=M("qkv_with_bias",t.dataType,l),w=E("qkv",t.dataType,l),y=E("bias",r.dataType,l),g=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` - ${u.registerUniforms(g).declareVariables(w,y,h)} + }`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:u=>{let h=k.size(i);return{outputs:[{dims:i,dataType:u[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:p}},getShaderSource:m}},Pl=(e,t)=>{Rf(e.inputs),e.compute(Hf(e.inputs,t))},zl=e=>J({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})});var Me,jf,Dl,Bl,Kf,rr,Ml,To=R(()=>{"use strict";te();oe();Se();Lr();Kr();ae();ut();Me=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,jf=(e,t)=>{let r=e[0],n=Me(e,1),o=Me(e,2),i=Me(e,3),a=Me(e,4),l=Me(e,5),d=Me(e,6),p=Me(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let m=r.dims[0],u=r.dims[1],h=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],_=u,y=0,g=0,x=Math.floor(h/t.numHeads);if(d&&p&&k.size(d.dims)&&k.size(p.dims)){if(d.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(d.dims[0]!==m||d.dims[1]!==t.numHeads||d.dims[3]!==x)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[0]!==m||p.dims[1]!==t.numHeads||p.dims[3]!==x)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.dims[2]!==p.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(p.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');y=d.dims[2],g=d.dims[2]}else if(d&&k.size(d.dims)||p&&k.size(p.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let $;if(n&&k.size(n.dims)>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');$=2,_=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==x)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');$=5,_=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==x)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');$=0,_=n.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(r.dims[2]!==t.numHeads||r.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');$=3}if(i&&k.size(i.dims)>0){if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let v=y+_,S=0;if(a&&k.size(a.dims)>0){S=8;let P=a.dims;throw P.length===1?P[0]===m?S=1:P[0]===3*m+2&&(S=3):P.length===2&&P[0]===m&&P[1]===v&&(S=5),S===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let T=!1,C=h;if(o&&k.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(_!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');C=o.dims[2]}else{if(_!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');C=o.dims[1]*o.dims[3],T=!0}}let A=!1;if(a&&k.size(a.dims)>0)throw new Error("Key padding mask is not supported");if(l&&k.size(l.dims)>0){if(l.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(l.dims[0]!==m||l.dims[1]!==t.numHeads||l.dims[2]!==u||l.dims[3]!==v)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:m,sequenceLength:u,pastSequenceLength:y,kvSequenceLength:_,totalSequenceLength:v,maxSequenceLength:g,inputHiddenSize:0,hiddenSize:h,vHiddenSize:C,headSize:x,vHeadSize:Math.floor(C/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:S,scale:t.scale,broadcastResPosBias:A,passPastInKv:T,qkvFormat:$}},Dl=e=>J({...e}),Bl=J({perm:[0,2,1,3]}),Kf=(e,t,r,n,o,i,a)=>{let l=[n,o,i],d=k.size(l),p=[{type:12,data:d},{type:12,data:a},{type:12,data:i}],m=u=>{let h=M("qkv_with_bias",t.dataType,l),_=E("qkv",t.dataType,l),y=E("bias",r.dataType,l),g=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${u.registerUniforms(g).declareVariables(_,y,h)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; - }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c}),getShaderSource:m},{inputs:[t,r],outputs:[-1]})[0]},ar=(e,t,r,n,o,i,a,l)=>{let d=i;if(a&&k.size(a.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return d=Kf(e,i,a,t,n,r*o,l),d=d.reshape([t,n,r,o]),r===1||n===1?d:e.compute(Pe(d,Dl.perm),{inputs:[d],outputs:[-1]})[0]}else return i.dims.length===3&&(d=i.reshape([t,n,r,o])),r===1||n===1?d:e.compute(Pe(d,Dl.perm),{inputs:[d],outputs:[-1]})[0]},Ml=(e,t)=>{let r=jf(e.inputs,t),n=e.inputs[0],o=Me(e.inputs,1),i=Me(e.inputs,2),a=Me(e.inputs,3),l=Me(e.inputs,4),d=Me(e.inputs,5),c=Me(e.inputs,6),m=Me(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if(o?.dims.length===5)throw new Error("Packed KV is not implemented");let u=o&&i&&o.dims.length===4&&i.dims.length===4,h=ar(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,a,0);if(u)return Rt(e,h,o,i,l,void 0,c,m,d,r);if(!o||!i)throw new Error("key and value must be provided");let w=ar(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,o,a,r.hiddenSize),y=ar(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,i,a,2*r.hiddenSize);Rt(e,h,w,y,l,void 0,c,m,d,r)}});var Yf,Zf,Xf,Qf,Eo,Rl,Ul,Po=R(()=>{"use strict";te();oe();Ie();ae();Yf=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Zf=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>r.push(Number(o))),n=r.length),re({numOutputs:n,axis:t.axis,splitSizes:r})},Xf=e=>` + }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p}),getShaderSource:m},{inputs:[t,r],outputs:[-1]})[0]},rr=(e,t,r,n,o,i,a,l)=>{let d=i;if(a&&k.size(a.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return d=Kf(e,i,a,t,n,r*o,l),d=d.reshape([t,n,r,o]),r===1||n===1?d:e.compute(Ee(d,Bl.perm),{inputs:[d],outputs:[-1]})[0]}else return i.dims.length===3&&(d=i.reshape([t,n,r,o])),r===1||n===1?d:e.compute(Ee(d,Bl.perm),{inputs:[d],outputs:[-1]})[0]},Ml=(e,t)=>{let r=jf(e.inputs,t),n=e.inputs[0],o=Me(e.inputs,1),i=Me(e.inputs,2),a=Me(e.inputs,3),l=Me(e.inputs,4),d=Me(e.inputs,5),p=Me(e.inputs,6),m=Me(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if(o?.dims.length===5)throw new Error("Packed KV is not implemented");let u=o&&i&&o.dims.length===4&&i.dims.length===4,h=rr(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,a,0);if(u)return Rt(e,h,o,i,l,void 0,p,m,d,r);if(!o||!i)throw new Error("key and value must be provided");let _=rr(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,o,a,r.hiddenSize),y=rr(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,i,a,2*r.hiddenSize);Rt(e,h,_,y,l,void 0,p,m,d,r)}});var Yf,Zf,Qf,Xf,Io,Rl,Ul,Co=R(()=>{"use strict";te();oe();Se();ae();Yf=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Zf=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>r.push(Number(o))),n=r.length),J({numOutputs:n,axis:t.axis,splitSizes:r})},Qf=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${F("uniforms.size_in_split_axis","i",e)}) { @@ -5682,14 +5485,14 @@ fn calculateOutputIndex(index: u32) -> u32 { } } return ${e}u; -}`,Qf=e=>{let t=e.length,r=[];for(let n=0;n{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=k.size(r),o=e[0].dataType,i=k.normalizeAxis(t.axis,r.length),a=new Array(t.numOutputs),l=E("input",o,r.length),d=new Array(t.numOutputs),c=[],m=[],u=0,h=[{type:12,data:n}];for(let y=0;y` + }`},Io=(e,t)=>{let r=e[0].dims,n=k.size(r),o=e[0].dataType,i=k.normalizeAxis(t.axis,r.length),a=new Array(t.numOutputs),l=E("input",o,r.length),d=new Array(t.numOutputs),p=[],m=[],u=0,h=[{type:12,data:n}];for(let y=0;y` ${y.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",d.length).declareVariables(l,...a)} - ${Xf(d.length)} - ${Qf(a)} + ${Qf(d.length)} + ${Xf(a)} ${y.mainStart()} ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} @@ -5702,7 +5505,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${l.indicesSet("indices",i,"index")}; } writeBufferData(output_number, indices, global_idx); - }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:c,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:h})}},Rl=(e,t)=>{Yf(e.inputs);let r=e.inputs.length===1?t:Zf(e.inputs,t);e.compute(Eo(e.inputs,r),{inputs:[0]})},Ul=e=>{let t=e.axis,r=e.splitSizes,n=e.numOutputs<0?r.length:e.numOutputs;if(n!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return re({axis:t,numOutputs:n,splitSizes:r})}});var Jf,eh,Vl,Nl,Wl=R(()=>{"use strict";Ie();Xr();ko();Po();ut();Jf=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let r=e[0],n=e[1],o=e[2],i=e[3],a=e[4];if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let l=!1,d=r.dims[0],c=r.dims[1],m=r.dims.length===3?l?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],u=c,h=0,w=!n||n.dims.length===0,y=Math.floor(w?m/(t.numHeads+2*t.kvNumHeads):m/t.numHeads);w&&(m=y*t.numHeads);let g=i&&i.dims.length!==0,x=a&&a.dims.length!==0;if(g&&i.dims.length===4&&i.dims[0]===d&&i.dims[1]!==t.kvNumHeads&&i.dims[2]===t.kvNumHeads&&i.dims[3]===y)throw new Error("BSNH pastKey/pastValue is not supported");if(g&&x){if(i.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(a.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');h=i.dims[2]}else if(g||x)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let v=1;if(n&&n.dims.length>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(r.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');u=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==y)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');u=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==y)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');u=n.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');v=3}let S=0,T=!1,C=t.kvNumHeads?y*t.kvNumHeads:m;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(u!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');C=o.dims[2]}else{if(u!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');C=o.dims[1]*o.dims[3],T=!0}}let A=e.length>4?e[5]:void 0;if(A&&A.dims.length!==1&&A.dims[0]!==d)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');let P=-1,O=-1,U=!1;return{batchSize:d,sequenceLength:c,pastSequenceLength:h,kvSequenceLength:u,totalSequenceLength:P,maxSequenceLength:O,inputHiddenSize:0,hiddenSize:m,vHiddenSize:C,headSize:y,vHeadSize:Math.floor(C/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:S,scale:t.scale,broadcastResPosBias:U,passPastInKv:T,qkvFormat:v}},eh=re({perm:[0,2,1,3]}),Vl=(e,t,r)=>{let n=t,o=r.kvNumHeads;return t.dims.length===3&&r.kvSequenceLength!==0&&(n=t.reshape([r.batchSize,r.kvSequenceLength,o,r.headSize]),n=e.compute(Pe(n,eh.perm),{inputs:[n],outputs:[-1]})[0]),n},Nl=(e,t)=>{let r=Jf(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(e.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let n=e.inputs[0],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,i=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,a=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,l=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,d=e.inputs.length>4?e.inputs[5]:void 0,c=e.inputs.length>5?e.inputs[6]:void 0,m=r.kvNumHeads?r.kvNumHeads:r.numHeads,u=re({axis:2,numOutputs:3,splitSizes:[r.numHeads*r.headSize,m*r.headSize,m*r.headSize]}),[h,w,y]=!o&&!i?e.compute(Eo([n],u),{inputs:[n],outputs:[-1,-1,-1]}):[n,o,i],g=ar(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,h,void 0,0);Rt(e,g,Vl(e,w,r),Vl(e,y,r),void 0,void 0,a,l,void 0,r,d,c)}});var Ll,th,rh,Gl,Hl=R(()=>{"use strict";te();oe();ut();ae();Ll=(e,t,r,n,o,i,a,l)=>{let d=ye(i),c=d===1?"f32":`vec${d}f`,m=d===1?"vec2f":`mat2x${d}f`,u=o*a,h=64;u===1&&(h=256);let w=[o,a,i/d],y=[o,a,2],g=["rank","type","type"],x=[];x.push(...V(w,y));let $=v=>{let S=E("x",t.dataType,3,d),T=E("scale",r.dataType,r.dims),C=E("bias",n.dataType,n.dims),A=M("output",1,3,2),P=[S,T,C,A];return` + }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:_,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:h})}},Rl=(e,t)=>{Yf(e.inputs);let r=e.inputs.length===1?t:Zf(e.inputs,t);e.compute(Io(e.inputs,r),{inputs:[0]})},Ul=e=>{let t=e.axis,r=e.splitSizes,n=e.numOutputs<0?r.length:e.numOutputs;if(n!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return J({axis:t,numOutputs:n,splitSizes:r})}});var Jf,eh,Nl,Vl,Wl=R(()=>{"use strict";Se();Kr();To();Co();ut();Jf=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let r=e[0],n=e[1],o=e[2],i=e[3],a=e[4];if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let l=!1,d=r.dims[0],p=r.dims[1],m=r.dims.length===3?l?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],u=p,h=0,_=!n||n.dims.length===0,y=Math.floor(_?m/(t.numHeads+2*t.kvNumHeads):m/t.numHeads);_&&(m=y*t.numHeads);let g=i&&i.dims.length!==0,x=a&&a.dims.length!==0;if(g&&i.dims.length===4&&i.dims[0]===d&&i.dims[1]!==t.kvNumHeads&&i.dims[2]===t.kvNumHeads&&i.dims[3]===y)throw new Error("BSNH pastKey/pastValue is not supported");if(g&&x){if(i.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(a.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');h=i.dims[2]}else if(g||x)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let v=1;if(n&&n.dims.length>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(r.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');u=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==y)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');u=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==y)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');u=n.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');v=3}let S=0,T=!1,C=t.kvNumHeads?y*t.kvNumHeads:m;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(u!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');C=o.dims[2]}else{if(u!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');C=o.dims[1]*o.dims[3],T=!0}}let A=e.length>4?e[5]:void 0;if(A&&A.dims.length!==1&&A.dims[0]!==d)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');let P=-1,O=-1,U=!1;return{batchSize:d,sequenceLength:p,pastSequenceLength:h,kvSequenceLength:u,totalSequenceLength:P,maxSequenceLength:O,inputHiddenSize:0,hiddenSize:m,vHiddenSize:C,headSize:y,vHeadSize:Math.floor(C/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:S,scale:t.scale,broadcastResPosBias:U,passPastInKv:T,qkvFormat:v}},eh=J({perm:[0,2,1,3]}),Nl=(e,t,r)=>{let n=t,o=r.kvNumHeads;return t.dims.length===3&&r.kvSequenceLength!==0&&(n=t.reshape([r.batchSize,r.kvSequenceLength,o,r.headSize]),n=e.compute(Ee(n,eh.perm),{inputs:[n],outputs:[-1]})[0]),n},Vl=(e,t)=>{let r=Jf(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(e.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let n=e.inputs[0],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,i=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,a=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,l=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,d=e.inputs.length>4?e.inputs[5]:void 0,p=e.inputs.length>5?e.inputs[6]:void 0,m=r.kvNumHeads?r.kvNumHeads:r.numHeads,u=J({axis:2,numOutputs:3,splitSizes:[r.numHeads*r.headSize,m*r.headSize,m*r.headSize]}),[h,_,y]=!o&&!i?e.compute(Io([n],u),{inputs:[n],outputs:[-1,-1,-1]}):[n,o,i],g=rr(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,h,void 0,0);Rt(e,g,Nl(e,_,r),Nl(e,y,r),void 0,void 0,a,l,void 0,r,d,p)}});var Ll,th,rh,Gl,Hl=R(()=>{"use strict";te();oe();ut();ae();Ll=(e,t,r,n,o,i,a,l)=>{let d=me(i),p=d===1?"f32":`vec${d}f`,m=d===1?"vec2f":`mat2x${d}f`,u=o*a,h=64;u===1&&(h=256);let _=[o,a,i/d],y=[o,a,2],g=["rank","type","type"],x=[];x.push(...N(_,y));let $=v=>{let S=E("x",t.dataType,3,d),T=E("scale",r.dataType,r.dims),C=E("bias",n.dataType,n.dims),A=M("output",1,3,2),P=[S,T,C,A];return` var workgroup_shared : array<${m}, ${h}>; const workgroup_size = ${h}u; ${v.declareVariables(...P)} @@ -5711,10 +5514,10 @@ fn calculateOutputIndex(index: u32) -> u32 { let channel = workgroup_index % uniforms.x_shape[1]; let hight = uniforms.x_shape[2]; // initialize workgroup memory - var sum = ${c}(0); - var squared_sum = ${c}(0); + var sum = ${p}(0); + var squared_sum = ${p}(0); for (var h = local_idx; h < hight; h += workgroup_size) { - let value = ${c}(${S.get("batch","channel","h")}); + let value = ${p}(${S.get("batch","channel","h")}); sum += value; squared_sum += value * value; } @@ -5728,15 +5531,15 @@ fn calculateOutputIndex(index: u32) -> u32 { workgroupBarrier(); } if (local_idx == 0) { - let sum_final = ${Ke("workgroup_shared[0][0]",d)} / f32(hight * ${d}); - let squared_sum_final = ${Ke("workgroup_shared[0][1]",d)} / f32(hight * ${d}); + let sum_final = ${He("workgroup_shared[0][0]",d)} / f32(hight * ${d}); + let squared_sum_final = ${He("workgroup_shared[0][1]",d)} / f32(hight * ${d}); let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${l})); let channel_scale = inv_std_dev * f32(scale[channel]); let channel_shift = f32(bias[channel]) - sum_final * channel_scale; output[workgroup_index] = vec2f(channel_scale, channel_shift); } - }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${d};${l};${h}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:y,dataType:1}],dispatchGroup:{x:u},programUniforms:x}),getShaderSource:$},{inputs:[t,r,n],outputs:[-1]})[0]},th=(e,t,r)=>{let n=t[0].dims,o=n,i=2,a=n[0],l=n[1],d=k.sizeFromDimension(n,i),c=ye(d),m=k.size(o)/c,u=Ll(e,t[0],t[1],t[2],a,d,l,r.epsilon),h=[a,l,d/c],w=[a,l],y=["type","none"],g=x=>{let $=E("x",t[0].dataType,h.length,c),v=E("scale_shift",1,w.length,2),S=M("output",t[0].dataType,h.length,c),T=[$,v,S];return` + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${d};${l};${h}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:y,dataType:1}],dispatchGroup:{x:u},programUniforms:x}),getShaderSource:$},{inputs:[t,r,n],outputs:[-1]})[0]},th=(e,t,r)=>{let n=t[0].dims,o=n,i=2,a=n[0],l=n[1],d=k.sizeFromDimension(n,i),p=me(d),m=k.size(o)/p,u=Ll(e,t[0],t[1],t[2],a,d,l,r.epsilon),h=[a,l,d/p],_=[a,l],y=["type","none"],g=x=>{let $=E("x",t[0].dataType,h.length,p),v=E("scale_shift",1,_.length,2),S=M("output",t[0].dataType,h.length,p),T=[$,v,S];return` ${x.registerUniform("output_size","u32").declareVariables(...T)} ${x.mainStart()} ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -5746,7 +5549,7 @@ fn calculateOutputIndex(index: u32) -> u32 { let scale_shift = ${v.getByIndices("vec2(batch, channel)")}; let value = ${$.getByOffset("global_idx")} * ${S.type.value}(scale_shift.x) + ${S.type.value}(scale_shift.y); ${S.setByOffset("global_idx","value")}; - }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${c}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...V(h,w,h)]}),getShaderSource:g},{inputs:[t[0],u]})},rh=(e,t,r)=>{let n=t[0].dims,o=n,i=n[0],a=n[n.length-1],l=k.sizeFromDimension(n,1)/a,d=ye(a),c=k.size(o)/d,m=[{type:12,data:l},{type:12,data:Math.floor(a/d)}],u=["type","type"],h=!1,w=[0,n.length-1];for(let $=0;$n[w[v]])),g=Ll(e,y,t[1],t[2],i,l,a,r.epsilon),x=$=>{let v=me(t[0].dataType),S=d===1?"vec2f":`mat${d}x2f`,T=P=>{let O=P===0?"x":"y",U=d===1?"f32":`vec${d}f`;switch(d){case 1:return`${v}(${U}(scale.${O}))`;case 2:return`vec2<${v}>(${U}(scale[0].${O}, scale[1].${O}))`;case 4:return`vec4<${v}>(${U}(scale[0].${O}, scale[1].${O}, scale[2].${O}, scale[3].${O}))`;default:throw new Error(`Not supported compoents ${d}`)}},C=E("input",t[0].dataType,t[0].dims,d),A=M("output",t[0].dataType,o,d);return` + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${p}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...N(h,_,h)]}),getShaderSource:g},{inputs:[t[0],u]})},rh=(e,t,r)=>{let n=t[0].dims,o=n,i=n[0],a=n[n.length-1],l=k.sizeFromDimension(n,1)/a,d=me(a),p=k.size(o)/d,m=[{type:12,data:l},{type:12,data:Math.floor(a/d)}],u=["type","type"],h=!1,_=[0,n.length-1];for(let $=0;$n[_[v]])),g=Ll(e,y,t[1],t[2],i,l,a,r.epsilon),x=$=>{let v=ye(t[0].dataType),S=d===1?"vec2f":`mat${d}x2f`,T=P=>{let O=P===0?"x":"y",U=d===1?"f32":`vec${d}f`;switch(d){case 1:return`${v}(${U}(scale.${O}))`;case 2:return`vec2<${v}>(${U}(scale[0].${O}, scale[1].${O}))`;case 4:return`vec4<${v}>(${U}(scale[0].${O}, scale[1].${O}, scale[2].${O}, scale[3].${O}))`;default:throw new Error(`Not supported compoents ${d}`)}},C=E("input",t[0].dataType,t[0].dims,d),A=M("output",t[0].dataType,o,d);return` @group(0) @binding(0) var input : array<${C.type.storage}>; @group(0) @binding(1) var scale_input : array<${S}>; @group(0) @binding(2) var output : array<${A.type.storage}>; @@ -5760,23 +5563,23 @@ fn calculateOutputIndex(index: u32) -> u32 { let scale_offset = current_image_number * uniforms.C + current_channel_number; let scale = scale_input[scale_offset]; output[global_idx] = fma(input[global_idx], ${T(0)}, ${T(1)}); - }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${d}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:m}),getShaderSource:x},{inputs:[t[0],g]})},Gl=(e,t)=>{t.format==="NHWC"?rh(e,e.inputs,t):th(e,e.inputs,t)}});var nh,oh,Fl,ql=R(()=>{"use strict";te();oe();ae();nh=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},oh=(e,t,r)=>{let n=t.simplified,o=e[0].dims,i=e[1],a=!n&&e[2],l=o,d=k.normalizeAxis(t.axis,o.length),c=k.sizeToDimension(o,d),m=k.sizeFromDimension(o,d),u=k.size(i.dims),h=a?k.size(a.dims):0;if(u!==m||a&&h!==m)throw new Error(`Size of X.shape()[axis:] == ${m}. + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${d}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:m}),getShaderSource:x},{inputs:[t[0],g]})},Gl=(e,t)=>{t.format==="NHWC"?rh(e,e.inputs,t):th(e,e.inputs,t)}});var nh,oh,Fl,ql=R(()=>{"use strict";te();oe();ae();nh=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},oh=(e,t,r)=>{let n=t.simplified,o=e[0].dims,i=e[1],a=!n&&e[2],l=o,d=k.normalizeAxis(t.axis,o.length),p=k.sizeToDimension(o,d),m=k.sizeFromDimension(o,d),u=k.size(i.dims),h=a?k.size(a.dims):0;if(u!==m||a&&h!==m)throw new Error(`Size of X.shape()[axis:] == ${m}. Size of scale and bias (if provided) must match this. - Got scale size of ${u} and bias size of ${h}`);let w=[];for(let C=0;C1,v=r>2,S=C=>{let A=me(e[0].dataType),P=[E("x",e[0].dataType,e[0].dims,y),E("scale",i.dataType,i.dims,y)];a&&P.push(E("bias",a.dataType,a.dims,y)),P.push(M("output",e[0].dataType,l,y)),$&&P.push(M("mean_data_output",1,w)),v&&P.push(M("inv_std_output",1,w));let O=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + Got scale size of ${u} and bias size of ${h}`);let _=[];for(let C=0;C1,v=r>2,S=C=>{let A=ye(e[0].dataType),P=[E("x",e[0].dataType,e[0].dims,y),E("scale",i.dataType,i.dims,y)];a&&P.push(E("bias",a.dataType,a.dims,y)),P.push(M("output",e[0].dataType,l,y)),$&&P.push(M("mean_data_output",1,_)),v&&P.push(M("inv_std_output",1,_));let O=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${C.registerUniforms(O).declareVariables(...P)} ${C.mainStart()} ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; - var mean_vector = ${mo("f32",y)}; - var mean_square_vector = ${mo("f32",y)}; + var mean_vector = ${lo("f32",y)}; + var mean_square_vector = ${lo("f32",y)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${At(A,y,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } - let mean = ${Ke("mean_vector",y)} / uniforms.norm_size; - let inv_std_dev = inverseSqrt(${Ke("mean_square_vector",y)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); + let mean = ${He("mean_vector",y)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${He("mean_square_vector",y)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${At(A,y,"x[j + offset]")}; @@ -5788,24 +5591,24 @@ fn calculateOutputIndex(index: u32) -> u32 { ${$?"mean_data_output[global_idx] = mean":""}; ${v?"inv_std_output[global_idx] = inv_std_dev":""}; - }`},T=[{dims:l,dataType:e[0].dataType}];return $&&T.push({dims:w,dataType:1}),v&&T.push({dims:w,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${y};${r};${n}`,inputDependencies:g},getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(c/64)},programUniforms:x}),getShaderSource:S}},Fl=(e,t)=>{nh(e.inputs),e.compute(oh(e.inputs,t,e.outputCount))}});var ih,jl,Kl=R(()=>{"use strict";oe();on();ir();ih=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},jl=e=>{ih(e.inputs);let t=et.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let r=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];if(r<8&&n<8)e.compute(nn(e.inputs,{activation:""},t));else{let o=t[t.length-2],i=k.size(e.inputs[0].dims.slice(0,-2)),a=k.size(e.inputs[1].dims.slice(0,-2));if(i!==1&&o===1&&a===1){let l=e.inputs[0].reshape([1,i,n]),d=e.inputs[1].reshape([1,n,r]),c=[1,i,r],m=[l,d];e.compute(or(m,{activation:""},t,c),{inputs:m})}else e.compute(or(e.inputs,{activation:""},t))}}});var ah,sh,uh,Yl,Zl,Xl=R(()=>{"use strict";te();oe();Ie();ae();ah=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],n=r.dims.length;if(r.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let o=Math.floor((t.k+t.blockSize-1)/t.blockSize),i=t.blockSize/8*t.bits,a=e[1];if(!k.areEqual(a.dims,[t.n,o,i]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let d=e[2].dims;if(k.size(d)!==t.n*o)throw new Error("scales input size error.");if(e.length===4){let m=e[3].dims,u=t.bits>4?t.n*o:t.n*Math.floor((o+1)/2);if(k.size(m)!==u)throw new Error("zeroPoints input size error.")}},sh=(e,t)=>{let r=e[0].dims,n=r.length,o=r[n-2],i=t.k,a=t.n,l=r.slice(0,n-2),d=k.size(l),m=e[1].dims[2]/4,u=e[0].dataType,h=ye(t.k),w=ye(m),y=ye(a),g=l.concat([o,a]),x=o>1&&a/y%2===0?2:1,$=k.size(g)/y/x,v=64,S=[],T=[d,o,i/h],C=k.convertShape(e[1].dims).slice();C.splice(-1,1,m/w),S.push(...V(T)),S.push(...V(C)),S.push(...V(e[2].dims)),e.length===4&&S.push(...V(k.convertShape(e[3].dims)));let A=[d,o,a/y];S.push(...V(A));let P=O=>{let U=T.length,L=E("a",e[0].dataType,U,h),j=E("b",12,C.length,w),K=E("scales",e[2].dataType,e[2].dims.length),W=[L,j,K],ee=e.length===4?E("zero_points",12,e[3].dims.length):void 0;ee&&W.push(ee);let ue=A.length,Z=M("output",e[0].dataType,ue,y),J=me(e[0].dataType),Q=(()=>{switch(h){case 1:return`array<${J}, 8>`;case 2:return`mat4x2<${J}>`;case 4:return`mat2x4<${J}>`;default:throw new Error(`${h}-component is not supported.`)}})(),ne=()=>{let $e=` + }`},T=[{dims:l,dataType:e[0].dataType}];return $&&T.push({dims:_,dataType:1}),v&&T.push({dims:_,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${y};${r};${n}`,inputDependencies:g},getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(p/64)},programUniforms:x}),getShaderSource:S}},Fl=(e,t)=>{nh(e.inputs),e.compute(oh(e.inputs,t,e.outputCount))}});var ih,jl,Kl=R(()=>{"use strict";oe();en();tn();ih=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},jl=e=>{ih(e.inputs);let t=et.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let r=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];if(r<8&&n<8)e.compute(Jr(e.inputs,{activation:""},t));else{let o=t[t.length-2],i=k.size(e.inputs[0].dims.slice(0,-2)),a=k.size(e.inputs[1].dims.slice(0,-2));if(i!==1&&o===1&&a===1){let l=e.inputs[0].reshape([1,i,n]),d=e.inputs[1].reshape([1,n,r]),p=[1,i,r],m=[l,d];e.compute(tr(m,{activation:""},t,p),{inputs:m})}else e.compute(tr(e.inputs,{activation:""},t))}}});var ah,sh,uh,Yl,Zl,Ql=R(()=>{"use strict";te();oe();Se();ae();ah=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],n=r.dims.length;if(r.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let o=Math.floor((t.k+t.blockSize-1)/t.blockSize),i=t.blockSize/8*t.bits,a=e[1];if(!k.areEqual(a.dims,[t.n,o,i]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let d=e[2].dims;if(k.size(d)!==t.n*o)throw new Error("scales input size error.");if(e.length===4){let m=e[3].dims,u=t.bits>4?t.n*o:t.n*Math.floor((o+1)/2);if(k.size(m)!==u)throw new Error("zeroPoints input size error.")}},sh=(e,t)=>{let r=e[0].dims,n=r.length,o=r[n-2],i=t.k,a=t.n,l=r.slice(0,n-2),d=k.size(l),m=e[1].dims[2]/4,u=e[0].dataType,h=me(t.k),_=me(m),y=me(a),g=l.concat([o,a]),x=o>1&&a/y%2===0?2:1,$=k.size(g)/y/x,v=64,S=[],T=[d,o,i/h],C=k.convertShape(e[1].dims).slice();C.splice(-1,1,m/_),S.push(...N(T)),S.push(...N(C)),S.push(...N(e[2].dims)),e.length===4&&S.push(...N(k.convertShape(e[3].dims)));let A=[d,o,a/y];S.push(...N(A));let P=O=>{let U=T.length,G=E("a",e[0].dataType,U,h),q=E("b",12,C.length,_),K=E("scales",e[2].dataType,e[2].dims.length),W=[G,q,K],Y=e.length===4?E("zero_points",12,e[3].dims.length):void 0;Y&&W.push(Y);let se=A.length,X=M("output",e[0].dataType,se,y),re=ye(e[0].dataType),ee=(()=>{switch(h){case 1:return`array<${re}, 8>`;case 2:return`mat4x2<${re}>`;case 4:return`mat2x4<${re}>`;default:throw new Error(`${h}-component is not supported.`)}})(),ne=()=>{let $e=` // reuse a data - var input_offset = ${L.indicesToOffset(`${L.type.indices}(batch, row, word_offset)`)}; - var a_data: ${Q}; + var input_offset = ${G.indicesToOffset(`${G.type.indices}(batch, row, word_offset)`)}; + var a_data: ${ee}; for (var j: u32 = 0; j < ${8/h}; j++) { - a_data[j] = ${L.getByOffset("input_offset")}; + a_data[j] = ${G.getByOffset("input_offset")}; input_offset++; } `;for(let de=0;de> 4) & b_mask); - b_quantized_values = ${Q}(${Array.from({length:4},(N,q)=>`${J}(b_value_lower[${q}]), ${J}(b_value_upper[${q}])`).join(", ")}); - b_dequantized_values = ${(()=>h===1?`${Q}(${Array.from({length:8},(N,q)=>`(b_quantized_values[${q}] - ${ee?`zero_point${de}`:"zero_point"}) * scale${de}`).join(", ")});`:`(b_quantized_values - ${Q}(${Array(8).fill(`${ee?`zero_point${de}`:"zero_point"}`).join(",")})) * scale${de};`)()}; - workgroup_shared[local_id.x * ${x} + ${Math.floor(de/y)}]${y>1?`[${de%y}]`:""} += ${Array.from({length:8/h},(N,q)=>`${h===1?`a_data[${q}] * b_dequantized_values[${q}]`:`dot(a_data[${q}], b_dequantized_values[${q}])`}`).join(" + ")}; - `;return $e},we=()=>{let $e=` + b_quantized_values = ${ee}(${Array.from({length:4},(V,j)=>`${re}(b_value_lower[${j}]), ${re}(b_value_upper[${j}])`).join(", ")}); + b_dequantized_values = ${(()=>h===1?`${ee}(${Array.from({length:8},(V,j)=>`(b_quantized_values[${j}] - ${Y?`zero_point${de}`:"zero_point"}) * scale${de}`).join(", ")});`:`(b_quantized_values - ${ee}(${Array(8).fill(`${Y?`zero_point${de}`:"zero_point"}`).join(",")})) * scale${de};`)()}; + workgroup_shared[local_id.x * ${x} + ${Math.floor(de/y)}]${y>1?`[${de%y}]`:""} += ${Array.from({length:8/h},(V,j)=>`${h===1?`a_data[${j}] * b_dequantized_values[${j}]`:`dot(a_data[${j}], b_dequantized_values[${j}])`}`).join(" + ")}; + `;return $e},ve=()=>{let $e=` var col_index = col * ${y}; - ${ee?` + ${Y?` let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; var zero_point_byte_count: u32; var zero_point_word_index: u32; @@ -5814,29 +5617,29 @@ fn calculateOutputIndex(index: u32) -> u32 { var zero_point_bits_offset: u32; var zero_point_word: u32;`:` // The default zero point is 8 for unsigned 4-bit quantization. - let zero_point = ${J}(8);`} + let zero_point = ${re}(8);`} `;for(let de=0;de> 0x1u); zero_point_word_index = zero_point_byte_count >> 0x2u; zero_point_byte_offset = zero_point_byte_count & 0x3u; zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); - zero_point_word = ${ee.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; - let zero_point${de} = ${J}((zero_point_word) & 0xFu);`:""} - col_index += 1;`;return $e},Ae=()=>{let $e=`col_index = col * ${y};`;for(let de=0;de> zero_point_bits_offset; + let zero_point${de} = ${re}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return $e},Be=()=>{let $e=`col_index = col * ${y};`;for(let de=0;de; var b_value_upper: vec4; - var b_quantized_values: ${Q}; - var b_dequantized_values: ${Q};`,$e};return` - var workgroup_shared: array<${Z.type.value}, ${x*v}>; - ${O.declareVariables(...W,Z)} + var b_quantized_values: ${ee}; + var b_dequantized_values: ${ee};`,$e};return` + var workgroup_shared: array<${X.type.value}, ${x*v}>; + ${O.declareVariables(...W,X)} ${O.mainStart([v,1,1])} - let output_indices = ${Z.offsetToIndices(`(global_idx / ${v}) * ${x}`)}; + let output_indices = ${X.offsetToIndices(`(global_idx / ${v}) * ${x}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; @@ -5845,10 +5648,10 @@ fn calculateOutputIndex(index: u32) -> u32 { for (var block = local_id.x; block < nBlocksPerCol; block += ${v}) { //process one block var word_offset: u32 = block * ${t.blockSize/h}; - ${we()} - for (var word: u32 = 0; word < ${m}; word += ${w}) { - ${Ae()} - for (var i: u32 = 0; i < ${w}; i++) { + ${ve()} + for (var word: u32 = 0; word < ${m}; word += ${_}) { + ${Be()} + for (var i: u32 = 0; i < ${_}; i++) { ${ne()} word_offset += ${8/h}; } @@ -5857,25 +5660,25 @@ fn calculateOutputIndex(index: u32) -> u32 { workgroupBarrier(); if (local_id.x < ${x}) { - var output_value: ${Z.type.value} = ${Z.type.value}(0); + var output_value: ${X.type.value} = ${X.type.value}(0); var workgroup_shared_offset: u32 = local_id.x; for (var b: u32 = 0u; b < ${v}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${x}; } - ${Z.setByIndices(`${Z.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + ${X.setByIndices(`${X.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } - }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${h};${w};${y};${x};${v}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:g,dataType:u}],dispatchGroup:{x:$},programUniforms:S}),getShaderSource:P}},uh=(e,t)=>{let r=e[0].dims,n=r.length,o=r[n-2],i=t.k,a=t.n,l=r.slice(0,n-2),d=k.size(l),m=e[1].dims[2]/4,u=e[0].dataType,h=ye(t.k),w=ye(m),y=l.concat([o,a]),g=128,x=a%8===0?8:a%4===0?4:1,$=g/x,v=$*w*8,S=v/h,T=v/t.blockSize,C=k.size(y)/x,A=[],P=[d,o,i/h],O=k.convertShape(e[1].dims).slice();O.splice(-1,1,m/w),A.push(...V(P)),A.push(...V(O)),A.push(...V(e[2].dims)),e.length===4&&A.push(...V(k.convertShape(e[3].dims)));let U=[d,o,a];A.push(...V(U));let L=j=>{let K=P.length,W=E("a",e[0].dataType,K,h),ee=E("b",12,O.length,w),ue=E("scales",e[2].dataType,e[2].dims.length),Z=[W,ee,ue],J=e.length===4?E("zero_points",12,e[3].dims.length):void 0;J&&Z.push(J);let Q=U.length,ne=M("output",e[0].dataType,Q),we=me(e[0].dataType),Ae=()=>{switch(h){case 1:return` - let a_data0 = vec4<${we}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); - let a_data1 = vec4<${we}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` - let a_data0 = vec4<${we}>(sub_a[word_offset], sub_a[word_offset + 1]); - let a_data1 = vec4<${we}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` + }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${h};${_};${y};${x};${v}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:g,dataType:u}],dispatchGroup:{x:$},programUniforms:S}),getShaderSource:P}},uh=(e,t)=>{let r=e[0].dims,n=r.length,o=r[n-2],i=t.k,a=t.n,l=r.slice(0,n-2),d=k.size(l),m=e[1].dims[2]/4,u=e[0].dataType,h=me(t.k),_=me(m),y=l.concat([o,a]),g=128,x=a%8===0?8:a%4===0?4:1,$=g/x,v=$*_*8,S=v/h,T=v/t.blockSize,C=k.size(y)/x,A=[],P=[d,o,i/h],O=k.convertShape(e[1].dims).slice();O.splice(-1,1,m/_),A.push(...N(P)),A.push(...N(O)),A.push(...N(e[2].dims)),e.length===4&&A.push(...N(k.convertShape(e[3].dims)));let U=[d,o,a];A.push(...N(U));let G=q=>{let K=P.length,W=E("a",e[0].dataType,K,h),Y=E("b",12,O.length,_),se=E("scales",e[2].dataType,e[2].dims.length),X=[W,Y,se],re=e.length===4?E("zero_points",12,e[3].dims.length):void 0;re&&X.push(re);let ee=U.length,ne=M("output",e[0].dataType,ee),ve=ye(e[0].dataType),Be=()=>{switch(h){case 1:return` + let a_data0 = vec4<${ve}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${ve}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` + let a_data0 = vec4<${ve}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${ve}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` let a_data0 = sub_a[word_offset]; let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${h}-component is not supported.`)}};return` var sub_a: array<${W.type.value}, ${S}>; var inter_results: array, ${x}>; - ${j.declareVariables(...Z,ne)} - ${j.mainStart([$,x,1])} + ${q.declareVariables(...X,ne)} + ${q.mainStart([$,x,1])} let output_indices = ${ne.offsetToIndices(`workgroup_index * ${x}`)}; let col = output_indices[2]; let row = output_indices[1]; @@ -5902,27 +5705,27 @@ fn calculateOutputIndex(index: u32) -> u32 { // each thread process one block let b_row = col + local_id.y; let block = tile * ${T} + local_id.x; - ${J?` + ${re?` let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); let zero_point_word_index = zero_point_byte_count >> 0x2u; let zero_point_byte_offset = zero_point_byte_count & 0x3u; let zero_point_nibble_offset: u32 = block & 0x1u; let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); - let zero_point_word = ${J.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; - let zero_point = ${we}((zero_point_word) & 0xFu);`:` + let zero_point_word = ${re.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${ve}((zero_point_word) & 0xFu);`:` // The default zero point is 8 for unsigned 4-bit quantization. - let zero_point = ${we}(8);`} - let scale = ${ue.getByOffset("b_row * n_blocks_per_col + block")}; - let b_data = ${ee.getByIndices(`${ee.type.indices}(b_row, block, 0)`)}; + let zero_point = ${ve}(8);`} + let scale = ${se.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${Y.getByIndices(`${Y.type.indices}(b_row, block, 0)`)}; var word_offset = local_id.x * ${t.blockSize/h}; - for (var i: u32 = 0; i < ${w}; i++) { - ${Ae()} - let b_value = ${w===1?"b_data":"b_data[i]"}; + for (var i: u32 = 0; i < ${_}; i++) { + ${Be()} + let b_value = ${_===1?"b_data":"b_data[i]"}; let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); - let b_quantized_values = mat2x4<${we}>(${Array.from({length:4},($e,de)=>`${we}(b_value_lower[${de}]), ${we}(b_value_upper[${de}])`).join(", ")}); - let b_dequantized_values = (b_quantized_values - mat2x4<${we}>(${Array(8).fill("zero_point").join(",")})) * scale; + let b_quantized_values = mat2x4<${ve}>(${Array.from({length:4},($e,de)=>`${ve}(b_value_lower[${de}]), ${ve}(b_value_upper[${de}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${ve}>(${Array(8).fill("zero_point").join(",")})) * scale; inter_results[local_id.y][local_id.x] += ${Array.from({length:2},($e,de)=>`${`dot(a_data${de}, b_dequantized_values[${de}])`}`).join(" + ")}; word_offset += ${8/h}; } @@ -5939,7 +5742,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${ne.setByIndices(`${ne.type.indices}(batch, row, col + local_idx)`,"output_value")} } } - }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${h};${w};${$};${x}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:y,dataType:u}],dispatchGroup:{x:C},programUniforms:A}),getShaderSource:L}},Yl=(e,t)=>{ah(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(uh(e.inputs,t)):e.compute(sh(e.inputs,t))},Zl=e=>re(e)});var lh,dh,ch,ph,mh,fh,hh,gh,Ql,Jl=R(()=>{"use strict";te();oe();ae();lh=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},dh=(e,t,r)=>{let n="";for(let o=t-1;o>=0;--o)n+=` + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${h};${_};${$};${x}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:y,dataType:u}],dispatchGroup:{x:C},programUniforms:A}),getShaderSource:G}},Yl=(e,t)=>{ah(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(uh(e.inputs,t)):e.compute(sh(e.inputs,t))},Zl=e=>J(e)});var lh,dh,ch,ph,mh,fh,hh,gh,Xl,Jl=R(()=>{"use strict";te();oe();ae();lh=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},dh=(e,t,r)=>{let n="";for(let o=t-1;o>=0;--o)n+=` k = i32(${e.indicesGet("indices",o)}) - ${F("uniforms.pads",o,r)}; if (k < 0) { break; @@ -6002,17 +5805,17 @@ fn calculateOutputIndex(index: u32) -> u32 { var k = 0; ${n} value = x[offset]; - `},fh=(e,t,r)=>{switch(r.mode){case 0:return dh(e,t,r.pads.length);case 1:return ch(e,t,r.pads.length);case 2:return ph(e,t,r.pads.length);case 3:return mh(e,t,r.pads.length);default:throw new Error("Invalid mode")}},hh=(e,t)=>{let r=k.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,o=k.size(r),i=[{type:12,data:o},{type:6,data:t.pads}],a=e.length>=3&&e[2].data;t.mode===0&&i.push({type:a?e[2].dataType:1,data:t.value}),i.push(...V(e[0].dims,r));let l=["rank"],d=c=>{let m=M("output",e[0].dataType,r.length),u=E("x",e[0].dataType,n.length),h=u.type.value,w=fh(m,n.length,t),y=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&y.push({name:"constant_value",type:a?h:"f32"}),` - ${c.registerUniforms(y).declareVariables(u,m)} - ${c.mainStart()} - ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + `},fh=(e,t,r)=>{switch(r.mode){case 0:return dh(e,t,r.pads.length);case 1:return ch(e,t,r.pads.length);case 2:return ph(e,t,r.pads.length);case 3:return mh(e,t,r.pads.length);default:throw new Error("Invalid mode")}},hh=(e,t)=>{let r=k.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,o=k.size(r),i=[{type:12,data:o},{type:6,data:t.pads}],a=e.length>=3&&e[2].data;t.mode===0&&i.push({type:a?e[2].dataType:1,data:t.value}),i.push(...N(e[0].dims,r));let l=["rank"],d=p=>{let m=M("output",e[0].dataType,r.length),u=E("x",e[0].dataType,n.length),h=u.type.value,_=fh(m,n.length,t),y=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&y.push({name:"constant_value",type:a?h:"f32"}),` + ${p.registerUniforms(y).declareVariables(u,m)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${m.offsetToIndices("global_idx")}; var value = ${h}(0); - ${w} + ${_} output[global_idx] = value; - }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${a}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k.size(r)/64)},programUniforms:i}),getShaderSource:d}},gh=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,i=new Int32Array(2*o).fill(0);if(e.length>=4){let l=e[3].getBigInt64Array();for(let d=0;di[Number(d)]=Number(l));let a=[];return i.forEach(l=>a.push(l)),{mode:t.mode,value:n,pads:a}}else return t},Ql=(e,t)=>{lh(e.inputs);let r=gh(e.inputs,t);e.compute(hh(e.inputs,r),{inputs:[0]})}});var un,ed,td,rd,nd,bh,yh,od,id,ad,sd,ud,ld,dd,cd,pd,md,fd,hd,gd=R(()=>{"use strict";He();te();oe();ae();un=e=>{if(ve.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},ed=(e,t,r)=>{let n=t.format==="NHWC",o=e.dims.slice();n&&o.splice(1,0,o.pop());let i=Object.hasOwnProperty.call(t,"dilations"),a=t.kernelShape.slice(),l=t.strides.slice(),d=i?t.dilations.slice():[],c=t.pads.slice();It.adjustPoolAttributes(r,o,a,l,d,c);let m=It.computePoolOutputShape(r,o,l,d,a,c,t.autoPad),u=Object.assign({},t);i?Object.assign(u,{kernelShape:a,strides:l,pads:c,dilations:d,cacheKey:t.cacheKey}):Object.assign(u,{kernelShape:a,strides:l,pads:c,cacheKey:t.cacheKey});let h=m.slice();return h.push(h.splice(1,1)[0]),[u,n?h:m]},td=(e,t)=>{let r=t.format==="NHWC",n=k.size(e),o=k.size(t.kernelShape),i=[{type:12,data:n},{type:12,data:o}],a=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let l=t.kernelShape[t.kernelShape.length-1],d=t.strides[t.strides.length-1],c=t.pads[t.pads.length/2-1],m=t.pads[t.pads.length-1],u=!!(c+m);i.push({type:12,data:l},{type:12,data:d},{type:12,data:c},{type:12,data:m}),a.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let h=!1;if(t.kernelShape.length===2){let w=t.kernelShape[t.kernelShape.length-2],y=t.strides[t.strides.length-2],g=t.pads[t.pads.length/2-2],x=t.pads[t.pads.length-2];h=!!(g+x),i.push({type:12,data:w},{type:12,data:y},{type:12,data:g},{type:12,data:x}),a.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[i,a,!0,u,h]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let l=k.computeStrides(t.kernelShape);i.push({type:12,data:l},{type:12,data:t.pads},{type:12,data:t.strides}),a.push({name:"kernelStrides",type:"u32",length:l.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let d=t.pads.reduce((c,m)=>c+m);return[i,a,!!d,!1,!1]}},rd=(e,t,r,n,o,i,a,l,d,c,m,u)=>{let h=o.format==="NHWC",w=t.type.value,y=M("output",t.type.tensor,n);if(o.kernelShape.length<=2){let g="",x="",$="",v=r-(h?2:1);if(m?g=` + }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${a}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k.size(r)/64)},programUniforms:i}),getShaderSource:d}},gh=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,i=new Int32Array(2*o).fill(0);if(e.length>=4){let l=e[3].getBigInt64Array();for(let d=0;di[Number(d)]=Number(l));let a=[];return i.forEach(l=>a.push(l)),{mode:t.mode,value:n,pads:a}}else return t},Xl=(e,t)=>{lh(e.inputs);let r=gh(e.inputs,t);e.compute(hh(e.inputs,r),{inputs:[0]})}});var on,ed,td,rd,nd,bh,yh,od,id,ad,sd,ud,ld,dd,cd,pd,md,fd,hd,gd=R(()=>{"use strict";We();te();oe();ae();on=e=>{if(we.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},ed=(e,t,r)=>{let n=t.format==="NHWC",o=e.dims.slice();n&&o.splice(1,0,o.pop());let i=Object.hasOwnProperty.call(t,"dilations"),a=t.kernelShape.slice(),l=t.strides.slice(),d=i?t.dilations.slice():[],p=t.pads.slice();It.adjustPoolAttributes(r,o,a,l,d,p);let m=It.computePoolOutputShape(r,o,l,d,a,p,t.autoPad),u=Object.assign({},t);i?Object.assign(u,{kernelShape:a,strides:l,pads:p,dilations:d,cacheKey:t.cacheKey}):Object.assign(u,{kernelShape:a,strides:l,pads:p,cacheKey:t.cacheKey});let h=m.slice();return h.push(h.splice(1,1)[0]),[u,n?h:m]},td=(e,t)=>{let r=t.format==="NHWC",n=k.size(e),o=k.size(t.kernelShape),i=[{type:12,data:n},{type:12,data:o}],a=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let l=t.kernelShape[t.kernelShape.length-1],d=t.strides[t.strides.length-1],p=t.pads[t.pads.length/2-1],m=t.pads[t.pads.length-1],u=!!(p+m);i.push({type:12,data:l},{type:12,data:d},{type:12,data:p},{type:12,data:m}),a.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let h=!1;if(t.kernelShape.length===2){let _=t.kernelShape[t.kernelShape.length-2],y=t.strides[t.strides.length-2],g=t.pads[t.pads.length/2-2],x=t.pads[t.pads.length-2];h=!!(g+x),i.push({type:12,data:_},{type:12,data:y},{type:12,data:g},{type:12,data:x}),a.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[i,a,!0,u,h]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let l=k.computeStrides(t.kernelShape);i.push({type:12,data:l},{type:12,data:t.pads},{type:12,data:t.strides}),a.push({name:"kernelStrides",type:"u32",length:l.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let d=t.pads.reduce((p,m)=>p+m);return[i,a,!!d,!1,!1]}},rd=(e,t,r,n,o,i,a,l,d,p,m,u)=>{let h=o.format==="NHWC",_=t.type.value,y=M("output",t.type.tensor,n);if(o.kernelShape.length<=2){let g="",x="",$="",v=r-(h?2:1);if(m?g=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${v}] < 0 || xIndices[${v}] @@ -6048,7 +5851,7 @@ fn calculateOutputIndex(index: u32) -> u32 { let indices = ${y.offsetToIndices("global_idx")}; var xIndices = ${y.offsetToIndices("global_idx")}; - var value = ${w}(${l}); + var value = ${_}(${l}); var pad = 0; ${x} ${g} @@ -6056,7 +5859,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${a} output[global_idx] = value; - }`}else{if(h)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let g=o.kernelShape.length,x=o.pads.length,$="";return c?$=` + }`}else{if(h)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let g=o.kernelShape.length,x=o.pads.length,$="";return p?$=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; @@ -6080,7 +5883,7 @@ fn calculateOutputIndex(index: u32) -> u32 { var offsets: array; - var value = ${w}(${l}); + var value = ${_}(${l}); var pad = 0; var isPad = false; @@ -6101,12 +5904,12 @@ fn calculateOutputIndex(index: u32) -> u32 { ${a} output[global_idx] = value; - }`}},nd=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,bh=e=>`${nd(e)};${e.countIncludePad}`,yh=e=>`${nd(e)};${e.storageOrder};${e.dilations}`,od=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),id=(e,t,r,n)=>{let[o,i]=ed(t,n,r),a=E("x",t.dataType,t.dims.length),l=a.type.value,d="value += x_val;",c="";o.countIncludePad?c+=`value /= ${l}(uniforms.kernelSize);`:c+=`value /= ${l}(i32(uniforms.kernelSize) - pad);`;let[m,u,h,w,y]=td(i,o);m.push(...V(t.dims,i));let g=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${h};${w};${y}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(k.size(i)/64)},programUniforms:m}),getShaderSource:x=>rd(x,a,t.dims.length,i.length,o,d,c,0,u,h,w,y)}},ad=e=>{let t=e.count_include_pad!==0,r=od(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...r,cacheKey:""};return{...n,cacheKey:bh(n)}},sd=(e,t)=>{un(e.inputs),e.compute(id("AveragePool",e.inputs[0],!1,t))},ud={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},ld=e=>{let t=e.format;return{format:t,...ud,cacheKey:t}},dd=(e,t)=>{un(e.inputs),e.compute(id("GlobalAveragePool",e.inputs[0],!0,t))},cd=(e,t,r,n)=>{let[o,i]=ed(t,n,r),a=` + }`}},nd=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,bh=e=>`${nd(e)};${e.countIncludePad}`,yh=e=>`${nd(e)};${e.storageOrder};${e.dilations}`,od=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),id=(e,t,r,n)=>{let[o,i]=ed(t,n,r),a=E("x",t.dataType,t.dims.length),l=a.type.value,d="value += x_val;",p="";o.countIncludePad?p+=`value /= ${l}(uniforms.kernelSize);`:p+=`value /= ${l}(i32(uniforms.kernelSize) - pad);`;let[m,u,h,_,y]=td(i,o);m.push(...N(t.dims,i));let g=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${h};${_};${y}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(k.size(i)/64)},programUniforms:m}),getShaderSource:x=>rd(x,a,t.dims.length,i.length,o,d,p,0,u,h,_,y)}},ad=e=>{let t=e.count_include_pad!==0,r=od(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...r,cacheKey:""};return{...n,cacheKey:bh(n)}},sd=(e,t)=>{on(e.inputs),e.compute(id("AveragePool",e.inputs[0],!1,t))},ud={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},ld=e=>{let t=e.format;return{format:t,...ud,cacheKey:t}},dd=(e,t)=>{on(e.inputs),e.compute(id("GlobalAveragePool",e.inputs[0],!0,t))},cd=(e,t,r,n)=>{let[o,i]=ed(t,n,r),a=` value = max(x_val, value); - `,l="",d=E("x",t.dataType,t.dims.length),c=["rank"],[m,u,h,w,y]=td(i,o);return m.push(...V(t.dims,i)),{name:e,shaderCache:{hint:`${n.cacheKey};${h};${w};${y}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(k.size(i)/64)},programUniforms:m}),getShaderSource:g=>rd(g,d,t.dims.length,i.length,o,a,l,t.dataType===10?-65504:-1e5,u,h,w,y)}},pd=(e,t)=>{un(e.inputs),e.compute(cd("MaxPool",e.inputs[0],!1,t))},md=e=>{let t=e.storage_order,r=e.dilations,n=od(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let o={storageOrder:t,dilations:r,...n,cacheKey:""};return{...o,cacheKey:yh(o)}},fd=e=>{let t=e.format;return{format:t,...ud,cacheKey:t}},hd=(e,t)=>{un(e.inputs),e.compute(cd("GlobalMaxPool",e.inputs[0],!0,t))}});var _h,vh,bd,yd,wd=R(()=>{"use strict";te();oe();Ie();ae();_h=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((r,n)=>r===e[2].dims[n]).reduce((r,n)=>r&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((o,i)=>i===t.axis||o===e[0].dims[i]).reduce((o,i)=>o&&i,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let r=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},vh=(e,t)=>{let r=k.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,o=n===3,i=e[0].dims,a=e[1].dataType,l=k.size(i),d=n===3||n===2,c=d?[Math.ceil(k.size(e[0].dims)/4)]:e[0].dims,m=e[1].dims,u=e.length>2?e[2]:void 0,h=u?d?[Math.ceil(k.size(u.dims)/4)]:u.dims:void 0,w=m.length===0||m.length===1&&m[0]===1,y=w===!1&&m.length===1,g=ye(l),x=w&&(!d||g===4),$=x?g:1,v=x&&!d?g:1,S=E("input",d?12:n,c.length,v),T=E("scale",a,m.length),C=u?E("zero_point",d?12:n,h.length):void 0,A=M("output",a,i.length,$),P=[S,T];C&&P.push(C);let O=[c,m];u&&O.push(h);let U=[{type:12,data:l/$},{type:12,data:r},{type:12,data:t.blockSize},...V(...O,i)],L=j=>{let K=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` - ${j.registerUniforms(K).declareVariables(...P,A)} - ${j.mainStart()} - ${j.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + `,l="",d=E("x",t.dataType,t.dims.length),p=["rank"],[m,u,h,_,y]=td(i,o);return m.push(...N(t.dims,i)),{name:e,shaderCache:{hint:`${n.cacheKey};${h};${_};${y}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(k.size(i)/64)},programUniforms:m}),getShaderSource:g=>rd(g,d,t.dims.length,i.length,o,a,l,t.dataType===10?-65504:-1e5,u,h,_,y)}},pd=(e,t)=>{on(e.inputs),e.compute(cd("MaxPool",e.inputs[0],!1,t))},md=e=>{let t=e.storage_order,r=e.dilations,n=od(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let o={storageOrder:t,dilations:r,...n,cacheKey:""};return{...o,cacheKey:yh(o)}},fd=e=>{let t=e.format;return{format:t,...ud,cacheKey:t}},hd=(e,t)=>{on(e.inputs),e.compute(cd("GlobalMaxPool",e.inputs[0],!0,t))}});var wh,vh,bd,yd,_d=R(()=>{"use strict";te();oe();Se();ae();wh=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((r,n)=>r===e[2].dims[n]).reduce((r,n)=>r&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((o,i)=>i===t.axis||o===e[0].dims[i]).reduce((o,i)=>o&&i,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let r=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},vh=(e,t)=>{let r=k.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,o=n===3,i=e[0].dims,a=e[1].dataType,l=k.size(i),d=n===3||n===2,p=d?[Math.ceil(k.size(e[0].dims)/4)]:e[0].dims,m=e[1].dims,u=e.length>2?e[2]:void 0,h=u?d?[Math.ceil(k.size(u.dims)/4)]:u.dims:void 0,_=m.length===0||m.length===1&&m[0]===1,y=_===!1&&m.length===1,g=me(l),x=_&&(!d||g===4),$=x?g:1,v=x&&!d?g:1,S=E("input",d?12:n,p.length,v),T=E("scale",a,m.length),C=u?E("zero_point",d?12:n,h.length):void 0,A=M("output",a,i.length,$),P=[S,T];C&&P.push(C);let O=[p,m];u&&O.push(h);let U=[{type:12,data:l/$},{type:12,data:r},{type:12,data:t.blockSize},...N(...O,i)],G=q=>{let K=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${q.registerUniforms(K).declareVariables(...P,A)} + ${q.mainStart()} + ${q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${A.offsetToIndices("global_idx")}; // Set input x @@ -6116,7 +5919,7 @@ fn calculateOutputIndex(index: u32) -> u32 { let x_value = ${$===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${S.getByOffset("global_idx")};`)()}; // Set scale input - ${(()=>w?`let scale_value= ${T.getByOffset("0")}`:y?` + ${(()=>_?`let scale_value= ${T.getByOffset("0")}`:y?` let scale_index = ${A.indicesGet("output_indices","uniforms.axis")}; let scale_value= ${T.getByOffset("scale_index")};`:` var scale_indices: ${T.type.indices} = output_indices; @@ -6125,7 +5928,7 @@ fn calculateOutputIndex(index: u32) -> u32 { let scale_value= ${T.getByIndices("scale_indices")};`)()}; // Set zero-point input - ${(()=>C?w?d?` + ${(()=>C?_?d?` let zero_point_input = ${C.getByOffset("0")}; let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${C.getByOffset("0")}`:y?d?` @@ -6141,13 +5944,59 @@ fn calculateOutputIndex(index: u32) -> u32 { let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${C.getByIndices("scale_indices")};`:`let zero_point_value = ${d?o?"i32":"u32":S.type.value}(0);`)()}; // Compute and write output ${A.setByOffset("global_idx",`${A.type.value}(x_value - zero_point_value) * scale_value`)}; - }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:C?["rank","rank","rank"]:["rank","rank"]},getShaderSource:L,getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:Math.ceil(l/$/64),y:1,z:1},programUniforms:U})}},bd=(e,t)=>{_h(e.inputs,t),e.compute(vh(e.inputs,t))},yd=e=>re({axis:e.axis,blockSize:e.blockSize})});var $h,xh,_d,vd=R(()=>{"use strict";He();te();ae();$h=(e,t,r)=>{let n=e===t,o=et&&r>0;if(n||o||i)throw new Error("Range these inputs' contents are invalid.")},xh=(e,t,r,n)=>{let o=Math.abs(Math.ceil((t-e)/r)),i=[o],a=o,l=[{type:12,data:a},{type:n,data:e},{type:n,data:r},...V(i)],d=c=>{let m=M("output",n,i.length),u=m.type.value,h=[{name:"outputSize",type:"u32"},{name:"start",type:u},{name:"delta",type:u}];return` - ${c.registerUniforms(h).declareVariables(m)} - ${c.mainStart()} - ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:C?["rank","rank","rank"]:["rank","rank"]},getShaderSource:G,getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:Math.ceil(l/$/64),y:1,z:1},programUniforms:U})}},bd=(e,t)=>{wh(e.inputs,t),e.compute(vh(e.inputs,t))},yd=e=>J({axis:e.axis,blockSize:e.blockSize})});var $h,xh,wd,vd=R(()=>{"use strict";We();te();ae();$h=(e,t,r)=>{let n=e===t,o=et&&r>0;if(n||o||i)throw new Error("Range these inputs' contents are invalid.")},xh=(e,t,r,n)=>{let o=Math.abs(Math.ceil((t-e)/r)),i=[o],a=o,l=[{type:12,data:a},{type:n,data:e},{type:n,data:r},...N(i)],d=p=>{let m=M("output",n,i.length),u=m.type.value,h=[{name:"outputSize",type:"u32"},{name:"start",type:u},{name:"delta",type:u}];return` + ${p.registerUniforms(h).declareVariables(m)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${u}(global_idx) * uniforms.delta; - }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:d,getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l})}},_d=e=>{let t=0,r=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),ve.webgpu.validateInputContent&&$h(t,r,n),e.compute(xh(t,r,n,e.inputs[0].dataType),{inputs:[]})}});var Sh,Th,Ih,Ch,Ah,kh,Eh,Ph,zh,Oh,Dh,$d,Bh,Mh,Rh,Uh,Vh,xd,Sd,Td=R(()=>{"use strict";te();oe();Ie();ae();Sh=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and - one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},Th=(e,t,r)=>{t.every(o=>o>=0&&o{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(r).fill(1);return t.forEach((o,i)=>n[o]=e[i]),n},Ih=(e,t,r,n,o,i)=>{let[a,l,d]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],c=e[0].dims.length;if(a>0&&e.length>a&&e[a].dims.length>0)e[a].getFloat32Array().forEach(m=>i.push(m));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0){if(e[l].getFloat32Array().forEach(m=>n.push(m)),n.length!==0&&n.length!==c&&r>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Sh(n,t),t.axes.length>0&&Th(n,t.axes,c).forEach((m,u)=>n[u]=m)}if(d>0&&e.length>d&&e[d].dims.length===1&&e[d].dims[0]>0&&(e[d].getBigInt64Array().forEach(m=>o.push(Number(m))),o.length!==0&&o.length!==c&&r>=18&&o.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(o.length!==0&&o.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof o<"u"&&n.length>0&&o.length>c)throw new Error("Resize requires only of scales or sizes to be specified")},Ch=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:d,getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l})}},wd=e=>{let t=0,r=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),we.webgpu.validateInputContent&&$h(t,r,n),e.compute(xh(t,r,n,e.inputs[0].dataType),{inputs:[]})}});var Sh,Th,$d,xd,Sd=R(()=>{"use strict";te();oe();Se();ae();Sh=(e,t,r,n)=>{if(e!=="none"&&n!=="i32"&&n!=="u32"&&n!=="f32")throw new Error(`Input ${n} is not supported with reduction ${e}.`);let o=`{ + var oldValue = 0; + loop { + let newValueF32 =`,i=`; + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`;switch(e){case"none":return`${t}=${r};`;case"add":return n==="i32"||n==="u32"?`atomicAdd(&${t}, bitcast<${n}>(${r}));`:` + ${o}bitcast<${n}>(oldValue) + (${r})${i}`;case"max":return n==="i32"||n==="u32"?`atomicMax(&${t}, bitcast<${n}>(${r}));`:` + ${o}max(bitcast(oldValue), (${r}))${i}`;case"min":return n==="i32"||n==="u32"?`atomicMin(&${t}, bitcast<${n}>(${r}));`:`${o}min(bitcast<${n}>(oldValue), (${r}))${i}`;case"mul":return`${o}(bitcast<${n}>(oldValue) * (${r}))${i}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Th=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r,i=1,a=Math.ceil(k.size(n)/i),l=n[n.length-1],d=k.sizeFromDimension(r,l),p=[{type:12,data:a},{type:12,data:l},{type:12,data:d},...N(e[1].dims,e[2].dims,o)],m=u=>{let h=E("indices",e[1].dataType,e[1].dims.length),_=E("updates",e[2].dataType,e[2].dims.length,i),y=t.reduction!=="none"&&t.reduction!==""?es("output",e[0].dataType,o.length):M("output",e[0].dataType,o.length,i);return` + ${u.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(h,_,y)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var data_offset = 0u; + let indices_start = uniforms.last_index_dimension * global_idx; + let indices_end = indices_start + uniforms.last_index_dimension; + for (var i = indices_start; i < indices_end; i++) { + var index = i32(indices[i].x); + ${e[0].dims.length===1?` + let element_count_dim = uniforms.output_strides; + let dim_value = uniforms.output_shape;`:` + let element_count_dim = uniforms.output_strides[i - indices_start]; + let dim_value = uniforms.output_shape[i - indices_start + uniforms.last_index_dimension];`} + if (index >= 0) { + if (index >= i32(dim_value)) { + index = i32(dim_value - 1); + } + } else { + if (index < -i32(dim_value)) { + index = 0; + } else { + index += i32(dim_value); + } + } + data_offset += u32((u32(index) * element_count_dim)); + } + + for (var i = 0u; i < uniforms.num_updates_elements; i++) { + let value = updates[uniforms.num_updates_elements * global_idx + i]; + ${Sh(t.reduction,"output[data_offset + i]","value",y.type.value)} + } + + }`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p}),getShaderSource:m}},$d=e=>J({reduction:e.reduction}),xd=(e,t)=>{e.compute(Th(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}});var Ih,Ch,Ah,kh,Eh,Ph,zh,Oh,Bh,Dh,Mh,Td,Rh,Uh,Nh,Vh,Wh,Id,Cd,Ad=R(()=>{"use strict";te();oe();Se();ae();Ih=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and + one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},Ch=(e,t,r)=>{t.every(o=>o>=0&&o{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(r).fill(1);return t.forEach((o,i)=>n[o]=e[i]),n},Ah=(e,t,r,n,o,i)=>{let[a,l,d]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],p=e[0].dims.length;if(a>0&&e.length>a&&e[a].dims.length>0)e[a].getFloat32Array().forEach(m=>i.push(m));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0){if(e[l].getFloat32Array().forEach(m=>n.push(m)),n.length!==0&&n.length!==p&&r>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Ih(n,t),t.axes.length>0&&Ch(n,t.axes,p).forEach((m,u)=>n[u]=m)}if(d>0&&e.length>d&&e[d].dims.length===1&&e[d].dims[0]>0&&(e[d].getBigInt64Array().forEach(m=>o.push(Number(m))),o.length!==0&&o.length!==p&&r>=18&&o.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(o.length!==0&&o.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof o<"u"&&n.length>0&&o.length>p)throw new Error("Resize requires only of scales or sizes to be specified")},kh=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`return ${t}(xResized) / ${t}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) { return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5; } else { @@ -6172,7 +6021,7 @@ fn calculateOutputIndex(index: u32) -> u32 { const adjustment = ${t}(lengthResized) / outputWidth; const center = ${t}(lengthOriginal) / 2; const offset = center * (1 - adjustment); - return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",Ah=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",kh=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),o=e.length===0?n:e.slice();return t.length>0?(t.forEach((i,a)=>{n[i]=o[a],n[a+r]=o[t.length+a]}),n):o},Eh=(e,t,r,n)=>{let o=[];if(r.length>0)if(n.length>0){if(e.forEach(i=>o.push(i)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((i,a)=>o[i]=r[a])}else r.forEach(i=>o.push(i));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((i,a)=>Math.round(i*t[a]))}return o},Ph=(e,t,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(i=>t[i]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(i=>t[i]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let o=e.slice();return r.axes.length>0?(r.axes.forEach(i=>t[i]=n),r.axes.forEach(i=>o[i]=Math.round(e[i]*t[i]))):(t.fill(n,0,t.length),o.forEach((i,a)=>o[a]=Math.round(i*t[a]))),o},zh=(e,t,r,n,o)=>` + return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",Eh=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",Ph=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),o=e.length===0?n:e.slice();return t.length>0?(t.forEach((i,a)=>{n[i]=o[a],n[a+r]=o[t.length+a]}),n):o},zh=(e,t,r,n)=>{let o=[];if(r.length>0)if(n.length>0){if(e.forEach(i=>o.push(i)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((i,a)=>o[i]=r[a])}else r.forEach(i=>o.push(i));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((i,a)=>Math.round(i*t[a]))}return o},Oh=(e,t,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(i=>t[i]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(i=>t[i]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let o=e.slice();return r.axes.length>0?(r.axes.forEach(i=>t[i]=n),r.axes.forEach(i=>o[i]=Math.round(e[i]*t[i]))):(t.fill(n,0,t.length),o.forEach((i,a)=>o[a]=Math.round(i*t[a]))),o},Bh=(e,t,r,n,o)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> { var original_indices: array<${e.type.value}, ${r.length}>; for (var i:u32 = 0; i < ${r.length}; i++) { @@ -6190,7 +6039,7 @@ fn calculateOutputIndex(index: u32) -> u32 { } } return original_indices; - }`,Oh=(e,t,r,n,o,i,a)=>` + }`,Dh=(e,t,r,n,o,i,a)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; for (var i:u32 = 0; i < ${n.length}; i++) { @@ -6221,7 +6070,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${e.indicesSet("input_indices","i"," input_index")} } return input_indices; - }`,Dh=(e,t)=>` + }`,Mh=(e,t)=>` fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { for (var i:u32 = 0; i < ${t.length}; i++) { var input_index = ${e.indicesGet("input_indices","i")}; @@ -6230,15 +6079,15 @@ fn calculateOutputIndex(index: u32) -> u32 { } } return true; - }`,$d=(e,t,r,n)=>e.rank>n?` + }`,Td=(e,t,r,n)=>e.rank>n?` ${e.indicesSet("input_indices",t,"channel")}; ${e.indicesSet("input_indices",r,"batch")}; -`:"",Bh=(e,t,r,n,o)=>{let[a,l,d,c]=r.length===2?[-1,0,1,-1]:[0,2,3,1],m=e.type.value;return` +`:"",Rh=(e,t,r,n,o)=>{let[a,l,d,p]=r.length===2?[-1,0,1,-1]:[0,2,3,1],m=e.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${m} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",l,`max(0, min(row, ${r[l]} - 1))`)}; ${e.indicesSet("input_indices",d,`max(0, min(col, ${r[d]} - 1))`)}; - ${$d(e,c,a,2)} + ${Td(e,p,a,2)} return ${e.getByIndices("input_indices")}; } @@ -6255,7 +6104,7 @@ fn calculateOutputIndex(index: u32) -> u32 { var col1: u32 = u32(col); var row2: u32 = u32(row + 1); var col2: u32 = u32(col + 1); - var channel: u32 = ${r.length>2?`u32(originalIndices[${c}])`:"0"}; + var channel: u32 = ${r.length>2?`u32(originalIndices[${p}])`:"0"}; var batch: u32 = ${r.length>2?`u32(originalIndices[${a}])`:"0"}; var x11: ${m} = getInputValue(batch, channel, row1, col1); var x12: ${m} = getInputValue(batch, channel, row1, col2); @@ -6274,7 +6123,7 @@ fn calculateOutputIndex(index: u32) -> u32 { dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); - }`},Mh=(e,t,r,n,o,i,a,l,d,c)=>{let m=r.length===2,u=!0,[h,w]=m?[0,1]:u?[2,3]:[1,2],y=e.type.value,g=x=>{let $=x===h?"row":"col";return` + }`},Uh=(e,t,r,n,o,i,a,l,d,p)=>{let m=r.length===2,u=!0,[h,_]=m?[0,1]:u?[2,3]:[1,2],y=e.type.value,g=x=>{let $=x===h?"row":"col";return` fn ${$}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${y} { var output_index = ${t.indicesGet("output_indices",x)}; var originalIdx: ${y} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[x]}, @@ -6289,7 +6138,7 @@ fn calculateOutputIndex(index: u32) -> u32 { for (var i: i32 = -1; i < 3; i++) { var ${$}: ${y} = originalIdx + ${y}(i); if (${$} < 0 || ${$} >= ${r[x]}) { - ${(()=>c?`coefs[i + 1] = 0.0; + ${(()=>p?`coefs[i + 1] = 0.0; continue;`:l?`return ${d};`:`${$} = max(0, min(${$}, ${r[x]} - 1));`)()}; } var input_indices_copy: ${e.type.indices} = input_indices; @@ -6299,7 +6148,7 @@ fn calculateOutputIndex(index: u32) -> u32 { return cubicInterpolation1D(data, coefs); }`};return` ${g(h)}; - ${g(w)}; + ${g(_)}; fn getCubicInterpolationCoefs(s: ${y}) -> array<${y}, 4> { var absS = abs(s); var coeffs: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0); @@ -6322,13 +6171,13 @@ fn calculateOutputIndex(index: u32) -> u32 { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } - `},Rh=(e,t,r,n,o)=>{let[a,l,d,c,m]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],u=e.type.value;return` + `},Nh=(e,t,r,n,o)=>{let[a,l,d,p,m]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],u=e.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${u} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",l,`max(0, min(depth, ${r[l]} - 1))`)}; ${e.indicesSet("input_indices",d,`max(0, min(height, ${r[d]} - 1))`)}; - ${e.indicesSet("input_indices",c,`max(0, min(width, ${r[c]} - 1))`)}; - ${$d(e,m,a,3)} + ${e.indicesSet("input_indices",p,`max(0, min(width, ${r[p]} - 1))`)}; + ${Td(e,m,a,3)} return ${e.getByIndices("input_indices")}; } @@ -6336,14 +6185,14 @@ fn calculateOutputIndex(index: u32) -> u32 { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${u} = originalIndices[${l}]; var height:${u} = originalIndices[${d}]; - var width:${u} = originalIndices[${c}]; - ${n?`if (depth < 0 || depth > (${r[l]} - 1) || height < 0 || height > (${r[d]} - 1) || width < 0 || (width > ${r[c]} - 1)) { + var width:${u} = originalIndices[${p}]; + ${n?`if (depth < 0 || depth > (${r[l]} - 1) || height < 0 || height > (${r[d]} - 1) || width < 0 || (width > ${r[p]} - 1)) { return ${o}; }`:""}; depth = max(0, min(depth, ${r[l]} - 1)); height = max(0, min(height, ${r[d]} - 1)); - width = max(0, min(width, ${r[c]} - 1)); + width = max(0, min(width, ${r[p]} - 1)); var depth1: u32 = u32(depth); var height1: u32 = u32(height); var width1: u32 = u32(width); @@ -6381,24 +6230,24 @@ fn calculateOutputIndex(index: u32) -> u32 { } return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); - }`},Uh=(e,t,r,n,o,i)=>{let a=e.dims,l=kh(i,t.axes,a.length),d=Eh(a,n,o,t.axes),c=n.slice();n.length===0&&(c=a.map((v,S)=>v===0?1:d[S]/v),t.keepAspectRatioPolicy!=="stretch"&&(d=Ph(a,c,t)));let m=M("output",e.dataType,d.length),u=E("input",e.dataType,a.length),h=k.size(d),w=a.length===d.length&&a.every((v,S)=>v===d[S]),y=t.coordinateTransformMode==="tf_crop_and_resize",g=t.extrapolationValue,x=u.type.value,$=v=>` - ${w?"":` - ${Ch(t.coordinateTransformMode,x)}; + }`},Vh=(e,t,r,n,o,i)=>{let a=e.dims,l=Ph(i,t.axes,a.length),d=zh(a,n,o,t.axes),p=n.slice();n.length===0&&(p=a.map((v,S)=>v===0?1:d[S]/v),t.keepAspectRatioPolicy!=="stretch"&&(d=Oh(a,p,t)));let m=M("output",e.dataType,d.length),u=E("input",e.dataType,a.length),h=k.size(d),_=a.length===d.length&&a.every((v,S)=>v===d[S]),y=t.coordinateTransformMode==="tf_crop_and_resize",g=t.extrapolationValue,x=u.type.value,$=v=>` + ${_?"":` + ${kh(t.coordinateTransformMode,x)}; ${(()=>{switch(t.mode){case"nearest":return` - ${Dh(u,a)}; - ${Ah(t.nearestMode,r,x)}; - ${Oh(u,m,a,d,c.length,l.length,y)}; + ${Mh(u,a)}; + ${Eh(t.nearestMode,r,x)}; + ${Dh(u,m,a,d,p.length,l.length,y)}; `;case"linear":return` - ${zh(m,a,d,c.length,l.length)}; - ${(()=>{if(a.length===2||a.length===4)return`${Bh(u,m,a,y,g)}`;if(a.length===3||a.length===5)return`${Rh(u,m,a,y,g)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + ${Bh(m,a,d,p.length,l.length)}; + ${(()=>{if(a.length===2||a.length===4)return`${Rh(u,m,a,y,g)}`;if(a.length===3||a.length===5)return`${Nh(u,m,a,y,g)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` - ${(()=>{if(a.length===2||a.length===4)return`${Mh(u,m,a,d,c,l,t.cubicCoeffA,y,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + ${(()=>{if(a.length===2||a.length===4)return`${Uh(u,m,a,d,p,l,t.cubicCoeffA,y,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; `;default:throw Error("Invalid resize mode")}})()}; `} - ${v.registerUniform("output_size","u32").registerUniform("scales","f32",c.length).registerUniform("roi","f32",l.length).declareVariables(u,m)} + ${v.registerUniform("output_size","u32").registerUniform("scales","f32",p.length).registerUniform("roi","f32",l.length).declareVariables(u,m)} ${v.mainStart()} ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - ${w?"output[global_idx] = input[global_idx];":` + ${_?"output[global_idx] = input[global_idx];":` let output_indices = ${m.offsetToIndices("global_idx")}; var input_indices: ${u.type.indices}; ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); @@ -6408,7 +6257,7 @@ fn calculateOutputIndex(index: u32) -> u32 { output[global_idx] = ${t.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${a.length===2||a.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; `} - }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${c.length>0?c:""}|${o.length>0?o:""}|${l.length>0?l:""}|${w}|${a}`,inputDependencies:["rank"]},getShaderSource:$,getRunData:()=>({outputs:[{dims:d,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:[{type:12,data:h},{type:1,data:c},{type:1,data:l},...V(a,d)]})}},Vh=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},xd=(e,t)=>{let r=[],n=[],o=[],i=Vh(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Ih(e.inputs,t,i,r,n,o),e.compute(Uh(e.inputs[0],t,i,r,n,o),{inputs:[0]})},Sd=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,o=e.cubicCoeffA,i=e.excludeOutside!==0,a=e.extrapolationValue,l=e.keepAspectRatioPolicy,d=e.mode,c=e.nearestMode===""?"simple":e.nearestMode;return re({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:o,excludeOutside:i,extrapolationValue:a,keepAspectRatioPolicy:l,mode:d,nearestMode:c})}});var Nh,Wh,Id,Cd=R(()=>{"use strict";te();oe();Ie();ae();Nh=(e,t)=>{let[r,n,o,i]=e,{numHeads:a,rotaryEmbeddingDim:l}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!k.areEqual(n.dims,[])&&!k.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(!k.areEqual(o.dims,i.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(l>0&&a===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let d=r.dims[0],c=r.dims[r.dims.length-2],m=o.dims[0],u=k.sizeFromDimension(r.dims,1)/c,h=l===0?o.dims[1]*2:u/a;if(l>h)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(d!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(c!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(h/2!==o.dims[1]&&l/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(c>m)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Wh=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:o,scale:i}=t,a=e[0].dims[0],l=k.sizeFromDimension(e[0].dims,1),d=e[0].dims[e[0].dims.length-2],c=l/d,m=e[2].dims[1],u=o===0?m*2:c/n,h=new Array(a,d,c/u,u-m),w=k.computeStrides(h),y=[{type:1,data:i},{type:12,data:h},{type:12,data:w},...e[0].dims.length===3?new Array({type:12,data:[l,c,u,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[l,u,d*u,1]}):[],...V(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],g=x=>{let $=E("input",e[0].dataType,e[0].dims.length),v=E("position_ids",e[1].dataType,e[1].dims.length),S=E("cos_cache",e[2].dataType,e[2].dims.length),T=E("sin_cache",e[3].dataType,e[3].dims.length),C=M("output",e[0].dataType,e[0].dims.length);return x.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:h.length},{name:"global_strides",type:"u32",length:w.length},{name:"input_output_strides",type:"u32",length:w.length}]),` + }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${p.length>0?p:""}|${o.length>0?o:""}|${l.length>0?l:""}|${_}|${a}`,inputDependencies:["rank"]},getShaderSource:$,getRunData:()=>({outputs:[{dims:d,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:[{type:12,data:h},{type:1,data:p},{type:1,data:l},...N(a,d)]})}},Wh=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Id=(e,t)=>{let r=[],n=[],o=[],i=Wh(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Ah(e.inputs,t,i,r,n,o),e.compute(Vh(e.inputs[0],t,i,r,n,o),{inputs:[0]})},Cd=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,o=e.cubicCoeffA,i=e.excludeOutside!==0,a=e.extrapolationValue,l=e.keepAspectRatioPolicy,d=e.mode,p=e.nearestMode===""?"simple":e.nearestMode;return J({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:o,excludeOutside:i,extrapolationValue:a,keepAspectRatioPolicy:l,mode:d,nearestMode:p})}});var Lh,Gh,kd,Ed=R(()=>{"use strict";te();oe();Se();ae();Lh=(e,t)=>{let[r,n,o,i]=e,{numHeads:a,rotaryEmbeddingDim:l}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!k.areEqual(n.dims,[])&&!k.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(!k.areEqual(o.dims,i.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(l>0&&a===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let d=r.dims[0],p=r.dims[r.dims.length-2],m=o.dims[0],u=k.sizeFromDimension(r.dims,1)/p,h=l===0?o.dims[1]*2:u/a;if(l>h)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(d!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(p!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(h/2!==o.dims[1]&&l/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(p>m)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Gh=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:o,scale:i}=t,a=e[0].dims[0],l=k.sizeFromDimension(e[0].dims,1),d=e[0].dims[e[0].dims.length-2],p=l/d,m=e[2].dims[1],u=o===0?m*2:p/n,h=new Array(a,d,p/u,u-m),_=k.computeStrides(h),y=[{type:1,data:i},{type:12,data:h},{type:12,data:_},...e[0].dims.length===3?new Array({type:12,data:[l,p,u,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[l,u,d*u,1]}):[],...N(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],g=x=>{let $=E("input",e[0].dataType,e[0].dims.length),v=E("position_ids",e[1].dataType,e[1].dims.length),S=E("cos_cache",e[2].dataType,e[2].dims.length),T=E("sin_cache",e[3].dataType,e[3].dims.length),C=M("output",e[0].dataType,e[0].dims.length);return x.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:h.length},{name:"global_strides",type:"u32",length:_.length},{name:"input_output_strides",type:"u32",length:_.length}]),` ${x.declareVariables($,v,S,T,C)} ${x.mainStart(Ct)} @@ -6434,7 +6283,7 @@ fn calculateOutputIndex(index: u32) -> u32 { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${C.setByOffset("k",$.getByOffset("k"))} } - }`};return{name:"RotaryEmbedding",shaderCache:{hint:re({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:g,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k.size(h)/Ct)},programUniforms:y})}},Id=(e,t)=>{Nh(e.inputs,t),e.compute(Wh(e.inputs,t))}});var Lh,Gh,Ad,kd=R(()=>{"use strict";te();oe();ae();Lh=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],n=e[2];if(t.dataType!==r.dataType||t.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let o=t.dims[t.dims.length-1],i=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==o)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==i)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==o)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let a=e[3];if(a.dims.length!==1)throw new Error("Beta must be 1D");if(a.dims[a.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let a=e[4];if(a.dims.length!==1)throw new Error("Bias must be 1D");if(a.dims[a.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},Gh=(e,t,r,n)=>{let o=t.simplified,i=e[0].dims,a=k.size(i),l=i,d=a,c=i.slice(-1)[0],m=n?i.slice(0,-1).concat(1):[],u=!o&&e.length>3,h=e.length>4,w=n&&r>1,y=n&&r>2,g=r>3,x=64,$=ye(c),v=[{type:12,data:d},{type:12,data:$},{type:12,data:c},{type:1,data:t.epsilon}],S=C=>{let A=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],P=[E("x",e[0].dataType,e[0].dims,$),E("skip",e[1].dataType,e[1].dims,$),E("gamma",e[2].dataType,e[2].dims,$)];u&&P.push(E("beta",e[3].dataType,e[3].dims,$)),h&&P.push(E("bias",e[4].dataType,e[4].dims,$)),P.push(M("output",e[0].dataType,l,$)),w&&P.push(M("mean_output",1,m)),y&&P.push(M("inv_std_output",1,m)),g&&P.push(M("input_skip_bias_sum",e[0].dataType,l,$));let O=me(e[0].dataType),U=me(1,$);return` + }`};return{name:"RotaryEmbedding",shaderCache:{hint:J({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:g,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k.size(h)/Ct)},programUniforms:y})}},kd=(e,t)=>{Lh(e.inputs,t),e.compute(Gh(e.inputs,t))}});var Hh,Fh,Pd,zd=R(()=>{"use strict";te();oe();ae();Hh=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],n=e[2];if(t.dataType!==r.dataType||t.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let o=t.dims[t.dims.length-1],i=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==o)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==i)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==o)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let a=e[3];if(a.dims.length!==1)throw new Error("Beta must be 1D");if(a.dims[a.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let a=e[4];if(a.dims.length!==1)throw new Error("Bias must be 1D");if(a.dims[a.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},Fh=(e,t,r,n)=>{let o=t.simplified,i=e[0].dims,a=k.size(i),l=i,d=a,p=i.slice(-1)[0],m=n?i.slice(0,-1).concat(1):[],u=!o&&e.length>3,h=e.length>4,_=n&&r>1,y=n&&r>2,g=r>3,x=64,$=me(p),v=[{type:12,data:d},{type:12,data:$},{type:12,data:p},{type:1,data:t.epsilon}],S=C=>{let A=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],P=[E("x",e[0].dataType,e[0].dims,$),E("skip",e[1].dataType,e[1].dims,$),E("gamma",e[2].dataType,e[2].dims,$)];u&&P.push(E("beta",e[3].dataType,e[3].dims,$)),h&&P.push(E("bias",e[4].dataType,e[4].dims,$)),P.push(M("output",e[0].dataType,l,$)),_&&P.push(M("mean_output",1,m)),y&&P.push(M("inv_std_output",1,m)),g&&P.push(M("input_skip_bias_sum",e[0].dataType,l,$));let O=ye(e[0].dataType),U=ye(1,$);return` ${C.registerUniforms(A).declareVariables(...P)} var sum_shared : array<${U}, ${x}>; @@ -6476,9 +6325,9 @@ fn calculateOutputIndex(index: u32) -> u32 { let sum = sum_shared[0]; let square_sum = sum_squared_shared[0]; - let mean = ${Ke("sum",$)} / f32(uniforms.hidden_size); - let inv_std_dev = inverseSqrt(${Ke("square_sum",$)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon); - ${w?"mean_output[global_idx] = mean;":""} + let mean = ${He("sum",$)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${He("square_sum",$)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon); + ${_?"mean_output[global_idx] = mean;":""} ${y?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < stride; i++) { @@ -6486,7 +6335,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${O}(inv_std_dev) * gamma[offset1d + i] ${u?"+ beta[offset1d + i]":""}; } - }`},T=[{dims:l,dataType:e[0].dataType}];return r>1&&T.push({dims:m,dataType:1}),r>2&&T.push({dims:m,dataType:1}),r>3&&T.push({dims:i,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${$};${w};${y};${g}`,inputDependencies:e.map((C,A)=>"type")},getShaderSource:S,getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(d/c)},programUniforms:v})}},Ad=(e,t)=>{Lh(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(Gh(e.inputs,t,e.outputCount,!1),{outputs:n})}});var Hh,ln,Fh,Ed,qh,jh,Pd,zd,Od=R(()=>{"use strict";te();oe();Ie();ae();Hh=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((r,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},ln=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>r.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>r.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},Fh=(e,t)=>{if(e.length>1){let r=ln(e,1),n=ln(e,2),o=ln(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),re({starts:r,ends:n,axes:o})}else return t},Ed=(e,t,r,n,o)=>{let i=e;return e<0&&(i+=r[n[t]]),o[t]<0?Math.max(0,Math.min(i,r[n[t]]-1)):Math.max(0,Math.min(i,r[n[t]]))},qh=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + }`},T=[{dims:l,dataType:e[0].dataType}];return r>1&&T.push({dims:m,dataType:1}),r>2&&T.push({dims:m,dataType:1}),r>3&&T.push({dims:i,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${$};${_};${y};${g}`,inputDependencies:e.map((C,A)=>"type")},getShaderSource:S,getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(d/p)},programUniforms:v})}},Pd=(e,t)=>{Hh(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(Fh(e.inputs,t,e.outputCount,!1),{outputs:n})}});var qh,an,jh,Od,Kh,Yh,Bd,Dd,Md=R(()=>{"use strict";te();oe();Se();ae();qh=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((r,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},an=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>r.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>r.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},jh=(e,t)=>{if(e.length>1){let r=an(e,1),n=an(e,2),o=an(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),J({starts:r,ends:n,axes:o})}else return t},Od=(e,t,r,n,o)=>{let i=e;return e<0&&(i+=r[n[t]]),o[t]<0?Math.max(0,Math.min(i,r[n[t]]-1)):Math.max(0,Math.min(i,r[n[t]]))},Kh=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; var carry = 0u; for (var i = ${r.length}; i >= 0; i--) { @@ -6504,15 +6353,15 @@ fn calculateOutputIndex(index: u32) -> u32 { ${e.indicesSet("input_indices","i","input_index")}; } return input_indices; - }`,jh=(e,t)=>{let r=e[0].dims,n=k.size(r),o=t.axes.length>0?k.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],i=ln(e,4);i.forEach($=>$!==0||(()=>{throw new Error("step cannot be 0")})),i.length===0&&(i=Array(o.length).fill(1));let a=t.starts.map(($,v)=>Ed($,v,r,o,i)),l=t.ends.map(($,v)=>Ed($,v,r,o,i));if(o.length!==a.length||o.length!==l.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==r.length)for(let $=0;$Math.sign($));i.forEach(($,v,S)=>{if($<0){let T=(l[v]-a[v])/$,C=a[v],A=C+T*i[v];a[v]=A,l[v]=C,S[v]=-$}});let c=r.slice(0);o.forEach(($,v)=>{c[$]=Math.ceil((l[$]-a[$])/i[$])});let m={dims:c,dataType:e[0].dataType},u=M("output",e[0].dataType,c.length),h=E("input",e[0].dataType,e[0].dims.length),w=k.size(c),y=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:a.length},{name:"signs",type:"i32",length:d.length},{name:"steps",type:"u32",length:i.length}],g=[{type:12,data:w},{type:12,data:a},{type:6,data:d},{type:12,data:i},...V(e[0].dims,c)],x=$=>` + }`,Yh=(e,t)=>{let r=e[0].dims,n=k.size(r),o=t.axes.length>0?k.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],i=an(e,4);i.forEach($=>$!==0||(()=>{throw new Error("step cannot be 0")})),i.length===0&&(i=Array(o.length).fill(1));let a=t.starts.map(($,v)=>Od($,v,r,o,i)),l=t.ends.map(($,v)=>Od($,v,r,o,i));if(o.length!==a.length||o.length!==l.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==r.length)for(let $=0;$Math.sign($));i.forEach(($,v,S)=>{if($<0){let T=(l[v]-a[v])/$,C=a[v],A=C+T*i[v];a[v]=A,l[v]=C,S[v]=-$}});let p=r.slice(0);o.forEach(($,v)=>{p[$]=Math.ceil((l[$]-a[$])/i[$])});let m={dims:p,dataType:e[0].dataType},u=M("output",e[0].dataType,p.length),h=E("input",e[0].dataType,e[0].dims.length),_=k.size(p),y=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:a.length},{name:"signs",type:"i32",length:d.length},{name:"steps",type:"u32",length:i.length}],g=[{type:12,data:_},{type:12,data:a},{type:6,data:d},{type:12,data:i},...N(e[0].dims,p)],x=$=>` ${$.registerUniforms(y).declareVariables(h,u)} - ${qh(h,u,r)} + ${Kh(h,u,r)} ${$.mainStart()} ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${u.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${u.setByOffset("global_idx",h.getByIndices("input_indices"))} - }`;return{name:"Slice",shaderCache:{hint:`${d.length}_${a.length}_${i.length}`,inputDependencies:["rank"]},getShaderSource:x,getRunData:()=>({outputs:[m],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:g})}},Pd=(e,t)=>{Hh(e.inputs,t);let r=Fh(e.inputs,t);e.compute(jh(e.inputs,r),{inputs:[0]})},zd=e=>{let t=e.starts,r=e.ends,n=e.axes;return re({starts:t,ends:r,axes:n})}});var Kh,Yh,Dd,Bd,Md=R(()=>{"use strict";te();oe();Ie();ut();ae();Kh=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Yh=(e,t)=>{let r=e.inputs[0],n=r.dims,o=k.size(n),i=n.length,a=k.normalizeAxis(t.axis,i),l=aO),c[a]=i-1,c[i-1]=a,d=e.compute(Pe(r,c),{inputs:[r],outputs:[-1]})[0]):d=r;let m=d.dims,u=m[i-1],h=o/u,w=ye(u),y=u/w,g=64;h===1&&(g=256);let x=(P,O)=>O===4?`max(max(${P}.x, ${P}.y), max(${P}.z, ${P}.w))`:O===2?`max(${P}.x, ${P}.y)`:O===3?`max(max(${P}.x, ${P}.y), ${P}.z)`:P,$=E("x",d.dataType,d.dims,w),v=M("result",d.dataType,d.dims,w),S=$.type.value,T=me(d.dataType)==="f32"?`var threadMax = ${S}(-3.402823e+38f);`:`var threadMax = ${S}(-65504.0h);`,C=P=>` + }`;return{name:"Slice",shaderCache:{hint:`${d.length}_${a.length}_${i.length}`,inputDependencies:["rank"]},getShaderSource:x,getRunData:()=>({outputs:[m],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:g})}},Bd=(e,t)=>{qh(e.inputs,t);let r=jh(e.inputs,t);e.compute(Yh(e.inputs,r),{inputs:[0]})},Dd=e=>{let t=e.starts,r=e.ends,n=e.axes;return J({starts:t,ends:r,axes:n})}});var Zh,Qh,Rd,Ud,Nd=R(()=>{"use strict";te();oe();Se();ut();ae();Zh=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Qh=(e,t)=>{let r=e.inputs[0],n=r.dims,o=k.size(n),i=n.length,a=k.normalizeAxis(t.axis,i),l=aO),p[a]=i-1,p[i-1]=a,d=e.compute(Ee(r,p),{inputs:[r],outputs:[-1]})[0]):d=r;let m=d.dims,u=m[i-1],h=o/u,_=me(u),y=u/_,g=64;h===1&&(g=256);let x=(P,O)=>O===4?`max(max(${P}.x, ${P}.y), max(${P}.z, ${P}.w))`:O===2?`max(${P}.x, ${P}.y)`:O===3?`max(max(${P}.x, ${P}.y), ${P}.z)`:P,$=E("x",d.dataType,d.dims,_),v=M("result",d.dataType,d.dims,_),S=$.type.value,T=ye(d.dataType)==="f32"?`var threadMax = ${S}(-3.402823e+38f);`:`var threadMax = ${S}(-65504.0h);`,C=P=>` var rowMaxShared : ${S}; var rowSumShared : ${S}; var threadShared : array<${S}, ${g}>; @@ -6555,7 +6404,7 @@ fn calculateOutputIndex(index: u32) -> u32 { workgroupBarrier(); } if (lindex == 0) { - rowMaxShared = ${S}(${x("threadShared[0]",w)}); + rowMaxShared = ${S}(${x("threadShared[0]",_)}); } workgroupBarrier(); @@ -6575,7 +6424,7 @@ fn calculateOutputIndex(index: u32) -> u32 { workgroupBarrier(); } if (lindex == 0) { - rowSumShared = ${S}(${Ke("threadShared[0]",w)}); + rowSumShared = ${S}(${He("threadShared[0]",_)}); } workgroupBarrier(); @@ -6584,7 +6433,7 @@ fn calculateOutputIndex(index: u32) -> u32 { let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; setValue(row, col, row_stride, value); } - }`,A=e.compute({name:"Softmax",shaderCache:{hint:`${w};${g}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:m,dataType:d.dataType}],dispatchGroup:{x:h},programUniforms:[{type:6,data:y}]}),getShaderSource:C},{inputs:[d],outputs:[l?-1:0]})[0];l&&e.compute(Pe(A,c),{inputs:[A]})},Dd=(e,t)=>{Kh(e.inputs),Yh(e,t)},Bd=e=>re({axis:e.axis})});var Rd,Zh,Xh,Qh,Ud,Vd=R(()=>{"use strict";te();oe();ae();Rd=e=>Array.from(e.getBigInt64Array(),Number),Zh=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Rd(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Xh=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??Rd(e[1]),o=Xh(r,n),i=k.size(o),a=e[0].dataType,l=E("input",a,r.length),d=M("output",a,o.length),c=m=>` + }`,A=e.compute({name:"Softmax",shaderCache:{hint:`${_};${g}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:m,dataType:d.dataType}],dispatchGroup:{x:h},programUniforms:[{type:6,data:y}]}),getShaderSource:C},{inputs:[d],outputs:[l?-1:0]})[0];l&&e.compute(Ee(A,p),{inputs:[A]})},Rd=(e,t)=>{Zh(e.inputs),Qh(e,t)},Ud=e=>J({axis:e.axis})});var Vd,Xh,Jh,eg,Wd,Ld=R(()=>{"use strict";te();oe();ae();Vd=e=>Array.from(e.getBigInt64Array(),Number),Xh=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Vd(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Jh=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??Vd(e[1]),o=Jh(r,n),i=k.size(o),a=e[0].dataType,l=E("input",a,r.length),d=M("output",a,o.length),p=m=>` const inputShape = ${l.indices(...r)}; ${m.registerUniform("output_size","u32").declareVariables(l,d)} ${m.mainStart()} @@ -6598,25 +6447,25 @@ fn calculateOutputIndex(index: u32) -> u32 { ${l.indicesSet("input_indices","i","input_dim_value")} } ${d.setByOffset("global_idx",l.getByIndices("input_indices"))} - }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...V(e[0].dims,o)]}),getShaderSource:c}},Ud=e=>{Zh(e.inputs),e.compute(Qh(e.inputs),{inputs:[0]})}});var Jh,eg,Nd,Wd=R(()=>{"use strict";te();oe();ae();Jh=(e,t,r,n,o)=>{let i=M("output_data",o,r.length,4),a=E("a_data",t[1].dataType,t[1].dims.length,4),l=E("b_data",t[2].dataType,t[2].dims.length,4),d=E("c_data",t[0].dataType,t[0].dims.length,4),c,m=(u,h,w)=>`select(${h}, ${u}, ${w})`;if(!n)c=i.setByOffset("global_idx",m(a.getByOffset("global_idx"),l.getByOffset("global_idx"),d.getByOffset("global_idx")));else{let u=(h,w,y="")=>{let g=`a_data[index_a${w}][component_a${w}]`,x=`b_data[index_b${w}][component_b${w}]`,$=`bool(c_data[index_c${w}] & (0xffu << (component_c${w} * 8)))`;return` - let output_indices${w} = ${i.offsetToIndices(`global_idx * 4u + ${w}u`)}; - let offset_a${w} = ${a.broadcastedIndicesToOffset(`output_indices${w}`,i)}; - let offset_b${w} = ${l.broadcastedIndicesToOffset(`output_indices${w}`,i)}; - let offset_c${w} = ${d.broadcastedIndicesToOffset(`output_indices${w}`,i)}; - let index_a${w} = offset_a${w} / 4u; - let index_b${w} = offset_b${w} / 4u; - let index_c${w} = offset_c${w} / 4u; - let component_a${w} = offset_a${w} % 4u; - let component_b${w} = offset_b${w} % 4u; - let component_c${w} = offset_c${w} % 4u; - ${h}[${w}] = ${y}(${m(g,x,$)}); - `};o===9?c=` + }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...N(e[0].dims,o)]}),getShaderSource:p}},Wd=e=>{Xh(e.inputs),e.compute(eg(e.inputs),{inputs:[0]})}});var tg,rg,Gd,Hd=R(()=>{"use strict";te();oe();ae();tg=(e,t,r,n,o)=>{let i=M("output_data",o,r.length,4),a=E("a_data",t[1].dataType,t[1].dims.length,4),l=E("b_data",t[2].dataType,t[2].dims.length,4),d=E("c_data",t[0].dataType,t[0].dims.length,4),p,m=(u,h,_)=>`select(${h}, ${u}, ${_})`;if(!n)p=i.setByOffset("global_idx",m(a.getByOffset("global_idx"),l.getByOffset("global_idx"),d.getByOffset("global_idx")));else{let u=(h,_,y="")=>{let g=`a_data[index_a${_}][component_a${_}]`,x=`b_data[index_b${_}][component_b${_}]`,$=`bool(c_data[index_c${_}] & (0xffu << (component_c${_} * 8)))`;return` + let output_indices${_} = ${i.offsetToIndices(`global_idx * 4u + ${_}u`)}; + let offset_a${_} = ${a.broadcastedIndicesToOffset(`output_indices${_}`,i)}; + let offset_b${_} = ${l.broadcastedIndicesToOffset(`output_indices${_}`,i)}; + let offset_c${_} = ${d.broadcastedIndicesToOffset(`output_indices${_}`,i)}; + let index_a${_} = offset_a${_} / 4u; + let index_b${_} = offset_b${_} / 4u; + let index_c${_} = offset_c${_} / 4u; + let component_a${_} = offset_a${_} % 4u; + let component_b${_} = offset_b${_} % 4u; + let component_c${_} = offset_c${_} % 4u; + ${h}[${_}] = ${y}(${m(g,x,$)}); + `};o===9?p=` var data = vec4(0); ${u("data",0,"u32")} ${u("data",1,"u32")} ${u("data",2,"u32")} ${u("data",3,"u32")} - output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:c=` + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:p=` ${u("output_data[global_idx]",0)} ${u("output_data[global_idx]",1)} ${u("output_data[global_idx]",2)} @@ -6625,11 +6474,11 @@ fn calculateOutputIndex(index: u32) -> u32 { ${e.registerUniform("vec_size","u32").declareVariables(d,a,l,i)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${c} - }`},eg=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,o=e[1].dataType,i=!(k.areEqual(t,r)&&k.areEqual(r,n)),a=t,l=k.size(t);if(i){let c=et.calcShape(et.calcShape(t,r,!1),n,!1);if(!c)throw new Error("Can't perform where op on the given tensors");a=c,l=k.size(a)}let d=Math.ceil(l/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>Jh(c,e,a,i,o),getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:Math.ceil(l/64/4)},programUniforms:[{type:12,data:d},...V(n,t,r,a)]})}},Nd=e=>{e.compute(eg(e.inputs))}});var Ld,Gd=R(()=>{"use strict";zs();Xr();Bs();Rs();$u();Ou();Mu();Yu();rl();il();ul();ml();gl();yl();vl();Sl();Cl();El();Ol();Wl();Hl();ql();Kl();Xl();ko();Jl();gd();wd();vd();Yr();Td();Cd();kd();Od();Md();Po();Vd();ut();Jr();Wd();Ld=new Map([["Abs",[Us]],["Acos",[Vs]],["Acosh",[Ns]],["Add",[xu]],["ArgMax",[Ps,go]],["ArgMin",[Es,go]],["Asin",[Ws]],["Asinh",[Ls]],["Atan",[Gs]],["Atanh",[Hs]],["Attention",[Os]],["AveragePool",[sd,ad]],["BatchNormalization",[Ds]],["BiasAdd",[Ms]],["BiasSplitGelu",[vu]],["Cast",[qs,Fs]],["Ceil",[Ks]],["Clip",[js]],["Concat",[Du,Bu]],["Conv",[So,xo]],["ConvTranspose",[tl,el]],["Cos",[Ys]],["Cosh",[Zs]],["CumSum",[nl,ol]],["DepthToSpace",[al,sl]],["DequantizeLinear",[bd,yd]],["Div",[Su]],["Einsum",[cl,pl]],["Elu",[Xs,Jt]],["Equal",[Tu]],["Erf",[Qs]],["Exp",[Js]],["Expand",[hl]],["FastGelu",[bl]],["Floor",[eu]],["FusedConv",[So,xo]],["Gather",[_l,wl]],["GatherElements",[Il,Tl]],["GatherBlockQuantized",[$l,xl]],["Gelu",[tu]],["Gemm",[kl,Al]],["GlobalAveragePool",[dd,ld]],["GlobalMaxPool",[hd,fd]],["Greater",[ku]],["GreaterOrEqual",[Pu]],["GridSample",[Pl,zl]],["GroupQueryAttention",[Nl]],["HardSigmoid",[lu,uu]],["InstanceNormalization",[Gl]],["LayerNormalization",[Fl]],["LeakyRelu",[ru,Jt]],["Less",[Eu]],["LessOrEqual",[zu]],["Log",[yu]],["MatMul",[jl]],["MatMulNBits",[Yl,Zl]],["MaxPool",[pd,md]],["Mul",[Iu]],["MultiHeadAttention",[Ml,Bl]],["Neg",[ou]],["Not",[nu]],["Pad",[Ql]],["Pow",[Cu]],["QuickGelu",[wu,Jt]],["Range",[_d]],["Reciprocal",[iu]],["ReduceMin",[Ss]],["ReduceMean",[ws]],["ReduceMax",[xs]],["ReduceSum",[Is]],["ReduceProd",[Ts]],["ReduceL1",[_s]],["ReduceL2",[vs]],["ReduceLogSum",[As]],["ReduceLogSumExp",[$s]],["ReduceSumSquare",[Cs]],["Relu",[au]],["Resize",[xd,Sd]],["RotaryEmbedding",[Id]],["Sigmoid",[su]],["Sin",[du]],["Sinh",[cu]],["Slice",[Pd,zd]],["SkipLayerNormalization",[Ad]],["Split",[Rl,Ul]],["Sqrt",[pu]],["Softmax",[Dd,Bd]],["Sub",[Au]],["Tan",[mu]],["Tanh",[hu]],["ThresholdedRelu",[bu,Jt]],["Tile",[Ud]],["Transpose",[as,ss]],["Where",[Nd]]])});var dn,Hd=R(()=>{"use strict";He();je();ae();dn=class{constructor(t){this.backend=t;this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,r){this.repo.set(t,r)}run(t,r,n,o,i){Ue(t.programInfo.name);let a=this.backend.device,l=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let d=[];for(let m of r)d.push({binding:d.length,resource:{buffer:m.buffer}});for(let m of n)d.push({binding:d.length,resource:{buffer:m.buffer}});i&&d.push({binding:d.length,resource:i});let c=a.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:d,label:t.programInfo.name});if(this.backend.sessionStatus==="capturing"){let m={kernelId:this.backend.currentKernelId,computePipeline:t.computePipeline,bindGroup:c,dispatchGroup:o};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(m)}l.setPipeline(t.computePipeline),l.setBindGroup(0,c),l.dispatchWorkgroups(...o),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Be(t.programInfo.name)}dispose(){}build(t,r){Ue(t.name);let n=this.backend.device,o=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"},{feature:"subgroups-f16",extension:"subgroups_f16"}].forEach(u=>{n.features.has(u.feature)&&o.push(`enable ${u.extension};`)});let a=os(r,this.backend.device.limits),l=t.getShaderSource(a),d=`${o.join(` + ${p} + }`},rg=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,o=e[1].dataType,i=!(k.areEqual(t,r)&&k.areEqual(r,n)),a=t,l=k.size(t);if(i){let p=et.calcShape(et.calcShape(t,r,!1),n,!1);if(!p)throw new Error("Can't perform where op on the given tensors");a=p,l=k.size(a)}let d=Math.ceil(l/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:p=>tg(p,e,a,i,o),getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:Math.ceil(l/64/4)},programUniforms:[{type:12,data:d},...N(n,t,r,a)]})}},Gd=e=>{e.compute(rg(e.inputs))}});var Fd,qd=R(()=>{"use strict";ks();Kr();zs();Bs();_u();Eu();Ou();Yu();rl();il();ul();ml();gl();yl();vl();Sl();Cl();El();Ol();Wl();Hl();ql();Kl();Ql();To();Jl();gd();_d();vd();Sd();qr();Ad();Ed();zd();Md();Nd();Co();Ld();ut();Zr();Hd();Fd=new Map([["Abs",[Ds]],["Acos",[Ms]],["Acosh",[Rs]],["Add",[wu]],["ArgMax",[As,po]],["ArgMin",[Cs,po]],["Asin",[Us]],["Asinh",[Ns]],["Atan",[Vs]],["Atanh",[Ws]],["Attention",[Es]],["AveragePool",[sd,ad]],["BatchNormalization",[Ps]],["BiasAdd",[Os]],["BiasSplitGelu",[yu]],["Cast",[Gs,Ls]],["Ceil",[Fs]],["Clip",[Hs]],["Concat",[Pu,zu]],["Conv",[vo,wo]],["ConvTranspose",[tl,Ju]],["Cos",[qs]],["Cosh",[js]],["CumSum",[nl,ol]],["DepthToSpace",[al,sl]],["DequantizeLinear",[bd,yd]],["Div",[vu]],["Einsum",[cl,pl]],["Elu",[Ks,Jt]],["Equal",[$u]],["Erf",[Ys]],["Exp",[Zs]],["Expand",[hl]],["FastGelu",[bl]],["Floor",[Qs]],["FusedConv",[vo,wo]],["Gather",[wl,_l]],["GatherElements",[Il,Tl]],["GatherBlockQuantized",[$l,xl]],["Gelu",[Xs]],["Gemm",[kl,Al]],["GlobalAveragePool",[dd,ld]],["GlobalMaxPool",[hd,fd]],["Greater",[Iu]],["GreaterOrEqual",[Au]],["GridSample",[Pl,zl]],["GroupQueryAttention",[Vl]],["HardSigmoid",[au,iu]],["InstanceNormalization",[Gl]],["LayerNormalization",[Fl]],["LeakyRelu",[Js,Jt]],["Less",[Cu]],["LessOrEqual",[ku]],["Log",[hu]],["MatMul",[jl]],["MatMulNBits",[Yl,Zl]],["MaxPool",[pd,md]],["Mul",[xu]],["MultiHeadAttention",[Ml,Dl]],["Neg",[tu]],["Not",[eu]],["Pad",[Xl]],["Pow",[Su]],["QuickGelu",[gu,Jt]],["Range",[wd]],["Reciprocal",[ru]],["ReduceMin",[vs]],["ReduceMean",[gs]],["ReduceMax",[ws]],["ReduceSum",[xs]],["ReduceProd",[$s]],["ReduceL1",[bs]],["ReduceL2",[ys]],["ReduceLogSum",[Ts]],["ReduceLogSumExp",[_s]],["ReduceSumSquare",[Ss]],["Relu",[nu]],["Resize",[Id,Cd]],["RotaryEmbedding",[kd]],["ScatterND",[xd,$d]],["Sigmoid",[ou]],["Sin",[su]],["Sinh",[uu]],["Slice",[Bd,Dd]],["SkipLayerNormalization",[Pd]],["Split",[Rl,Ul]],["Sqrt",[lu]],["Softmax",[Rd,Ud]],["Sub",[Tu]],["Tan",[du]],["Tanh",[pu]],["ThresholdedRelu",[fu,Jt]],["Tile",[Wd]],["Transpose",[ns,os]],["Where",[Gd]]])});var sn,jd=R(()=>{"use strict";We();Je();ae();sn=class{constructor(t){this.backend=t;this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,r){this.repo.set(t,r)}run(t,r,n,o,i){Ue(t.programInfo.name);let a=this.backend.device,l=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let d=[];for(let m of r)d.push({binding:d.length,resource:{buffer:m.buffer}});for(let m of n)d.push({binding:d.length,resource:{buffer:m.buffer}});i&&d.push({binding:d.length,resource:i});let p=a.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:d,label:t.programInfo.name});if(this.backend.sessionStatus==="capturing"){let m={kernelId:this.backend.currentKernelId,computePipeline:t.computePipeline,bindGroup:p,dispatchGroup:o};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(m)}l.setPipeline(t.computePipeline),l.setBindGroup(0,p),l.dispatchWorkgroups(...o),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),De(t.programInfo.name)}dispose(){}build(t,r){Ue(t.name);let n=this.backend.device,o=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"},{feature:"subgroups-f16",extension:"subgroups_f16"}].forEach(u=>{n.features.has(u.feature)&&o.push(`enable ${u.extension};`)});let a=ts(r,this.backend.device.limits),l=t.getShaderSource(a),d=`${o.join(` `)} ${a.additionalImplementations} -${l}`,c=n.createShaderModule({code:d,label:t.name});se("verbose",()=>`[WebGPU] ${t.name} shader code: ${d}`);let m=n.createComputePipeline({compute:{module:c,entryPoint:"main"},layout:"auto",label:t.name});return Be(t.name),{programInfo:t,computePipeline:m,uniformVariablesInfo:a.variablesInfo}}normalizeDispatchGroupSize(t){let r=typeof t=="number"?t:t.x,n=typeof t=="number"?1:t.y||1,o=typeof t=="number"?1:t.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=i&&n<=i&&o<=i)return[r,n,o];let a=r*n*o,l=Math.ceil(Math.sqrt(a));if(l>i){if(l=Math.ceil(Math.cbrt(a)),l>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[l,l,l]}else return[l,l,1]}}});var tg,rg,zo,Oo,cn,Fd=R(()=>{"use strict";He();te();je();no();ts();Gd();Hd();tg=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let n=0;n{let n=e.name;return e.shaderCache?.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+r+`:${tg(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,n},zo=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},Oo=class{constructor(t){this.subgroupsSupported=t.features.has("subgroups"),this.subgroupsF16Supported=t.features.has("subgroups");let r=t.limits;!this.subgroupsSupported||!r.minSubgroupSize||!r.maxSubgroupSize?this.subgroupSizeRange=void 0:this.subgroupSizeRange=[r.minSubgroupSize,r.maxSubgroupSize]}},cn=class{constructor(){this.currentSessionId=null;this.currentKernelId=null;this.commandEncoder=null;this.computePassEncoder=null;this.maxDispatchNumber=16;this.pendingDispatchNumber=0;this.pendingKernels=[];this.pendingQueries=new Map;this.sessionStatus="default";this.capturedCommandList=new Map;this.capturedPendingKernels=new Map;this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,r){this.env=t;let n=[],o={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},i=a=>r.features.has(a)&&n.push(a)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups")&&i("subgroups-f16"),this.device=await r.requestDevice(o),this.deviceInfo=new Oo(this.device),this.adapterInfo=new zo(r.info||await r.requestAdapterInfo()),this.gpuDataManager=es(this),this.programManager=new dn(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Hr(t.logLevel,!!t.debug),this.device.onuncapturederror=a=>{a.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${a.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ue(),this.endComputePass();let t;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),t=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(t,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,t,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&t.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(t.getMappedRange()),n=this.pendingQueries.get(t);for(let o=0;o"u"&&(this.queryTimeBase=w);let g=Number(w-this.queryTimeBase),x=Number(y-this.queryTimeBase);if(!Number.isSafeInteger(g)||!Number.isSafeInteger(x))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:u.map($=>({dims:$.dims,dataType:bt($.dataType)})),outputsMetadata:h.map($=>({dims:$.dims,dataType:bt($.dataType)})),kernelId:a,kernelType:d,kernelName:c,programName:m,startTime:g,endTime:x});else{let $="";u.forEach((S,T)=>{$+=`input[${T}]: [${S.dims}] | ${bt(S.dataType)}, `});let v="";h.forEach((S,T)=>{v+=`output[${T}]: [${S.dims}] | ${bt(S.dataType)}, `}),console.log(`[profiling] kernel "${a}|${d}|${c}|${m}" ${$}${v}execution time: ${x-g} ns`)}Cr("GPU",`${m}::${w}::${y}`)}t.unmap(),this.pendingQueries.delete(t)}),Be()}run(t,r,n,o,i,a){Ue(t.name);let l=[];for(let S=0;ST):n;if(u.length!==d.length)throw new Error(`Output size ${u.length} must be equal to ${d.length}.`);let h=[],w=[];for(let S=0;S=a)throw new Error(`Invalid output index: ${u[S]}`);if(u[S]===-3)continue;let T=u[S]===-1,C=u[S]===-2,A=T||C?i(d[S].dataType,d[S].dims):o(u[S],d[S].dataType,d[S].dims);if(h.push(A),A.data===0)continue;let P=this.gpuDataManager.get(A.data);if(!P)throw new Error(`no GPU data for output: ${A.data}`);if(T&&this.temporaryData.push(P),C){let O=this.kernelPersistentData.get(this.currentKernelId);O||(O=[],this.kernelPersistentData.set(this.currentKernelId,O)),O.push(P)}w.push(P)}if(l.length!==r.length||w.length!==h.length){if(w.length===0)return Be(t.name),h;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let y;if(m){let S=0,T=[];m.forEach(O=>{let U=typeof O.data=="number"?[O.data]:O.data;if(U.length===0)return;let L=O.type===10?2:4,j,K;O.type===10?(K=U.length>4?16:U.length>2?8:U.length*L,j=U.length>4?16:L*U.length):(K=U.length<=2?U.length*L:16,j=16),S=Math.ceil(S/K)*K,T.push(S);let W=O.type===10?8:4;S+=U.length>4?Math.ceil(U.length/W)*j:U.length*L});let C=16;S=Math.ceil(S/C)*C;let A=new ArrayBuffer(S);m.forEach((O,U)=>{let L=T[U],j=typeof O.data=="number"?[O.data]:O.data;if(O.type===6)new Int32Array(A,L,j.length).set(j);else if(O.type===12)new Uint32Array(A,L,j.length).set(j);else if(O.type===10)new Uint16Array(A,L,j.length).set(j);else if(O.type===1)new Float32Array(A,L,j.length).set(j);else throw new Error(`Unsupported uniform type: ${bt(O.type)}`)});let P=this.gpuDataManager.create(S,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(P.buffer,0,A,0,S),this.gpuDataManager.release(P.id),y={offset:0,size:S,buffer:P.buffer}}let g=this.programManager.normalizeDispatchGroupSize(c),x=g[1]===1&&g[2]===1,$=rg(t,r,x),v=this.programManager.getArtifact($);if(v||(v=this.programManager.build(t,g),this.programManager.setArtifact($,v),se("info",()=>`[artifact] key: ${$}, programName: ${t.name}`)),m&&v.uniformVariablesInfo){if(m.length!==v.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${v.uniformVariablesInfo.length}, got ${m.length} in program "${v.programInfo.name}".`);for(let S=0;S`[ProgramManager] run "${t.name}" (key=${$}) with ${g[0]}x${g[1]}x${g[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let S={kernelId:this.currentKernelId,programName:v.programInfo.name,inputTensorViews:r,outputTensorViews:h};this.pendingKernels.push(S),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(S)}return this.programManager.run(v,l,w,g,y),Be(t.name),h}upload(t,r){this.gpuDataManager.upload(t,r)}memcpy(t,r){this.gpuDataManager.memcpy(t,r)}async download(t,r){await this.gpuDataManager.download(t,r)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,r,n,o){let i=Ld.get(t);if(!i)throw new Error(`kernel not implemented: ${t}`);let a={kernelType:t,kernelName:o,kernelEntry:i[0],attributes:[i[1],n]};this.kernels.set(r,a)}releaseKernel(t){let r=this.kernelPersistentData.get(t);if(r){for(let n of r)this.gpuDataManager.release(n.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,r,n){let o=this.kernels.get(t);if(!o)throw new Error(`kernel not created: ${t}`);let i=o.kernelType,a=o.kernelName,l=o.kernelEntry,d=o.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=t,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),se("info",()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`);let c=this.env.debug;this.temporaryData=[];try{return c&&this.device.pushErrorScope("validation"),l(r,d[1]),0}catch(m){return n.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${m}`)),1}finally{c&&n.push(this.device.popErrorScope().then(m=>m?`GPU validation error for kernel "[${i}] ${a}": ${m.message}`:null));for(let m of this.temporaryData)this.gpuDataManager.release(m.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,r,n,o){let i=this.sessionExternalDataMapping.get(t);i||(i=new Map,this.sessionExternalDataMapping.set(t,i));let a=i.get(r),l=this.gpuDataManager.registerExternalBuffer(n,o,a);return i.set(r,[l,n]),l}unregisterBuffers(t){let r=this.sessionExternalDataMapping.get(t);r&&(r.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[0])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let r=this.gpuDataManager.get(t);if(!r)throw new Error(`no GPU data for buffer: ${t}`);return r.buffer}createDownloader(t,r,n){return async()=>{let o=await so(this,t,r);return Fr(o.buffer,n)}}writeTimestamp(t){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){se("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){se("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){se("info","replay"),this.sessionStatus="replaying";let t=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),n=t.length;this.pendingKernels=[];for(let o=0;o=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}});var ng,qd,og,jd,pn,mn,Do,Kd,Yd=R(()=>{"use strict";je();ng=1,qd=()=>ng++,og=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),jd=(e,t)=>{let r=og.get(e);if(!r)throw new Error("Unsupported data type.");return Math.ceil(t.reduce((n,o)=>n*o)*r/8)},pn=class{constructor(t){this.sessionId=t.sessionId,this.mlContext=t.context,this.mlTensor=t.tensor,this.dataType=t.dataType,this.tensorShape=t.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return jd(this.dataType,this.tensorShape)}destroy(){se("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t){return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}sameTypeAndShape(t,r){return this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((n,o)=>n===r[o])}},mn=class{constructor(t,r){this.tensorManager=t;this.wrapper=r}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(t,r,n){if(this.wrapper){if(this.wrapper.sameTypeAndShape(t,r))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==jd(t,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let o=MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,r,o,!0,!0),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(t){if(this.wrapper)if(t.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else se("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(t){if(this.activeUpload)if(t){t instanceof ArrayBuffer?new Uint8Array(t).set(this.activeUpload):new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.wrapper)throw new Error("Tensor has not been created.");return t?this.wrapper.read(t):this.wrapper.read()}},Do=class{constructor(t){this.backend=t;this.tensorTrackersById=new Map;this.freeTensors=[];this.externalTensors=new Set}reserveTensorId(){let t=qd();return this.tensorTrackersById.set(t,new mn(this)),t}releaseTensorId(t){let r=this.tensorTrackersById.get(t);r&&(this.tensorTrackersById.delete(t),r.tensorWrapper&&this.releaseTensor(r.tensorWrapper))}async ensureTensor(t,r,n,o){se("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${n}, copyOld: ${o}}`);let i=this.tensorTrackersById.get(t);if(!i)throw new Error("Tensor not found.");return i.ensureTensor(r,n,o)}upload(t,r){let n=this.tensorTrackersById.get(t);if(!n)throw new Error("Tensor not found.");n.upload(r)}async download(t,r){se("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${r?.byteLength}}`);let n=this.tensorTrackersById.get(t);if(!n)throw new Error("Tensor not found.");return n.download(r)}releaseTensorsForSession(t){for(let r of this.freeTensors)r.sessionId===t&&r.destroy();this.freeTensors=this.freeTensors.filter(r=>r.sessionId!==t)}registerTensor(t,r,n,o){let i=qd(),a=new pn({sessionId:this.backend.currentSessionId,context:t,tensor:r,dataType:n,shape:o});return this.tensorTrackersById.set(i,new mn(this,a)),this.externalTensors.add(a),i}async getCachedTensor(t,r,n,o,i){let a=this.backend.currentSessionId;for(let[c,m]of this.freeTensors.entries())if(m.sameTypeAndShape(t,r)){se("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, shape: ${r}}`);let u=this.freeTensors.splice(c,1)[0];return u.sessionId=a,u}let l=this.backend.currentContext;se("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, shape: ${r}}`);let d=await l.createTensor({dataType:t,shape:r,dimensions:r,usage:n,writable:o,readable:i});return new pn({sessionId:a,context:l,tensor:d,dataType:t,shape:r})}releaseTensor(t){this.externalTensors.has(t)&&this.externalTensors.delete(t),this.freeTensors.push(t)}},Kd=(...e)=>new Do(...e)});var Zd,ig,fn,Xd=R(()=>{"use strict";te();gt();no();Yd();je();Zd=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),ig=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.length===n.length&&r.every((o,i)=>o===n[i]&&e[o]===t[o])},fn=class{constructor(t){this.tensorManager=Kd(this);this.mlContextBySessionId=new Map;this.sessionIdsByMLContext=new Map;this.mlContextCache=[];Hr(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){this.activeSessionId=t}async createMLContext(t){if(t instanceof GPUDevice){let n=this.mlContextCache.findIndex(o=>o.gpuDevice===t);if(n!==-1)return this.mlContextCache[n].mlContext;{let o=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:o}),o}}else if(t===void 0){let n=this.mlContextCache.findIndex(o=>o.options===void 0&&o.gpuDevice===void 0);if(n!==-1)return this.mlContextCache[n].mlContext;{let o=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:o}),o}}let r=this.mlContextCache.findIndex(n=>ig(n.options,t));if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:n}),n}}get currentContext(){let t=this.getMLContext(this.currentSessionId);if(!t)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return t}registerMLContext(t,r){this.mlContextBySessionId.set(t,r);let n=this.sessionIdsByMLContext.get(r);n||(n=new Set,this.sessionIdsByMLContext.set(r,n)),n.add(t)}onReleaseSession(t){let r=this.mlContextBySessionId.get(t);if(!r)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t);let n=this.sessionIdsByMLContext.get(r);if(n.delete(t),n.size===0){this.sessionIdsByMLContext.delete(r);let o=this.mlContextCache.findIndex(i=>i.mlContext===r);o!==-1&&this.mlContextCache.splice(o,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){se("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,r,n,o){let i=Zd.get(r);if(!i)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(t,i,n,o)}uploadTensor(t,r){if(!Te().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");se("verbose",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${r.byteLength}}`),this.tensorManager.upload(t,r)}async downloadTensor(t,r){return this.tensorManager.download(t,r)}createMLTensorDownloader(t,r){return async()=>{let n=await this.tensorManager.download(t);return Fr(n,r)}}registerMLTensor(t,r,n){let o=Zd.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);let i=this.tensorManager.registerTensor(this.currentContext,t,o,n);return se("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${o}, dimensions: ${n}} -> {tensorId: ${i}}`),i}registerMLConstant(t,r,n,o,i,a){if(!a)throw new Error("External mounted files are not available.");let l=t;t.startsWith("./")&&(l=t.substring(2));let d=a.get(l);if(!d)throw new Error(`File with name ${l} not found in preloaded files.`);if(r+n>d.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=d.slice(r,r+n).buffer,m;switch(i.dataType){case"float32":m=new Float32Array(c);break;case"float16":m=new Uint16Array(c);break;case"int32":m=new Int32Array(c);break;case"uint32":m=new Uint32Array(c);break;case"int64":m=new BigInt64Array(c);break;case"uint64":m=new BigUint64Array(c);break;case"int8":m=new Int8Array(c);break;case"int4":case"uint4":case"uint8":m=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return se("verbose",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`),o.constant(i,m)}flush(){}}});var Qd={};Ft(Qd,{init:()=>ag});var sr,Bo,ag,Jd=R(()=>{"use strict";te();Fd();je();oe();Xd();sr=class e{constructor(t,r,n,o){this.module=t;this.dataType=r;this.data=n;this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=k.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=k.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=k.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=k.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(k.size(t)!==k.size(this.dims))throw new Error("Invalid new shape");return new e(this.module,this.dataType,this.data,t)}},Bo=class{constructor(t,r,n){this.module=t;this.backend=r;this.customDataOffset=0;this.customDataSize=0;this.adapterInfo=r.adapterInfo,this.deviceInfo=r.deviceInfo;let o=t.PTR_SIZE,i=n/t.PTR_SIZE,a=o===4?"i32":"i64";this.opKernelContext=Number(t.getValue(o*i++,a));let l=Number(t.getValue(o*i++,a));this.outputCount=Number(t.getValue(o*i++,a)),this.customDataOffset=Number(t.getValue(o*i++,"*")),this.customDataSize=Number(t.getValue(o*i++,a));let d=[];for(let c=0;ctypeof l=="number"?this.inputs[l]:l)??this.inputs,o=r?.outputs??[],i=(l,d,c)=>new sr(this.module,d,this.output(l,c),c),a=(l,d)=>{let c=Tt(l,d);if(!c)throw new Error(`Unsupported data type: ${l}`);let m=c>0?this.backend.gpuDataManager.create(c).id:0;return new sr(this.module,l,m,d)};return this.backend.run(t,n,o,i,a,this.outputCount)}output(t,r){let n=this.module.stackSave();try{let o=this.module.PTR_SIZE,i=o===4?"i32":"i64",a=this.module.stackAlloc((1+r.length)*o);this.module.setValue(a,r.length,i);for(let l=0;l{let o=t.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let i=new cn;await i.initialize(r,n),o("webgpu",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,d,c=!1)=>{if(c)se("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(d)}`),i.memcpy(Number(a),Number(l));else{se("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(d)}`);let m=t.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(d));i.upload(Number(l),m)}},async(a,l,d)=>{se("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${d}`),await i.download(Number(a),()=>t.HEAPU8.subarray(Number(l)>>>0,Number(l+d)>>>0))},(a,l,d)=>i.createKernel(a,Number(l),d,t.UTF8ToString(t._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,d,c)=>{se("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${d}, kernel=${a}, contextDataOffset=${l}`);let m=new Bo(t,i,Number(l));return i.computeKernel(Number(a),m,c)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let i=new fn(r);o("webnn",[i,()=>i.reserveTensorId(),a=>i.releaseTensorId(a),async(a,l,d,c)=>i.ensureTensor(a,l,d,c),(a,l)=>{i.uploadTensor(a,l)},async(a,l)=>i.downloadTensor(a,l)])}}});var sg,zr,Or,kt,ug,Kt,Dr,Br,ec,Mr,Rr,Ur,Xn=R(()=>{"use strict";qa();Ka();te();gt();Nr();ro();sg=(e,t)=>{Te()._OrtInit(e,t)!==0&&pe("Can't initialize onnxruntime.")},zr=async e=>{sg(e.wasm.numThreads,Xt(e.logLevel))},Or=async(e,t)=>{{let r=(Jd(),vr(Qd)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let o=e.webgpu.powerPreference;if(o!==void 0&&o!=="low-power"&&o!=="high-performance")throw new Error(`Invalid powerPreference setting: "${o}"`);let i=e.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:o,forceFallbackAdapter:i}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await r("webgpu",Te(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",Te(),e)}}},kt=new Map,ug=e=>{let t=Te(),r=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,o,o+n)!==0&&pe("Can't get session input/output count.");let a=n===4?"i32":"i64";return[Number(t.getValue(o,a)),Number(t.getValue(o+n,a))]}finally{t.stackRestore(r)}},Kt=e=>{let t=Te(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},Dr=async(e,t)=>{let r,n,o=Te();Array.isArray(e)?[r,n]=e:e.buffer===o.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=Kt(e);let i=0,a=0,l=0,d=[],c=[],m=[];try{if([a,d]=ja(t),t?.externalData&&o.mountExternalData){let v=[];for(let S of t.externalData){let T=typeof S=="string"?S:S.path;v.push(Qt(typeof S=="string"?S:S.data).then(C=>{o.mountExternalData(T,C)}))}await Promise.all(v)}for(let v of t?.executionProviders??[])if((typeof v=="string"?v:v.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,o.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof v!="string"){let T=v,C=T?.context,A=T?.gpuDevice,P=T?.deviceType,O=T?.powerPreference;C?o.currentContext=C:A?o.currentContext=await o.jsepCreateMLContext(A):o.currentContext=await o.jsepCreateMLContext({deviceType:P,powerPreference:O})}else o.currentContext=await o.jsepCreateMLContext();break}i=await o._OrtCreateSession(r,n,a),i===0&&pe("Can't create a session."),o.jsepOnCreateSession?.(),o.currentContext&&(o.jsepRegisterMLContext(i,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[u,h]=ug(i),w=!!t?.enableGraphCapture,y=[],g=[],x=[];for(let v=0;vv==="gpu-buffer"||v==="ml-tensor")&&(l=o._OrtCreateBinding(i),l===0&&pe("Can't create IO binding."),$={handle:l,outputPreferredLocations:x,outputPreferredLocationsEncoded:x.map(v=>to(v))}),kt.set(i,[i,c,m,$,w,!1]),[i,y,g]}catch(u){throw c.forEach(h=>o._OrtFree(h)),m.forEach(h=>o._OrtFree(h)),l!==0&&o._OrtReleaseBinding(l)!==0&&pe("Can't release IO binding."),i!==0&&o._OrtReleaseSession(i)!==0&&pe("Can't release session."),u}finally{o._free(r),a!==0&&o._OrtReleaseSessionOptions(a)!==0&&pe("Can't release session options."),d.forEach(u=>o._free(u)),o.unmountExternalData?.()}},Br=e=>{let t=Te(),r=kt.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,o,i,a,l]=r;a&&(l&&t._OrtClearBoundOutputs(a.handle)!==0&&pe("Can't clear bound outputs."),t._OrtReleaseBinding(a.handle)!==0&&pe("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),o.forEach(d=>t._OrtFree(d)),i.forEach(d=>t._OrtFree(d)),t._OrtReleaseSession(n)!==0&&pe("Can't release session."),kt.delete(e)},ec=(e,t,r,n,o,i=!1)=>{if(!e){t.push(0);return}let a=Te(),l=a.PTR_SIZE,d=e[0],c=e[1],m=e[3],u,h;if(d==="string"&&(m==="gpu-buffer"||m==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&m!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(m==="gpu-buffer"){let g=e[2].gpuBuffer;h=Tt(Zt(d),c);let x=a.jsepRegisterBuffer;if(!x)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');u=x(n,o,g,h)}else if(m==="ml-tensor"){let g=e[2].mlTensor;h=Tt(Zt(d),c);let x=a.jsepRegisterMLTensor;if(!x)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');u=x(g,Zt(d),c)}else{let g=e[2];if(Array.isArray(g)){h=l*g.length,u=a._malloc(h),r.push(u);for(let x=0;xa.setValue(y+$*l,x,l===4?"i32":"i64"));let g=a._OrtCreateTensor(Zt(d),u,h,y,c.length,to(m));g===0&&pe(`Can't create tensor for input/output. session=${n}, index=${o}.`),t.push(g)}finally{a.stackRestore(w)}},Mr=async(e,t,r,n,o,i)=>{let a=Te(),l=a.PTR_SIZE,d=kt.get(e);if(!d)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=d[0],m=d[1],u=d[2],h=d[3],w=d[4],y=d[5],g=t.length,x=n.length,$=0,v=[],S=[],T=[],C=[],A=a.stackSave(),P=a.stackAlloc(g*l),O=a.stackAlloc(g*l),U=a.stackAlloc(x*l),L=a.stackAlloc(x*l);try{a.jsepOnRunStart?.(c),[$,v]=Fa(i);for(let W=0;W_e*be,1);Q=bt($e);let qe=h?.outputPreferredLocations[n[W]];if(Q==="string"){if(qe==="gpu-buffer"||qe==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let _e=[];for(let be=0;be0){let _e=a.jsepGetBuffer;if(!_e)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let be=_e(ne),Ye=Tt($e,he);if(Ye===void 0||!Lr(Q))throw new Error(`Unsupported data type: ${Q}`);J=!0,K.push([Q,q,{gpuBuffer:be,download:a.jsepCreateDownloader(be,Ye,Q),dispose:()=>{a._OrtReleaseTensor(ee)!==0&&pe("Can't release tensor.")}},"gpu-buffer"])}else if(qe==="ml-tensor"&&he>0){let _e=a.jsepEnsureTensor;if(!_e)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Tt($e,he)===void 0||!Gr(Q))throw new Error(`Unsupported data type: ${Q}`);let Ye=await _e(ne,$e,q,!1);J=!0,K.push([Q,q,{mlTensor:Ye,download:a.jsepCreateMLTensorDownloader(ne,Q),dispose:()=>{a.jsepReleaseTensorId(ne),a._OrtReleaseTensor(ee)}},"ml-tensor"])}else{let _e=Wr(Q),be=new _e(he);new Uint8Array(be.buffer,be.byteOffset,be.byteLength).set(a.HEAPU8.subarray(ne,ne+be.byteLength)),K.push([Q,q,be,"cpu"])}}finally{a.stackRestore(ue),Q==="string"&&ne&&a._free(ne),J||a._OrtReleaseTensor(ee)}}return h&&!w&&(a._OrtClearBoundOutputs(h.handle)!==0&&pe("Can't clear bound outputs."),kt.set(e,[c,m,u,h,w,!1])),K}finally{a.stackRestore(A),S.forEach(j=>a._OrtReleaseTensor(j)),T.forEach(j=>a._OrtReleaseTensor(j)),C.forEach(j=>a._free(j)),$!==0&&a._OrtReleaseRunOptions($),v.forEach(j=>a._free(j))}},Rr=e=>{let t=Te(),r=kt.get(e);if(!r)throw new Error("invalid session id");let n=r[0],o=t._OrtEndProfiling(n);o===0&&pe("Can't get an profile file name."),t._OrtFree(o)},Ur=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}});var Et,Fe,ur,gn,bn,hn,Mo,Ro,Nt,Wt,dg,tc,rc,nc,oc,ic,ac,sc,Uo=R(()=>{"use strict";He();Xn();gt();jt();Et=()=>!!ve.wasm.proxy&&typeof document<"u",ur=!1,gn=!1,bn=!1,Ro=new Map,Nt=(e,t)=>{let r=Ro.get(e);r?r.push(t):Ro.set(e,[t])},Wt=()=>{if(ur||!gn||bn||!Fe)throw new Error("worker not ready")},dg=e=>{switch(e.data.type){case"init-wasm":ur=!1,e.data.err?(bn=!0,Mo[1](e.data.err)):(gn=!0,Mo[0]()),hn&&(URL.revokeObjectURL(hn),hn=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Ro.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},tc=async()=>{if(!gn){if(ur)throw new Error("multiple calls to 'initWasm()' detected.");if(bn)throw new Error("previous call to 'initWasm()' failed.");if(ur=!0,Et())return new Promise((e,t)=>{Fe?.terminate(),La().then(([r,n])=>{try{Fe=n,Fe.onerror=i=>t(i),Fe.onmessage=dg,Mo=[e,t];let o={type:"init-wasm",in:ve};Fe.postMessage(o),hn=r}catch(o){t(o)}},t)});try{await Pr(ve.wasm),await zr(ve),gn=!0}catch(e){throw bn=!0,e}finally{ur=!1}}},rc=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Nt("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:ve}};Fe.postMessage(n)});await Or(ve,e)},nc=async e=>Et()?(Wt(),new Promise((t,r)=>{Nt("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};Fe.postMessage(n,[e.buffer])})):Kt(e),oc=async(e,t)=>{if(Et()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Wt(),new Promise((r,n)=>{Nt("create",[r,n]);let o={type:"create",in:{model:e,options:{...t}}},i=[];e instanceof Uint8Array&&i.push(e.buffer),Fe.postMessage(o,i)})}else return Dr(e,t)},ic=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Nt("release",[t,r]);let n={type:"release",in:e};Fe.postMessage(n)});Br(e)},ac=async(e,t,r,n,o,i)=>{if(Et()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return Wt(),new Promise((a,l)=>{Nt("run",[a,l]);let d=r,c={type:"run",in:{sessionId:e,inputIndices:t,inputs:d,outputIndices:n,options:i}};Fe.postMessage(c,Ur(d))})}else return Mr(e,t,r,n,o,i)},sc=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Nt("end-profiling",[t,r]);let n={type:"end-profiling",in:e};Fe.postMessage(n)});Rr(e)}});var uc,cg,yn,lc=R(()=>{"use strict";He();Uo();te();Er();ro();uc=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},cg=e=>{switch(e[3]){case"cpu":return new De(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Lr(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:o}=e[2];return De.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:o})}case"ml-tensor":{let t=e[0];if(!Gr(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:o}=e[2];return De.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},yn=class{async fetchModelAndCopyToWasmMemory(t){return nc(await Qt(t))}async loadModel(t,r){Ue();let n;typeof t=="string"? false?0:n=await this.fetchModelAndCopyToWasmMemory(t):n=t,[this.sessionId,this.inputNames,this.outputNames]=await oc(n,r),Be()}async dispose(){return ic(this.sessionId)}async run(t,r,n){Ue();let o=[],i=[];Object.entries(t).forEach(h=>{let w=h[0],y=h[1],g=this.inputNames.indexOf(w);if(g===-1)throw new Error(`invalid input '${w}'`);o.push(y),i.push(g)});let a=[],l=[];Object.entries(r).forEach(h=>{let w=h[0],y=h[1],g=this.outputNames.indexOf(w);if(g===-1)throw new Error(`invalid output '${w}'`);a.push(y),l.push(g)});let d=o.map((h,w)=>uc(h,()=>`input "${this.inputNames[i[w]]}"`)),c=a.map((h,w)=>h?uc(h,()=>`output "${this.outputNames[l[w]]}"`):null),m=await ac(this.sessionId,i,d,l,c,n),u={};for(let h=0;hwn,initializeFlags:()=>dc,wasmBackend:()=>pg});var dc,wn,pg,pc=R(()=>{"use strict";He();Uo();lc();jt();dc=()=>{if((typeof ve.wasm.initTimeout!="number"||ve.wasm.initTimeout<0)&&(ve.wasm.initTimeout=0),ve.wasm.simd===!1&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof ve.wasm.proxy!="boolean"&&(ve.wasm.proxy=!1),typeof ve.wasm.trace!="boolean"&&(ve.wasm.trace=!1),typeof ve.wasm.numThreads!="number"||!Number.isInteger(ve.wasm.numThreads)||ve.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)ve.wasm.numThreads=1;else{let e=typeof navigator>"u"?qn("node:os").cpus().length:navigator.hardwareConcurrency;ve.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},wn=class{async init(t){dc(),await tc(),await rc(t)}async createInferenceSessionHandler(t,r){let n=new yn;return await n.loadModel(t,r),Promise.resolve(n)}},pg=new wn});He();He();He();var Oa="1.21.0-dev.20241109-d3ad76b2cf";var y1=Zn;{let e=(pc(),vr(cc)).wasmBackend;xt("webgpu",e,5),xt("webnn",e,5),xt("cpu",e,10),xt("wasm",e,10)}Object.defineProperty(ve.versions,"web",{value:Oa,enumerable:!0}); +${l}`,p=n.createShaderModule({code:d,label:t.name});ue("verbose",()=>`[WebGPU] ${t.name} shader code: ${d}`);let m=n.createComputePipeline({compute:{module:p,entryPoint:"main"},layout:"auto",label:t.name});return De(t.name),{programInfo:t,computePipeline:m,uniformVariablesInfo:a.variablesInfo}}normalizeDispatchGroupSize(t){let r=typeof t=="number"?t:t.x,n=typeof t=="number"?1:t.y||1,o=typeof t=="number"?1:t.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=i&&n<=i&&o<=i)return[r,n,o];let a=r*n*o,l=Math.ceil(Math.sqrt(a));if(l>i){if(l=Math.ceil(Math.cbrt(a)),l>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[l,l,l]}else return[l,l,1]}}});var ng,og,Ao,ko,un,Kd=R(()=>{"use strict";We();te();Je();eo();Qa();qd();jd();ng=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let n=0;n{let n=e.name;return e.shaderCache?.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+r+`:${ng(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,n},Ao=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},ko=class{constructor(t){this.subgroupsSupported=t.features.has("subgroups"),this.subgroupsF16Supported=t.features.has("subgroups");let r=t.limits;!this.subgroupsSupported||!r.minSubgroupSize||!r.maxSubgroupSize?this.subgroupSizeRange=void 0:this.subgroupSizeRange=[r.minSubgroupSize,r.maxSubgroupSize]}},un=class{constructor(){this.currentSessionId=null;this.currentKernelId=null;this.commandEncoder=null;this.computePassEncoder=null;this.maxDispatchNumber=16;this.pendingDispatchNumber=0;this.pendingKernels=[];this.pendingQueries=new Map;this.sessionStatus="default";this.capturedCommandList=new Map;this.capturedPendingKernels=new Map;this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,r){this.env=t;let n=[],o={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},i=a=>r.features.has(a)&&n.push(a)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups")&&i("subgroups-f16"),this.device=await r.requestDevice(o),this.deviceInfo=new ko(this.device),this.adapterInfo=new Ao(r.info||await r.requestAdapterInfo()),this.gpuDataManager=Za(this),this.programManager=new sn(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Vr(t.logLevel,!!t.debug),this.device.onuncapturederror=a=>{a.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${a.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ue(),this.endComputePass();let t;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),t=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(t,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,t,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&t.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(t.getMappedRange()),n=this.pendingQueries.get(t);for(let o=0;o"u"&&(this.queryTimeBase=_);let g=Number(_-this.queryTimeBase),x=Number(y-this.queryTimeBase);if(!Number.isSafeInteger(g)||!Number.isSafeInteger(x))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:u.map($=>({dims:$.dims,dataType:gt($.dataType)})),outputsMetadata:h.map($=>({dims:$.dims,dataType:gt($.dataType)})),kernelId:a,kernelType:d,kernelName:p,programName:m,startTime:g,endTime:x});else{let $="";u.forEach((S,T)=>{$+=`input[${T}]: [${S.dims}] | ${gt(S.dataType)}, `});let v="";h.forEach((S,T)=>{v+=`output[${T}]: [${S.dims}] | ${gt(S.dataType)}, `}),console.log(`[profiling] kernel "${a}|${d}|${p}|${m}" ${$}${v}execution time: ${x-g} ns`)}xr("GPU",`${m}::${_}::${y}`)}t.unmap(),this.pendingQueries.delete(t)}),De()}run(t,r,n,o,i,a){Ue(t.name);let l=[];for(let S=0;ST):n;if(u.length!==d.length)throw new Error(`Output size ${u.length} must be equal to ${d.length}.`);let h=[],_=[];for(let S=0;S=a)throw new Error(`Invalid output index: ${u[S]}`);if(u[S]===-3)continue;let T=u[S]===-1,C=u[S]===-2,A=T||C?i(d[S].dataType,d[S].dims):o(u[S],d[S].dataType,d[S].dims);if(h.push(A),A.data===0)continue;let P=this.gpuDataManager.get(A.data);if(!P)throw new Error(`no GPU data for output: ${A.data}`);if(T&&this.temporaryData.push(P),C){let O=this.kernelPersistentData.get(this.currentKernelId);O||(O=[],this.kernelPersistentData.set(this.currentKernelId,O)),O.push(P)}_.push(P)}if(l.length!==r.length||_.length!==h.length){if(_.length===0)return De(t.name),h;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let y;if(m){let S=0,T=[];m.forEach(O=>{let U=typeof O.data=="number"?[O.data]:O.data;if(U.length===0)return;let G=O.type===10?2:4,q,K;O.type===10?(K=U.length>4?16:U.length>2?8:U.length*G,q=U.length>4?16:G*U.length):(K=U.length<=2?U.length*G:16,q=16),S=Math.ceil(S/K)*K,T.push(S);let W=O.type===10?8:4;S+=U.length>4?Math.ceil(U.length/W)*q:U.length*G});let C=16;S=Math.ceil(S/C)*C;let A=new ArrayBuffer(S);m.forEach((O,U)=>{let G=T[U],q=typeof O.data=="number"?[O.data]:O.data;if(O.type===6)new Int32Array(A,G,q.length).set(q);else if(O.type===12)new Uint32Array(A,G,q.length).set(q);else if(O.type===10)new Uint16Array(A,G,q.length).set(q);else if(O.type===1)new Float32Array(A,G,q.length).set(q);else throw new Error(`Unsupported uniform type: ${gt(O.type)}`)});let P=this.gpuDataManager.create(S,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(P.buffer,0,A,0,S),this.gpuDataManager.release(P.id),y={offset:0,size:S,buffer:P.buffer}}let g=this.programManager.normalizeDispatchGroupSize(p),x=g[1]===1&&g[2]===1,$=og(t,r,x),v=this.programManager.getArtifact($);if(v||(v=this.programManager.build(t,g),this.programManager.setArtifact($,v),ue("info",()=>`[artifact] key: ${$}, programName: ${t.name}`)),m&&v.uniformVariablesInfo){if(m.length!==v.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${v.uniformVariablesInfo.length}, got ${m.length} in program "${v.programInfo.name}".`);for(let S=0;S`[ProgramManager] run "${t.name}" (key=${$}) with ${g[0]}x${g[1]}x${g[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let S={kernelId:this.currentKernelId,programName:v.programInfo.name,inputTensorViews:r,outputTensorViews:h};this.pendingKernels.push(S),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(S)}return this.programManager.run(v,l,_,g,y),De(t.name),h}upload(t,r){this.gpuDataManager.upload(t,r)}memcpy(t,r){this.gpuDataManager.memcpy(t,r)}async download(t,r){await this.gpuDataManager.download(t,r)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,r,n,o){let i=Fd.get(t);if(!i)throw new Error(`kernel not implemented: ${t}`);let a={kernelType:t,kernelName:o,kernelEntry:i[0],attributes:[i[1],n]};this.kernels.set(r,a)}releaseKernel(t){let r=this.kernelPersistentData.get(t);if(r){for(let n of r)this.gpuDataManager.release(n.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,r,n){let o=this.kernels.get(t);if(!o)throw new Error(`kernel not created: ${t}`);let i=o.kernelType,a=o.kernelName,l=o.kernelEntry,d=o.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=t,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),ue("info",()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope("validation"),l(r,d[1]),0}catch(m){return n.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${m}`)),1}finally{p&&n.push(this.device.popErrorScope().then(m=>m?`GPU validation error for kernel "[${i}] ${a}": ${m.message}`:null));for(let m of this.temporaryData)this.gpuDataManager.release(m.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,r,n,o){let i=this.sessionExternalDataMapping.get(t);i||(i=new Map,this.sessionExternalDataMapping.set(t,i));let a=i.get(r),l=this.gpuDataManager.registerExternalBuffer(n,o,a);return i.set(r,[l,n]),l}unregisterBuffers(t){let r=this.sessionExternalDataMapping.get(t);r&&(r.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[0])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let r=this.gpuDataManager.get(t);if(!r)throw new Error(`no GPU data for buffer: ${t}`);return r.buffer}createDownloader(t,r,n){return async()=>{let o=await oo(this,t,r);return Wr(o.buffer,n)}}writeTimestamp(t){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){ue("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){ue("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){ue("info","replay"),this.sessionStatus="replaying";let t=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),n=t.length;this.pendingKernels=[];for(let o=0;o=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}});var ig,Yd,ag,Zd,ln,dn,Eo,Qd,Xd=R(()=>{"use strict";Je();ig=1,Yd=()=>ig++,ag=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Zd=(e,t)=>{let r=ag.get(e);if(!r)throw new Error("Unsupported data type.");return Math.ceil(t.reduce((n,o)=>n*o)*r/8)},ln=class{constructor(t){this.sessionId=t.sessionId,this.mlContext=t.context,this.mlTensor=t.tensor,this.dataType=t.dataType,this.tensorShape=t.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Zd(this.dataType,this.tensorShape)}destroy(){ue("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t){return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}sameTypeAndShape(t,r){return this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((n,o)=>n===r[o])}},dn=class{constructor(t,r){this.tensorManager=t;this.wrapper=r}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(t,r,n){if(this.wrapper){if(this.wrapper.sameTypeAndShape(t,r))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==Zd(t,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let o=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,r,o,!0,!0),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(t){if(this.wrapper)if(t.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else ue("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(t){if(this.activeUpload)if(t){t instanceof ArrayBuffer?new Uint8Array(t).set(this.activeUpload):new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.wrapper)throw new Error("Tensor has not been created.");return t?this.wrapper.read(t):this.wrapper.read()}},Eo=class{constructor(t){this.backend=t;this.tensorTrackersById=new Map;this.freeTensors=[];this.externalTensors=new Set}reserveTensorId(){let t=Yd();return this.tensorTrackersById.set(t,new dn(this)),t}releaseTensorId(t){let r=this.tensorTrackersById.get(t);r&&(this.tensorTrackersById.delete(t),r.tensorWrapper&&this.releaseTensor(r.tensorWrapper))}async ensureTensor(t,r,n,o){ue("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${n}, copyOld: ${o}}`);let i=this.tensorTrackersById.get(t);if(!i)throw new Error("Tensor not found.");return i.ensureTensor(r,n,o)}upload(t,r){let n=this.tensorTrackersById.get(t);if(!n)throw new Error("Tensor not found.");n.upload(r)}async download(t,r){ue("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${r?.byteLength}}`);let n=this.tensorTrackersById.get(t);if(!n)throw new Error("Tensor not found.");return n.download(r)}releaseTensorsForSession(t){for(let r of this.freeTensors)r.sessionId===t&&r.destroy();this.freeTensors=this.freeTensors.filter(r=>r.sessionId!==t)}registerTensor(t,r,n,o){let i=Yd(),a=new ln({sessionId:this.backend.currentSessionId,context:t,tensor:r,dataType:n,shape:o});return this.tensorTrackersById.set(i,new dn(this,a)),this.externalTensors.add(a),i}async getCachedTensor(t,r,n,o,i){let a=this.backend.currentSessionId;for(let[p,m]of this.freeTensors.entries())if(m.sameTypeAndShape(t,r)){ue("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, shape: ${r}}`);let u=this.freeTensors.splice(p,1)[0];return u.sessionId=a,u}let l=this.backend.currentContext;ue("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, shape: ${r}}`);let d=await l.createTensor({dataType:t,shape:r,dimensions:r,usage:n,writable:o,readable:i});return new ln({sessionId:a,context:l,tensor:d,dataType:t,shape:r})}releaseTensor(t){this.externalTensors.has(t)&&this.externalTensors.delete(t),this.freeTensors.push(t)}},Qd=(...e)=>new Eo(...e)});var Jd,sg,cn,ec=R(()=>{"use strict";te();ht();eo();Xd();Je();Jd=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),sg=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.length===n.length&&r.every((o,i)=>o===n[i]&&e[o]===t[o])},cn=class{constructor(t){this.tensorManager=Qd(this);this.mlContextBySessionId=new Map;this.sessionIdsByMLContext=new Map;this.mlContextCache=[];Vr(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){this.activeSessionId=t}async createMLContext(t){if(t instanceof GPUDevice){let n=this.mlContextCache.findIndex(o=>o.gpuDevice===t);if(n!==-1)return this.mlContextCache[n].mlContext;{let o=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:o}),o}}else if(t===void 0){let n=this.mlContextCache.findIndex(o=>o.options===void 0&&o.gpuDevice===void 0);if(n!==-1)return this.mlContextCache[n].mlContext;{let o=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:o}),o}}let r=this.mlContextCache.findIndex(n=>sg(n.options,t));if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:n}),n}}get currentContext(){let t=this.getMLContext(this.currentSessionId);if(!t)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return t}registerMLContext(t,r){this.mlContextBySessionId.set(t,r);let n=this.sessionIdsByMLContext.get(r);n||(n=new Set,this.sessionIdsByMLContext.set(r,n)),n.add(t)}onReleaseSession(t){let r=this.mlContextBySessionId.get(t);if(!r)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t);let n=this.sessionIdsByMLContext.get(r);if(n.delete(t),n.size===0){this.sessionIdsByMLContext.delete(r);let o=this.mlContextCache.findIndex(i=>i.mlContext===r);o!==-1&&this.mlContextCache.splice(o,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){ue("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,r,n,o){let i=Jd.get(r);if(!i)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(t,i,n,o)}uploadTensor(t,r){if(!Ce().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");ue("verbose",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${r.byteLength}}`),this.tensorManager.upload(t,r)}async downloadTensor(t,r){return this.tensorManager.download(t,r)}createMLTensorDownloader(t,r){return async()=>{let n=await this.tensorManager.download(t);return Wr(n,r)}}registerMLTensor(t,r,n){let o=Jd.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);let i=this.tensorManager.registerTensor(this.currentContext,t,o,n);return ue("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${o}, dimensions: ${n}} -> {tensorId: ${i}}`),i}registerMLConstant(t,r,n,o,i,a){if(!a)throw new Error("External mounted files are not available.");let l=t;t.startsWith("./")&&(l=t.substring(2));let d=a.get(l);if(!d)throw new Error(`File with name ${l} not found in preloaded files.`);if(r+n>d.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=d.slice(r,r+n).buffer,m;switch(i.dataType){case"float32":m=new Float32Array(p);break;case"float16":m=new Uint16Array(p);break;case"int32":m=new Int32Array(p);break;case"uint32":m=new Uint32Array(p);break;case"int64":m=new BigInt64Array(p);break;case"uint64":m=new BigUint64Array(p);break;case"int8":m=new Int8Array(p);break;case"int4":case"uint4":case"uint8":m=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return ue("verbose",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`),o.constant(i,m)}flush(){}}});var tc={};Ft(tc,{init:()=>ug});var nr,Po,ug,rc=R(()=>{"use strict";te();Kd();Je();oe();ec();nr=class e{constructor(t,r,n,o){this.module=t;this.dataType=r;this.data=n;this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=k.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=k.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=k.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=k.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(k.size(t)!==k.size(this.dims))throw new Error("Invalid new shape");return new e(this.module,this.dataType,this.data,t)}},Po=class{constructor(t,r,n){this.module=t;this.backend=r;this.customDataOffset=0;this.customDataSize=0;this.adapterInfo=r.adapterInfo,this.deviceInfo=r.deviceInfo;let o=t.PTR_SIZE,i=n/t.PTR_SIZE,a=o===4?"i32":"i64";this.opKernelContext=Number(t.getValue(o*i++,a));let l=Number(t.getValue(o*i++,a));this.outputCount=Number(t.getValue(o*i++,a)),this.customDataOffset=Number(t.getValue(o*i++,"*")),this.customDataSize=Number(t.getValue(o*i++,a));let d=[];for(let p=0;ptypeof l=="number"?this.inputs[l]:l)??this.inputs,o=r?.outputs??[],i=(l,d,p)=>new nr(this.module,d,this.output(l,p),p),a=(l,d)=>{let p=Tt(l,d);if(!p)throw new Error(`Unsupported data type: ${l}`);let m=p>0?this.backend.gpuDataManager.create(p).id:0;return new nr(this.module,l,m,d)};return this.backend.run(t,n,o,i,a,this.outputCount)}output(t,r){let n=this.module.stackSave();try{let o=this.module.PTR_SIZE,i=o===4?"i32":"i64",a=this.module.stackAlloc((1+r.length)*o);this.module.setValue(a,r.length,i);for(let l=0;l{let o=t.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let i=new un;await i.initialize(r,n),o("webgpu",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,d,p=!1)=>{if(p)ue("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(d)}`),i.memcpy(Number(a),Number(l));else{ue("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(d)}`);let m=t.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(d));i.upload(Number(l),m)}},async(a,l,d)=>{ue("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${d}`),await i.download(Number(a),()=>t.HEAPU8.subarray(Number(l)>>>0,Number(l+d)>>>0))},(a,l,d)=>i.createKernel(a,Number(l),d,t.UTF8ToString(t._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,d,p)=>{ue("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${d}, kernel=${a}, contextDataOffset=${l}`);let m=new Po(t,i,Number(l));return i.computeKernel(Number(a),m,p)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let i=new cn(r);o("webnn",[i,()=>i.reserveTensorId(),a=>i.releaseTensorId(a),async(a,l,d,p)=>i.ensureTensor(a,l,d,p),(a,l)=>{i.uploadTensor(a,l)},async(a,l)=>i.downloadTensor(a,l)])}}});var lg,Ar,kr,kt,dg,Kt,Er,Pr,nc,zr,Or,Br,Kn=R(()=>{"use strict";La();Ha();te();ht();Mr();Jn();lg=(e,t)=>{Ce()._OrtInit(e,t)!==0&&pe("Can't initialize onnxruntime.")},Ar=async e=>{lg(e.wasm.numThreads,Qt(e.logLevel))},kr=async(e,t)=>{{let r=(rc(),br(tc)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let o=e.webgpu.powerPreference;if(o!==void 0&&o!=="low-power"&&o!=="high-performance")throw new Error(`Invalid powerPreference setting: "${o}"`);let i=e.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:o,forceFallbackAdapter:i}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await r("webgpu",Ce(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",Ce(),e)}}},kt=new Map,dg=e=>{let t=Ce(),r=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,o,o+n)!==0&&pe("Can't get session input/output count.");let a=n===4?"i32":"i64";return[Number(t.getValue(o,a)),Number(t.getValue(o+n,a))]}finally{t.stackRestore(r)}},Kt=e=>{let t=Ce(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},Er=async(e,t)=>{let r,n,o=Ce();Array.isArray(e)?[r,n]=e:e.buffer===o.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=Kt(e);let i=0,a=0,l=0,d=[],p=[],m=[];try{if([a,d]=Ga(t),t?.externalData&&o.mountExternalData){let v=[];for(let S of t.externalData){let T=typeof S=="string"?S:S.path;v.push(Xt(typeof S=="string"?S:S.data).then(C=>{o.mountExternalData(T,C)}))}await Promise.all(v)}for(let v of t?.executionProviders??[])if((typeof v=="string"?v:v.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof v!="string"){let T=v,C=T?.context,A=T?.gpuDevice,P=T?.deviceType,O=T?.powerPreference;C?o.currentContext=C:A?o.currentContext=await o.jsepCreateMLContext(A):o.currentContext=await o.jsepCreateMLContext({deviceType:P,powerPreference:O})}else o.currentContext=await o.jsepCreateMLContext();break}i=await o._OrtCreateSession(r,n,a),i===0&&pe("Can't create a session."),o.jsepOnCreateSession?.(),o.currentContext&&(o.jsepRegisterMLContext(i,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[u,h]=dg(i),_=!!t?.enableGraphCapture,y=[],g=[],x=[];for(let v=0;vv==="gpu-buffer"||v==="ml-tensor")&&(l=o._OrtCreateBinding(i),l===0&&pe("Can't create IO binding."),$={handle:l,outputPreferredLocations:x,outputPreferredLocationsEncoded:x.map(v=>Xn(v))}),kt.set(i,[i,p,m,$,_,!1]),[i,y,g]}catch(u){throw p.forEach(h=>o._OrtFree(h)),m.forEach(h=>o._OrtFree(h)),l!==0&&o._OrtReleaseBinding(l)!==0&&pe("Can't release IO binding."),i!==0&&o._OrtReleaseSession(i)!==0&&pe("Can't release session."),u}finally{o._free(r),a!==0&&o._OrtReleaseSessionOptions(a)!==0&&pe("Can't release session options."),d.forEach(u=>o._free(u)),o.unmountExternalData?.()}},Pr=e=>{let t=Ce(),r=kt.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,o,i,a,l]=r;a&&(l&&t._OrtClearBoundOutputs(a.handle)!==0&&pe("Can't clear bound outputs."),t._OrtReleaseBinding(a.handle)!==0&&pe("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),o.forEach(d=>t._OrtFree(d)),i.forEach(d=>t._OrtFree(d)),t._OrtReleaseSession(n)!==0&&pe("Can't release session."),kt.delete(e)},nc=(e,t,r,n,o,i=!1)=>{if(!e){t.push(0);return}let a=Ce(),l=a.PTR_SIZE,d=e[0],p=e[1],m=e[3],u,h;if(d==="string"&&(m==="gpu-buffer"||m==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&m!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(m==="gpu-buffer"){let g=e[2].gpuBuffer;h=Tt(Zt(d),p);let x=a.jsepRegisterBuffer;if(!x)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');u=x(n,o,g,h)}else if(m==="ml-tensor"){let g=e[2].mlTensor;h=Tt(Zt(d),p);let x=a.jsepRegisterMLTensor;if(!x)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');u=x(g,Zt(d),p)}else{let g=e[2];if(Array.isArray(g)){h=l*g.length,u=a._malloc(h),r.push(u);for(let x=0;xa.setValue(y+$*l,x,l===4?"i32":"i64"));let g=a._OrtCreateTensor(Zt(d),u,h,y,p.length,Xn(m));g===0&&pe(`Can't create tensor for input/output. session=${n}, index=${o}.`),t.push(g)}finally{a.stackRestore(_)}},zr=async(e,t,r,n,o,i)=>{let a=Ce(),l=a.PTR_SIZE,d=kt.get(e);if(!d)throw new Error(`cannot run inference. invalid session id: ${e}`);let p=d[0],m=d[1],u=d[2],h=d[3],_=d[4],y=d[5],g=t.length,x=n.length,$=0,v=[],S=[],T=[],C=[],A=a.stackSave(),P=a.stackAlloc(g*l),O=a.stackAlloc(g*l),U=a.stackAlloc(x*l),G=a.stackAlloc(x*l);try{a.jsepOnRunStart?.(p),[$,v]=Wa(i);for(let W=0;W_e*be,1);ee=gt($e);let Ge=h?.outputPreferredLocations[n[W]];if(ee==="string"){if(Ge==="gpu-buffer"||Ge==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let _e=[];for(let be=0;be0){let _e=a.jsepGetBuffer;if(!_e)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let be=_e(ne),Ke=Tt($e,he);if(Ke===void 0||!Ur(ee))throw new Error(`Unsupported data type: ${ee}`);re=!0,K.push([ee,j,{gpuBuffer:be,download:a.jsepCreateDownloader(be,Ke,ee),dispose:()=>{a._OrtReleaseTensor(Y)!==0&&pe("Can't release tensor.")}},"gpu-buffer"])}else if(Ge==="ml-tensor"&&he>0){let _e=a.jsepEnsureTensor;if(!_e)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Tt($e,he)===void 0||!Nr(ee))throw new Error(`Unsupported data type: ${ee}`);let Ke=await _e(ne,$e,j,!1);re=!0,K.push([ee,j,{mlTensor:Ke,download:a.jsepCreateMLTensorDownloader(ne,ee),dispose:()=>{a.jsepReleaseTensorId(ne),a._OrtReleaseTensor(Y)}},"ml-tensor"])}else{let _e=Rr(ee),be=new _e(he);new Uint8Array(be.buffer,be.byteOffset,be.byteLength).set(a.HEAPU8.subarray(ne,ne+be.byteLength)),K.push([ee,j,be,"cpu"])}}finally{a.stackRestore(se),ee==="string"&&ne&&a._free(ne),re||a._OrtReleaseTensor(Y)}}return h&&!_&&(a._OrtClearBoundOutputs(h.handle)!==0&&pe("Can't clear bound outputs."),kt.set(e,[p,m,u,h,_,!1])),K}finally{a.stackRestore(A),S.forEach(q=>a._OrtReleaseTensor(q)),T.forEach(q=>a._OrtReleaseTensor(q)),C.forEach(q=>a._free(q)),$!==0&&a._OrtReleaseRunOptions($),v.forEach(q=>a._free(q))}},Or=e=>{let t=Ce(),r=kt.get(e);if(!r)throw new Error("invalid session id");let n=r[0],o=t._OrtEndProfiling(n);o===0&&pe("Can't get an profile file name."),t._OrtFree(o)},Br=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}});var Et,Le,or,mn,fn,pn,zo,Oo,Vt,Wt,pg,oc,ic,ac,sc,uc,lc,dc,Bo=R(()=>{"use strict";We();Kn();ht();jt();Et=()=>!!we.wasm.proxy&&typeof document<"u",or=!1,mn=!1,fn=!1,Oo=new Map,Vt=(e,t)=>{let r=Oo.get(e);r?r.push(t):Oo.set(e,[t])},Wt=()=>{if(or||!mn||fn||!Le)throw new Error("worker not ready")},pg=e=>{switch(e.data.type){case"init-wasm":or=!1,e.data.err?(fn=!0,zo[1](e.data.err)):(mn=!0,zo[0]()),pn&&(URL.revokeObjectURL(pn),pn=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Oo.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},oc=async()=>{if(!mn){if(or)throw new Error("multiple calls to 'initWasm()' detected.");if(fn)throw new Error("previous call to 'initWasm()' failed.");if(or=!0,Et())return new Promise((e,t)=>{Le?.terminate(),Ua().then(([r,n])=>{try{Le=n,Le.onerror=i=>t(i),Le.onmessage=pg,zo=[e,t];let o={type:"init-wasm",in:we};Le.postMessage(o),pn=r}catch(o){t(o)}},t)});try{await Cr(we.wasm),await Ar(we),mn=!0}catch(e){throw fn=!0,e}finally{or=!1}}},ic=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Vt("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:we}};Le.postMessage(n)});await kr(we,e)},ac=async e=>Et()?(Wt(),new Promise((t,r)=>{Vt("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};Le.postMessage(n,[e.buffer])})):Kt(e),sc=async(e,t)=>{if(Et()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Wt(),new Promise((r,n)=>{Vt("create",[r,n]);let o={type:"create",in:{model:e,options:{...t}}},i=[];e instanceof Uint8Array&&i.push(e.buffer),Le.postMessage(o,i)})}else return Er(e,t)},uc=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Vt("release",[t,r]);let n={type:"release",in:e};Le.postMessage(n)});Pr(e)},lc=async(e,t,r,n,o,i)=>{if(Et()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return Wt(),new Promise((a,l)=>{Vt("run",[a,l]);let d=r,p={type:"run",in:{sessionId:e,inputIndices:t,inputs:d,outputIndices:n,options:i}};Le.postMessage(p,Br(d))})}else return zr(e,t,r,n,o,i)},dc=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Vt("end-profiling",[t,r]);let n={type:"end-profiling",in:e};Le.postMessage(n)});Or(e)}});var cc,mg,hn,pc=R(()=>{"use strict";We();Bo();te();Ir();Jn();cc=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},mg=e=>{switch(e[3]){case"cpu":return new Oe(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Ur(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:o}=e[2];return Oe.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:o})}case"ml-tensor":{let t=e[0];if(!Nr(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:o}=e[2];return Oe.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},hn=class{async fetchModelAndCopyToWasmMemory(t){return ac(await Xt(t))}async loadModel(t,r){Ue();let n;typeof t=="string"? false?0:n=await this.fetchModelAndCopyToWasmMemory(t):n=t,[this.sessionId,this.inputNames,this.outputNames]=await sc(n,r),De()}async dispose(){return uc(this.sessionId)}async run(t,r,n){Ue();let o=[],i=[];Object.entries(t).forEach(h=>{let _=h[0],y=h[1],g=this.inputNames.indexOf(_);if(g===-1)throw new Error(`invalid input '${_}'`);o.push(y),i.push(g)});let a=[],l=[];Object.entries(r).forEach(h=>{let _=h[0],y=h[1],g=this.outputNames.indexOf(_);if(g===-1)throw new Error(`invalid output '${_}'`);a.push(y),l.push(g)});let d=o.map((h,_)=>cc(h,()=>`input "${this.inputNames[i[_]]}"`)),p=a.map((h,_)=>h?cc(h,()=>`output "${this.outputNames[l[_]]}"`):null),m=await lc(this.sessionId,i,d,l,p,n),u={};for(let h=0;hgn,initializeFlags:()=>mc,wasmBackend:()=>fg});var mc,gn,fg,hc=R(()=>{"use strict";We();Bo();pc();jt();mc=()=>{if((typeof we.wasm.initTimeout!="number"||we.wasm.initTimeout<0)&&(we.wasm.initTimeout=0),we.wasm.simd===!1&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof we.wasm.proxy!="boolean"&&(we.wasm.proxy=!1),typeof we.wasm.trace!="boolean"&&(we.wasm.trace=!1),typeof we.wasm.numThreads!="number"||!Number.isInteger(we.wasm.numThreads)||we.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)we.wasm.numThreads=1;else{let e=typeof navigator>"u"?Gn("node:os").cpus().length:navigator.hardwareConcurrency;we.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},gn=class{async init(t){mc(),await oc(),await ic(t)}async createInferenceSessionHandler(t,r){let n=new hn;return await n.loadModel(t,r),Promise.resolve(n)}},fg=new gn});We();We();We();var ka="1.21.0-dev.20241122-a2ba3cb547";var bS=jn;{let e=(hc(),br(fc)).wasmBackend;xt("webgpu",e,5),xt("webnn",e,5),xt("cpu",e,10),xt("wasm",e,10)}Object.defineProperty(we.versions,"web",{value:ka,enumerable:!0}); /** * @license * Copyright 2021 Google LLC. All Rights Reserved. diff --git a/assets/dist_transformers/1.21.0-dev.20241122/transformers.js.map b/assets/dist_transformers/1.21.0-dev.20241122/transformers.js.map new file mode 100644 index 0000000..deaeb6d --- /dev/null +++ b/assets/dist_transformers/1.21.0-dev.20241122/transformers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transformers.js","mappings":";;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;;;;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD;AACA;AACA;AACA,aAAa,QAAQ;AACrB,aAAa,WAAW;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,MAAM;AACN,MAAM;AACN,MAAM;AACN;AACA;AACA;AACA,KAAK;AACL,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C;AAC1C;AACA;AACA;AACA,gCAAgC,MAAM,OAAO,GAAG;AAChD;AACA,0CAA0C;AAC1C;AACA;AACA,uCAAuC;AACvC;AACA,4BAA4B,GAAG,oBAAoB,UAAU,gBAAgB,QAAQ,gBAAgB,UAAU,iBAAiB,QAAQ;AACxI;AACA,sCAAsC;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iEAAiE,QAAQ;AACzE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC,uEAAuE;AAC3G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yDAAyD,KAAK;AAC9D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,KAAK,EAAE,IAAI;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA,qDAAqD,KAAK;AAC1D;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uCAAuC,MAAM,IAAI,WAAW,MAAM,KAAK;AACvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wDAAwD,qBAAqB;AAC7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qDAAqD;AACrD;AACA,wDAAwD;AACxD;AACA;AACA;AACA;AACA,qDAAqD;AACrD;AACA,wDAAwD;AACxD;AACA;AACA;AACA;AACA,qDAAqD;AACrD;AACA,wDAAwD;AACxD;AACA;AACA,yDAAyD,qBAAqB;AAC9E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oFAAoF,mBAAmB;AACvG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qEAAqE,sBAAsB;AAC3F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,WAAW;AAC9D;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB,UAAU;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA,sBAAsB,kCAAkC;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,cAAc;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB;AACxB,wBAAwB;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8DAA8D,SAAS;AACvE;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8DAA8D,aAAa;AAC3E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+DAA+D,aAAa;AAC5E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0DAA0D,KAAK;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa,QAAQ;AACrB,eAAe,aAAa;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yCAAyC,KAAK;AAC9C;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+CAA+C,oBAAoB,YAAY,WAAW,MAAM,WAAW;AAC3G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qEAAqE,QAAQ,MAAM,OAAO;AAC1F;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4DAA4D,OAAO;AACnE;AACA,eAAe;AACf;AACA;AACA,0DAA0D,aAAa;AACvE;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2DAA2D,aAAa;AACxE;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA,4DAA4D,aAAa;AACzE;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2DAA2D,aAAa;AACxE;AACA;AACA,8CAA8C,aAAa,aAAa,aAAa;AACrF,MAAM;AACN;AACA;AACA,2CAA2C,mBAAmB;AAC9D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD,eAAe;AAChE;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe;AACf;AACA,cAAc;AACd;AACA;AACA;AACA;AACA,sDAAsD,WAAW;AACjE,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,WAAW;AAClE,QAAQ;AACR,gDAAgD,WAAW,aAAa,aAAa;AACrF;AACA;AACA,uCAAuC,iBAAiB;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uCAAuC,gBAAgB;AACvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,oBAAoB;AACvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2EAA2E,QAAQ;AACnF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,uEAAuE,cAAc;AACrF;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA,QAAQ;AACR,kFAAkF,cAAc;AAChG;AACA,MAAM;AACN;AACA,uEAAuE,cAAc;AACrF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN,mEAAmE,8BAA8B;AACjG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,iEAAiE,cAAc;AAC/E;AACA;AACA;AACA,oBAAoB,2BAA2B;AAC/C;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA;AACA,8DAA8D,aAAa;AAC3E;AACA;AACA;AACA,iCAAiC,wDAAwD;AACzF;AACA;AACA,0BAA0B,0BAA0B;AACpD;AACA,oEAAoE,sBAAsB;AAC1F;AACA;AACA;AACA;AACA,QAAQ;AACR,qDAAqD,kBAAkB;AACvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,kBAAkB;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA;AACA;AACA;AACA;AACA,8DAA8D,iBAAiB;AAC/E;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ,sDAAsD,aAAa;AACnE;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gEAAgE,kBAAkB;AAClF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oDAAoD,eAAe;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ;AACR;AACA,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA,0DAA0D,MAAM;AAChE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,gBAAgB,EAAE,cAAc,gBAAgB,GAAG,EAAE,YAAY,SAAS,gBAAgB;AACtH,QAAQ;AACR;AACA,wBAAwB,IAAI,KAAK,wCAAwC;AACzE,6BAA6B,gBAAgB,EAAE,EAAE;AACjD,SAAS;AACT,0BAA0B,EAAE,eAAe,EAAE,aAAa,MAAM,EAAE,iBAAiB;AACnF;AACA;AACA;AACA,iDAAiD,WAAW;AAC5D;AACA;;AAEA;AACA;AACA;AACA;AACA,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAOE;;;;;;;;;;;;;;;;AChxDF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,iCAAiC,mBAAmB;AACpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4DAA4D,KAAK,mBAAmB,SAAS;AAC7F;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,qCAAqC;AACjE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uCAAuC,EAAE;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,uCAAuC;AACjE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4DAA4D,oBAAoB,OAAO,IAAI,MAAM,cAAc;AAC/G;AACA;AACA,iBAAiB,YAAY;AAC7B;AACA;AACA,mEAAmE,KAAK,sDAAsD,IAAI;AAClI;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;;;;;;;;;;;;;;;AC5IA;AACA;AACoD;AACpD;;;;;;;;;;;;;;;ACHA;AACA;AACuC;AACvC;AACO;AACP,YAAY;AACZ,aAAa;AACb,cAAc;AACd,gBAAgB,QAAQ,gDAAO,EAAE;AACjC;AACA;AACA;AACA;AACA;AACA,0DAA0D,MAAM;AAChE;AACA;AACA,KAAK;AACL;AACA;AACA,KAAK;AACL;AACA;AACA,yCAAyC,kBAAkB;AAC3D;;;;;;;;;;;;;;;ACxBA;AACA;AAC+C;AAC/C;AACA;AACA;AACO,YAAY,6CAAO;AAC1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC6B;AACJ;AACc;AACX;AACW;AACH;AACT;AACK;AACA;AACM;AACtC;;;;;;;;;;;;;;;;;AC3BA;AACA;AACwE;AACnC;AACyB;AACvD;AACP;AACA;AACA;AACA;AACA,QAAQ,2DAAgB;AACxB;AACA;AACA;AACA,4EAA4E,8CAAM;AAClF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,8CAAM;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wFAAwF,KAAK;AAC7F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,8CAAM;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,KAAK;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sCAAsC,8CAAM;AAC5C;AACA;AACA;AACA,2CAA2C,8CAAM;AACjD;AACA;AACA;AACA,QAAQ,yDAAc;AACtB;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,2DAAgB;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6EAA6E,kBAAkB;AAC/F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iFAAiF,+BAA+B;AAChH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yDAAyD,qFAAmC;AAC5F;AACA,QAAQ,yDAAc;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;ACrMA;AACA;AACuF;AACvF;AACO,yBAAyB,wEAAoB;AACpD;;;;;;;;;;;ACLA;AACA;AACU;AACV;;;;;;;;;;;ACHA;AACA;AACU;AACV;;;;;;;;;;;;;;;ACHA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe;AACf;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,YAAY;AACpC,4BAA4B,WAAW;AACvC,uFAAuF;AACvF,uFAAuF;AACvF,uFAAuF;AACvF;AACA;AACA,iFAAiF;AACjF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe;AACf;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB,oBAAoB;AAC5C,qGAAqG;AACrG,qGAAqG;AACrG,qGAAqG;AACrG;AACA;AACA,6EAA6E;AAC7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;ACpMA;AACA;AACU;AACV;;;;;;;;;;;;;;;;;;;ACHA;AACA;AAC0C;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,gBAAgB;AAC5B,mCAAmC;AACnC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,YAAY;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,mDAAM;AAC7D,YAAY,mDAAM;AAClB;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,YAAY,mCAAmC;AAC/C;AACA;AACA,eAAe,mDAAM,GAAG,wEAAwE;AAChG;AACA;AACA;AACA;AACO;AACP,YAAY,oCAAoC;AAChD,eAAe,mDAAM,GAAG,yFAAyF;AACjH;AACA;AACA;AACA;AACO,2DAA2D,mDAAM,GAAG,2EAA2E;AACtJ;;;;;;;;;;;AChQA;AACA;AACU;AACV;;;;;;;;;;;;;;;;ACHA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;ACrDA;AACA;AACiF;AAC0C;AACmB;AACxE;AACtE;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA,QAAQ,6EAAe;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0DAA0D,+FAAqC;AAC/F;AACA,iEAAiE,KAAK;AACtE;AACA;AACA,wEAAwE,mCAAmC;AAC3G;AACA;AACA;AACA;AACA;AACA;AACA,iEAAiE,KAAK;AACtE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iEAAiE,KAAK;AACtE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iFAAiF,kBAAkB;AACnG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oFAAoF;AACpF;AACA;AACA;AACA;AACA;AACA,kDAAkD,+FAAqC;AACvF;AACA,wEAAwE,KAAK;AAC7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD,MAAM,gCAAgC,sBAAsB;AAC7G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mFAAmF,iBAAiB;AACpG;AACA;AACA;AACA;AACA,uCAAuC,+FAAqC;AAC5E;AACA,iFAAiF,iBAAiB;AAClG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,oEAAa;AAClC;AACA;AACA,6CAA6C,KAAK,+BAA+B,oBAAoB;AACrG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,wEAAe;AAC9B;AACA;AACA,eAAe,0EAAiB;AAChC;AACA;AACA,eAAe,4EAAmB;AAClC;AACA;AACA,eAAe,+EAAsB;AACrC;AACA;AACA;AACA;AACA,eAAe,2EAAe;AAC9B;AACA;AACA,eAAe,6EAAiB;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kEAAkE,kBAAkB;AACpF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,oEAAa;AAC5B;AACA;AACA;;;;;;;;;;;;;;;;AC1SA;AACA;AAC0C;AAC1C;AACA;AACA;AACA;AACA;AACO;AACP;AACA,oBAAoB,iBAAiB;AACrC;AACA;AACA,wCAAwC,EAAE,6BAA6B,IAAI;AAC3E;AACA;AACA,yCAAyC,EAAE,yCAAyC,IAAI;AACxF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,uBAAuB,mDAAM;AAC7B;AACA,uBAAuB,mDAAM;AAC7B;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,uBAAuB,mDAAM;AAC7B;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,uBAAuB,mDAAM;AAC7B;AACA;AACA;AACA;AACA,aAAa;AACb;AACA,8DAA8D,iBAAiB;AAC/E;AACA;AACA;;;;;;;;;;;;;;;ACtDA;AACA;AACwD;AACxD;AACO,eAAe,mDAAU;AAChC;;;;;;;;;;;;;;;;;ACLA;AACA;AACoC;AACpC;AACA;AACA;AACO;AACP,eAAe,6CAAG,0BAA0B,6CAAG,eAAe,6CAAG;AACjE;AACA;AACA;AACA,yBAAyB,WAAW,SAAS,MAAM;AACnD;AACA;AACA;AACA;AACA,oBAAoB,kBAAkB;AACtC;AACA,gCAAgC,IAAI,IAAI,8BAA8B;AACtE;AACA,8BAA8B,SAAS;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,eAAe,6CAAG,0BAA0B,6CAAG,eAAe,6CAAG;AACjE;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,eAAe,6CAAG,0BAA0B,6CAAG,eAAe,6CAAG;AACjE;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;AChDA;AACA;AACwE;AACnC;AACrC;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yDAAyD,qFAAmC;AAC5F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4EAA4E,8CAAM;AAClF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,8CAAM;AACtC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wFAAwF,KAAK;AAC7F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,8CAAM;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,KAAK;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sCAAsC,8CAAM;AAC5C;AACA;AACA;AACA,2CAA2C,8CAAM;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6DAA6D;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;ACpNA;AACA;AACoF;AACpF;AACO,wBAAwB,sEAAmB;AAClD;;;;;;;;;;;;;;ACLA;AACA;AACA;AACA;AACO;AACP;;;;;;;;;;;;;;;;;;;;;;ACLA;AACA;AACA;AACA;AACA;AACA,6BAA6B,uCAAuC,kCAAkC,uCAAuC,oEAAoE,6CAA6C,iBAAiB,2DAA2D,2DAA2D,EAAE,mCAAmC,eAAe,uBAAuB,uBAAuB,EAAE,gBAAgB,gGAAgG,mDAAmD,EAAE,UAAU,kBAAkB,eAAe,SAAS,KAAK,6BAA6B,aAAa,8BAA8B,qFAAqF,gBAAgB,wBAAwB,qBAAqB,EAAE,KAAK,uBAAuB,6EAA6E,EAAE,mBAAmB,EAAE,GAAG,SAAS,oBAAoB,uBAAuB,YAAY,YAAY,kCAAkC,iBAAiB,OAAO,WAAW,OAAO,2CAA2C,cAAc,gBAA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AACV;AACA;;AAEA,WAAW,0BAA0B;AACrC;AACA;AACA;;AAEA;AACA;AACA;;AAEA,EAAE,SAAS,yCAAI;AACf,WAAW,6CAAiB,IAAI,0NAAS;;AAEzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,EAAE;AACF,WAAW,gDAAQ;;AAEnB,QAAQ,yCAAI;AACZ;AACA;AACA;;AAEA,QAAQ,yCAAI;AACZ;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,WAAW,sDAAsD;AACjE,aAAa,0BAA0B;AACvC;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,4CAA4C,OAAO,uBAAuB,4BAA4B;AACtG;;;AAGA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;;AAEA;AACA;AACA,WAAW,YAAY;AACvB,WAAW,8DAA8D;AACzE,WAAW,QAAQ;AACnB,aAAa,0DAA0D,eAAe,GAAG;AACzF;AACO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,KAAK;AAChB,aAAa,SAAS;AACtB;AACO;AACP;AACA;;AAEA,WAAW,kCAAkC;AAC7C;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,wFAAwF,wCAAG,SAAS;;AAEpG;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,aAAa,SAAS;AACtB;AACO;AACP;AACA;AACA;;AAEA;AACA,wCAAG;;;;;;;;;;;;;;;;;;;;ACtNH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,aAAa;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEuC;AAGf;;AAExB;AACA,aAAa,4CAA4C;AACzD;;;AAGA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,mBAAmB;AAC9B,aAAa,iBAAiB;AAC9B;AACA;AACA,iBAAiB,2DAAY;AAC7B;;AAEA;AACA;AACA,WAAW,kBAAkB;AAC7B,aAAa,QAAQ;AACrB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,2BAA2B,oDAAI;AAC/B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,WAAW,oDAAI;AACf;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,kBAAkB;AAC7B,aAAa;AACb;AACO;AACP;AACA,EAAE,IAAI;AACN,eAAe,0BAA0B;AACzC;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,wBAAwB,0CAA0C;AAClE,4BAA4B,OAAO,GAAG,EAAE;AACxC,4BAA4B,OAAO,GAA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;;;;;;;;;;;ACrJA;AACA;AACA;;AAEwC;;AAExC;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,uCAAuC;AACvC,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,+BAA+B,mDAAmD;AAClF,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;AACA,eAAe,2DAA2D;AAC1E;AACA;AACA,4BAA4B,oDAAI;AAChC;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC1XA;AACA;AACA;;AAE+C;AACH;;AAES;;AAErD;AACA;AACA;AACO,8BAA8B,uDAAQ;AAC7C;AACA;AACA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACO,2BAA2B,uDAAQ;AAC1C;AACA;AACA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACO,kCAAkC,uDAAQ;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,iBAAiB;AAChC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,mBAAmB;AAClC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,oBAAoB;AACtC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,kBAAkB,YAAY;AAC9B,kBAAkB,QAAQ;AAC1B,oBAAoB,QAAQ;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA,qDAAqD,cAAc;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,iBAAiB;AAChC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA,qDAAqD,cAAc;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,UAAU;AACzB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA,qDAAqD,cAAc;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,2EAA2E;AAC1F,eAAe,UAAU;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA,wBAAwB,sBAAsB;AAC9C,iDAAiD,cAAc;;AAE/D;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,qFAAqF;AACrF;AACA;AACA;;AAEA;AACA,iDAAiD;AACjD;AACA,kBAAkB,OAAO;AACzB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,6BAA6B,4DAAW;AACxC;AACA,2CAA2C,oDAAG;;AAE9C;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,uBAAuB;AACxC;AACA;AACA;;AAEA,kBAAkB,YAAY;AAC9B;AACA,wBAAwB,4CAA4C;AACpE;AACA,4BAA4B,+BAA+B;AAC3D;AACA;AACA;AACA;;AAEA,mBAAmB,uBAAuB;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,uBAAuB;AACtC,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA;;AAEA,UAAU;AACV;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA,wBAAwB,sBAAsB;AAC9C,iDAAiD,cAAc;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;;AAEA,wBAAwB,sBAAsB;AAC9C,iDAAiD,cAAc;AAC/D;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,iBAAiB;AAChC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA,qDAAqD,cAAc;;AAEnE;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,iBAAiB;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA;AACA,qDAAqD,cAAc;;AAEnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,iBAAiB;AAChC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA,wBAAwB,sBAAsB;AAC9C,iDAAiD,cAAc;AAC/D;AACA;AACA;AACA;;AAEA;AACA;AACA,gCAAgC,kEAAkE;;AAElG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+GAA+G,eAAe;AAC9H;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,gBAAgB,qBAAqB,kBAAkB;AACrF;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,wBAAwB,+BAA+B;AACvD;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,qCAAqC,YAAY;;AAEjD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA,6CAA6C,cAAc;AAC3D,wBAAwB,8BAA8B;AACtD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA,MAAM,IAAI;AACV;AACA;AACA,6EAA6E,MAAM;AACnF;AACA;AACA,yFAAyF,mBAAmB;AAC5G;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA,MAAM,IAAI;AACV;AACA;AACA,4EAA4E,MAAM;AAClF;;AAEA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;AC7sBA;AACA;AACA;;AAE+C;AACG;;AAKvB;AAC6C;;AAExE;AACA;AACA;AACO,4BAA4B,uDAAQ;AAC3C;AACA;AACA,eAAe,kBAAkB;AACjC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,gBAAgB,OAAO;AACvB,iBAAiB;AACjB;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB;AACjB;AACA;AACA;;AAEA,8BAA8B,cAAc;;AAE5C;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,wCAAwC;AACvD,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA,wBAAwB,0BAA0B;AAClD;AACA;;AAEA;AACA,wBAAwB,0BAA0B;AAClD;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;;AAEA;AACA;AACA,eAAe,kBAAkB;AACjC,iBAAiB,eAAe;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,UAAU;AACV;;AAEA,UAAU;AACV;AACA,iGAAiG,uCAAuC;AACxI;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,6BAA6B;AAC9C;AACA;AACA;AACA,uBAAuB,oDAAG;;AAE1B;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB;AACjB;AACA;AACA,oCAAoC;AACpC;AACA;AACA;;AAEA;AACA,6BAA6B,sDAAI;;AAEjC;AACA,8BAA8B,wDAAO,YAAY,cAAc;;AAE/D,4BAA4B,0CAA0C;AACtE;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;;AAGA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB;AACjB;AACA;AACA,oCAAoC;AACpC;AACA;AACA;;AAEA;AACA,6BAA6B,sDAAI;;AAEjC;AACA,8BAA8B,wDAAO,YAAY,cAAc;;AAE/D,4BAA4B,0CAA0C;AACtE;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;;;;;;;;;;;;;;;;;;;;AC1MA;AACA;AACA;;AAE+C;;AAE/C;AACA;;AAEA;AACA;AACA;AACO,+BAA+B,uDAAQ;AAC9C;AACA;AACA,eAAe,YAAY;AAC3B;AACA,eAAe,YAAY;AAC3B;AACA;AACA,iBAAiB,WAAW;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACO,mCAAmC,uDAAQ;AAClD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,kBAAkB;AACjC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,0DAA0D;AACzE;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,4BAA4B,oBAAoB;AAChD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA,eAAe,iBAAiB;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,YAAY;AAC3B,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;AC1JA;AACA;AACA;;AAE+C;AACI;AAClB;;AAE1B;AACP;AACA;AACA,eAAe,YAAY;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,qBAAqB,yCAAI;AACzB;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,gDAAgD;AAC/D;AACA;AACA;AACA;AACA;AACA,0BAA0B;AAC1B;AACA,MAAM,IAAI;AACV;AACA;AACA;AACA;AACA;AACA,+BAA+B;;AAE/B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,2BAA2B,2DAAW;AACtC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU,4BAA4B,+DAAe;AACrD;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB;AACA;AACA;AACA;AACA;AACA,qEAAqE,yCAAI;AACzE;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA,eAAe,6CAA6C;AAC5D,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,wBAAwB;AACvC,eAAe,wBAAwB;AACvC,eAAe,wBAAwB;AACvC,eAAe,wBAAwB;AACvC,eAAe,kBAAkB;AACjC,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,QAAQ,yBAAyB;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B;AAC1B,MAAM,IAAI;AACV;AACA;AACA;AACA;AACA,6BAA6B,uCAAuC;AACpE,SAAS;AACT;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA,eAAe,YAAY;AAC3B;AACA;AACA;AACA;AAC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AuB,kEAAkE;AACzF;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA,aAAa;AACb;;AAEA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,wBAAwB;AACnC,WAAW,iDAAiD;AAC5D,aAAa,8BAA8B;AAC3C;AACA;AACA;AACA;AACA;AACA,oBAAoB,0CAA0C;AAC9D,kCAAkC,yEAAsB;AACxD;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,wBAAwB;AACnC,WAAW,iDAAiD;AAC5D,aAAa,8BAA8B;AAC3C;AACA;AACA;AACA;AACA;AACA,iCAAiC,2DAAY;AAC7C;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,wBAAwB;AACrC,YAAY,OAAO;AACnB;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,oDAAM;AACtC;AACA;AACA;AACA;AACA;AACA;AACA,mCAAmC,8DAAW;AAC9C;AACA;AACA;AACA,wFAAwF,yBAAyB;AACjH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,gEAAgE,mBAAmB,IAAI,gBAAgB,4CAA4C,mBAAmB;AACtK;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,iBAAiB;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,yBAAyB;AAC9C;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA,6CAA6C,QAAQ;AACrD;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA,oEAAoE,EAAE;AACtE;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA,YAAY,+DAAY;AACxB,4BAA4B,oDAAM;AAClC,UAAU;AACV;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA,WAAW,cAAc;AACzB,aAAa,QAAQ;AACrB,YAAY,OAAO;AACnB;AACA;AACA;AACA,yBAAyB,oDAAM;AAC/B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,mBAAmB,oDAAM;AACzB;AACA;AACA;AACA,MAAM;AACN;AACA,mBAAmB,oDAAM;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,SAAS;AACpB,aAAa,QAAQ;AACrB;AACA;AACA;AACA,eAAe,oDAAM;AACrB;;AAEA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,0BAA0B;AACvC;AACA;AACA;AACA,UAAU,yEAAyE;AACnF;AACA;AACA,+BAA+B,oDAAI;AACnC;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,iBAAiB;AAC9B;AACA;AACA;AACA;AACA,yBAAyB,oDAAI;;AAE7B;AACA;AACA;AACA;AACA,8DAA8D,mCAAmC;AACjG;AACA;AACA;AACA;AACA,0CAA0C,oDAAM;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,iBAAiB;AAC9B;AACA;AACA;;AAEA;AACA;AACA;;AAEA,YAAY,uCAAuC;;AAEnD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,kBAAkB,oDAAI;AACtB;AACA;;;AAGA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,iBAAiB;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,CAAC;;AAED;AACA;AACA,iDAAiD,WAAW;;AAE5D;AACA;AACA,6DAA6D,cAAc;;AAE3E,eAAe,gCAAgC;AAC/C;AACA;AACA;AACA;AACA,aAAa;;AAEb,UAAU;AACV;AACA,qDAAqD;AACrD;;AAEA,6BAA6B,qDAAG;AAChC,gBAAgB,sDAAI;AACpB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,2CAA2C;AACvD;;AAEA;AACA,oBAAoB,QAAQ;AAC5B;AACA;AACA,wBAAwB,aAAa;AACrC;AACA;AACA;AACA,cAAc,OAAO;AACrB;AACA;AACA;AACA;AACA;;AAEA,2BAA2B,oDAAM;AACjC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,gBAAgB,4BAA4B;;AAE5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,8CAA8C,sDAAI;AAClD;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACO,8BAA8B,uDAAQ;AAC7C;AACA;AACA;AACA;AACA,eAAe,yCAAyC;AACxD,eAAe,qBAAqB;AACpC,eAAe,wBAAwB;AACvC;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,mBAAmB,6CAA6C;AAChE;AACA;;AAEA;AACA;AACA,gBAAgB,oBAAoB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA,eAAe,iDAAiD;AAChE;AACA,iBAAiB,0BAA0B;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B;AAC5B,MAAM,IAAI;;AAEV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA,wCAAwC,mDAAU;;AAElD;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA,iBAAiB;AACjB;;AAEA,UAAU;AACV;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA,iBAAiB;AACjB;;AAEA,UAAU;AACV;AACA;AACA;AACA;AACA,iBAAiB;AACjB;;AAEA,UAAU;AACV;AACA;AACA;AACA;AACA,iBAAiB;AACjB;;AAEA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;;AAEA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA,iBAAiB;AACjB;;AAEA,UAAU,OAAO;AACjB;AACA,gDAAgD,gCAAgC,yEAAyE,iEAAgB,CAAC;AAC1K;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,iBAAiB;AAClC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,iBAAiB;AAClC,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,uBAAuB;AACxC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,kBAAkB;AACjC,iBAAiB,qBAAqB;AACtC;AACA;;AAEA;AACA,4BAA4B,8EAAmB;;AAE/C;AACA,6BAA6B,kFAAuB;AACpD;AACA;AACA;AACA,6BAA6B,2EAAgB;AAC7C;AACA;AACA;AACA,6BAA6B,2EAAgB;AAC7C;;AAEA;AACA;;AAEA;AACA,eAAe,kBAAkB;AACjC,eAAe,QAAQ;AACvB,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,8EAAmB;;AAElD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,gCAAgC,2FAAgC;AAChE;;AAEA;AACA,gCAAgC,uFAA4B;AAC5D;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;;AAEA;AACA,gCAAgC,oFAAyB;AACzD;;AAEA;AACA,gCAAgC,mFAAwB;AACxD;;AAEA;AACA,gCAAgC,4FAAiC;AACjE;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA,gCAAgC,wFAA6B;AAC7D;;AAEA;AACA,gCAAgC,wFAA6B;AAC7D;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,gCAAgC,+FAAoC;AACpE;;AAEA;AACA;AACA;AACA;;;AAGA;AACA;AACA,gCAAgC,gGAAqC;AACrE;;AAEA;AACA;AACA;;AAEA;AACA;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,YAAY;AAC5E,+CAA+C,QAAQ,IAAI,WAAW;AACtE;AACA;AACA,UAAU;AACV;AACA;;AAEA;;AAEA,iBAAiB;AACjB;;AAEA,2DAA2D,kEAAkE;AAC7H;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,qDAAqD;AACzE;AACA;AACA;AACA;AACA,mBAAmB,oDAAI;AACvB;AACA;AACA,cAAc,oBAAoB;;AAElC;AACA;;AAEA,gCAAgC,qDAAG;AACnC;AACA,gBAAgB,2DAAS;AACzB;;AAEA;AACA,iDAAiD,qDAAG;AACpD;AACA,oBAAoB,4DAAU;AAC9B;AACA;;AAEA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA,4EAA4E,0BAA0B,6BAA6B,6BAA6B;AAChK;AACA;AACA,oCAAoC,qDAAG,cAAc,sCAAsC;AAC3F;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,GAAG;AAClB;AACA,gDAAgD,qGAAqG;AACrJ,cAAc,qCAAqC;;AAEnD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,iBAAiB;;AAEjB,cAAc;AACd;AACA;AACA,6EAA6E,YAAY,UAAU,8BAA8B;AACjI;AACA;AACA;AACA,cAAc;AACd;AACA;AACA,iBAAiB;AACjB;AACA,UAAU;AACV;AACA;AACA;AACA,aAAa;AACb;;AAEA;AACA,iDAAiD,2DAAS;;AAE1D,iBAAiB;AACjB;;AAEA;AACA;AACA,eAAe,mEAAmE;AAClF,iBAAiB,6BAA6B;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,KAAK;AACL;;AAEA;AACA;;AAEA;AACA,cAAc,gDAAgD;AAC9D;AACA;AACA,SAAS;;AAET;;AAEA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,eAAe,0BAA0B;AACzC;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb,UAAU;AACV;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,sBAAsB,UAAU;AAChC;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA,wBAAwB,yEAAa;;AAErC;AACA;AACA,mBAAmB,YAAY;AAC/B;AACA;AACA;AACA;AACA,wDAAwD,mBAAmB;;AAE3E;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA,uBAAuB,YAAY;AACnC;AACA,uCAAuC;AACvC;AACA,oCAAoC,2CAA2C;AAC/E;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,aAAa;AACb;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,8BAA8B,oDAAM;;AAEpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,OAAO;AACzB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,kBAAkB,8BAA8B;AAChD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;;AAEA,2BAA2B,8DAAiB;;AAE5C;AACA,yCAAyC,oDAAM;AAC/C;AACA;AACA;;AAEA,yBAAyB,cAAc;AACvC,8BAA8B;AAC9B,8EAA8E,cAAc;AAC5F;AACA;AACA;AACA,wFAAwF,iBAAiB;AACzG;AACA;AACA;AACA;AACA;;AAEA,wBAAwB,WAAW;AACnC,6BAA6B;AAC7B,kEAAkE,WAAW;AAC7E;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,kBAAkB,4DAA4D;AAC9E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACA;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;AACA;AACP;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;AACA;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;AACA;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;AACA;AACA;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;AACA;AACA;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;;AAEP;AACA;AACA;AACO;AACP;;;AAGA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;;;AAGA;AACA;AACO;;AAEA;;AAEP;AACA;AACA;AACO;AACP;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;;AAGO;AACP;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;;;AAGA;AACA;AACO;AACA;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;AACA;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,yBAAyB;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,uCAAuC;AACxD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACO;AACP;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;;;AAGP;AACA;AACA;AACO;;AAEP;AACA,0BAA0B,yBAAyB,gEAAgE,2FAAuB;AAC1I;;AAEA;AACA;AACA,eAAe,yBAAyB;AACxC;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,kCAAkC,4FAAwB;AAC1D,wCAAwC,cAAc;AACtD;;AAEA;AACA;AACA;;AAEA,UAAU;AACV;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,eAAe,sFAAsF;AACrG,iBAAiB,6BAA6B;AAC9C;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AAC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B,kBAAkB;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,wBAAwB,yBAAyB;AACjD;;AAEA;AACA;AACA;AACA;AACA,gBAAgB,qDAAG;AACnB;AACA;AACA;AACA;AACA;;AAEA;AACA,gBAAgB,qDAAG;AACnB;AACA,oBAAoB,sDAAI;AACxB;AACA;AACA;AACA;;AAEA;AACA,2BAA2B,uDAAK;AAChC,4BAA4B,uDAAK;AACjC;AACA;AACA;AACA;;AAEO,mFAAmF;;AAEnF;AACP;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;;AAEP;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA,2BAA2B,qDAAG;AAC9B;AACA;AACA;AACA,4BAA4B,qDAAG;AAC/B,gBAAgB,sDAAI;AACpB;AACA;AACA;AACA;;AAEA,mCAAmC,wDAAwD;AAC3F;AACA;AACA;;AAEA;AACA;AACA;AACA,qDAAqD,WAAW;AAChE;AACA;AACA,uDAAuD,cAAc;AACrE;;AAEA;AACA;AACA,eAAe,gCAAgC;AAC/C;AACA;AACA;AACA;AACA,aAAa;AACb,UAAU;AACV;AACA;;AAEA,iBAAiB;AACjB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA,eAAe,gCAAgC,sCAAsC,wDAAwD;AAC7I;;AAEA;AACA;AACA,kBAAkB,oBAAoB,+BAA+B,+BAA+B;AACpG;AACA;;AAEA;AACA;AACA;AACA;AACA,6DAA6D,8BAA8B;AAC3F;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,oDAAoD;AAChE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,iCAAiC;AACzE;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,iCAAiC;AAC/D;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP,eAAe,iCAAiC;AAChD,4EAA4E;AAC5E;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,6CAA6C;AACzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,iCAAiC;AACzE;AACA;AACA,WAAW,cAAc;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,eAAe,iCAAiC;AAChD,4EAA4E;AAC5E;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP,eAAe,iCAAiC;AAChD,4EAA4E;AAC5E;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,wDAAwD;AACpE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,eAAe;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,eAAe,iCAAiC;AAChD,4EAA4E;AAC5E;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,sDAAsD;AAClE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,yCAAyC;AACnF;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,iCAAiC;AACjE;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,iCAAiC;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,yCAAyC;AACnF;AACA;AACA,WAAW,gBAAgB;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP,eAAe,iCAAiC;AAChD,4EAA4E;AAC5E;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,4CAA4C;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,gBAAgB;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,eAAe,iCAAiC;AAChD,4EAA4E;AAC5E;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEA;AACP;;;AAGA;AACA;AACO;;AAEA;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,sEAAsE;AAClF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,iCAAiC;AAC3E;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,SAAS,gBAAgB,iCAAiC;AACrE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,mBAAmB;AACtC;AACA,4BAA4B,EAAE;AAC9B;AACA;AACA;AACO;AACP;;;AAGA;AACA;AACO;;AAEA;;AAEP;AACA;AACA;AACO;AACP;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;;;AAGA;AACA;AACO;AACA;;AAEA;AACP;;AAEA;AACA;AACO;AACA;;AAEA;AACP;;;AAGA;AACA;AACO;;AAEA;;AAEA;AACP;;;AAGA;AACA;AACO;;AAEA;;AAEA;AACP;;AAEA;AACA;AACO;AACP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;;;AAGA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACO;;AAEA;AACP;;;AAGA;AACA;AACO;AACA;AACA;AACP;;;AAGA;AACA;;AAEA;AACA;AACA;AACO;AACA;;AAEA;AACP;;AAEA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACO;;AAEA;AACP;;AAEA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACO;;AAEA;AACP;;AAEA;AACO;AACA;;AAEA;;;AAGP;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACO;;AAEA;AACP;;;AAGA;AACA;AACO;AACP;AACA;AACA;AACO;;AAEA;AACP;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEA;AACP;;;AAGA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;;AAEA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;AACA;AACP;;;AAGA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;AACA;AACP;;;AAGA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA,YAAY,mDAAmD;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,SAAS;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,cAAc;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACO;AACA;AACA;AACP;;AAEA;AACO;AACA;AACA;AACP;;AAEA;AACA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,iCAAiC;AAClD;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA,kBAAkB,oBAAoB;AACtC;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,kBAAkB,gCAAgC;AAClD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA,kBAAkB,oBAAoB;AACtC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;;AAEP;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACO;AACP;;;AAGA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,0DAA0D;AACtE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;;AAEA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA,YAAY,mEAAmE;AAC/E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,kBAAkB;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;;AAEA;AACO;;AAEP;AACA;AACA;AACO;AACP;;;AAGA;AACO;AACA;AACA;AACA;AACP;;AAEA;AACO;AACA;AACP;;AAEA;AACO;AACA;AACA;AACP;;AAEA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA,YAAY,oEAAoE;AAChF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,kBAAkB;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;;AAEA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,iEAAiE;AAC7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,iEAAiE;AAC7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gDAAgD,SAAS;AACzD;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACO;AACP;;;AAGA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACO;AACA;AACA;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA,kBAAkB,oBAAoB;AACtC;AACA;AACA;AACA;AACA;AACA;;;;;AAKA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,oCAAoC;AAChD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+CAA+C,cAAc;AAC7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU,+DAA+D,GAAG;AAC7F;AACA,iCAAiC,cAAc;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C,cAAc;AAC1D;;AAEA;AACA,iBAAiB,QAAQ;AACzB,kBAAkB,QAAQ;AAC1B;AACA,kBAAkB,QAAQ;AAC1B;AACA,kBAAkB,QAAQ;AAC1B;AACA;AACA;AACA;AACA;AACA,kBAAkB,QAAQ;AAC1B,kBAAkB,QAAQ;AAC1B,kBAAkB,QAAQ;AAC1B;;AAEA;AACA,eAAe,gBAAgB;AAC/B,iBAAiB,iBAAiB;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,4CAA4C,oDAAM;AAClD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,qCAAqC;AACtD;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,kBAAkB,wBAAwB;AAC1C;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;;AAEA;;AAEA;AACP;;AAEA;AACA;AACO;;AAEA;;AAEA;AACP;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,uCAAuC;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEA;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,kEAAkE;AAC9E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,SAAS;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,0EAA0E;AACtF,YAAY,2FAA2F;AACvG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;AACA;AACP;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,uCAAuC;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,uCAAuC;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,mCAAmC;AACpD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,YAAY,uCAAuC;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,wBAAwB;AACzC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,YAAY,kEAAkE;AAC9E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,SAAS;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wBAAwB;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,gCAAgC;AACjD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA,YAAY,iFAAiF;AAC7F;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wFAAwF,eAAe;AACvG,sFAAsF,eAAe;AACrG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,YAAY;AACvB;AACA;AACA,WAAW,WAAW,+DAA+D,SAAS;AAC9F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA,iBAAiB,QAAQ;AACzB,kBAAkB,QAAQ;AAC1B;AACA,kBAAkB,QAAQ;AAC1B,kBAAkB,QAAQ;AAC1B;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,iBAAiB,uBAAuB;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;;AAEV;AACA;AACA;;AAEA,gBAAgB,0CAA0C;;AAE1D;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd,sCAAsC,oDAAM;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,oBAAoB,iBAAiB;AACrC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,4BAA4B,qDAAG;AAC/B,gBAAgB,WAAW,gDAAgD,aAAa;;AAExF;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;;;AAGA;AACA;AACA;AACA;AACA;AACO;;AAEA;;AAEA;AACP;;;AAGA;AACA;AACA;AACA;AACA;AACO;;AAEA;;AAEA;AACP;;;AAGA;AACA;AACA;AACA;AACA;AACO;;AAEA;;AAEA;AACP;;;AAGA;AACA;AACO;;AAEA;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,6CAA6C;AACzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,iCAAiC;AAC3E;AACA;AACA,WAAW,cAAc;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP,eAAe,iCAAiC;AAChD,4EAA4E;AAC5E;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,0DAA0D;AACtE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,eAAe;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,eAAe,iCAAiC;AAChD,4EAA4E;AAC5E;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA,YAAY,2BAA2B;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,WAAW;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,0BAA0B;AAC3C;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;;;AAGA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,kDAAkD;AAC9D;AACA;AACA;AACA;AACA,gCAAgC;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,iEAAiE;AACxE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA,wBAAwB,kBAAkB;AAC1C;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,mBAAmB,oDAAM;AACzB;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA,wBAAwB,2BAA2B;AACnD,4BAA4B,8BAA8B;AAC1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,eAAe,mEAAmE;AAClF,iBAAiB,6BAA6B;AAC9C;AACA;;AAEA;;AAEA;AACA;AACA;AACA,uBAAuB,QAAQ;AAC/B,yBAAyB;;AAEzB,gBAAgB,eAAe,sDAAsD,aAAa;;AAElG;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACO;AACP;AACA,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACO;;AAEP;AACA;AACA;AACA;AACO;;AAEP;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA;AACA;;;AAGA,eAAe,wCAAwC;AACvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B;AAC5B,MAAM,IAAI;;AAEV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,mDAAU;;AAEzC;AACA;AACA;;AAEA;AACA;AACA;AACA,0BAA0B;AAC1B;AACA;AACA;;AAEA;AACA,iDAAiD,0BAA0B;AAC3E;AACA,UAAU;AACV,mDAAmD,0BAA0B;AAC7E;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP,eAAe,uBAAuB;AACtC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEO;AACP;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEO;AACP;AACA;;AAEO;AACP;AACA;;A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AACvB,eAAe,QAAQ;AACvB;AACA,kBAAkB,QAAQ;AAC1B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA,kBAAkB,uBAAuB;AACzC;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;ACxuNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO;AACP;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA,UAAU;AACV;AACA;AACA;;AAEA,yCAAyC,SAAS,sCAAsC,sBAAsB;AAC9G;AACA;AACA;AACA;;;;;;;;;;;;;;;;ACtJ2E;;AAEpE,sCAAsC,gFAAgB;;AAE7D;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA,aAAa,yEAAyE,4CAA4C,2BAA2B;AAC7J;;;;;;;;;;;;;;;;;ACxF6D;AACjB;;AAE5C;AACA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,8DAA8D;AACzE,cAAc,8BAA8B;AAC5C,WAAW,GAAG;AACd;AACA,aAAa,qGAAqG,yBAAyB;AAC3I;AACA;AACA;AACA,0BAA0B,yEAAsB;AAChD;AACA;AACA,sBAAsB,KAAK,qBAAqB,wBAAwB;AACxE;AACA;;AAEA;AACA,wCAAwC,oDAAM;AAC9C,UAAU;AACV,uBAAuB,oDAAM,oBAAoB,QAAQ;AACzD;AACA,KAAK;AACL;;AAEA;AACO;AACP;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACtGA;AACA;AACA;AACA;AACA;AACA,YAAY,WAAW;AACvB;AACA;AACA;AACA,QAAQ,0CAA0C;AAClD;AACA;AACA;AACA;;AAKyB;AA0BJ;AAII;;AAIG;;AAMH;AAKC;AAGA;AAOC;AACiB;;;AAG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ACA,UAAU,2GAA2G;AACrH,UAAU,mGAAmG;AAC7G,UAAU,6GAA6G;AACvH,UAAU,0GAA0G;AACpH,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA,wEAAwE,UAAU;AAClF,SAAS,6GAA6G;AACtH;AACA;AACO,2CAA2C,oEAAoE;;AAEtH;AACA;AACA,eAAe,6BAA6B;AAC5C;AACA;AACA;AACA;;AAEA,eAAe,0BAA0B;AACzC;AACA;AACA,MAAM,IAAI;;AAEV;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA,gBAAgB,SAAS;;AAEzB;;AAEA,mBAAmB,YAAY;AAC/B;AACA,wBAAwB,sBAAsB;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,0BAA0B;AACrE;AACA;;AAEA,iCAAiC,sDAAI,KAAK,oDAAM;AAChD;AACA,gBAAgB,wDAAO;AACvB;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,gEAAgE,2BAA2B;AAC3F;AACA,aAAa;AACb;AACA;AACA;AACA;;;AAGA;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,aAAa,6BAA6B;AAC1C;AACA;AACA,WAAW,iBAAiB;AAC5B,WAAW,yEAAyE;AACpF,aAAa;AACb;AACA,aAAa,gFAAgF;AAC7F;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ,SAAS,0cAA0c;AACnd;AACA;AACO,sDAAsD,+EAA+E;AAC5I,eAAe,kBAAkB;AACjC;;AAEA;AACA;AACA,eAAe,6BAA6B;AAC5C;AACA;AACA;AACA;;AAEA,eAAe,qCAAqC;AACpD,2CAA2C;AAC3C;AACA;AACA;;;AAGA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,UAAU;AACV;AACA;;AAEA,2DAA2D,+BA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;AAC5G;AACA;AACA,WAAW,6BAA6B;AACxC,WAAW,+BAA+B;AAC1C,aAAa,sDAAsD;AACnE;AACA,aAAa,2EAA2E;AACxF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,6FAA6F;AACtG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA,OAAO;AACP;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI;AACJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACO,iDAAiD,0EAA0E;;AAElI;AACA;AACA,eAAe,6BAA6B;AAC5C;AACA;AACA;AACA;;AAEA,eAAe,gCAAgC;AAC/C,2CAA2C;AAC3C;AACA;;AAEA;AACA,mBAAmB,UAAU;AAC7B;AACA;AACA;AACA,UAAU;AACV;AACA,gCAAgC,UAAU;AAC1C,UAAU;AACV;AACA,oCAAoC,MAAM;AAC1C,cAAc;AACd;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA,gCAAgC,UAAU,cAAc,QAAQ;AAChE;AACA;AACA;AACA,iBAAiB;AACjB;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,SAAS;;AAET,0CAA0C,QAAQ;AAClD;AACA;AACA,SAAS;;AAET;AACA;AACA,SAAS;;AAET;AACA;AACA;AACA;AACA,aAAa;AACb;;AAEA,mBAAmB,wBAAwB;AAC3C,sCAAsC,sBAAsB;AAC5D,wBAAwB,oBAAoB;AAC5C;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,QAAQ;AAChD,0BAA0B,wCAAwC;AAClE;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;;AAEA;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,cAAc,UAAU;AACxB,cAAc,UAAU;AACxB;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ,wCAAwC;AAC9D,yFAAyF;AACzF,cAAc,SAAS;AACvB;AACA;AACA;AACA;AACA;AACA,WAAW,iBAAiB;AAC5B,WAAW,iBAAiB;AAC5B;AACA,WAAW,uCAAuC;AAClD,aAAa,sEAAsE;AACnF;AACA,aAAa,mFAAmF;AAChG;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,mBAAmB;AACtE;AACA;AACA;AACA;AACA;AACA;AACA;AACO,yDAAyD,kFAAkF;AAClJ;AACA;AACA,eAAe,6BAA6B;AAC5C;AACA;AACA;;AAEA;AACA;AACA,uCAAuC,KAAK;AAC5C;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA,eAAe,wCAAwC;AACvD;AACA,iDAAiD;AACjD;AACA,MAAM,IAAI;;AAEV;AACA;AACA,gCAAgC,QAAQ;AACxC;AACA;AACA;AACA;;AAEA;AACA;AACA,gDAAgD;AAChD;;AAEA;AACA;AACA;AACA;;AAEA,mBAAmB,gCAAgC;AACnD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;;AAEA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;;AAEA,uBAAuB,UAAU;AACjC;AACA,0CAA0C,wDAAO;AACjD,kBAAkB,wDAAO;;AAEzB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;;AAEA;AACA,aAAa,QAAQ;AACrB,cAAc,qBAAqB;AACnC,cAAc,SAAS;AACvB,cAAc,SAAS;AACvB,cAAc,oBAAoB;AAClC;AACA;AACA,WAAW,iBAAiB;AAC5B,WAAW,kCAAkC;AAC7C,aAAa,iBAAiB;AAC9B;AACA,aAAa,8EAA8E;AAC3F;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,wFAAwF,qBAAqB;AAC7G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wFAAwF,qBAAqB;AAC7G,8DAA8D,kCAAkC;AAChG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8DAA8D,kCAAkC;AAChG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8DAA8D,sDAAsD;AACpH;AACA;AACA;AACA;AACA;AACA;AACA;AACO,oDAAoD,6EAA6E;AACxI;AACA;AACA,eAAe,6BAA6B;AAC5C;AACA;AACA;AACA;;AAEA,eAAe,mCAAmC;AAClD;AACA,6BAA6B,QAAQ;AACrC;AACA;AACA,+BAA+B,UAAU;AACzC,MAAM,IAAI;;AAEV;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;;AAEA;AACA;AACA;AACA;;AAEA,mBAAmB,QAAQ;AAC3B;AACA;AACA;AACA,UAAU;AACV,qBAAqB,8DAAY;AACjC,UAAU;AACV;AACA,UAAU;AACV,2CAA2C,QAAQ;AACnD;;AAEA;AACA;AACA;;AAEA;AACA,qBAAqB,qEAAmB;AACxC;;AAEA;AACA;AACA;;;AAGA;AACA,aAAa,QAAQ;AACrB,cAAc,SAAS;AACvB;AACA;AACA,WAAW,qBAAqB;AAChC,WAAW,uCAAuC;AAClD,aAAa,iBAAiB;AAC9B;AACA,aAAa,oFAAoF;AACjG;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,yDAAyD,mFAAmF;AACnJ;AACA;AACA,eAAe,8BAA8B;AAC7C;AACA;AACA;AACA;;AAEA,eAAe,wCAAwC;AACvD;AACA;AACA,MAAM,IAAI;;AAEV;AACA,gBAAgB,eAAe;AAC/B,2CAA2C,cAAc;;AAEzD,mBAAmB,QAAQ;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Z;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,wCAAwC;AACnF,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,uCAAuC;AAClF,QAAQ;AACR;AACA;AACA;AACA;AACA;AACA;AACA,2CAA2C,wCAAwC;AACnF,QAAQ;AACR;AACA;AACO,6DAA6D,2FAA2F;;AAE/J;AACA;AACA,eAAe,kCAAkC;AACjD;AACA;AACA;AACA;;AAEA,eAAe,4CAA4C;AAC3D,kCAAkC;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mGAAmG,6BAA6B;AAChI;AACA;;AAEA;AACA,cAAc;AACd;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,gCAAgC,YAAY;AAC5C;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,mCAAmC,oDAAG;AACtC;AACA;AACA,4BAA4B,2BAA2B;AACvD;AACA;AACA;;AAEA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,oCAAoC;;AAEpC;AACA;AACA,4DAA4D;AAC5D;;AAEA;AACA;AACA,gCAAgC,YAAY;AAC5C;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,wBAAwB,2GAA2G,IAAI;AACvI;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;;AAEA,cAAc;AACd;AACA;AACA;AACA;AACA,iBAAiB;AACjB;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,iBAAiB;;AAEjB;AACA;AACA;AACA;AACA,oCAAoC,QAAQ,SAAS,sDAAK;AAC1D;;AAEA,kBAAkB;AAClB,+CAA+C,QAAQ;AACvD;;AAEA;AAC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C;AAC9C;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,cAAc,SAAS;AACvB;AACA;AACA,WAAW,qBAAqB;AAChC,WAAW,gCAAgC;AAC3C,aAAa,wEAAwE;AACrF;AACA,aAAa,6EAA6E;AAC1F;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,gBAAgB;AACxD;AACA;AACA;AACA,eAAe;AACf,OAAO;AACP;AACA;AACA;AACA;AACA,eAAe;AACf,OAAO;AACP;AACA;AACO,kDAAkD,4EAA4E;;AAErI;AACA;AACA,eAAe,8BAA8B;AAC7C;AACA;AACA;AACA;;AAEA,eAAe,iCAAiC;AAChD;AACA;AACA;AACA,MAAM,IAAI;;AAEV;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA,gBAAgB,2BAA2B;AAC3C,0CAA0C,0BAA0B;;AAEpE;AACA;;AAEA;AACA;;AAEA;AACA,mBAAmB,iCAAiC;AACpD;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;;AAEA;AACA;AACA;;;AAGA;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,cAAc,QAAQ;AACtB,cAAc,aAAa;AAC3B;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,cAAc,QAAQ;AACtB;AACA;AACA,cAAc,SAAS;AACvB;AACA;AACA,WAAW,qBAAqB;AAChC,WAAW,UAAU;AACrB,WAAW,wCAAwC;AACnD,aAAa,4EAA4E;AACzF;AACA,aAAa,yFAAyF;AACtG;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB,SAAS;AACT;AACA;AACA;AACA,iBAAiB;AACjB,SAAS;AACT;AACA;AACA;AACA,iBAAiB;AACjB,SAAS;AACT;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0DAA0D,2BAA2B;AACrF;AACA;AACA;AACA;AACA,iBAAiB;AACjB,SAAS;AACT;AACA;AACA;AACA,iBAAiB;AACjB,SAAS;AACT;AACA;AACA;AACA,iBAAiB;AACjB,SAAS;AACT;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACO,0DAA0D,wFAAwF;;AAEzJ;AACA;AACA,eAAe,kCAAkC;AACjD;AACA;AACA;AACA;;AAEA,eAAe,yCAAyC;AACxD;AACA;AACA;AACA;AACA,MAAM,IAAI;;AAEV;AACA;;AAEA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;;AAEA;AACA;AACA;AACA;AACA,wBAAwB,2BAA2B;AACnD;AACA;AACA;;AAEA;AACA,8CAA8C,8BAA8B;;AAE5E;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,aAAa,mCAAmC;AAChD;AACA;AACA,WAAW,YAAY;AACvB,WAAW,QAAQ;AACnB,WAAW,yEAAyE;AACpF,aAAa,4EAA4E;AACzF;AACA,aAAa,2FAA2F;AACxG;;AAEA;AACA;AACA,mFAAmF;AACnF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,kBAAkB;AAC3B;AACA;AACO,4DAA4D,0FAA0F;;AAE7J;AACA;AACA,eAAe,kCAAkC;AACjD;AACA;AACA;AACA;;AAEA,eAAe,2CAA2C;AAC1D,qDAAqD;AACrD,sFAAsF;;AAEtF;;AAEA;AACA;AACA,gBAAgB,eAAe;;AAE/B;AACA,qDAAqD,SAAS;AAC9D;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA,+DAA+D,QAAQ;;AAEvE;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,QAAQ;AAC1B;AACA;;;AAGA;AACA,aAAa,QAAQ;AACrB,cAAc,iBAAiB;AAC/B,aAAa,mDAAmD;AAChE;;AAEA;AACA,aAAa,QAAQ;AACrB,cAAc,cAAc;AAC5B,cAAc,QAAQ;AACtB;AACA,aAAa,QAAQ;AACrB,cAAc,gCAAgC;AAC9C;AACA;AACA,WAAW,iBAAiB;AAC5B,WAAW,4BAA4B;AACvC,aAAa,4BAA4B;AACzC;AACA,aAAa,+EAA+E;AAC5F;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,iFAAiF,kBAAkB;AACnG;AACA,4DAA4D,oBAAoB;AAChF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,8CAA8C,8EAA8E;AACnI;;AAEA;AACA;AACA,eAAe,oCAAoC;AACnD;AACA;AACA;;AAEA;AACA;AACA;;;AAGA,eAAe,6BAA6B;AAC5C;AACA;AACA,MAAM,IAAI;;AAEV;AACA;AACA,iEAAiE,oBAAoB;AACrF,UAAU;AACV;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA,gBAAgB,WAAW;;AAE3B;AACA;AACA;AACA;AACA;AACA;;AAEA,mDAAmD,oBAAoB;;AAEvE;AACA;AACA;AACA,iCAAiC,iDAAS,4CAA4C,eAAe;AACrG;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,qCAAqC,oDAAM;AAC3C;AACA;AACA;AACA;AACA,UAAU,yCAAyC,oDAAM;AACzD;AACA;;AAEA;AACA,gBAAgB,YAAY;AAC5B;AACA;AACA,SAAS;;AAET;AACA;AACA,gBAAgB,WAAW,oEAAoE,uBAAuB;;AAEtH;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,qBAAqB;AAChC,aAAa,8BAA8B;AAC3C;AACA,aAAa,0EAA0E;AACvF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,+CAA+C,yEAAyE;AAC/H;AACA;AACA,eAAe,8BAA8B;AAC7C;AACA;AACA;AACA;;AAEA,eAAe,8BAA8B;AAC7C;;AAEA;AACA;AACA;;AAEA,mBAAmB,YAAY;AAC/B;AACA;AACA;AACA,0BAA0B,qDAAQ;AAClC;;AAEA;AACA;AACA;;AAEA;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,cAAc,UAAU;AACxB;AACA;AACA,WAAW,qBAAqB;AAChC,aAAa,wEAAwE;AACrF;AACA,aAAa,6EAA6E;AAC1F;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,kDAAkD,4EAA4E;AACrI;AACA;AACA,eAAe,8BAA8B;AAC7C;AACA;AACA;AACA;;AAEA,eAAe,iCAAiC;AAChD;;AAEA;;AAEA;AACA,gBAAgB,kBAAkB;;AAElC;AACA,wBAAwB,2BAA2B;AACnD,+BAA+B,6DAAW;AAC1C,oDAAoD,oDAAG;AACvD;AACA;AACA,uBAAuB,qDAAQ;AAC/B,aAAa;AACb;;AAEA;AACA;AACA;;AAEA;AACA;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,0EAAkC;AACnD;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,uEAA+B;AAChD;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,qEAA6B;AAC9C;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;;AAEL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,4DAAoB;AACrC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,6DAAqB;AACtC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,6DAAqB;AACtC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,6DAAqB;AACtC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,4DAAoB;AACrC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,0EAAkC;AACnD;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA;AACA,iBAAiB,uEAA+B;AAChD,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,iDAAS;AAC1B,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,kBAAkB,iEAAyB,EAAE,uDAAe;AAC5D,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,kBAAkB,kEAA0B,EAAE,qEAA6B;AAC3E,sBAAsB,yDAAa;AACnC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,8DAAsB;AACvC,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;;AAEL;AACA;AACA;AACA,iBAAiB,uEAA+B;AAChD,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;;AAEL;AACA;AACA;AACA,kBAAkB,qEAA6B,EAAE,wEAAgC,EAAE,yEAAiC;AACpH,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;;AAEL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,iDAAS;AAC1B,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;;AAEL;AACA;AACA;AACA,iBAAiB,mEAA2B;AAC5C,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,2EAAmC;AACpD,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,6EAAqC;AACtD,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA;AACA;AACA,iBAAiB,gEAAwB;AACzC,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA;AACA;AACA,iBAAiB,mEAA2B;AAC5C,qBAAqB,yDAAa;AAClC;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;;AAEL;AACA;AACA,qBAAqB,yDAAa;AAClC;AACA,iBAAiB,iDAAS;AAC1B;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL;AACA,qBAAqB,yDAAa;AAClC;AACA,kBAAkB,0EAAkC,EAAE,iDAAS;AAC/D;AACA;AACA;AACA;AACA,SAAS;AACT;AACA,KAAK;AACL,CAAC;;;AAGD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,CAAC;;AAED;AACA,aAAa,8BAA8B;AAC3C,aAAa,2BAA2B;AACxC,aAAa,sBAAsB;AACnC,cAAc,uEAAuE;AACrF,cAAc,sFAAsF;AACpG,aAAa,6BAA6B;AAC1C;;AAEA;AACA;AACA;AACA,cAAc,cAAc;AAC5B,WAAW,GAAG;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,iDAAiD;AAC5D,aAAa,sBAAsB;AACnC,YAAY,OAAO;AACnB;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B;AAC5B,MAAM;AACN;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,6CAA6C,KAAK,oBAAoB,6BAA6B;AACnG;;AAEA;AACA;AACA;AACA,iEAAiE,MAAM;AACvE;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,IAAI,gEAAgB;AACpB;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;;;AAGA;AACA;AACA,WAAW,kBAAkB;AAC7B,WAAW,QAAQ;AACnB,WAAW,4CAA4C;AACvD;AACA;AACA;;AAEA;;AAEA,cAAc,WAAW;AACzB;AACA;AACA;;AAEA,kBAAkB,SAAS;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA;AACA;AACA;AACA,0BAA0B;AAC1B;AACA,0BAA0B;AAC1B;AACA;AACA;;AAEA;AACA;AACA;AACA,aAAa;AACb,UAAU;AACV;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC5wGA;AACA;AACA;AACA;AACA;AACA,YAAY,4BAA4B;AACxC;AACA;AACA;AACA,SAAS,iBAAiB;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAG4B;;AAKH;;AAID;;AAOE;;;AAGgE;;AAE9C;AAKlB;;;AAG1B;;AAEA;AACA;AACA;AACA,WAAW,UAAU;AACrB,aAAa,UAAU;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,oBAAoB;AAC/B,WAAW,SAAS;AACpB,YAAY,UAAU;AACtB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,oBAAoB,gBAAgB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,wBAAwB,eAAe;AACvC;;AAEA;AACA;AACA;AACA;AACA;AACA,gCAAgC,kBAAkB;AAClD;AACA;AACA;AACA;;AAEA,cAAc;AACd;AACA,+BAA+B,oDAAG;;AAElC;AACA;AACA;AACA;AACA;AACA,wBAAwB,wDAAO;;AAE/B;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA,2BAA2B,UAAU;AACrC;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA,WAAW,GAAG;AACd,WAAW,oBAAoB;AAC/B;AACA,cAAc,sBAAsB,iBAAiB,IAAI;AACzD;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,oBAAoB,gBAAgB;AACpC;;AAEA;;AAEA;AACA;AACA;AACA,mBAAmB,6DAAW;AAC9B;AACA;;AAEA,iCAAiC,oDAAM;AACvC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,wBAAwB,kBAAkB;AAC1C;AACA,4BAA4B,gBAAgB;AAC5C;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,wBAAwB,8BAA8B;AACtD;AACA;AACA;AACA,mBAAmB,UAAU;AAC7B;;AAEA,wBAAwB,sBAAsB;AAC9C;AACA;AACA;;;AAGA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,gCAAgC;AAC7C;AACA;AACA;;AAEA;AACA;AACA;;AAEA,oBAAoB,0BAA0B;AAC9C;AACA;;AAEA,2BAA2B,oDAAG;AAC9B;AACA;AACA;AACA;;AAEA,uBAAuB,wDAAO;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,WAAW,YAAY;AACvB,WAAW,UAAU;AACrB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,qBAAqB;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA,oBAAoB,wBAAwB;AAC5C;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,UAAU;AACrB,WAAW,UAAU;AACrB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,aAAa;AACxB,WAAW,UAAU;AACrB,aAAa,gBAAgB,4CAA4C,IAAI;AAC7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,6BAA6B,oDAAM;AACnC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,wBAAwB,uBAAuB;AAC/C,4BAA4B,6DAAW;AACvC;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA,oBAAoB,uBAAuB;AAC3C;;AAEA;;AAEA,wBAAwB,8BAA8B;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,oBAAoB,wBAAwB;AAC5C;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;;;AAGA;AACA;AACA;AACA;;AAEA;AAC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vB,eAAe,wBAAwB;AACvC,eAAe,SAAS;AACxB,eAAe,QAAQ;AACvB,iBAAiB,0BAA0B;AAC3C;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;AACV;;AAEA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,gCAAgC,4BAA4B;AAC5D;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;;AAEA;AACA,4BAA4B,iBAAiB;AAC7C;AACA;AACA,gCAAgC,gBAAgB;AAChD;AACA;AACA,oCAAoC,mBAAmB;AACvD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gCAAgC,uBAAuB;AACvD;AACA,8BAA8B,sEAAsB;;AAEpD,oCAAoC,sBAAsB;AAC1D,yEAAyE;AACzE;AACA,uCAAuC,sEAAsB;;AAE7D;AACA,wCAAwC,mBAAmB;AAC3D;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,cAAc;AAC7B,iBAAiB;AACjB;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,UAAU;AACzB,eAAe,KAAK;AACpB,iBAAiB,kBAAkB;AACnC;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA,oBAAoB,gBAAgB;AACpC;AACA;AACA;AACA;AACA;AACA;;AAEA,UAAU;AACV;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,UAAU;AACV;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA,UAAU;AACV;AACA,UAAU;AACV,yGAAyG,qBAAqB;AAC9H;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,mBAAmB;AACpC;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;;AAEA;AACA,iBAAiB,QAAQ;AACzB,kBAAkB,aAAa;AAC/B,kBAAkB,aAAa;AAC/B,kBAAkB,QAAQ;AAC1B;;AAEA;AACA;AACA;AACA,eAAe,UAAU;AACzB,eAAe,QAAQ;AACvB,iBAAiB,4BAA4B;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;AACV;AACA;AACA;AACA;AACA;;AAEA,kDAAkD;;AAElD;AACA;AACA;AACA,UAAU;AACV;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;;AAEA,mBAAmB,aAAa;AAChC;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,qFAAqF,kBAAkB,uBAAuB,iBAAiB,oDAAoD,eAAe;AAClN;;AAEA,4BAA4B,sBAAsB;AAClD,gCAAgC,oBAAoB;AACpD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,+CAA+C;AAC/C,cAAc;AACd;AACA,4EAA4E,0CAA0C;AACtH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,4BAA4B,sBAAsB;AAClD;AACA;AACA;AACA;AACA;;AAEA,iCAAiC,oDAAM;AACvC,+BAA+B;;AAE/B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,sCAAsC;AACvD;AACA;AACA;AACA;AACA;AACA,mBAAmB,qBAAqB;AACxC;;AAEA;AACA,6BAA6B,uDAAK;;AAElC;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEO;AACP,eAAe,2CAA2C;AAC1D;AACA;AACA;AACA;AACO;AACP,eAAe,2CAA2C;AAC1D;AACA;AACA;AACA;AACO;AACA;AACA,wDAAwD;AACxD;AACA;AACA;AACA,0DAA0D;AAC1D;AACA;AACA;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,aAAa;;AAEb;AACA;AACA,aAAa;;AAEb;AACA;AACA,UAAU;AACV;AACA;AACA;AACA,aAAa;AACb;;AAEA;AACA;AACA;AACO,mEAAmE;AACnE;AACA;;AAEA;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;AACA;AACA;AACA;;AAEA;AACA,oEAAoE;AACpE;AACP,eAAe,sCAAsC;AACrD;AACA;AACA;AACA;AACO,6DAA6D;;AAE7D;AACP,eAAe,sCAAsC;AACrD;AACA;AACA;AACA;;AAEO;AACA;AACA;AACP,uDAAuD;AACvD;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACO,6DAA6D;;AAEpE;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,aAAa,+DAA+D;AAC5E;;AAEA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,YAAY;AAC3B,iBAAiB,qCAAqC;AACtD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,2BAA2B,sDAAI;;AAE/B,iBAAiB;AACjB;;AAEA,eAAe,sCAAsC;AACrD;AACA;AACA;;AAEA,eAAe,2CAA2C;AAC1D;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEO;;AAEP,eAAe,2CAA2C;AAC1D;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;;AAGO;AACP,eAAe,sCAAsC;AACrD;AACA;AACA;AACA;;AAEA;AACA,aAAa,QAAQ;AACrB,cA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QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,mBAAmB;AACpC;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;AACV;;AAEA;;AAEA;;AAEA,mBAAmB,kBAAkB;AACrC;;AAEA,wBAAwB,2BAA2B;AACnD;AACA;;AAEA;AACA,2CAA2C,gEAAc;AACzD;AACA,kBAAkB;AAClB;;AAEA;AACA;;AAEA;AACA,uCAAuC,gEAAc;AACrD;AACA,kBAAkB;AAClB;;AAEA;AACA;AACA;AACA,gCAAgC,iBAAiB;AACjD;AACA;AACA;AACA;AACA,wCAAwC,oDAAM;AAC9C;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,eAAe,QAAQ;AACvB;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;AACV;AACA,oBAAoB;AACpB;AACA;;AAEO;AACP,uDAAuD;AACvD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;AAEO;AACP;AACA;AACA;AACA,eAAe,YAAY;AAC3B,eAAe,YAAY;AAC3B,iBAAiB,sCAAsC;AACvD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,SAAS;;;AAGT;AACA,6BAA6B,uDAAK;AAClC;AACA,sBAAsB,qDAAG;AACzB;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEO;;AAEP;AACA;;AAEA;AACA,oCAAoC,gEAAe;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,sBAAsB,gEAAe;AACrC;;AAEA;AACA;AACA,eAAe,2BAA2B;AAC1C,iBAAiB,iBAAiB;AAClC;AACA;AACA,+BAA+B,4DAAW;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,yBAAyB,oDAAG;;AAE5B,wBAAwB,iBAAiB;AACzC;AACA;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,2BAA2B;AAC1C,iBAAiB,UAAU,wBAAwB,GAAG;AACtD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEO;;AAEP;AACA,eAAe,cAAc;AAC7B,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,2BAA2B;AAC1C,iBAAiB,UAAU,sBAAsB,wBAAwB,GAAG;AAC5E;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,8BAA8B,oDAAM;AACpC,gCAAgC,oDAAM;AACtC;AACA;AACA;;AAEO;;AAEP;AACA;;AAEA;AACA,4BAA4B,gEAAe;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,wBAAwB,wBAAwB;AAChD;AACA;AACA;;AAEA,sBAAsB,gEAAe;AACrC;AACA,SAAS;AACT;;AAEA;AACA;AACA,eAAe,2BAA2B;AAC1C,eAAe,QAAQ;AACvB,iBAAiB,iBAAiB;AAClC;AACA;AACA;;AAEA;AACA;AACA,4CAA4C,QAAQ;;AAEpD,eAAe,4DAAW;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,2BAA2B;AAC1C,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,iBAAiB,UAAU,iDAAiD,GAAG;AAC/E;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;AACV;;AAEA;;AAEA;AACA;AACA;AACA,4BAA4B,kBAAkB;AAC9C;AACA,gCAAgC,kBAAkB;AAClD;AACA;;AAEA;;AAEA;AACA,gCAAgC,kBAAkB;AAClD;AACA;AACA,8CAA8C;;AAE9C;AACA,gCAAgC,kBAAkB;AAClD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,oCAAoC,cAAc;;AAElD;AACA;AACA;AACA;AACA;;AAEA;AACA,+BAA+B,oDAAM;AACrC;AACA;AACA;AACA;;AAEA;AACA,gDAAgD,oDAAM;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,qDAAqD,WAAW,sCAAsC,OAAO;AAC7G;;AAEA;AACA;AACA;AACA;AACA;;AAEA,yBAAyB;;AAEzB;AACA;;AAEA;;AAEA;AACA;AACA,uCAAuC,gBAAgB;AACvD;AACA;AACA,cAAc;AACd;AACA;AACA,wCAAwC,oDAAM;AAC9C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEO;;;AAGP;AACA;;AAEA;AACA,4BAA4B,gEAAe;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,wBAAwB,wBAAwB;AAChD;AACA;AACA;;AAEA,sBAAsB,gEAAe;AACrC;AACA,SAAS;;AAET;AACA;AACA;;AAEA;AACA;AACA,eAAe,2BAA2B;AAC1C,eAAe,QAAQ;AACvB,iBAAiB,iBAAiB;AAClC;AACA;AACA;AACA,eAAe,4DAAW;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA,eAAe,2BAA2B;AAC1C,iBAAiB,UAAU,sBAAsB,GAAG;AACpD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,4BAA4B,0BAA0B;AACtD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEO;;AAEP;AACA;;AAEA,2BAA2B,gEAAe;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,kCAAkC,gEAAe;AACjD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,sBAAsB,gEAAe;;AAErC;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,2BAA2B;AAC1C,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,iBAAiB;AAClC;AACA;AACA;;AAEA,mBAAmB,QAAQ;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,cAAc;AACd;AACA,wDAAwD,WAAW;AACnE;AACA,UAAU;AACV;AACA,2DAA2D;AAC3D;;AAEA;AACA,kDAAkD,gBAAgB;AAClE;AACA;AACA,kBAAkB;AAClB,kDAAkD,WAAW;AAC7D;AACA;AACA;AACA;AACA;;AAEA;AACA,wDAAwD,WAAW;AACnE;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,2BAA2B;AAC1C,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,iBAAiB,iBAAiB;AAClC;AACA;AACA;AACA,eAAe,4DAAW;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA,eAAe,2BAA2B;AAC1C,iBAAiB,UAAU,wBAAwB,GAAG;AACtD;AACA;AACA;AACA,MAAM,IAAI;AACV;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;;AAGO;AACP;AACA;AACA,eAAe,2BAA2B;AAC1C,iBAAiB,UAAU,uBAAuB,GAAG;AACrD;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,8BAA8B,oDAAM;AACpC;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,cAAc,4DAA4D,IAAI;AAC/F;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,4BAA4B,mBAAmB;AAC/C,sCAAsC,wDAAO;AAC7C,oCAAoC,oDAAG;AACvC;;AAEA;AACA;AACA;AACA,gDAAgD,uBAAuB;AACvE,kBAAkB;AAClB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,mBAAmB,uBAAuB;AAC1C;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;;AAEA;;AAEO;;AAEP;AACA;;AAEA;AACA,4BAA4B,gEAAe;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,wBAAwB,wBAAwB;AAChD;AACA;AACA;;AAEA,sBAAsB,gEAAe;AACrC;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA,eAAe,2BAA2B;AAC1C,iBAAiB,iBAAiB;AAClC;AACA;AACA;AACA;AACA,4CAA4C,QAAQ;;AAEpD,eAAe,4DAAW;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA,eAAe,2BAA2B;AAC1C,iBAAiB,UAAU,wBAAwB,GAAG;AACtD;AACA;AACA;;AAEA;;AAEA;AACA;AACA,wCAAwC,cAAc;AACtD,4CAA4C,cAAc;AAC1D;;AAEA,4BAA4B,gBAAgB;AAC5C;AACA;AACA,gCAAgC,gBAAgB;AAChD;AACA,oCAAoC,kBAAkB;AACtD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEO;;AAEP;AACA;AACA;AACA;AACO,wBAAwB,uDAAQ;AACvC;AACA;AACA,eAAe,kBAAkB;AACjC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,KAAK;AACpB,eAAe,QAAQ;AACvB,iBAAiB,cAAc;AAC/B;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,KAAK;AACpB,iBAAiB,cAAc;AAC/B;AACA;AACA;AACA;AACA;;;AAGO;AACP;AACA;AACA,eAAe,KAAK;AACpB,iBAAiB,cAAc;AAC/B;AACA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA,eAAe,KAAK;AACpB,iBAAiB,cAAc;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEO;AACP;AACA;AACA,eAAe,KAAK;AACpB,iBAAiB,cAAc;AAC/B;AACA;AACA;AACA;AACA;;AAEO;;AAEA;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA,UAAU;;AAEV,mBAAmB,qBAAqB;AACxC,+GAA+G;;AAE/G,mBAAmB,qBAAqB;AACxC,mGAAmG;;AAEnG,mBAAmB,qBAAqB;AACxC,2FAA2F;;AAE3F;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,iBAAiB;AAChC,iBAAiB;AACjB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,yDAAyD,MAAM;AAC/D;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,kBAAkB;AACjC;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iCAAiC;AACjC;;AAEA;AACA,yCAAyC,KAAK,cAAc,iCAAiC;AAC7F;;AAEA,iBAAiB;AACjB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA,eAAe,4CAA4C;AAC3D;AACA,iBAAiB,oBAAoB;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;;AAEV,iDAAiD,2DAAY;AAC7D;AACA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,wDAAwD,IAAI;AAC5D;AACA,cAAc;AACd,mEAAmE,IAAI;AACvE;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC1lFA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,gBAAgB;AAC5B;AACA;AACA,WAAW,YAAY;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAG4B;;AAQH;;AAID;;AAE2B;AACR;;AAMP;;AAEU;;AAKF;AACY;;AAExD;AACA,aAAa,QAAQ;AACrB,cAAc,SAAS;AACvB,aAAa,kEAAkE;AAC/E;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,4BAA4B;AACvC,aAAa,gBAAgB;AAC7B;AACA;;AAEA;AACA,QAAQ,2DAAY;AACpB,QAAQ,2DAAY;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,UAAU;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,SAAS;AACpB,aAAa,aAAa;AAC1B;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,+DAA+D;;AAE/D;AACA;AACA;AACA;;AAEA;;AAEA,MAAM;AACN,wBAAwB,4DAAY;AACpC;AACA,iDAAiD,QAAQ;;AAEzD,MAAM;AACN;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,kBAAkB;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,UAAU;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2EAA2E,YAAY;AACvF;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACA;AACA,4BAA4B,EAAE;AAC9B;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,eAAe;AAC1B,aAAa,SAAS;AACtB;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,kBAAkB;AAC7B,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,UAAU;AACvB;AACA;AACA;AACA;;AAEA,+BAA+B,EAAE;AACjC,+CAA+C,kBAAkB;AACjE;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,kBAAkB,kBAAkB,iBAAiB,kBAAkB;AACvE;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACO,6BAA6B,uDAAQ;AAC5C;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;;AAEA,mBAAmB,UAAU;AAC7B;;AAEA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA;;AAEA,mBAAmB,SAAS;AAC5B;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,MAAM;AACrB,iBAAiB,gBAAgB;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA;AACA;AACA;AACA,gEAAgE,YAAY;AAC5E;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,mBAAmB;AAClC,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,QAAQ;AACvB;AACA;AACA;;AAEA;AACA;AACA;AACA,wBAAwB,eAAe;AACvC;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,8BAA8B;;AAE9B,oEAAoE;AACpE;;AAEA;AACA;;AAEA,wBAAwB,oDAAG;;AAE3B;AACA;;AAEA,wBAAwB,+DAAQ;AAChC;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,cAAc;AAC7B;AACA;AACA;AACA;AAC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C3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,8BAA8B,oEAAa;;AAE3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,4BAA4B,iBAAiB;AAC7C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,8CAA8C;;AAE9C;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,sBAAsB;AACtB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,iDAAiD,sBAAsB;AACvE;AACA;AACA,UAAU;AACV;AACA;;AAEA;AACA;AACA;AACA,4BAA4B,uBAAuB;AACnD;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;;AAGA;AACA;AACA,eAAe,eAAe;AAC9B,eAAe,SAAS;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,kBAAkB;AAClB;AACA,wCAAwC,8CAA8C;AACtF;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;;AAEA,kBAAkB,qBAAqB;AACvC;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA,yBAAyB,uDAAQ;AACjC;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,YAAY;AAC7B,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4DAA4D,YAAY;AACxE;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;;AAEA;AACA,kBAAkB,2BAA2B;AAC7C,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa,QAAQ;AACrB,aAAa,UAAU;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc,QAAQ;AACtB,gBAAgB,QAAQ;AACxB;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA,wBAAwB,iBAAiB;AACzC;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA,iDAAiD,GAAG;AACpD;;;AAGA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,SAAS;AAC1B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,GAAG;AACpD;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qCAAqC;AACrC;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,UAAU;AACV;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,2BAA2B,uDAAQ;AACnC;AACA;AACA;AACA;AACA,aAAa,QAAQ;AACrB,eAAe,cAAc;AAC7B,cAAc,OAAO;AACrB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8DAA8D,YAAY;AAC1E;AACA;;AAEA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,iBAAiB;AAChC,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,kBAAkB,gCAAgC;AAClD,eAAe,iBAAiB;AAChC,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA,mFAAmF,GAAG;AACtF,0CAA0C,kBAAkB,MAAM,kBAAkB;AACpF;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;;AAEA;AACA,kBAAkB,SAAS;AAC3B;AACA;AACA;;AAEA;AACA,kBAAkB,SAAS;AAC3B;AACA;AACA;AACA;;AAEA;AACA,kBAAkB,SAAS;AAC3B;AACA;AACA;AACA,qDAAqD,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,EAAE;;AAElF;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA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A;AACA;;AAEA;AACA;AACA;AACA,+DAA+D,YAAY;AAC3E;AACA;;AAEA;AACA;AACA;AACA,eAAe,OAAO;AACtB,eAAe,MAAM;AACrB,iBAAiB,qBAAqB;AACtC,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;;AAEA;AACA,kBAAkB,iCAAiC;AACnD,eAAe,OAAO;AACtB,eAAe,MAAM;AACrB,iBAAiB,qBAAqB;AACtC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,UAAU;AACzB,eAAe,UAAU;AACzB;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,eAAe,UAAU;AACzB,iBAAiB,qBAAqB;AACtC;AACA;AACA;AACA,MAAM,IAAI;AACV;AACA,qBAAqB,2DAAW;AAChC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,qBAAqB,2DAAW;AAChC,6BAA6B,2DAAW;AACxC;AACA,iBAAiB;AACjB;AACA;AACA,mDAAmD;;AAEnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,OAAO;AACtB,eAAe,OAAO;AACtB;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,eAAe,UAAU;AACzB,iBAAiB,qBAAqB;AACtC;AACA;AACA;AACA,MAAM,IAAI;AACV;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA,sCAAsC,2DAAW;AACjD,4BAA4B,2DAAW;;AAEvC,kBAAkB;AAClB,sCAAsC,2DAAW;AACjD,4BAA4B,2DAAW;AACvC;AACA;AACA;AACA,iBAAiB;AACjB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,UAAU;AACzB,eAAe,UAAU;AACzB,iBAAiB,qBAAqB;AACtC;AACA;AACA;AACA,qBAAqB,2DAAW;AAChC;AACA,iBAAiB;AACjB;AACA;;;AAGA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,UAAU;AACzB;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,eAAe,UAAU;AACzB,iBAAiB,qBAAqB;AACtC;AACA,yDAAyD;AACzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;;AAEA;AACA;AACA;AACA;AACA,sBAAsB,uDAAQ;;AAE9B;AACA;AACA;AACA,cAAc,QAAQ;AACtB;AACA;AACA;AACA;;AAEA,mBAAmB,cAAc;AACjC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,aAAa,QAAQ;AACrB,eAAe,SAAS;AACxB,cAAc,OAAO;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,yDAAyD,YAAY;AACrE;AACA;;AAEA;AACA;AACA;AACA,cAAc,UAAU;AACxB,gBAAgB,QAAQ;AACxB;AACA;AACA;AACA;;AAEA;AACA;AACA,cAAc,UAAU;AACxB,gBAAgB,QAAQ;AACxB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA,eAAe,yBAAyB;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;;AAEA;AACA;;AAEA,eAAe,yBAAyB;AACxC;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA,eAAe,yBAAyB;AACxC;AACA;AACA;AACA;;;AAGA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,eAAe,yBAAyB;AACxC;AACA;AACA;AACA,4BAA4B,gBAAgB;AAC5C;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;;AAEA;AACA,4BAA4B,eAAe;AAC3C;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;;AAEA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB;AACA;AACA;AACA;AACA;;AAEA,eAAe,yBAAyB;AACxC;AACA;AACA;AACA;AACA,qDAAqD;AACrD;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,eAAe,yBAAyB;AACxC;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,QAAQ;AACzB;AACA;AACA;;AAEA;AACA;AACA,wBAAwB,mBAAmB;AAC3C;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA,eAAe,yBAAyB;AACxC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,UAAU;AACzB;AACA;AACA;AACA;AACA;;AAEA,eAAe,yBAAyB;AACxC;AACA;AACA;AACA;AACA,SAAS;AACT;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,eAAe,yBAAyB;AACxC;AACA;AACA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA,eAAe,yBAAyB;AACxC;AACA;AACA,wBAAwB,mBAAmB;AAC3C;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,0BAA0B;AACzC;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA,MAAM,IAAI;;AAEV;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,QAAQ;AACvB;AACA;AACA;;AAEA;AACA;AACA;;AAEA,eAAe,yBAAyB;AACxC;AACA;AACA,wBAAwB,mBAAmB;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,KAAK;AACpB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,2FAA2F;AAC3F,gJAAgJ;;AAEhJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,UAAU;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,uBAAuB;AAClC,WAAW,QAAQ;AACnB,WAAW,sBAAsB;AACjC,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,cAAc,2DAAW;AACzB,cAAc,2DAAW;AACzB;AACA;;AAEA;AACA;AACA;AACA,WAAW,uBAAuB;AAClC,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB,cAAc,QAAQ;AACtB;;AAEO,kCAAkC,uDAAQ;AACjD;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,mBAAmB,cAAc;AACjC;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iEAAiE;;AAEjE;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,6BAA6B,uBAAuB,GAAG,4DAAY,YAAY,GAAG,uBAAuB;AACzG;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;;AAEA,mBAAmB,SAAS;AAC5B;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,yBAAyB,iBAAiB;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,WAAW;AAC1B,iBAAiB,aAAa;AAC9B,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,kBAAkB;AAClB,kDAAkD,KAAK;AACvD;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,4BAA4B;AAC3C;AACA,gBAAgB,OAAO;AACvB,iBAAiB,8BAA8B;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;;AAEV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;AACA;;AAEA;AACA,iBAAiB,4BAA4B;AAC7C;AACA,iBAAiB,QAAQ;AACzB,kBAAkB,mBAAmB;AACrC,kBAAkB,mBAAmB;AACrC,kBAAkB,mBAAmB;AACrC;;AAEA;AACA;AACA,eAAe,iBAAiB;AAChC,eAAe,QAAQ;AACvB,eAAe,iBAAiB;AAChC,eAAe,sBAAsB;AACrC,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,iBAAiB,eAAe;AAChC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU,IAAI;AACd;;AAEA;;AAEA,mBAAmB,kBAAkB;AACrC;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,kBAAkB;AAClB;AACA;;AAEA;AACA,qDAAqD,oEAAoE;AACzH;;AAEA,cAAc;AACd,qEAAqE,2CAA2C;AAChH;;AAEA,UAAU;AACV;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,uDAAuD,sDAAsD;AAC7G;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA,6BAA6B,oDAAG;AAChC;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA,4BAA4B,0BAA0B;AACtD;AACA;;AAEA,kBAAkB;AAClB;AACA;AACA;AACA;;AAEA,kBAAkB,OAAO;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,kCAAkC,oDAAM;AACxC;AACA;AACA;AACA;;AAEA,UAAU;AACV;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,0BAA0B,eAAe;AACzC;;AAEA;AACA;AACA;AACA,eAAe,aAAa;AAC5B,iBAAiB,eAAe;AAChC;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA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A,iBAAiB,QAAQ;AACzB,gBAAgB,OAAO;AACvB;AACA;AACA;AACA,wBAAwB;AACxB;AACA,iCAAiC,oDAAM;AACvC;AACA;;AAEA,oEAAoE,gEAAgB;AACpF;AACA;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,mBAAmB;AAClC,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB;AACA,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,mBAAmB,QAAQ;AAC3B;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA,eAAe,UAAU;AACzB;AACA;AACA;AACA;AACA;AACA,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA,MAAM,IAAI;;AAEV;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA,kBAAkB;AAClB;AACA,kBAAkB;AAClB;AACA;AACA;AACA,8CAA8C,kCAAkC;AAChF;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,gBAAgB;AAChC;AACA;AACA;AACA;AACA,WAAW,kDAAkD;AAC7D,WAAW,8EAA8E;AACzF,WAAW,8EAA8E;AACzF;AACA;AACA,0DAA0D,iBAAiB;AAC3E;AACA;AACA,+DAA+D,sCAAsC;AACrG;AACA;AACA;AACA,eAAe,WAAW;AAC1B;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,eAAe,UAAU;AACzB;AACA;AACA;AACA;AACA;AACA,eAAe,0BAA0B;AACzC;AACA;AACA;AACA;AACA;AACA,eAAe,SAAS;AACxB;AACA;AACA;AACA,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,eAAe,QAAQ;AACvB;AACA,eAAe,SAAS;AACxB,eAAe,SAAS;AACxB,eAAe,QAAQ,4BAA4B;AACnD,iBAAiB,sDAAsD;AACvE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B;AACA,MAAM,IAAI;;AAEV,iDAAiD,sBAAsB;;AAEvE;AACA,mEAAmE,qBAAqB;AACxF;;AAEA;AACA;AACA;AACA,mCAAmC,wDAAQ;AAC3C;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACO;AACP;AACA;AACO;AACP;AACA;AACO;AACP;AACA;AACO;AACP;AACA;AACO;AACP;AACA;AACO;AACP;AACA;AACO;AACP;AACA;AACO;AACA;AACA;AACP;;AAEA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;;AAEO;AACA;AACA;AACA;AACP;AACA;;AAEA,qCAAqC,EAAE,OAAO,EAAE;AAChD;AACA,qCAAqC;AACrC;;AAEA;AACA;AACA,eAAe,iBAAiB;AAChC,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACO,kDAAkD;;AAElD;;AAEA;;AAEP;;AAEO;;AAEP;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEA;AACA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEP;AACA;AACA,WAAW,qBAAqB;AAChC,WAAW,iBAAiB;AAC5B,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iDAAiD,eAAe,iCAAiC,EAAE,gCAAgC;AACnI;;AAEA;AACA;AACA;AACA;AACA,qDAAqD,eAAe,iCAAiC,EAAE,gCAAgC;AACvI;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACO;;AAEP;AACA;;AAEA,qCAAqC,EAAE,YAAY,EAAE;AACrD;AACA,qCAAqC;AACrC;;AAEA;AACA;AACA,eAAe,iBAAiB;AAChC,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACO;AACP;AACA;;AAEA,uCAAuC,IAAI;AAC3C;AACA;AACA;AACA,uCAAuC,EAAE;AACzC;;AAEA;AACA;AACA,eAAe,iBAAiB;AAChC,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA;;AAEA;AACA;AACA,eAAe,OAAO,gEAAgE,GAAG;AACzF,eAAe,QAAQ;AACvB,iBAAiB,cAAc,0BAA0B,mEAAmE,EAAE,GAAG;AACjI;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;AACV;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA,qBAAqB;AACrB;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;;AAGA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,uDAAuD,QAAQ;AAC/D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,4BAA4B,sBAAsB;AAClD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,qCAAqC,uFAAwB;;AAE7D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,sBAAsB;AACtB;AACA;AACA,kBAAkB;AAClB;AACA;AACA,yCAAyC,sDAAK;;AAE9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,sBAAsB;AACtB;AACA,sBAAsB;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B;AAC1B;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,kBAAkB;AAClB;AACA;AACA;AACA;;AAEA;AACA,yCAAyC,sDAAK;;AAE9C;AACA;AACA,uCAAuC,sDAAK;;AAE5C;AACA;AACA;AACA;AACA;AACA,2CAA2C,sDAAK;AAChD;AACA,0BAA0B;AAC1B;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,4BAA4B,mBAAmB;AAC/C;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B;AAC7B,cAAc;AACd,6BAA6B;AAC7B;AACA;AACA;;AAEA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,iBAAiB,YAAY;AAC7B,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;;AAEA;AACA;;AAEA;;AAEA;AACA;;AAEA;;AAEA;AACA;;AAEA;;AAEA;AACA,4BAA4B,8BAA8B;AAC1D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA,wBAAwB,kBAAkB;AAC1C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,UAAU;AACzB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA,gFAAgF,4CAA4C;AAC5H;;AAEA;;AAEA;AACA;AACA;AACA,UAAU;AACV;AACA;;AAEA;AACA;;AAEA,eAAe,+BAA+B;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qCAAqC,oDAAM;AAC3C;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,eAAe,mBAAmB;AAClC,eAAe,QAAQ;AACvB;AACA;AACA;AACA;;AAEA;AACA,kBAAkB,OAAO;AACzB;AACA;AACA;AACA;AACA;AACA,kCAAkC,UAAU;AAC5C;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA,gCAAgC,2BAA2B;AAC3D;;AAEA;AACA;;AAEA;AACA;AACA;AACA,aAAa;;AAEb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA,iDAAiD,kBAAkB;;AAEnE,wBAAwB,qBAAqB;;AAE7C;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,eAAe,YAAY;AAC3B,eAAe,YAAY;AAC3B,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;AACA;;AAEA;AACA;AACA;AACA,+BAA+B,2DAAW;AAC1C,gCAAgC,2DAAW;AAC3C;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B,2DAAW;AAC1C,gCAAgC,2DAAW;AAC3C;AACA;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACA;AACA;;AAEP;AACA;AACA;AACA;AACO;AACP;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,eAAe,aAAa;AAC5B,iBAAiB,OAAO;AACxB;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA,UAAU;AACV;AACA;;AAEA;AACA,2DAA2D,SAAS,uEAAuE,8CAA8C;AACzL;AACA,mBAAmB,2DAAW;AAC9B;AACA;;AAEA;;AAEO;;AAEA;AACA;;AAEA;;AAEA;;AAEA;;AAEP;AACA;;AAEA;AACA,yCAAyC;AACzC;AACA;;AAEO;;AAEP;AACA;AACA;AACA;AACA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA,eAAe,4BAA4B;AAC3C;AACA,iBAAiB,8BAA8B;AAC/C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,IAAI;;AAEV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;;AAEA;AACA;AACA,qDAAqD,cAAc;AACnE;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;ACvwIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAIkB;AACoB;AAGnB;AAC0B;;;AAG7C;AACA;AACA,WAAW,YAAY;AACvB,WAAW,QAAQ;AACnB,aAAa,uBAAuB;AACpC;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,kCAAkC,gDAAO;AACzC,wCAAwC,2BAA2B;AACnE;AACA,oEAAoE,oBAAoB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;AAC5B,wBAAwB,wBAAwB;AAChD;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc,2BAA2B;AACzC,WAAW,GAAG;AACd,WAAW,QAAQ;AACnB;AACA,WAAW,QAAQ;AACnB;AACA,WAAW,QAAQ;AACnB;AACA,aAAa,GAAG;AAChB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,cAAc,2BAA2B;AACzC,WAAW,GAAG;AACd,WAAW,QAAQ;AACnB;AACA,WAAW,QAAQ;AACnB;AACA,WAAW,QAAQ;AACnB;AACA,aAAa,GAAG;AAChB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,2BAA2B;AACtC,WAAW,2BAA2B;AACtC;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB;AACA,WAAW,QAAQ;AACnB,WAAW,SAAS;AACpB;AACA,WAAW,QAAQ;AACnB;AACA,WAAW,SAAS;AACpB;AACA,WAAW,QAAQ;AACnB,WAAW,YAAY;AACvB;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB;AACA;AACA,WAAW,QAAQ;AACnB;AACA,WAAW,QAAQ;AACnB;AACA;AACA,WAAW,QAAQ;AACnB;AACA,WAAW,SAAS;AACpB;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,SAAS;AACpB,WAAW,SAAS;AACpB,aAAa,iBAAiB;AAC9B;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA,qCAAqC,aAAa,uCAAuC,WAAW;AACpG;;AAEA;AACA,iDAAiD,cAAc,6BAA6B,aAAa;AACzG;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,yCAAyC,SAAS;AAClD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,2CAA2C;AAC3C;AACA;AACA;AACA,UAAU,OAAO;AACjB;AACA;AACA;;AAEA;AACA,oBAAoB,0CAAG;AACvB;AACA;AACA;;AAEA,oBAAoB,QAAQ;AAC5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,wBAAwB,iBAAiB;AACzC;AACA;;AAEA;AACA;AACA,4BAA4B,iBAAiB;AAC7C;AACA;AACA;AACA,4BAA4B,iBAAiB;AAC7C;AACA;AACA;;AAEA;AACA;AACA,0CAA0C,QAAQ;AAClD;AACA;AACA;AACA;;AAEA;AACA,wBAAwB,mBAAmB;AAC3C;AACA;;AAEA;;AAEA;AACA,wBAAwB,wBAAwB;AAChD;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,+BAA+B;AAC/B,wBAAwB,oCAAoC;AAC5D;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,yBAAyB,kDAAM;AAC/B;AACA,YAAY,8CAAM;AAClB,YAAY,8CAAM;AAClB;AACA;AACA;AACA;;AAEA,qCAAqC,cAAc;AACnD,oBAAoB,0BAA0B;AAC9C;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,gCAAgC,OAAO;AACvC;AACA;AACA;AACA;AACA,gCAAgC,OAAO;AACvC;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA,kBAAkB;AAClB,kEAAkE,QAAQ,eAAe,MAAM;AAC/F;AACA;AACA;AACA,6FAA6F,QAAQ;AACrG;AACA;;AAEA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,SAAS;AACpB,WAAW,QAAQ;AACnB;AACA,WAAW,SAAS;AACpB,aAAa,cAAc;AAC3B;AACO;AACP;AACA;AACA;AACA,EAAE,IAAI;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mDAAmD,KAAK;AACxD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iDAAiD,cAAc,yCAAyC,aAAa;AACrH;;AAEA;AACA;;;;;;;;;;;;;;;;AC9rBO;;;;;;;;;;;;;;;;;;;;;;;;;;ACAP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,KAAK;AAChB,aAAa;AACb;AACA;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACA;AACO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP,oCAAoC,sBAAsB;AAC1D;;AAEA;AACA;AACA,WAAW,GAAG;AACd,aAAa,SAAS;AACtB;AACA;AACA;AACO;AACP;AACA;;;AAGA;AACA;AACA,WAAW,GAAG;AACd,aAAa,SAAS;AACtB;AACO;AACP;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,UAAU;AACvB;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,GAAG;AACd,aAAa,GAAG;AAChB,YAAY,OAAO;AACnB;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,KAAK;AAChC;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY,SAAS;AACrB,aAAa,OAAO;AACpB;AACO;AACP;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,aAAa,OAAO;AACpB;AACA;AACO;AACP;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,UAAU;AACrB,aAAa;AACb;AACO;AACP;AACA,UAAU;AACV;AACA;AACA,yBAAyB;AACzB;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;AC/JA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO;;AAEP;AACA;AACA,eAAe,6BAA6B;AAC5C;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,SAAS;AAC1B;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,KAAK;AACtB;AACA;AACA;AACA;;AAEA;AACA;AACA,gBAAgB,QAAQ;AACxB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,OAAO;AACtB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,KAAK;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,GAAG;AAClB,iBAAiB,GAAG;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,SAAS;AAC1B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,gBAAgB,QAAQ;AACxB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAAS;AACxB,eAAe,2BAA2B;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,cAAc;AAC/B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uCAAuC,sBAAsB;AAC7D,qCAAqC,sBAAsB;;AAE3D;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB,oBAAoB;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,eAAe,kBAAkB;AACjC,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;;AAEA;AACA,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,kBAAkB;AACnC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;AC7bA;AACA;AACA;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,CAAC;;AAED;AACA,aAAa,2BAA2B;AACxC;;;;;;;;;;;;;;;;;;;;ACrBiC;;AAEW;;AAE5C;AACA;AACA;;AAEA;AACA;AACA;AACO;AACP,eAAe,SAAS;AACxB;;AAEA;AACA;AACA,iBAAiB,yCAAI;AACrB;AACA,cAAc;AACd;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;;AAEM;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,cAAc,yBAAyB;;AAEhC;AACP;AACA,KAAK,qDAAY;AACjB,CAAC;;AAED,WAAW,0BAA0B;AAC9B;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;;;;;;;;;;;;;;;;AC1DD;AACA;AACA;AACA;AACA,UAAU,WAAW;AACrB;AACO,4BAA4B,KAAK;AACxC;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB,mBAAmB,QAAQ;AAC3B,qBAAqB,GAAG;AACxB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,eAAe,OAAO;AACtB,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA,CAAC;;;;;;;;;;;;;;;;;;;;;;ACjCD;AACA;AACA;AACA;AACA;;AAEoB;AACI;;AAEQ;AACa;;AAE7C;AACA,aAAa,QAAQ;AACrB,cAAc,UAAU;AACxB,cAAc,0CAA0C;AACxD;AACA;AACA,cAAc,QAAQ;AACtB,cAAc,SAAS;AACvB,cAAc,QAAQ;AACtB;AACA;AACA;;AAEA;AACA,aAAa,QAAQ;AACrB,cAAc,QAAQ;AACtB;AACA,cAAc,QAAQ;AACtB,cAAc,qFAAqF;AACnG,cAAc,+EAA+E;AAC7F,cAAc,iCAAiC;AAC/C,cAAc,8DAA8D;AAC5E;;AAEA;AACA,aAAa,oDAAoD;AACjE;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B;AACA;AACA;AACA;;AAEA,sBAAsB,0CAAa;AACnC;AACA;AACA;;AAEA,wBAAwB,wCAAW;AACnC;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA,aAAa;AACb,UAAU;AACV;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,cAAc;AAC/B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB,sBAAsB;AACvC,gBAAgB,OAAO;AACvB;AACA;AACA,2BAA2B,wCAAW;AACtC;AACA;;AAEA;AACA;AACA;AACA,iBAAiB,eAAe;AAChC,gBAAgB,OAAO;AACvB;AACA;AACA,2BAA2B,wCAAW;AACtC,kCAAkC,wCAAwC;AAC1E;;AAEA;AACA;AACA;AACA,iBAAiB,iBAAiB;AAClC,gBAAgB,OAAO;AACvB;AACA;AACA,2BAA2B,wCAAW;AACtC;AACA;;AAEA;AACA;AACA;AACA;AACA,iBAAiB,iBAAiB;AAClC,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,YAAY;AACvB,WAAW,UAAU;AACrB,WAAW,UAAU;AACrB,aAAa,SAAS;AACtB;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,YAAY;AACvB,aAAa,gCAAgC;AAC7C;AACO;;AAEP,QAAQ,wCAAG;AACX;;AAEA,MAAM;AACN;AACA,wBAAwB,wCAAG;;AAE3B;AACA,qDAAqD,UAAU,QAAQ,OAAO;;AAE9E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uDAAuD,MAAM;AAC7D;AACA;AACA,kCAAkC,SAAS;AAC3C,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,SAAS;AACpB,aAAa,MAAM;AACnB,YAAY,OAAO;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,uDAAuD,OAAO;AAC9D,mBAAmB,QAAQ,KAAK,UAAU;AAC1C;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB;AACjB;AACA;;AAEA,uBAAuB,sCAAS;AAChC;;AAEA;AACA;AACA,UAAU;A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iC;AAChD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA,YAAY,wCAAG;AACf;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C;AAC1C,kBAAkB;AAClB;AACA;AACA,oEAAoE,UAAU,MAAM,EAAE;AACtF;AACA,cAAc;AACd,wGAAwG,WAAW;AACnH,cAAc,UAAU,wCAAG;AAC3B,8GAA8G,WAAW;AACzH;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,6CAA6C,wCAAG;AAChD;AACA;AACA,mIAAmI,UAAU;AAC7I,kBAAkB;AAClB;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,IAAI,0DAAgB;AACpB;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA;AACA;;AAEA,eAAe,YAAY;AAC3B;;AAEA;AACA;AACA;AACA;;AAEA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,QAAQ,0DAAgB;AACxB;AACA;AACA;AACA;AACA,SAAS;AACT,MAAM;AACN;AACA,YAAY,0DAAgB;AAC5B;AACA;AACA,aAAa;AACb,SAAS;AACT;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,yEAAyE,IAAI;AAC7E,aAAa;;AAEb;;AAEA,IAAI,0DAAgB;AACpB;AACA;AACA;AACA,KAAK;;AAEL;AACA;;AAEA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,SAAS;AACpB,WAAW,mBAAmB;AAC9B,aAAa,iBAAiB;AAC9B;AACA;AACO,2EAA2E;AAClF;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,KAAK;AAChB,WAAW,UAAU;AACrB,aAAa,qBAAqB;AAClC;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,gBAAgB,cAAc;AAC9B;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,WAAW;AACtB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;;;;;;;;;;;;;;;;;;;AC9pBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEmC;AACH;AACK;;AAErC;AAC0B;;AAE1B;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,uCAAuC,QAAQ,qBAAqB,QAAQ;AAC5E;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,EAAE,SAAS,kCAAK;AAChB;;AAEA,yCAAyC,YAAY;AACrD;AACA;;AAEA,gBAAgB,aAAa,sCAAsC,yBAAyB;;AAE5F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,EAAE;AACF;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEO;;AAEP;AACA;AACA,eAAe,8BAA8B;AAC7C,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,kBAAkB;AACnC;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,qBAAqB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,UAAU;AACV,uDAAuD,aAAa;AACpE;AACA;;AAEA;AACA;AACA,eAAe,mCAAmC;AAClD,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,YAAY;AAC3B,iBAAiB,mBAAmB;AACpC;AACA;AACA,+BAA+B,gDAAO;AACtC;AACA,0DAA0D,IAAI,KAAK,iBAAiB,EAAE,oBAAoB;AAC1G;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,MAAM;AACrB,iBAAiB,mBAAmB;AACpC;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;;AAEA,UAAU;AACV;AACA,wBAAwB,kCAAK;;AAE7B;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA,wEAAwE,oBAAoB;AAC5F;;AAEA;AACA;AACA,UAAU;AACV;AACA,UAAU;AACV,2DAA2D,eAAe;AAC1E;AACA;AACA,wDAAwD,YAAY;AACpE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mEAAmE,eAAe;AAClF;AACA;;AAEA;AACA;AACA,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,4CAA4C,sBAAsB;AAClE;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,4FAA4F,cAAc;AAC1G;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,4CAA4C,sBAAsB;AAClE;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C,sBAAsB;AAClE;AACA;AACA;AACA;AACA;AACA;AACA,4FAA4F,cAAc;AAC1G;AACA;;AAEA;;AAEA;AACA;AACA,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,4CAA4C,sBAAsB;AAClE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C,sBAAsB;AAClE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4FAA4F,cAAc;AAC1G;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,oBAAoB;AACnC,iBAAiB,mBAAmB;AACpC;AACA;AACA;AACA,MAAM,IAAI;;AAEV;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA,UAAU;AACV;AACA;;AAEA;AACA;AACA;AACA;AACA,0DAA0D,gBAAgB;AAC1E;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB;AACrB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB;AACrB;;AAEA;AACA,yDAAyD,gBAAgB;AACzE;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA,UAAU;AACV,gDAAgD,0BAA0B;AAC1E;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;;AAEb;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA,UAAU;AACV;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB;AACjB,cAAc;AACd;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA,iBAAiB;AACjB;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,4CAA4C,eAAe;AAC3D;;AAEA;AACA,yBAAyB,8CAAM;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA,UAAU,qCAAqC;AAC/C;AACA,UAAU;AACV,2DAA2D,eAAe;AAC1E;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,mBAAmB;AAClC,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,cAAc;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,UAAU;AAC3B;AACA;AACA,wDAAwD;;AAExD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4FAA4F,cAAc;AAC1G;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA,UAAU,UAAU,wCAAG;AACvB;;AAEA,UAAU;AACV;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,eAAe,kCAAK;AACpB;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACvuBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,aAAa,gIAAgI;AAC7I,aAAa,gCAAgC;AAC7C,aAAa,4BAA4B;AACzC;;AAEA;AACA,WAAW,YAAY;AACvB;AACO;AACP;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,oBAAoB,gBAAgB;AACpC,wBAAwB,eAAe;AACvC;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;;AAGA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,4BAA4B,iBAAiB;AAC7C;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;;AAGA;AACA;AACA,cAAc,eAAe;AAC7B,WAAW,GAAG;AACd,WAAW,UAAU;AACrB,WAAW,UAAU;AACrB,aAAa,eAAe;AAC5B;AACO;AACP;AACA;AACA;AACA;;AAEA,yCAAyC,QAAQ;AACjD;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,oBAAoB,kBAAkB;AACtC;AACA,6CAA6C,QAAQ;AACrD;AACA;AACA;AACA;AACA;;AAEA;AACA;;;AAGA;AACA;AACA,cAAc,qBAAqB;AACnC,WAAW,GAAG;AACd,aAAa,GAAG;AAChB;AACO;AACP;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA,sBAAsB,GAAG;AACzB;;AAEA;AACA;AACA,cAAc,qBAAqB;AACnC,WAAW,GAAG;AACd,aAAa,GAAG;AAChB;AACO;AACP;AACA;;AAEA;AACA;AACA,mBAAmB,gBAAgB;AACnC;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA,sBAAsB,GAAG;AACzB;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,UAAU;AACrB,aAAa,QAAQ;AACrB;AACO;AACP;AACA,oBAAoB,iBAAiB;AACrC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,UAAU;AACrB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;;;AAGA;AACA;AACA,WAAW,qBAAqB;AAChC,aAAa,kBAAkB;AAC/B,YAAY,OAAO;AACnB;AACO;AACP;AACA;AACA;AACA,oBAAoB,gBAAgB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA,WAAW,wBAAwB;AACnC,aAAa,kBAAkB;AAC/B,YAAY,OAAO;AACnB;AACO;AACP;AACA;AACA;AACA,oBAAoB,gBAAgB;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,gBAAgB,OAAO;AACvB;AACA;AACA,8BAA8B;AAC9B;AACA;;AAEA;;AAEA;AACA,wBAAwB,uBAAuB;AAC/C;AACA;AACA;AACA;;AAEA;AACA;AACA,wBAAwB,eAAe;AACvC;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,wBAAwB,yBAAyB;AACjD;AACA,gCAAgC,qBAAqB;AACrD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB,cAAc;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,UAAU;AACzB,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA,wBAAwB,oBAAoB;AAC5C;AACA;AACA;;AAEA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B,iBAAiB,cAAc;AAC/B;AACA;AACA;AACA,wBAAwB,gBAAgB;AACxC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B;AACA,gBAAgB,OAAO;AACvB;AACA,iBAAiB;AACjB;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B;AACA,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B,gBAAgB,OAAO;AACvB,iBAAiB;AACjB;AACA;AACA;AACA;;AAEA;AACA,wBAAwB,gBAAgB;AACxC;AACA;;AAEA;AACA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B,eAAe,QAAQ;AACvB,iBAAiB;AACjB;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,oCAAoC,eAAe;AACnD;AACA;AACA;AACA,UAAU;AACV;AACA,oCAAoC,eAAe;AACnD;AACA;AACA;AACA;;AAEA;AACA;AACA,yBAAyB,WAAW;AACpC;AACA;;AAEA;AACA,6BAA6B,eAAe;AAC5C;AACA;AACA,4CAA4C,WAAW;AACvD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB;AACjB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B,eAAe,QAAQ;AACvB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,oCAAoC,eAAe;AACnD;AACA;AACA;AACA,UAAU;AACV;AACA,oCAAoC,eAAe;AACnD;AACA;AACA;AACA;;AAEA;AACA;AACA,yBAAyB,WAAW;AACpC;AACA;AACA;AACA;;AAEA;AACA,6BAA6B,eAAe;AAC5C,uCAAuC,kBAAkB;AACzD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,wBAAwB,UAAU;AAClC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA,iBAAiB;AACjB;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,eAAe,cAAc;AAC7B,eAAe,cAAc;AAC7B,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,wBAAwB,YAAY;AACpC;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,4BAA4B,eAAe;AAC3C;AACA;;AAEA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,4BAA4B,eAAe;AAC3C;AACA;AACA;AACA;AACA;AACA;;AAEA,wBAAwB,eAAe;AACvC;;AAEA;AACA;AACA;AACA;;AAEA,wBAAwB,gBAAgB;AACxC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEO;AACP;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;AAGA;AACA;AACA,WAAW,eAAe;AAC1B,WAAW,QAAQ;AACnB;AACO;;AAEP;AACA;AACA;;AAEA;AACA;;AAEA;AACA,qDAAqD;;AAErD;;AAEA,oBAAoB,iBAAiB;AACrC;;AAEA,sCAAsC,qBAAqB;AAC3D;AACA;AACA;AACA,cAAc;AACd;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA,WAAW,YAAY;AACvB,aAAa;AACb;AACO;AACP;AACA;;AAEA;;AAEA;AACA,UAAU,wBAAwB;AAClC;AACA;AACA;;AAEA;AACA,UAAU,wBAAwB;AAClC;AACA;;AAEA,oBAAoB,oBAAoB;AACxC,wBAAwB,oBAAoB;AAC5C;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc;AACd;AACA;AACA,cAAc;AACd;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,oBAAoB,oBAAoB,OAAO;AAC/C;AACA;AACA,oBAAoB,oBAAoB,OAAO;AAC/C;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gFAAgF,EAAE,IAAI,EAAE;AACxF;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACliCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAKoB;;AAIS;;AAEyB;;AAEtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;;AAED;AACA,aAAa,0BAA0B;AACvC,aAAa,4CAA4C;AACzD;;;AAGO;AACP,eAAe,UAAU;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,eAAe,UAAU;AACzB;AACA;AACA;;AAEA,eAAe,WAAW;AAC1B;AACA;AACA;;AAEA,eAAe,QAAQ;AACvB;AACA;AACA;;AAEA,eAAe,QAAQ;AACvB;AACA;AACA;;AAEA;;AAEA;AACA;AACA,eAAe,8CAA8C;AAC7D;AACA;AACA,YAAY,+DAAY;AACxB,yCAAyC,YAAY;AACrD,UAAU;AACV;AACA,kCAAkC,qDAAU;AAC5C,2BAA2B,UAAU;AACrC,2BAA2B,gEAAgE;AAC3F;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;;AAEA;AACA;AACA;AACA,SAAS;AACT;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB,UAAU;AAC3B;AACA;AACA;;AAEA;AACA;AACA,4BAA4B,gBAAgB;AAC5C;AACA;AACA,UAAU;AACV;AACA;;AAEA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;;AAEA;AACA,eAAe,eAAe;AAC9B,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA,4BAA4B,0BAA0B;AACtD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,eAAe,KAAK;AACpB,iBAAiB;AACjB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB,eAAe;AAChC,gBAAgB,OAAO;AACvB;AACA;AACA;AACA;AACA,6CAA6C,kBAAkB;AAC/D;AACA;AACA;;AAEA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB;AACA,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB;AACA,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA,wBAAwB,sBAAsB;AAC9C;A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AACzB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,SAAS;AACxB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,eAAe;AAC9B,eAAe,QAAQ;AACvB;AACA,eAAe,SAAS;AACxB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA,UAAU;AACV,6CAA6C,EAAE;AAC/C;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,8CAA8C;AAC9C,6BAA6B;;AAE7B;AACA;AACA;;AAEA;AACA,wBAAwB,sBAAsB;;AAE9C;AACA;;AAEA,8EAA8E,QAAQ;AACtF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,4BAA4B,mBAAmB;AAC/C;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;;AAEA;;AAEA;AACA;AACA,wBAAwB,sBAAsB;;AAE9C;AACA;;AAEA,8EAA8E,QAAQ;AACtF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,iBAAiB,UAAU;AAC3B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,iCAAiC;AACjC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,iCAAiC;AACjC;AACA;AACA;AACA;AACA;;AAEA;AACA,iCAAiC;AACjC;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;;AAEA;AACA;AACA,gBAAgB,WAAW;AAC3B,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA,wBAAwB,iBAAiB;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,aAAa;;AAEb;AACA;AACA,uDAAuD;AACvD;;AAEA;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,iCAAiC;AACjC;AACA;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe,QAAQ;AACvB,eAAe,QAAQ;AACvB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;;AAEA;AACA,iCAAiC;AACjC;AACA;AACA;AACA,wBAAwB,sBAAsB;AAC9C;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,eAAe,UAAU;AACzB,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;;AAEA;AACA;AACA,iDAAiD,KAAK;AACtD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,2BAA2B;AAC3B;AACA,2BAA2B;AAC3B;AACA,2BAA2B;AAC3B;AACA,cAAc,QAAQ;AACtB,cAAc,SAAS;AACvB,aAAa,0EAA0E;AACvF;;AAEA;AACA;AACA;AACA;AACA,mDAAmD;AACnD,mDAAmD;AACnD,mDAAmD;AACnD,mDAAmD;AACnD,WAAW,eAAe;AAC1B,WAAW,KAAK;AAChB;AACA,cAAc,mBAAmB;AACjC,aAAa,6BA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ACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,2BAA2B;AACxC;AACO;AACP,qBAAqB,8DAAgB;;AAErC;AACA;AACA,MAAM;AACN;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA,oBAAoB,eAAe;AACnC;;AAEA,wBAAwB,cAAc;AACtC;AACA;;AAEA;AACA;AACA;AACA,4BAA4B,eAAe;AAC3C;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,UAAU;AACrB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP;AACA,EAAE,IAAI;AACN;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA,+BAA+B,cAAc;AAC7C,gCAAgC,cAAc;;AAE9C,iCAAiC,cAAc;;AAE/C;AACA;;AAEA,oBAAoB,eAAe;AACnC;AACA,wBAAwB,gBAAgB;AACxC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,sBAAsB;AACjC,aAAa,UAAU;AACvB;AACA;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,SAAS;AACT;AACA;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,QAAQ;AACnB,aAAa,UAAU;AACvB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACA,YAAY,OAAO;AACnB;AACA;AACA;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C;AAC1C,yBAAyB;;AAEzB;AACA;AACA;;AAEA;AACA,oBAAoB,sBAAsB;;AAE1C;AACA;;AAEA,0EAA0E,QAAQ;AAClF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,wBAAwB,mBAAmB;AAC3C;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;;AAGA;AACA;AACA,0CAA0C,QAAQ;AAClD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,WAAW,eAAe;AAC1B,aAAa,QAAQ;AACrB;AACO;AACP;AACA;AACA;AACA;AACA;AACA,MAAM;AACN;AACA;AACA,MAAM;AACN;AACA,kDAAkD,kBAAkB;AACpE;AACA;AACA;;AAEO;AACP;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;;AAEA;AACA;AACA,WAAW,UAAU;AACrB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,aAAa,QAAQ;AACrB;AACO;AACP;AACA;;AAEA;AACA;AACA,WAAW,QAAQ;AACnB,WAAW,oBAAoB;AAC/B,aAAa,QAAQ;AACrB;AACO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,oBAAoB,sBAAsB;AAC1C;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;;;;;;SCh5CA;SACA;;SAEA;SACA;SACA;SACA;SACA;SACA;SACA;SACA;SACA;SACA;SACA;SACA;SACA;;SAEA;SACA;;SAEA;SACA;SACA;;SAEA;SACA;;;;;UCzBA;UACA;UACA;UACA;UACA;UACA;UACA;UACA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ACI;AACA;AACH;;AAEI;AACA;AACC;AACD;;AAES;AACQ","sources":["webpack://@huggingface/transformers/ignored|/home/belem/github/transformers.js/src/backends|onnxruntime-node","webpack://@huggingface/transformers/ignored|/home/belem/github/transformers.js/src/utils|fs","webpack://@huggingface/transformers/ignored|/home/belem/github/transformers.js/src/utils|path","webpack://@huggingface/transformers/ignored|/home/belem/github/transformers.js/src/utils|sharp","webpack://@huggingface/transformers/ignored|/home/belem/github/transformers.js/src|fs","webpack://@huggingface/transformers/ignored|/home/belem/github/transformers.js/src|path","webpack://@huggingface/transformers/ignored|/home/belem/github/transformers.js/src|url","webpack://@huggingface/transformers/./node_modules/@huggingface/jinja/dist/index.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/backend-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/backend.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/env-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/env.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/index.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/inference-session.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/onnx-model.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/onnx-value.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-factory.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/trace.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/training-session-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/training-session.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/version.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs","webpack://@huggingface/transformers/./src/backends/onnx.js","webpack://@huggingface/transformers/./src/configs.js","webpack://@huggingface/transformers/./src/env.js","webpack://@huggingface/transformers/./src/generation/configuration_utils.js","webpack://@huggingface/transformers/./src/generation/logits_process.js","webpack://@huggingface/transformers/./src/generation/logits_sampler.js","webpack://@huggingface/transformers/./src/generation/stopping_criteria.js","webpack://@huggingface/transformers/./src/generation/streamers.js","webpack://@huggingface/transformers/./src/models.js","webpack://@huggingface/transformers/./src/models/whisper/common_whisper.js","webpack://@huggingface/transformers/./src/models/whisper/generation_whisper.js","webpack://@huggingface/transformers/./src/ops/registry.js","webpack://@huggingface/transformers/./src/pipelines.js","webpack://@huggingface/transformers/./src/processors.js","webpack://@huggingface/transformers/./src/tokenizers.js","webpack://@huggingface/transformers/./src/utils/audio.js","webpack://@huggingface/transformers/./src/utils/constants.js","webpack://@huggingface/transformers/./src/utils/core.js","webpack://@huggingface/transformers/./src/utils/data-structures.js","webpack://@huggingface/transformers/./src/utils/devices.js","webpack://@huggingface/transformers/./src/utils/dtypes.js","webpack://@huggingface/transformers/./src/utils/generic.js","webpack://@huggingface/transformers/./src/utils/hub.js","webpack://@huggingface/transformers/./src/utils/image.js","webpack://@huggingface/transformers/./src/utils/maths.js","webpack://@huggingface/transformers/./src/utils/tensor.js","webpack://@huggingface/transformers/webpack/bootstrap","webpack://@huggingface/transformers/webpack/runtime/create fake namespace object","webpack://@huggingface/transformers/webpack/runtime/define property getters","webpack://@huggingface/transformers/webpack/runtime/hasOwnProperty shorthand","webpack://@huggingface/transformers/webpack/runtime/make namespace object","webpack://@huggingface/transformers/webpack/runtime/publicPath","webpack://@huggingface/transformers/webpack/runtime/import chunk loading","webpack://@huggingface/transformers/./src/transformers.js"],"sourcesContent":["/* (ignored) */","/* (ignored) */","/* (ignored) */","/* (ignored) */","/* (ignored) */","/* (ignored) */","/* (ignored) */","// src/lexer.ts\nvar TOKEN_TYPES = Object.freeze({\n Text: \"Text\",\n // The text between Jinja statements or expressions\n NumericLiteral: \"NumericLiteral\",\n // e.g., 123\n BooleanLiteral: \"BooleanLiteral\",\n // true or false\n StringLiteral: \"StringLiteral\",\n // 'string'\n Identifier: \"Identifier\",\n // Variables, functions, etc.\n Equals: \"Equals\",\n // =\n OpenParen: \"OpenParen\",\n // (\n CloseParen: \"CloseParen\",\n // )\n OpenStatement: \"OpenStatement\",\n // {%\n CloseStatement: \"CloseStatement\",\n // %}\n OpenExpression: \"OpenExpression\",\n // {{\n CloseExpression: \"CloseExpression\",\n // }}\n OpenSquareBracket: \"OpenSquareBracket\",\n // [\n CloseSquareBracket: \"CloseSquareBracket\",\n // ]\n OpenCurlyBracket: \"OpenCurlyBracket\",\n // {\n CloseCurlyBracket: \"CloseCurlyBracket\",\n // }\n Comma: \"Comma\",\n // ,\n Dot: \"Dot\",\n // .\n Colon: \"Colon\",\n // :\n Pipe: \"Pipe\",\n // |\n CallOperator: \"CallOperator\",\n // ()\n AdditiveBinaryOperator: \"AdditiveBinaryOperator\",\n // + -\n MultiplicativeBinaryOperator: \"MultiplicativeBinaryOperator\",\n // * / %\n ComparisonBinaryOperator: \"ComparisonBinaryOperator\",\n // < > <= >= == !=\n UnaryOperator: \"UnaryOperator\",\n // ! - +\n // Keywords\n Set: \"Set\",\n If: \"If\",\n For: \"For\",\n In: \"In\",\n Is: \"Is\",\n NotIn: \"NotIn\",\n Else: \"Else\",\n EndIf: \"EndIf\",\n ElseIf: \"ElseIf\",\n EndFor: \"EndFor\",\n And: \"And\",\n Or: \"Or\",\n Not: \"UnaryOperator\",\n Macro: \"Macro\",\n EndMacro: \"EndMacro\"\n});\nvar KEYWORDS = Object.freeze({\n set: TOKEN_TYPES.Set,\n for: TOKEN_TYPES.For,\n in: TOKEN_TYPES.In,\n is: TOKEN_TYPES.Is,\n if: TOKEN_TYPES.If,\n else: TOKEN_TYPES.Else,\n endif: TOKEN_TYPES.EndIf,\n elif: TOKEN_TYPES.ElseIf,\n endfor: TOKEN_TYPES.EndFor,\n and: TOKEN_TYPES.And,\n or: TOKEN_TYPES.Or,\n not: TOKEN_TYPES.Not,\n \"not in\": TOKEN_TYPES.NotIn,\n macro: TOKEN_TYPES.Macro,\n endmacro: TOKEN_TYPES.EndMacro,\n // Literals\n true: TOKEN_TYPES.BooleanLiteral,\n false: TOKEN_TYPES.BooleanLiteral,\n // NOTE: According to the Jinja docs: The special constants true, false, and none are indeed lowercase.\n // Because that caused confusion in the past, (True used to expand to an undefined variable that was considered false),\n // all three can now also be written in title case (True, False, and None). However, for consistency, (all Jinja identifiers are lowercase)\n // you should use the lowercase versions.\n True: TOKEN_TYPES.BooleanLiteral,\n False: TOKEN_TYPES.BooleanLiteral\n});\nvar Token = class {\n /**\n * Constructs a new Token.\n * @param {string} value The raw value as seen inside the source code.\n * @param {TokenType} type The type of token.\n */\n constructor(value, type) {\n this.value = value;\n this.type = type;\n }\n};\nfunction isWord(char) {\n return /\\w/.test(char);\n}\nfunction isInteger(char) {\n return /[0-9]/.test(char);\n}\nvar ORDERED_MAPPING_TABLE = [\n // Control sequences\n [\"{%\", TOKEN_TYPES.OpenStatement],\n [\"%}\", TOKEN_TYPES.CloseStatement],\n [\"{{\", TOKEN_TYPES.OpenExpression],\n [\"}}\", TOKEN_TYPES.CloseExpression],\n // Single character tokens\n [\"(\", TOKEN_TYPES.OpenParen],\n [\")\", TOKEN_TYPES.CloseParen],\n [\"{\", TOKEN_TYPES.OpenCurlyBracket],\n [\"}\", TOKEN_TYPES.CloseCurlyBracket],\n [\"[\", TOKEN_TYPES.OpenSquareBracket],\n [\"]\", TOKEN_TYPES.CloseSquareBracket],\n [\",\", TOKEN_TYPES.Comma],\n [\".\", TOKEN_TYPES.Dot],\n [\":\", TOKEN_TYPES.Colon],\n [\"|\", TOKEN_TYPES.Pipe],\n // Comparison operators\n [\"<=\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\">=\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\"==\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\"!=\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\"<\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\">\", TOKEN_TYPES.ComparisonBinaryOperator],\n // Arithmetic operators\n [\"+\", TOKEN_TYPES.AdditiveBinaryOperator],\n [\"-\", TOKEN_TYPES.AdditiveBinaryOperator],\n [\"*\", TOKEN_TYPES.MultiplicativeBinaryOperator],\n [\"/\", TOKEN_TYPES.MultiplicativeBinaryOperator],\n [\"%\", TOKEN_TYPES.MultiplicativeBinaryOperator],\n // Assignment operator\n [\"=\", TOKEN_TYPES.Equals]\n];\nvar ESCAPE_CHARACTERS = /* @__PURE__ */ new Map([\n [\"n\", \"\\n\"],\n // New line\n [\"t\", \"\t\"],\n // Horizontal tab\n [\"r\", \"\\r\"],\n // Carriage return\n [\"b\", \"\\b\"],\n // Backspace\n [\"f\", \"\\f\"],\n // Form feed\n [\"v\", \"\\v\"],\n // Vertical tab\n [\"'\", \"'\"],\n // Single quote\n ['\"', '\"'],\n // Double quote\n [\"\\\\\", \"\\\\\"]\n // Backslash\n]);\nfunction preprocess(template, options = {}) {\n if (template.endsWith(\"\\n\")) {\n template = template.slice(0, -1);\n }\n template = template.replace(/{#.*?#}/gs, \"{##}\");\n if (options.lstrip_blocks) {\n template = template.replace(/^[ \\t]*({[#%])/gm, \"$1\");\n }\n if (options.trim_blocks) {\n template = template.replace(/([#%]})\\n/g, \"$1\");\n }\n return template.replace(/{##}/g, \"\").replace(/-%}\\s*/g, \"%}\").replace(/\\s*{%-/g, \"{%\").replace(/-}}\\s*/g, \"}}\").replace(/\\s*{{-/g, \"{{\");\n}\nfunction tokenize(source, options = {}) {\n const tokens = [];\n const src = preprocess(source, options);\n let cursorPosition = 0;\n const consumeWhile = (predicate) => {\n let str = \"\";\n while (predicate(src[cursorPosition])) {\n if (src[cursorPosition] === \"\\\\\") {\n ++cursorPosition;\n if (cursorPosition >= src.length)\n throw new SyntaxError(\"Unexpected end of input\");\n const escaped = src[cursorPosition++];\n const unescaped = ESCAPE_CHARACTERS.get(escaped);\n if (unescaped === void 0) {\n throw new SyntaxError(`Unexpected escaped character: ${escaped}`);\n }\n str += unescaped;\n continue;\n }\n str += src[cursorPosition++];\n if (cursorPosition >= src.length)\n throw new SyntaxError(\"Unexpected end of input\");\n }\n return str;\n };\n main:\n while (cursorPosition < src.length) {\n const lastTokenType = tokens.at(-1)?.type;\n if (lastTokenType === void 0 || lastTokenType === TOKEN_TYPES.CloseStatement || lastTokenType === TOKEN_TYPES.CloseExpression) {\n let text = \"\";\n while (cursorPosition < src.length && // Keep going until we hit the next Jinja statement or expression\n !(src[cursorPosition] === \"{\" && (src[cursorPosition + 1] === \"%\" || src[cursorPosition + 1] === \"{\"))) {\n text += src[cursorPosition++];\n }\n if (text.length > 0) {\n tokens.push(new Token(text, TOKEN_TYPES.Text));\n continue;\n }\n }\n consumeWhile((char2) => /\\s/.test(char2));\n const char = src[cursorPosition];\n if (char === \"-\" || char === \"+\") {\n const lastTokenType2 = tokens.at(-1)?.type;\n if (lastTokenType2 === TOKEN_TYPES.Text || lastTokenType2 === void 0) {\n throw new SyntaxError(`Unexpected character: ${char}`);\n }\n switch (lastTokenType2) {\n case TOKEN_TYPES.Identifier:\n case TOKEN_TYPES.NumericLiteral:\n case TOKEN_TYPES.BooleanLiteral:\n case TOKEN_TYPES.StringLiteral:\n case TOKEN_TYPES.CloseParen:\n case TOKEN_TYPES.CloseSquareBracket:\n break;\n default: {\n ++cursorPosition;\n const num = consumeWhile(isInteger);\n tokens.push(\n new Token(`${char}${num}`, num.length > 0 ? TOKEN_TYPES.NumericLiteral : TOKEN_TYPES.UnaryOperator)\n );\n continue;\n }\n }\n }\n for (const [char2, token] of ORDERED_MAPPING_TABLE) {\n const slice2 = src.slice(cursorPosition, cursorPosition + char2.length);\n if (slice2 === char2) {\n tokens.push(new Token(char2, token));\n cursorPosition += char2.length;\n continue main;\n }\n }\n if (char === \"'\" || char === '\"') {\n ++cursorPosition;\n const str = consumeWhile((c) => c !== char);\n tokens.push(new Token(str, TOKEN_TYPES.StringLiteral));\n ++cursorPosition;\n continue;\n }\n if (isInteger(char)) {\n const num = consumeWhile(isInteger);\n tokens.push(new Token(num, TOKEN_TYPES.NumericLiteral));\n continue;\n }\n if (isWord(char)) {\n const word = consumeWhile(isWord);\n const type = Object.hasOwn(KEYWORDS, word) ? KEYWORDS[word] : TOKEN_TYPES.Identifier;\n if (type === TOKEN_TYPES.In && tokens.at(-1)?.type === TOKEN_TYPES.Not) {\n tokens.pop();\n tokens.push(new Token(\"not in\", TOKEN_TYPES.NotIn));\n } else {\n tokens.push(new Token(word, type));\n }\n continue;\n }\n throw new SyntaxError(`Unexpected character: ${char}`);\n }\n return tokens;\n}\n\n// src/ast.ts\nvar Statement = class {\n type = \"Statement\";\n};\nvar Program = class extends Statement {\n constructor(body) {\n super();\n this.body = body;\n }\n type = \"Program\";\n};\nvar If = class extends Statement {\n constructor(test, body, alternate) {\n super();\n this.test = test;\n this.body = body;\n this.alternate = alternate;\n }\n type = \"If\";\n};\nvar For = class extends Statement {\n constructor(loopvar, iterable, body, defaultBlock) {\n super();\n this.loopvar = loopvar;\n this.iterable = iterable;\n this.body = body;\n this.defaultBlock = defaultBlock;\n }\n type = \"For\";\n};\nvar SetStatement = class extends Statement {\n constructor(assignee, value) {\n super();\n this.assignee = assignee;\n this.value = value;\n }\n type = \"Set\";\n};\nvar Macro = class extends Statement {\n constructor(name, args, body) {\n super();\n this.name = name;\n this.args = args;\n this.body = body;\n }\n type = \"Macro\";\n};\nvar Expression = class extends Statement {\n type = \"Expression\";\n};\nvar MemberExpression = class extends Expression {\n constructor(object, property, computed) {\n super();\n this.object = object;\n this.property = property;\n this.computed = computed;\n }\n type = \"MemberExpression\";\n};\nvar CallExpression = class extends Expression {\n constructor(callee, args) {\n super();\n this.callee = callee;\n this.args = args;\n }\n type = \"CallExpression\";\n};\nvar Identifier = class extends Expression {\n /**\n * @param {string} value The name of the identifier\n */\n constructor(value) {\n super();\n this.value = value;\n }\n type = \"Identifier\";\n};\nvar Literal = class extends Expression {\n constructor(value) {\n super();\n this.value = value;\n }\n type = \"Literal\";\n};\nvar NumericLiteral = class extends Literal {\n type = \"NumericLiteral\";\n};\nvar StringLiteral = class extends Literal {\n type = \"StringLiteral\";\n};\nvar BooleanLiteral = class extends Literal {\n type = \"BooleanLiteral\";\n};\nvar ArrayLiteral = class extends Literal {\n type = \"ArrayLiteral\";\n};\nvar TupleLiteral = class extends Literal {\n type = \"TupleLiteral\";\n};\nvar ObjectLiteral = class extends Literal {\n type = \"ObjectLiteral\";\n};\nvar BinaryExpression = class extends Expression {\n constructor(operator, left, right) {\n super();\n this.operator = operator;\n this.left = left;\n this.right = right;\n }\n type = \"BinaryExpression\";\n};\nvar FilterExpression = class extends Expression {\n constructor(operand, filter) {\n super();\n this.operand = operand;\n this.filter = filter;\n }\n type = \"FilterExpression\";\n};\nvar SelectExpression = class extends Expression {\n constructor(iterable, test) {\n super();\n this.iterable = iterable;\n this.test = test;\n }\n type = \"SelectExpression\";\n};\nvar TestExpression = class extends Expression {\n constructor(operand, negate, test) {\n super();\n this.operand = operand;\n this.negate = negate;\n this.test = test;\n }\n type = \"TestExpression\";\n};\nvar UnaryExpression = class extends Expression {\n constructor(operator, argument) {\n super();\n this.operator = operator;\n this.argument = argument;\n }\n type = \"UnaryExpression\";\n};\nvar SliceExpression = class extends Expression {\n constructor(start = void 0, stop = void 0, step = void 0) {\n super();\n this.start = start;\n this.stop = stop;\n this.step = step;\n }\n type = \"SliceExpression\";\n};\nvar KeywordArgumentExpression = class extends Expression {\n constructor(key, value) {\n super();\n this.key = key;\n this.value = value;\n }\n type = \"KeywordArgumentExpression\";\n};\n\n// src/parser.ts\nfunction parse(tokens) {\n const program = new Program([]);\n let current = 0;\n function expect(type, error) {\n const prev = tokens[current++];\n if (!prev || prev.type !== type) {\n throw new Error(`Parser Error: ${error}. ${prev.type} !== ${type}.`);\n }\n return prev;\n }\n function parseAny() {\n switch (tokens[current].type) {\n case TOKEN_TYPES.Text:\n return parseText();\n case TOKEN_TYPES.OpenStatement:\n return parseJinjaStatement();\n case TOKEN_TYPES.OpenExpression:\n return parseJinjaExpression();\n default:\n throw new SyntaxError(`Unexpected token type: ${tokens[current].type}`);\n }\n }\n function not(...types) {\n return current + types.length <= tokens.length && types.some((type, i) => type !== tokens[current + i].type);\n }\n function is(...types) {\n return current + types.length <= tokens.length && types.every((type, i) => type === tokens[current + i].type);\n }\n function parseText() {\n return new StringLiteral(expect(TOKEN_TYPES.Text, \"Expected text token\").value);\n }\n function parseJinjaStatement() {\n expect(TOKEN_TYPES.OpenStatement, \"Expected opening statement token\");\n let result;\n switch (tokens[current].type) {\n case TOKEN_TYPES.Set:\n ++current;\n result = parseSetStatement();\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n break;\n case TOKEN_TYPES.If:\n ++current;\n result = parseIfStatement();\n expect(TOKEN_TYPES.OpenStatement, \"Expected {% token\");\n expect(TOKEN_TYPES.EndIf, \"Expected endif token\");\n expect(TOKEN_TYPES.CloseStatement, \"Expected %} token\");\n break;\n case TOKEN_TYPES.Macro:\n ++current;\n result = parseMacroStatement();\n expect(TOKEN_TYPES.OpenStatement, \"Expected {% token\");\n expect(TOKEN_TYPES.EndMacro, \"Expected endmacro token\");\n expect(TOKEN_TYPES.CloseStatement, \"Expected %} token\");\n break;\n case TOKEN_TYPES.For:\n ++current;\n result = parseForStatement();\n expect(TOKEN_TYPES.OpenStatement, \"Expected {% token\");\n expect(TOKEN_TYPES.EndFor, \"Expected endfor token\");\n expect(TOKEN_TYPES.CloseStatement, \"Expected %} token\");\n break;\n default:\n throw new SyntaxError(`Unknown statement type: ${tokens[current].type}`);\n }\n return result;\n }\n function parseJinjaExpression() {\n expect(TOKEN_TYPES.OpenExpression, \"Expected opening expression token\");\n const result = parseExpression();\n expect(TOKEN_TYPES.CloseExpression, \"Expected closing expression token\");\n return result;\n }\n function parseSetStatement() {\n const left = parseExpression();\n if (is(TOKEN_TYPES.Equals)) {\n ++current;\n const value = parseSetStatement();\n return new SetStatement(left, value);\n }\n return left;\n }\n function parseIfStatement() {\n const test = parseExpression();\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n const body = [];\n const alternate = [];\n while (!(tokens[current]?.type === TOKEN_TYPES.OpenStatement && (tokens[current + 1]?.type === TOKEN_TYPES.ElseIf || tokens[current + 1]?.type === TOKEN_TYPES.Else || tokens[current + 1]?.type === TOKEN_TYPES.EndIf))) {\n body.push(parseAny());\n }\n if (tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type !== TOKEN_TYPES.EndIf) {\n ++current;\n if (is(TOKEN_TYPES.ElseIf)) {\n expect(TOKEN_TYPES.ElseIf, \"Expected elseif token\");\n alternate.push(parseIfStatement());\n } else {\n expect(TOKEN_TYPES.Else, \"Expected else token\");\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n while (!(tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type === TOKEN_TYPES.EndIf)) {\n alternate.push(parseAny());\n }\n }\n }\n return new If(test, body, alternate);\n }\n function parseMacroStatement() {\n const name = parsePrimaryExpression();\n if (name.type !== \"Identifier\") {\n throw new SyntaxError(`Expected identifier following macro statement`);\n }\n const args = parseArgs();\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n const body = [];\n while (not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.EndMacro)) {\n body.push(parseAny());\n }\n return new Macro(name, args, body);\n }\n function parseExpressionSequence(primary = false) {\n const fn = primary ? parsePrimaryExpression : parseExpression;\n const expressions = [fn()];\n const isTuple = is(TOKEN_TYPES.Comma);\n while (isTuple) {\n ++current;\n expressions.push(fn());\n if (!is(TOKEN_TYPES.Comma)) {\n break;\n }\n }\n return isTuple ? new TupleLiteral(expressions) : expressions[0];\n }\n function parseForStatement() {\n const loopVariable = parseExpressionSequence(true);\n if (!(loopVariable instanceof Identifier || loopVariable instanceof TupleLiteral)) {\n throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${loopVariable.type} instead`);\n }\n expect(TOKEN_TYPES.In, \"Expected `in` keyword following loop variable\");\n const iterable = parseExpression();\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n const body = [];\n while (not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.EndFor) && not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.Else)) {\n body.push(parseAny());\n }\n const alternative = [];\n if (is(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.Else)) {\n ++current;\n ++current;\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n while (not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.EndFor)) {\n alternative.push(parseAny());\n }\n }\n return new For(loopVariable, iterable, body, alternative);\n }\n function parseExpression() {\n return parseIfExpression();\n }\n function parseIfExpression() {\n const a = parseLogicalOrExpression();\n if (is(TOKEN_TYPES.If)) {\n ++current;\n const predicate = parseLogicalOrExpression();\n if (is(TOKEN_TYPES.Else)) {\n ++current;\n const b = parseLogicalOrExpression();\n return new If(predicate, [a], [b]);\n } else {\n return new SelectExpression(a, predicate);\n }\n }\n return a;\n }\n function parseLogicalOrExpression() {\n let left = parseLogicalAndExpression();\n while (is(TOKEN_TYPES.Or)) {\n const operator = tokens[current];\n ++current;\n const right = parseLogicalAndExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseLogicalAndExpression() {\n let left = parseLogicalNegationExpression();\n while (is(TOKEN_TYPES.And)) {\n const operator = tokens[current];\n ++current;\n const right = parseLogicalNegationExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseLogicalNegationExpression() {\n let right;\n while (is(TOKEN_TYPES.Not)) {\n const operator = tokens[current];\n ++current;\n const arg = parseLogicalNegationExpression();\n right = new UnaryExpression(operator, arg);\n }\n return right ?? parseComparisonExpression();\n }\n function parseComparisonExpression() {\n let left = parseAdditiveExpression();\n while (is(TOKEN_TYPES.ComparisonBinaryOperator) || is(TOKEN_TYPES.In) || is(TOKEN_TYPES.NotIn)) {\n const operator = tokens[current];\n ++current;\n const right = parseAdditiveExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseAdditiveExpression() {\n let left = parseMultiplicativeExpression();\n while (is(TOKEN_TYPES.AdditiveBinaryOperator)) {\n const operator = tokens[current];\n ++current;\n const right = parseMultiplicativeExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseCallMemberExpression() {\n const member = parseMemberExpression();\n if (is(TOKEN_TYPES.OpenParen)) {\n return parseCallExpression(member);\n }\n return member;\n }\n function parseCallExpression(callee) {\n let callExpression = new CallExpression(callee, parseArgs());\n if (is(TOKEN_TYPES.OpenParen)) {\n callExpression = parseCallExpression(callExpression);\n }\n return callExpression;\n }\n function parseArgs() {\n expect(TOKEN_TYPES.OpenParen, \"Expected opening parenthesis for arguments list\");\n const args = parseArgumentsList();\n expect(TOKEN_TYPES.CloseParen, \"Expected closing parenthesis for arguments list\");\n return args;\n }\n function parseArgumentsList() {\n const args = [];\n while (!is(TOKEN_TYPES.CloseParen)) {\n let argument = parseExpression();\n if (is(TOKEN_TYPES.Equals)) {\n ++current;\n if (!(argument instanceof Identifier)) {\n throw new SyntaxError(`Expected identifier for keyword argument`);\n }\n const value = parseExpression();\n argument = new KeywordArgumentExpression(argument, value);\n }\n args.push(argument);\n if (is(TOKEN_TYPES.Comma)) {\n ++current;\n }\n }\n return args;\n }\n function parseMemberExpressionArgumentsList() {\n const slices = [];\n let isSlice = false;\n while (!is(TOKEN_TYPES.CloseSquareBracket)) {\n if (is(TOKEN_TYPES.Colon)) {\n slices.push(void 0);\n ++current;\n isSlice = true;\n } else {\n slices.push(parseExpression());\n if (is(TOKEN_TYPES.Colon)) {\n ++current;\n isSlice = true;\n }\n }\n }\n if (slices.length === 0) {\n throw new SyntaxError(`Expected at least one argument for member/slice expression`);\n }\n if (isSlice) {\n if (slices.length > 3) {\n throw new SyntaxError(`Expected 0-3 arguments for slice expression`);\n }\n return new SliceExpression(...slices);\n }\n return slices[0];\n }\n function parseMemberExpression() {\n let object = parsePrimaryExpression();\n while (is(TOKEN_TYPES.Dot) || is(TOKEN_TYPES.OpenSquareBracket)) {\n const operator = tokens[current];\n ++current;\n let property;\n const computed = operator.type !== TOKEN_TYPES.Dot;\n if (computed) {\n property = parseMemberExpressionArgumentsList();\n expect(TOKEN_TYPES.CloseSquareBracket, \"Expected closing square bracket\");\n } else {\n property = parsePrimaryExpression();\n if (property.type !== \"Identifier\") {\n throw new SyntaxError(`Expected identifier following dot operator`);\n }\n }\n object = new MemberExpression(object, property, computed);\n }\n return object;\n }\n function parseMultiplicativeExpression() {\n let left = parseTestExpression();\n while (is(TOKEN_TYPES.MultiplicativeBinaryOperator)) {\n const operator = tokens[current];\n ++current;\n const right = parseTestExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseTestExpression() {\n let operand = parseFilterExpression();\n while (is(TOKEN_TYPES.Is)) {\n ++current;\n const negate = is(TOKEN_TYPES.Not);\n if (negate) {\n ++current;\n }\n let filter = parsePrimaryExpression();\n if (filter instanceof BooleanLiteral) {\n filter = new Identifier(filter.value.toString());\n }\n if (!(filter instanceof Identifier)) {\n throw new SyntaxError(`Expected identifier for the test`);\n }\n operand = new TestExpression(operand, negate, filter);\n }\n return operand;\n }\n function parseFilterExpression() {\n let operand = parseCallMemberExpression();\n while (is(TOKEN_TYPES.Pipe)) {\n ++current;\n let filter = parsePrimaryExpression();\n if (!(filter instanceof Identifier)) {\n throw new SyntaxError(`Expected identifier for the filter`);\n }\n if (is(TOKEN_TYPES.OpenParen)) {\n filter = parseCallExpression(filter);\n }\n operand = new FilterExpression(operand, filter);\n }\n return operand;\n }\n function parsePrimaryExpression() {\n const token = tokens[current];\n switch (token.type) {\n case TOKEN_TYPES.NumericLiteral:\n ++current;\n return new NumericLiteral(Number(token.value));\n case TOKEN_TYPES.StringLiteral:\n ++current;\n return new StringLiteral(token.value);\n case TOKEN_TYPES.BooleanLiteral:\n ++current;\n return new BooleanLiteral(token.value.toLowerCase() === \"true\");\n case TOKEN_TYPES.Identifier:\n ++current;\n return new Identifier(token.value);\n case TOKEN_TYPES.OpenParen: {\n ++current;\n const expression = parseExpressionSequence();\n if (tokens[current].type !== TOKEN_TYPES.CloseParen) {\n throw new SyntaxError(`Expected closing parenthesis, got ${tokens[current].type} instead`);\n }\n ++current;\n return expression;\n }\n case TOKEN_TYPES.OpenSquareBracket: {\n ++current;\n const values = [];\n while (!is(TOKEN_TYPES.CloseSquareBracket)) {\n values.push(parseExpression());\n if (is(TOKEN_TYPES.Comma)) {\n ++current;\n }\n }\n ++current;\n return new ArrayLiteral(values);\n }\n case TOKEN_TYPES.OpenCurlyBracket: {\n ++current;\n const values = /* @__PURE__ */ new Map();\n while (!is(TOKEN_TYPES.CloseCurlyBracket)) {\n const key = parseExpression();\n expect(TOKEN_TYPES.Colon, \"Expected colon between key and value in object literal\");\n const value = parseExpression();\n values.set(key, value);\n if (is(TOKEN_TYPES.Comma)) {\n ++current;\n }\n }\n ++current;\n return new ObjectLiteral(values);\n }\n default:\n throw new SyntaxError(`Unexpected token: ${token.type}`);\n }\n }\n while (current < tokens.length) {\n program.body.push(parseAny());\n }\n return program;\n}\n\n// src/utils.ts\nfunction range(start, stop, step = 1) {\n if (stop === void 0) {\n stop = start;\n start = 0;\n }\n const result = [];\n for (let i = start; i < stop; i += step) {\n result.push(i);\n }\n return result;\n}\nfunction slice(array, start, stop, step = 1) {\n const direction = Math.sign(step);\n if (direction >= 0) {\n start = (start ??= 0) < 0 ? Math.max(array.length + start, 0) : Math.min(start, array.length);\n stop = (stop ??= array.length) < 0 ? Math.max(array.length + stop, 0) : Math.min(stop, array.length);\n } else {\n start = (start ??= array.length - 1) < 0 ? Math.max(array.length + start, -1) : Math.min(start, array.length - 1);\n stop = (stop ??= -1) < -1 ? Math.max(array.length + stop, -1) : Math.min(stop, array.length - 1);\n }\n const result = [];\n for (let i = start; direction * i < direction * stop; i += step) {\n result.push(array[i]);\n }\n return result;\n}\nfunction titleCase(value) {\n return value.replace(/\\b\\w/g, (c) => c.toUpperCase());\n}\n\n// src/runtime.ts\nvar RuntimeValue = class {\n type = \"RuntimeValue\";\n value;\n /**\n * A collection of built-in functions for this type.\n */\n builtins = /* @__PURE__ */ new Map();\n /**\n * Creates a new RuntimeValue.\n */\n constructor(value = void 0) {\n this.value = value;\n }\n /**\n * Determines truthiness or falsiness of the runtime value.\n * This function should be overridden by subclasses if it has custom truthiness criteria.\n * @returns {BooleanValue} BooleanValue(true) if the value is truthy, BooleanValue(false) otherwise.\n */\n __bool__() {\n return new BooleanValue(!!this.value);\n }\n};\nvar NumericValue = class extends RuntimeValue {\n type = \"NumericValue\";\n};\nvar StringValue = class extends RuntimeValue {\n type = \"StringValue\";\n builtins = /* @__PURE__ */ new Map([\n [\n \"upper\",\n new FunctionValue(() => {\n return new StringValue(this.value.toUpperCase());\n })\n ],\n [\n \"lower\",\n new FunctionValue(() => {\n return new StringValue(this.value.toLowerCase());\n })\n ],\n [\n \"strip\",\n new FunctionValue(() => {\n return new StringValue(this.value.trim());\n })\n ],\n [\n \"title\",\n new FunctionValue(() => {\n return new StringValue(titleCase(this.value));\n })\n ],\n [\"length\", new NumericValue(this.value.length)]\n ]);\n};\nvar BooleanValue = class extends RuntimeValue {\n type = \"BooleanValue\";\n};\nvar ObjectValue = class extends RuntimeValue {\n type = \"ObjectValue\";\n /**\n * NOTE: necessary to override since all JavaScript arrays are considered truthy,\n * while only non-empty Python arrays are consider truthy.\n *\n * e.g.,\n * - JavaScript: {} && 5 -> 5\n * - Python: {} and 5 -> {}\n */\n __bool__() {\n return new BooleanValue(this.value.size > 0);\n }\n builtins = /* @__PURE__ */ new Map([\n [\n \"get\",\n new FunctionValue(([key, defaultValue]) => {\n if (!(key instanceof StringValue)) {\n throw new Error(`Object key must be a string: got ${key.type}`);\n }\n return this.value.get(key.value) ?? defaultValue ?? new NullValue();\n })\n ],\n [\n \"items\",\n new FunctionValue(() => {\n return new ArrayValue(\n Array.from(this.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value]))\n );\n })\n ]\n ]);\n};\nvar KeywordArgumentsValue = class extends ObjectValue {\n type = \"KeywordArgumentsValue\";\n};\nvar ArrayValue = class extends RuntimeValue {\n type = \"ArrayValue\";\n builtins = /* @__PURE__ */ new Map([[\"length\", new NumericValue(this.value.length)]]);\n /**\n * NOTE: necessary to override since all JavaScript arrays are considered truthy,\n * while only non-empty Python arrays are consider truthy.\n *\n * e.g.,\n * - JavaScript: [] && 5 -> 5\n * - Python: [] and 5 -> []\n */\n __bool__() {\n return new BooleanValue(this.value.length > 0);\n }\n};\nvar TupleValue = class extends ArrayValue {\n type = \"TupleValue\";\n};\nvar FunctionValue = class extends RuntimeValue {\n type = \"FunctionValue\";\n};\nvar NullValue = class extends RuntimeValue {\n type = \"NullValue\";\n};\nvar UndefinedValue = class extends RuntimeValue {\n type = \"UndefinedValue\";\n};\nvar Environment = class {\n constructor(parent) {\n this.parent = parent;\n }\n /**\n * The variables declared in this environment.\n */\n variables = /* @__PURE__ */ new Map([\n [\n \"namespace\",\n new FunctionValue((args) => {\n if (args.length === 0) {\n return new ObjectValue(/* @__PURE__ */ new Map());\n }\n if (args.length !== 1 || !(args[0] instanceof ObjectValue)) {\n throw new Error(\"`namespace` expects either zero arguments or a single object argument\");\n }\n return args[0];\n })\n ]\n ]);\n /**\n * The tests available in this environment.\n */\n tests = /* @__PURE__ */ new Map([\n [\"boolean\", (operand) => operand.type === \"BooleanValue\"],\n [\"callable\", (operand) => operand instanceof FunctionValue],\n [\n \"odd\",\n (operand) => {\n if (operand.type !== \"NumericValue\") {\n throw new Error(`Cannot apply test \"odd\" to type: ${operand.type}`);\n }\n return operand.value % 2 !== 0;\n }\n ],\n [\n \"even\",\n (operand) => {\n if (operand.type !== \"NumericValue\") {\n throw new Error(`Cannot apply test \"even\" to type: ${operand.type}`);\n }\n return operand.value % 2 === 0;\n }\n ],\n [\"false\", (operand) => operand.type === \"BooleanValue\" && !operand.value],\n [\"true\", (operand) => operand.type === \"BooleanValue\" && operand.value],\n [\"string\", (operand) => operand.type === \"StringValue\"],\n [\"number\", (operand) => operand.type === \"NumericValue\"],\n [\"integer\", (operand) => operand.type === \"NumericValue\" && Number.isInteger(operand.value)],\n [\"iterable\", (operand) => operand instanceof ArrayValue || operand instanceof StringValue],\n [\n \"lower\",\n (operand) => {\n const str = operand.value;\n return operand.type === \"StringValue\" && str === str.toLowerCase();\n }\n ],\n [\n \"upper\",\n (operand) => {\n const str = operand.value;\n return operand.type === \"StringValue\" && str === str.toUpperCase();\n }\n ],\n [\"none\", (operand) => operand.type === \"NullValue\"],\n [\"defined\", (operand) => operand.type !== \"UndefinedValue\"],\n [\"undefined\", (operand) => operand.type === \"UndefinedValue\"],\n [\"equalto\", (a, b) => a.value === b.value],\n [\"eq\", (a, b) => a.value === b.value]\n ]);\n /**\n * Set the value of a variable in the current environment.\n */\n set(name, value) {\n return this.declareVariable(name, convertToRuntimeValues(value));\n }\n declareVariable(name, value) {\n if (this.variables.has(name)) {\n throw new SyntaxError(`Variable already declared: ${name}`);\n }\n this.variables.set(name, value);\n return value;\n }\n // private assignVariable(name: string, value: AnyRuntimeValue): AnyRuntimeValue {\n // \tconst env = this.resolve(name);\n // \tenv.variables.set(name, value);\n // \treturn value;\n // }\n /**\n * Set variable in the current scope.\n * See https://jinja.palletsprojects.com/en/3.0.x/templates/#assignments for more information.\n */\n setVariable(name, value) {\n this.variables.set(name, value);\n return value;\n }\n /**\n * Resolve the environment in which the variable is declared.\n * @param {string} name The name of the variable.\n * @returns {Environment} The environment in which the variable is declared.\n */\n resolve(name) {\n if (this.variables.has(name)) {\n return this;\n }\n if (this.parent) {\n return this.parent.resolve(name);\n }\n throw new Error(`Unknown variable: ${name}`);\n }\n lookupVariable(name) {\n try {\n return this.resolve(name).variables.get(name) ?? new UndefinedValue();\n } catch {\n return new UndefinedValue();\n }\n }\n};\nvar Interpreter = class {\n global;\n constructor(env) {\n this.global = env ?? new Environment();\n }\n /**\n * Run the program.\n */\n run(program) {\n return this.evaluate(program, this.global);\n }\n /**\n * Evaluates expressions following the binary operation type.\n */\n evaluateBinaryExpression(node, environment) {\n const left = this.evaluate(node.left, environment);\n switch (node.operator.value) {\n case \"and\":\n return left.__bool__().value ? this.evaluate(node.right, environment) : left;\n case \"or\":\n return left.__bool__().value ? left : this.evaluate(node.right, environment);\n }\n const right = this.evaluate(node.right, environment);\n switch (node.operator.value) {\n case \"==\":\n return new BooleanValue(left.value == right.value);\n case \"!=\":\n return new BooleanValue(left.value != right.value);\n }\n if (left instanceof UndefinedValue || right instanceof UndefinedValue) {\n throw new Error(\"Cannot perform operation on undefined values\");\n } else if (left instanceof NullValue || right instanceof NullValue) {\n throw new Error(\"Cannot perform operation on null values\");\n } else if (left instanceof NumericValue && right instanceof NumericValue) {\n switch (node.operator.value) {\n case \"+\":\n return new NumericValue(left.value + right.value);\n case \"-\":\n return new NumericValue(left.value - right.value);\n case \"*\":\n return new NumericValue(left.value * right.value);\n case \"/\":\n return new NumericValue(left.value / right.value);\n case \"%\":\n return new NumericValue(left.value % right.value);\n case \"<\":\n return new BooleanValue(left.value < right.value);\n case \">\":\n return new BooleanValue(left.value > right.value);\n case \">=\":\n return new BooleanValue(left.value >= right.value);\n case \"<=\":\n return new BooleanValue(left.value <= right.value);\n }\n } else if (left instanceof ArrayValue && right instanceof ArrayValue) {\n switch (node.operator.value) {\n case \"+\":\n return new ArrayValue(left.value.concat(right.value));\n }\n } else if (right instanceof ArrayValue) {\n const member = right.value.find((x) => x.value === left.value) !== void 0;\n switch (node.operator.value) {\n case \"in\":\n return new BooleanValue(member);\n case \"not in\":\n return new BooleanValue(!member);\n }\n }\n if (left instanceof StringValue || right instanceof StringValue) {\n switch (node.operator.value) {\n case \"+\":\n return new StringValue(left.value.toString() + right.value.toString());\n }\n }\n if (left instanceof StringValue && right instanceof StringValue) {\n switch (node.operator.value) {\n case \"in\":\n return new BooleanValue(right.value.includes(left.value));\n case \"not in\":\n return new BooleanValue(!right.value.includes(left.value));\n }\n }\n if (left instanceof StringValue && right instanceof ObjectValue) {\n switch (node.operator.value) {\n case \"in\":\n return new BooleanValue(right.value.has(left.value));\n case \"not in\":\n return new BooleanValue(!right.value.has(left.value));\n }\n }\n throw new SyntaxError(`Unknown operator \"${node.operator.value}\" between ${left.type} and ${right.type}`);\n }\n evaluateArguments(args, environment) {\n const positionalArguments = [];\n const keywordArguments = /* @__PURE__ */ new Map();\n for (const argument of args) {\n if (argument.type === \"KeywordArgumentExpression\") {\n const kwarg = argument;\n keywordArguments.set(kwarg.key.value, this.evaluate(kwarg.value, environment));\n } else {\n if (keywordArguments.size > 0) {\n throw new Error(\"Positional arguments must come before keyword arguments\");\n }\n positionalArguments.push(this.evaluate(argument, environment));\n }\n }\n return [positionalArguments, keywordArguments];\n }\n /**\n * Evaluates expressions following the filter operation type.\n */\n evaluateFilterExpression(node, environment) {\n const operand = this.evaluate(node.operand, environment);\n if (node.filter.type === \"Identifier\") {\n const filter = node.filter;\n if (filter.value === \"tojson\") {\n return new StringValue(toJSON(operand));\n }\n if (operand instanceof ArrayValue) {\n switch (filter.value) {\n case \"list\":\n return operand;\n case \"first\":\n return operand.value[0];\n case \"last\":\n return operand.value[operand.value.length - 1];\n case \"length\":\n return new NumericValue(operand.value.length);\n case \"reverse\":\n return new ArrayValue(operand.value.reverse());\n case \"sort\":\n return new ArrayValue(\n operand.value.sort((a, b) => {\n if (a.type !== b.type) {\n throw new Error(`Cannot compare different types: ${a.type} and ${b.type}`);\n }\n switch (a.type) {\n case \"NumericValue\":\n return a.value - b.value;\n case \"StringValue\":\n return a.value.localeCompare(b.value);\n default:\n throw new Error(`Cannot compare type: ${a.type}`);\n }\n })\n );\n default:\n throw new Error(`Unknown ArrayValue filter: ${filter.value}`);\n }\n } else if (operand instanceof StringValue) {\n switch (filter.value) {\n case \"length\":\n return new NumericValue(operand.value.length);\n case \"upper\":\n return new StringValue(operand.value.toUpperCase());\n case \"lower\":\n return new StringValue(operand.value.toLowerCase());\n case \"title\":\n return new StringValue(titleCase(operand.value));\n case \"capitalize\":\n return new StringValue(operand.value.charAt(0).toUpperCase() + operand.value.slice(1));\n case \"trim\":\n return new StringValue(operand.value.trim());\n case \"indent\":\n return new StringValue(\n operand.value.split(\"\\n\").map(\n (x, i) => (\n // By default, don't indent the first line or empty lines\n i === 0 || x.length === 0 ? x : \" \" + x\n )\n ).join(\"\\n\")\n );\n case \"string\":\n return operand;\n default:\n throw new Error(`Unknown StringValue filter: ${filter.value}`);\n }\n } else if (operand instanceof NumericValue) {\n switch (filter.value) {\n case \"abs\":\n return new NumericValue(Math.abs(operand.value));\n default:\n throw new Error(`Unknown NumericValue filter: ${filter.value}`);\n }\n } else if (operand instanceof ObjectValue) {\n switch (filter.value) {\n case \"items\":\n return new ArrayValue(\n Array.from(operand.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value]))\n );\n case \"length\":\n return new NumericValue(operand.value.size);\n default:\n throw new Error(`Unknown ObjectValue filter: ${filter.value}`);\n }\n }\n throw new Error(`Cannot apply filter \"${filter.value}\" to type: ${operand.type}`);\n } else if (node.filter.type === \"CallExpression\") {\n const filter = node.filter;\n if (filter.callee.type !== \"Identifier\") {\n throw new Error(`Unknown filter: ${filter.callee.type}`);\n }\n const filterName = filter.callee.value;\n if (filterName === \"tojson\") {\n const [, kwargs] = this.evaluateArguments(filter.args, environment);\n const indent = kwargs.get(\"indent\") ?? new NullValue();\n if (!(indent instanceof NumericValue || indent instanceof NullValue)) {\n throw new Error(\"If set, indent must be a number\");\n }\n return new StringValue(toJSON(operand, indent.value));\n }\n if (operand instanceof ArrayValue) {\n switch (filterName) {\n case \"selectattr\": {\n if (operand.value.some((x) => !(x instanceof ObjectValue))) {\n throw new Error(\"`selectattr` can only be applied to array of objects\");\n }\n if (filter.args.some((x) => x.type !== \"StringLiteral\")) {\n throw new Error(\"arguments of `selectattr` must be strings\");\n }\n const [attr, testName, value] = filter.args.map((x) => this.evaluate(x, environment));\n let testFunction;\n if (testName) {\n const test = environment.tests.get(testName.value);\n if (!test) {\n throw new Error(`Unknown test: ${testName.value}`);\n }\n testFunction = test;\n } else {\n testFunction = (...x) => x[0].__bool__().value;\n }\n const filtered = operand.value.filter((item) => {\n const a = item.value.get(attr.value);\n if (a) {\n return testFunction(a, value);\n }\n return false;\n });\n return new ArrayValue(filtered);\n }\n case \"map\": {\n const [, kwargs] = this.evaluateArguments(filter.args, environment);\n if (kwargs.has(\"attribute\")) {\n const attr = kwargs.get(\"attribute\");\n if (!(attr instanceof StringValue)) {\n throw new Error(\"attribute must be a string\");\n }\n const defaultValue = kwargs.get(\"default\");\n const mapped = operand.value.map((item) => {\n if (!(item instanceof ObjectValue)) {\n throw new Error(\"items in map must be an object\");\n }\n return item.value.get(attr.value) ?? defaultValue ?? new UndefinedValue();\n });\n return new ArrayValue(mapped);\n } else {\n throw new Error(\"`map` expressions without `attribute` set are not currently supported.\");\n }\n }\n }\n throw new Error(`Unknown ArrayValue filter: ${filterName}`);\n } else if (operand instanceof StringValue) {\n switch (filterName) {\n case \"indent\": {\n const [args, kwargs] = this.evaluateArguments(filter.args, environment);\n const width = args.at(0) ?? kwargs.get(\"width\") ?? new NumericValue(4);\n if (!(width instanceof NumericValue)) {\n throw new Error(\"width must be a number\");\n }\n const first = args.at(1) ?? kwargs.get(\"first\") ?? new BooleanValue(false);\n const blank = args.at(2) ?? kwargs.get(\"blank\") ?? new BooleanValue(false);\n const lines = operand.value.split(\"\\n\");\n const indent = \" \".repeat(width.value);\n const indented = lines.map(\n (x, i) => !first.value && i === 0 || !blank.value && x.length === 0 ? x : indent + x\n );\n return new StringValue(indented.join(\"\\n\"));\n }\n }\n throw new Error(`Unknown StringValue filter: ${filterName}`);\n } else {\n throw new Error(`Cannot apply filter \"${filterName}\" to type: ${operand.type}`);\n }\n }\n throw new Error(`Unknown filter: ${node.filter.type}`);\n }\n /**\n * Evaluates expressions following the test operation type.\n */\n evaluateTestExpression(node, environment) {\n const operand = this.evaluate(node.operand, environment);\n const test = environment.tests.get(node.test.value);\n if (!test) {\n throw new Error(`Unknown test: ${node.test.value}`);\n }\n const result = test(operand);\n return new BooleanValue(node.negate ? !result : result);\n }\n /**\n * Evaluates expressions following the unary operation type.\n */\n evaluateUnaryExpression(node, environment) {\n const argument = this.evaluate(node.argument, environment);\n switch (node.operator.value) {\n case \"not\":\n return new BooleanValue(!argument.value);\n default:\n throw new SyntaxError(`Unknown operator: ${node.operator.value}`);\n }\n }\n evalProgram(program, environment) {\n return this.evaluateBlock(program.body, environment);\n }\n evaluateBlock(statements, environment) {\n let result = \"\";\n for (const statement of statements) {\n const lastEvaluated = this.evaluate(statement, environment);\n if (lastEvaluated.type !== \"NullValue\" && lastEvaluated.type !== \"UndefinedValue\") {\n result += lastEvaluated.value;\n }\n }\n return new StringValue(result);\n }\n evaluateIdentifier(node, environment) {\n return environment.lookupVariable(node.value);\n }\n evaluateCallExpression(expr, environment) {\n const [args, kwargs] = this.evaluateArguments(expr.args, environment);\n if (kwargs.size > 0) {\n args.push(new KeywordArgumentsValue(kwargs));\n }\n const fn = this.evaluate(expr.callee, environment);\n if (fn.type !== \"FunctionValue\") {\n throw new Error(`Cannot call something that is not a function: got ${fn.type}`);\n }\n return fn.value(args, environment);\n }\n evaluateSliceExpression(object, expr, environment) {\n if (!(object instanceof ArrayValue || object instanceof StringValue)) {\n throw new Error(\"Slice object must be an array or string\");\n }\n const start = this.evaluate(expr.start, environment);\n const stop = this.evaluate(expr.stop, environment);\n const step = this.evaluate(expr.step, environment);\n if (!(start instanceof NumericValue || start instanceof UndefinedValue)) {\n throw new Error(\"Slice start must be numeric or undefined\");\n }\n if (!(stop instanceof NumericValue || stop instanceof UndefinedValue)) {\n throw new Error(\"Slice stop must be numeric or undefined\");\n }\n if (!(step instanceof NumericValue || step instanceof UndefinedValue)) {\n throw new Error(\"Slice step must be numeric or undefined\");\n }\n if (object instanceof ArrayValue) {\n return new ArrayValue(slice(object.value, start.value, stop.value, step.value));\n } else {\n return new StringValue(slice(Array.from(object.value), start.value, stop.value, step.value).join(\"\"));\n }\n }\n evaluateMemberExpression(expr, environment) {\n const object = this.evaluate(expr.object, environment);\n let property;\n if (expr.computed) {\n if (expr.property.type === \"SliceExpression\") {\n return this.evaluateSliceExpression(object, expr.property, environment);\n } else {\n property = this.evaluate(expr.property, environment);\n }\n } else {\n property = new StringValue(expr.property.value);\n }\n let value;\n if (object instanceof ObjectValue) {\n if (!(property instanceof StringValue)) {\n throw new Error(`Cannot access property with non-string: got ${property.type}`);\n }\n value = object.value.get(property.value) ?? object.builtins.get(property.value);\n } else if (object instanceof ArrayValue || object instanceof StringValue) {\n if (property instanceof NumericValue) {\n value = object.value.at(property.value);\n if (object instanceof StringValue) {\n value = new StringValue(object.value.at(property.value));\n }\n } else if (property instanceof StringValue) {\n value = object.builtins.get(property.value);\n } else {\n throw new Error(`Cannot access property with non-string/non-number: got ${property.type}`);\n }\n } else {\n if (!(property instanceof StringValue)) {\n throw new Error(`Cannot access property with non-string: got ${property.type}`);\n }\n value = object.builtins.get(property.value);\n }\n return value instanceof RuntimeValue ? value : new UndefinedValue();\n }\n evaluateSet(node, environment) {\n const rhs = this.evaluate(node.value, environment);\n if (node.assignee.type === \"Identifier\") {\n const variableName = node.assignee.value;\n environment.setVariable(variableName, rhs);\n } else if (node.assignee.type === \"MemberExpression\") {\n const member = node.assignee;\n const object = this.evaluate(member.object, environment);\n if (!(object instanceof ObjectValue)) {\n throw new Error(\"Cannot assign to member of non-object\");\n }\n if (member.property.type !== \"Identifier\") {\n throw new Error(\"Cannot assign to member with non-identifier property\");\n }\n object.value.set(member.property.value, rhs);\n } else {\n throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(node.assignee)}`);\n }\n return new NullValue();\n }\n evaluateIf(node, environment) {\n const test = this.evaluate(node.test, environment);\n return this.evaluateBlock(test.__bool__().value ? node.body : node.alternate, environment);\n }\n evaluateFor(node, environment) {\n const scope = new Environment(environment);\n let test, iterable;\n if (node.iterable.type === \"SelectExpression\") {\n const select = node.iterable;\n iterable = this.evaluate(select.iterable, scope);\n test = select.test;\n } else {\n iterable = this.evaluate(node.iterable, scope);\n }\n if (!(iterable instanceof ArrayValue)) {\n throw new Error(`Expected iterable type in for loop: got ${iterable.type}`);\n }\n const items = [];\n const scopeUpdateFunctions = [];\n for (let i = 0; i < iterable.value.length; ++i) {\n const loopScope = new Environment(scope);\n const current = iterable.value[i];\n let scopeUpdateFunction;\n if (node.loopvar.type === \"Identifier\") {\n scopeUpdateFunction = (scope2) => scope2.setVariable(node.loopvar.value, current);\n } else if (node.loopvar.type === \"TupleLiteral\") {\n const loopvar = node.loopvar;\n if (current.type !== \"ArrayValue\") {\n throw new Error(`Cannot unpack non-iterable type: ${current.type}`);\n }\n const c = current;\n if (loopvar.value.length !== c.value.length) {\n throw new Error(`Too ${loopvar.value.length > c.value.length ? \"few\" : \"many\"} items to unpack`);\n }\n scopeUpdateFunction = (scope2) => {\n for (let j = 0; j < loopvar.value.length; ++j) {\n if (loopvar.value[j].type !== \"Identifier\") {\n throw new Error(`Cannot unpack non-identifier type: ${loopvar.value[j].type}`);\n }\n scope2.setVariable(loopvar.value[j].value, c.value[j]);\n }\n };\n } else {\n throw new Error(`Invalid loop variable(s): ${node.loopvar.type}`);\n }\n if (test) {\n scopeUpdateFunction(loopScope);\n const testValue = this.evaluate(test, loopScope);\n if (!testValue.__bool__().value) {\n continue;\n }\n }\n items.push(current);\n scopeUpdateFunctions.push(scopeUpdateFunction);\n }\n let result = \"\";\n let noIteration = true;\n for (let i = 0; i < items.length; ++i) {\n const loop = /* @__PURE__ */ new Map([\n [\"index\", new NumericValue(i + 1)],\n [\"index0\", new NumericValue(i)],\n [\"revindex\", new NumericValue(items.length - i)],\n [\"revindex0\", new NumericValue(items.length - i - 1)],\n [\"first\", new BooleanValue(i === 0)],\n [\"last\", new BooleanValue(i === items.length - 1)],\n [\"length\", new NumericValue(items.length)],\n [\"previtem\", i > 0 ? items[i - 1] : new UndefinedValue()],\n [\"nextitem\", i < items.length - 1 ? items[i + 1] : new UndefinedValue()]\n ]);\n scope.setVariable(\"loop\", new ObjectValue(loop));\n scopeUpdateFunctions[i](scope);\n const evaluated = this.evaluateBlock(node.body, scope);\n result += evaluated.value;\n noIteration = false;\n }\n if (noIteration) {\n const defaultEvaluated = this.evaluateBlock(node.defaultBlock, scope);\n result += defaultEvaluated.value;\n }\n return new StringValue(result);\n }\n /**\n * See https://jinja.palletsprojects.com/en/3.1.x/templates/#macros for more information.\n */\n evaluateMacro(node, environment) {\n environment.setVariable(\n node.name.value,\n new FunctionValue((args, scope) => {\n const macroScope = new Environment(scope);\n args = args.slice();\n let kwargs;\n if (args.at(-1)?.type === \"KeywordArgumentsValue\") {\n kwargs = args.pop();\n }\n for (let i = 0; i < node.args.length; ++i) {\n const nodeArg = node.args[i];\n const passedArg = args[i];\n if (nodeArg.type === \"Identifier\") {\n const identifier = nodeArg;\n if (!passedArg) {\n throw new Error(`Missing positional argument: ${identifier.value}`);\n }\n macroScope.setVariable(identifier.value, passedArg);\n } else if (nodeArg.type === \"KeywordArgumentExpression\") {\n const kwarg = nodeArg;\n const value = passedArg ?? // Try positional arguments first\n kwargs?.value.get(kwarg.key.value) ?? // Look in user-passed kwargs\n this.evaluate(kwarg.value, macroScope);\n macroScope.setVariable(kwarg.key.value, value);\n } else {\n throw new Error(`Unknown argument type: ${nodeArg.type}`);\n }\n }\n return this.evaluateBlock(node.body, macroScope);\n })\n );\n return new NullValue();\n }\n evaluate(statement, environment) {\n if (statement === void 0)\n return new UndefinedValue();\n switch (statement.type) {\n case \"Program\":\n return this.evalProgram(statement, environment);\n case \"Set\":\n return this.evaluateSet(statement, environment);\n case \"If\":\n return this.evaluateIf(statement, environment);\n case \"For\":\n return this.evaluateFor(statement, environment);\n case \"Macro\":\n return this.evaluateMacro(statement, environment);\n case \"NumericLiteral\":\n return new NumericValue(Number(statement.value));\n case \"StringLiteral\":\n return new StringValue(statement.value);\n case \"BooleanLiteral\":\n return new BooleanValue(statement.value);\n case \"ArrayLiteral\":\n return new ArrayValue(statement.value.map((x) => this.evaluate(x, environment)));\n case \"TupleLiteral\":\n return new TupleValue(statement.value.map((x) => this.evaluate(x, environment)));\n case \"ObjectLiteral\": {\n const mapping = /* @__PURE__ */ new Map();\n for (const [key, value] of statement.value) {\n const evaluatedKey = this.evaluate(key, environment);\n if (!(evaluatedKey instanceof StringValue)) {\n throw new Error(`Object keys must be strings: got ${evaluatedKey.type}`);\n }\n mapping.set(evaluatedKey.value, this.evaluate(value, environment));\n }\n return new ObjectValue(mapping);\n }\n case \"Identifier\":\n return this.evaluateIdentifier(statement, environment);\n case \"CallExpression\":\n return this.evaluateCallExpression(statement, environment);\n case \"MemberExpression\":\n return this.evaluateMemberExpression(statement, environment);\n case \"UnaryExpression\":\n return this.evaluateUnaryExpression(statement, environment);\n case \"BinaryExpression\":\n return this.evaluateBinaryExpression(statement, environment);\n case \"FilterExpression\":\n return this.evaluateFilterExpression(statement, environment);\n case \"TestExpression\":\n return this.evaluateTestExpression(statement, environment);\n default:\n throw new SyntaxError(`Unknown node type: ${statement.type}`);\n }\n }\n};\nfunction convertToRuntimeValues(input) {\n switch (typeof input) {\n case \"number\":\n return new NumericValue(input);\n case \"string\":\n return new StringValue(input);\n case \"boolean\":\n return new BooleanValue(input);\n case \"undefined\":\n return new UndefinedValue();\n case \"object\":\n if (input === null) {\n return new NullValue();\n } else if (Array.isArray(input)) {\n return new ArrayValue(input.map(convertToRuntimeValues));\n } else {\n return new ObjectValue(\n new Map(Object.entries(input).map(([key, value]) => [key, convertToRuntimeValues(value)]))\n );\n }\n case \"function\":\n return new FunctionValue((args, _scope) => {\n const result = input(...args.map((x) => x.value)) ?? null;\n return convertToRuntimeValues(result);\n });\n default:\n throw new Error(`Cannot convert to runtime value: ${input}`);\n }\n}\nfunction toJSON(input, indent, depth) {\n const currentDepth = depth ?? 0;\n switch (input.type) {\n case \"NullValue\":\n case \"UndefinedValue\":\n return \"null\";\n case \"NumericValue\":\n case \"StringValue\":\n case \"BooleanValue\":\n return JSON.stringify(input.value);\n case \"ArrayValue\":\n case \"ObjectValue\": {\n const indentValue = indent ? \" \".repeat(indent) : \"\";\n const basePadding = \"\\n\" + indentValue.repeat(currentDepth);\n const childrenPadding = basePadding + indentValue;\n if (input.type === \"ArrayValue\") {\n const core = input.value.map((x) => toJSON(x, indent, currentDepth + 1));\n return indent ? `[${childrenPadding}${core.join(`,${childrenPadding}`)}${basePadding}]` : `[${core.join(\", \")}]`;\n } else {\n const core = Array.from(input.value.entries()).map(([key, value]) => {\n const v = `\"${key}\": ${toJSON(value, indent, currentDepth + 1)}`;\n return indent ? `${childrenPadding}${v}` : v;\n });\n return indent ? `{${core.join(\",\")}${basePadding}}` : `{${core.join(\", \")}}`;\n }\n }\n default:\n throw new Error(`Cannot convert to JSON: ${input.type}`);\n }\n}\n\n// src/index.ts\nvar Template = class {\n parsed;\n /**\n * @param {string} template The template string\n */\n constructor(template) {\n const tokens = tokenize(template, {\n lstrip_blocks: true,\n trim_blocks: true\n });\n this.parsed = parse(tokens);\n }\n render(items) {\n const env = new Environment();\n env.set(\"false\", false);\n env.set(\"true\", true);\n env.set(\"raise_exception\", (args) => {\n throw new Error(args);\n });\n env.set(\"range\", range);\n for (const [key, value] of Object.entries(items)) {\n env.set(key, value);\n }\n const interpreter = new Interpreter(env);\n const result = interpreter.run(this.parsed);\n return result.value;\n }\n};\nexport {\n Environment,\n Interpreter,\n Template,\n parse,\n tokenize\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nconst backends = new Map();\nconst backendsSortedByPriority = [];\n/**\n * Register a backend.\n *\n * @param name - the name as a key to lookup as an execution provider.\n * @param backend - the backend object.\n * @param priority - an integer indicating the priority of the backend. Higher number means higher priority. if priority\n * < 0, it will be considered as a 'beta' version and will not be used as a fallback backend by default.\n *\n * @ignore\n */\nexport const registerBackend = (name, backend, priority) => {\n if (backend && typeof backend.init === 'function' && typeof backend.createInferenceSessionHandler === 'function') {\n const currentBackend = backends.get(name);\n if (currentBackend === undefined) {\n backends.set(name, { backend, priority });\n }\n else if (currentBackend.priority > priority) {\n // same name is already registered with a higher priority. skip registeration.\n return;\n }\n else if (currentBackend.priority === priority) {\n if (currentBackend.backend !== backend) {\n throw new Error(`cannot register backend \"${name}\" using priority ${priority}`);\n }\n }\n if (priority >= 0) {\n const i = backendsSortedByPriority.indexOf(name);\n if (i !== -1) {\n backendsSortedByPriority.splice(i, 1);\n }\n for (let i = 0; i < backendsSortedByPriority.length; i++) {\n if (backends.get(backendsSortedByPriority[i]).priority <= priority) {\n backendsSortedByPriority.splice(i, 0, name);\n return;\n }\n }\n backendsSortedByPriority.push(name);\n }\n return;\n }\n throw new TypeError('not a valid backend');\n};\n/**\n * Try to resolve and initialize a backend.\n *\n * @param backendName - the name of the backend.\n * @returns the backend instance if resolved and initialized successfully, or an error message if failed.\n */\nconst tryResolveAndInitializeBackend = async (backendName) => {\n const backendInfo = backends.get(backendName);\n if (!backendInfo) {\n return 'backend not found.';\n }\n if (backendInfo.initialized) {\n return backendInfo.backend;\n }\n else if (backendInfo.aborted) {\n return backendInfo.error;\n }\n else {\n const isInitializing = !!backendInfo.initPromise;\n try {\n if (!isInitializing) {\n backendInfo.initPromise = backendInfo.backend.init(backendName);\n }\n await backendInfo.initPromise;\n backendInfo.initialized = true;\n return backendInfo.backend;\n }\n catch (e) {\n if (!isInitializing) {\n backendInfo.error = `${e}`;\n backendInfo.aborted = true;\n }\n return backendInfo.error;\n }\n finally {\n delete backendInfo.initPromise;\n }\n }\n};\n/**\n * Resolve execution providers from the specific session options.\n *\n * @param options - the session options object.\n * @returns a promise that resolves to a tuple of an initialized backend instance and a session options object with\n * filtered EP list.\n *\n * @ignore\n */\nexport const resolveBackendAndExecutionProviders = async (options) => {\n // extract backend hints from session options\n const eps = options.executionProviders || [];\n const backendHints = eps.map(i => typeof i === 'string' ? i : i.name);\n const backendNames = backendHints.length === 0 ? backendsSortedByPriority : backendHints;\n // try to resolve and initialize all requested backends\n let backend;\n const errors = [];\n const availableBackendNames = new Set();\n for (const backendName of backendNames) {\n const resolveResult = await tryResolveAndInitializeBackend(backendName);\n if (typeof resolveResult === 'string') {\n errors.push({ name: backendName, err: resolveResult });\n }\n else {\n if (!backend) {\n backend = resolveResult;\n }\n if (backend === resolveResult) {\n availableBackendNames.add(backendName);\n }\n }\n }\n // if no backend is available, throw error.\n if (!backend) {\n throw new Error(`no available backend found. ERR: ${errors.map(e => `[${e.name}] ${e.err}`).join(', ')}`);\n }\n // for each explicitly requested backend, if it's not available, output warning message.\n for (const { name, err } of errors) {\n if (backendHints.includes(name)) {\n // eslint-disable-next-line no-console\n console.warn(`removing requested execution provider \"${name}\" from session options because it is not available: ${err}`);\n }\n }\n const filteredEps = eps.filter(i => availableBackendNames.has(typeof i === 'string' ? i : i.name));\n return [\n backend, new Proxy(options, {\n get: (target, prop) => {\n if (prop === 'executionProviders') {\n return filteredEps;\n }\n return Reflect.get(target, prop);\n }\n })\n ];\n};\n//# sourceMappingURL=backend-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nexport { registerBackend } from './backend-impl.js';\n//# sourceMappingURL=backend.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { version } from './version.js';\nlet logLevelValue = 'warning';\nexport const env = {\n wasm: {},\n webgl: {},\n webgpu: {},\n versions: { common: version },\n set logLevel(value) {\n if (value === undefined) {\n return;\n }\n if (typeof value !== 'string' || ['verbose', 'info', 'warning', 'error', 'fatal'].indexOf(value) === -1) {\n throw new Error(`Unsupported logging level: ${value}`);\n }\n logLevelValue = value;\n },\n get logLevel() {\n return logLevelValue;\n },\n};\n// set property 'logLevel' so that they can be correctly transferred to worker by `postMessage()`.\nObject.defineProperty(env, 'logLevel', { enumerable: true });\n//# sourceMappingURL=env-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { env as envImpl } from './env-impl.js';\n/**\n * Represent a set of flags as a global singleton.\n */\nexport const env = envImpl;\n//# sourceMappingURL=env.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n/**\n * # ONNX Runtime JavaScript API\n *\n * ONNX Runtime JavaScript API is a unified API for all JavaScript usages, including the following NPM packages:\n *\n * - [onnxruntime-node](https://www.npmjs.com/package/onnxruntime-node)\n * - [onnxruntime-web](https://www.npmjs.com/package/onnxruntime-web)\n * - [onnxruntime-react-native](https://www.npmjs.com/package/onnxruntime-react-native)\n *\n * See also:\n * - [Get Started](https://onnxruntime.ai/docs/get-started/with-javascript/)\n * - [Inference examples](https://github.com/microsoft/onnxruntime-inference-examples/tree/main/js)\n *\n * @packageDocumentation\n */\nexport * from './backend.js';\nexport * from './env.js';\nexport * from './inference-session.js';\nexport * from './tensor.js';\nexport * from './tensor-conversion.js';\nexport * from './tensor-factory.js';\nexport * from './trace.js';\nexport * from './onnx-model.js';\nexport * from './onnx-value.js';\nexport * from './training-session.js';\n//# sourceMappingURL=index.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { resolveBackendAndExecutionProviders } from './backend-impl.js';\nimport { Tensor } from './tensor.js';\nimport { TRACE_FUNC_BEGIN, TRACE_FUNC_END } from './trace.js';\nexport class InferenceSession {\n constructor(handler) {\n this.handler = handler;\n }\n async run(feeds, arg1, arg2) {\n TRACE_FUNC_BEGIN();\n const fetches = {};\n let options = {};\n // check inputs\n if (typeof feeds !== 'object' || feeds === null || feeds instanceof Tensor || Array.isArray(feeds)) {\n throw new TypeError('\\'feeds\\' must be an object that use input names as keys and OnnxValue as corresponding values.');\n }\n let isFetchesEmpty = true;\n // determine which override is being used\n if (typeof arg1 === 'object') {\n if (arg1 === null) {\n throw new TypeError('Unexpected argument[1]: cannot be null.');\n }\n if (arg1 instanceof Tensor) {\n throw new TypeError('\\'fetches\\' cannot be a Tensor');\n }\n if (Array.isArray(arg1)) {\n if (arg1.length === 0) {\n throw new TypeError('\\'fetches\\' cannot be an empty array.');\n }\n isFetchesEmpty = false;\n // output names\n for (const name of arg1) {\n if (typeof name !== 'string') {\n throw new TypeError('\\'fetches\\' must be a string array or an object.');\n }\n if (this.outputNames.indexOf(name) === -1) {\n throw new RangeError(`'fetches' contains invalid output name: ${name}.`);\n }\n fetches[name] = null;\n }\n if (typeof arg2 === 'object' && arg2 !== null) {\n options = arg2;\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else {\n // decide whether arg1 is fetches or options\n // if any output name is present and its value is valid OnnxValue, we consider it fetches\n let isFetches = false;\n const arg1Keys = Object.getOwnPropertyNames(arg1);\n for (const name of this.outputNames) {\n if (arg1Keys.indexOf(name) !== -1) {\n const v = arg1[name];\n if (v === null || v instanceof Tensor) {\n isFetches = true;\n isFetchesEmpty = false;\n fetches[name] = v;\n }\n }\n }\n if (isFetches) {\n if (typeof arg2 === 'object' && arg2 !== null) {\n options = arg2;\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else {\n options = arg1;\n }\n }\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('Unexpected argument[1]: must be \\'fetches\\' or \\'options\\'.');\n }\n // check if all inputs are in feed\n for (const name of this.inputNames) {\n if (typeof feeds[name] === 'undefined') {\n throw new Error(`input '${name}' is missing in 'feeds'.`);\n }\n }\n // if no fetches is specified, we use the full output names list\n if (isFetchesEmpty) {\n for (const name of this.outputNames) {\n fetches[name] = null;\n }\n }\n // feeds, fetches and options are prepared\n const results = await this.handler.run(feeds, fetches, options);\n const returnValue = {};\n for (const key in results) {\n if (Object.hasOwnProperty.call(results, key)) {\n const result = results[key];\n if (result instanceof Tensor) {\n returnValue[key] = result;\n }\n else {\n returnValue[key] = new Tensor(result.type, result.data, result.dims);\n }\n }\n }\n TRACE_FUNC_END();\n return returnValue;\n }\n async release() {\n return this.handler.dispose();\n }\n static async create(arg0, arg1, arg2, arg3) {\n TRACE_FUNC_BEGIN();\n // either load from a file or buffer\n let filePathOrUint8Array;\n let options = {};\n if (typeof arg0 === 'string') {\n filePathOrUint8Array = arg0;\n if (typeof arg1 === 'object' && arg1 !== null) {\n options = arg1;\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else if (arg0 instanceof Uint8Array) {\n filePathOrUint8Array = arg0;\n if (typeof arg1 === 'object' && arg1 !== null) {\n options = arg1;\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else if (arg0 instanceof ArrayBuffer ||\n (typeof SharedArrayBuffer !== 'undefined' && arg0 instanceof SharedArrayBuffer)) {\n const buffer = arg0;\n let byteOffset = 0;\n let byteLength = arg0.byteLength;\n if (typeof arg1 === 'object' && arg1 !== null) {\n options = arg1;\n }\n else if (typeof arg1 === 'number') {\n byteOffset = arg1;\n if (!Number.isSafeInteger(byteOffset)) {\n throw new RangeError('\\'byteOffset\\' must be an integer.');\n }\n if (byteOffset < 0 || byteOffset >= buffer.byteLength) {\n throw new RangeError(`'byteOffset' is out of range [0, ${buffer.byteLength}).`);\n }\n byteLength = arg0.byteLength - byteOffset;\n if (typeof arg2 === 'number') {\n byteLength = arg2;\n if (!Number.isSafeInteger(byteLength)) {\n throw new RangeError('\\'byteLength\\' must be an integer.');\n }\n if (byteLength <= 0 || byteOffset + byteLength > buffer.byteLength) {\n throw new RangeError(`'byteLength' is out of range (0, ${buffer.byteLength - byteOffset}].`);\n }\n if (typeof arg3 === 'object' && arg3 !== null) {\n options = arg3;\n }\n else if (typeof arg3 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'byteLength\\' must be a number.');\n }\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n filePathOrUint8Array = new Uint8Array(buffer, byteOffset, byteLength);\n }\n else {\n throw new TypeError('Unexpected argument[0]: must be \\'path\\' or \\'buffer\\'.');\n }\n // resolve backend, update session options with validated EPs, and create session handler\n const [backend, optionsWithValidatedEPs] = await resolveBackendAndExecutionProviders(options);\n const handler = await backend.createInferenceSessionHandler(filePathOrUint8Array, optionsWithValidatedEPs);\n TRACE_FUNC_END();\n return new InferenceSession(handler);\n }\n startProfiling() {\n this.handler.startProfiling();\n }\n endProfiling() {\n this.handler.endProfiling();\n }\n get inputNames() {\n return this.handler.inputNames;\n }\n get outputNames() {\n return this.handler.outputNames;\n }\n}\n//# sourceMappingURL=inference-session-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { InferenceSession as InferenceSessionImpl } from './inference-session-impl.js';\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const InferenceSession = InferenceSessionImpl;\n//# sourceMappingURL=inference-session.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nexport {};\n//# sourceMappingURL=onnx-model.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nexport {};\n//# sourceMappingURL=onnx-value.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n/**\n * implementation of Tensor.toDataURL()\n */\nexport const tensorToDataURL = (tensor, options) => {\n const canvas = typeof document !== 'undefined' ? document.createElement('canvas') : (new OffscreenCanvas(1, 1));\n canvas.width = tensor.dims[3];\n canvas.height = tensor.dims[2];\n const pixels2DContext = canvas.getContext('2d');\n if (pixels2DContext != null) {\n // Default values for height and width & format\n let width;\n let height;\n if (options?.tensorLayout !== undefined && options.tensorLayout === 'NHWC') {\n width = tensor.dims[2];\n height = tensor.dims[3];\n }\n else { // Default layout is NCWH\n width = tensor.dims[3];\n height = tensor.dims[2];\n }\n const inputformat = options?.format !== undefined ? options.format : 'RGB';\n const norm = options?.norm;\n let normMean;\n let normBias;\n if (norm === undefined || norm.mean === undefined) {\n normMean = [255, 255, 255, 255];\n }\n else {\n if (typeof (norm.mean) === 'number') {\n normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n }\n else {\n normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 0];\n if (norm.mean[3] !== undefined) {\n normMean[3] = norm.mean[3];\n }\n }\n }\n if (norm === undefined || norm.bias === undefined) {\n normBias = [0, 0, 0, 0];\n }\n else {\n if (typeof (norm.bias) === 'number') {\n normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n }\n else {\n normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];\n if (norm.bias[3] !== undefined) {\n normBias[3] = norm.bias[3];\n }\n }\n }\n const stride = height * width;\n // Default pointer assignments\n let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;\n // Updating the pointer assignments based on the input image format\n if (inputformat === 'RGBA') {\n rTensorPointer = 0;\n gTensorPointer = stride;\n bTensorPointer = stride * 2;\n aTensorPointer = stride * 3;\n }\n else if (inputformat === 'RGB') {\n rTensorPointer = 0;\n gTensorPointer = stride;\n bTensorPointer = stride * 2;\n }\n else if (inputformat === 'RBG') {\n rTensorPointer = 0;\n bTensorPointer = stride;\n gTensorPointer = stride * 2;\n }\n for (let i = 0; i < height; i++) {\n for (let j = 0; j < width; j++) {\n const R = (tensor.data[rTensorPointer++] - normBias[0]) * normMean[0]; // R value\n const G = (tensor.data[gTensorPointer++] - normBias[1]) * normMean[1]; // G value\n const B = (tensor.data[bTensorPointer++] - normBias[2]) * normMean[2]; // B value\n const A = aTensorPointer === -1 ?\n 255 :\n (tensor.data[aTensorPointer++] - normBias[3]) * normMean[3]; // A value\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n pixels2DContext.fillStyle = 'rgba(' + R + ',' + G + ',' + B + ',' + A + ')';\n pixels2DContext.fillRect(j, i, 1, 1);\n }\n }\n if ('toDataURL' in canvas) {\n return canvas.toDataURL();\n }\n else {\n throw new Error('toDataURL is not supported');\n }\n }\n else {\n throw new Error('Can not access image data');\n }\n};\n/**\n * implementation of Tensor.toImageData()\n */\nexport const tensorToImageData = (tensor, options) => {\n const pixels2DContext = typeof document !== 'undefined' ?\n document.createElement('canvas').getContext('2d') :\n new OffscreenCanvas(1, 1).getContext('2d');\n let image;\n if (pixels2DContext != null) {\n // Default values for height and width & format\n let width;\n let height;\n let channels;\n if (options?.tensorLayout !== undefined && options.tensorLayout === 'NHWC') {\n width = tensor.dims[2];\n height = tensor.dims[1];\n channels = tensor.dims[3];\n }\n else { // Default layout is NCWH\n width = tensor.dims[3];\n height = tensor.dims[2];\n channels = tensor.dims[1];\n }\n const inputformat = options !== undefined ? (options.format !== undefined ? options.format : 'RGB') : 'RGB';\n const norm = options?.norm;\n let normMean;\n let normBias;\n if (norm === undefined || norm.mean === undefined) {\n normMean = [255, 255, 255, 255];\n }\n else {\n if (typeof (norm.mean) === 'number') {\n normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n }\n else {\n normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 255];\n if (norm.mean[3] !== undefined) {\n normMean[3] = norm.mean[3];\n }\n }\n }\n if (norm === undefined || norm.bias === undefined) {\n normBias = [0, 0, 0, 0];\n }\n else {\n if (typeof (norm.bias) === 'number') {\n normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n }\n else {\n normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];\n if (norm.bias[3] !== undefined) {\n normBias[3] = norm.bias[3];\n }\n }\n }\n const stride = height * width;\n if (options !== undefined) {\n if (options.format !== undefined && (channels === 4 && options.format !== 'RGBA') ||\n (channels === 3 && (options.format !== 'RGB' && options.format !== 'BGR'))) {\n throw new Error('Tensor format doesn\\'t match input tensor dims');\n }\n }\n // Default pointer assignments\n const step = 4;\n let rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;\n let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;\n // Updating the pointer assignments based on the input image format\n if (inputformat === 'RGBA') {\n rTensorPointer = 0;\n gTensorPointer = stride;\n bTensorPointer = stride * 2;\n aTensorPointer = stride * 3;\n }\n else if (inputformat === 'RGB') {\n rTensorPointer = 0;\n gTensorPointer = stride;\n bTensorPointer = stride * 2;\n }\n else if (inputformat === 'RBG') {\n rTensorPointer = 0;\n bTensorPointer = stride;\n gTensorPointer = stride * 2;\n }\n image = pixels2DContext.createImageData(width, height);\n for (let i = 0; i < height * width; rImagePointer += step, gImagePointer += step, bImagePointer += step, aImagePointer += step, i++) {\n image.data[rImagePointer] = (tensor.data[rTensorPointer++] - normBias[0]) * normMean[0]; // R value\n image.data[gImagePointer] = (tensor.data[gTensorPointer++] - normBias[1]) * normMean[1]; // G value\n image.data[bImagePointer] = (tensor.data[bTensorPointer++] - normBias[2]) * normMean[2]; // B value\n image.data[aImagePointer] = aTensorPointer === -1 ?\n 255 :\n (tensor.data[aTensorPointer++] - normBias[3]) * normMean[3]; // A value\n }\n }\n else {\n throw new Error('Can not access image data');\n }\n return image;\n};\n//# sourceMappingURL=tensor-conversion-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nexport {};\n//# sourceMappingURL=tensor-conversion.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { Tensor } from './tensor-impl.js';\n/**\n * Create a new tensor object from image object\n *\n * @param buffer - Extracted image buffer data - assuming RGBA format\n * @param imageFormat - input image configuration - required configurations height, width, format\n * @param tensorFormat - output tensor configuration - Default is RGB format\n */\nexport const bufferToTensor = (buffer, options) => {\n if (buffer === undefined) {\n throw new Error('Image buffer must be defined');\n }\n if (options.height === undefined || options.width === undefined) {\n throw new Error('Image height and width must be defined');\n }\n if (options.tensorLayout === 'NHWC') {\n throw new Error('NHWC Tensor layout is not supported yet');\n }\n const { height, width } = options;\n const norm = options.norm ?? { mean: 255, bias: 0 };\n let normMean;\n let normBias;\n if (typeof (norm.mean) === 'number') {\n normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n }\n else {\n normMean = [norm.mean[0], norm.mean[1], norm.mean[2], norm.mean[3] ?? 255];\n }\n if (typeof (norm.bias) === 'number') {\n normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n }\n else {\n normBias = [norm.bias[0], norm.bias[1], norm.bias[2], norm.bias[3] ?? 0];\n }\n const inputformat = options.format !== undefined ? options.format : 'RGBA';\n // default value is RGBA since imagedata and HTMLImageElement uses it\n const outputformat = options.tensorFormat !== undefined ? (options.tensorFormat !== undefined ? options.tensorFormat : 'RGB') : 'RGB';\n const stride = height * width;\n const float32Data = outputformat === 'RGBA' ? new Float32Array(stride * 4) : new Float32Array(stride * 3);\n // Default pointer assignments\n let step = 4, rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;\n let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;\n // Updating the pointer assignments based on the input image format\n if (inputformat === 'RGB') {\n step = 3;\n rImagePointer = 0;\n gImagePointer = 1;\n bImagePointer = 2;\n aImagePointer = -1;\n }\n // Updating the pointer assignments based on the output tensor format\n if (outputformat === 'RGBA') {\n aTensorPointer = stride * 3;\n }\n else if (outputformat === 'RBG') {\n rTensorPointer = 0;\n bTensorPointer = stride;\n gTensorPointer = stride * 2;\n }\n else if (outputformat === 'BGR') {\n bTensorPointer = 0;\n gTensorPointer = stride;\n rTensorPointer = stride * 2;\n }\n for (let i = 0; i < stride; i++, rImagePointer += step, bImagePointer += step, gImagePointer += step, aImagePointer += step) {\n float32Data[rTensorPointer++] = (buffer[rImagePointer] + normBias[0]) / normMean[0];\n float32Data[gTensorPointer++] = (buffer[gImagePointer] + normBias[1]) / normMean[1];\n float32Data[bTensorPointer++] = (buffer[bImagePointer] + normBias[2]) / normMean[2];\n if (aTensorPointer !== -1 && aImagePointer !== -1) {\n float32Data[aTensorPointer++] = (buffer[aImagePointer] + normBias[3]) / normMean[3];\n }\n }\n // Float32Array -> ort.Tensor\n const outputTensor = outputformat === 'RGBA' ? new Tensor('float32', float32Data, [1, 4, height, width]) :\n new Tensor('float32', float32Data, [1, 3, height, width]);\n return outputTensor;\n};\n/**\n * implementation of Tensor.fromImage().\n */\nexport const tensorFromImage = async (image, options) => {\n // checking the type of image object\n const isHTMLImageEle = typeof (HTMLImageElement) !== 'undefined' && image instanceof HTMLImageElement;\n const isImageDataEle = typeof (ImageData) !== 'undefined' && image instanceof ImageData;\n const isImageBitmap = typeof (ImageBitmap) !== 'undefined' && image instanceof ImageBitmap;\n const isString = typeof image === 'string';\n let data;\n let bufferToTensorOptions = options ?? {};\n const createCanvas = () => {\n if (typeof document !== 'undefined') {\n return document.createElement('canvas');\n }\n else if (typeof OffscreenCanvas !== 'undefined') {\n return new OffscreenCanvas(1, 1);\n }\n else {\n throw new Error('Canvas is not supported');\n }\n };\n const createCanvasContext = (canvas) => {\n if (canvas instanceof HTMLCanvasElement) {\n return canvas.getContext('2d');\n }\n else if (canvas instanceof OffscreenCanvas) {\n return canvas.getContext('2d');\n }\n else {\n return null;\n }\n };\n // filling and checking image configuration options\n if (isHTMLImageEle) {\n // HTMLImageElement - image object - format is RGBA by default\n const canvas = createCanvas();\n canvas.width = image.width;\n canvas.height = image.height;\n const pixels2DContext = createCanvasContext(canvas);\n if (pixels2DContext != null) {\n let height = image.height;\n let width = image.width;\n if (options !== undefined && options.resizedHeight !== undefined && options.resizedWidth !== undefined) {\n height = options.resizedHeight;\n width = options.resizedWidth;\n }\n if (options !== undefined) {\n bufferToTensorOptions = options;\n if (options.tensorFormat !== undefined) {\n throw new Error('Image input config format must be RGBA for HTMLImageElement');\n }\n else {\n bufferToTensorOptions.tensorFormat = 'RGBA';\n }\n bufferToTensorOptions.height = height;\n bufferToTensorOptions.width = width;\n }\n else {\n bufferToTensorOptions.tensorFormat = 'RGBA';\n bufferToTensorOptions.height = height;\n bufferToTensorOptions.width = width;\n }\n pixels2DContext.drawImage(image, 0, 0);\n data = pixels2DContext.getImageData(0, 0, width, height).data;\n }\n else {\n throw new Error('Can not access image data');\n }\n }\n else if (isImageDataEle) {\n let height;\n let width;\n if (options !== undefined && options.resizedWidth !== undefined && options.resizedHeight !== undefined) {\n height = options.resizedHeight;\n width = options.resizedWidth;\n }\n else {\n height = image.height;\n width = image.width;\n }\n if (options !== undefined) {\n bufferToTensorOptions = options;\n }\n bufferToTensorOptions.format = 'RGBA';\n bufferToTensorOptions.height = height;\n bufferToTensorOptions.width = width;\n if (options !== undefined) {\n const tempCanvas = createCanvas();\n tempCanvas.width = width;\n tempCanvas.height = height;\n const pixels2DContext = createCanvasContext(tempCanvas);\n if (pixels2DContext != null) {\n pixels2DContext.putImageData(image, 0, 0);\n data = pixels2DContext.getImageData(0, 0, width, height).data;\n }\n else {\n throw new Error('Can not access image data');\n }\n }\n else {\n data = image.data;\n }\n }\n else if (isImageBitmap) {\n // ImageBitmap - image object - format must be provided by user\n if (options === undefined) {\n throw new Error('Please provide image config with format for Imagebitmap');\n }\n const canvas = createCanvas();\n canvas.width = image.width;\n canvas.height = image.height;\n const pixels2DContext = createCanvasContext(canvas);\n if (pixels2DContext != null) {\n const height = image.height;\n const width = image.width;\n pixels2DContext.drawImage(image, 0, 0, width, height);\n data = pixels2DContext.getImageData(0, 0, width, height).data;\n bufferToTensorOptions.height = height;\n bufferToTensorOptions.width = width;\n return bufferToTensor(data, bufferToTensorOptions);\n }\n else {\n throw new Error('Can not access image data');\n }\n }\n else if (isString) {\n return new Promise((resolve, reject) => {\n const canvas = createCanvas();\n const context = createCanvasContext(canvas);\n if (!image || !context) {\n return reject();\n }\n const newImage = new Image();\n newImage.crossOrigin = 'Anonymous';\n newImage.src = image;\n newImage.onload = () => {\n canvas.width = newImage.width;\n canvas.height = newImage.height;\n context.drawImage(newImage, 0, 0, canvas.width, canvas.height);\n const img = context.getImageData(0, 0, canvas.width, canvas.height);\n bufferToTensorOptions.height = canvas.height;\n bufferToTensorOptions.width = canvas.width;\n resolve(bufferToTensor(img.data, bufferToTensorOptions));\n };\n });\n }\n else {\n throw new Error('Input data provided is not supported - aborted tensor creation');\n }\n if (data !== undefined) {\n return bufferToTensor(data, bufferToTensorOptions);\n }\n else {\n throw new Error('Input data provided is not supported - aborted tensor creation');\n }\n};\n/**\n * implementation of Tensor.fromTexture().\n */\nexport const tensorFromTexture = (texture, options) => {\n const { width, height, download, dispose } = options;\n // Always assume RGBAF32. TODO: support different texture format\n const dims = [1, height, width, 4];\n return new Tensor({ location: 'texture', type: 'float32', texture, dims, download, dispose });\n};\n/**\n * implementation of Tensor.fromGpuBuffer().\n */\nexport const tensorFromGpuBuffer = (gpuBuffer, options) => {\n const { dataType, dims, download, dispose } = options;\n return new Tensor({ location: 'gpu-buffer', type: dataType ?? 'float32', gpuBuffer, dims, download, dispose });\n};\n/**\n * implementation of Tensor.fromPinnedBuffer().\n */\nexport const tensorFromPinnedBuffer = (type, buffer, dims) => new Tensor({ location: 'cpu-pinned', type, data: buffer, dims: dims ?? [buffer.length] });\n//# sourceMappingURL=tensor-factory-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nexport {};\n//# sourceMappingURL=tensor-factory.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.\nexport const NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = new Map([\n ['float32', Float32Array],\n ['uint8', Uint8Array],\n ['int8', Int8Array],\n ['uint16', Uint16Array],\n ['int16', Int16Array],\n ['int32', Int32Array],\n ['bool', Uint8Array],\n ['float64', Float64Array],\n ['uint32', Uint32Array],\n]);\n// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.\nexport const NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = new Map([\n [Float32Array, 'float32'],\n [Uint8Array, 'uint8'],\n [Int8Array, 'int8'],\n [Uint16Array, 'uint16'],\n [Int16Array, 'int16'],\n [Int32Array, 'int32'],\n [Float64Array, 'float64'],\n [Uint32Array, 'uint32'],\n]);\n// the following code allows delaying execution of BigInt/Float16Array checking. This allows lazy initialization for\n// NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP and NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP, which allows BigInt/Float16Array\n// polyfill if available.\nlet isTypedArrayChecked = false;\nexport const checkTypedArray = () => {\n if (!isTypedArrayChecked) {\n isTypedArrayChecked = true;\n const isBigInt64ArrayAvailable = typeof BigInt64Array !== 'undefined' && BigInt64Array.from;\n const isBigUint64ArrayAvailable = typeof BigUint64Array !== 'undefined' && BigUint64Array.from;\n const isFloat16ArrayAvailable = typeof Float16Array !== 'undefined' && Float16Array.from;\n if (isBigInt64ArrayAvailable) {\n NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('int64', BigInt64Array);\n NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, 'int64');\n }\n if (isBigUint64ArrayAvailable) {\n NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('uint64', BigUint64Array);\n NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, 'uint64');\n }\n if (isFloat16ArrayAvailable) {\n NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('float16', Float16Array);\n NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(Float16Array, 'float16');\n }\n else {\n // if Float16Array is not available, use 'Uint16Array' to store the data.\n NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('float16', Uint16Array);\n }\n }\n};\n//# sourceMappingURL=tensor-impl-type-mapping.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { tensorToDataURL, tensorToImageData } from './tensor-conversion-impl.js';\nimport { tensorFromGpuBuffer, tensorFromImage, tensorFromPinnedBuffer, tensorFromTexture } from './tensor-factory-impl.js';\nimport { checkTypedArray, NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP, NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP } from './tensor-impl-type-mapping.js';\nimport { calculateSize, tensorReshape } from './tensor-utils-impl.js';\n/**\n * the implementation of Tensor interface.\n *\n * @ignore\n */\nexport class Tensor {\n /**\n * implementation.\n */\n constructor(arg0, arg1, arg2) {\n // perform one-time check for BigInt/Float16Array support\n checkTypedArray();\n let type;\n let dims;\n if (typeof arg0 === 'object' && 'location' in arg0) {\n //\n // constructing tensor from specific location\n //\n this.dataLocation = arg0.location;\n type = arg0.type;\n dims = arg0.dims;\n switch (arg0.location) {\n case 'cpu-pinned': {\n const expectedTypedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(type);\n if (!expectedTypedArrayConstructor) {\n throw new TypeError(`unsupported type \"${type}\" to create tensor from pinned buffer`);\n }\n if (!(arg0.data instanceof expectedTypedArrayConstructor)) {\n throw new TypeError(`buffer should be of type ${expectedTypedArrayConstructor.name}`);\n }\n this.cpuData = arg0.data;\n break;\n }\n case 'texture': {\n if (type !== 'float32') {\n throw new TypeError(`unsupported type \"${type}\" to create tensor from texture`);\n }\n this.gpuTextureData = arg0.texture;\n this.downloader = arg0.download;\n this.disposer = arg0.dispose;\n break;\n }\n case 'gpu-buffer': {\n if ((type !== 'float32' && type !== 'float16' && type !== 'int32' && type !== 'int64' && type !== 'uint32' &&\n type !== 'uint8' && type !== 'bool')) {\n throw new TypeError(`unsupported type \"${type}\" to create tensor from gpu buffer`);\n }\n this.gpuBufferData = arg0.gpuBuffer;\n this.downloader = arg0.download;\n this.disposer = arg0.dispose;\n break;\n }\n default:\n throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`);\n }\n }\n else {\n //\n // constructing tensor of location 'cpu'\n //\n let data;\n let maybeDims;\n // check whether arg0 is type or data\n if (typeof arg0 === 'string') {\n //\n // Override: constructor(type, data, ...)\n //\n type = arg0;\n maybeDims = arg2;\n if (arg0 === 'string') {\n // string tensor\n if (!Array.isArray(arg1)) {\n throw new TypeError('A string tensor\\'s data must be a string array.');\n }\n // we don't check whether every element in the array is string; this is too slow. we assume it's correct and\n // error will be populated at inference\n data = arg1;\n }\n else {\n // numeric tensor\n const typedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(arg0);\n if (typedArrayConstructor === undefined) {\n throw new TypeError(`Unsupported tensor type: ${arg0}.`);\n }\n if (Array.isArray(arg1)) {\n if (arg0 === 'float16' && typedArrayConstructor === Uint16Array) {\n // When no Float16Array polyfill is used, we cannot create 'float16' tensor from number array.\n //\n // Throw error here because when user try to use number array as data,\n // e.g. new Tensor('float16', [1, 2, 3, 4], dims)), it will actually call\n // Uint16Array.from(arg1) which generates wrong data.\n throw new TypeError('Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.');\n }\n else if (arg0 === 'uint64' || arg0 === 'int64') {\n // use 'as any' here because:\n // 1. TypeScript's check on type of 'Array.isArray()' does not work with readonly arrays.\n // see https://github.com/microsoft/TypeScript/issues/17002\n // 2. TypeScript's check on union type of '(BigInt64ArrayConstructor|BigUint64ArrayConstructor).from()'\n // does not accept parameter mapFn.\n // 3. parameters of 'SupportedTypedArrayConstructors.from()' does not match the requirement of the union\n // type.\n // assume 'arg1' is of type \"readonly number[]|readonly bigint[]\" here.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data = typedArrayConstructor.from(arg1, BigInt);\n }\n else {\n // assume 'arg1' is of type \"readonly number[]\" here.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data = typedArrayConstructor.from(arg1);\n }\n }\n else if (arg1 instanceof typedArrayConstructor) {\n data = arg1;\n }\n else {\n throw new TypeError(`A ${type} tensor's data must be type of ${typedArrayConstructor}`);\n }\n }\n }\n else {\n //\n // Override: constructor(data, ...)\n //\n maybeDims = arg1;\n if (Array.isArray(arg0)) {\n // only boolean[] and string[] is supported\n if (arg0.length === 0) {\n throw new TypeError('Tensor type cannot be inferred from an empty array.');\n }\n const firstElementType = typeof arg0[0];\n if (firstElementType === 'string') {\n type = 'string';\n data = arg0;\n }\n else if (firstElementType === 'boolean') {\n type = 'bool';\n // 'arg0' is of type 'boolean[]'. Uint8Array.from(boolean[]) actually works, but typescript thinks this is\n // wrong type. We use 'as any' to make it happy.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data = Uint8Array.from(arg0);\n }\n else {\n throw new TypeError(`Invalid element type of data array: ${firstElementType}.`);\n }\n }\n else {\n // get tensor type from TypedArray\n const mappedType = NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(arg0.constructor);\n if (mappedType === undefined) {\n throw new TypeError(`Unsupported type for tensor data: ${arg0.constructor}.`);\n }\n type = mappedType;\n data = arg0;\n }\n }\n // type and data is processed, now processing dims\n if (maybeDims === undefined) {\n // assume 1-D tensor if dims omitted\n maybeDims = [data.length];\n }\n else if (!Array.isArray(maybeDims)) {\n throw new TypeError('A tensor\\'s dims must be a number array');\n }\n dims = maybeDims;\n this.cpuData = data;\n this.dataLocation = 'cpu';\n }\n // perform check on dims\n const size = calculateSize(dims);\n // if data is on CPU, check whether data length matches tensor size\n if (this.cpuData && size !== this.cpuData.length) {\n throw new Error(`Tensor's size(${size}) does not match data length(${this.cpuData.length}).`);\n }\n this.type = type;\n this.dims = dims;\n this.size = size;\n }\n // #endregion\n // #region factory\n static async fromImage(image, options) {\n return tensorFromImage(image, options);\n }\n static fromTexture(texture, options) {\n return tensorFromTexture(texture, options);\n }\n static fromGpuBuffer(gpuBuffer, options) {\n return tensorFromGpuBuffer(gpuBuffer, options);\n }\n static fromPinnedBuffer(type, buffer, dims) {\n return tensorFromPinnedBuffer(type, buffer, dims);\n }\n // #endregion\n // #region conversions\n toDataURL(options) {\n return tensorToDataURL(this, options);\n }\n toImageData(options) {\n return tensorToImageData(this, options);\n }\n // #endregion\n // #region properties\n get data() {\n this.ensureValid();\n if (!this.cpuData) {\n throw new Error('The data is not on CPU. Use `getData()` to download GPU data to CPU, ' +\n 'or use `texture` or `gpuBuffer` property to access the GPU data directly.');\n }\n return this.cpuData;\n }\n get location() {\n return this.dataLocation;\n }\n get texture() {\n this.ensureValid();\n if (!this.gpuTextureData) {\n throw new Error('The data is not stored as a WebGL texture.');\n }\n return this.gpuTextureData;\n }\n get gpuBuffer() {\n this.ensureValid();\n if (!this.gpuBufferData) {\n throw new Error('The data is not stored as a WebGPU buffer.');\n }\n return this.gpuBufferData;\n }\n // #endregion\n // #region methods\n async getData(releaseData) {\n this.ensureValid();\n switch (this.dataLocation) {\n case 'cpu':\n case 'cpu-pinned':\n return this.data;\n case 'texture':\n case 'gpu-buffer': {\n if (!this.downloader) {\n throw new Error('The current tensor is not created with a specified data downloader.');\n }\n if (this.isDownloading) {\n throw new Error('The current tensor is being downloaded.');\n }\n try {\n this.isDownloading = true;\n const data = await this.downloader();\n this.downloader = undefined;\n this.dataLocation = 'cpu';\n this.cpuData = data;\n if (releaseData && this.disposer) {\n this.disposer();\n this.disposer = undefined;\n }\n return data;\n }\n finally {\n this.isDownloading = false;\n }\n }\n default:\n throw new Error(`cannot get data from location: ${this.dataLocation}`);\n }\n }\n dispose() {\n if (this.isDownloading) {\n throw new Error('The current tensor is being downloaded.');\n }\n if (this.disposer) {\n this.disposer();\n this.disposer = undefined;\n }\n this.cpuData = undefined;\n this.gpuTextureData = undefined;\n this.gpuBufferData = undefined;\n this.downloader = undefined;\n this.isDownloading = undefined;\n this.dataLocation = 'none';\n }\n // #endregion\n // #region tensor utilities\n ensureValid() {\n if (this.dataLocation === 'none') {\n throw new Error('The tensor is disposed.');\n }\n }\n reshape(dims) {\n this.ensureValid();\n if (this.downloader || this.disposer) {\n throw new Error('Cannot reshape a tensor that owns GPU resource.');\n }\n return tensorReshape(this, dims);\n }\n}\n//# sourceMappingURL=tensor-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { Tensor } from './tensor-impl.js';\n/**\n * calculate size from dims.\n *\n * @param dims the dims array. May be an illegal input.\n */\nexport const calculateSize = (dims) => {\n let size = 1;\n for (let i = 0; i < dims.length; i++) {\n const dim = dims[i];\n if (typeof dim !== 'number' || !Number.isSafeInteger(dim)) {\n throw new TypeError(`dims[${i}] must be an integer, got: ${dim}`);\n }\n if (dim < 0) {\n throw new RangeError(`dims[${i}] must be a non-negative integer, got: ${dim}`);\n }\n size *= dim;\n }\n return size;\n};\n/**\n * implementation of Tensor.reshape()\n */\nexport const tensorReshape = (tensor, dims) => {\n switch (tensor.location) {\n case 'cpu':\n return new Tensor(tensor.type, tensor.data, dims);\n case 'cpu-pinned':\n return new Tensor({\n location: 'cpu-pinned',\n data: tensor.data,\n type: tensor.type,\n dims,\n });\n case 'texture':\n return new Tensor({\n location: 'texture',\n texture: tensor.texture,\n type: tensor.type,\n dims,\n });\n case 'gpu-buffer':\n return new Tensor({\n location: 'gpu-buffer',\n gpuBuffer: tensor.gpuBuffer,\n type: tensor.type,\n dims,\n });\n default:\n throw new Error(`tensorReshape: tensor location ${tensor.location} is not supported`);\n }\n};\n//# sourceMappingURL=tensor-utils-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { Tensor as TensorImpl } from './tensor-impl.js';\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const Tensor = TensorImpl;\n//# sourceMappingURL=tensor.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { env } from './env-impl.js';\n/**\n * @ignore\n */\nexport const TRACE = (deviceType, label) => {\n if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n return;\n }\n // eslint-disable-next-line no-console\n console.timeStamp(`${deviceType}::ORT::${label}`);\n};\nconst TRACE_FUNC = (msg, extraMsg) => {\n const stack = new Error().stack?.split(/\\r\\n|\\r|\\n/g) || [];\n let hasTraceFunc = false;\n for (let i = 0; i < stack.length; i++) {\n if (hasTraceFunc && !stack[i].includes('TRACE_FUNC')) {\n let label = `FUNC_${msg}::${stack[i].trim().split(' ')[1]}`;\n if (extraMsg) {\n label += `::${extraMsg}`;\n }\n TRACE('CPU', label);\n return;\n }\n if (stack[i].includes('TRACE_FUNC')) {\n hasTraceFunc = true;\n }\n }\n};\n/**\n * @ignore\n */\nexport const TRACE_FUNC_BEGIN = (extraMsg) => {\n if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n return;\n }\n TRACE_FUNC('BEGIN', extraMsg);\n};\n/**\n * @ignore\n */\nexport const TRACE_FUNC_END = (extraMsg) => {\n if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n return;\n }\n TRACE_FUNC('END', extraMsg);\n};\n//# sourceMappingURL=trace.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { resolveBackendAndExecutionProviders } from './backend-impl.js';\nimport { Tensor } from './tensor.js';\nconst noBackendErrMsg = 'Training backend could not be resolved. ' +\n 'Make sure you\\'re using the correct configuration & WebAssembly files.';\nexport class TrainingSession {\n constructor(handler, hasOptimizerModel, hasEvalModel) {\n this.handler = handler;\n this.hasOptimizerModel = hasOptimizerModel;\n this.hasEvalModel = hasEvalModel;\n }\n get trainingInputNames() {\n return this.handler.inputNames;\n }\n get trainingOutputNames() {\n return this.handler.outputNames;\n }\n get evalInputNames() {\n if (this.hasEvalModel) {\n return this.handler.evalInputNames;\n }\n else {\n throw new Error('This training session has no evalModel loaded.');\n }\n }\n get evalOutputNames() {\n if (this.hasEvalModel) {\n return this.handler.evalOutputNames;\n }\n else {\n throw new Error('This training session has no evalModel loaded.');\n }\n }\n static async create(trainingOptions, sessionOptions) {\n const evalModel = trainingOptions.evalModel || '';\n const optimizerModel = trainingOptions.optimizerModel || '';\n const options = sessionOptions || {};\n // resolve backend, update session options with validated EPs, and create session handler\n const [backend, optionsWithValidatedEPs] = await resolveBackendAndExecutionProviders(options);\n if (backend.createTrainingSessionHandler) {\n const handler = await backend.createTrainingSessionHandler(trainingOptions.checkpointState, trainingOptions.trainModel, evalModel, optimizerModel, optionsWithValidatedEPs);\n return new TrainingSession(handler, !!trainingOptions.optimizerModel, !!trainingOptions.evalModel);\n }\n else {\n throw new Error(noBackendErrMsg);\n }\n }\n /**\n * Helper function for runTrainStep and future runStep methods that handles the type-narrowing conversion from\n * the given parameters to SessionHandler.FetchesType and RunOptions.\n *\n * @param inputNames the feeds object is checked that they contain all input names in the provided list of input\n * names.\n * @param outputNames the fetches object is checked that their keys match up with valid names in the list of output\n * names.\n * @param feeds the required input\n * @param arg1 narrowed & converted into the SessionHandler.FetchesType or RunOptions object\n * @param arg2 optional RunOptions object.\n * @returns\n */\n typeNarrowingForRunStep(inputNames, outputNames, feeds, arg1, arg2) {\n const fetches = {};\n let options = {};\n // check inputs\n if (typeof feeds !== 'object' || feeds === null || feeds instanceof Tensor || Array.isArray(feeds)) {\n throw new TypeError('\\'feeds\\' must be an object that use input names as keys and OnnxValue as corresponding values.');\n }\n let isFetchesEmpty = true;\n // determine which override is being used\n if (typeof arg1 === 'object') {\n if (arg1 === null) {\n throw new TypeError('Unexpected argument[1]: cannot be null.');\n }\n if (arg1 instanceof Tensor) {\n throw new TypeError('\\'fetches\\' cannot be a Tensor');\n }\n if (Array.isArray(arg1)) {\n if (arg1.length === 0) {\n throw new TypeError('\\'fetches\\' cannot be an empty array.');\n }\n isFetchesEmpty = false;\n // output names\n for (const name of arg1) {\n if (typeof name !== 'string') {\n throw new TypeError('\\'fetches\\' must be a string array or an object.');\n }\n if (outputNames.indexOf(name) === -1) {\n throw new RangeError(`'fetches' contains invalid output name: ${name}.`);\n }\n fetches[name] = null;\n }\n if (typeof arg2 === 'object' && arg2 !== null) {\n options = arg2;\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else {\n // decide whether arg1 is fetches or options\n // if any output name is present and its value is valid OnnxValue, we consider it fetches\n let isFetches = false;\n const arg1Keys = Object.getOwnPropertyNames(arg1);\n for (const name of outputNames) {\n if (arg1Keys.indexOf(name) !== -1) {\n const v = arg1[name];\n if (v === null || v instanceof Tensor) {\n isFetches = true;\n isFetchesEmpty = false;\n fetches[name] = v;\n }\n }\n }\n if (isFetches) {\n if (typeof arg2 === 'object' && arg2 !== null) {\n options = arg2;\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else {\n options = arg1;\n }\n }\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('Unexpected argument[1]: must be \\'fetches\\' or \\'options\\'.');\n }\n // check if all inputs are in feed\n for (const name of inputNames) {\n if (typeof feeds[name] === 'undefined') {\n throw new Error(`input '${name}' is missing in 'feeds'.`);\n }\n }\n // if no fetches is specified, we use the full output names list\n if (isFetchesEmpty) {\n for (const name of outputNames) {\n fetches[name] = null;\n }\n }\n return [fetches, options];\n }\n /**\n * Helper method for runTrainStep and any other runStep methods. Takes the ReturnType result from the SessionHandler\n * and changes it into a map of Tensors.\n *\n * @param results\n * @returns\n */\n convertHandlerReturnTypeToMapOfTensors(results) {\n const returnValue = {};\n for (const key in results) {\n if (Object.hasOwnProperty.call(results, key)) {\n const result = results[key];\n if (result instanceof Tensor) {\n returnValue[key] = result;\n }\n else {\n returnValue[key] = new Tensor(result.type, result.data, result.dims);\n }\n }\n }\n return returnValue;\n }\n async lazyResetGrad() {\n await this.handler.lazyResetGrad();\n }\n async runTrainStep(feeds, arg1, arg2) {\n const [fetches, options] = this.typeNarrowingForRunStep(this.trainingInputNames, this.trainingOutputNames, feeds, arg1, arg2);\n const results = await this.handler.runTrainStep(feeds, fetches, options);\n return this.convertHandlerReturnTypeToMapOfTensors(results);\n }\n async runOptimizerStep(options) {\n if (this.hasOptimizerModel) {\n await this.handler.runOptimizerStep(options || {});\n }\n else {\n throw new Error('This TrainingSession has no OptimizerModel loaded.');\n }\n }\n async runEvalStep(feeds, arg1, arg2) {\n if (this.hasEvalModel) {\n const [fetches, options] = this.typeNarrowingForRunStep(this.evalInputNames, this.evalOutputNames, feeds, arg1, arg2);\n const results = await this.handler.runEvalStep(feeds, fetches, options);\n return this.convertHandlerReturnTypeToMapOfTensors(results);\n }\n else {\n throw new Error('This TrainingSession has no EvalModel loaded.');\n }\n }\n async getParametersSize(trainableOnly = true) {\n return this.handler.getParametersSize(trainableOnly);\n }\n async loadParametersBuffer(array, trainableOnly = true) {\n const paramsSize = await this.getParametersSize(trainableOnly);\n // checking that the size of the Uint8Array is equivalent to the byte length of a Float32Array of the number\n // of parameters\n if (array.length !== 4 * paramsSize) {\n throw new Error('Size of the buffer passed into loadParametersBuffer must match the number of parameters in ' +\n 'the model. Please use getParametersSize method to check.');\n }\n return this.handler.loadParametersBuffer(array, trainableOnly);\n }\n async getContiguousParameters(trainableOnly = true) {\n return this.handler.getContiguousParameters(trainableOnly);\n }\n async release() {\n return this.handler.dispose();\n }\n}\n//# sourceMappingURL=training-session-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { TrainingSession as TrainingSessionImpl } from './training-session-impl.js';\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const TrainingSession = TrainingSessionImpl;\n//# sourceMappingURL=training-session.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n// This file is generated by /js/scripts/update-version.ts\n// Do not modify file content manually.\nexport const version = '1.19.2';\n//# sourceMappingURL=version.js.map","/*!\n * ONNX Runtime Web v1.21.0-dev.20241122-a2ba3cb547\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\nvar Ln=Object.defineProperty;var Bp=Object.getOwnPropertyDescriptor;var Dp=Object.getOwnPropertyNames;var Mp=Object.prototype.hasOwnProperty;var Gn=(e=>typeof require<\"u\"?require:typeof Proxy<\"u\"?new Proxy(e,{get:(t,r)=>(typeof require<\"u\"?require:t)[r]}):e)(function(e){if(typeof require<\"u\")return require.apply(this,arguments);throw Error('Dynamic require of \"'+e+'\" is not supported')});var R=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ft=(e,t)=>{for(var r in t)Ln(e,r,{get:t[r],enumerable:!0})},Rp=(e,t,r,n)=>{if(t&&typeof t==\"object\"||typeof t==\"function\")for(let o of Dp(t))!Mp.call(e,o)&&o!==r&&Ln(e,o,{get:()=>t[o],enumerable:!(n=Bp(t,o))||n.enumerable});return e};var br=e=>Rp(Ln({},\"__esModule\",{value:!0}),e);var yr,$t,xt,Up,_r,wr=R(()=>{\"use strict\";yr=new Map,$t=[],xt=(e,t,r)=>{if(t&&typeof t.init==\"function\"&&typeof t.createInferenceSessionHandler==\"function\"){let n=yr.get(e);if(n===void 0)yr.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend \"${e}\" using priority ${r}`)}if(r>=0){let o=$t.indexOf(e);o!==-1&&$t.splice(o,1);for(let i=0;i<$t.length;i++)if(yr.get($t[i]).priority<=r){$t.splice(i,0,e);return}$t.push(e)}return}throw new TypeError(\"not a valid backend\")},Up=async e=>{let t=yr.get(e);if(!t)return\"backend not found.\";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},_r=async e=>{let t=e.executionProviders||[],r=t.map(d=>typeof d==\"string\"?d:d.name),n=r.length===0?$t:r,o,i=[],a=new Set;for(let d of n){let p=await Up(d);typeof p==\"string\"?i.push({name:d,err:p}):(o||(o=p),o===p&&a.add(d))}if(!o)throw new Error(`no available backend found. ERR: ${i.map(d=>`[${d.name}] ${d.err}`).join(\", \")}`);for(let{name:d,err:p}of i)r.includes(d)&&console.warn(`removing requested execution provider \"${d}\" from session options because it is not available: ${p}`);let l=t.filter(d=>a.has(typeof d==\"string\"?d:d.name));return[o,new Proxy(e,{get:(d,p)=>p===\"executionProviders\"?l:Reflect.get(d,p)})]}});var ea=R(()=>{\"use strict\";wr()});var ta,ra=R(()=>{\"use strict\";ta=\"1.21.0-dev.20241026-05fbb43b34\"});var na,Re,Hn=R(()=>{\"use strict\";ra();na=\"warning\",Re={wasm:{},webgl:{},webgpu:{},versions:{common:ta},set logLevel(e){if(e!==void 0){if(typeof e!=\"string\"||[\"verbose\",\"info\",\"warning\",\"error\",\"fatal\"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);na=e}},get logLevel(){return na}};Object.defineProperty(Re,\"logLevel\",{enumerable:!0})});var we,oa=R(()=>{\"use strict\";Hn();we=Re});var ia,aa,sa=R(()=>{\"use strict\";ia=(e,t)=>{let r=typeof document<\"u\"?document.createElement(\"canvas\"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext(\"2d\");if(n!=null){let o,i;t?.tensorLayout!==void 0&&t.tensorLayout===\"NHWC\"?(o=e.dims[2],i=e.dims[3]):(o=e.dims[3],i=e.dims[2]);let a=t?.format!==void 0?t.format:\"RGB\",l=t?.norm,d,p;l===void 0||l.mean===void 0?d=[255,255,255,255]:typeof l.mean==\"number\"?d=[l.mean,l.mean,l.mean,l.mean]:(d=[l.mean[0],l.mean[1],l.mean[2],0],l.mean[3]!==void 0&&(d[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias==\"number\"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let m=i*o,u=0,h=m,_=m*2,y=-1;a===\"RGBA\"?(u=0,h=m,_=m*2,y=m*3):a===\"RGB\"?(u=0,h=m,_=m*2):a===\"RBG\"&&(u=0,_=m,h=m*2);for(let g=0;g{let r=typeof document<\"u\"?document.createElement(\"canvas\").getContext(\"2d\"):new OffscreenCanvas(1,1).getContext(\"2d\"),n;if(r!=null){let o,i,a;t?.tensorLayout!==void 0&&t.tensorLayout===\"NHWC\"?(o=e.dims[2],i=e.dims[1],a=e.dims[3]):(o=e.dims[3],i=e.dims[2],a=e.dims[1]);let l=t!==void 0&&t.format!==void 0?t.format:\"RGB\",d=t?.norm,p,m;d===void 0||d.mean===void 0?p=[255,255,255,255]:typeof d.mean==\"number\"?p=[d.mean,d.mean,d.mean,d.mean]:(p=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(p[3]=d.mean[3])),d===void 0||d.bias===void 0?m=[0,0,0,0]:typeof d.bias==\"number\"?m=[d.bias,d.bias,d.bias,d.bias]:(m=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(m[3]=d.bias[3]));let u=i*o;if(t!==void 0&&(t.format!==void 0&&a===4&&t.format!==\"RGBA\"||a===3&&t.format!==\"RGB\"&&t.format!==\"BGR\"))throw new Error(\"Tensor format doesn't match input tensor dims\");let h=4,_=0,y=1,g=2,x=3,$=0,v=u,S=u*2,T=-1;l===\"RGBA\"?($=0,v=u,S=u*2,T=u*3):l===\"RGB\"?($=0,v=u,S=u*2):l===\"RBG\"&&($=0,S=u,v=u*2),n=r.createImageData(o,i);for(let C=0;C{\"use strict\";vr();Fn=(e,t)=>{if(e===void 0)throw new Error(\"Image buffer must be defined\");if(t.height===void 0||t.width===void 0)throw new Error(\"Image height and width must be defined\");if(t.tensorLayout===\"NHWC\")throw new Error(\"NHWC Tensor layout is not supported yet\");let{height:r,width:n}=t,o=t.norm??{mean:255,bias:0},i,a;typeof o.mean==\"number\"?i=[o.mean,o.mean,o.mean,o.mean]:i=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias==\"number\"?a=[o.bias,o.bias,o.bias,o.bias]:a=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let l=t.format!==void 0?t.format:\"RGBA\",d=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:\"RGB\",p=r*n,m=d===\"RGBA\"?new Float32Array(p*4):new Float32Array(p*3),u=4,h=0,_=1,y=2,g=3,x=0,$=p,v=p*2,S=-1;l===\"RGB\"&&(u=3,h=0,_=1,y=2,g=-1),d===\"RGBA\"?S=p*3:d===\"RBG\"?(x=0,v=p,$=p*2):d===\"BGR\"&&(v=0,$=p,x=p*2);for(let C=0;C{let r=typeof HTMLImageElement<\"u\"&&e instanceof HTMLImageElement,n=typeof ImageData<\"u\"&&e instanceof ImageData,o=typeof ImageBitmap<\"u\"&&e instanceof ImageBitmap,i=typeof e==\"string\",a,l=t??{},d=()=>{if(typeof document<\"u\")return document.createElement(\"canvas\");if(typeof OffscreenCanvas<\"u\")return new OffscreenCanvas(1,1);throw new Error(\"Canvas is not supported\")},p=m=>typeof HTMLCanvasElement<\"u\"&&m instanceof HTMLCanvasElement||m instanceof OffscreenCanvas?m.getContext(\"2d\"):null;if(r){let m=d();m.width=e.width,m.height=e.height;let u=p(m);if(u!=null){let h=e.height,_=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(h=t.resizedHeight,_=t.resizedWidth),t!==void 0){if(l=t,t.tensorFormat!==void 0)throw new Error(\"Image input config format must be RGBA for HTMLImageElement\");l.tensorFormat=\"RGBA\",l.height=h,l.width=_}else l.tensorFormat=\"RGBA\",l.height=h,l.width=_;u.drawImage(e,0,0),a=u.getImageData(0,0,_,h).data}else throw new Error(\"Can not access image data\")}else if(n){let m,u;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(m=t.resizedHeight,u=t.resizedWidth):(m=e.height,u=e.width),t!==void 0&&(l=t),l.format=\"RGBA\",l.height=m,l.width=u,t!==void 0){let h=d();h.width=u,h.height=m;let _=p(h);if(_!=null)_.putImageData(e,0,0),a=_.getImageData(0,0,u,m).data;else throw new Error(\"Can not access image data\")}else a=e.data}else if(o){if(t===void 0)throw new Error(\"Please provide image config with format for Imagebitmap\");let m=d();m.width=e.width,m.height=e.height;let u=p(m);if(u!=null){let h=e.height,_=e.width;return u.drawImage(e,0,0,_,h),a=u.getImageData(0,0,_,h).data,l.height=h,l.width=_,Fn(a,l)}else throw new Error(\"Can not access image data\")}else{if(i)return new Promise((m,u)=>{let h=d(),_=p(h);if(!e||!_)return u();let y=new Image;y.crossOrigin=\"Anonymous\",y.src=e,y.onload=()=>{h.width=y.width,h.height=y.height,_.drawImage(y,0,0,h.width,h.height);let g=_.getImageData(0,0,h.width,h.height);l.height=h.height,l.width=h.width,m(Fn(g.data,l))}});throw new Error(\"Input data provided is not supported - aborted tensor creation\")}if(a!==void 0)return Fn(a,l);throw new Error(\"Input data provided is not supported - aborted tensor creation\")},la=(e,t)=>{let{width:r,height:n,download:o,dispose:i}=t,a=[1,n,r,4];return new ze({location:\"texture\",type:\"float32\",texture:e,dims:a,download:o,dispose:i})},da=(e,t)=>{let{dataType:r,dims:n,download:o,dispose:i}=t;return new ze({location:\"gpu-buffer\",type:r??\"float32\",gpuBuffer:e,dims:n,download:o,dispose:i})},ca=(e,t)=>{let{dataType:r,dims:n,download:o,dispose:i}=t;return new ze({location:\"ml-tensor\",type:r??\"float32\",mlTensor:e,dims:n,download:o,dispose:i})},pa=(e,t,r)=>new ze({location:\"cpu-pinned\",type:e,data:t,dims:r??[t.length]})});var St,qt,fa,ha,ga=R(()=>{\"use strict\";St=new Map([[\"float32\",Float32Array],[\"uint8\",Uint8Array],[\"int8\",Int8Array],[\"uint16\",Uint16Array],[\"int16\",Int16Array],[\"int32\",Int32Array],[\"bool\",Uint8Array],[\"float64\",Float64Array],[\"uint32\",Uint32Array],[\"int4\",Uint8Array],[\"uint4\",Uint8Array]]),qt=new Map([[Float32Array,\"float32\"],[Uint8Array,\"uint8\"],[Int8Array,\"int8\"],[Uint16Array,\"uint16\"],[Int16Array,\"int16\"],[Int32Array,\"int32\"],[Float64Array,\"float64\"],[Uint32Array,\"uint32\"]]),fa=!1,ha=()=>{if(!fa){fa=!0;let e=typeof BigInt64Array<\"u\"&&BigInt64Array.from,t=typeof BigUint64Array<\"u\"&&BigUint64Array.from,r=typeof Float16Array<\"u\"&&Float16Array.from;e&&(St.set(\"int64\",BigInt64Array),qt.set(BigInt64Array,\"int64\")),t&&(St.set(\"uint64\",BigUint64Array),qt.set(BigUint64Array,\"uint64\")),r?(St.set(\"float16\",Float16Array),qt.set(Float16Array,\"float16\")):St.set(\"float16\",Uint16Array)}}});var ba,ya,_a=R(()=>{\"use strict\";vr();ba=e=>{let t=1;for(let r=0;r{switch(e.location){case\"cpu\":return new ze(e.type,e.data,t);case\"cpu-pinned\":return new ze({location:\"cpu-pinned\",data:e.data,type:e.type,dims:t});case\"texture\":return new ze({location:\"texture\",texture:e.texture,type:e.type,dims:t});case\"gpu-buffer\":return new ze({location:\"gpu-buffer\",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case\"ml-tensor\":return new ze({location:\"ml-tensor\",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}});var ze,vr=R(()=>{\"use strict\";sa();ma();ga();_a();ze=class{constructor(t,r,n){ha();let o,i;if(typeof t==\"object\"&&\"location\"in t)switch(this.dataLocation=t.location,o=t.type,i=t.dims,t.location){case\"cpu-pinned\":{let l=St.get(o);if(!l)throw new TypeError(`unsupported type \"${o}\" to create tensor from pinned buffer`);if(!(t.data instanceof l))throw new TypeError(`buffer should be of type ${l.name}`);this.cpuData=t.data;break}case\"texture\":{if(o!==\"float32\")throw new TypeError(`unsupported type \"${o}\" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case\"gpu-buffer\":{if(o!==\"float32\"&&o!==\"float16\"&&o!==\"int32\"&&o!==\"int64\"&&o!==\"uint32\"&&o!==\"uint8\"&&o!==\"bool\"&&o!==\"uint4\"&&o!==\"int4\")throw new TypeError(`unsupported type \"${o}\" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case\"ml-tensor\":{if(o!==\"float32\"&&o!==\"float16\"&&o!==\"int32\"&&o!==\"int64\"&&o!==\"uint32\"&&o!==\"uint64\"&&o!==\"int8\"&&o!==\"uint8\"&&o!==\"bool\"&&o!==\"uint4\"&&o!==\"int4\")throw new TypeError(`unsupported type \"${o}\" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let l,d;if(typeof t==\"string\")if(o=t,d=n,t===\"string\"){if(!Array.isArray(r))throw new TypeError(\"A string tensor's data must be a string array.\");l=r}else{let p=St.get(t);if(p===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t===\"float16\"&&p===Uint16Array||t===\"uint4\"||t===\"int4\")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${p.name} as data.`);t===\"uint64\"||t===\"int64\"?l=p.from(r,BigInt):l=p.from(r)}else if(r instanceof p)l=r;else if(r instanceof Uint8ClampedArray)if(t===\"uint8\")l=Uint8Array.from(r);else throw new TypeError(\"A Uint8ClampedArray tensor's data must be type of uint8\");else throw new TypeError(`A ${o} tensor's data must be type of ${p}`)}else if(d=r,Array.isArray(t)){if(t.length===0)throw new TypeError(\"Tensor type cannot be inferred from an empty array.\");let p=typeof t[0];if(p===\"string\")o=\"string\",l=t;else if(p===\"boolean\")o=\"bool\",l=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${p}.`)}else if(t instanceof Uint8ClampedArray)o=\"uint8\",l=Uint8Array.from(t);else{let p=qt.get(t.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);o=p,l=t}if(d===void 0)d=[l.length];else if(!Array.isArray(d))throw new TypeError(\"A tensor's dims must be a number array\");i=d,this.cpuData=l,this.dataLocation=\"cpu\"}let a=ba(i);if(this.cpuData&&a!==this.cpuData.length&&!((o===\"uint4\"||o===\"int4\")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=i,this.size=a}static async fromImage(t,r){return ua(t,r)}static fromTexture(t,r){return la(t,r)}static fromGpuBuffer(t,r){return da(t,r)}static fromMLTensor(t,r){return ca(t,r)}static fromPinnedBuffer(t,r,n){return pa(t,r,n)}toDataURL(t){return ia(this,t)}toImageData(t){return aa(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error(\"The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.\");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error(\"The data is not stored as a WebGL texture.\");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error(\"The data is not stored as a WebGPU buffer.\");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error(\"The data is not stored as a WebNN MLTensor.\");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case\"cpu\":case\"cpu-pinned\":return this.data;case\"texture\":case\"gpu-buffer\":case\"ml-tensor\":{if(!this.downloader)throw new Error(\"The current tensor is not created with a specified data downloader.\");if(this.isDownloading)throw new Error(\"The current tensor is being downloaded.\");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation=\"cpu\",this.cpuData=r,t&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error(\"The current tensor is being downloaded.\");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=\"none\"}ensureValid(){if(this.dataLocation===\"none\")throw new Error(\"The tensor is disposed.\")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error(\"Cannot reshape a tensor that owns GPU resource.\");return ya(this,t)}}});var Oe,$r=R(()=>{\"use strict\";vr();Oe=ze});var xr,wa,Ue,De,qn=R(()=>{\"use strict\";Hn();xr=(e,t)=>{(typeof Re.trace>\"u\"?!Re.wasm.trace:!Re.trace)||console.timeStamp(`${e}::ORT::${t}`)},wa=(e,t)=>{let r=new Error().stack?.split(/\\r\\n|\\r|\\n/g)||[],n=!1;for(let o=0;o{(typeof Re.trace>\"u\"?!Re.wasm.trace:!Re.trace)||wa(\"BEGIN\",e)},De=e=>{(typeof Re.trace>\"u\"?!Re.wasm.trace:!Re.trace)||wa(\"END\",e)}});var Sr,va=R(()=>{\"use strict\";wr();$r();qn();Sr=class e{constructor(t){this.handler=t}async run(t,r,n){Ue();let o={},i={};if(typeof t!=\"object\"||t===null||t instanceof Oe||Array.isArray(t))throw new TypeError(\"'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.\");let a=!0;if(typeof r==\"object\"){if(r===null)throw new TypeError(\"Unexpected argument[1]: cannot be null.\");if(r instanceof Oe)throw new TypeError(\"'fetches' cannot be a Tensor\");if(Array.isArray(r)){if(r.length===0)throw new TypeError(\"'fetches' cannot be an empty array.\");a=!1;for(let p of r){if(typeof p!=\"string\")throw new TypeError(\"'fetches' must be a string array or an object.\");if(this.outputNames.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);o[p]=null}if(typeof n==\"object\"&&n!==null)i=n;else if(typeof n<\"u\")throw new TypeError(\"'options' must be an object.\")}else{let p=!1,m=Object.getOwnPropertyNames(r);for(let u of this.outputNames)if(m.indexOf(u)!==-1){let h=r[u];(h===null||h instanceof Oe)&&(p=!0,a=!1,o[u]=h)}if(p){if(typeof n==\"object\"&&n!==null)i=n;else if(typeof n<\"u\")throw new TypeError(\"'options' must be an object.\")}else i=r}}else if(typeof r<\"u\")throw new TypeError(\"Unexpected argument[1]: must be 'fetches' or 'options'.\");for(let p of this.inputNames)if(typeof t[p]>\"u\")throw new Error(`input '${p}' is missing in 'feeds'.`);if(a)for(let p of this.outputNames)o[p]=null;let l=await this.handler.run(t,o,i),d={};for(let p in l)if(Object.hasOwnProperty.call(l,p)){let m=l[p];m instanceof Oe?d[p]=m:d[p]=new Oe(m.type,m.data,m.dims)}return De(),d}async release(){return this.handler.dispose()}static async create(t,r,n,o){Ue();let i,a={};if(typeof t==\"string\"){if(i=t,typeof r==\"object\"&&r!==null)a=r;else if(typeof r<\"u\")throw new TypeError(\"'options' must be an object.\")}else if(t instanceof Uint8Array){if(i=t,typeof r==\"object\"&&r!==null)a=r;else if(typeof r<\"u\")throw new TypeError(\"'options' must be an object.\")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<\"u\"&&t instanceof SharedArrayBuffer){let m=t,u=0,h=t.byteLength;if(typeof r==\"object\"&&r!==null)a=r;else if(typeof r==\"number\"){if(u=r,!Number.isSafeInteger(u))throw new RangeError(\"'byteOffset' must be an integer.\");if(u<0||u>=m.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${m.byteLength}).`);if(h=t.byteLength-u,typeof n==\"number\"){if(h=n,!Number.isSafeInteger(h))throw new RangeError(\"'byteLength' must be an integer.\");if(h<=0||u+h>m.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${m.byteLength-u}].`);if(typeof o==\"object\"&&o!==null)a=o;else if(typeof o<\"u\")throw new TypeError(\"'options' must be an object.\")}else if(typeof n<\"u\")throw new TypeError(\"'byteLength' must be a number.\")}else if(typeof r<\"u\")throw new TypeError(\"'options' must be an object.\");i=new Uint8Array(m,u,h)}else throw new TypeError(\"Unexpected argument[0]: must be 'path' or 'buffer'.\");let[l,d]=await _r(a),p=await l.createInferenceSessionHandler(i,d);return De(),new e(p)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}});var Np,$a=R(()=>{\"use strict\";va();Np=Sr});var xa=R(()=>{\"use strict\"});var Sa=R(()=>{\"use strict\"});var Ta=R(()=>{\"use strict\"});var Ia=R(()=>{\"use strict\"});var Vp,Tr,Ca=R(()=>{\"use strict\";wr();$r();Vp=\"Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.\",Tr=class e{constructor(t,r,n){this.handler=t,this.hasOptimizerModel=r,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error(\"This training session has no evalModel loaded.\")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error(\"This training session has no evalModel loaded.\")}static async create(t,r){let n=t.evalModel||\"\",o=t.optimizerModel||\"\",i=r||{},[a,l]=await _r(i);if(a.createTrainingSessionHandler){let d=await a.createTrainingSessionHandler(t.checkpointState,t.trainModel,n,o,l);return new e(d,!!t.optimizerModel,!!t.evalModel)}else throw new Error(Vp)}typeNarrowingForRunStep(t,r,n,o,i){let a={},l={};if(typeof n!=\"object\"||n===null||n instanceof Oe||Array.isArray(n))throw new TypeError(\"'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.\");let d=!0;if(typeof o==\"object\"){if(o===null)throw new TypeError(\"Unexpected argument[1]: cannot be null.\");if(o instanceof Oe)throw new TypeError(\"'fetches' cannot be a Tensor\");if(Array.isArray(o)){if(o.length===0)throw new TypeError(\"'fetches' cannot be an empty array.\");d=!1;for(let p of o){if(typeof p!=\"string\")throw new TypeError(\"'fetches' must be a string array or an object.\");if(r.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);a[p]=null}if(typeof i==\"object\"&&i!==null)l=i;else if(typeof i<\"u\")throw new TypeError(\"'options' must be an object.\")}else{let p=!1,m=Object.getOwnPropertyNames(o);for(let u of r)if(m.indexOf(u)!==-1){let h=o[u];(h===null||h instanceof Oe)&&(p=!0,d=!1,a[u]=h)}if(p){if(typeof i==\"object\"&&i!==null)l=i;else if(typeof i<\"u\")throw new TypeError(\"'options' must be an object.\")}else l=o}}else if(typeof o<\"u\")throw new TypeError(\"Unexpected argument[1]: must be 'fetches' or 'options'.\");for(let p of t)if(typeof n[p]>\"u\")throw new Error(`input '${p}' is missing in 'feeds'.`);if(d)for(let p of r)a[p]=null;return[a,l]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let n in t)if(Object.hasOwnProperty.call(t,n)){let o=t[n];o instanceof Oe?r[n]=o:r[n]=new Oe(o.type,o.data,o.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,n){let[o,i]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,n),a=await this.handler.runTrainStep(t,o,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}async runOptimizerStep(t){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(t||{});else throw new Error(\"This TrainingSession has no OptimizerModel loaded.\")}async runEvalStep(t,r,n){if(this.hasEvalModel){let[o,i]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,n),a=await this.handler.runEvalStep(t,o,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}else throw new Error(\"This TrainingSession has no EvalModel loaded.\")}async getParametersSize(t=!0){return this.handler.getParametersSize(t)}async loadParametersBuffer(t,r=!0){let n=await this.getParametersSize(r);if(t.length!==4*n)throw new Error(\"Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.\");return this.handler.loadParametersBuffer(t,r)}async getContiguousParameters(t=!0){return this.handler.getContiguousParameters(t)}async release(){return this.handler.dispose()}}});var Wp,Aa=R(()=>{\"use strict\";Ca();Wp=Tr});var jn={};Ft(jn,{InferenceSession:()=>Np,TRACE:()=>xr,TRACE_FUNC_BEGIN:()=>Ue,TRACE_FUNC_END:()=>De,Tensor:()=>Oe,TrainingSession:()=>Wp,env:()=>we,registerBackend:()=>xt});var We=R(()=>{\"use strict\";ea();oa();$a();$r();xa();Sa();qn();Ta();Ia();Aa()});var Ir=R(()=>{\"use strict\"});var za={};Ft(za,{default:()=>Lp});var Ea,Pa,Lp,Oa=R(()=>{\"use strict\";Kn();ht();jt();Ea=\"ort-wasm-proxy-worker\",Pa=globalThis.self?.name===Ea;Pa&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case\"init-wasm\":Cr(r.wasm).then(()=>{Ar(r).then(()=>{postMessage({type:t})},n=>{postMessage({type:t,err:n})})},n=>{postMessage({type:t,err:n})});break;case\"init-ep\":{let{epName:n,env:o}=r;kr(o,n).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case\"copy-from\":{let{buffer:n}=r,o=Kt(n);postMessage({type:t,out:o});break}case\"create\":{let{model:n,options:o}=r;Er(n,o).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case\"release\":Pr(r),postMessage({type:t});break;case\"run\":{let{sessionId:n,inputIndices:o,inputs:i,outputIndices:a,options:l}=r;zr(n,o,i,a,new Array(a.length).fill(null),l).then(d=>{d.some(p=>p[3]!==\"cpu\")?postMessage({type:t,err:\"Proxy does not support non-cpu tensor location.\"}):postMessage({type:t,out:d},Br([...i,...d]))},d=>{postMessage({type:t,err:d})});break}case\"end-profiling\":Or(r),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}});Lp=Pa?null:e=>new Worker(e??Dt,{type:\"module\",name:Ea})});var Da={};Ft(Da,{default:()=>Gp});var Yn,Ba,Gp,Ma=R(()=>{\"use strict\";Ba=(Yn=import.meta.url,async function(e={}){function t(){return se.buffer!=ee.buffer&&be(),ee}function r(){return se.buffer!=ee.buffer&&be(),ne}function n(){return se.buffer!=ee.buffer&&be(),ve}function o(){return se.buffer!=ee.buffer&&be(),Be}function i(){return se.buffer!=ee.buffer&&be(),$e}function a(){return se.buffer!=ee.buffer&&be(),de}function l(){return se.buffer!=ee.buffer&&be(),V}function d(){return se.buffer!=ee.buffer&&be(),Ge}var p,m,u=Object.assign({},e),h=new Promise((s,c)=>{p=s,m=c}),_=typeof window==\"object\",y=typeof importScripts==\"function\",g=y&&self.name==\"em-pthread\";u.mountExternalData=(s,c)=>{s.startsWith(\"./\")&&(s=s.substring(2)),(u.Eb||(u.Eb=new Map)).set(s,c)},u.unmountExternalData=()=>{delete u.Eb};var x=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let $=()=>{let s=(f,b,w)=>(...I)=>{let B=Qe,D=b?.();I=f(...I);let L=b?.();return D!==L&&(f=L,w(D),b=w=null),Qe!=B?new Promise((H,Q)=>{Bn={resolve:H,reject:Q}}):I},c=f=>async(...b)=>{try{if(u.Fb)throw Error(\"Session already started\");let w=u.Fb={fc:b[0],errors:[]},I=await f(...b);if(u.Fb!==w)throw Error(\"Session mismatch\");u.Gb?.flush();let B=w.errors;if(0L),0u._OrtCreateSession,f=>u._OrtCreateSession=f),u._OrtRun=c(s(u._OrtRun,()=>u._OrtRun,f=>u._OrtRun=f)),u._OrtRunWithBinding=c(s(u._OrtRunWithBinding,()=>u._OrtRunWithBinding,f=>u._OrtRunWithBinding=f)),u._OrtBindInput=s(u._OrtBindInput,()=>u._OrtBindInput,f=>u._OrtBindInput=f),$=void 0};u.jsepInit=(s,c)=>{if($?.(),s===\"webgpu\"){[u.Gb,u.Ub,u.Yb,u.Nb,u.Xb,u.jb,u.Zb,u.bc,u.Vb,u.Wb,u.$b]=c;let f=u.Gb;u.jsepRegisterBuffer=(b,w,I,B)=>f.registerBuffer(b,w,I,B),u.jsepGetBuffer=b=>f.getBuffer(b),u.jsepCreateDownloader=(b,w,I)=>f.createDownloader(b,w,I),u.jsepOnCreateSession=b=>{f.onCreateSession(b)},u.jsepOnReleaseSession=b=>{f.onReleaseSession(b)},u.jsepOnRunStart=b=>f.onRunStart(b),u.cc=(b,w)=>{f.upload(b,w)}}else if(s===\"webnn\"){[u.Gb,u.ac,u.Ob,u.jsepEnsureTensor,u.dc,u.jsepDownloadTensor]=c,u.jsepReleaseTensorId=u.Ob;let f=u.Gb;u.jsepOnRunStart=b=>f.onRunStart(b),u.jsepRegisterMLContext=(b,w)=>{f.registerMLContext(b,w)},u.jsepOnReleaseSession=b=>{f.onReleaseSession(b)},u.jsepCreateMLTensorDownloader=(b,w)=>f.createMLTensorDownloader(b,w),u.jsepRegisterMLTensor=(b,w,I)=>f.registerMLTensor(b,w,I),u.jsepCreateMLContext=b=>f.createMLContext(b),u.jsepRegisterMLConstant=(b,w,I,B,D)=>f.registerMLConstant(b,w,I,B,D,u.Eb)}};var v,S,T=Object.assign({},u),C=\"./this.program\",A=(s,c)=>{throw c},P=\"\";(_||y)&&(y?P=self.location.href:typeof document<\"u\"&&document.currentScript&&(P=document.currentScript.src),Yn&&(P=Yn),P=P.startsWith(\"blob:\")?\"\":P.substr(0,P.replace(/[?#].*/,\"\").lastIndexOf(\"/\")+1),y&&(S=s=>{var c=new XMLHttpRequest;return c.open(\"GET\",s,!1),c.responseType=\"arraybuffer\",c.send(null),new Uint8Array(c.response)}),v=(s,c,f)=>{var b=new XMLHttpRequest;b.open(\"GET\",s,!0),b.responseType=\"arraybuffer\",b.onload=()=>{b.status==200||b.status==0&&b.response?c(b.response):f()},b.onerror=f,b.send(null)});var O,U=console.log.bind(console),G=console.error.bind(console),q=U,K=G;if(Object.assign(u,T),T=null,g){let s=function(c){try{var f=c.data,b=f.cmd;if(b===\"load\"){let w=[];self.onmessage=I=>w.push(I),self.startWorker=()=>{postMessage({cmd:\"loaded\"});for(let I of w)s(I);self.onmessage=s};for(let I of f.handlers)u[I]&&!u[I].proxy||(u[I]=(...B)=>{postMessage({Mb:\"callHandler\",oc:I,args:B})},I==\"print\"&&(q=u[I]),I==\"printErr\"&&(K=u[I]));se=f.wasmMemory,be(),W(f.wasmModule)}else if(b===\"run\"){Un(f.pthread_ptr,0,0,1,0,0),Pn(f.pthread_ptr),yc(),Fo(),Y||(Li(),Y=!0);try{_c(f.start_routine,f.arg)}catch(w){if(w!=\"unwind\")throw w}}else b===\"cancel\"?Bt()&&hr(-1):f.target!==\"setimmediate\"&&(b===\"checkMailbox\"?Y&&ar():b&&(K(`worker: received unknown command ${b}`),K(f)))}catch(w){throw Gi(),w}};var hg=s,W,Y=!1;K=function(...c){c=c.join(\" \"),console.error(c)},self.alert=function(...c){postMessage({Mb:\"alert\",text:c.join(\" \"),qc:Bt()})},u.instantiateWasm=(c,f)=>new Promise(b=>{W=w=>{w=new WebAssembly.Instance(w,Vo()),f(w),b()}}),self.onunhandledrejection=c=>{throw c.reason||c},self.onmessage=s}u.wasmBinary&&(O=u.wasmBinary);var se,X,re,ee,ne,ve,Be,$e,de,V,j,he,Ge,_e=!1;function be(){var s=se.buffer;u.HEAP8=ee=new Int8Array(s),u.HEAP16=ve=new Int16Array(s),u.HEAPU8=ne=new Uint8Array(s),u.HEAPU16=Be=new Uint16Array(s),u.HEAP32=$e=new Int32Array(s),u.HEAPU32=de=new Uint32Array(s),u.HEAPF32=V=new Float32Array(s),u.HEAPF64=Ge=new Float64Array(s),u.HEAP64=j=new BigInt64Array(s),u.HEAPU64=he=new BigUint64Array(s)}if(!g){if(!((se=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof x))throw K(\"requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag\"),Error(\"bad memory\");be()}var Ke=[],Lt=[],bn=[],Gt=0,yn=null,Ht=null;function Do(){if(--Gt==0&&(yn!==null&&(clearInterval(yn),yn=null),Ht)){var s=Ht;Ht=null,s()}}function dt(s){throw K(s=\"Aborted(\"+s+\")\"),_e=!0,re=1,s=new WebAssembly.RuntimeError(s+\". Build with -sASSERTIONS for more info.\"),m(s),s}var _n,Mo=s=>s.startsWith(\"data:application/octet-stream;base64,\"),Ro=s=>s.startsWith(\"file://\");function Uo(s){if(s==_n&&O)return new Uint8Array(O);if(S)return S(s);throw\"both async and sync fetching of the wasm failed\"}function No(s,c,f){return function(b){if(!O&&(_||y)){if(typeof fetch==\"function\"&&!Ro(b))return fetch(b,{credentials:\"same-origin\"}).then(w=>{if(!w.ok)throw`failed to load wasm binary file at '${b}'`;return w.arrayBuffer()}).catch(()=>Uo(b));if(v)return new Promise((w,I)=>{v(b,B=>w(new Uint8Array(B)),I)})}return Promise.resolve().then(()=>Uo(b))}(s).then(b=>WebAssembly.instantiate(b,c)).then(f,b=>{K(`failed to asynchronously prepare wasm: ${b}`),dt(b)})}function Vo(){return{a:{O:bc,Aa:gc,b:vc,aa:Yo,B:Xo,qa:Jo,Y:ti,_:ri,ra:ni,oa:oi,ha:ii,na:ai,L:si,Z:ui,W:li,pa:di,X:ci,wa:$c,F:Sc,Q:Tc,P:Cc,E:kc,u:Ec,q:Pc,G:zc,A:Nc,R:Vc,ua:Wc,ka:Lc,U:Gc,ba:Hc,H:Fc,ja:Pn,ta:qc,t:jc,x:Zc,o:Qc,m:Jc,c:kn,n:ep,k:np,w:op,p:ip,f:ap,s:sp,l:up,e:lp,j:dp,i:cp,h:pp,d:mp,ea:fp,fa:hp,ga:gp,ca:Ti,da:Ii,T:bp,g:yp,D:_p,I:wp,M:vp,y:$p,sa:xp,V:Sp,v:Ai,z:Tp,N:Ip,S:Cp,za:Ap,ya:kp,la:Pi,ma:zi,$:Sn,C:Oi,K:Bi,ia:Di,J:Mi,a:se,xa:xn,va:Ni,r:zp}}}var wn={873844:(s,c,f,b,w)=>{if(u===void 0||!u.Eb)return 1;if((s=Te(Number(s>>>0))).startsWith(\"./\")&&(s=s.substring(2)),!(s=u.Eb.get(s)))return 2;if(c=Number(c>>>0),f=Number(f>>>0),b=Number(b>>>0),c+f>s.byteLength)return 3;try{let I=s.subarray(c,c+f);switch(w){case 0:r().set(I,b>>>0);break;case 1:u.cc(b,I);break;default:return 4}return 0}catch{return 4}},874559:(s,c,f)=>{u.dc(s,r().subarray(c>>>0,c+f>>>0))},874622:()=>u.ac(),874663:s=>{u.Ob(s)},874699:()=>{u.Vb()},874730:()=>{u.Wb()},874759:()=>{u.$b()},874784:s=>u.Ub(s),874817:s=>u.Yb(s),874849:(s,c,f)=>{u.Nb(Number(s),Number(c),Number(f),!0)},874912:(s,c,f)=>{u.Nb(Number(s),Number(c),Number(f))},874969:()=>typeof wasmOffsetConverter<\"u\",875026:s=>{u.jb(\"Abs\",s,void 0)},875077:s=>{u.jb(\"Neg\",s,void 0)},875128:s=>{u.jb(\"Floor\",s,void 0)},875181:s=>{u.jb(\"Ceil\",s,void 0)},875233:s=>{u.jb(\"Reciprocal\",s,void 0)},875291:s=>{u.jb(\"Sqrt\",s,void 0)},875343:s=>{u.jb(\"Exp\",s,void 0)},875394:s=>{u.jb(\"Erf\",s,void 0)},875445:s=>{u.jb(\"Sigmoid\",s,void 0)},875500:(s,c,f)=>{u.jb(\"HardSigmoid\",s,{alpha:c,beta:f})},875579:s=>{u.jb(\"Log\",s,void 0)},875630:s=>{u.jb(\"Sin\",s,void 0)},875681:s=>{u.jb(\"Cos\",s,void 0)},875732:s=>{u.jb(\"Tan\",s,void 0)},875783:s=>{u.jb(\"Asin\",s,void 0)},875835:s=>{u.jb(\"Acos\",s,void 0)},875887:s=>{u.jb(\"Atan\",s,void 0)},875939:s=>{u.jb(\"Sinh\",s,void 0)},875991:s=>{u.jb(\"Cosh\",s,void 0)},876043:s=>{u.jb(\"Asinh\",s,void 0)},876096:s=>{u.jb(\"Acosh\",s,void 0)},876149:s=>{u.jb(\"Atanh\",s,void 0)},876202:s=>{u.jb(\"Tanh\",s,void 0)},876254:s=>{u.jb(\"Not\",s,void 0)},876305:(s,c,f)=>{u.jb(\"Clip\",s,{min:c,max:f})},876374:s=>{u.jb(\"Clip\",s,void 0)},876426:(s,c)=>{u.jb(\"Elu\",s,{alpha:c})},876484:s=>{u.jb(\"Gelu\",s,void 0)},876536:s=>{u.jb(\"Relu\",s,void 0)},876588:(s,c)=>{u.jb(\"LeakyRelu\",s,{alpha:c})},876652:(s,c)=>{u.jb(\"ThresholdedRelu\",s,{alpha:c})},876722:(s,c)=>{u.jb(\"Cast\",s,{to:c})},876780:s=>{u.jb(\"Add\",s,void 0)},876831:s=>{u.jb(\"Sub\",s,void 0)},876882:s=>{u.jb(\"Mul\",s,void 0)},876933:s=>{u.jb(\"Div\",s,void 0)},876984:s=>{u.jb(\"Pow\",s,void 0)},877035:s=>{u.jb(\"Equal\",s,void 0)},877088:s=>{u.jb(\"Greater\",s,void 0)},877143:s=>{u.jb(\"GreaterOrEqual\",s,void 0)},877205:s=>{u.jb(\"Less\",s,void 0)},877257:s=>{u.jb(\"LessOrEqual\",s,void 0)},877316:(s,c,f,b,w)=>{u.jb(\"ReduceMean\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},877491:(s,c,f,b,w)=>{u.jb(\"ReduceMax\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},877665:(s,c,f,b,w)=>{u.jb(\"ReduceMin\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},877839:(s,c,f,b,w)=>{u.jb(\"ReduceProd\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},878014:(s,c,f,b,w)=>{u.jb(\"ReduceSum\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},878188:(s,c,f,b,w)=>{u.jb(\"ReduceL1\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},878361:(s,c,f,b,w)=>{u.jb(\"ReduceL2\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},878534:(s,c,f,b,w)=>{u.jb(\"ReduceLogSum\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},878711:(s,c,f,b,w)=>{u.jb(\"ReduceSumSquare\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},878891:(s,c,f,b,w)=>{u.jb(\"ReduceLogSumExp\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},879071:s=>{u.jb(\"Where\",s,void 0)},879124:(s,c,f)=>{u.jb(\"Transpose\",s,{perm:c?Array.from(i().subarray(Number(c)>>>0,Number(f)>>>0)):[]})},879248:(s,c,f,b)=>{u.jb(\"DepthToSpace\",s,{blocksize:c,mode:Te(f),format:b?\"NHWC\":\"NCHW\"})},879381:(s,c,f,b)=>{u.jb(\"DepthToSpace\",s,{blocksize:c,mode:Te(f),format:b?\"NHWC\":\"NCHW\"})},879514:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z,le)=>{u.jb(\"ConvTranspose\",s,{format:L?\"NHWC\":\"NCHW\",autoPad:c,dilations:[f],group:b,kernelShape:[w],pads:[I,B],strides:[D],wIsConst:()=>!!t()[H>>>0],outputPadding:Q?Array.from(i().subarray(Number(Q)>>>0,Number(ce)>>>0)):[],outputShape:ge?Array.from(i().subarray(Number(ge)>>>0,Number(z)>>>0)):[],activation:Te(le)})},879947:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z)=>{u.jb(\"ConvTranspose\",s,{format:D?\"NHWC\":\"NCHW\",autoPad:c,dilations:Array.from(i().subarray(Number(f)>>>0,2+(Number(f)>>>0)>>>0)),group:b,kernelShape:Array.from(i().subarray(Number(w)>>>0,2+(Number(w)>>>0)>>>0)),pads:Array.from(i().subarray(Number(I)>>>0,4+(Number(I)>>>0)>>>0)),strides:Array.from(i().subarray(Number(B)>>>0,2+(Number(B)>>>0)>>>0)),wIsConst:()=>!!t()[L>>>0],outputPadding:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],outputShape:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[],activation:Te(z)})},880608:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z,le)=>{u.jb(\"ConvTranspose\",s,{format:L?\"NHWC\":\"NCHW\",autoPad:c,dilations:[f],group:b,kernelShape:[w],pads:[I,B],strides:[D],wIsConst:()=>!!t()[H>>>0],outputPadding:Q?Array.from(i().subarray(Number(Q)>>>0,Number(ce)>>>0)):[],outputShape:ge?Array.from(i().subarray(Number(ge)>>>0,Number(z)>>>0)):[],activation:Te(le)})},881041:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z)=>{u.jb(\"ConvTranspose\",s,{format:D?\"NHWC\":\"NCHW\",autoPad:c,dilations:Array.from(i().subarray(Number(f)>>>0,2+(Number(f)>>>0)>>>0)),group:b,kernelShape:Array.from(i().subarray(Number(w)>>>0,2+(Number(w)>>>0)>>>0)),pads:Array.from(i().subarray(Number(I)>>>0,4+(Number(I)>>>0)>>>0)),strides:Array.from(i().subarray(Number(B)>>>0,2+(Number(B)>>>0)>>>0)),wIsConst:()=>!!t()[L>>>0],outputPadding:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],outputShape:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[],activation:Te(z)})},881702:(s,c)=>{u.jb(\"GlobalAveragePool\",s,{format:c?\"NHWC\":\"NCHW\"})},881793:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z)=>{u.jb(\"AveragePool\",s,{format:z?\"NHWC\":\"NCHW\",auto_pad:c,ceil_mode:f,count_include_pad:b,storage_order:w,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(B)>>>0)):[],kernel_shape:D?Array.from(i().subarray(Number(D)>>>0,Number(L)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},882272:(s,c)=>{u.jb(\"GlobalAveragePool\",s,{format:c?\"NHWC\":\"NCHW\"})},882363:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z)=>{u.jb(\"AveragePool\",s,{format:z?\"NHWC\":\"NCHW\",auto_pad:c,ceil_mode:f,count_include_pad:b,storage_order:w,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(B)>>>0)):[],kernel_shape:D?Array.from(i().subarray(Number(D)>>>0,Number(L)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},882842:(s,c)=>{u.jb(\"GlobalMaxPool\",s,{format:c?\"NHWC\":\"NCHW\"})},882929:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z)=>{u.jb(\"MaxPool\",s,{format:z?\"NHWC\":\"NCHW\",auto_pad:c,ceil_mode:f,count_include_pad:b,storage_order:w,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(B)>>>0)):[],kernel_shape:D?Array.from(i().subarray(Number(D)>>>0,Number(L)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},883404:(s,c)=>{u.jb(\"GlobalMaxPool\",s,{format:c?\"NHWC\":\"NCHW\"})},883491:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z)=>{u.jb(\"MaxPool\",s,{format:z?\"NHWC\":\"NCHW\",auto_pad:c,ceil_mode:f,count_include_pad:b,storage_order:w,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(B)>>>0)):[],kernel_shape:D?Array.from(i().subarray(Number(D)>>>0,Number(L)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},883966:(s,c,f,b,w)=>{u.jb(\"Gemm\",s,{alpha:c,beta:f,transA:b,transB:w})},884070:s=>{u.jb(\"MatMul\",s,void 0)},884124:(s,c,f,b)=>{u.jb(\"ArgMax\",s,{keepDims:!!c,selectLastIndex:!!f,axis:b})},884232:(s,c,f,b)=>{u.jb(\"ArgMin\",s,{keepDims:!!c,selectLastIndex:!!f,axis:b})},884340:(s,c)=>{u.jb(\"Softmax\",s,{axis:c})},884403:(s,c)=>{u.jb(\"Concat\",s,{axis:c})},884463:(s,c,f,b,w)=>{u.jb(\"Split\",s,{axis:c,numOutputs:f,splitSizes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},884619:s=>{u.jb(\"Expand\",s,void 0)},884673:(s,c)=>{u.jb(\"Gather\",s,{axis:Number(c)})},884744:(s,c)=>{u.jb(\"GatherElements\",s,{axis:Number(c)})},884823:(s,c,f,b,w,I,B,D,L,H,Q)=>{u.jb(\"Resize\",s,{antialias:c,axes:f?Array.from(i().subarray(Number(f)>>>0,Number(b)>>>0)):[],coordinateTransformMode:Te(w),cubicCoeffA:I,excludeOutside:B,extrapolationValue:D,keepAspectRatioPolicy:Te(L),mode:Te(H),nearestMode:Te(Q)})},885185:(s,c,f,b,w,I,B)=>{u.jb(\"Slice\",s,{starts:c?Array.from(i().subarray(Number(c)>>>0,Number(f)>>>0)):[],ends:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[],axes:I?Array.from(i().subarray(Number(I)>>>0,Number(B)>>>0)):[]})},885449:s=>{u.jb(\"Tile\",s,void 0)},885501:(s,c,f)=>{u.jb(\"InstanceNormalization\",s,{epsilon:c,format:f?\"NHWC\":\"NCHW\"})},885615:(s,c,f)=>{u.jb(\"InstanceNormalization\",s,{epsilon:c,format:f?\"NHWC\":\"NCHW\"})},885729:s=>{u.jb(\"Range\",s,void 0)},885782:(s,c)=>{u.jb(\"Einsum\",s,{equation:Te(c)})},885863:(s,c,f,b,w)=>{u.jb(\"Pad\",s,{mode:c,value:f,pads:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},886006:(s,c,f,b,w,I)=>{u.jb(\"BatchNormalization\",s,{epsilon:c,momentum:f,spatial:!!w,trainingMode:!!b,format:I?\"NHWC\":\"NCHW\"})},886175:(s,c,f,b,w,I)=>{u.jb(\"BatchNormalization\",s,{epsilon:c,momentum:f,spatial:!!w,trainingMode:!!b,format:I?\"NHWC\":\"NCHW\"})},886344:(s,c,f)=>{u.jb(\"CumSum\",s,{exclusive:Number(c),reverse:Number(f)})},886441:(s,c,f)=>{u.jb(\"DequantizeLinear\",s,{axis:c,blockSize:f})},886531:(s,c,f,b,w)=>{u.jb(\"GridSample\",s,{align_corners:c,mode:Te(f),padding_mode:Te(b),format:w?\"NHWC\":\"NCHW\"})},886701:(s,c,f,b,w)=>{u.jb(\"GridSample\",s,{align_corners:c,mode:Te(f),padding_mode:Te(b),format:w?\"NHWC\":\"NCHW\"})},886871:(s,c)=>{u.jb(\"ScatterND\",s,{reduction:Te(c)})},886956:(s,c,f,b,w,I,B,D,L)=>{u.jb(\"Attention\",s,{numHeads:c,isUnidirectional:f,maskFilterValue:b,scale:w,doRotary:I,qkvHiddenSizes:B?Array.from(i().subarray(Number(D)>>>0,Number(D)+B>>>0)):[],pastPresentShareBuffer:!!L})},887228:s=>{u.jb(\"BiasAdd\",s,void 0)},887283:s=>{u.jb(\"BiasSplitGelu\",s,void 0)},887344:s=>{u.jb(\"FastGelu\",s,void 0)},887400:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z,le,Ie)=>{u.jb(\"Conv\",s,{format:ce?\"NHWC\":\"NCHW\",auto_pad:c,dilations:f?Array.from(i().subarray(Number(f)>>>0,Number(b)>>>0)):[],group:w,kernel_shape:I?Array.from(i().subarray(Number(I)>>>0,Number(B)>>>0)):[],pads:D?Array.from(i().subarray(Number(D)>>>0,Number(L)>>>0)):[],strides:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],w_is_const:()=>!!t()[Number(ge)>>>0],activation:Te(z),activation_params:le?Array.from(l().subarray(Number(le)>>>0,Number(Ie)>>>0)):[]})},887984:s=>{u.jb(\"Gelu\",s,void 0)},888036:(s,c,f,b,w,I,B,D,L)=>{u.jb(\"GroupQueryAttention\",s,{numHeads:c,kvNumHeads:f,scale:b,softcap:w,doRotary:I,rotaryInterleaved:B,smoothSoftmax:D,localWindowSize:L})},888253:(s,c,f,b)=>{u.jb(\"LayerNormalization\",s,{axis:c,epsilon:f,simplified:!!b})},888364:(s,c,f,b)=>{u.jb(\"LayerNormalization\",s,{axis:c,epsilon:f,simplified:!!b})},888475:(s,c,f,b,w,I)=>{u.jb(\"MatMulNBits\",s,{k:c,n:f,accuracyLevel:b,bits:w,blockSize:I})},888602:(s,c,f,b,w,I)=>{u.jb(\"MultiHeadAttention\",s,{numHeads:c,isUnidirectional:f,maskFilterValue:b,scale:w,doRotary:I})},888761:(s,c)=>{u.jb(\"QuickGelu\",s,{alpha:c})},888825:(s,c,f,b,w)=>{u.jb(\"RotaryEmbedding\",s,{interleaved:!!c,numHeads:f,rotaryEmbeddingDim:b,scale:w})},888964:(s,c,f)=>{u.jb(\"SkipLayerNormalization\",s,{epsilon:c,simplified:!!f})},889066:(s,c,f)=>{u.jb(\"SkipLayerNormalization\",s,{epsilon:c,simplified:!!f})},889168:(s,c,f,b)=>{u.jb(\"GatherBlockQuantized\",s,{gatherAxis:c,quantizeAxis:f,blockSize:b})},889289:s=>{u.Zb(s)},889323:(s,c)=>u.bc(Number(s),Number(c),u.Fb.fc,u.Fb.errors)};function gc(s,c,f){return wi(async()=>{await u.Xb(Number(s),Number(c),Number(f))})}function bc(){return typeof wasmOffsetConverter<\"u\"}function vn(s){this.name=\"ExitStatus\",this.message=`Program terminated with exit(${s})`,this.status=s}var $n=s=>{s.terminate(),s.onmessage=()=>{}},Wo=s=>{ct.length==0&&(jo(),qo(ct[0]));var c=ct.pop();if(!c)return 6;wt.push(c),Ye[s.Ab]=c,c.Ab=s.Ab;var f={cmd:\"run\",start_routine:s.hc,arg:s.Qb,pthread_ptr:s.Ab};return c.postMessage(f,s.mc),0},_t=0,xe=(s,c,...f)=>{for(var b=2*f.length,w=Wn(),I=Vn(8*b),B=I>>>3,D=0;D>>0]=L)}return s=Hi(s,0,b,I,c),gr(w),s};function xn(s){if(g)return xe(0,1,s);if(re=s,!(0<_t)){for(var c of wt)$n(c);for(c of ct)$n(c);ct=[],wt=[],Ye=[],_e=!0}A(s,new vn(s))}function Lo(s){if(g)return xe(1,0,s);Sn(s)}var Sn=s=>{if(re=s,g)throw Lo(s),\"unwind\";xn(s)},ct=[],wt=[],Go=[],Ye={},Ho=s=>{var c=s.Ab;delete Ye[c],ct.push(s),wt.splice(wt.indexOf(s),1),s.Ab=0,Nn(c)};function Fo(){Go.forEach(s=>s())}var qo=s=>new Promise(c=>{s.onmessage=w=>{var I=(w=w.data).cmd;if(w.targetThread&&w.targetThread!=Bt()){var B=Ye[w.targetThread];B?B.postMessage(w,w.transferList):K(`Internal error! Worker sent a message \"${I}\" to target pthread ${w.targetThread}, but that thread no longer exists!`)}else I===\"checkMailbox\"?ar():I===\"spawnThread\"?Wo(w):I===\"cleanupThread\"?Ho(Ye[w.thread]):I===\"killThread\"?(w=w.thread,I=Ye[w],delete Ye[w],$n(I),Nn(w),wt.splice(wt.indexOf(I),1),I.Ab=0):I===\"cancelThread\"?Ye[w.thread].postMessage({cmd:\"cancel\"}):I===\"loaded\"?(s.loaded=!0,c(s)):I===\"alert\"?alert(`Thread ${w.threadId}: ${w.text}`):w.target===\"setimmediate\"?s.postMessage(w):I===\"callHandler\"?u[w.handler](...w.args):I&&K(`worker sent an unknown command ${I}`)},s.onerror=w=>{throw K(`worker sent an error! ${w.filename}:${w.lineno}: ${w.message}`),w};var f,b=[];for(f of[])u.hasOwnProperty(f)&&b.push(f);s.postMessage({cmd:\"load\",handlers:b,wasmMemory:se,wasmModule:X})});function jo(){var s=new Worker(new URL(import.meta.url),{type:\"module\",workerData:\"em-pthread\",name:\"em-pthread\"});ct.push(s)}var ir=s=>{for(;0{var s=Bt(),c=a()[s+52>>>2>>>0];s=a()[s+56>>>2>>>0],qi(c,c-s),gr(c)},_c=(s,c)=>{_t=0,s=ji(s,c),0<_t?re=s:hr(s)};class wc{constructor(c){this.Jb=c-24}}function vc(s,c,f){var b=new wc(s>>>=0);throw c>>>=0,f>>>=0,a()[b.Jb+16>>>2>>>0]=0,a()[b.Jb+4>>>2>>>0]=c,a()[b.Jb+8>>>2>>>0]=f,s}function Ko(s,c,f,b){return g?xe(2,1,s,c,f,b):Yo(s,c,f,b)}function Yo(s,c,f,b){if(s>>>=0,c>>>=0,f>>>=0,b>>>=0,x===void 0)return K(\"Current environment does not support SharedArrayBuffer, pthreads are not available!\"),6;var w=[];return g&&w.length===0?Ko(s,c,f,b):(s={hc:f,Ab:s,Qb:b,mc:w},g?(s.Mb=\"spawnThread\",postMessage(s,w),0):Wo(s))}var Zo=typeof TextDecoder<\"u\"?new TextDecoder(\"utf8\"):void 0,Qo=(s,c,f)=>{var b=(c>>>=0)+f;for(f=c;s[f]&&!(f>=b);)++f;if(16(w=(240&w)==224?(15&w)<<12|I<<6|B:(7&w)<<18|I<<12|B<<6|63&s[c++])?b+=String.fromCharCode(w):(w-=65536,b+=String.fromCharCode(55296|w>>10,56320|1023&w))}}else b+=String.fromCharCode(w)}return b},Te=(s,c)=>(s>>>=0)?Qo(r(),s,c):\"\";function Xo(s,c,f){return g?xe(3,1,s,c,f):0}function Jo(s,c){if(g)return xe(4,1,s,c)}var Tn=s=>{for(var c=0,f=0;f=b?c++:2047>=b?c+=2:55296<=b&&57343>=b?(c+=4,++f):c+=3}return c},ei=(s,c,f,b)=>{if(!(0>>=0;b=f+b-1;for(var I=0;I=B&&(B=65536+((1023&B)<<10)|1023&s.charCodeAt(++I)),127>=B){if(f>=b)break;c[f++>>>0]=B}else{if(2047>=B){if(f+1>=b)break;c[f++>>>0]=192|B>>6}else{if(65535>=B){if(f+2>=b)break;c[f++>>>0]=224|B>>12}else{if(f+3>=b)break;c[f++>>>0]=240|B>>18,c[f++>>>0]=128|B>>12&63}c[f++>>>0]=128|B>>6&63}c[f++>>>0]=128|63&B}}return c[f>>>0]=0,f-w},Pt=(s,c,f)=>ei(s,r(),c,f);function ti(s,c){if(g)return xe(5,1,s,c)}function ri(s,c,f){if(g)return xe(6,1,s,c,f)}function ni(s,c,f){return g?xe(7,1,s,c,f):0}function oi(s,c){if(g)return xe(8,1,s,c)}function ii(s,c,f){if(g)return xe(9,1,s,c,f)}function ai(s,c,f,b){if(g)return xe(10,1,s,c,f,b)}function si(s,c,f,b){if(g)return xe(11,1,s,c,f,b)}function ui(s,c,f,b){if(g)return xe(12,1,s,c,f,b)}function li(s){if(g)return xe(13,1,s)}function di(s,c){if(g)return xe(14,1,s,c)}function ci(s,c,f){if(g)return xe(15,1,s,c,f)}var pi,pt,$c=()=>{dt(\"\")},Ze=s=>{for(var c=\"\";r()[s>>>0];)c+=pi[r()[s++>>>0]];return c},In={},Cn={},xc={};function at(s,c,f={}){if(!(\"argPackAdvance\"in c))throw new TypeError(\"registerType registeredInstance requires argPackAdvance\");return function(b,w,I={}){var B=w.name;if(!b)throw new pt(`type \"${B}\" must have a positive integer typeid pointer`);if(Cn.hasOwnProperty(b)){if(I.Sb)return;throw new pt(`Cannot register type '${B}' twice`)}Cn[b]=w,delete xc[b],In.hasOwnProperty(b)&&(w=In[b],delete In[b],w.forEach(D=>D()))}(s,c,f)}var mi=(s,c,f)=>{switch(c){case 1:return f?b=>t()[b>>>0]:b=>r()[b>>>0];case 2:return f?b=>n()[b>>>1>>>0]:b=>o()[b>>>1>>>0];case 4:return f?b=>i()[b>>>2>>>0]:b=>a()[b>>>2>>>0];case 8:return f?b=>j[b>>>3]:b=>he[b>>>3];default:throw new TypeError(`invalid integer width (${c}): ${s}`)}};function Sc(s,c,f){f>>>=0,at(s>>>=0,{name:c=Ze(c>>>0),fromWireType:b=>b,toWireType:function(b,w){if(typeof w!=\"bigint\"&&typeof w!=\"number\")throw w=w===null?\"null\":(b=typeof w)==\"object\"||b===\"array\"||b===\"function\"?w.toString():\"\"+w,new TypeError(`Cannot convert \"${w}\" to ${this.name}`);return typeof w==\"number\"&&(w=BigInt(w)),w},argPackAdvance:mt,readValueFromPointer:mi(c,f,c.indexOf(\"u\")==-1),Db:null})}var mt=8;function Tc(s,c,f,b){at(s>>>=0,{name:c=Ze(c>>>0),fromWireType:function(w){return!!w},toWireType:function(w,I){return I?f:b},argPackAdvance:mt,readValueFromPointer:function(w){return this.fromWireType(r()[w>>>0])},Db:null})}var An=[],st=[];function kn(s){9<(s>>>=0)&&--st[s+1]==0&&(st[s]=void 0,An.push(s))}var Ne=s=>{if(!s)throw new pt(\"Cannot use deleted val. handle = \"+s);return st[s]},Ve=s=>{switch(s){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let c=An.pop()||st.length;return st[c]=s,st[c+1]=1,c}};function En(s){return this.fromWireType(a()[s>>>2>>>0])}var Ic={name:\"emscripten::val\",fromWireType:s=>{var c=Ne(s);return kn(s),c},toWireType:(s,c)=>Ve(c),argPackAdvance:mt,readValueFromPointer:En,Db:null};function Cc(s){return at(s>>>0,Ic)}var Ac=(s,c)=>{switch(c){case 4:return function(f){return this.fromWireType(l()[f>>>2>>>0])};case 8:return function(f){return this.fromWireType(d()[f>>>3>>>0])};default:throw new TypeError(`invalid float width (${c}): ${s}`)}};function kc(s,c,f){f>>>=0,at(s>>>=0,{name:c=Ze(c>>>0),fromWireType:b=>b,toWireType:(b,w)=>w,argPackAdvance:mt,readValueFromPointer:Ac(c,f),Db:null})}function Ec(s,c,f,b,w){if(s>>>=0,f>>>=0,c=Ze(c>>>0),w===-1&&(w=4294967295),w=D=>D,b===0){var I=32-8*f;w=D=>D<>>I}var B=c.includes(\"unsigned\")?function(D,L){return L>>>0}:function(D,L){return L};at(s,{name:c,fromWireType:w,toWireType:B,argPackAdvance:mt,readValueFromPointer:mi(c,f,b!==0),Db:null})}function Pc(s,c,f){function b(I){var B=a()[I>>>2>>>0];return I=a()[I+4>>>2>>>0],new w(t().buffer,I,B)}var w=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][c];at(s>>>=0,{name:f=Ze(f>>>0),fromWireType:b,argPackAdvance:mt,readValueFromPointer:b},{Sb:!0})}function zc(s,c){s>>>=0;var f=(c=Ze(c>>>0))===\"std::string\";at(s,{name:c,fromWireType:function(b){var w=a()[b>>>2>>>0],I=b+4;if(f)for(var B=I,D=0;D<=w;++D){var L=I+D;if(D==w||r()[L>>>0]==0){if(B=Te(B,L-B),H===void 0)var H=B;else H+=String.fromCharCode(0),H+=B;B=L+1}}else{for(H=Array(w),D=0;D>>0]);H=H.join(\"\")}return Xe(b),H},toWireType:function(b,w){w instanceof ArrayBuffer&&(w=new Uint8Array(w));var I=typeof w==\"string\";if(!(I||w instanceof Uint8Array||w instanceof Uint8ClampedArray||w instanceof Int8Array))throw new pt(\"Cannot pass non-string to std::string\");var B=f&&I?Tn(w):w.length,D=fr(4+B+1),L=D+4;if(a()[D>>>2>>>0]=B,f&&I)Pt(w,L,B+1);else if(I)for(I=0;I>>0]=H}else for(I=0;I>>0]=w[I];return b!==null&&b.push(Xe,D),D},argPackAdvance:mt,readValueFromPointer:En,Db(b){Xe(b)}})}var fi=typeof TextDecoder<\"u\"?new TextDecoder(\"utf-16le\"):void 0,Oc=(s,c)=>{for(var f=s>>1,b=f+c/2;!(f>=b)&&o()[f>>>0];)++f;if(32<(f<<=1)-s&&fi)return fi.decode(r().slice(s,f));for(f=\"\",b=0;!(b>=c/2);++b){var w=n()[s+2*b>>>1>>>0];if(w==0)break;f+=String.fromCharCode(w)}return f},Bc=(s,c,f)=>{if(f??=2147483647,2>f)return 0;var b=c;f=(f-=2)<2*s.length?f/2:s.length;for(var w=0;w>>1>>>0]=I,c+=2}return n()[c>>>1>>>0]=0,c-b},Dc=s=>2*s.length,Mc=(s,c)=>{for(var f=0,b=\"\";!(f>=c/4);){var w=i()[s+4*f>>>2>>>0];if(w==0)break;++f,65536<=w?(w-=65536,b+=String.fromCharCode(55296|w>>10,56320|1023&w)):b+=String.fromCharCode(w)}return b},Rc=(s,c,f)=>{if(c>>>=0,f??=2147483647,4>f)return 0;var b=c;f=b+f-4;for(var w=0;w=I&&(I=65536+((1023&I)<<10)|1023&s.charCodeAt(++w)),i()[c>>>2>>>0]=I,(c+=4)+4>f)break}return i()[c>>>2>>>0]=0,c-b},Uc=s=>{for(var c=0,f=0;f=b&&++f,c+=4}return c};function Nc(s,c,f){if(s>>>=0,c>>>=0,f=Ze(f>>>=0),c===2)var b=Oc,w=Bc,I=Dc,B=D=>o()[D>>>1>>>0];else c===4&&(b=Mc,w=Rc,I=Uc,B=D=>a()[D>>>2>>>0]);at(s,{name:f,fromWireType:D=>{for(var L,H=a()[D>>>2>>>0],Q=D+4,ce=0;ce<=H;++ce){var ge=D+4+ce*c;ce!=H&&B(ge)!=0||(Q=b(Q,ge-Q),L===void 0?L=Q:(L+=String.fromCharCode(0),L+=Q),Q=ge+c)}return Xe(D),L},toWireType:(D,L)=>{if(typeof L!=\"string\")throw new pt(`Cannot pass non-string to C++ string type ${f}`);var H=I(L),Q=fr(4+H+c);return a()[Q>>>2>>>0]=H/c,w(L,Q+4,H+c),D!==null&&D.push(Xe,Q),Q},argPackAdvance:mt,readValueFromPointer:En,Db(D){Xe(D)}})}function Vc(s,c){at(s>>>=0,{Tb:!0,name:c=Ze(c>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Wc=()=>1;function Lc(s){Un(s>>>0,!y,1,!_,131072,!1),Fo()}var hi=s=>{if(!_e)try{if(s(),!(0<_t))try{g?hr(re):Sn(re)}catch(c){c instanceof vn||c==\"unwind\"||A(1,c)}}catch(c){c instanceof vn||c==\"unwind\"||A(1,c)}};function Pn(s){s>>>=0,typeof Atomics.nc==\"function\"&&(Atomics.nc(i(),s>>>2,s).value.then(ar),s+=128,Atomics.store(i(),s>>>2,1))}var ar=()=>{var s=Bt();s&&(Pn(s),hi(Fi))};function Gc(s,c){(s>>>=0)==c>>>0?setTimeout(ar):g?postMessage({targetThread:s,cmd:\"checkMailbox\"}):(s=Ye[s])&&s.postMessage({cmd:\"checkMailbox\"})}var zn=[];function Hc(s,c,f,b,w){for(c>>>=0,b/=2,zn.length=b,f=w>>>0>>>3,w=0;w>>0];return(c?wn[c]:Op[s])(...zn)}function Fc(s){s>>>=0,g?postMessage({cmd:\"cleanupThread\",thread:s}):Ho(Ye[s])}function qc(s){}var On=(s,c)=>{var f=Cn[s];if(f===void 0)throw s=Wi(s),f=Ze(s),Xe(s),new pt(`${c} has unknown type ${f}`);return f},gi=(s,c,f)=>{var b=[];return s=s.toWireType(b,f),b.length&&(a()[c>>>2>>>0]=Ve(b)),s};function jc(s,c,f){return c>>>=0,f>>>=0,s=Ne(s>>>0),c=On(c,\"emval::as\"),gi(c,f,s)}var sr=s=>{try{s()}catch(c){dt(c)}},ft=0,Qe=null,bi=0,ur=[],yi={},_i={},Kc=0,Bn=null,Yc=[];function wi(s){return function(c){if(!_e){if(ft===0){var f=!1,b=!1;c((w=0)=>{if(!_e&&(bi=w,f=!0,b)){ft=2,sr(()=>Zi(Qe)),typeof Browser<\"u\"&&Browser.Kb.Rb&&Browser.Kb.resume(),w=!1;try{var I=function(){var L=i()[Qe+8>>>2>>>0];return L=Z[_i[L]],--_t,L()}()}catch(L){I=L,w=!0}var B=!1;if(!Qe){var D=Bn;D&&(Bn=null,(w?D.reject:D.resolve)(I),B=!0)}if(w&&!B)throw I}}),b=!0,f||(ft=1,Qe=function(){var w=fr(65548),I=w+12;a()[w>>>2>>>0]=I,a()[w+4>>>2>>>0]=I+65536,I=ur[0];var B=yi[I];return B===void 0&&(B=Kc++,yi[I]=B,_i[B]=I),I=B,i()[w+8>>>2>>>0]=I,w}(),typeof Browser<\"u\"&&Browser.Kb.Rb&&Browser.Kb.pause(),sr(()=>Ki(Qe)))}else ft===2?(ft=0,sr(Qi),Xe(Qe),Qe=null,Yc.forEach(hi)):dt(`invalid state: ${ft}`);return bi}}(c=>{s().then(c)})}function Zc(s){return s>>>=0,wi(()=>(s=Ne(s)).then(Ve))}var lr=[];function Qc(s,c,f,b){return f>>>=0,b>>>=0,(s=lr[s>>>0])(null,c=Ne(c>>>0),f,b)}var Xc={},dr=s=>{var c=Xc[s];return c===void 0?Ze(s):c};function Jc(s,c,f,b,w){return f>>>=0,b>>>=0,w>>>=0,(s=lr[s>>>0])(c=Ne(c>>>0),c[f=dr(f)],b,w)}var vi=()=>typeof globalThis==\"object\"?globalThis:Function(\"return this\")();function ep(s){return(s>>>=0)==0?Ve(vi()):(s=dr(s),Ve(vi()[s]))}var tp=s=>{var c=lr.length;return lr.push(s),c},rp=(s,c)=>{for(var f=Array(s),b=0;b>>2>>>0],\"parameter \"+b);return f},$i=(s,c)=>Object.defineProperty(c,\"name\",{value:s});function np(s,c,f){var b=(c=rp(s,c>>>0)).shift();s--;var w=`return function (obj, func, destructorsRef, args) {\n`,I=0,B=[];f===0&&B.push(\"obj\");for(var D=[\"retType\"],L=[b],H=0;HQ.name).join(\", \")}) => ${b.name}>`,tp($i(f,s))}function op(s){return s=dr(s>>>0),Ve(u[s])}function ip(s,c){return c>>>=0,s=Ne(s>>>0),c=Ne(c),Ve(s[c])}function ap(s){9<(s>>>=0)&&(st[s+1]+=1)}function sp(){return Ve([])}function up(s){s=Ne(s>>>0);for(var c=Array(s.length),f=0;f>>0))}function dp(){return Ve({})}function cp(s){for(var c=Ne(s>>>=0);c.length;){var f=c.pop();c.pop()(f)}kn(s)}function pp(s,c,f){c>>>=0,f>>>=0,s=Ne(s>>>0),c=Ne(c),f=Ne(f),s[c]=f}function mp(s,c){return c>>>=0,s=(s=On(s>>>0,\"_emval_take_value\")).readValueFromPointer(c),Ve(s)}function fp(s,c){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),i()[c>>>2>>>0]=s.getUTCSeconds(),i()[c+4>>>2>>>0]=s.getUTCMinutes(),i()[c+8>>>2>>>0]=s.getUTCHours(),i()[c+12>>>2>>>0]=s.getUTCDate(),i()[c+16>>>2>>>0]=s.getUTCMonth(),i()[c+20>>>2>>>0]=s.getUTCFullYear()-1900,i()[c+24>>>2>>>0]=s.getUTCDay(),s=(s.getTime()-Date.UTC(s.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[c+28>>>2>>>0]=s}var zt=s=>s%4==0&&(s%100!=0||s%400==0),xi=[0,31,60,91,121,152,182,213,244,274,305,335],Si=[0,31,59,90,120,151,181,212,243,273,304,334];function hp(s,c){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),i()[c>>>2>>>0]=s.getSeconds(),i()[c+4>>>2>>>0]=s.getMinutes(),i()[c+8>>>2>>>0]=s.getHours(),i()[c+12>>>2>>>0]=s.getDate(),i()[c+16>>>2>>>0]=s.getMonth(),i()[c+20>>>2>>>0]=s.getFullYear()-1900,i()[c+24>>>2>>>0]=s.getDay();var f=(zt(s.getFullYear())?xi:Si)[s.getMonth()]+s.getDate()-1|0;i()[c+28>>>2>>>0]=f,i()[c+36>>>2>>>0]=-60*s.getTimezoneOffset(),f=new Date(s.getFullYear(),6,1).getTimezoneOffset();var b=new Date(s.getFullYear(),0,1).getTimezoneOffset();s=0|(f!=b&&s.getTimezoneOffset()==Math.min(b,f)),i()[c+32>>>2>>>0]=s}function gp(s){s>>>=0;var c=new Date(i()[s+20>>>2>>>0]+1900,i()[s+16>>>2>>>0],i()[s+12>>>2>>>0],i()[s+8>>>2>>>0],i()[s+4>>>2>>>0],i()[s>>>2>>>0],0),f=i()[s+32>>>2>>>0],b=c.getTimezoneOffset(),w=new Date(c.getFullYear(),6,1).getTimezoneOffset(),I=new Date(c.getFullYear(),0,1).getTimezoneOffset(),B=Math.min(I,w);return 0>f?i()[s+32>>>2>>>0]=+(w!=I&&B==b):0>>2>>>0]=c.getDay(),f=(zt(c.getFullYear())?xi:Si)[c.getMonth()]+c.getDate()-1|0,i()[s+28>>>2>>>0]=f,i()[s>>>2>>>0]=c.getSeconds(),i()[s+4>>>2>>>0]=c.getMinutes(),i()[s+8>>>2>>>0]=c.getHours(),i()[s+12>>>2>>>0]=c.getDate(),i()[s+16>>>2>>>0]=c.getMonth(),i()[s+20>>>2>>>0]=c.getYear(),s=c.getTime(),BigInt(isNaN(s)?-1:s/1e3)}function Ti(s,c,f,b,w,I,B){return g?xe(16,1,s,c,f,b,w,I,B):-52}function Ii(s,c,f,b,w,I){if(g)return xe(17,1,s,c,f,b,w,I)}function bp(s,c,f,b){s>>>=0,c>>>=0,f>>>=0,b>>>=0;var w=new Date().getFullYear(),I=new Date(w,0,1),B=new Date(w,6,1);w=I.getTimezoneOffset();var D=B.getTimezoneOffset(),L=Math.max(w,D);a()[s>>>2>>>0]=60*L,i()[c>>>2>>>0]=+(w!=D),I=(s=H=>H.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:\"short\"}).split(\" \")[1])(I),B=s(B),D{Dn.length=0;for(var f;f=r()[s++>>>0];){var b=f!=105;c+=(b&=f!=112)&&c%8?4:0,Dn.push(f==112?a()[c>>>2>>>0]:f==106?j[c>>>3]:f==105?i()[c>>>2>>>0]:d()[c>>>3>>>0]),c+=b?8:4}return Dn};function yp(s,c,f){return s>>>=0,c=Ci(c>>>0,f>>>0),wn[s](...c)}function _p(s,c,f){return s>>>=0,c=Ci(c>>>0,f>>>0),wn[s](...c)}var wp=()=>{},vp=()=>Date.now();function $p(s,c){return K(Te(s>>>0,c>>>0))}var Ai,xp=()=>{throw _t+=1,\"unwind\"};function Sp(){return 4294901760}Ai=()=>performance.timeOrigin+performance.now();var Tp=()=>navigator.hardwareConcurrency;function Ip(){return dt(\"Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER\"),0}function Cp(s){s>>>=0;var c=r().length;if(s<=c||4294901760=f;f*=2){var b=c*(1+.2/f);b=Math.min(b,s+100663296);var w=Math;b=Math.max(s,b);e:{w=(w.min.call(w,4294901760,b+(65536-b%65536)%65536)-se.buffer.byteLength+65535)/65536;try{se.grow(w),be();var I=1;break e}catch{}I=void 0}if(I)return!0}return!1}var cr=()=>(dt(\"Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER\"),0),Ot={},ki=s=>{s.forEach(c=>{var f=cr();f&&(Ot[f]=c)})};function Ap(){var s=Error().stack.toString().split(`\n`);return s[0]==\"Error\"&&s.shift(),ki(s),Ot.Pb=cr(),Ot.ec=s,Ot.Pb}function kp(s,c,f){if(s>>>=0,c>>>=0,Ot.Pb==s)var b=Ot.ec;else(b=Error().stack.toString().split(`\n`))[0]==\"Error\"&&b.shift(),ki(b);for(var w=3;b[w]&&cr()!=s;)++w;for(s=0;s>>2>>>0]=cr();return s}var Mn,Rn={},Ei=()=>{if(!Mn){var s,c={USER:\"web_user\",LOGNAME:\"web_user\",PATH:\"/\",PWD:\"/\",HOME:\"/home/web_user\",LANG:(typeof navigator==\"object\"&&navigator.languages&&navigator.languages[0]||\"C\").replace(\"-\",\"_\")+\".UTF-8\",_:C||\"./this.program\"};for(s in Rn)Rn[s]===void 0?delete c[s]:c[s]=Rn[s];var f=[];for(s in c)f.push(`${s}=${c[s]}`);Mn=f}return Mn};function Pi(s,c){if(g)return xe(18,1,s,c);s>>>=0,c>>>=0;var f=0;return Ei().forEach((b,w)=>{var I=c+f;for(w=a()[s+4*w>>>2>>>0]=I,I=0;I>>0]=b.charCodeAt(I);t()[w>>>0]=0,f+=b.length+1}),0}function zi(s,c){if(g)return xe(19,1,s,c);s>>>=0,c>>>=0;var f=Ei();a()[s>>>2>>>0]=f.length;var b=0;return f.forEach(w=>b+=w.length+1),a()[c>>>2>>>0]=b,0}function Oi(s){return g?xe(20,1,s):52}function Bi(s,c,f,b){return g?xe(21,1,s,c,f,b):52}function Di(s,c,f,b){return g?xe(22,1,s,c,f,b):70}var Ep=[null,[],[]];function Mi(s,c,f,b){if(g)return xe(23,1,s,c,f,b);c>>>=0,f>>>=0,b>>>=0;for(var w=0,I=0;I>>2>>>0],D=a()[c+4>>>2>>>0];c+=8;for(var L=0;L>>0],Q=Ep[s];H===0||H===10?((s===1?q:K)(Qo(Q,0)),Q.length=0):Q.push(H)}w+=D}return a()[b>>>2>>>0]=w,0}var Ri=[31,29,31,30,31,30,31,31,30,31,30,31],Ui=[31,28,31,30,31,30,31,31,30,31,30,31],Pp=(s,c)=>{t().set(s,c>>>0)};function Ni(s,c,f,b){function w(z,le,Ie){for(z=typeof z==\"number\"?z.toString():z||\"\";z.lengthJi?-1:0vt-z.getDate())){z.setDate(z.getDate()+le);break}le-=vt-z.getDate()+1,z.setDate(1),11>Ie?z.setMonth(Ie+1):(z.setMonth(0),z.setFullYear(z.getFullYear()+1))}return Ie=new Date(z.getFullYear()+1,0,4),le=D(new Date(z.getFullYear(),0,4)),Ie=D(Ie),0>=B(le,z)?0>=B(Ie,z)?z.getFullYear()+1:z.getFullYear():z.getFullYear()-1}s>>>=0,c>>>=0,f>>>=0,b>>>=0;var H=a()[b+40>>>2>>>0];for(var Q in b={kc:i()[b>>>2>>>0],jc:i()[b+4>>>2>>>0],Hb:i()[b+8>>>2>>>0],Lb:i()[b+12>>>2>>>0],Ib:i()[b+16>>>2>>>0],Cb:i()[b+20>>>2>>>0],ub:i()[b+24>>>2>>>0],Bb:i()[b+28>>>2>>>0],rc:i()[b+32>>>2>>>0],ic:i()[b+36>>>2>>>0],lc:H?Te(H):\"\"},f=Te(f),H={\"%c\":\"%a %b %d %H:%M:%S %Y\",\"%D\":\"%m/%d/%y\",\"%F\":\"%Y-%m-%d\",\"%h\":\"%b\",\"%r\":\"%I:%M:%S %p\",\"%R\":\"%H:%M\",\"%T\":\"%H:%M:%S\",\"%x\":\"%m/%d/%y\",\"%X\":\"%H:%M:%S\",\"%Ec\":\"%c\",\"%EC\":\"%C\",\"%Ex\":\"%m/%d/%y\",\"%EX\":\"%H:%M:%S\",\"%Ey\":\"%y\",\"%EY\":\"%Y\",\"%Od\":\"%d\",\"%Oe\":\"%e\",\"%OH\":\"%H\",\"%OI\":\"%I\",\"%Om\":\"%m\",\"%OM\":\"%M\",\"%OS\":\"%S\",\"%Ou\":\"%u\",\"%OU\":\"%U\",\"%OV\":\"%V\",\"%Ow\":\"%w\",\"%OW\":\"%W\",\"%Oy\":\"%y\"})f=f.replace(new RegExp(Q,\"g\"),H[Q]);var ce=\"Sunday Monday Tuesday Wednesday Thursday Friday Saturday\".split(\" \"),ge=\"January February March April May June July August September October November December\".split(\" \");for(Q in H={\"%a\":z=>ce[z.ub].substring(0,3),\"%A\":z=>ce[z.ub],\"%b\":z=>ge[z.Ib].substring(0,3),\"%B\":z=>ge[z.Ib],\"%C\":z=>I((z.Cb+1900)/100|0,2),\"%d\":z=>I(z.Lb,2),\"%e\":z=>w(z.Lb,2,\" \"),\"%g\":z=>L(z).toString().substring(2),\"%G\":L,\"%H\":z=>I(z.Hb,2),\"%I\":z=>((z=z.Hb)==0?z=12:12{for(var le=0,Ie=0;Ie<=z.Ib-1;le+=(zt(z.Cb+1900)?Ri:Ui)[Ie++]);return I(z.Lb+le,3)},\"%m\":z=>I(z.Ib+1,2),\"%M\":z=>I(z.jc,2),\"%n\":()=>`\n`,\"%p\":z=>0<=z.Hb&&12>z.Hb?\"AM\":\"PM\",\"%S\":z=>I(z.kc,2),\"%t\":()=>\"\t\",\"%u\":z=>z.ub||7,\"%U\":z=>I(Math.floor((z.Bb+7-z.ub)/7),2),\"%V\":z=>{var le=Math.floor((z.Bb+7-(z.ub+6)%7)/7);if(2>=(z.ub+371-z.Bb-2)%7&&le++,le)le==53&&((Ie=(z.ub+371-z.Bb)%7)==4||Ie==3&&zt(z.Cb)||(le=1));else{le=52;var Ie=(z.ub+7-z.Bb-1)%7;(Ie==4||Ie==5&&zt(z.Cb%400-1))&&le++}return I(le,2)},\"%w\":z=>z.ub,\"%W\":z=>I(Math.floor((z.Bb+7-(z.ub+6)%7)/7),2),\"%y\":z=>(z.Cb+1900).toString().substring(2),\"%Y\":z=>z.Cb+1900,\"%z\":z=>{var le=0<=(z=z.ic);return z=Math.abs(z)/60,(le?\"+\":\"-\")+(\"0000\"+(z/60*100+z%60)).slice(-4)},\"%Z\":z=>z.lc,\"%%\":()=>\"%\"},f=f.replace(/%%/g,\"\\0\\0\"),H)f.includes(Q)&&(f=f.replace(new RegExp(Q,\"g\"),H[Q](b)));return Q=function(z){var le=Array(Tn(z)+1);return ei(z,le,0,le.length),le}(f=f.replace(/\\0\\0/g,\"%\")),Q.length>c?0:(Pp(Q,s),Q.length-1)}function zp(s,c,f,b){return Ni(s>>>0,c>>>0,f>>>0,b>>>0)}g||function(){for(var s=u.numThreads-1;s--;)jo();Ke.unshift(()=>{Gt++,function(c){g?c():Promise.all(ct.map(qo)).then(c)}(()=>Do())})}();for(var Vi=Array(256),pr=0;256>pr;++pr)Vi[pr]=String.fromCharCode(pr);pi=Vi,pt=u.BindingError=class extends Error{constructor(s){super(s),this.name=\"BindingError\"}},u.InternalError=class extends Error{constructor(s){super(s),this.name=\"InternalError\"}},st.push(0,1,void 0,1,null,1,!0,1,!1,1),u.count_emval_handles=()=>st.length/2-5-An.length;var Op=[xn,Lo,Ko,Xo,Jo,ti,ri,ni,oi,ii,ai,si,ui,li,di,ci,Ti,Ii,Pi,zi,Oi,Bi,Di,Mi],Z=function(){function s(f,b){return Z=f.exports,Z=function(){var w=Z,I={};for(let[B,D]of Object.entries(w))I[B]=typeof D==\"function\"?(...L)=>{ur.push(B);try{return D(...L)}finally{_e||(ur.pop(),Qe&&ft===1&&ur.length===0&&(ft=0,_t+=1,sr(Yi),typeof Fibers<\"u\"&&Fibers.sc()))}}:D;return I}(),Z=function(){var w=Z,I=D=>L=>D(L)>>>0,B=D=>()=>D()>>>0;return(w=Object.assign({},w)).Ca=I(w.Ca),w.fb=B(w.fb),w.hb=I(w.hb),w.emscripten_main_runtime_thread_id=B(w.emscripten_main_runtime_thread_id),w.sb=I(w.sb),w.tb=B(w.tb),w}(),Go.push(Z.ib),Lt.unshift(Z.Ba),X=b,Do(),Z}var c=Vo();if(Gt++,u.instantiateWasm)try{return u.instantiateWasm(c,s)}catch(f){K(`Module.instantiateWasm callback failed with error: ${f}`),m(f)}return _n||=u.locateFile?Mo(\"ort-wasm-simd-threaded.jsep.wasm\")?\"ort-wasm-simd-threaded.jsep.wasm\":u.locateFile?u.locateFile(\"ort-wasm-simd-threaded.jsep.wasm\",P):P+\"ort-wasm-simd-threaded.jsep.wasm\":new URL(\"ort-wasm-simd-threaded.jsep.wasm\",import.meta.url).href,function(f,b){var w=_n;return O||typeof WebAssembly.instantiateStreaming!=\"function\"||Mo(w)||Ro(w)||typeof fetch!=\"function\"?No(w,f,b):fetch(w,{credentials:\"same-origin\"}).then(I=>WebAssembly.instantiateStreaming(I,f).then(b,function(B){return K(`wasm streaming compile failed: ${B}`),K(\"falling back to ArrayBuffer instantiation\"),No(w,f,b)}))}(c,function(f){s(f.instance,f.module)}).catch(m),{}}(),Wi=s=>(Wi=Z.Ca)(s),Li=()=>(Li=Z.Da)();u._OrtInit=(s,c)=>(u._OrtInit=Z.Ea)(s,c),u._OrtGetLastError=(s,c)=>(u._OrtGetLastError=Z.Fa)(s,c),u._OrtCreateSessionOptions=(s,c,f,b,w,I,B,D,L,H)=>(u._OrtCreateSessionOptions=Z.Ga)(s,c,f,b,w,I,B,D,L,H),u._OrtAppendExecutionProvider=(s,c)=>(u._OrtAppendExecutionProvider=Z.Ha)(s,c),u._OrtAddFreeDimensionOverride=(s,c,f)=>(u._OrtAddFreeDimensionOverride=Z.Ia)(s,c,f),u._OrtAddSessionConfigEntry=(s,c,f)=>(u._OrtAddSessionConfigEntry=Z.Ja)(s,c,f),u._OrtReleaseSessionOptions=s=>(u._OrtReleaseSessionOptions=Z.Ka)(s),u._OrtCreateSession=(s,c,f)=>(u._OrtCreateSession=Z.La)(s,c,f),u._OrtReleaseSession=s=>(u._OrtReleaseSession=Z.Ma)(s),u._OrtGetInputOutputCount=(s,c,f)=>(u._OrtGetInputOutputCount=Z.Na)(s,c,f),u._OrtGetInputName=(s,c)=>(u._OrtGetInputName=Z.Oa)(s,c),u._OrtGetOutputName=(s,c)=>(u._OrtGetOutputName=Z.Pa)(s,c),u._OrtFree=s=>(u._OrtFree=Z.Qa)(s),u._OrtCreateTensor=(s,c,f,b,w,I)=>(u._OrtCreateTensor=Z.Ra)(s,c,f,b,w,I),u._OrtGetTensorData=(s,c,f,b,w)=>(u._OrtGetTensorData=Z.Sa)(s,c,f,b,w),u._OrtReleaseTensor=s=>(u._OrtReleaseTensor=Z.Ta)(s),u._OrtCreateRunOptions=(s,c,f,b)=>(u._OrtCreateRunOptions=Z.Ua)(s,c,f,b),u._OrtAddRunConfigEntry=(s,c,f)=>(u._OrtAddRunConfigEntry=Z.Va)(s,c,f),u._OrtReleaseRunOptions=s=>(u._OrtReleaseRunOptions=Z.Wa)(s),u._OrtCreateBinding=s=>(u._OrtCreateBinding=Z.Xa)(s),u._OrtBindInput=(s,c,f)=>(u._OrtBindInput=Z.Ya)(s,c,f),u._OrtBindOutput=(s,c,f,b)=>(u._OrtBindOutput=Z.Za)(s,c,f,b),u._OrtClearBoundOutputs=s=>(u._OrtClearBoundOutputs=Z._a)(s),u._OrtReleaseBinding=s=>(u._OrtReleaseBinding=Z.$a)(s),u._OrtRunWithBinding=(s,c,f,b,w)=>(u._OrtRunWithBinding=Z.ab)(s,c,f,b,w),u._OrtRun=(s,c,f,b,w,I,B,D)=>(u._OrtRun=Z.bb)(s,c,f,b,w,I,B,D),u._OrtEndProfiling=s=>(u._OrtEndProfiling=Z.cb)(s),u._JsepOutput=(s,c,f)=>(u._JsepOutput=Z.db)(s,c,f),u._JsepGetNodeName=s=>(u._JsepGetNodeName=Z.eb)(s);var mr,Bt=()=>(Bt=Z.fb)(),Xe=u._free=s=>(Xe=u._free=Z.gb)(s),fr=u._malloc=s=>(fr=u._malloc=Z.hb)(s),Un=(s,c,f,b,w,I)=>(Un=Z.kb)(s,c,f,b,w,I),Gi=()=>(Gi=Z.lb)(),Hi=(s,c,f,b,w)=>(Hi=Z.mb)(s,c,f,b,w),Nn=s=>(Nn=Z.nb)(s),hr=s=>(hr=Z.ob)(s),Fi=()=>(Fi=Z.pb)(),qi=(s,c)=>(qi=Z.qb)(s,c),gr=s=>(gr=Z.rb)(s),Vn=s=>(Vn=Z.sb)(s),Wn=()=>(Wn=Z.tb)(),ji=u.dynCall_ii=(s,c)=>(ji=u.dynCall_ii=Z.vb)(s,c),Ki=s=>(Ki=Z.wb)(s),Yi=()=>(Yi=Z.xb)(),Zi=s=>(Zi=Z.yb)(s),Qi=()=>(Qi=Z.zb)();function Xi(){0Wn(),u.stackRestore=s=>gr(s),u.stackAlloc=s=>Vn(s),u.setValue=function(s,c,f=\"i8\"){switch(f.endsWith(\"*\")&&(f=\"*\"),f){case\"i1\":case\"i8\":t()[s>>>0]=c;break;case\"i16\":n()[s>>>1>>>0]=c;break;case\"i32\":i()[s>>>2>>>0]=c;break;case\"i64\":j[s>>>3]=BigInt(c);break;case\"float\":l()[s>>>2>>>0]=c;break;case\"double\":d()[s>>>3>>>0]=c;break;case\"*\":a()[s>>>2>>>0]=c;break;default:dt(`invalid type for setValue: ${f}`)}},u.getValue=function(s,c=\"i8\"){switch(c.endsWith(\"*\")&&(c=\"*\"),c){case\"i1\":case\"i8\":return t()[s>>>0];case\"i16\":return n()[s>>>1>>>0];case\"i32\":return i()[s>>>2>>>0];case\"i64\":return j[s>>>3];case\"float\":return l()[s>>>2>>>0];case\"double\":return d()[s>>>3>>>0];case\"*\":return a()[s>>>2>>>0];default:dt(`invalid type for getValue: ${c}`)}},u.UTF8ToString=Te,u.stringToUTF8=Pt,u.lengthBytesUTF8=Tn,Ht=function s(){mr||Xi(),mr||(Ht=s)},Xi(),u.PTR_SIZE=4,h}),Gp=Ba;globalThis.self?.name===\"em-pthread\"&&Ba()});var Dt,Hp,Fp,qp,Ra,Ua,jp,Na,jt=R(()=>{\"use strict\";Ir();Dt=!1?void 0:import.meta.url??(typeof document<\"u\"?document.currentScript?.src:typeof self<\"u\"?self.location?.href:void 0),Hp=!1||typeof location>\"u\"?void 0:location.origin,Fp=(e,t)=>{try{let r=t??Dt;return(r?new URL(e,r):new URL(e)).origin===Hp}catch{return!1}},qp=async e=>{let r=await(await fetch(e,{credentials:\"same-origin\"})).blob();return URL.createObjectURL(r)},Ra=(Oa(),br(za)).default,Ua=async()=>{if(!Dt)throw new Error(\"Failed to load proxy worker: cannot determine the script source URL.\");if(Fp(Dt))return[void 0,Ra()];let e=await qp(Dt);return[e,Ra(e)]},jp=(Ma(),br(Da)).default,Na=async(e,t,r)=>[void 0,jp]});var Zn,Qn,Dr,Va,Kp,Yp,Cr,Ce,ht=R(()=>{\"use strict\";jt();Qn=!1,Dr=!1,Va=!1,Kp=()=>{if(typeof SharedArrayBuffer>\"u\")return!1;try{return typeof MessageChannel<\"u\"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Yp=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Cr=async e=>{if(Qn)return Promise.resolve();if(Dr)throw new Error(\"multiple calls to 'initializeWebAssembly()' detected.\");if(Va)throw new Error(\"previous call to 'initializeWebAssembly()' failed.\");Dr=!0;let t=e.initTimeout,r=e.numThreads;if(!Yp())throw new Error(\"WebAssembly SIMD is not supported in the current environment.\");let n=Kp();r>1&&!n&&(typeof self<\"u\"&&!self.crossOriginIsolated&&console.warn(\"env.wasm.numThreads is set to \"+r+\", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info.\"),console.warn(\"WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading.\"),e.numThreads=r=1);let o=e.wasmPaths,i=typeof o==\"string\"?o:void 0,a=o?.mjs,l=a?.href??a,d=o?.wasm,p=d?.href??d,m=e.wasmBinary,[u,h]=await Na(l,i,r>1),_=!1,y=[];if(t>0&&y.push(new Promise(g=>{setTimeout(()=>{_=!0,g()},t)})),y.push(new Promise((g,x)=>{let $={numThreads:r};m?$.wasmBinary=m:(p||i)&&($.locateFile=(v,S)=>p??(i??S)+v),h($).then(v=>{Dr=!1,Qn=!0,Zn=v,g(),u&&URL.revokeObjectURL(u)},v=>{Dr=!1,Va=!0,x(v)})})),await Promise.race(y),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ce=()=>{if(Qn&&Zn)return Zn;throw new Error(\"WebAssembly is not initialized yet.\")}});var Ae,Yt,pe,Mr=R(()=>{\"use strict\";ht();Ae=(e,t)=>{let r=Ce(),n=r.lengthBytesUTF8(e)+1,o=r._malloc(n);return r.stringToUTF8(e,o,n),t.push(o),o},Yt=(e,t,r,n)=>{if(typeof e==\"object\"&&e!==null){if(r.has(e))throw new Error(\"Circular reference in options\");r.add(e)}Object.entries(e).forEach(([o,i])=>{let a=t?t+o:o;if(typeof i==\"object\")Yt(i,a+\".\",r,n);else if(typeof i==\"string\"||typeof i==\"number\")n(a,i.toString());else if(typeof i==\"boolean\")n(a,i?\"1\":\"0\");else throw new Error(`Can't handle extra config type: ${typeof i}`)})},pe=e=>{let t=Ce(),r=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetLastError(o,o+n);let i=Number(t.getValue(o,n===4?\"i32\":\"i64\")),a=t.getValue(o+n,\"*\"),l=a?t.UTF8ToString(a):\"\";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${l}`)}finally{t.stackRestore(r)}}});var Wa,La=R(()=>{\"use strict\";ht();Mr();Wa=e=>{let t=Ce(),r=0,n=[],o=e||{};try{if(e?.logSeverityLevel===void 0)o.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=\"number\"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)o.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=\"number\"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(o.terminate=!1);let i=0;return e?.tag!==void 0&&(i=Ae(e.tag,n)),r=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,i),r===0&&pe(\"Can't create run options.\"),e?.extra!==void 0&&Yt(e.extra,\"\",new WeakSet,(a,l)=>{let d=Ae(a,n),p=Ae(l,n);t._OrtAddRunConfigEntry(r,d,p)!==0&&pe(`Can't set a run config entry: ${a} - ${l}.`)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(a=>t._free(a)),i}}});var Zp,Qp,Xp,Jp,Ga,Ha=R(()=>{\"use strict\";ht();Mr();Zp=e=>{switch(e){case\"disabled\":return 0;case\"basic\":return 1;case\"extended\":return 2;case\"all\":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},Qp=e=>{switch(e){case\"sequential\":return 0;case\"parallel\":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Xp=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly=\"1\"),e.executionProviders&&e.executionProviders.some(r=>(typeof r==\"string\"?r:r.name)===\"webgpu\")&&(e.enableMemPattern=!1)},Jp=(e,t,r)=>{for(let n of t){let o=typeof n==\"string\"?n:n.name;switch(o){case\"webnn\":if(o=\"WEBNN\",typeof n!=\"string\"){let l=n?.deviceType;if(l){let d=Ae(\"deviceType\",r),p=Ae(l,r);Ce()._OrtAddSessionConfigEntry(e,d,p)!==0&&pe(`Can't set a session config entry: 'deviceType' - ${l}.`)}}break;case\"webgpu\":if(o=\"JS\",typeof n!=\"string\"){let a=n;if(a?.preferredLayout){if(a.preferredLayout!==\"NCHW\"&&a.preferredLayout!==\"NHWC\")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${a.preferredLayout}`);let l=Ae(\"preferredLayout\",r),d=Ae(a.preferredLayout,r);Ce()._OrtAddSessionConfigEntry(e,l,d)!==0&&pe(`Can't set a session config entry: 'preferredLayout' - ${a.preferredLayout}.`)}}break;case\"wasm\":case\"cpu\":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=Ae(o,r);Ce()._OrtAppendExecutionProvider(e,i)!==0&&pe(`Can't append execution provider: ${o}.`)}},Ga=e=>{let t=Ce(),r=0,n=[],o=e||{};Xp(o);try{let i=Zp(o.graphOptimizationLevel??\"all\"),a=Qp(o.executionMode??\"sequential\"),l=typeof o.logId==\"string\"?Ae(o.logId,n):0,d=o.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let p=o.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let m=typeof o.optimizedModelFilePath==\"string\"?Ae(o.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(i,!!o.enableCpuMemArena,!!o.enableMemPattern,a,!!o.enableProfiling,0,l,d,p,m),r===0&&pe(\"Can't create session options.\"),o.executionProviders&&Jp(r,o.executionProviders,n),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!=\"boolean\")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);let u=Ae(\"enableGraphCapture\",n),h=Ae(o.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,u,h)!==0&&pe(`Can't set a session config entry: 'enableGraphCapture' - ${o.enableGraphCapture}.`)}if(o.freeDimensionOverrides)for(let[u,h]of Object.entries(o.freeDimensionOverrides)){if(typeof u!=\"string\")throw new Error(`free dimension override name must be a string: ${u}`);if(typeof h!=\"number\"||!Number.isInteger(h)||h<0)throw new Error(`free dimension override value must be a non-negative integer: ${h}`);let _=Ae(u,n);t._OrtAddFreeDimensionOverride(r,_,h)!==0&&pe(`Can't set a free dimension override: ${u} - ${h}.`)}return o.extra!==void 0&&Yt(o.extra,\"\",new WeakSet,(u,h)=>{let _=Ae(u,n),y=Ae(h,n);t._OrtAddSessionConfigEntry(r,_,y)!==0&&pe(`Can't set a session config entry: ${u} - ${h}.`)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&pe(\"Can't release session options.\"),n.forEach(a=>t._free(a)),i}}});var Zt,gt,Tt,Rr,Qt,Ur,Nr,Xn,te=R(()=>{\"use strict\";Zt=e=>{switch(e){case\"int8\":return 3;case\"uint8\":return 2;case\"bool\":return 9;case\"int16\":return 5;case\"uint16\":return 4;case\"int32\":return 6;case\"uint32\":return 12;case\"float16\":return 10;case\"float32\":return 1;case\"float64\":return 11;case\"string\":return 8;case\"int64\":return 7;case\"uint64\":return 13;case\"int4\":return 22;case\"uint4\":return 21;default:throw new Error(`unsupported data type: ${e}`)}},gt=e=>{switch(e){case 3:return\"int8\";case 2:return\"uint8\";case 9:return\"bool\";case 5:return\"int16\";case 4:return\"uint16\";case 6:return\"int32\";case 12:return\"uint32\";case 10:return\"float16\";case 1:return\"float32\";case 11:return\"float64\";case 8:return\"string\";case 7:return\"int64\";case 13:return\"uint64\";case 22:return\"int4\";case 21:return\"uint4\";default:throw new Error(`unsupported data type: ${e}`)}},Tt=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t==\"number\"?t:t.reduce((o,i)=>o*i,1);return r>0?Math.ceil(n*r):void 0},Rr=e=>{switch(e){case\"float16\":return typeof Float16Array<\"u\"&&Float16Array.from?Float16Array:Uint16Array;case\"float32\":return Float32Array;case\"uint8\":return Uint8Array;case\"int8\":return Int8Array;case\"uint16\":return Uint16Array;case\"int16\":return Int16Array;case\"int32\":return Int32Array;case\"bool\":return Uint8Array;case\"float64\":return Float64Array;case\"uint32\":return Uint32Array;case\"int64\":return BigInt64Array;case\"uint64\":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Qt=e=>{switch(e){case\"verbose\":return 0;case\"info\":return 1;case\"warning\":return 2;case\"error\":return 3;case\"fatal\":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},Ur=e=>e===\"float32\"||e===\"float16\"||e===\"int32\"||e===\"int64\"||e===\"uint32\"||e===\"uint8\"||e===\"bool\"||e===\"uint4\"||e===\"int4\",Nr=e=>e===\"float32\"||e===\"float16\"||e===\"int32\"||e===\"int64\"||e===\"uint32\"||e===\"uint64\"||e===\"int8\"||e===\"uint8\"||e===\"bool\"||e===\"uint4\"||e===\"int4\",Xn=e=>{switch(e){case\"none\":return 0;case\"cpu\":return 1;case\"cpu-pinned\":return 2;case\"texture\":return 3;case\"gpu-buffer\":return 4;case\"ml-tensor\":return 5;default:throw new Error(`unsupported data location: ${e}`)}}});var Xt,Jn=R(()=>{\"use strict\";Ir();Xt=async e=>{if(typeof e==\"string\")if(!1)try{let{readFile:t}=Gn(\"node:fs/promises\");return new Uint8Array(await t(e))}catch(t){if(t.code===\"ERR_FS_FILE_TOO_LARGE\"){let{createReadStream:r}=Gn(\"node:fs\"),n=r(e),o=[];for await(let i of n)o.push(i);return new Uint8Array(Buffer.concat(o))}throw t}else{let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get(\"Content-Length\"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=t.body.getReader(),i;try{i=new ArrayBuffer(n)}catch(l){if(l instanceof RangeError){let d=Math.ceil(n/65536);i=new WebAssembly.Memory({initial:d,maximum:d}).buffer}else throw l}let a=0;for(;;){let{done:l,value:d}=await o.read();if(l)break;let p=d.byteLength;new Uint8Array(i,a,p).set(d),a+=p}return new Uint8Array(i,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}});var em,tm,Fa,qa,Vr,rm,ue,Je=R(()=>{\"use strict\";te();em=[\"V\",\"I\",\"W\",\"E\",\"F\"],tm=(e,t)=>{console.log(`[${em[e]},${new Date().toISOString()}]${t}`)},Vr=(e,t)=>{Fa=e,qa=t},rm=(e,t)=>{let r=Qt(e),n=Qt(Fa);r>=n&&tm(r,typeof t==\"function\"?t():t)},ue=(...e)=>{qa&&rm(...e)}});var Wr,eo=R(()=>{\"use strict\";te();Wr=(e,t)=>new(Rr(t))(e)});var Lr=R(()=>{\"use strict\"});var ja,to,ro,nm,om,Ka,oo,no,Za,Qa=R(()=>{\"use strict\";Je();Lr();ja=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),to=[],ro=e=>Math.ceil(Number(e)/16)*16,nm=e=>{for(let t=0;tom++,oo=async(e,t,r,n)=>{let o=ro(r),i=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=e.getCommandEncoder();e.endComputePass(),a.copyBufferToBuffer(t,0,i,0,o),e.flush(),await i.mapAsync(GPUMapMode.READ);let l=i.getMappedRange();if(n){let d=n();return d.set(new Uint8Array(l,0,r)),d}else return new Uint8Array(l.slice(0,r))}finally{i.destroy()}},no=class{constructor(t){this.backend=t;this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[r]of ja)to.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(t,r){let n=r.buffer,o=r.byteOffset,i=r.byteLength,a=ro(i),l=this.storageCache.get(t);if(!l)throw new Error(\"gpu data for uploading does not exist\");if(Number(l.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${l.originalSize}, data size=${i}`);let d=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=d.getMappedRange();new Uint8Array(p).set(new Uint8Array(n,o,i)),d.unmap();let m=this.backend.device.createCommandEncoder();m.copyBufferToBuffer(d,0,l.gpuData.buffer,0,a),this.backend.device.queue.submit([m.finish()]),d.destroy(),ue(\"verbose\",()=>`[WebGPU] GpuDataManager.upload(id=${t})`)}memcpy(t,r){let n=this.storageCache.get(t);if(!n)throw new Error(\"source gpu data for memcpy does not exist\");let o=this.storageCache.get(r);if(!o)throw new Error(\"destination gpu data for memcpy does not exist\");if(n.originalSize!==o.originalSize)throw new Error(\"inconsistent source and destination gpu data size\");let i=ro(n.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(n.gpuData.buffer,0,o.gpuData.buffer,0,i)}registerExternalBuffer(t,r,n){let o;if(n){if(o=n[0],t===n[1])return ue(\"verbose\",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, buffer is the same, skip.`),o;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.\n Please use the previous external buffer!`)}else o=Ka();return this.storageCache.set(o,{gpuData:{id:o,type:0,buffer:t},originalSize:r}),ue(\"verbose\",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, registered.`),o}unregisterExternalBuffer(t){t!==void 0&&(this.storageCache.delete(t),ue(\"verbose\",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`))}create(t,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=nm(t),o,i=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let p=(i?this.freeBuffers:this.freeUniformBuffers).get(n);p?p.length>0?o=p.pop():o=this.backend.device.createBuffer({size:n,usage:r}):o=this.backend.device.createBuffer({size:n,usage:r})}else o=this.backend.device.createBuffer({size:n,usage:r});let l={id:Ka(),type:0,buffer:o};return this.storageCache.set(l.id,{gpuData:l,originalSize:Number(t)}),ue(\"verbose\",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${l.id}`),l}get(t){return this.storageCache.get(t)?.gpuData}release(t){let r=typeof t==\"bigint\"?Number(t):t,n=this.storageCache.get(r);if(!n){if(this.storageCache.size===0)return 0;throw new Error(\"releasing data does not exist\")}return ue(\"verbose\",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${n.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(t,r){let n=this.storageCache.get(Number(t));if(!n)throw new Error(\"data does not exist\");await oo(this.backend,n.gpuData.buffer,n.originalSize,r)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus===\"default\"){for(let t of this.buffersPending){let r=ja.get(t.size);if((t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(t.size)||[];r===void 0||n.length>=r?t.destroy():n.push(t)}else if((t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(t.size)||[];r===void 0||n.length>=r?t.destroy():n.push(t)}else t.destroy()}this.buffersPending=[]}else{let t=this.capturedPendingBuffers.get(this.backend.currentSessionId);t||(t=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,t));for(let r of this.buffersPending)t.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(t){let r=this.capturedPendingBuffers.get(t);r&&(r.forEach(n=>{n.destroy()}),this.capturedPendingBuffers.delete(t)),this.sessionCount-=1,this.sessionCount===0&&(ue(\"warning\",()=>\"[WebGPU] Clearing webgpu buffer cache\"),this.storageCache.forEach(n=>{n.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Za=(...e)=>new no(...e)});var io,J,Se=R(()=>{\"use strict\";io=class{constructor(t){Object.assign(this,t)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(t=>`${this[t]}`).join(\";\")),this.key}},J=e=>new io(e)});var ao,et,k,It,Gr,Xa,Ja,oe=R(()=>{\"use strict\";ao=class{static calcMatMulShape(t,r){return t[1]!==r[0]?void 0:[t[0],r[1]]}},et=class{static calcShape(t,r,n=!1){let o=t.length,i=r.length;if(o===0)return r;if(i===0)return t;let a=Math.max(t.length,r.length),l=new Array(a);if(n){if(o<2||i<2)return;let d=ao.calcMatMulShape([t[o-2],t[o-1]],[r[i-2],r[i-1]]);if(d===void 0)return;[l[a-2],l[a-1]]=d}for(let d=n?3:1;d<=a;d++){let p=o-d<0?1:t[o-d],m=i-d<0?1:r[i-d];if(p!==m&&p>1&&m>1)return;let u=Math.max(p,m);if(p&&m)l[a-d]=Math.max(p,m);else{if(u>1)return;l[a-d]=0}}return l}static isValidBroadcast(t,r){let n=t.length,o=r.length;if(n>o)return!1;for(let i=1;i<=n;i++)if(t[n-i]!==1&&t[n-i]!==r[o-i])return!1;return!0}},k=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let o=new Array(n),i=n-1;for(;i>=0;){if(t[i]%r===0){o[i]=t[i]/r;break}if(r%t[i]!==0)throw new Error(\"cannot convert shape\");o[i]=1,r/=t[i],i--}for(i--;i>=0;i--)o[i]=t[i];return o}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let o=1;for(let i=r;i=0;--o)n[o]=n[o+1]*t[o+1];return n}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error(\"unsupported axis for this operation.\");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(n=>this.normalizeAxis(n,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(n=>t[n]):t.slice().reverse()}static padShape(t,r){let n=t.length;return t.map((o,i)=>o+r[i]+r[i+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,o)=>n===r[o])}},It=class e{static adjustPoolAttributes(t,r,n,o,i,a){if(!t&&n.length!==r.length-2)throw new Error(\"length of specified kernel shapes should be 2 less than length of input dimensions\");if(t)for(let l=0;l=n.length?n.push(r[l+2]):n[l]=r[l+2];for(let l=0;l=n[l]||a[l+n.length]>=n[l])throw new Error(\"pads should be smaller than kernel\")}}static adjustPadsBasedOnAutoPad(t,r,n,o,i,a,l){if(l){if(i.length!==2*(t.length-2))throw new Error(\"length of pads should be twice the length of data dimensions\");if(r.length!==t.length-2)throw new Error(\"length of strides should be the length of data dimensions\");if(o.length!==t.length-2)throw new Error(\"length of kernel shapes should be the length of data dimensions\");for(let d=0;d{\"use strict\";te();oe();Ct=64,uo=(e,t)=>{if(t===3)throw new Error(\"vec3 has same alignment as vec4, use vec4 instead\");switch(Number(e)){case 10:return t>1?`vec${t}`:\"f16\";case 1:return t>1?`vec${t}`:\"f32\";case 6:return t>1?`vec${t}`:\"i32\";case 12:return t>1?`vec${t}`:\"u32\";case 7:if(t>1)throw new Error(\"currently not supported vecX of uint64 yet\");return[\"vec2\",\"i32\"];case 13:if(t>1)throw new Error(\"currently not supported vecX of uint64 yet\");return[\"vec2\",\"u32\"];case 9:if(t!==4)throw new Error(\"bool must be vec4\");return[\"u32\",\"vec4\"];case 22:return\"i32\";case 21:return\"u32\";default:throw new Error(`Unknown data type: ${e}`)}},ye=(e,t=1)=>{let r=uo(e,t);return typeof r==\"string\"?r:r[0]},ke=(e,t=1)=>{let r=uo(e,t);return typeof r==\"string\"?r:r[1]},N=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:k.computeStrides(r)})}),t},me=e=>e%4===0?4:e%2===0?2:1,lo=(e=\"f32\",t,r=\"0\")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,At=(e,t,r)=>e===\"f32\"?r:t===1?`f32(${r})`:`vec${t}(${r})`,He=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,F=(e,t,r,n)=>e.startsWith(\"uniforms.\")&&r>4?typeof t==\"string\"?n===\"f16\"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n===\"f16\"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Hr=(e,t,r,n,o)=>{let i=typeof r==\"number\",a=i?r:r.length,l=[...new Array(a).keys()],d=a<2?\"u32\":a<=4?`vec${a}`:`array`,p=uo(t,o),m=typeof p==\"string\"?p:p[1],u=typeof p==\"string\"?p:p[0],h={indices:d,value:m,storage:u,tensor:t},_=V=>typeof V==\"string\"?V:`${V}u`,y={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},g=i?\"uniforms.\":\"\",x=`${g}${e}_shape`,$=`${g}${e}_strides`,v=\"\";for(let V=0;V ${h.indices} {\n var indices: ${h.indices};\n var current = offset;\n ${v}\n return indices;\n }`,T=V=>(y.offsetToIndices=!0,a<2?V:`o2i_${e}(${V})`),C=[];if(a>=2)for(let V=a-1;V>=0;V--)C.push(`${F($,V,a)} * (indices[${V}])`);let A=a<2?\"\":`\n fn i2o_${e}(indices: ${h.indices}) -> u32 {\n return ${C.join(\"+\")};\n }`,P=V=>(y.indicesToOffset=!0,a<2?V:`i2o_${e}(${V})`),O=(...V)=>a===0?\"0u\":`${h.indices}(${V.map(_).join(\",\")})`,U=(V,j)=>a<2?`${V}`:`${F(V,j,a)}`,G=(V,j,he)=>a<2?`${V}=${he};`:`${F(V,j,a)}=${he};`,q={},K=(V,j)=>{y.broadcastedIndicesToOffset=!0;let he=`${j.name}broadcastedIndicesTo${e}Offset`;if(he in q)return`${he}(${V})`;let Ge=[];for(let _e=a-1;_e>=0;_e--){let be=j.indicesGet(\"outputIndices\",_e+j.rank-a);Ge.push(`${U($,_e)} * (${be} % ${U(x,_e)})`)}return q[he]=`fn ${he}(outputIndices: ${j.type.indices}) -> u32 {\n return ${Ge.length>0?Ge.join(\"+\"):\"0u\"};\n }`,`${he}(${V})`},W=(V,j)=>(()=>{if(h.storage===h.value)return`${e}[${V}]=${j};`;if(h.storage===\"vec2\"&&h.value===\"i32\")return`${e}[${V}]=vec2(u32(${j}), select(0u, 0xFFFFFFFFu, ${j} < 0));`;if(h.storage===\"vec2\"&&h.value===\"u32\")return`${e}[${V}]=vec2(u32(${j}), 0u);`;if(h.storage===\"u32\"&&h.value===\"vec4\")return`${e}[${V}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${j}));`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),Y=V=>(()=>{if(h.storage===h.value)return`${e}[${V}]`;if(h.storage===\"vec2\"&&h.value===\"i32\")return`i32(${e}[${V}].x)`;if(h.storage===\"vec2\"&&h.value===\"u32\")return`u32(${e}[${V}].x)`;if(h.storage===\"u32\"&&h.value===\"vec4\")return`vec4(bool(${e}[${V}] & 0xFFu), bool(${e}[${V}] & 0xFF00u), bool(${e}[${V}] & 0xFF0000u), bool(${e}[${V}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),se=a<2?\"\":`\n fn get_${e}ByIndices(indices: ${h.indices}) -> ${m} {\n return ${Y(`i2o_${e}(indices)`)};\n }`,X=a<2?\"\":(()=>{let V=l.map(he=>`d${he}: u32`).join(\", \"),j=l.map(he=>`d${he}`).join(\", \");return`\n fn get_${e}(${V}) -> ${m} {\n return get_${e}ByIndices(${O(j)});\n }`})(),re=(...V)=>{if(V.length!==a)throw new Error(`indices length must be ${a}`);let j=V.map(_).join(\",\");return a===0?Y(\"0u\"):a===1?Y(j[0]):(y.get=!0,y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}(${j})`)},ee=V=>a<2?Y(V):(y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}ByIndices(${V})`),ne=a<2?\"\":`\n fn set_${e}ByIndices(indices: ${h.indices}, value: ${m}) {\n ${W(`i2o_${e}(indices)`,\"value\")}\n }`,ve=a<2?\"\":(()=>{let V=l.map(he=>`d${he}: u32`).join(\", \"),j=l.map(he=>`d${he}`).join(\", \");return`\n fn set_${e}(${V}, value: ${m}) {\n set_${e}ByIndices(${O(j)}, value);\n }`})();return{impl:()=>{let V=[],j=!1;return y.offsetToIndices&&(V.push(S),j=!0),y.indicesToOffset&&(V.push(A),j=!0),y.broadcastedIndicesToOffset&&(Object.values(q).forEach(he=>V.push(he)),j=!0),y.set&&(V.push(ve),j=!0),y.setByIndices&&(V.push(ne),j=!0),y.get&&(V.push(X),j=!0),y.getByIndices&&(V.push(se),j=!0),!i&&j&&V.unshift(`const ${x} = ${h.indices}(${r.join(\",\")});`,`const ${$} = ${h.indices}(${k.computeStrides(r).join(\",\")});`),V.join(`\n`)},type:h,offsetToIndices:T,indicesToOffset:P,broadcastedIndicesToOffset:K,indices:O,indicesGet:U,indicesSet:G,set:(...V)=>{if(V.length!==a+1)throw new Error(`indices length must be ${a}`);let j=V[a];if(typeof j!=\"string\")throw new Error(\"value must be string\");let he=V.slice(0,a).map(_).join(\",\");return a===0?W(\"0u\",j):a===1?W(he[0],j):(y.set=!0,y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}(${he}, ${j})`)},setByOffset:W,setByIndices:(V,j)=>a<2?W(V,j):(y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}ByIndices(${V}, ${j});`),get:re,getByOffset:Y,getByIndices:ee,usage:n,name:e,strides:$,shape:x,rank:a}},E=(e,t,r,n=1)=>Hr(e,t,r,\"input\",n),M=(e,t,r,n=1)=>Hr(e,t,r,\"output\",n),es=(e,t,r)=>Hr(e,t,r,\"atomicOutput\",1),Fr=(e,t,r,n=1)=>Hr(e,t,r,\"internal\",n),so=class{constructor(t,r){this.normalizedDispatchGroup=t;this.limits=r;this.internalVariables=[];this.variables=[];this.uniforms=[];this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t==\"number\"?`${t}u`:t}) { return; }`}mainStart(t=Ct){let r=typeof t==\"number\"?t:t[0],n=typeof t==\"number\"?1:t[1],o=typeof t==\"number\"?1:t[2];if(r>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||o>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*n*o>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=i?`@builtin(global_invocation_id) global_id : vec3,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3,\n @builtin(local_invocation_id) local_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(num_workgroups) num_workgroups : vec3`,l=i?`let global_idx = global_id.x;\n let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] +\n workgroup_id.y * num_workgroups[0] + workgroup_id.x;\n let global_idx = workgroup_index * ${r*n*o}u + local_idx;`;return`@compute @workgroup_size(${r}, ${n}, ${o})\n fn main(${a}) {\n ${l}\n `}appendVariableUniforms(t){t.rank!==0&&(t.shape.startsWith(\"uniforms.\")&&this.uniforms.push({name:t.shape.replace(\"uniforms.\",\"\"),type:\"u32\",length:t.rank}),t.strides.startsWith(\"uniforms.\")&&this.uniforms.push({name:t.strides.replace(\"uniforms.\",\"\"),type:\"u32\",length:t.rank}))}declareVariable(t,r){if(t.usage===\"internal\")throw new Error(\"cannot use internal variable with declareVariable(). use registerInternalVariables() instead.\");this.variables.push(t),this.appendVariableUniforms(t);let n=t.usage===\"input\"?\"read\":\"read_write\",o=t.usage===\"atomicOutput\"?\"atomic\":t.type.storage;return`@group(0) @binding(${r}) var ${t.name}: array<${o}>;`}declareVariables(...t){return t.map(r=>this.declareVariable(r,this.variableIndex++)).join(`\n`)}registerInternalVariable(t){if(t.usage!==\"internal\")throw new Error(\"cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.\");this.internalVariables.push(t),this.appendVariableUniforms(t)}registerInternalVariables(...t){return t.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(t,r,n=1){return this.uniforms.push({name:t,type:r,length:n}),this}registerUniforms(t){return this.uniforms=this.uniforms.concat(t),this}uniformDeclaration(){if(this.uniforms.length===0)return\"\";let t=[];for(let{name:r,type:n,length:o}of this.uniforms)if(o&&o>4)n===\"f16\"?t.push(`@align(16) ${r}:array, ${Math.ceil(o/8)}>`):t.push(`${r}:array, ${Math.ceil(o/4)}>`);else{let i=o==null||o===1?n:`vec${o}<${n}>`;t.push(`${r}:${i}`)}return`\n struct Uniforms { ${t.join(\", \")} };\n @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(t=>t.impl()).join(`\n`)+this.internalVariables.map(t=>t.impl()).join(`\n`)}get variablesInfo(){if(this.uniforms.length===0)return;let t=r=>[12,10,1,6][[\"u32\",\"f16\",\"f32\",\"i32\"].indexOf(r)];return this.uniforms.map(r=>[t(r.type),r.length??1])}},ts=(e,t)=>new so(e,t)});var im,rs,am,sm,um,lm,Ee,ns,os,ut=R(()=>{\"use strict\";te();oe();Se();ae();im=e=>{if(!e||e.length!==1)throw new Error(\"Transpose requires 1 input.\")},rs=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,am=(e,t)=>k.sortBasedOnPerm(e,rs(e.length,t)),sm=(e,t,r,n)=>{let o=`fn perm(i: ${n.type.indices}) -> ${r.type.indices} {\n var a: ${r.type.indices};`;for(let i=0;i{let r=[],n=[];for(let o=0;o{let r=0;for(let n=0;n{let r=e.dataType,n=e.dims.length,o=rs(n,t),i=am(e.dims,o),a=e.dims,l=i,d=lm(o,e.dims),p;if(d)return p=g=>{let x=E(\"input\",r,a,4),$=M(\"output\",r,l,4);return`\n ${g.registerUniform(\"output_size\",\"u32\").declareVariables(x,$)}\n ${g.mainStart()}\n ${g.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n output[global_idx] = input[global_idx];\n }`},{name:\"TransposeCopy\",shaderCache:{inputDependencies:[\"type\"]},getRunData:()=>{let g=k.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(g/64/4)},programUniforms:[{type:12,data:Math.ceil(g/4)}]}},getShaderSource:p};let{newShape:m,newPerm:u}=um(e.dims,o),h=k.areEqual(u,[2,3,1]),_=k.areEqual(u,[3,1,2]);if(m.length===2||h||_){a=h?[m[0],m[1]*m[2]]:_?[m[0]*m[1],m[2]]:m,l=[a[1],a[0]];let g=16;return p=x=>{let $=E(\"a\",r,a.length),v=M(\"output\",r,l.length);return`\n ${x.registerUniform(\"output_size\",\"u32\").declareVariables($,v)}\n var tile : array, ${g}>;\n ${x.mainStart([g,g,1])}\n let stride = (uniforms.output_shape[1] - 1) / ${g} + 1;\n let workgroup_id_x = workgroup_index % stride;\n let workgroup_id_y = workgroup_index / stride;\n let input_col = workgroup_id_y * ${g}u + local_id.x;\n let input_row = workgroup_id_x * ${g}u + local_id.y;\n if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) {\n tile[local_id.y][local_id.x] = ${$.getByIndices(`${$.type.indices}(input_row, input_col)`)};\n }\n workgroupBarrier();\n\n let output_col = workgroup_id_x * ${g}u + local_id.x;\n let output_row = workgroup_id_y * ${g}u + local_id.y;\n if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) {\n ${v.setByIndices(`${v.type.indices}(output_row, output_col)`,\"tile[local_id.x][local_id.y]\")}\n }\n }`},{name:\"TransposeShared\",shaderCache:{inputDependencies:[\"type\"]},getRunData:()=>{let x=k.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(l[1]/g),y:Math.ceil(l[0]/g)},programUniforms:[{type:12,data:x},...N(a,l)]}},getShaderSource:p}}return p=g=>{let x=E(\"a\",r,a.length),$=M(\"output\",r,l.length);return`\n ${g.registerUniform(\"output_size\",\"u32\").declareVariables(x,$)}\n\n ${sm(o,n,x,$)}\n\n ${g.mainStart()}\n ${g.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let indices = ${$.offsetToIndices(\"global_idx\")};\n let aIndices = perm(indices);\n\n ${$.setByOffset(\"global_idx\",x.getByIndices(\"aIndices\"))}\n }`},{name:\"Transpose\",shaderCache:{hint:`${t}`,inputDependencies:[\"rank\"]},getRunData:()=>{let g=k.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:[{type:12,data:g},...N(a,l)]}},getShaderSource:p}},ns=(e,t)=>{im(e.inputs),e.compute(Ee(e.inputs[0],t.perm))},os=e=>J({perm:e.perm})});var dm,cm,pm,mm,fm,hm,gm,bm,ym,_m,tt,is,as,ss,us,ls,ds,cs,ps,ms,fs,hs=R(()=>{\"use strict\";te();oe();ae();qr();ut();dm={max:\"select(bestValue, candidate, candidate > bestValue)\",min:\"select(bestValue, candidate, candidate < bestValue)\",mean:\"bestValue + candidate\",sum:\"bestValue + candidate\",prod:\"bestValue * candidate\",sumSquare:\"bestValue + candidate * candidate\",logSumExp:\"bestValue + exp(candidate)\",l1:\"bestValue + abs(candidate)\",l2:\"bestValue + candidate * candidate\",logSum:\"bestValue + candidate\"},cm={max:\"select(bestValue, candidate, candidate > bestValue)\",min:\"select(bestValue, candidate, candidate < bestValue)\",mean:\"bestValue + candidate\",sum:\"bestValue + candidate\",prod:\"bestValue * candidate\",sumSquare:\"bestValue + candidate\",logSumExp:\"bestValue + candidate\",l1:\"bestValue + candidate\",l2:\"bestValue + candidate\",logSum:\"bestValue + candidate\"},pm={max:\"_A[offset]\",min:\"_A[offset]\",mean:\"0\",sum:\"0\",prod:\"1\",sumSquare:\"0\",logSumExp:\"0\",l1:\"0\",l2:\"0\",logSum:\"0\"},mm={max:\"bestValue\",min:\"bestValue\",sum:\"bestValue\",prod:\"bestValue\",sumSquare:\"bestValue\",logSumExp:\"log(bestValue)\",l1:\"bestValue\",l2:\"sqrt(bestValue)\",logSum:\"log(bestValue)\"},fm=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let i=0;ie[i]);return[r,o]},gm=(e,t)=>{let r=e.length+t.length,n=[],o=0;for(let i=0;i{for(let r=0;r{let r=[];if(!bm(e,t)){for(let n=0;nr.push(n))}return r},_m=(e,t,r,n,o,i,a)=>{let l=r[0].dims,d=k.size(i),p=k.size(a),m=E(\"_A\",r[0].dataType,l),u=M(\"output\",o,i),h=64;d===1&&(h=256);let _=`\n var aBestValues : array;\n `,y=g=>`\n ${g.registerUniform(\"reduceSize\",\"u32\").declareVariables(m,u)}\n ${_}\n fn DIV_CEIL(a : u32, b : u32) -> u32 {\n return ((a - 1u) / b + 1u);\n }\n ${g.mainStart(h)}\n\n let outputIndex = global_idx / ${h};\n let offset = outputIndex * uniforms.reduceSize;\n\n var bestValue = f32(${pm[n]});\n let Length = uniforms.reduceSize;\n for (var k = local_idx; k < Length; k = k + ${h}) {\n let candidate = f32(${m.getByOffset(\"offset + k\")});\n bestValue = ${dm[n]};\n }\n aBestValues[local_idx] = bestValue;\n workgroupBarrier();\n\n var reduceSize = min(Length, ${h}u);\n for (var currentSize = reduceSize / 2u; reduceSize > 1u;\n currentSize = reduceSize / 2u) {\n let interval = DIV_CEIL(reduceSize, 2u);\n if (local_idx < currentSize) {\n let candidate = aBestValues[local_idx + interval];\n bestValue = ${cm[n]};\n aBestValues[local_idx] = bestValue;\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (local_idx == 0u) {\n ${u.setByOffset(\"outputIndex\",`${n===\"mean\"?`${u.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${u.type.storage}(${mm[n]})`}`)};\n }\n }`;return{name:e,shaderCache:{hint:`${t};${h}`,inputDependencies:[\"type\"]},getShaderSource:y,getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:d},programUniforms:[{type:12,data:p}]})}},tt=(e,t,r,n)=>{let o=e.inputs.length===1?r:co(e.inputs,r),i=o.axes;i.length===0&&!o.noopWithEmptyAxes&&(i=e.inputs[0].dims.map((_,y)=>y));let a=k.normalizeAxes(i,e.inputs[0].dims.length),l=a,d=e.inputs[0],p=ym(l,e.inputs[0].dims.length);p.length>0&&(d=e.compute(Ee(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],l=fm(l.length,d.dims.length));let[m,u]=hm(d.dims,l),h=m;o.keepDims&&(h=gm(m,a)),e.compute(_m(t,o.cacheKey,[d],n,e.inputs[0].dataType,h,u),{inputs:[d]})},is=(e,t)=>{tt(e,\"ReduceMeanShared\",t,\"mean\")},as=(e,t)=>{tt(e,\"ReduceL1Shared\",t,\"l1\")},ss=(e,t)=>{tt(e,\"ReduceL2Shared\",t,\"l2\")},us=(e,t)=>{tt(e,\"ReduceLogSumExpShared\",t,\"logSumExp\")},ls=(e,t)=>{tt(e,\"ReduceMaxShared\",t,\"max\")},ds=(e,t)=>{tt(e,\"ReduceMinShared\",t,\"min\")},cs=(e,t)=>{tt(e,\"ReduceProdShared\",t,\"prod\")},ps=(e,t)=>{tt(e,\"ReduceSumShared\",t,\"sum\")},ms=(e,t)=>{tt(e,\"ReduceSumSquareShared\",t,\"sumSquare\")},fs=(e,t)=>{tt(e,\"ReduceLogSumShared\",t,\"logSum\")}});var rt,wm,jr,co,nt,vm,$m,xm,Sm,Tm,Im,Cm,Am,km,Em,ot,gs,bs,ys,_s,ws,vs,$s,xs,Ss,Ts,qr=R(()=>{\"use strict\";te();oe();Se();ae();hs();rt=e=>{if(!e||e.length===0||e.length>2)throw new Error(\"Reduce op requires 1 or 2 inputs.\");if(e.length===2&&e[1].dims.length!==1)throw new Error(\"Invalid axes input dims.\")},wm=e=>[\"\",\"\",`var value = ${e.getByIndices(\"input_indices\")};`,\"\"],jr=(e,t,r,n,o,i,a=!1,l=!1)=>{let d=[],p=r[0].dims,m=p.length,u=k.normalizeAxes(o,m),h=!l&&u.length===0;p.forEach((x,$)=>{h||u.indexOf($)>=0?a&&d.push(1):d.push(x)});let _=d.length,y=k.size(d);return{name:e,shaderCache:t,getShaderSource:x=>{let $=[],v=E(\"_A\",r[0].dataType,m),S=M(\"output\",i,_),T=n(v,S,u),C=T[2];for(let A=0,P=0;A=0?(a&&P++,C=`for(var j${A}: u32 = 0; j${A} < ${p[A]}; j${A}++) {\n ${T[2].includes(\"last_index\")?`let last_index = j${A};`:\"\"}\n ${v.indicesSet(\"input_indices\",A,`j${A}`)}\n ${C}\n }`):($.push(`${v.indicesSet(\"input_indices\",A,S.indicesGet(\"output_indices\",P))};`),P++);return`\n\n ${x.registerUniform(\"output_size\",\"u32\").declareVariables(v,S)}\n\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n var input_indices: ${v.type.indices};\n let output_indices = ${S.offsetToIndices(\"global_idx\")};\n\n ${$.join(`\n`)}\n ${T[0]} // init ops for reduce max/min\n ${T[1]}\n ${C}\n ${T[3]}\n ${T.length===4?S.setByOffset(\"global_idx\",\"value\"):T.slice(4).join(`\n`)}\n }`},getRunData:()=>({outputs:[{dims:d,dataType:i}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:[{type:12,data:y},...N(p,d)]})}},co=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),J({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},nt=(e,t,r,n)=>{let o=e.inputs,i=o.length===1?r:co(o,r);e.compute(jr(t,{hint:i.cacheKey,inputDependencies:[\"rank\"]},[o[0]],i.noopWithEmptyAxes&&i.axes.length===0?wm:n,i.axes,o[0].dataType,i.keepDims,i.noopWithEmptyAxes),{inputs:[0]})},vm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceLogSum\",t,(n,o)=>[`var value = ${o.type.storage}(0);`,\"\",`value += ${n.getByIndices(\"input_indices\")};`,\"value = log(value);\"])},$m=(e,t)=>{rt(e.inputs),nt(e,\"ReduceL1\",t,(n,o)=>[`var value = ${o.type.storage}(0);`,\"\",`value += abs(${n.getByIndices(\"input_indices\")});`,\"\"])},xm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceL2\",t,(n,o)=>[`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`,\"\",`t = ${n.getByIndices(\"input_indices\")}; value += (t * t);`,\"value = sqrt(value);\"])},Sm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceLogSumExp\",t,(n,o)=>[`var value = ${o.type.storage}(0);`,\"\",`value += exp(${n.getByIndices(\"input_indices\")});`,\"value = log(value);\"])},Tm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceMax\",t,(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(n.indicesSet(\"input_indices\",l,0));return[`${a.join(`\n`)}`,`var value = ${n.getByIndices(\"input_indices\")};`,`value = max(value, ${n.getByIndices(\"input_indices\")});`,\"\"]})},Im=(e,t)=>{rt(e.inputs),nt(e,\"ReduceMean\",t,(n,o,i)=>{let a=1;for(let l=0;l=0||i.length===0)&&(a*=e.inputs[0].dims[l]);return[\"var sum = f32(0);\",\"\",`sum += f32(${n.getByIndices(\"input_indices\")});`,`let value = ${o.type.value}(sum / ${a});`]})},Cm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceMin\",t,(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(`input_indices[${l}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${n.getByIndices(\"input_indices\")};`,`value = min(value, ${n.getByIndices(\"input_indices\")});`,\"\"]})},Am=(e,t)=>{rt(e.inputs),nt(e,\"ReduceProd\",t,(n,o)=>[`var value = ${o.type.storage}(1);`,\"\",`value *= ${n.getByIndices(\"input_indices\")};`,\"\"])},km=(e,t)=>{rt(e.inputs),nt(e,\"ReduceSum\",t,(n,o)=>[`var value = ${o.type.storage}(0);`,\"\",`value += ${n.getByIndices(\"input_indices\")};`,\"\"])},Em=(e,t)=>{rt(e.inputs),nt(e,\"ReduceSumSquare\",t,(n,o)=>[`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`,\"\",`t = ${n.getByIndices(\"input_indices\")}; value += t * t;`,\"\"])},ot=(e,t,r)=>{if(t.length===0)return r;let n=1,o=1;for(let i=0;i1024},gs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Im(e,t):is(e,t)},bs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?$m(e,t):as(e,t)},ys=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?xm(e,t):ss(e,t)},_s=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Sm(e,t):us(e,t)},ws=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Tm(e,t):ls(e,t)},vs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Cm(e,t):ds(e,t)},$s=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Am(e,t):cs(e,t)},xs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?km(e,t):ps(e,t)},Ss=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Em(e,t):ms(e,t)},Ts=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?vm(e,t):fs(e,t)}});var Is,Cs,As,po,ks=R(()=>{\"use strict\";te();Se();qr();Is=e=>{if(!e||e.length===0||e.length>2)throw new Error(\"ArgMinMaxOp op requires 1 or 2 inputs.\");if(e[0].dataType!==1)throw new Error(\"Invalid input type.\")},Cs=(e,t)=>{Is(e.inputs);let r=(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(`input_indices[${l}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${n.getByIndices(\"input_indices\")};\nvar best_index : i32 = 0;`,`if (${n.getByIndices(\"input_indices\")} ${t.selectLastIndex>0?\"<=\":\"<\"} value) {\n value = ${n.getByIndices(\"input_indices\")};\n best_index = i32(last_index);\n }`,\"\",o.setByOffset(\"global_idx\",\"best_index\")]};e.compute(jr(\"ArgMin\",{hint:t.cacheKey,inputDependencies:[\"rank\"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},As=(e,t)=>{Is(e.inputs);let r=(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(`input_indices[${l}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${n.getByIndices(\"input_indices\")};\nvar best_index : i32 = 0;`,`if (${n.getByIndices(\"input_indices\")} ${t.selectLastIndex>0?\">=\":\">\"} value) {\n value = ${n.getByIndices(\"input_indices\")};\n best_index = i32(last_index);\n }`,\"\",o.setByOffset(\"global_idx\",\"best_index\")]};e.compute(jr(\"argMax\",{hint:t.cacheKey,inputDependencies:[\"rank\"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},po=e=>J(e)});var Pm,mo,zm,Om,Bm,Rt,Dm,Es,Kr=R(()=>{\"use strict\";te();oe();Lr();ae();Pm=(e,t)=>{let r=e[0],n=e[1],o=e[2],i=e[3],a=e[4],l=e[5];if(a&&l)throw new Error(\"Attention cannot have both past and attention_bias\");if(r.dims.length!==3)throw new Error('Input \"input\" must have 3 dimensions');let d=r.dims[0],p=r.dims[1],m=r.dims[2];if(o.dims.length!==1)throw new Error('Input \"bias\" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input \"weights\" is expected to have 2 dimensions');if(n.dims[0]!==m)throw new Error(\"Input 1 dimension 0 should have same length as dimension 2 of input 0\");if(o.dims[0]!==n.dims[1])throw new Error('Input \"bias\" dimension 0 should have same length as dimension 1 of input \"weights\"');let u=o.dims[0]/3,h=u,_=h;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error(\"qkv_hidden_sizes attribute should have 3 elements\");for(let S of t.qkvHiddenSizes)if(S%t.numHeads!==0)throw new Error(\"qkv_hidden_sizes should be divisible by num_heads\");u=t.qkvHiddenSizes[0],h=t.qkvHiddenSizes[1],_=t.qkvHiddenSizes[2]}let y=p;if(u!==h)throw new Error(\"qkv_hidden_sizes first element should be same as the second\");if(o.dims[0]!==u+h+_)throw new Error('Input \"bias\" dimension 0 should have same length as sum of Q/K/V hidden sizes');let g=0;if(a){if(h!==_)throw new Error('Input \"past\" expect k_hidden_size == v_hidden_size');if(a.dims.length!==5)throw new Error('Input \"past\" must have 5 dimensions');if(a.dims[0]!==2)throw new Error('Input \"past\" first dimension must be 2');if(a.dims[1]!==d)throw new Error('Input \"past\" second dimension must be batch_size');if(a.dims[2]!==t.numHeads)throw new Error('Input \"past\" third dimension must be num_heads');if(a.dims[4]!==h/t.numHeads)throw new Error('Input \"past\" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(g=a.dims[3])}let x=y+g,$=-1,v=0;if(i)throw new Error(\"Mask not supported\");if(a)throw new Error(\"past is not supported\");if(l){if(l.dims.length!==4)throw new Error('Input \"attention_bias\" must have 4 dimensions');if(l.dims[0]!==d||l.dims[1]!==t.numHeads||l.dims[2]!==p||l.dims[3]!==x)throw new Error('Expect \"attention_bias\" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:d,sequenceLength:p,pastSequenceLength:g,kvSequenceLength:y,totalSequenceLength:x,maxSequenceLength:$,inputHiddenSize:m,hiddenSize:u,vHiddenSize:_,headSize:Math.floor(u/t.numHeads),vHeadSize:Math.floor(_/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:v,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},mo=(e,t,r)=>t&&e?`\n let total_sequence_length_input = u32(${t.getByOffset(\"0\")});\n let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);\n let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;\n let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input;\n total_sequence_length = u32(${e?.getByOffset(\"batchIdx\")}) + 1;\n var past_sequence_length: u32 = 0;\n if (is_first_prompt == false) {\n past_sequence_length = total_sequence_length - sequence_length;\n }\n `:`\n ${r?\"let past_sequence_length = uniforms.past_sequence_length\":\"\"};\n let present_sequence_length = total_sequence_length;\n `,zm=(e,t,r,n,o,i,a,l)=>{let d=me(a?1:i),p=64,m=i/d;m{let v=M(\"x\",e.dataType,e.dims,d),S=[v],T=a?E(\"seq_lens\",a.dataType,a.dims):void 0;T&&S.push(T);let C=l?E(\"total_sequence_length_input\",l.dataType,l.dims):void 0;C&&S.push(C);let A=ke(e.dataType),P=[{name:\"batch_size\",type:\"u32\"},{name:\"num_heads\",type:\"u32\"},{name:\"past_sequence_length\",type:\"u32\"},{name:\"sequence_length\",type:\"u32\"},{name:\"total_sequence_length\",type:\"u32\"},{name:\"elements_per_thread\",type:\"u32\"}];return`\n var thread_max: array;\n var thread_sum: array;\n ${$.registerUniforms(P).declareVariables(...S)}\n ${$.mainStart([p,1,1])}\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let sequence_length = uniforms.sequence_length;\n var total_sequence_length = uniforms.total_sequence_length;\n ${mo(T,C,!1)}\n let local_offset = local_idx * uniforms.elements_per_thread;\n let offset = (global_idx / ${p}) * uniforms.total_sequence_length + local_offset;\n let seq_causal_length = ${a?\"u32(past_sequence_length + workgroup_id.y + 1)\":\"total_sequence_length\"};\n var thread_max_vector = ${y}(-3.402823e+38f);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n thread_max_vector = max(${y}(x[offset + i]), thread_max_vector);\n }\n thread_max[local_idx] = ${(()=>{switch(d){case 1:return\"thread_max_vector\";case 2:return\"max(thread_max_vector.x, thread_max_vector.y)\";case 4:return\"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))\";default:throw new Error(`Unsupported components: ${d}`)}})()};\n workgroupBarrier();\n\n var max_value = f32(-3.402823e+38f);\n for (var i = 0u; i < ${p}; i++) {\n max_value = max(thread_max[i], max_value);\n }\n\n var sum_vector = ${y}(0);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n sum_vector += exp(${y}(x[offset + i]) - max_value);\n }\n thread_sum[local_idx] = ${(()=>{switch(d){case 1:return\"sum_vector\";case 2:return\"sum_vector.x + sum_vector.y\";case 4:return\"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w\";default:throw new Error(`Unsupported components: ${d}`)}})()};\n workgroupBarrier();\n\n var sum: f32 = 0;\n for (var i = 0u; i < ${p}; i++) {\n sum += thread_sum[i];\n }\n\n if (sum == 0) {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n x[offset + i] = ${v.type.value}(${A}(1.0) / ${A}(seq_causal_length));\n }\n } else {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n var f32input = ${y}(x[offset + i]);\n x[offset + i] = ${v.type.value}(exp(f32input - max_value) / sum);\n }\n }\n ${a?`\n for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) {\n x[offset + total_seq_id] = ${v.type.value}(${A}(0));\n }`:\"\"};\n }`};return{name:\"AttentionProbsSoftmax\",shaderCache:{hint:`${p};${_};${d}`,inputDependencies:g},getShaderSource:x,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(i/p),y:o,z:t*r},programUniforms:h})}},Om=(e,t,r,n,o,i,a,l,d)=>{let p=a+i.kvSequenceLength,m=[i.batchSize,i.numHeads,i.sequenceLength,p],u=e>1&&n,h=i.kvNumHeads?i.kvNumHeads:i.numHeads,_=u?[i.batchSize,h,p,i.headSize]:void 0,y=i.nReps?i.nReps:1,g=i.scale===0?1/Math.sqrt(i.headSize):i.scale,x=me(i.headSize),$=i.headSize/x,v=12,S={x:Math.ceil(p/v),y:Math.ceil(i.sequenceLength/v),z:i.batchSize*i.numHeads},T=[{type:12,data:i.sequenceLength},{type:12,data:$},{type:12,data:p},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:1,data:g},{type:12,data:a},{type:12,data:i.kvSequenceLength},{type:12,data:y}],C=u&&n&&k.size(n.dims)>0,A=[\"type\",\"type\"];C&&A.push(\"type\"),o&&A.push(\"type\"),l&&A.push(\"type\"),d&&A.push(\"type\");let P=[{dims:m,dataType:t.dataType,gpuDataType:0}];u&&P.push({dims:_,dataType:t.dataType,gpuDataType:0});let O=U=>{let G=E(\"q\",t.dataType,t.dims,x),q=E(\"key\",r.dataType,r.dims,x),K=[G,q];if(C){let ne=E(\"past_key\",n.dataType,n.dims,x);K.push(ne)}o&&K.push(E(\"attention_bias\",o.dataType,o.dims));let W=l?E(\"seq_lens\",l.dataType,l.dims):void 0;W&&K.push(W);let Y=d?E(\"total_sequence_length_input\",d.dataType,d.dims):void 0;Y&&K.push(Y);let se=M(\"output\",t.dataType,m),X=[se];u&&X.push(M(\"present_key\",t.dataType,_,x));let re=ke(1,x),ee=[{name:\"M\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"num_heads\",type:\"u32\"},{name:\"head_size\",type:\"u32\"},{name:\"alpha\",type:\"f32\"},{name:\"past_sequence_length\",type:\"u32\"},{name:\"kv_sequence_length\",type:\"u32\"},{name:\"n_reps\",type:\"u32\"}];return`\n const TILE_SIZE = ${v}u;\n\n var tileQ: array<${G.type.storage}, ${v*v}>;\n var tileK: array<${G.type.storage}, ${v*v}>;\n ${U.registerUniforms(ee).declareVariables(...K,...X)}\n ${U.mainStart([v,v,1])}\n // x holds the N and y holds the M\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let kvHeadIdx = ${y===1?\"headIdx\":\"headIdx / uniforms.n_reps\"};\n let kv_num_heads = ${y===1?\"uniforms.num_heads\":\"uniforms.num_heads / uniforms.n_reps\"};\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let m = workgroup_id.y * TILE_SIZE;\n let n = workgroup_id.x * TILE_SIZE;\n let sequence_length = uniforms.M;\n var total_sequence_length = uniforms.N;\n ${mo(W,Y,!0)}\n let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx;\n let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;\n ${C&&u?\"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;\":\"\"};\n let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K;\n ${u?\"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;\":\"\"}\n var value = ${re}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {\n var idx = TILE_SIZE * local_id.y + local_id.x;\n ${(()=>C&&u?`\n if (n + local_id.y < past_sequence_length) {\n tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x];\n } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {\n tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x];\n }`:`\n if (n + local_id.y < uniforms.kv_sequence_length) {\n tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x];\n }`)()}\n ${u?`if (n + local_id.y < present_sequence_length) {\n present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];\n }`:\"\"}\n }\n workgroupBarrier();\n\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {\n value += ${re}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);\n }\n\n workgroupBarrier();\n }\n\n if (global_id.y < uniforms.M && global_id.x < total_sequence_length) {\n let headOffset = workgroup_id.z * uniforms.M * uniforms.N;\n let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;\n var sum: f32 = ${(()=>{switch(x){case 1:return\"value\";case 2:return\"value.x + value.y\";case 4:return\"value.x + value.y + value.z + value.w\";default:throw new Error(`Unsupported components: ${x}`)}})()};\n output[outputIdx] = ${se.type.value} (sum * uniforms.alpha) + ${o?\"attention_bias[outputIdx]\":\"0.0\"};\n }\n }`};return{name:\"AttentionProbs\",shaderCache:{hint:`${x};${o!==void 0};${n!==void 0};${e}`,inputDependencies:A},getRunData:()=>({outputs:P,dispatchGroup:S,programUniforms:T}),getShaderSource:O}},Bm=(e,t,r,n,o,i,a=void 0,l=void 0)=>{let d=i+o.kvSequenceLength,p=o.nReps?o.nReps:1,m=o.vHiddenSize*p,u=e>1&&n,h=o.kvNumHeads?o.kvNumHeads:o.numHeads,_=u?[o.batchSize,h,d,o.headSize]:void 0,y=[o.batchSize,o.sequenceLength,m],g=12,x={x:Math.ceil(o.vHeadSize/g),y:Math.ceil(o.sequenceLength/g),z:o.batchSize*o.numHeads},$=[{type:12,data:o.sequenceLength},{type:12,data:d},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:m},{type:12,data:i},{type:12,data:o.kvSequenceLength},{type:12,data:p}],v=u&&n&&k.size(n.dims)>0,S=[\"type\",\"type\"];v&&S.push(\"type\"),a&&S.push(\"type\"),l&&S.push(\"type\");let T=[{dims:y,dataType:t.dataType,gpuDataType:0}];u&&T.push({dims:_,dataType:t.dataType,gpuDataType:0});let C=A=>{let P=E(\"probs\",t.dataType,t.dims),O=E(\"v\",r.dataType,r.dims),U=[P,O];v&&U.push(E(\"past_value\",n.dataType,n.dims));let G=a?E(\"seq_lens\",a.dataType,a.dims):void 0;a&&U.push(G);let q=l?E(\"total_sequence_length_input\",l.dataType,l.dims):void 0;l&&U.push(q);let W=[M(\"output\",t.dataType,y)];u&&W.push(M(\"present_value\",t.dataType,_));let Y=[{name:\"M\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"num_heads\",type:\"u32\"},{name:\"head_size\",type:\"u32\"},{name:\"v_hidden_size\",type:\"u32\"},{name:\"past_sequence_length\",type:\"u32\"},{name:\"kv_sequence_length\",type:\"u32\"},{name:\"n_reps\",type:\"u32\"}];return`\n const TILE_SIZE = ${g}u;\n var tileQ: array<${P.type.value}, ${g*g}>;\n var tileV: array<${P.type.value}, ${g*g}>;\n ${A.registerUniforms(Y).declareVariables(...U,...W)}\n ${A.mainStart([g,g,1])}\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let kvHeadIdx = ${p===1?\"headIdx\":\"headIdx / uniforms.n_reps\"};\n let kv_num_heads = ${p===1?\"uniforms.num_heads\":\"uniforms.num_heads / uniforms.n_reps\"};\n let m = global_id.y;\n let n = global_id.x;\n let sequence_length = uniforms.M;\n var total_sequence_length = uniforms.K;\n ${mo(G,q,!0)}\n let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;\n let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch\n ${v&&u?\"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;\":\"\"};\n let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n;\n ${u?\"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;\":\"\"}\n var value = ${P.type.storage}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n var idx = TILE_SIZE * local_id.y + local_id.x;\n ${(()=>v&&u?`\n if (w + local_id.y < past_sequence_length) {\n tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N];\n } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {\n tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N];\n }\n `:`\n if (w + local_id.y < uniforms.kv_sequence_length) {\n tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N];\n }`)()}\n ${u?`\n if (w + local_id.y < present_sequence_length) {\n present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx];\n }`:\"\"}\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) {\n value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x];\n }\n workgroupBarrier();\n }\n\n // we need to transpose output from BNSH_v to BSND_v\n if (m < uniforms.M && n < uniforms.N) {\n let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size\n + headIdx * uniforms.N + n;\n output[outputIdx] = value;\n }\n }`};return{name:\"AttentionScore\",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:S},getRunData:()=>({outputs:T,dispatchGroup:x,programUniforms:$}),getShaderSource:C}},Rt=(e,t,r,n,o,i,a,l,d,p,m=void 0,u=void 0)=>{let h=Math.min(e.outputCount,1+(a?1:0)+(l?1:0)),_=h>1?p.pastSequenceLength:0,y=_+p.kvSequenceLength,g=d&&k.size(d.dims)>0?d:void 0,x=[t,r];h>1&&a&&k.size(a.dims)>0&&x.push(a),g&&x.push(g),m&&x.push(m),u&&x.push(u);let $=e.compute(Om(h,t,r,a,g,p,_,m,u),{inputs:x,outputs:h>1?[-1,1]:[-1]})[0];e.compute(zm($,p.batchSize,p.numHeads,_,p.sequenceLength,y,m,u),{inputs:m&&u?[$,m,u]:[$],outputs:[]});let v=[$,n];h>1&&l&&k.size(l.dims)>0&&v.push(l),m&&v.push(m),u&&v.push(u),e.compute(Bm(h,$,n,l,p,_,m,u),{inputs:v,outputs:h>1?[0,2]:[0]})},Dm=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,o=t.inputHiddenSize,i=t.headSize,a=12,l={x:Math.ceil(t.headSize/a),y:Math.ceil(t.sequenceLength/a),z:t.batchSize*t.numHeads},d=[e.inputs[0],e.inputs[1],e.inputs[2]],p=[{type:12,data:n},{type:12,data:o},{type:12,data:i},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],m=u=>{let h=M(\"output_q\",d[0].dataType,r),_=M(\"output_k\",d[0].dataType,r),y=M(\"output_v\",d[0].dataType,r),g=E(\"input\",d[0].dataType,d[0].dims),x=E(\"weight\",d[1].dataType,d[1].dims),$=E(\"bias\",d[2].dataType,d[2].dims),v=g.type.storage,S=[{name:\"M\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"num_heads\",type:\"u32\"},{name:\"head_size\",type:\"u32\"},{name:\"hidden_size\",type:\"u32\"},{name:\"ldb\",type:\"u32\"}];return`\n const TILE_SIZE = ${a}u;\n var tileInput: array<${v}, ${a*a}>;\n var tileWeightQ: array<${v}, ${a*a}>;\n var tileWeightK: array<${v}, ${a*a}>;\n var tileWeightV: array<${v}, ${a*a}>;\n ${u.registerUniforms(S).declareVariables(g,x,$,h,_,y)}\n ${u.mainStart([a,a,1])}\n let batchIndex = workgroup_id.z / uniforms.num_heads;\n let headNumber = workgroup_id.z % uniforms.num_heads;\n let m = global_id.y;\n let n = global_id.x;\n\n let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;\n let biasOffsetQ = headNumber * uniforms.head_size;\n let biasOffsetK = uniforms.hidden_size + biasOffsetQ;\n let biasOffsetV = uniforms.hidden_size + biasOffsetK;\n\n var valueQ = ${v}(0);\n var valueK = ${v}(0);\n var valueV = ${v}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n let offset = n + (w + local_id.y) * uniforms.ldb;\n tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];\n tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];\n tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:l,programUniforms:p}),getShaderSource:m},{inputs:d,outputs:[-1,-1,-1]})},Es=(e,t)=>{let r=Pm(e.inputs,t),[n,o,i]=Dm(e,r);return Rt(e,n,o,i,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r)}});var Mm,Rm,Um,Ps,zs=R(()=>{\"use strict\";We();te();oe();Se();ae();Mm=(e,t)=>{if(!e||e.length!==5)throw new Error(\"BatchNormalization requires 5 inputs\");let r=(n,o,i)=>{let a=o.length;if(a!==n.length)throw new Error(`${i}: num dimensions != ${a}`);o.forEach((l,d)=>{if(l!==n[d])throw new Error(`${i}: dim[${d}] do not match`)})};if(e[0].dims.length>1){let n=t.format===\"NHWC\"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,n,\"Invalid input scale\"),r(e[2].dims,n,\"Invalid input B\"),r(e[3].dims,n,\"Invalid input mean\"),r(e[4].dims,n,\"Invalid input var\")}else r(e[1].dims,[1],\"Invalid input scale\"),r(e[2].dims,[1],\"Invalid input B\"),r(e[3].dims,[1],\"Invalid input mean\"),r(e[4].dims,[1],\"Invalid input var\")},Rm=(e,t)=>{let{epsilon:r,spatial:n,format:o}=t,i=e[0].dims,a=n?me(i[i.length-1]):1,l=o===\"NHWC\"&&i.length>1?a:1,d=k.size(i)/a,p=n,m=p?i.length:i,u=E(\"x\",e[0].dataType,e[0].dims,a),h=E(\"scale\",e[1].dataType,e[1].dims,l),_=E(\"bias\",e[2].dataType,e[2].dims,l),y=E(\"inputMean\",e[3].dataType,e[3].dims,l),g=E(\"inputVar\",e[4].dataType,e[4].dims,l),x=M(\"y\",e[0].dataType,m,a),$=()=>{let S=\"\";if(n)S=`let cOffset = ${i.length===1?\"0u\":o===\"NHWC\"?`outputIndices[${i.length-1}] / ${a}`:\"outputIndices[1]\"};`;else if(o===\"NCHW\")S=`\n ${x.indicesSet(\"outputIndices\",\"0\",\"0\")}\n let cOffset = ${x.indicesToOffset(\"outputIndices\")};`;else{S=`var cIndices = ${h.type.indices}(0);\n cIndices[0] = outputIndices[${i.length-1}];`;for(let T=1;T`\n const epsilon = ${r};\n ${S.registerUniform(\"outputSize\",\"u32\").declareVariables(u,h,_,y,g,x)}\n ${S.mainStart()}\n ${S.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n var outputIndices = ${x.offsetToIndices(`global_idx * ${a}`)};\n ${$()}\n let scale = ${h.getByOffset(\"cOffset\")};\n let bias = ${_.getByOffset(\"cOffset\")};\n let inputMean = ${y.getByOffset(\"cOffset\")};\n let inputVar = ${g.getByOffset(\"cOffset\")};\n let x = ${u.getByOffset(\"global_idx\")};\n let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;\n ${x.setByOffset(\"global_idx\",\"value\")}\n }`;return{name:\"BatchNormalization\",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${a}`,inputDependencies:p?[\"rank\",\"type\",\"type\",\"type\",\"type\"]:void 0},getShaderSource:v,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p?[{type:12,data:d},...N(i)]:[{type:12,data:d}]})}},Um=e=>J(e),Ps=(e,t)=>{let{inputs:r,outputCount:n}=e,o=Um({...t,outputCount:n});if(we.webgpu.validateInputContent&&Mm(r,o),t.trainingMode)throw new Error(\"BatchNormalization trainingMode is not supported yet.\");e.compute(Rm(r,o))}});var Nm,Vm,Os,Bs=R(()=>{\"use strict\";oe();ae();Nm=e=>{if(e[0].dims.length!==3)throw new Error(\"input should have 3 dimensions\");if(![320,640,1280].includes(e[0].dims[2]))throw new Error(\"number of channels should be 320, 640 or 1280\");if(e[1].dims.length!==1)throw new Error(\"bias is expected to have 1 dimensions\");if(e[0].dims[2]!==e[1].dims[0])throw new Error(\"last dimension of input and bias are not the same\")},Vm=e=>{let t=e[0].dims,r=e[0].dims[2],n=k.size(t)/4,o=e[0].dataType,i=E(\"input\",o,t,4),a=E(\"bias\",o,[r],4),l=E(\"residual\",o,t,4),d=M(\"output\",o,t,4);return{name:\"BiasAdd\",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:m=>`\n const channels = ${r}u / 4;\n ${m.declareVariables(i,a,l,d)}\n\n ${m.mainStart()}\n ${m.guardAgainstOutOfBoundsWorkgroupSizes(n)}\n let value = ${i.getByOffset(\"global_idx\")}\n + ${a.getByOffset(\"global_idx % channels\")} + ${l.getByOffset(\"global_idx\")};\n ${d.setByOffset(\"global_idx\",\"value\")}\n }`}},Os=e=>{Nm(e.inputs),e.compute(Vm(e.inputs))}});var Wm,fe,Ds,Ms,Rs,Us,Ns,Vs,Ws,Ls,Gs,Lm,Hs,Fs,qs,js,Jt,Ks,Yr,Ys,Zs,Qs,Xs,Js,eu,tu,ru,nu,ou,iu,au,su,uu,lu,du,cu,pu,fo,ho,mu,fu,hu,Gm,Hm,gu,Zr=R(()=>{\"use strict\";te();oe();Se();ae();Wm=(e,t,r,n,o,i,a)=>{let l=Math.ceil(t/4),d=\"\";typeof o==\"string\"?d=`${o}(a)`:d=o(\"a\");let p=E(\"inputData\",r,[l],4),m=M(\"outputData\",n,[l],4),u=[{name:\"vec_size\",type:\"u32\"}];return a&&u.push(...a),`\n ${e.registerUniforms(u).declareVariables(p,m)}\n\n ${i??\"\"}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.vec_size\")}\n\n let a = ${p.getByOffset(\"global_idx\")};\n ${m.setByOffset(\"global_idx\",d)}\n }`},fe=(e,t,r,n,o,i=e.dataType,a,l)=>{let d=[{type:12,data:Math.ceil(k.size(e.dims)/4)}];return a&&d.push(...a),{name:t,shaderCache:{hint:o,inputDependencies:[\"type\"]},getShaderSource:p=>Wm(p,k.size(e.dims),e.dataType,i,r,n,l),getRunData:p=>({outputs:[{dims:e.dims,dataType:i}],dispatchGroup:{x:Math.ceil(k.size(p[0].dims)/64/4)},programUniforms:d})}},Ds=e=>{e.compute(fe(e.inputs[0],\"Abs\",\"abs\"))},Ms=e=>{e.compute(fe(e.inputs[0],\"Acos\",\"acos\"))},Rs=e=>{e.compute(fe(e.inputs[0],\"Acosh\",\"acosh\"))},Us=e=>{e.compute(fe(e.inputs[0],\"Asin\",\"asin\"))},Ns=e=>{e.compute(fe(e.inputs[0],\"Asinh\",\"asinh\"))},Vs=e=>{e.compute(fe(e.inputs[0],\"Atan\",\"atan\"))},Ws=e=>{e.compute(fe(e.inputs[0],\"Atanh\",\"atanh\"))},Ls=e=>J(e),Gs=(e,t)=>{let r;switch(t.to){case 10:r=\"vec4\";break;case 1:r=\"vec4\";break;case 12:r=\"vec4\";break;case 6:r=\"vec4\";break;case 9:r=\"vec4\";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(fe(e.inputs[0],\"Cast\",r,void 0,t.cacheKey,t.to))},Lm=e=>{let t,r,n=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,r=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,r=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error(\"Unsupport data type\")}return J({min:t,max:r})},Hs=(e,t)=>{let r=t||Lm(e.inputs),n=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Clip\",o=>`clamp(${o}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,r.cacheKey,void 0,[{type:e.inputs[0].dataType,data:r.min},{type:e.inputs[0].dataType,data:r.max}],[{name:\"min\",type:n},{name:\"max\",type:n}]),{inputs:[0]})},Fs=e=>{e.compute(fe(e.inputs[0],\"Ceil\",\"ceil\"))},qs=e=>{e.compute(fe(e.inputs[0],\"Cos\",\"cos\"))},js=e=>{e.compute(fe(e.inputs[0],\"Cosh\",\"cosh\"))},Jt=e=>J(e),Ks=(e,t)=>{let r=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Elu\",n=>`elu_vf32(${n})`,`\n const elu_alpha_ = ${r}(${t.alpha});\n\n fn elu_f32(a: ${r}) -> ${r} {\n return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);\n }\n\n fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> {\n return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));\n }`,t.cacheKey))},Yr=(e=\"f32\")=>`\nconst r0: ${e} = 0.3275911;\nconst r1: ${e} = 0.254829592;\nconst r2: ${e} = -0.284496736;\nconst r3: ${e} = 1.421413741;\nconst r4: ${e} = -1.453152027;\nconst r5: ${e} = 1.061405429;\n\nfn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {\n let absv = abs(v);\n let x = 1.0 / (1.0 + r0 * absv);\n return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));\n}`,Ys=e=>{let t=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Erf\",r=>`erf_vf32(${r})`,Yr(t)))},Zs=e=>{e.compute(fe(e.inputs[0],\"Exp\",\"exp\"))},Qs=e=>{e.compute(fe(e.inputs[0],\"Floor\",\"floor\"))},Xs=e=>{let t=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Gelu\",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Yr(t)))},Js=(e,t)=>{let r=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"LeakyRelu\",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},eu=e=>{e.compute(fe(e.inputs[0],\"Not\",t=>`!${t}`))},tu=e=>{e.compute(fe(e.inputs[0],\"Neg\",t=>`-${t}`))},ru=e=>{e.compute(fe(e.inputs[0],\"Reciprocal\",t=>`1.0/${t}`))},nu=e=>{let t=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Relu\",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},ou=e=>{e.compute(fe(e.inputs[0],\"Sigmoid\",t=>`(1.0 / (1.0 + exp(-${t})))`))},iu=e=>J(e),au=(e,t)=>{let r=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"HardSigmoid\",n=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${n} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},su=e=>{e.compute(fe(e.inputs[0],\"Sin\",\"sin\"))},uu=e=>{e.compute(fe(e.inputs[0],\"Sinh\",\"sinh\"))},lu=e=>{e.compute(fe(e.inputs[0],\"Sqrt\",\"sqrt\"))},du=e=>{e.compute(fe(e.inputs[0],\"Tan\",\"tan\"))},cu=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,pu=e=>{e.compute(fe(e.inputs[0],\"Tanh\",cu))},fo=(e=\"f32\")=>`\nconst fast_gelu_a: ${e} = 0.5;\nconst fast_gelu_b: ${e} = 0.7978845608028654;\nconst fast_gelu_c: ${e} = 0.035677408136300125;\n\nfn tanh_v(v: vec4<${e}>) -> vec4<${e}> {\n return ${cu(\"v\")};\n}\n`,ho=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,mu=e=>{let t=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"FastGelu\",ho,fo(t),void 0,e.inputs[0].dataType))},fu=(e,t)=>{let r=ke(e.inputs[0].dataType);return e.compute(fe(e.inputs[0],\"ThresholdedRelu\",n=>`select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},hu=e=>{e.compute(fe(e.inputs[0],\"Log\",\"log\"))},Gm=(e,t)=>`\nconst alpha = vec4<${e}>(${t});\nconst one = ${e}(1.0);\nconst zero = ${e}(0.0);\n\nfn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {\n let v = x *alpha;\n var x1 : vec4<${e}>;\n for (var i = 0; i < 4; i = i + 1) {\n if (v[i] >= zero) {\n x1[i] = one / (one + exp(-v[i]));\n } else {\n x1[i] = one - one / (one + exp(v[i]));\n }\n }\n return x * x1;\n}\n`,Hm=e=>`quick_gelu_impl(${e})`,gu=(e,t)=>{let r=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"QuickGelu\",Hm,Gm(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}});var Fm,qm,yu,_u=R(()=>{\"use strict\";oe();ae();Zr();Fm=e=>{if(e[0].dims.length!==3)throw new Error(\"input should have 3 dimensions\");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error(\"hidden state should be 2560, 5120 or 10240\");if(e[1].dims.length!==1)throw new Error(\"bias is expected to have 1 dimensions\");if(e[0].dims[2]!==e[1].dims[0])throw new Error(\"last dimension of input and bias are not the same\")},qm=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=E(\"input\",e[0].dataType,e[0].dims,4),n=E(\"bias\",e[0].dataType,[e[0].dims[2]],4),o=M(\"output\",e[0].dataType,t,4),i=k.size(t)/4,a=ye(e[0].dataType);return{name:\"BiasSplitGelu\",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:d=>`\n const M_SQRT2 = sqrt(2.0);\n const halfChannels = ${e[0].dims[2]/4/2}u;\n\n ${d.declareVariables(r,n,o)}\n\n ${Yr(a)}\n\n ${d.mainStart()}\n ${d.guardAgainstOutOfBoundsWorkgroupSizes(i)}\n let biasIdx = global_idx % halfChannels;\n let batchIndex = global_idx / halfChannels;\n let inputOffset = biasIdx + batchIndex * halfChannels * 2;\n let valueLeft = input[inputOffset] + bias[biasIdx];\n let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];\n let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);\n\n ${o.setByOffset(\"global_idx\",\"valueLeft * geluRight\")}\n }`}},yu=e=>{Fm(e.inputs),e.compute(qm(e.inputs))}});var jm,Km,it,wu,vu,$u,xu,Su,Tu,Iu,Cu,Au,ku,Eu=R(()=>{\"use strict\";te();oe();ae();jm=(e,t,r,n,o,i,a,l,d,p,m,u)=>{let h,_;typeof l==\"string\"?h=_=(v,S)=>`${l}((${v}),(${S}))`:typeof l==\"function\"?h=_=l:(h=l.scalar,_=l.vector);let y=M(\"outputData\",m,n.length,4),g=E(\"aData\",d,t.length,4),x=E(\"bData\",p,r.length,4),$;if(o)if(i){let v=k.size(t)===1,S=k.size(r)===1,T=t.length>0&&t[t.length-1]%4===0,C=r.length>0&&r[r.length-1]%4===0;v||S?$=y.setByOffset(\"global_idx\",_(v?`${g.type.value}(${g.getByOffset(\"0\")}.x)`:g.getByOffset(\"global_idx\"),S?`${x.type.value}(${x.getByOffset(\"0\")}.x)`:x.getByOffset(\"global_idx\"))):$=`\n let outputIndices = ${y.offsetToIndices(\"global_idx * 4u\")};\n let offsetA = ${g.broadcastedIndicesToOffset(\"outputIndices\",y)};\n let offsetB = ${x.broadcastedIndicesToOffset(\"outputIndices\",y)};\n ${y.setByOffset(\"global_idx\",_(a||T?g.getByOffset(\"offsetA / 4u\"):`${g.type.value}(${g.getByOffset(\"offsetA / 4u\")}[offsetA % 4u])`,a||C?x.getByOffset(\"offsetB / 4u\"):`${x.type.value}(${x.getByOffset(\"offsetB / 4u\")}[offsetB % 4u])`))}\n `}else $=y.setByOffset(\"global_idx\",_(g.getByOffset(\"global_idx\"),x.getByOffset(\"global_idx\")));else{if(!i)throw new Error(\"no necessary to use scalar implementation for element-wise binary op implementation.\");let v=(S,T,C=\"\")=>{let A=`aData[indexA${T}][componentA${T}]`,P=`bData[indexB${T}][componentB${T}]`;return`\n let outputIndices${T} = ${y.offsetToIndices(`global_idx * 4u + ${T}u`)};\n let offsetA${T} = ${g.broadcastedIndicesToOffset(`outputIndices${T}`,y)};\n let offsetB${T} = ${x.broadcastedIndicesToOffset(`outputIndices${T}`,y)};\n let indexA${T} = offsetA${T} / 4u;\n let indexB${T} = offsetB${T} / 4u;\n let componentA${T} = offsetA${T} % 4u;\n let componentB${T} = offsetB${T} % 4u;\n ${S}[${T}] = ${C}(${h(A,P)});\n `};m===9?$=`\n var data = vec4(0);\n ${v(\"data\",0,\"u32\")}\n ${v(\"data\",1,\"u32\")}\n ${v(\"data\",2,\"u32\")}\n ${v(\"data\",3,\"u32\")}\n outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:$=`\n ${v(\"outputData[global_idx]\",0)}\n ${v(\"outputData[global_idx]\",1)}\n ${v(\"outputData[global_idx]\",2)}\n ${v(\"outputData[global_idx]\",3)}\n `}return`\n ${e.registerUniform(\"vec_size\",\"u32\").declareVariables(g,x,y)}\n\n ${u??\"\"}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.vec_size\")}\n ${$}\n }`},Km=(e,t,r,n,o,i,a=r.dataType)=>{let l=r.dims.map(g=>Number(g)??1),d=n.dims.map(g=>Number(g)??1),p=!k.areEqual(l,d),m=l,u=k.size(l),h=!1,_=!1,y=[p];if(p){let g=et.calcShape(l,d,!1);if(!g)throw new Error(\"Can't perform binary op on the given tensors\");m=g.slice(),u=k.size(m);let x=k.size(l)===1,$=k.size(d)===1,v=l.length>0&&l[l.length-1]%4===0,S=d.length>0&&d[d.length-1]%4===0;y.push(x),y.push($),y.push(v),y.push(S);let T=1;for(let C=1;Cg.toString()).join(\"_\"),inputDependencies:[\"rank\",\"rank\"]},getShaderSource:g=>jm(g,l,d,m,h,p,_,o,r.dataType,n.dataType,a,i),getRunData:()=>({outputs:[{dims:m,dataType:a}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:Math.ceil(k.size(m)/4)},...N(l,d,m)]})}},it=(e,t,r,n,o,i)=>{e.compute(Km(t,o??\"\",e.inputs[0],e.inputs[1],r,n,i))},wu=e=>{it(e,\"Add\",(t,r)=>`${t}+${r}`)},vu=e=>{it(e,\"Div\",(t,r)=>`${t}/${r}`)},$u=e=>{it(e,\"Equal\",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},xu=e=>{it(e,\"Mul\",(t,r)=>`${t}*${r}`)},Su=e=>{let t=E(\"input\",e.inputs[0].dataType,e.inputs[0].dims).type.value;it(e,\"Pow\",{scalar:(n,o)=>`pow_custom(${n},${o})`,vector:(n,o)=>`pow_vector_custom(${n},${o})`},`\n fn pow_custom(a : ${t}, b : ${t}) -> ${t} {\n if (b == ${t}(0.0)) {\n return ${t}(1.0);\n } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {\n return ${t}(pow(f32(a), f32(b))); // NaN\n }\n return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t===\"i32\"?\"round\":\"\"}(pow(f32(abs(a)), f32(b))));\n }\n fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {\n // TODO: implement vectorized pow\n return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));\n }\n `)},Tu=e=>{it(e,\"Sub\",(t,r)=>`${t}-${r}`)},Iu=e=>{it(e,\"Greater\",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},Cu=e=>{it(e,\"Less\",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Au=e=>{it(e,\"GreaterOrEqual\",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},ku=e=>{it(e,\"LessOrEqual\",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}});var Zm,Qm,Xm,Jm,Pu,zu,Ou=R(()=>{\"use strict\";te();oe();Se();ae();Zm=(e,t)=>{if(!e||e.length<1)throw new Error(\"too few inputs\");let r=0,n=e[r],o=n.dataType,i=n.dims.length;e.forEach((a,l)=>{if(l!==r){if(a.dataType!==o)throw new Error(\"input tensors should be one type\");if(a.dims.length!==i)throw new Error(\"input tensors should have the same shape\");a.dims.forEach((d,p)=>{if(p!==t&&d!==n.dims[p])throw new Error(\"non concat dimensions must match\")})}})},Qm=(e,t)=>`\n fn calculateInputIndex(index: u32) -> u32 {\n let sizeInConcatAxis = array(${t});\n for (var i: u32 = 0u; i < ${e}; i += 1u ) {\n if (index < sizeInConcatAxis[i]) {\n return i;\n }\n }\n return ${e}u;\n }`,Xm=(e,t)=>{let r=e.length,n=[];for(let o=0;o{let o=k.size(r),i=new Array(e.length),a=new Array(e.length),l=0,d=[],p=[],m=[{type:12,data:o}];for(let g=0;g`uniforms.sizeInConcatAxis${g}`).join(\",\"),y=g=>`\n\n ${(()=>{g.registerUniform(\"outputSize\",\"u32\");for(let x=0;x(${_});\n ${h} -= sizeInConcatAxis[inputIndex - 1u];\n }\n\n ${Xm(a,u)}\n }`;return{name:\"Concat\",shaderCache:{hint:`${t}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:m}),getShaderSource:y}},Pu=(e,t)=>{let r=e.inputs,n=r[0].dims,o=k.normalizeAxis(t.axis,n.length);Zm(r,o);let i=n.slice();i[o]=r.reduce((l,d)=>l+(d.dims.length>o?d.dims[o]:0),0);let a=r.filter(l=>k.size(l.dims)>0);e.compute(Jm(a,o,i,r[0].dataType),{inputs:a})},zu=e=>J({axis:e.axis})});var Fe,qe,je,Qr,bt=R(()=>{\"use strict\";te();oe();Fe=(e,t,r=\"f32\")=>{switch(e.activation){case\"Relu\":return`value = max(value, ${t}(0.0));`;case\"Sigmoid\":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case\"Clip\":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case\"HardSigmoid\":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case\"LeakyRelu\":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case\"Tanh\":return`let e2x = exp(-2.0 * abs(value));\n value = sign(value) * (1.0 - e2x) / (1.0 + e2x);\n `;case\"\":return\"\";default:throw new Error(`Unsupported activation ${e.activation}`)}},qe=(e,t)=>{e.activation===\"Clip\"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation===\"HardSigmoid\"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation===\"LeakyRelu\"&&t.push({type:1,data:e.alpha})},je=(e,t)=>{e.activation===\"Clip\"?t.push({name:\"clip_max\",type:\"f32\"},{name:\"clip_min\",type:\"f32\"}):e.activation===\"HardSigmoid\"?t.push({name:\"alpha\",type:\"f32\"},{name:\"beta\",type:\"f32\"}):e.activation===\"LeakyRelu\"&&t.push({name:\"alpha\",type:\"f32\"})},Qr=e=>{let t=e?.activation||\"\";if(t===\"HardSigmoid\"){let[r,n]=e?.activation_params||[.2,.5];return{activation:t,alpha:r,beta:n}}else if(t===\"Clip\"){let[r,n]=e?.activation_params||[Xa,Ja];return{activation:t,clipMax:n,clipMin:r}}else if(t===\"LeakyRelu\"){let[r]=e?.activation_params||[.01];return{activation:t,alpha:r}}return{activation:t}}});var Pe,Bu,Xr=R(()=>{\"use strict\";Pe=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},Bu=e=>`\n ${e?\"value = value + getBiasByOutputCoords(coords);\":\"\"}\n `});var Du,Mu=R(()=>{\"use strict\";Du=e=>`\nfn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 {\n return dot(coords, vec4(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n}\nfn getOutputIndexFromCoords(coords : vec4) -> i32 {\n return dot(coords, vec4(\n i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));\n}\n`});var er,Jr,en=R(()=>{\"use strict\";te();oe();ae();bt();er=(e,t,r,n,o)=>{let i=n-r;return`\n ${Array.from({length:r}).map((a,l)=>`\n if (${F(t.shape,l,t.rank)} != 1) {\n ${t.indicesSet(e,l,F(o,l+i,n))}\n } else {\n ${t.indicesSet(e,l,0)}\n }`).join(\"\")}\n`},Jr=(e,t,r,n,o=!1,i)=>{let a=e[0].dims,l=e[1].dims,d=a[a.length-2],p=l[l.length-1],m=a[a.length-1],u=me(p),h=me(m),_=me(d),y=k.size(r)/u/_,g=e.length>2,x=n?n.slice(0,-2):r.slice(0,-2),v=[k.size(x),d,p],S=[{type:12,data:y},{type:12,data:d},{type:12,data:p},{type:12,data:m}];qe(t,S),S.push(...N(x,a,l)),g&&S.push(...N(e[2].dims)),S.push(...N(v));let T=C=>{let A=Fr(\"batch_dims\",e[0].dataType,x.length),P=E(\"a\",e[0].dataType,a.length,h),O=E(\"b\",e[1].dataType,l.length,u),U=M(\"output\",e[0].dataType,v.length,u),G=ye(U.type.tensor),q=Fe(t,U.type.value,G),K=[P,O],W=\"\";if(g){let X=o?u:1;K.push(E(\"bias\",e[2].dataType,e[2].dims.length,X)),W=`${o?`value += bias[col / ${X}];`:`value += ${U.type.value}(bias[row + i]);`}`}let Y=[{name:\"output_size\",type:\"u32\"},{name:\"M\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"K\",type:\"u32\"}];je(t,Y);let se=()=>{let X=`var a_data: ${P.type.value};`;for(let re=0;re;\n for (var k: u32 = 0u; k < uniforms.K; k = k + ${h}) {\n ${se()}\n }\n for (var i = 0u; i < ${_}u; i++) {\n var value = values[i];\n ${W}\n ${q}\n let cur_indices = ${U.type.indices}(batch, row + i, col);\n let offset = ${U.indicesToOffset(\"cur_indices\")};\n ${U.setByOffset(`offset / ${u}`,\"value\")};\n }\n }\n `};return{name:\"MatMulNaive\",shaderCache:{hint:`${t.activation};${u};${h};${_};${o}`,inputDependencies:g?[\"rank\",\"rank\",\"rank\"]:[\"rank\",\"rank\"]},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:S}),getShaderSource:T}}});var ef,tf,go,Ru,rf,bo,nf,tr,tn=R(()=>{\"use strict\";te();oe();ae();bt();en();Xr();ef=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart / innerElementSize + inputCol${t?\", batchIndices\":\"\"});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRow + innerRow,\n kStart / innerElementSize + inputCol${t?\", batchIndices\":\"\"});\n `,tf=(e,t)=>e?`\n let ACached0 = mm_Asub[k * innerElementSize][localRow];\n let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];\n let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];\n ${t===3?\"\":\"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];\"}\n for (var i = 0; i < rowPerThread; i = i + 1) {\n acc[i] = BCached0 * ACached0[i] + acc[i];\n acc[i] = BCached1 * ACached1[i] + acc[i];\n acc[i] = BCached2 * ACached2[i] + acc[i];\n ${t===3?\"\":\"acc[i] = BCached3 * ACached3[i] + acc[i];\"}\n }`:`\n for (var i = 0; i < rowPerThread; i = i + 1) {\n let ACached = mm_Asub[tileRow + i][k];\n acc[i] = BCached0 * ACached.x + acc[i];\n acc[i] = BCached1 * ACached.y + acc[i];\n acc[i] = BCached2 * ACached.z + acc[i];\n ${t===3?\"\":\"acc[i] = BCached3 * ACached.w + acc[i];\"}\n }`,go=(e,t,r=\"f32\",n,o=!1,i=32,a=!1,l=32)=>{let d=t[1]*e[1],p=t[0]*e[0],m=o?d:i,u=o?i:d,h=m/t[0],_=i/t[1];if(!((o&&h===4&&e[1]===4||!o&&(h===3||h===4))&&m%t[0]===0&&i%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${h} and workPerThread[1] ${e[1]} must be 4.\n Otherwise, innerElementSize ${h} must be 3 or 4.\n tileAWidth ${m} must be divisible by workgroupSize[0]${t[0]}. tileInner ${i} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`\nvar mm_Asub: array, ${m/h}>, ${u}>;\nvar mm_Bsub: array, ${p/e[0]}>, ${i}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${h};\nconst tileInner = ${i};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let localRow = i32(localId.y);\n let tileRow = localRow * rowPerThread;\n let tileCol = i32(localId.x);\n\n let globalRow =i32(globalId.y) * rowPerThread;\n let globalCol = i32(globalId.x);\n let batch = ${a?\"0\":\"i32(globalId.z)\"};\n ${n?`let batchIndices = ${n.offsetToIndices(\"u32(batch)\")};`:\"\"}\n let globalRowStart = i32(workgroupId.y) * ${d};\n\n let num_tiles = ${a?`${Math.ceil(l/i)}`:\"(uniforms.dim_inner - 1) / tileInner + 1\"};\n var kStart = ${a?`i32(globalId.z) * ${l}`:\"0\"};\n\n var acc: array, rowPerThread>;\n\n // Loop over shared dimension.\n let tileRowB = localRow * ${_};\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileCol;\n ${ef(o,n)}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?\", batchIndices\":\"\"});\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {\n let BCached0 = mm_Bsub[k * innerElementSize][tileCol];\n let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];\n let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];\n ${h===3?\"\":\"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];\"}\n\n ${tf(o,h)}\n }\n\n workgroupBarrier();\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);\n }\n}`},Ru=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart + inputCol${t?\", batchIndices\":\"\"});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRowStart + inputRow,\n kStart + inputCol${t?\", batchIndices\":\"\"});\n `,rf=e=>e?\"let ACached = mm_Asub[k][tileRow + innerRow];\":\"let ACached = mm_Asub[tileRow + innerRow][k];\",bo=(e,t,r=\"f32\",n,o=!1,i=32,a=!1,l=32,d=!1)=>{let p=e[1]*t[1],m=e[0]*t[0],u=o?p:i,h=o?i:p;if(!(h%t[1]===0&&u%t[0]===0&&i%t[1]===0))throw new Error(`tileAHight ${h} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${u} must be divisible by workgroupSize[0]${t[0]}, tileInner ${i} must be divisible by workgroupSize[1]${t[1]}`);let _=h/t[1],y=u/t[0],g=i/t[1],x=d?`\n let localRow = i32(localId.y);\n let localCol = i32(localId.x);\n let globalRowStart = i32(workgroupId.y) * ${p};\n let globalColStart = i32(workgroupId.x) * ${m};\n\n // Loop over shared dimension.\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var inputRow = localRow; inputRow < ${h}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${t[0]}) {\n ${Ru(o,n)}\n }\n }\n // Load one tile of B into local memory.\n for (var inputRow = localRow; inputRow < ${i}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${m}; inputCol = inputCol + ${t[0]}) {\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalColStart + inputCol${n?\", batchIndices\":\"\"});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] +\n ACached * BCached[innerCol];\n }\n }\n }\n workgroupBarrier();\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let gRow = globalRowStart + localRow + innerRow * ${t[1]};\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let gCol = globalColStart + localCol + innerCol * ${t[0]};\n mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);\n }\n }\n `:`\nlet tileRow = i32(localId.y) * rowPerThread;\nlet tileCol = i32(localId.x) * colPerThread;\n\nlet globalRow = i32(globalId.y) * rowPerThread;\nlet globalCol = i32(globalId.x) * colPerThread;\nlet globalRowStart = i32(workgroupId.y) * ${p};\n\nlet tileRowA = i32(localId.y) * ${_};\nlet tileColA = i32(localId.x) * ${y};\nlet tileRowB = i32(localId.y) * ${g};\n// Loop over shared dimension.\nfor (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${y}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${Ru(o,n)}\n }\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${g}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol + innerCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalCol + innerCol${n?\", batchIndices\":\"\"});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][tileCol + inner];\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n ${rf(o)}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];\n }\n }\n }\n\n workgroupBarrier();\n}\n\nfor (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n mm_write(batch, globalRow + innerRow, globalCol + innerCol,\n acc[innerRow][innerCol]);\n }\n}\n`;return`\n var mm_Asub : array, ${h}>;\n var mm_Bsub : array, ${i}>;\n const rowPerThread = ${e[1]};\n const colPerThread = ${e[0]};\n const tileInner = ${i};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let batch = ${a?\"0\":\"i32(globalId.z)\"};\n ${n?`let batchIndices = ${n.offsetToIndices(\"u32(batch)\")};`:\"\"}\n let num_tiles = ${a?`${Math.ceil(l/i)}`:\"(uniforms.dim_inner - 1) / tileInner + 1\"};\n var kStart = ${a?`i32(globalId.z) * ${l}`:\"0\"};\n\n var acc : array, rowPerThread>;\n ${x}\n }\n`},nf=(e,t,r,n,o=!1)=>{let[i,a,l,d]=n,p=ye(n[0].type.tensor);return`\n fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${Pe(e,p)} {\n var value = ${Pe(e,p)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)\n {\n var aIndices: ${a.type.indices};\n ${er(\"aIndices\",a,a.rank-2,i.rank,\"batchIndices\")}\n ${a.indicesSet(\"aIndices\",a.rank-2,\"u32(row)\")}\n ${a.indicesSet(\"aIndices\",a.rank-1,\"u32(colIn)\")}\n value = ${a.getByIndices(\"aIndices\")};\n }\n return value;\n }\n\n fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${Pe(e,p)} {\n var value = ${Pe(e,p)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)\n {\n var bIndices: ${l.type.indices};\n ${er(\"bIndices\",l,l.rank-2,i.rank,\"batchIndices\")}\n ${l.indicesSet(\"bIndices\",l.rank-2,\"u32(row)\")}\n ${l.indicesSet(\"bIndices\",l.rank-1,\"u32(colIn)\")}\n value = ${l.getByIndices(\"bIndices\")};\n }\n return value;\n }\n\n fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Pe(e,p)}) {\n let col = colIn * ${e};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueIn;\n let coords = vec3(batch, row, colIn);\n ${t?`value = value + ${o?\"bias[colIn]\":`${Pe(e,p)}(bias[row])`};`:\"\"}\n ${r}\n ${d.setByIndices(\"vec3(coords)\",\"value\")}\n }\n }\n `},tr=(e,t,r,n,o=!1,i)=>{let a=e[0].dims,l=e[1].dims,d=a.slice(0,-2),p=l.slice(0,-2),m=n?n.slice(0,-2):r.slice(0,-2),u=k.size(m),h=a[a.length-2],_=a[a.length-1],y=l[l.length-1],g=_%4===0&&y%4===0,x=h<=8?[4,1,1]:[4,4,1],$=[8,8,1],v=[Math.ceil(y/$[0]/x[0]),Math.ceil(h/$[1]/x[1]),Math.ceil(u/$[2]/x[2])],S=g?4:1,T=[...d,h,_/S],C=T.length,A=[...p,_,y/S],P=A.length,O=[u,h,y/S],U=[{type:6,data:h},{type:6,data:y},{type:6,data:_}];qe(t,U),U.push(...N(m,T,A));let G=[\"rank\",\"rank\"],q=e.length>2;q&&(U.push(...N(e[2].dims)),G.push(\"rank\")),U.push(...N(O));let K=W=>{let Y=m.length,se=Fr(\"batchDims\",e[0].dataType,Y,1),X=ye(e[0].dataType),re=E(\"a\",e[0].dataType,C,S),ee=E(\"b\",e[1].dataType,P,S),ne=M(\"result\",e[0].dataType,O.length,S),ve=[re,ee];if(q){let j=o?S:1;ve.push(E(\"bias\",e[2].dataType,e[2].dims.length,j))}let Be=[{name:\"dim_a_outer\",type:\"i32\"},{name:\"dim_b_outer\",type:\"i32\"},{name:\"dim_inner\",type:\"i32\"}];je(t,Be);let $e=ye(ne.type.tensor),de=Fe(t,ne.type.value,$e),V=nf(S,q,de,[se,re,ee,ne],o);return`\n ${W.registerUniforms(Be).registerInternalVariables(se).declareVariables(...ve,ne)}\n ${V}\n ${g?go(x,$,X,se):bo(x,$,X,se)}\n `};return{name:\"MatMul\",shaderCache:{hint:`${x};${t.activation};${g};${o}`,inputDependencies:G},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:v[0],y:v[1],z:v[2]},programUniforms:U}),getShaderSource:K}}});var of,Uu,Nu=R(()=>{\"use strict\";te();Je();ae();bt();Xr();Mu();tn();of=(e,t,r,n,o=!1,i,a=4,l=4,d=4,p=\"f32\")=>{let m=G=>{switch(G){case 1:return\"resData = x[xIndex];\";case 3:return`resData = vec3<${p}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return\"resData = x[xIndex / 4];\";default:throw new Error(`innerElementSize ${G} is not supported.`)}},u=G=>{switch(G){case 1:return\"return w[row * i32(uniforms.w_shape[3]) + colIn];\";case 4:return\"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];\";default:throw new Error(`innerElementSize ${G} is not supported.`)}},h=e?`\n let coord = vec4(batch, xRow, xCol, xCh);\n `:`\n let coord = vec4(batch, xCh, xRow, xCol);\n `,_=e?`\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n `:`\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n `,y=e?\"i32(uniforms.x_shape[1])\":\"i32(uniforms.x_shape[2])\",g=e?\"i32(uniforms.x_shape[2])\":\"i32(uniforms.x_shape[3])\",x=e?\"row\":\"col\",$=e?\"col\":\"row\",v=`\n let inChannels = i32(uniforms.w_shape[2]);\n let outWidth = ${e?\"i32(uniforms.result_shape[2])\":\"i32(uniforms.result_shape[3])\"};\n let outRow = ${x} / outWidth;\n let outCol = ${x} % outWidth;\n\n let WRow = ${$} / (i32(uniforms.w_shape[1]) * inChannels);\n let WCol = ${$} / inChannels % i32(uniforms.w_shape[1]);\n let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];\n let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];\n let xCh = ${$} % inChannels;\n var resData = ${Pe(a,p)}(0.0);\n // The bounds checking is always needed since we use it to pad zero for\n // the 'same' padding type.\n if (xRow >= 0 && xRow < ${y} && xCol >= 0 && xCol < ${g}) {\n ${h}\n let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape));\n ${m(a)}\n }\n return resData;`,S=e?t&&n?`\n let col = colIn * ${a};\n ${v}`:`\n let col = colIn * ${a};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${v}\n }\n return ${Pe(a,p)}(0.0);`:n&&r?`\n let col = colIn * ${a};\n ${v}`:`\n let col = colIn * ${a};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${v}\n }\n return ${Pe(a,p)}(0.0);`,T=`${u(l)}`,C=Pe(d,p),A=e?Pe(a,p):Pe(l,p),P=e?Pe(l,p):Pe(a,p),O=Fe(i,C,p);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${A} {\n ${e?S:T}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${P} {\n ${e?T:S}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${C}) {\n let col = colIn * ${d};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)\n {\n var value = valueIn;\n let outWidth = ${e?\"i32(uniforms.result_shape[2])\":\"i32(uniforms.result_shape[3])\"};\n ${_}\n ${Bu(o)}\n ${O}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`},Uu=(e,t,r,n,o,i,a,l,d)=>{let p=t.format===\"NHWC\",m=p?e[0].dims[3]:e[0].dims[1],u=r[0],h=p?r[2]:r[3],_=p?r[1]:r[2],y=p?r[3]:r[1],g=p&&(m%4===0||m%3===0)&&y%4===0,x=p?y:h*_,$=p?h*_:y,v=[8,8,1],S=n<=8?[4,1,1]:[4,4,1],T=[Math.ceil(x/v[0]/S[0]),Math.ceil($/v[1]/S[1]),Math.ceil(u/v[2]/S[2])];ue(\"verbose\",()=>`[conv2d_mm_webgpu] dispatch = ${T}`);let C=g?p&&m%4!==0?3:4:1,A=v[1]*S[1],P=v[0]*S[0],O=Math.max(v[0]*C,v[1]),U=n%A===0,G=o%P===0,q=i%O===0,K=g?[C,4,4]:[1,1,1],W=[{type:6,data:n},{type:6,data:o},{type:6,data:i},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];qe(t,W),W.push(...N(e[0].dims,e[1].dims));let Y=[\"rank\",\"rank\"];a&&(W.push(...N(e[2].dims)),Y.push(\"rank\")),W.push(...N(r));let se=X=>{let re=[{name:\"dim_a_outer\",type:\"i32\"},{name:\"dim_b_outer\",type:\"i32\"},{name:\"dim_inner\",type:\"i32\"},{name:\"pad\",type:\"i32\",length:2},{name:\"stride\",type:\"i32\",length:2},{name:\"dilation\",type:\"i32\",length:2}];je(t,re);let ee=g?4:1,ne=ye(e[0].dataType),ve=`\n fn setOutputAtIndex(flatIndex : i32, value : ${g?`vec4<${ne}>`:ne}) {\n result[flatIndex] = ${g?`vec4<${ne}>`:ne}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${g?`vec4<${ne}>`:ne}) {\n let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${g?\"/ 4\":\"\"}, value);\n }`,Be=E(\"x\",e[0].dataType,e[0].dims.length,C===3?1:C),$e=E(\"w\",e[1].dataType,e[1].dims.length,ee),de=[Be,$e],V=M(\"result\",e[0].dataType,r.length,ee);if(a){let j=E(\"bias\",e[2].dataType,e[2].dims.length,ee);de.push(j),ve+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${g?`vec4<${ne}>`:ne} {\n return bias[coords.${p?\"w\":\"y\"}${g?\"/ 4\":\"\"}];\n }`}return`\n ${Du(\"uniforms.result_strides\")}\n //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4,\n // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2,\n // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };\n ${X.registerUniforms(re).declareVariables(...de,V)}\n ${ve}\n ${of(p,U,G,q,a,t,K[0],K[1],K[2],ne)}\n ${g?go(S,v,ne,void 0,!p,O):bo(S,v,ne,void 0,!p,O,!1,void 0,l)}`};return{name:\"Conv2DMatMul\",shaderCache:{hint:`${t.cacheKey};${C};${g};${U};${G};${q};${A};${P};${O}`,inputDependencies:Y},getRunData:()=>({outputs:[{dims:d?d(r):r,dataType:e[0].dataType}],dispatchGroup:{x:T[0],y:T[1],z:T[2]},programUniforms:W}),getShaderSource:se}}});var af,Vu,rn,sf,Wu,uf,Lu,Gu,Hu=R(()=>{\"use strict\";te();Je();oe();ae();bt();Xr();af=e=>{let t=1;for(let r=0;rtypeof e==\"number\"?[e,e,e]:e,rn=(e,t)=>t<=1?e:e+(e-1)*(t-1),sf=(e,t,r,n=1)=>{let o=rn(t,n);return Math.floor((e[0]*(r-1)-r+o)/2)},Wu=(e,t,r,n,o)=>{o==null&&(o=sf(e,t[0],n[0]));let i=[0,0,0,r];for(let a=0;a<3;a++)e[a]+2*o>=t[a]&&(i[a]=Math.trunc((e[a]-t[a]+2*o)/n[a]+1));return i},uf=(e,t,r,n,o,i,a,l,d,p)=>{let m,u,h,_;if(e===\"VALID\"&&(e=0),typeof e==\"number\"){m={top:e,bottom:e,left:e,right:e,front:e,back:e};let y=Wu([t,r,n,1],[l,d,p],1,[o,i,a],e);u=y[0],h=y[1],_=y[2]}else if(Array.isArray(e)){if(!e.every((g,x,$)=>g===$[0]))throw Error(`Unsupported padding parameter: ${e}`);m={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let y=Wu([t,r,n,1],[l,d,p],1,[o,i,a],e[0]);u=y[0],h=y[1],_=y[2]}else if(e===\"SAME_UPPER\"){u=Math.ceil(t/o),h=Math.ceil(r/i),_=Math.ceil(n/a);let y=(u-1)*o+l-t,g=(h-1)*i+d-r,x=(_-1)*a+p-n,$=Math.floor(y/2),v=y-$,S=Math.floor(g/2),T=g-S,C=Math.floor(x/2),A=x-C;m={top:S,bottom:T,left:C,right:A,front:$,back:v}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:m,outDepth:u,outHeight:h,outWidth:_}},Lu=(e,t,r,n,o,i=!1,a=\"channelsLast\")=>{let l,d,p,m,u;if(a===\"channelsLast\")[l,d,p,m,u]=e;else if(a===\"channelsFirst\")[l,u,d,p,m]=e;else throw new Error(`Unknown dataFormat ${a}`);let[h,,_,y,g]=t,[x,$,v]=Vu(r),[S,T,C]=Vu(n),A=rn(_,S),P=rn(y,T),O=rn(g,C),{padInfo:U,outDepth:G,outHeight:q,outWidth:K}=uf(o,d,p,m,x,$,v,A,P,O),W=i?h*u:h,Y=[0,0,0,0,0];return a===\"channelsFirst\"?Y=[l,W,G,q,K]:a===\"channelsLast\"&&(Y=[l,G,q,K,W]),{batchSize:l,dataFormat:a,inDepth:d,inHeight:p,inWidth:m,inChannels:u,outDepth:G,outHeight:q,outWidth:K,outChannels:W,padInfo:U,strideDepth:x,strideHeight:$,strideWidth:v,filterDepth:_,filterHeight:y,filterWidth:g,effectiveFilterDepth:A,effectiveFilterHeight:P,effectiveFilterWidth:O,dilationDepth:S,dilationHeight:T,dilationWidth:C,inShape:e,outShape:Y,filterShape:t}},Gu=(e,t,r,n,o,i)=>{let a=i===\"channelsLast\",l=a?e[0].dims[3]:e[0].dims[1],d=!1,p=[64,1,1],m={x:r.map((v,S)=>S)},u=[Math.ceil(af(m.x.map(v=>r[v]))/p[0]),1,1];ue(\"verbose\",()=>`[conv3d_naive_webgpu] dispatch = ${u}`);let h=d?a&&l%4!==0?3:4:1,_=k.size(r),y=[{type:12,data:_},{type:12,data:n},{type:12,data:o},{type:12,data:t.strides},{type:12,data:t.dilations}];qe(t,y),y.push(...N(e[0].dims,e[1].dims));let g=[\"rank\",\"rank\"],x=e.length===3;x&&(y.push(...N(e[2].dims)),g.push(\"rank\")),y.push(...N(r));let $=v=>{let S=[{name:\"output_size\",type:\"u32\"},{name:\"filter_dims\",type:\"u32\",length:n.length},{name:\"pads\",type:\"u32\",length:o.length},{name:\"strides\",type:\"u32\",length:t.strides.length},{name:\"dilations\",type:\"u32\",length:t.dilations.length}];je(t,S);let T=d?4:1,C=ye(e[0].dataType),A=E(\"x\",e[0].dataType,e[0].dims.length,h===3?1:h),P=E(\"W\",e[1].dataType,e[1].dims.length,T),O=[A,P],U=M(\"result\",e[0].dataType,r.length,T),G=\"\";if(x){let W=E(\"bias\",e[2].dataType,e[2].dims.length,T);O.push(W),G+=`\n fn getBiasByOutputCoords(coords : array) -> ${d?`vec4<${C}>`:C} {\n return bias[${a?F(\"coords\",4,5):F(\"coords\",1,5)}${d?\"/ 4\":\"\"}];\n }`}let q=Pe(h,C),K=Fe(t,q,C);return`\n ${G}\n fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {\n let aIndices = array(d0, d1, d2, d3, d4);\n return ${A.getByIndices(\"aIndices\")};\n }\n fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {\n let aIndices = array(d0, d1, d2, d3, d4);\n return ${P.getByIndices(\"aIndices\")};\n }\n ${v.registerUniforms(S).declareVariables(...O,U)}\n ${v.mainStart()}\n ${v.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let coords = ${U.offsetToIndices(\"global_idx\")};\n let batch = ${F(\"coords\",0,A.rank)};\n let d2 = ${a?F(\"coords\",A.rank-1,A.rank):F(\"coords\",1,A.rank)};\n let xFRCCorner = vec3(${a?F(\"coords\",1,A.rank):F(\"coords\",2,A.rank)},\n ${a?F(\"coords\",2,A.rank):F(\"coords\",3,A.rank)},\n ${a?F(\"coords\",3,A.rank):F(\"coords\",4,A.rank)}) * uniforms.strides - uniforms.pads;\n let xFCorner = xFRCCorner.x;\n let xRCorner = xFRCCorner.y;\n let xCCorner = xFRCCorner.z;\n let xShapeY = ${a?F(\"uniforms.x_shape\",1,A.rank):F(\"uniforms.x_shape\",2,A.rank)};\n let xShapeZ = ${a?F(\"uniforms.x_shape\",2,A.rank):F(\"uniforms.x_shape\",3,A.rank)};\n let xShapeW = ${a?F(\"uniforms.x_shape\",3,A.rank):F(\"uniforms.x_shape\",4,A.rank)};\n let xShapeU = ${a?F(\"uniforms.x_shape\",4,A.rank):F(\"uniforms.x_shape\",1,A.rank)};\n let inputDepthNearestVec4 = (xShapeU / 4) * 4;\n let inputDepthVec4Remainder = xShapeU % 4;\n\n var value = 0.0;\n for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) {\n let xF = xFCorner + wF * uniforms.dilations[0];\n if (xF < 0 || xF >= xShapeY) {\n continue;\n }\n\n for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) {\n let xR = xRCorner + wR * uniforms.dilations[1];\n if (xR < 0 || xR >= xShapeZ) {\n continue;\n }\n\n for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) {\n let xC = xCCorner + wC * uniforms.dilations[2];\n if (xC < 0 || xC >= xShapeW) {\n continue;\n }\n\n for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) {\n ${a?`let 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 `:`let xValues = vec4(\n getX(batch, d1, xF, xR, xC),\n getX(batch, d1 + 1, xF, xR, xC),\n getX(batch, d1 + 2, xF, xR, xC),\n getX(batch, d1 + 3, xF, xR, xC));\n `}\n let wValues = vec4(\n getW(d2, d1, wF, wR, wC),\n getW(d2, d1 + 1, wF, wR, wC),\n getW(d2, d1 + 2, wF, wR, wC),\n getW(d2, d1 + 3, wF, wR, wC));\n value += dot(xValues, wValues);\n }\n if (inputDepthVec4Remainder == 1) {\n ${a?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4)\n * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC)\n * getW(d2, inputDepthNearestVec4, wF, wR, wC);`}\n } else if (inputDepthVec4Remainder == 2) {\n ${a?`let xValues = vec2(\n getX(batch, xF, xR, xC, inputDepthNearestVec4),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1));\n `:`let xValues = vec2(\n getX(batch, inputDepthNearestVec4, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC));\n `}\n let wValues = vec2(\n getW(d2, inputDepthNearestVec4, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC));\n value += dot(xValues, wValues);\n } else if (inputDepthVec4Remainder == 3) {\n ${a?`let xValues = vec3(\n getX(batch, xF, xR, xC, inputDepthNearestVec4),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2));\n `:`let xValues = vec3(\n getX(batch, inputDepthNearestVec4, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC));\n `}\n let wValues = vec3(\n getW(d2, inputDepthNearestVec4, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC));\n value += dot(xValues, wValues);\n }\n }\n }\n }\n ${x?\"value = value + getBiasByOutputCoords(coords)\":\"\"};\n ${K}\n result[global_idx] = f32(value);\n }`};return{name:\"Conv3DNaive\",shaderCache:{hint:`${t.cacheKey};${a};${h};${x}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:u[0],y:u[1],z:u[2]},programUniforms:y}),getShaderSource:$}}});var Fu,qu,ju=R(()=>{\"use strict\";te();oe();ae();bt();Fu=(e,t,r,n)=>{let o=e.length>2,i=o?\"value += b[output_channel];\":\"\",a=e[0].dims,l=e[1].dims,d=t.format===\"NHWC\",p=d?r[3]:r[1],m=p/t.group,u=d&&m>=4?me(p):1,h=k.size(r)/u,_=[{type:12,data:h},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:m}];qe(t,_),_.push(...N(a,[l[0],l[1],l[2],l[3]/u]));let y=o?[\"rank\",\"rank\",\"rank\"]:[\"rank\",\"rank\"];_.push(...N([r[0],r[1],r[2],r[3]/u]));let g=x=>{let $=M(\"output\",e[0].dataType,r.length,u),v=ye($.type.tensor),S=Fe(t,$.type.value,v),T=E(\"x\",e[0].dataType,a.length),C=E(\"w\",e[1].dataType,l.length,u),A=[T,C];o&&A.push(E(\"b\",e[2].dataType,e[2].dims,u));let P=[{name:\"output_size\",type:\"u32\"},{name:\"dilations\",type:\"u32\",length:t.dilations.length},{name:\"strides\",type:\"u32\",length:2},{name:\"pads\",type:\"u32\",length:2},{name:\"output_channels_per_group\",type:\"u32\"}];je(t,P);let O=d?`\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) {\n continue;\n }\n\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) {\n let input_channel = in_channel_offset + wInChannel;\n let xVal = ${T.get(\"batch\",\"xHeight\",\"xWidth\",\"input_channel\")};\n let wVal = ${C.get(\"wHeight\",\"wWidth\",\"wInChannel\",\"output_channel\")};\n value += xVal * wVal;\n }\n }\n }\n `:`\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {\n let input_channel = in_channel_offset + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) {\n continue;\n }\n\n let xVal = ${T.get(\"batch\",\"input_channel\",\"xHeight\",\"xWidth\")};\n let wVal = ${C.get(\"output_channel\",\"wInChannel\",\"wHeight\",\"wWidth\")};\n value += xVal * wVal;\n }\n }\n }\n `;return`\n ${x.registerUniforms(P).declareVariables(...A,$)}\n\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let outputIndices = ${$.offsetToIndices(\"global_idx\")};\n let batch: u32 = outputIndices[0];\n let output_channel: u32 = outputIndices[${d?3:1}];\n let xRCCorner: vec2 = vec2(outputIndices[${d?1:2}], outputIndices[${d?2:3}]) * uniforms.strides - uniforms.pads;\n let group_id: u32 = output_channel * ${u} / uniforms.output_channels_per_group;\n var in_channel_offset = group_id * uniforms.w_shape[${d?2:1}];\n\n var value: ${$.type.value} = ${$.type.value}(0);\n ${O}\n ${i}\n ${S}\n ${$.setByOffset(\"global_idx\",\"value\")}\n }`};return{name:\"GroupedConv\",shaderCache:{hint:`${t.cacheKey}_${u}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:_}),getShaderSource:g}},qu=(e,t,r,n)=>{let o=e.length>2,i=me(r[3]),a=me(r[2]),l=k.size(r)/i/a,d=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/i],p=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/i],m=[r[0],r[1],r[2],r[3]/i],u=[{type:12,data:l},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];qe(t,u),u.push(...N(d,p,m));let h=(a-1)*t.strides[1]+p[1],_=y=>{let g=M(\"output\",e[0].dataType,m.length,i),x=ye(g.type.tensor),$=Fe(t,g.type.value,x),v=E(\"x\",e[0].dataType,d.length,i),S=E(\"w\",e[1].dataType,p.length,i),T=[v,S];o&&T.push(E(\"b\",e[2].dataType,e[2].dims,i));let C=o?\"value += b[output_channel];\":\"\",A=[{name:\"output_size\",type:\"u32\"},{name:\"strides\",type:\"i32\",length:2},{name:\"pads\",type:\"i32\",length:2}];return je(t,A),`\n ${y.registerUniforms(A).declareVariables(...T,g)}\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let width0 = uniforms.output_shape[3];\n let output_channel = global_idx % width0;\n var index1 = global_idx / width0;\n let width1 = uniforms.output_shape[2] / ${a}u;\n let col = (index1 % width1) * ${a}u;\n index1 = index1 / width1;\n let row = index1 % uniforms.output_shape[1];\n let batch = index1 / uniforms.output_shape[1];\n\n let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads;\n\n var x_vals: array<${v.type.value}, ${h}>;\n var values: array<${g.type.value}, ${a}>;\n let input_channel = output_channel;\n // Use constant instead of uniform can give better performance for w's height/width.\n for (var w_height: u32 = 0u; w_height < ${p[0]}; w_height++) {\n let x_height = x_corner.x + i32(w_height);\n if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {\n for (var i = 0; i < ${h}; i++) {\n let x_width = x_corner.y + i;\n if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {\n x_vals[i] = ${v.get(\"batch\",\"u32(x_height)\",\"u32(x_width)\",\"input_channel\")};\n } else {\n x_vals[i] = ${v.type.value}(0);\n }\n }\n for (var w_width: u32 = 0u; w_width < ${p[1]}; w_width++) {\n let w_val = ${S.get(\"w_height\",\"w_width\",\"0\",\"output_channel\")};\n for (var i = 0u; i < ${a}u; i++) {\n values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);\n }\n }\n }\n }\n\n for (var i = 0u; i < ${a}u; i++) {\n var value = values[i];\n ${C}\n ${$}\n ${g.set(\"batch\",\"row\",\"col + i\",\"output_channel\",\"value\")};\n }\n }`};return{name:\"GroupedConv-Vectorize\",shaderCache:{hint:`${t.cacheKey};${i};${a};${h};${p[0]};${p[1]}`,inputDependencies:o?[\"rank\",\"rank\",\"type\"]:[\"rank\",\"rank\"]},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:_}}});var lf,yo,df,_o,wo,Ku,cf,pf,vo,Yu=R(()=>{\"use strict\";oe();Nu();Hu();tn();ju();bt();en();ut();lf=(e,t,r,n,o,i)=>{let a=e[0],l=e.slice(i?1:2,i?3:4),d=l.length,p=t[0],u=t.slice(2).map((y,g)=>y+(y-1)*(r[g]-1)),_=l.map((y,g)=>y+n[g]+n[g+d]).map((y,g)=>Math.floor((y-u[g]+o[g])/o[g]));return _.splice(0,0,a),_.splice(i?3:1,0,p),_},yo=[2,3,1,0],df=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error(\"Conv requires 2 or 3 inputs\");if(e[0].dims.length>5)throw new Error(\"greater than 5D is not supported\");if(e[0].dims.length!==e[1].dims.length)throw new Error(\"filter does not have same dimension as input\");let r=e[0].dims[t.format===\"NHWC\"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(r!==n)throw new Error(\"FILTER_IN_CHANNEL should be equal to DATA_CHANNEL\");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error(\"invalid bias\");let o=e[0].dims.length-2;if(t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error(\"invalid kernel shape\")},_o=(e,t)=>{let r=e.kernelShape.slice();r.length{let t=Qr(e),r=e.format,n=[\"NOTSET\",\"VALID\",\"SAME_UPPER\",\"SAME_LOWER\"][e.auto_pad],o=e.dilations,i=e.group,a=e.kernel_shape,l=e.pads,d=e.strides,p=e.w_is_const();return{autoPad:n,format:r,dilations:o,group:i,kernelShape:a,pads:l,strides:d,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},Ku=(e,t,r,n)=>{let o=r.format===\"NHWC\",i=lf(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,o);if(r.group!==1){let A=[t[0]];if(o){let O=e.kernelCustomData.wT??e.compute(Ee(t[1],yo),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=O),A.push(O)}else A.push(t[1]);t.length===3&&A.push(t[2]),!e.adapterInfo.isArchitecture(\"ampere\")&&o&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(qu(A,r,i,n),{inputs:A}):e.compute(Fu(A,r,i,n),{inputs:A});return}let a=t.length===3,l=t[0].dims[o?1:2],d=t[0].dims[o?2:3],p=t[0].dims[o?3:1],m=t[1].dims[2],u=t[1].dims[3],h=i[o?1:2],_=i[o?2:3],y=i[o?3:1],g=o&&m===l&&u===d&&r.pads[0]===0&&r.pads[1]===0;if(g||m===1&&u===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let A=i[0],P,O,U,G=[];if(o){let W=e.kernelCustomData.wT??e.compute(Ee(t[1],yo),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=W),g){let Y=l*d*p;P=t[0].reshape([1,A,Y]),O=W.reshape([1,Y,y]),U=[1,A,y]}else P=t[0].reshape([A,l*d,p]),O=W.reshape([1,p,y]),U=[A,h*_,y];G.push(P),G.push(O)}else P=t[0].reshape([A,p,l*d]),O=t[1].reshape([1,y,p]),U=[A,y,h*_],G.push(O),G.push(P);a&&G.push(t[2]);let q=U[2],K=G[0].dims[G[0].dims.length-1];q<8&&K<8?e.compute(Jr(G,r,i,U,o,n),{inputs:G}):e.compute(tr(G,r,i,U,o,n),{inputs:G});return}let x=!0,$=e.kernelCustomData.wT??e.compute(Ee(t[1],yo),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=$);let v=[t[0],$];a&&v.push(t[2]);let S=o?h*_:y,T=o?y:h*_,C=m*u*p;e.compute(Uu(v,r,i,S,T,C,a,x,n),{inputs:v})},cf=(e,t)=>{let r=t.format===\"NHWC\",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=[0,t.pads[0],0,t.pads[1]],i=[1].concat(t.strides),a=[1].concat(t.dilations),l=[1].concat(t.kernelShape),d=_o({...t,pads:o,strides:i,dilations:a,kernelShape:l},n);Ku(e,n,d,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},pf=(e,t,r)=>{let n=r.format===\"NHWC\"?\"channelsLast\":\"channelsFirst\",o=_o(r,t),i=r.autoPad===\"NOTSET\"?r.pads:r.autoPad,a=Lu(t[0].dims,t[1].dims,r.strides,r.dilations,i,!1,n);e.compute(Gu(t,o,a.outShape,[a.filterDepth,a.filterHeight,a.filterWidth],[a.padInfo.front,a.padInfo.top,a.padInfo.left],n))},vo=(e,t)=>{if(df(e.inputs,t),e.inputs[0].dims.length===3)cf(e,t);else if(e.inputs[0].dims.length===5)pf(e,e.inputs,t);else{let r=_o(t,e.inputs);Ku(e,e.inputs,r)}}});var Zu,Qu=R(()=>{\"use strict\";te();Je();oe();ae();Zu=(e,t,r)=>{let n=e.length>2,o=t.outputShape,i=t.format===\"NHWC\",a=t.group,l=e[1].dims,d=l[2]/a,p=l[3],m=i?me(p):1,u=k.size(o)/m,h=[Math.ceil(u/64),1,1];ue(\"verbose\",()=>`[conv2d_backprop_webgpu] dispatch = ${h}`);let _=[\"rank\",\"rank\"],y=[t.strides[0],t.strides[1]],g=[t.kernelShape[i?1:2],t.kernelShape[i?2:3]],x=[t.dilations[0],t.dilations[1]],$=[g[0]+(t.dilations[0]<=1?0:(t.kernelShape[i?1:2]-1)*(t.dilations[0]-1)),g[1]+(t.dilations[1]<=1?0:(t.kernelShape[i?2:3]-1)*(t.dilations[1]-1))],v=[$[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),$[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],S=[{type:12,data:u},{type:12,data:y},{type:12,data:g},{type:12,data:x},{type:12,data:$},{type:6,data:v},{type:12,data:d},{type:12,data:p},...N(e[0].dims,e[1].dims)];n&&(S.push(...N(e[2].dims)),_.push(\"rank\")),S.push(...N(o));let T=C=>{let A=[{name:\"output_size\",type:\"u32\"},{name:\"strides\",type:\"u32\",length:y.length},{name:\"filter_dims\",type:\"u32\",length:g.length},{name:\"dilations\",type:\"u32\",length:g.length},{name:\"effective_filter_dims\",type:\"u32\",length:$.length},{name:\"pads\",type:\"i32\",length:v.length},{name:\"input_channels_per_group\",type:\"u32\"},{name:\"output_channels_per_group\",type:\"u32\"}],P=ye(e[0].dataType),O=i?1:2,U=i?2:3,G=i?3:1,q=E(\"W\",e[1].dataType,e[1].dims.length,m),K=E(\"Dy\",e[0].dataType,e[0].dims.length),W=[K,q];n&&W.push(E(\"bias\",e[2].dataType,[o[G]].length,m));let Y=M(\"result\",e[0].dataType,o.length,m),se=`\n let outputIndices = ${Y.offsetToIndices(`global_idx * ${m}`)};\n let batch = ${Y.indicesGet(\"outputIndices\",0)};\n let d1 = ${Y.indicesGet(\"outputIndices\",G)};\n let r = ${Y.indicesGet(\"outputIndices\",O)};\n let c = ${Y.indicesGet(\"outputIndices\",U)};\n let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads;\n let dyRCorner = dyCorner.x;\n let dyCCorner = dyCorner.y;\n let groupId = d1 / uniforms.output_channels_per_group;\n let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;\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 var dotProd = ${Y.type.value}(0.0);\n for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {\n if (wR % uniforms.dilations.x != 0) {\n continue;\n }\n let dyR = (${P}(dyRCorner) + ${P}(wR)) / ${P}(uniforms.strides[0]);\n let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;\n if (dyR < 0.0 || dyR >= ${P}(uniforms.Dy_shape[${O}]) || fract(dyR) > 0.0 ||\n wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {\n if (wC % uniforms.dilations.y != 0) {\n continue;\n }\n let dyC = (${P}(dyCCorner) + ${P}(wC)) / ${P}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;\n if (dyC < 0.0 || dyC >= ${P}(uniforms.Dy_shape[${U}]) ||\n fract(dyC) > 0.0 || wCPerm < 0) {\n continue;\n }\n let idyC: u32 = u32(dyC);\n var inputChannel = groupId * uniforms.input_channels_per_group;\n for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) {\n let xValue = ${i?K.get(\"batch\",\"idyR\",\"idyC\",\"inputChannel\"):K.get(\"batch\",\"inputChannel\",\"idyR\",\"idyC\")};\n let w_offset = ${q.indicesToOffset(`${q.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)};\n let wValue = ${q.getByOffset(`w_offset / ${m}`)};\n dotProd = dotProd + xValue * wValue;\n inputChannel = inputChannel + 1;\n }\n }\n }\n let value = dotProd${n?` + bias[d1 / ${m}]`:\"\"};\n ${Y.setByOffset(\"global_idx\",\"value\")};\n `;return`\n ${C.registerUniforms(A).declareVariables(...W,Y)}\n ${C.mainStart()}\n ${C.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")};\n ${se}}`};return{name:\"ConvTranspose2D\",shaderCache:{hint:`${t.cacheKey};${m}`,inputDependencies:_},getRunData:()=>({dispatchGroup:{x:h[0],y:h[1],z:h[2]},outputs:[{dims:r?r(o):o,dataType:e[0].dataType}],programUniforms:S}),getShaderSource:T}}});var mf,ff,hf,Xu,Ju,gf,el,bf,tl,rl=R(()=>{\"use strict\";Qu();bt();ut();mf=(e,t,r,n,o,i)=>(e-1)*t+r+(n-1)*o+1-i,ff=(e,t,r,n,o)=>{let i=Math.floor(e/2);t===\"SAME_UPPER\"?(r[n]=i,r[o]=e-i):t===\"SAME_LOWER\"&&(r[n]=e-i,r[o]=i)},hf=(e,t,r,n,o,i,a,l,d,p)=>{let m=e.length-2,u=p.length===0;d.length{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((u,h)=>u*h,1)===0){r.length=0;for(let u=2;uu+h,0)===0){let u=t[0].dims.length-2;d=new Array(u).fill(1)}let p=e.strides.slice();if(p.reduce((u,h)=>u+h,0)===0){let u=t[0].dims.length-2;p=new Array(u).fill(1)}hf(l,r,d,e.autoPad,e.group,o,p,n,a,i);let m=Object.assign({},e);return Object.assign(m,{kernelShape:r,pads:o,outputPadding:a,outputShape:i,dilations:d,strides:p}),m},Ju=e=>{let t=Qr(e),r=e.format,n=[\"NOTSET\",\"VALID\",\"SAME_UPPER\",\"SAME_LOWER\"][typeof e.autoPad>\"u\"?0:e.autoPad],o=e.dilations,i=e.group,a=e.kernelShape,l=e.pads,d=e.strides,p=e.wIsConst(),m=e.outputPadding,u=e.outputShape;return{autoPad:n,format:r,dilations:o,group:i,kernelShape:a,outputPadding:m,outputShape:u,pads:l,strides:d,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},gf=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error(\"Conv requires 2 or 3 inputs\");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error(\"currently only support 2-dimensional conv\");if(e[0].dims.length!==e[1].dims.length)throw new Error(\"filter does not have same dimension as input\");let r=e[0].dims[t.format===\"NHWC\"?e[0].dims.length-1:1],n=e[1].dims[0];if(r!==n)throw new Error(\"FILTER_IN_CHANNEL should be equal to DATA_CHANNEL\");let o=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error(\"invalid bias\");let i=e[0].dims.length-2;if(t.dilations.reduce((m,u)=>m+u,0)>0&&t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.reduce((m,u)=>m+u,0)>0&&t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.reduce((m,u)=>m+u,0)>0&&t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.outputPadding.length!==i&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${i}D`);if(t.kernelShape.reduce((m,u)=>m+u,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error(\"invalid kernel shape\");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error(\"invalid output shape\")},el=(e,t,r,n)=>{let o=e.kernelCustomData.wT??e.compute(Ee(t[1],[2,3,0,1]),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let i=[t[0],o];t.length===3&&i.push(t[2]),e.compute(Zu(i,r,n),{inputs:i})},bf=(e,t)=>{let r=t.format===\"NHWC\",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=t.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let i=t.dilations;(i.length===0||i[0]===0)&&(i=[1]);let a=t.strides;(a.length===0||a[0]===0)&&(a=[1]);let l=t.pads;l.length===0&&(l=[0,0]),l=[0,l[0],0,l[1]],a=[1].concat(a),i=[1].concat(i),o=[1].concat(o);let d=Xu({...t,pads:l,strides:a,dilations:i,kernelShape:o},n);el(e,n,d,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},tl=(e,t)=>{if(gf(e.inputs,t),e.inputs[0].dims.length===3)bf(e,t);else{let r=Xu(t,e.inputs);el(e,e.inputs,r)}}});var yf,nl,ol,il=R(()=>{\"use strict\";te();oe();Se();ae();yf=(e,t,r,n)=>{let o=k.size(t),i=t.length,a=E(\"input\",e,i),l=M(\"output\",e,i),d=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),p=k.normalizeAxis(d,i),m=u=>{let h=` i32(${a.indicesGet(\"inputIndices\",\"uniforms.axis\")}) `,_=F(\"uniforms.input_shape\",\"uniforms.axis\",i),y=n.reverse?h+(n.exclusive?\" + 1\":\"\"):\"0\",g=n.reverse?_:h+(n.exclusive?\"\":\" + 1\");return`\n ${u.registerUniform(\"outputSize\",\"u32\").registerUniform(\"axis\",\"u32\").declareVariables(a,l)}\n ${u.mainStart()}\n ${u.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n var inputIndices = ${l.offsetToIndices(\"global_idx\")};\n var sum = ${l.type.value}(0);\n let first : i32 = ${y};\n let last : i32 = ${g};\n for (var i : i32 = first; i < last; i++) {\n ${a.indicesSet(\"inputIndices\",\"uniforms.axis\",\"u32(i)\")};\n sum = sum + ${a.getByIndices(\"inputIndices\")};\n }\n ${l.setByOffset(\"global_idx\",\"sum\")};\n }`};return{name:\"CumSum\",shaderCache:{hint:n.cacheKey,inputDependencies:[\"rank\"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:p},...N(t,t)]}),getShaderSource:m}},nl=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,o=e.inputs[1];e.compute(yf(n,r,o,t),{inputs:[0]})},ol=e=>{let t=e.exclusive===1,r=e.reverse===1;return J({exclusive:t,reverse:r})}});var _f,wf,vf,al,sl,ul=R(()=>{\"use strict\";te();oe();Se();ae();_f=e=>{if(!e||e.length!==1)throw new Error(\"DepthToSpace requires 1 input.\");if(e[0].dims.length!==4)throw new Error(\"DepthToSpace requires 4D input.\")},wf=(e,t,r,n)=>{let o=[];o.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} {\n var a: ${r.type.indices};`);for(let i=0;i{let r,n,o,i,a,l,d=t.format===\"NHWC\",p=t.blocksize,m=t.mode===\"DCR\";d?([r,n,o,i]=e.dims,a=m?[r,n,o,p,p,i/p**2]:[r,n,o,i/p**2,p,p],l=m?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,o,i]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],a=m?[r,p,p,i/p**2,n,o]:[r,i/p**2,p,p,n,o],l=m?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let u=e.reshape(a),h=u.dims.length,_=e.dataType,y=E(\"a\",_,h),g=M(\"output\",_,h),x=$=>`\n ${$.registerUniform(\"output_size\",\"u32\").declareVariables(y,g)}\n\n ${wf(l,h,y,g)}\n\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let indices = ${g.offsetToIndices(\"global_idx\")};\n let aIndices = perm(indices);\n\n ${g.setByOffset(\"global_idx\",y.getByIndices(\"aIndices\"))}\n }`;return{name:\"DepthToSpace\",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:[\"rank\"]},getRunData:$=>{let v=d?[r,n*p,o*p,i/p**2]:[r,i/p**2,n*p,o*p],S=k.size(v),T=u.dims,C=k.sortBasedOnPerm(T,l);return{outputs:[{dims:v,dataType:$[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...N(T,C)]}},getShaderSource:x}},al=(e,t)=>{_f(e.inputs),e.compute(vf(e.inputs[0],t))},sl=e=>J({blocksize:e.blocksize,mode:e.mode,format:e.format})});var $o,nn,ll,$f,xf,xo,So,dl,Sf,cl,pl,ml=R(()=>{\"use strict\";te();oe();Se();ae();$o=\"[a-zA-Z]|\\\\.\\\\.\\\\.\",nn=\"(\"+$o+\")+\",ll=\"^\"+nn+\"$\",$f=\"(\"+nn+\",)*\"+nn,xf=\"^\"+$f+\"$\",xo=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,r){let n=this.symbolToIndices.get(t);n===void 0?n=[r]:n.push(r),this.symbolToIndices.set(t,n)}},So=class{constructor(t,r){this.equation=r;this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[n,o]=r.includes(\"->\")?r.split(\"->\",2):[r,\"\"];if(!n.match(RegExp(xf)))throw new Error(\"Invalid LHS term\");if(n.split(\",\").forEach((l,d)=>{let p=t[d].dims.slice();if(!l.match(RegExp(ll)))throw new Error(\"Invalid LHS term\");let m=this.processTerm(l,!0,p,d);this.lhs.push(m)}),o===\"\")o+=[...this.symbolToInfo.entries()].filter(([l,d])=>d.count===1||l===\"...\").map(([l])=>l).join(\"\");else if(!o.match(RegExp(nn)))throw new Error(\"Invalid RHS\");o.match(RegExp($o,\"g\"))?.forEach(l=>{if(l===\"...\")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let d=this.symbolToInfo.get(l);if(d===void 0)throw new Error(\"Invalid RHS symbol\");this.outputDims.push(d.dimValue)}}),this.rhs=this.processTerm(o,!1,this.outputDims)}addSymbol(t,r,n){let o=this.symbolToInfo.get(t);if(o!==void 0){if(o.dimValue!==r&&o.count!==1)throw new Error(\"Dimension mismatch\");o.count++,o.inputIndices.push(n)}else o={count:1,dimValue:r,inputIndices:[n]};this.symbolToInfo.set(t,o)}processTerm(t,r,n,o=-1){let i=n.length,a=!1,l=[],d=0;if(!t.match(RegExp(ll))&&!r&&t!==\"\")throw new Error(\"Invalid LHS term\");let p=t.match(RegExp($o,\"g\")),m=new xo(o);return p?.forEach((u,h)=>{if(u===\"...\"){if(a)throw new Error(\"Only one ellipsis is allowed per input term\");a=!0;let _=i-p.length+1;if(_<0)throw new Error(\"Ellipsis out of bounds\");if(l=n.slice(d,d+_),this.hasEllipsis){if(this.ellipsisDims.length!==l.length||this.ellipsisDims.toString()!==l.toString())throw new Error(\"Ellipsis dimensions mismatch\")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=l;else throw new Error(\"Ellipsis must be specified in the LHS\");for(let y=0;ye+\"_max\",Sf=(e,t,r,n)=>{let i=e.map(m=>m.length).map((m,u)=>E(`input${u}`,t,m)),a=k.size(n),l=M(\"output\",t,n.length),d=[...r.symbolToInfo.keys()].filter(m=>!r.rhs.symbolToIndices.has(m)),p=m=>{let u=[],h=\"var prod = 1.0;\",_=\"var sum = 0.0;\",y=\"sum += prod;\",g=[],x=[],$=[],v=[],S=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((C,A)=>{if(r.rhs.symbolToIndices.has(A)){let P=r.rhs.symbolToIndices.get(A)?.[0];P!==void 0&&r.lhs.forEach((O,U)=>{if(C.inputIndices.includes(U)){let G=O.symbolToIndices.get(A);if(G===void 0)throw new Error(\"Invalid symbol error\");G.forEach(q=>{u.push(`${i[U].indicesSet(`input${U}Indices`,q,l.indicesGet(\"outputIndices\",P))}`)})}})}else r.lhs.forEach((P,O)=>{if(C.inputIndices.includes(O)){let U=P.symbolToIndices.get(A);if(U===void 0)throw new Error(\"Invalid symbol error\");U.forEach(G=>{g.push(`${i[O].indicesSet(`input${O}Indices`,G,`${A}`)}`)}),v.push(`prod *= ${i[O].getByIndices(`input${O}Indices`)};`)}}),x.push(`for(var ${A}: u32 = 0; ${A} < uniforms.${dl(A)}; ${A}++) {`),$.push(\"}\")});let T=S?[...u,`let sum = ${i.map((C,A)=>C.getByIndices(`input${A}Indices`)).join(\" * \")};`]:[...u,_,...x,...g,h,...v,y,...$];return`\n ${m.registerUniforms(d.map(C=>({name:`${dl(C)}`,type:\"u32\"}))).registerUniform(\"outputSize\",\"u32\").declareVariables(...i,l)}\n\n ${m.mainStart()}\n ${m.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n var outputIndices = ${l.offsetToIndices(\"global_idx\")};\n ${i.map((C,A)=>`var input${A}Indices: ${i[A].type.indices};`).join(`\n`)}\n ${T.join(`\n`)};\n ${l.setByOffset(\"global_idx\",\"sum\")};\n }`};return{name:\"Einsum\",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>\"rank\")},getRunData:()=>{let m=d.filter(h=>r.symbolToInfo.has(h)).map(h=>({type:12,data:r.symbolToInfo.get(h)?.dimValue||0}));m.push({type:12,data:a});let u=e.map((h,_)=>[...N(h)]).reduce((h,_)=>h.concat(_),m);return u.push(...N(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:u}},getShaderSource:p}},cl=(e,t)=>{let r=new So(e.inputs,t.equation),n=r.outputDims,o=e.inputs.map((i,a)=>i.dims);e.compute(Sf(o,e.inputs[0].dataType,r,n))},pl=e=>{let t=e.equation.replace(/\\s+/g,\"\");return J({equation:t})}});var Tf,fl,If,Cf,hl,gl=R(()=>{\"use strict\";te();oe();ae();Tf=e=>{if(!e||e.length!==2)throw new Error(\"Expand requires 2 input.\");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=r.length{let r=e.length-t.length,n=[];for(let o=0;oe.length>t.length?fl(e,t):fl(t,e),Cf=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=If(t,r),o=e[0].dataType,i=o===9||k.size(t)===1,a=o===9||t.length>0&&t[t.length-1]%4===0?4:1,l=i||n.length>0&&n[n.length-1]%4===0?4:1,d=Math.ceil(k.size(n)/l),p=u=>{let h=E(\"input\",o,t.length,a),_=M(\"output\",o,n.length,l),y;if(o===9){let g=(x,$,v=\"\")=>`\n let outputIndices${$} = ${_.offsetToIndices(`outputOffset + ${$}u`)};\n let offset${$} = ${h.broadcastedIndicesToOffset(`outputIndices${$}`,_)};\n let index${$} = offset${$} / 4u;\n let component${$} = offset${$} % 4u;\n ${x}[${$}] = ${v}(${h.getByOffset(`index${$}`)}[component${$}]);\n `;y=`\n let outputOffset = global_idx * ${l};\n var data = vec4(0);\n ${g(\"data\",0,\"u32\")}\n ${g(\"data\",1,\"u32\")}\n ${g(\"data\",2,\"u32\")}\n ${g(\"data\",3,\"u32\")}\n ${_.setByOffset(\"global_idx\",\"data\")}\n }`}else y=`\n let outputIndices = ${_.offsetToIndices(`global_idx * ${l}`)};\n let inputOffset = ${h.broadcastedIndicesToOffset(\"outputIndices\",_)};\n let data = ${_.type.value}(${h.getByOffset(`inputOffset / ${a}`)});\n ${_.setByOffset(\"global_idx\",\"data\")}\n }`;return`\n ${u.registerUniform(\"vec_size\",\"u32\").declareVariables(h,_)}\n ${u.mainStart()}\n ${u.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.vec_size\")}\n ${y}`},m=[{type:12,data:d},...N(t,n)];return{name:\"Expand\",shaderCache:{hint:`${n.length};${a}${l}`,inputDependencies:[\"rank\"]},getShaderSource:p,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:m})}},hl=e=>{Tf(e.inputs),e.compute(Cf(e.inputs),{inputs:[0]})}});var Af,bl,yl=R(()=>{\"use strict\";te();oe();ae();Zr();Af=e=>{let t=e[0].dataType,r=k.size(e[0].dims),n=k.size(e[1].dims),o=n%4===0,i=a=>{let l=E(\"x\",t,[1],4),d=E(\"bias\",t,[1],4),p=M(\"y\",t,[1],4),m=[{name:\"output_vec_size\",type:\"u32\"},{name:\"bias_size\",type:\"u32\"}],u=_=>`\n let bias${_}_offset: u32 = (global_idx * 4 + ${_}) % uniforms.bias_size;\n let bias${_} = ${d.getByOffset(`bias${_}_offset / 4`)}[bias${_}_offset % 4];`,h=o?`\n let bias = ${d.getByOffset(\"global_idx % (uniforms.bias_size / 4)\")};`:`${u(0)}${u(1)}${u(2)}${u(3)}\n let bias = ${l.type.value}(bias0, bias1, bias2, bias3);`;return`${a.registerUniforms(m).declareVariables(l,d,p)}\n\n ${fo(ke(t))}\n\n ${a.mainStart(Ct)}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_vec_size\")}\n\n let x = ${l.getByOffset(\"global_idx\")};\n ${h}\n let x_in = x + bias;\n ${p.setByOffset(\"global_idx\",ho(\"x_in\"))}\n }`};return{name:\"FastGeluWithBias\",shaderCache:{hint:`${o}`,inputDependencies:[\"type\",\"type\"]},getShaderSource:i,getRunData:a=>({outputs:[{dims:a[0].dims,dataType:a[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/Ct/4)}})}},bl=e=>{e.inputs.length<2||k.size(e.inputs[1].dims)===0?mu(e):e.compute(Af(e.inputs))}});var kf,Ef,_l,wl,vl=R(()=>{\"use strict\";te();oe();Se();ae();kf=e=>{if(!e||e.length!==2)throw new Error(\"Gather requires 2 inputs.\")},Ef=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r.length,i=k.normalizeAxis(t.axis,o),a=r.slice(0);a.splice(i,1,...n);let l=r[i],d=e[0].dataType===9?4:1,p=Math.ceil(k.size(a)/d),m=[{type:12,data:p},{type:6,data:l},{type:12,data:i},...N(e[0].dims,e[1].dims,a)],u=h=>{let _=E(\"data\",e[0].dataType,e[0].dims.length,d),y=E(\"inputIndices\",e[1].dataType,e[1].dims.length),g=M(\"output\",e[0].dataType,a.length,d),x=v=>{let S=n.length,T=`var indicesIndices${v} = ${y.type.indices}(0);`;for(let C=0;C1?`indicesIndices${v}[${C}]`:`indicesIndices${v}`} = ${a.length>1?`outputIndices${v}[uniforms.axis + ${C}]`:`outputIndices${v}`};`;T+=`\n var idx${v} = ${y.getByIndices(`indicesIndices${v}`)};\n if (idx${v} < 0) {\n idx${v} = idx${v} + uniforms.axisDimLimit;\n }\n var dataIndices${v} : ${_.type.indices};\n `;for(let C=0,A=0;C1?`dataIndices${v}[${C}]`:`dataIndices${v}`} = u32(idx${v});`,A+=S):(T+=`${o>1?`dataIndices${v}[${C}]`:`dataIndices${v}`} = ${a.length>1?`outputIndices${v}[${A}]`:`outputIndices${v}`};`,A++);return T},$;if(e[0].dataType===9){let v=(S,T,C=\"\")=>`\n let outputIndices${T} = ${g.offsetToIndices(`outputOffset + ${T}u`)};\n ${x(T)};\n let offset${T} = ${_.indicesToOffset(`dataIndices${T}`)};\n let index${T} = offset${T} / 4u;\n let component${T} = offset${T} % 4u;\n ${S}[${T}] = ${C}(${_.getByOffset(`index${T}`)}[component${T}]);\n `;$=`\n let outputOffset = global_idx * ${d};\n var value = vec4(0);\n ${v(\"value\",0,\"u32\")}\n ${v(\"value\",1,\"u32\")}\n ${v(\"value\",2,\"u32\")}\n ${v(\"value\",3,\"u32\")}\n ${g.setByOffset(\"global_idx\",\"value\")}\n `}else $=`\n let outputIndices = ${g.offsetToIndices(\"global_idx\")};\n ${x(\"\")};\n let value = ${_.getByIndices(\"dataIndices\")};\n ${g.setByOffset(\"global_idx\",\"value\")};\n `;return`\n ${h.registerUniform(\"outputSize\",\"u32\").registerUniform(\"axisDimLimit\",\"i32\").registerUniform(\"axis\",\"u32\").declareVariables(_,y,g)}\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n ${$}\n }`};return{name:\"Gather\",shaderCache:{hint:t.cacheKey,inputDependencies:[\"rank\",\"rank\"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:m}),getShaderSource:u}},_l=e=>J({axis:e.axis}),wl=(e,t)=>{let r=e.inputs;kf(r),e.compute(Ef(e.inputs,t))}});var Pf,zf,$l,xl,Sl=R(()=>{\"use strict\";te();oe();Se();ae();Pf=(e,t)=>{if(e.length<3||e.length>4)throw new Error(\"GatherBlockQuantized requires 3 or 4 inputs.\");let r=k.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,o=e[0],i=e[2],a=e.length===4?e[3]:void 0;if(i.dims.length!==o.dims.length||!o.dims.map((l,d)=>d===r?Math.ceil(l/n)===i.dims[d]:l===i.dims[d]).reduce((l,d)=>l&&d,!0))throw new Error(\"Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.\");if(a){if(a.dataType!==o.dataType)throw new Error(\"Zero point must have the same data type as the input tensor.\");if(a.dims.length!==i.dims.length||!a.dims.map((l,d)=>l===i.dims[d]).reduce((l,d)=>l&&d,!0))throw new Error(\"Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.\")}},zf=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r.length,i=k.normalizeAxis(t.gatherAxis,o),a=k.normalizeAxis(t.quantizeAxis,o),l=r.slice(0);l.splice(i,1,...n);let d=k.size(l),p=e[2].dataType,u=e[0].dataType===22,h=[{type:12,data:d},{type:12,data:a},{type:12,data:i},{type:12,data:t.blockSize},...N(...e.map((y,g)=>y.dims),l)],_=y=>{let g=E(\"data\",e[0].dataType,e[0].dims.length),x=E(\"inputIndices\",e[1].dataType,e[1].dims.length),$=E(\"scales\",e[2].dataType,e[2].dims.length),v=e.length>3?E(\"zeroPoint\",e[3].dataType,e[3].dims.length):void 0,S=M(\"output\",p,l.length),T=[g,x,$];v&&T.push(v);let C=[{name:\"output_size\",type:\"u32\"},{name:\"quantize_axis\",type:\"u32\"},{name:\"gather_axis\",type:\"u32\"},{name:\"block_size\",type:\"u32\"}];return`\n ${y.registerUniforms(C).declareVariables(...T,S)}\n ${y.mainStart()}\n let output_indices = ${S.offsetToIndices(\"global_idx\")};\n var indices_indices = ${x.type.indices}(0);\n ${(()=>n.length>1?`\n for (var i: u32 = 0; i < ${n.length}; i++) {\n let index = ${S.indicesGet(\"output_indices\",\"uniforms.gather_axis + i\")};\n ${x.indicesSet(\"indices_indices\",\"i\",\"index\")};\n }`:`indices_indices = ${S.indicesGet(\"output_indices\",\"uniforms.gather_axis\")};`)()};\n var data_indices = ${g.type.indices}(0);\n for (var i: u32 = 0; i < uniforms.gather_axis; i++) {\n let index = ${S.indicesGet(\"output_indices\",\"i\")};\n ${g.indicesSet(\"data_indices\",\"i\",\"index\")};\n }\n var index_from_indices = ${x.getByIndices(\"indices_indices\")};\n if (index_from_indices < 0) {\n index_from_indices += ${r[i]};\n }\n ${g.indicesSet(\"data_indices\",\"uniforms.gather_axis\",\"u32(index_from_indices)\")};\n for (var i = uniforms.gather_axis + 1; i < ${l.length}; i++) {\n let index = ${S.indicesGet(\"output_indices\",`i + ${n.length} - 1`)};\n ${g.indicesSet(\"data_indices\",\"i\",\"index\")};\n }\n let data_offset = ${g.indicesToOffset(\"data_indices\")};\n let data_index = data_offset % 8;\n // Convert 4-bit packed data to 8-bit packed data.\n let packed_4bit_quantized_data = ${g.getByOffset(\"data_offset / 8\")};\n let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f;\n let quantized_data_vec = ${u?\"unpack4xI8\":\"unpack4xU8\"}(u32(packed_8bit_quantized_data));\n let quantized_data = quantized_data_vec[data_index / 2];\n var scale_indices = data_indices;\n let quantize_axis_index = ${$.indicesGet(\"data_indices\",\"uniforms.quantize_axis\")} / uniforms.block_size;\n ${$.indicesSet(\"scale_indices\",\"uniforms.quantize_axis\",\"quantize_axis_index\")};\n var scale = ${$.getByIndices(\"scale_indices\")};\n ${(()=>v?`\n let zero_point_indices = scale_indices;\n let zero_point_offset = ${v.indicesToOffset(\"zero_point_indices\")};\n let zero_point_index = zero_point_offset % 8;\n let packed_4bit_zero_points = ${v.getByOffset(\"zero_point_offset / 8\")};\n let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f;\n let zero_point_vec = ${u?\"unpack4xI8\":\"unpack4xU8\"}(u32(packed_8bit_zero_points));\n let zero_point = zero_point_vec[zero_point_index / 2];`:\"var zero_point = 0\")()};\n let dequantized_data = ${ke(p)}(quantized_data - zero_point) * scale;\n ${S.setByOffset(\"global_idx\",\"dequantized_data\")};\n }`};return{name:\"GatherBlockQuantized\",shaderCache:{hint:`${t.cacheKey};${e.filter((y,g)=>g!==1).map(y=>y.dims.join(\"_\")).join(\";\")}`,inputDependencies:Array.from({length:e.length},(y,g)=>\"rank\")},getRunData:()=>({outputs:[{dims:l,dataType:p}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:h}),getShaderSource:_}},$l=(e,t)=>{let r=e.inputs;Pf(r,t),e.compute(zf(e.inputs,t))},xl=e=>J({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})});var Of,Bf,Tl,Il,Cl=R(()=>{\"use strict\";te();oe();Se();ae();Of=e=>{if(!e||e.length!==2)throw new Error(\"GatherElements requires 2 inputs.\");if(e[0].dims.length<1)throw new Error(\"GatherElements requires that the data input be rank >= 1.\");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and\n indices input tensors be of same rank.`)},Bf=(e,t)=>{let r=e[0].dims,n=e[0].dataType,o=r.length,i=e[1].dims,a=e[1].dataType,l=k.normalizeAxis(t.axis,o),d=r[l],p=i.slice(0),m=k.size(p),u=E(\"input\",n,o),h=E(\"indicesInput\",a,i.length),_=M(\"output\",n,p.length),y=[{type:12,data:m},{type:6,data:d},{type:12,data:l}];return y.push(...N(r,i,p)),{name:\"GatherElements\",shaderCache:{inputDependencies:[\"rank\",\"rank\"]},getRunData:()=>({outputs:[{dims:p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:y}),getShaderSource:$=>`\n ${$.registerUniform(\"outputSize\",\"u32\").registerUniform(\"axisDimLimit\",\"i32\").registerUniform(\"axis\",\"u32\").declareVariables(u,h,_)}\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n\n let outputIndices = ${_.offsetToIndices(\"global_idx\")};\n\n var idx = ${h.getByOffset(\"global_idx\")};\n if (idx < 0) {\n idx = idx + uniforms.axisDimLimit;\n }\n var inputIndices = ${u.type.indices}(outputIndices);\n ${u.indicesSet(\"inputIndices\",\"uniforms.axis\",\"u32(idx)\")};\n let value = ${u.getByIndices(\"inputIndices\")};\n\n ${_.setByOffset(\"global_idx\",\"value\")};\n }`}},Tl=e=>J({axis:e.axis}),Il=(e,t)=>{let r=e.inputs;Of(r),e.compute(Bf(e.inputs,t))}});var Df,Mf,Al,kl,El=R(()=>{\"use strict\";te();oe();ae();Df=e=>{if(!e)throw new Error(\"Input is missing\");if(e.length<2||e.length>3)throw new Error(\"Invaid input number.\");if(e.length===3&&e[2].dims.length>2)throw new Error(\"Invalid input shape of C\");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error(\"Input types are mismatched\")},Mf=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[o,i,a]=Gr.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),l=[o,i];if(!l)throw new Error(\"Can't use gemm on the given tensors\");let d=16,p=Math.ceil(i/d),m=Math.ceil(o/d),u=!0,h=k.size(l),_=[{type:12,data:u?p:h},{type:12,data:o},{type:12,data:i},{type:12,data:a},{type:1,data:t.alpha},{type:1,data:t.beta}],y=[\"type\",\"type\"];e.length===3&&(_.push(...N(e[2].dims)),y.push(\"rank\")),_.push(...N(l));let g=$=>{let v=\"\";t.transA&&t.transB?v=\"value += a[k * uniforms.M + m] * b[n * uniforms.K + k];\":t.transA&&!t.transB?v=\"value += a[k * uniforms.M + m] * b[k * uniforms.N + n];\":!t.transA&&t.transB?v=\"value += a[m * uniforms.K + k] * b[n * uniforms.K + k];\":!t.transA&&!t.transB&&(v=\"value += a[m * uniforms.K + k] * b[k * uniforms.N + n];\");let S=t.alpha===1?\"\":\"value *= uniforms.alpha;\",T=E(\"a\",e[0].dataType,e[0].dims),C=E(\"b\",e[1].dataType,e[1].dims),A=T.type.value,P=null,O=[T,C];e.length===3&&(P=E(\"c\",e[2].dataType,e[2].dims.length),O.push(P));let U=M(\"output\",e[0].dataType,l.length);O.push(U);let G=[{name:\"output_size\",type:\"u32\"},{name:\"M\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"alpha\",type:\"f32\"},{name:\"beta\",type:\"f32\"}];return`\n ${$.registerUniforms(G).declareVariables(...O)}\n\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let m = global_idx / uniforms.N;\n let n = global_idx % uniforms.N;\n\n var value = ${A}(0);\n for (var k: u32 = 0u; k < uniforms.K; k++) {\n ${v}\n }\n\n ${S}\n ${(()=>P!=null?`let cOffset = ${P.broadcastedIndicesToOffset(\"vec2(m, n)\",U)}; value += ${A}(uniforms.beta) * ${P.getByOffset(\"cOffset\")};`:\"\")()}\n output[global_idx] = value;\n }`},x=$=>{let v=E(\"a\",e[0].dataType,e[0].dims),S=E(\"b\",e[1].dataType,e[1].dims),T=null,C=[v,S];e.length===3&&(T=E(\"c\",e[2].dataType,e[2].dims.length),C.push(T));let A=M(\"output\",e[0].dataType,l.length);C.push(A);let P=[{name:\"num_tile_n\",type:\"u32\"},{name:\"M\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"alpha\",type:\"f32\"},{name:\"beta\",type:\"f32\"}],O=\"\",U=\"\";t.transA&&t.transB?(U=`\n var col = tile_row_start + local_id.x;\n var row = k_start + local_id.y;\n if (col < uniforms.M && row < uniforms.K) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${v.type.value}(0);\n }\n\n col = k_start + local_id.x;\n row = tile_col_start + local_id.y;\n if (col < uniforms.K && row < uniforms.N) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${S.type.value}(0);\n }\n `,O=\"value += tile_a[k][local_id.y] * tile_b[local_id.x][k];\"):t.transA&&!t.transB?(U=`\n var col = tile_row_start + local_id.x;\n var row = k_start + local_id.y;\n if (col < uniforms.M && row < uniforms.K) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${v.type.value}(0);\n }\n\n col = tile_col_start + local_id.x;\n row = k_start + local_id.y;\n if (col < uniforms.N && row < uniforms.K) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${S.type.value}(0);\n }\n `,O=\"value += tile_a[k][local_id.y] * tile_b[k][local_id.x];\"):!t.transA&&t.transB?(U=`\n var col = k_start + local_id.x;\n var row = tile_row_start + local_id.y;\n if (col < uniforms.K && row < uniforms.M) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${v.type.value}(0);\n }\n\n col = k_start + local_id.x;\n row = tile_col_start + local_id.y;\n if (col < uniforms.K && row < uniforms.N) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${S.type.value}(0);\n }\n `,O=\"value += tile_a[local_id.y][k] * tile_b[local_id.x][k];\"):!t.transA&&!t.transB&&(U=`\n var col = k_start + local_id.x;\n var row = tile_row_start + local_id.y;\n if (col < uniforms.K && row < uniforms.M) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${v.type.value}(0);\n }\n\n col = tile_col_start + local_id.x;\n row = k_start + local_id.y;\n if (col < uniforms.N && row < uniforms.K) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${S.type.value}(0);\n }\n `,O=\"value += tile_a[local_id.y][k] * tile_b[k][local_id.x];\");let G=t.alpha===1?\"\":\"value *= uniforms.alpha;\";return`\n ${$.registerUniforms(P).declareVariables(...C)}\n var tile_a: array, ${d}>;\n var tile_b: array, ${d}>;\n ${$.mainStart([d,d,1])}\n let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${d};\n let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${d};\n let num_tiles = (uniforms.K - 1) / ${d} + 1;\n var k_start = 0u;\n var value = ${A.type.value}(0);\n for (var t: u32 = 0u; t < num_tiles; t++) {\n ${U}\n k_start = k_start + ${d};\n workgroupBarrier();\n\n for (var k: u32 = 0u; k < ${d}; k++) {\n ${O}\n }\n workgroupBarrier();\n }\n\n ${G}\n let m = tile_row_start + local_id.y;\n let n = tile_col_start + local_id.x;\n ${(()=>T!=null?`let cOffset = ${T.broadcastedIndicesToOffset(\"vec2(m, n)\",A)}; value += ${A.type.value}(uniforms.beta) * ${T.getByOffset(\"cOffset\")};`:\"\")()}\n if (m < uniforms.M && n < uniforms.N) {\n output[m * uniforms.N + n] = value;\n }\n }`};return u?{name:\"GemmShared\",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:p*m},programUniforms:_}),getShaderSource:x}:{name:\"Gemm\",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:_}),getShaderSource:g}},Al=e=>{let t=e.transA,r=e.transB,n=e.alpha,o=e.beta;return{transA:t,transB:r,alpha:n,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},kl=(e,t)=>{Df(e.inputs),e.compute(Mf(e.inputs,t))}});var lt,yt,Ut,Nt,Rf,Uf,Nf,Vf,Wf,Lf,Gf,Hf,Pl,zl,Ol=R(()=>{\"use strict\";te();oe();Se();ae();[lt,yt,Ut,Nt]=[0,1,2,3],Rf=e=>{if(e[0].dims.length!==4)throw new Error(\"only 4-D tensor is supported.\");if(e[0].dims.length!==e[1].dims.length)throw new Error(\"input dimensions must be equal to grid dimensions\");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error(\"grid batch size must match input batch size\")},Uf=`\n fn gs_get_cubic_coeffs(x: f32) -> vec4 {\n let cubic_alpha = -0.75f;\n let x_abs = abs(x);\n var coeffs: vec4;\n coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha);\n coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1);\n coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1);\n coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha);\n return coeffs;\n }\n`,Nf=e=>`\n fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} {\n var v: vec4;\n var coeffs = gs_get_cubic_coeffs(x);\n for (var i = 0; i < 4; i++) {\n v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3];\n }\n coeffs = gs_get_cubic_coeffs(y);\n let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]);\n return pixel;\n }\n`,Vf=e=>`\n fn gs_denormalize(n: f32, length: i32) -> f32 {\n ${e.alignCorners===0?`\n // alignCorners: false => [-1, 1] to [-0.5, length - 0.5]\n return ((n + 1.0) * f32(length) - 1.0) / 2.0;\n `:`\n // alignCorners: true => [-1, 1] to [0, length - 1]\n return (n + 1.0) / 2.0 * (f32(length - 1));\n `}\n }\n`,Wf=e=>`\n ${e.paddingMode===\"reflection\"?`\n fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 {\n var dx = 0.0;\n var fx = f32(x);\n let range = x_max - x_min;\n if (fx < x_min) {\n dx = x_min - fx;\n let n = u32(dx / range);\n let r = dx - f32(n) * range;\n if (n % 2 == 0) {\n fx = x_min + r;\n } else {\n fx = x_max - r;\n }\n } else if (fx > x_max) {\n dx = fx - x_max;\n let n = u32(dx / range);\n let r = dx - f32(n) * range;\n if (n % 2 == 0) {\n fx = x_max - r;\n } else {\n fx = x_min + r;\n }\n }\n return u32(fx);\n }`:\"\"}\n`,Lf=(e,t,r)=>`\n fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} {\n var pixel = ${t}(0);\n var indices = vec4(0);\n indices[${lt}] = batch;\n indices[${yt}] = channel;`+(()=>{switch(r.paddingMode){case\"zeros\":return`\n if (r >= 0 && r < H && c >=0 && c < W) {\n indices[${Ut}] = u32(r);\n indices[${Nt}] = u32(c);\n }\n `;case\"border\":return`\n indices[${Ut}] = u32(clamp(r, 0, H - 1));\n indices[${Nt}] = u32(clamp(c, 0, W - 1));\n `;case\"reflection\":return`\n indices[${Ut}] = gs_reflect(r, border[1], border[3]);\n indices[${Nt}] = gs_reflect(c, border[0], border[2]);\n `;default:throw new Error(`padding mode ${r.paddingMode} is not supported`)}})()+`\n return ${e.getByIndices(\"indices\")};\n }\n`,Gf=(e,t,r)=>(()=>{switch(r.mode){case\"nearest\":return`\n let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${lt}], indices[${yt}], border);\n `;case\"bilinear\":return`\n let x1 = i32(floor(x));\n let y1 = i32(floor(y));\n let x2 = x1 + 1;\n let y2 = y1 + 1;\n\n let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${lt}], indices[${yt}], border);\n let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${lt}], indices[${yt}], border);\n let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${lt}], indices[${yt}], border);\n let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${lt}], indices[${yt}], border);\n\n let dx2 = ${t}(f32(x2) - x);\n let dx1 = ${t}(x - f32(x1));\n let dy2 = ${t}(f32(y2) - y);\n let dy1 = ${t}(y - f32(y1));\n let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22);\n `;case\"bicubic\":return`\n let x0 = i32(floor(x)) - 1;\n let y0 = i32(floor(y)) - 1;\n var p: mat4x4<${t}>;\n for (var h = 0; h < 4; h++) {\n for (var w = 0; w < 4; w++) {\n p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${lt}], indices[${yt}], border);\n }\n }\n\n let dx = x - f32(x0 + 1);\n let dy = y - f32(y0 + 1);\n let result = gs_bicubic_interpolate(p, dx, dy);\n `;default:throw new Error(`mode ${r.mode} is not supported`)}})()+`${e.setByOffset(\"global_idx\",\"result\")}`,Hf=(e,t)=>{let r=E(\"x\",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=E(\"grid\",e[1].dataType,n.length,2),i=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format===\"NHWC\"&&(i=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[lt,yt,Ut,Nt]=[0,3,1,2]);let a=M(\"output\",e[0].dataType,i.length),l=r.type.value,d=k.size(i),p=[{type:12,data:d},...N(e[0].dims,n,i)],m=u=>`\n ${u.registerUniform(\"output_size\",\"u32\").declareVariables(r,o,a)}\n ${Uf}\n ${Nf(l)}\n ${Vf(t)}\n ${Wf(t)}\n ${Lf(r,l,t)}\n\n ${u.mainStart()}\n ${u.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let H_in = i32(uniforms.x_shape[${Ut}]);\n let W_in = i32(uniforms.x_shape[${Nt}]);\n\n ${t.alignCorners===0?`\n let x_min = -0.5;\n let x_max = f32(W_in) - 0.5;\n let y_min = -0.5;\n let y_max = f32(H_in) - 0.5;\n `:`\n let x_min = 0.0;\n let x_max = f32(W_in) - 1.0;\n let y_min = 0.0;\n let y_max = f32(H_in) - 1.0;\n `};\n let border = vec4(x_min, y_min, x_max, y_max);\n\n let indices = ${a.offsetToIndices(\"global_idx\")};\n var grid_indices = vec3(indices[${lt}], indices[${Ut}], indices[${Nt}]);\n let nxy = ${o.getByIndices(\"grid_indices\")};\n var x = gs_denormalize(f32(nxy[0]), W_in);\n var y = gs_denormalize(f32(nxy[1]), H_in);\n\n ${Gf(a,l,t)}\n }`;return{name:\"GridSample\",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:[\"type\",\"type\"]},getRunData:u=>{let h=k.size(i);return{outputs:[{dims:i,dataType:u[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:p}},getShaderSource:m}},Pl=(e,t)=>{Rf(e.inputs),e.compute(Hf(e.inputs,t))},zl=e=>J({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})});var Me,jf,Dl,Bl,Kf,rr,Ml,To=R(()=>{\"use strict\";te();oe();Se();Lr();Kr();ae();ut();Me=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,jf=(e,t)=>{let r=e[0],n=Me(e,1),o=Me(e,2),i=Me(e,3),a=Me(e,4),l=Me(e,5),d=Me(e,6),p=Me(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error(\"Input query is expected to have 3 or 5 dimensions\");let m=r.dims[0],u=r.dims[1],h=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],_=u,y=0,g=0,x=Math.floor(h/t.numHeads);if(d&&p&&k.size(d.dims)&&k.size(p.dims)){if(d.dims.length!==4)throw new Error('Input \"past_key\" is expected to have 4 dimensions');if(d.dims[0]!==m||d.dims[1]!==t.numHeads||d.dims[3]!==x)throw new Error('Input \"past_key\" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[0]!==m||p.dims[1]!==t.numHeads||p.dims[3]!==x)throw new Error('Input \"past_value\" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.dims[2]!==p.dims[2])throw new Error('Input \"past_key\" and \"past_value\" shall have same dim 2 (past_sequence_length)');if(p.dims.length!==4)throw new Error('Input \"past_value\" is expected to have 4 dimensions');y=d.dims[2],g=d.dims[2]}else if(d&&k.size(d.dims)||p&&k.size(p.dims))throw new Error('Input \"past_key\" and \"past_value\" shall be both present or both absent');let $;if(n&&k.size(n.dims)>0){if(r.dims.length!==3)throw new Error('Input \"query\" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input \"key\" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input \"query\" and \"key\" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input \"query\" and \"key\" shall have same dim 2 (hidden_size)');$=2,_=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==x)throw new Error('Expect \"key\" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect \"value\" be none when \"key\" has packed kv format.');$=5,_=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==x)throw new Error('Expect \"key\" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');$=0,_=n.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input \"query\" is expected to have 5 dimensions when key is empty');if(r.dims[2]!==t.numHeads||r.dims[3]!==3)throw new Error('Expect \"query\" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');$=3}if(i&&k.size(i.dims)>0){if(i.dims.length!==1)throw new Error('Input \"bias\" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error(\"bias is not allowed for packed kv.\")}let v=y+_,S=0;if(a&&k.size(a.dims)>0){S=8;let P=a.dims;throw P.length===1?P[0]===m?S=1:P[0]===3*m+2&&(S=3):P.length===2&&P[0]===m&&P[1]===v&&(S=5),S===8?new Error('Input \"key_padding_mask\" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error(\"Mask not supported\")}let T=!1,C=h;if(o&&k.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input \"value\" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input \"query\" and \"value\" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(_!==o.dims[1])throw new Error('Input \"key\" and \"value\" shall have the same dim 1 (kv_sequence_length)');C=o.dims[2]}else{if(_!==o.dims[2])throw new Error('Input \"key\" and \"value\" shall have the same dim 2 (kv_sequence_length)');C=o.dims[1]*o.dims[3],T=!0}}let A=!1;if(a&&k.size(a.dims)>0)throw new Error(\"Key padding mask is not supported\");if(l&&k.size(l.dims)>0){if(l.dims.length!==4)throw new Error('Input \"attention_bias\" is expected to have 4 dimensions');if(l.dims[0]!==m||l.dims[1]!==t.numHeads||l.dims[2]!==u||l.dims[3]!==v)throw new Error('Expect \"attention_bias\" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:m,sequenceLength:u,pastSequenceLength:y,kvSequenceLength:_,totalSequenceLength:v,maxSequenceLength:g,inputHiddenSize:0,hiddenSize:h,vHiddenSize:C,headSize:x,vHeadSize:Math.floor(C/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:S,scale:t.scale,broadcastResPosBias:A,passPastInKv:T,qkvFormat:$}},Dl=e=>J({...e}),Bl=J({perm:[0,2,1,3]}),Kf=(e,t,r,n,o,i,a)=>{let l=[n,o,i],d=k.size(l),p=[{type:12,data:d},{type:12,data:a},{type:12,data:i}],m=u=>{let h=M(\"qkv_with_bias\",t.dataType,l),_=E(\"qkv\",t.dataType,l),y=E(\"bias\",r.dataType,l),g=[{name:\"output_size\",type:\"u32\"},{name:\"bias_offset\",type:\"u32\"},{name:\"hidden_size\",type:\"u32\"}];return`\n ${u.registerUniforms(g).declareVariables(_,y,h)}\n ${u.mainStart()}\n ${u.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;\n\n qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];\n }`};return e.compute({name:\"MultiHeadAttentionAddBias\",shaderCache:{inputDependencies:[\"type\",\"type\"]},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p}),getShaderSource:m},{inputs:[t,r],outputs:[-1]})[0]},rr=(e,t,r,n,o,i,a,l)=>{let d=i;if(a&&k.size(a.dims)>0){if(n===1)throw new Error(\"AddBiasReshape is not implemented. Please export your model with packed QKV or KV\");return d=Kf(e,i,a,t,n,r*o,l),d=d.reshape([t,n,r,o]),r===1||n===1?d:e.compute(Ee(d,Bl.perm),{inputs:[d],outputs:[-1]})[0]}else return i.dims.length===3&&(d=i.reshape([t,n,r,o])),r===1||n===1?d:e.compute(Ee(d,Bl.perm),{inputs:[d],outputs:[-1]})[0]},Ml=(e,t)=>{let r=jf(e.inputs,t),n=e.inputs[0],o=Me(e.inputs,1),i=Me(e.inputs,2),a=Me(e.inputs,3),l=Me(e.inputs,4),d=Me(e.inputs,5),p=Me(e.inputs,6),m=Me(e.inputs,7);if(n.dims.length===5)throw new Error(\"Packed QKV is not implemented\");if(o?.dims.length===5)throw new Error(\"Packed KV is not implemented\");let u=o&&i&&o.dims.length===4&&i.dims.length===4,h=rr(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,a,0);if(u)return Rt(e,h,o,i,l,void 0,p,m,d,r);if(!o||!i)throw new Error(\"key and value must be provided\");let _=rr(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,o,a,r.hiddenSize),y=rr(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,i,a,2*r.hiddenSize);Rt(e,h,_,y,l,void 0,p,m,d,r)}});var Yf,Zf,Qf,Xf,Io,Rl,Ul,Co=R(()=>{\"use strict\";te();oe();Se();ae();Yf=e=>{if(!e||e.length<1)throw new Error(\"too few inputs\")},Zf=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>r.push(Number(o))),n=r.length),J({numOutputs:n,axis:t.axis,splitSizes:r})},Qf=e=>`\nfn calculateOutputIndex(index: u32) -> u32 {\n for (var i: u32 = 0u; i < ${e}u; i += 1u ) {\n if (index < ${F(\"uniforms.size_in_split_axis\",\"i\",e)}) {\n return i;\n }\n }\n return ${e}u;\n}`,Xf=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=k.size(r),o=e[0].dataType,i=k.normalizeAxis(t.axis,r.length),a=new Array(t.numOutputs),l=E(\"input\",o,r.length),d=new Array(t.numOutputs),p=[],m=[],u=0,h=[{type:12,data:n}];for(let y=0;y`\n ${y.registerUniform(\"input_size\",\"u32\").registerUniform(\"size_in_split_axis\",\"u32\",d.length).declareVariables(l,...a)}\n ${Qf(d.length)}\n ${Xf(a)}\n\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.input_size\")}\n\n var indices = ${l.offsetToIndices(\"global_idx\")};\n var index = ${l.indicesGet(\"indices\",i)};\n let output_number = calculateOutputIndex(index);\n if (output_number != 0) {\n index -= ${F(\"uniforms.size_in_split_axis\",\"output_number - 1u\",d.length)};\n ${l.indicesSet(\"indices\",i,\"index\")};\n }\n writeBufferData(output_number, indices, global_idx);\n }`;return{name:\"Split\",shaderCache:{hint:t.cacheKey,inputDependencies:[\"rank\"]},getShaderSource:_,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:h})}},Rl=(e,t)=>{Yf(e.inputs);let r=e.inputs.length===1?t:Zf(e.inputs,t);e.compute(Io(e.inputs,r),{inputs:[0]})},Ul=e=>{let t=e.axis,r=e.splitSizes,n=e.numOutputs<0?r.length:e.numOutputs;if(n!==r.length)throw new Error(\"numOutputs and splitSizes lengh must be equal\");return J({axis:t,numOutputs:n,splitSizes:r})}});var Jf,eh,Nl,Vl,Wl=R(()=>{\"use strict\";Se();Kr();To();Co();ut();Jf=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error(\"cos_cache and sin_cache inputs are required if do_rotary is specified\");let r=e[0],n=e[1],o=e[2],i=e[3],a=e[4];if(t.localWindowSize!==-1)throw new Error(\"Local attention is not supported\");if(t.softcap!==0)throw new Error(\"Softcap is not supported\");if(t.rotaryInterleaved!==0)throw new Error(\"Rotary interleaved is not supported\");if(t.smoothSoftmax)throw new Error(\"Smooth softmax is not supported\");if(r.dims.length!==3&&r.dims.length!==5)throw new Error(\"Input query is expected to have 3 or 5 dimensions\");let l=!1,d=r.dims[0],p=r.dims[1],m=r.dims.length===3?l?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],u=p,h=0,_=!n||n.dims.length===0,y=Math.floor(_?m/(t.numHeads+2*t.kvNumHeads):m/t.numHeads);_&&(m=y*t.numHeads);let g=i&&i.dims.length!==0,x=a&&a.dims.length!==0;if(g&&i.dims.length===4&&i.dims[0]===d&&i.dims[1]!==t.kvNumHeads&&i.dims[2]===t.kvNumHeads&&i.dims[3]===y)throw new Error(\"BSNH pastKey/pastValue is not supported\");if(g&&x){if(i.dims.length!==4)throw new Error('Input \"past_key\" is expected to have 4 dimensions');if(a.dims.length!==4)throw new Error('Input \"past_value\" is expected to have 4 dimensions');h=i.dims[2]}else if(g||x)throw new Error('Input \"past_key\" and \"past_value\" shall be both present or both absent');let v=1;if(n&&n.dims.length>0){if(r.dims.length!==3)throw new Error('Input \"query\" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input \"key\" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input \"query\" and \"key\" shall have same dim 0 (batch size)');if(n.dims.length===3){if(r.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of \"query\" should be a multiple of \"key\"');u=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==y)throw new Error('Expect \"key\" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect \"value\" be none when \"key\" has packed kv format.');u=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==y)throw new Error('Expect \"key\" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');u=n.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input \"query\" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error('Expect \"query\" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');v=3}let S=0,T=!1,C=t.kvNumHeads?y*t.kvNumHeads:m;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input \"value\" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input \"query\" and \"value\" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(u!==o.dims[1])throw new Error('Input \"key\" and \"value\" shall have the same dim 1 (kv_sequence_length)');C=o.dims[2]}else{if(u!==o.dims[2])throw new Error('Input \"past_key\" and \"past_value\" shall have the same dim 2 (kv_sequence_length)');C=o.dims[1]*o.dims[3],T=!0}}let A=e.length>4?e[5]:void 0;if(A&&A.dims.length!==1&&A.dims[0]!==d)throw new Error('Input \"seqlens\" is expected to have 1 dimension and the same dim 0 as batch_size');let P=-1,O=-1,U=!1;return{batchSize:d,sequenceLength:p,pastSequenceLength:h,kvSequenceLength:u,totalSequenceLength:P,maxSequenceLength:O,inputHiddenSize:0,hiddenSize:m,vHiddenSize:C,headSize:y,vHeadSize:Math.floor(C/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:S,scale:t.scale,broadcastResPosBias:U,passPastInKv:T,qkvFormat:v}},eh=J({perm:[0,2,1,3]}),Nl=(e,t,r)=>{let n=t,o=r.kvNumHeads;return t.dims.length===3&&r.kvSequenceLength!==0&&(n=t.reshape([r.batchSize,r.kvSequenceLength,o,r.headSize]),n=e.compute(Ee(n,eh.perm),{inputs:[n],outputs:[-1]})[0]),n},Vl=(e,t)=>{let r=Jf(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error(\"Packed QKV is not implemented\");if(e.inputs[1]?.dims.length===5)throw new Error(\"Packed KV is not implemented\");let n=e.inputs[0],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,i=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,a=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,l=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,d=e.inputs.length>4?e.inputs[5]:void 0,p=e.inputs.length>5?e.inputs[6]:void 0,m=r.kvNumHeads?r.kvNumHeads:r.numHeads,u=J({axis:2,numOutputs:3,splitSizes:[r.numHeads*r.headSize,m*r.headSize,m*r.headSize]}),[h,_,y]=!o&&!i?e.compute(Io([n],u),{inputs:[n],outputs:[-1,-1,-1]}):[n,o,i],g=rr(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,h,void 0,0);Rt(e,g,Nl(e,_,r),Nl(e,y,r),void 0,void 0,a,l,void 0,r,d,p)}});var Ll,th,rh,Gl,Hl=R(()=>{\"use strict\";te();oe();ut();ae();Ll=(e,t,r,n,o,i,a,l)=>{let d=me(i),p=d===1?\"f32\":`vec${d}f`,m=d===1?\"vec2f\":`mat2x${d}f`,u=o*a,h=64;u===1&&(h=256);let _=[o,a,i/d],y=[o,a,2],g=[\"rank\",\"type\",\"type\"],x=[];x.push(...N(_,y));let $=v=>{let S=E(\"x\",t.dataType,3,d),T=E(\"scale\",r.dataType,r.dims),C=E(\"bias\",n.dataType,n.dims),A=M(\"output\",1,3,2),P=[S,T,C,A];return`\n var workgroup_shared : array<${m}, ${h}>;\n const workgroup_size = ${h}u;\n ${v.declareVariables(...P)}\n ${v.mainStart(h)}\n let batch = workgroup_index / uniforms.x_shape[1];\n let channel = workgroup_index % uniforms.x_shape[1];\n let hight = uniforms.x_shape[2];\n // initialize workgroup memory\n var sum = ${p}(0);\n var squared_sum = ${p}(0);\n for (var h = local_idx; h < hight; h += workgroup_size) {\n let value = ${p}(${S.get(\"batch\",\"channel\",\"h\")});\n sum += value;\n squared_sum += value * value;\n }\n workgroup_shared[local_idx] = ${m}(sum, squared_sum);\n workgroupBarrier();\n\n for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) {\n if (local_idx < currSize) {\n workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize];\n }\n workgroupBarrier();\n }\n if (local_idx == 0) {\n let sum_final = ${He(\"workgroup_shared[0][0]\",d)} / f32(hight * ${d});\n let squared_sum_final = ${He(\"workgroup_shared[0][1]\",d)} / f32(hight * ${d});\n\n let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${l}));\n let channel_scale = inv_std_dev * f32(scale[channel]);\n let channel_shift = f32(bias[channel]) - sum_final * channel_scale;\n output[workgroup_index] = vec2f(channel_scale, channel_shift);\n }\n }`};return e.compute({name:\"InstanceNormComputeChannelScaleShift\",shaderCache:{hint:`${d};${l};${h}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:y,dataType:1}],dispatchGroup:{x:u},programUniforms:x}),getShaderSource:$},{inputs:[t,r,n],outputs:[-1]})[0]},th=(e,t,r)=>{let n=t[0].dims,o=n,i=2,a=n[0],l=n[1],d=k.sizeFromDimension(n,i),p=me(d),m=k.size(o)/p,u=Ll(e,t[0],t[1],t[2],a,d,l,r.epsilon),h=[a,l,d/p],_=[a,l],y=[\"type\",\"none\"],g=x=>{let $=E(\"x\",t[0].dataType,h.length,p),v=E(\"scale_shift\",1,_.length,2),S=M(\"output\",t[0].dataType,h.length,p),T=[$,v,S];return`\n ${x.registerUniform(\"output_size\",\"u32\").declareVariables(...T)}\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let outputIndices = ${S.offsetToIndices(\"global_idx\")};\n let batch = outputIndices[0];\n let channel = outputIndices[1];\n let scale_shift = ${v.getByIndices(\"vec2(batch, channel)\")};\n let value = ${$.getByOffset(\"global_idx\")} * ${S.type.value}(scale_shift.x) + ${S.type.value}(scale_shift.y);\n ${S.setByOffset(\"global_idx\",\"value\")};\n }`};e.compute({name:\"InstanceNormalization\",shaderCache:{hint:`${p}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...N(h,_,h)]}),getShaderSource:g},{inputs:[t[0],u]})},rh=(e,t,r)=>{let n=t[0].dims,o=n,i=n[0],a=n[n.length-1],l=k.sizeFromDimension(n,1)/a,d=me(a),p=k.size(o)/d,m=[{type:12,data:l},{type:12,data:Math.floor(a/d)}],u=[\"type\",\"type\"],h=!1,_=[0,n.length-1];for(let $=0;$n[_[v]])),g=Ll(e,y,t[1],t[2],i,l,a,r.epsilon),x=$=>{let v=ye(t[0].dataType),S=d===1?\"vec2f\":`mat${d}x2f`,T=P=>{let O=P===0?\"x\":\"y\",U=d===1?\"f32\":`vec${d}f`;switch(d){case 1:return`${v}(${U}(scale.${O}))`;case 2:return`vec2<${v}>(${U}(scale[0].${O}, scale[1].${O}))`;case 4:return`vec4<${v}>(${U}(scale[0].${O}, scale[1].${O}, scale[2].${O}, scale[3].${O}))`;default:throw new Error(`Not supported compoents ${d}`)}},C=E(\"input\",t[0].dataType,t[0].dims,d),A=M(\"output\",t[0].dataType,o,d);return`\n @group(0) @binding(0) var input : array<${C.type.storage}>;\n @group(0) @binding(1) var scale_input : array<${S}>;\n @group(0) @binding(2) var output : array<${A.type.storage}>;\n struct Uniforms {H: u32, C : u32};\n @group(0) @binding(3) var uniforms: Uniforms;\n\n ${$.mainStart()}\n let current_image_number = global_idx / (uniforms.C * uniforms.H);\n let current_channel_number = global_idx % uniforms.C;\n\n let scale_offset = current_image_number * uniforms.C + current_channel_number;\n let scale = scale_input[scale_offset];\n output[global_idx] = fma(input[global_idx], ${T(0)}, ${T(1)});\n }`};e.compute({name:\"InstanceNormalizationNHWC\",shaderCache:{hint:`${d}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:m}),getShaderSource:x},{inputs:[t[0],g]})},Gl=(e,t)=>{t.format===\"NHWC\"?rh(e,e.inputs,t):th(e,e.inputs,t)}});var nh,oh,Fl,ql=R(()=>{\"use strict\";te();oe();ae();nh=e=>{if(!e||e.length<2)throw new Error(\"layerNorm requires at least 2 inputs.\")},oh=(e,t,r)=>{let n=t.simplified,o=e[0].dims,i=e[1],a=!n&&e[2],l=o,d=k.normalizeAxis(t.axis,o.length),p=k.sizeToDimension(o,d),m=k.sizeFromDimension(o,d),u=k.size(i.dims),h=a?k.size(a.dims):0;if(u!==m||a&&h!==m)throw new Error(`Size of X.shape()[axis:] == ${m}.\n Size of scale and bias (if provided) must match this.\n Got scale size of ${u} and bias size of ${h}`);let _=[];for(let C=0;C1,v=r>2,S=C=>{let A=ye(e[0].dataType),P=[E(\"x\",e[0].dataType,e[0].dims,y),E(\"scale\",i.dataType,i.dims,y)];a&&P.push(E(\"bias\",a.dataType,a.dims,y)),P.push(M(\"output\",e[0].dataType,l,y)),$&&P.push(M(\"mean_data_output\",1,_)),v&&P.push(M(\"inv_std_output\",1,_));let O=[{name:\"norm_count\",type:\"u32\"},{name:\"norm_size\",type:\"f32\"},{name:\"norm_size_vectorized\",type:\"u32\"},{name:\"epsilon\",type:\"f32\"}];return`\n ${C.registerUniforms(O).declareVariables(...P)}\n ${C.mainStart()}\n ${C.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.norm_count\")}\n let offset = global_idx * uniforms.norm_size_vectorized;\n var mean_vector = ${lo(\"f32\",y)};\n var mean_square_vector = ${lo(\"f32\",y)};\n\n for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {\n let value = ${At(A,y,\"x[h + offset]\")};\n mean_vector += value;\n mean_square_vector += value * value;\n }\n let mean = ${He(\"mean_vector\",y)} / uniforms.norm_size;\n let inv_std_dev = inverseSqrt(${He(\"mean_square_vector\",y)} / uniforms.norm_size ${n?\"\":\"- mean * mean\"} + uniforms.epsilon);\n\n for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {\n let f32input = ${At(A,y,\"x[j + offset]\")};\n let f32scale = ${At(A,y,\"scale[j]\")};\n output[j + offset] = ${P[0].type.value}((f32input ${n?\"\":\"- mean\"}) * inv_std_dev * f32scale\n ${a?`+ ${At(A,y,\"bias[j]\")}`:\"\"}\n );\n }\n\n ${$?\"mean_data_output[global_idx] = mean\":\"\"};\n ${v?\"inv_std_output[global_idx] = inv_std_dev\":\"\"};\n }`},T=[{dims:l,dataType:e[0].dataType}];return $&&T.push({dims:_,dataType:1}),v&&T.push({dims:_,dataType:1}),{name:\"LayerNormalization\",shaderCache:{hint:`${y};${r};${n}`,inputDependencies:g},getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(p/64)},programUniforms:x}),getShaderSource:S}},Fl=(e,t)=>{nh(e.inputs),e.compute(oh(e.inputs,t,e.outputCount))}});var ih,jl,Kl=R(()=>{\"use strict\";oe();en();tn();ih=e=>{if(!e||e.length!==2)throw new Error(\"MatMul requires 2 inputs.\");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error(\"shared dimension does not match.\")},jl=e=>{ih(e.inputs);let t=et.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error(\"Can't use matmul on the given tensors\");let r=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];if(r<8&&n<8)e.compute(Jr(e.inputs,{activation:\"\"},t));else{let o=t[t.length-2],i=k.size(e.inputs[0].dims.slice(0,-2)),a=k.size(e.inputs[1].dims.slice(0,-2));if(i!==1&&o===1&&a===1){let l=e.inputs[0].reshape([1,i,n]),d=e.inputs[1].reshape([1,n,r]),p=[1,i,r],m=[l,d];e.compute(tr(m,{activation:\"\"},t,p),{inputs:m})}else e.compute(tr(e.inputs,{activation:\"\"},t))}}});var ah,sh,uh,Yl,Zl,Ql=R(()=>{\"use strict\";te();oe();Se();ae();ah=(e,t)=>{if(e.length<3||e.length>4)throw new Error(\"MatMulNBits requires 3 or 4 inputs\");let r=e[0],n=r.dims.length;if(r.dims[n-1]!==t.k)throw new Error(\"The last dim of input shape does not match the k value\");let o=Math.floor((t.k+t.blockSize-1)/t.blockSize),i=t.blockSize/8*t.bits,a=e[1];if(!k.areEqual(a.dims,[t.n,o,i]))throw new Error(\"The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize\");let d=e[2].dims;if(k.size(d)!==t.n*o)throw new Error(\"scales input size error.\");if(e.length===4){let m=e[3].dims,u=t.bits>4?t.n*o:t.n*Math.floor((o+1)/2);if(k.size(m)!==u)throw new Error(\"zeroPoints input size error.\")}},sh=(e,t)=>{let r=e[0].dims,n=r.length,o=r[n-2],i=t.k,a=t.n,l=r.slice(0,n-2),d=k.size(l),m=e[1].dims[2]/4,u=e[0].dataType,h=me(t.k),_=me(m),y=me(a),g=l.concat([o,a]),x=o>1&&a/y%2===0?2:1,$=k.size(g)/y/x,v=64,S=[],T=[d,o,i/h],C=k.convertShape(e[1].dims).slice();C.splice(-1,1,m/_),S.push(...N(T)),S.push(...N(C)),S.push(...N(e[2].dims)),e.length===4&&S.push(...N(k.convertShape(e[3].dims)));let A=[d,o,a/y];S.push(...N(A));let P=O=>{let U=T.length,G=E(\"a\",e[0].dataType,U,h),q=E(\"b\",12,C.length,_),K=E(\"scales\",e[2].dataType,e[2].dims.length),W=[G,q,K],Y=e.length===4?E(\"zero_points\",12,e[3].dims.length):void 0;Y&&W.push(Y);let se=A.length,X=M(\"output\",e[0].dataType,se,y),re=ye(e[0].dataType),ee=(()=>{switch(h){case 1:return`array<${re}, 8>`;case 2:return`mat4x2<${re}>`;case 4:return`mat2x4<${re}>`;default:throw new Error(`${h}-component is not supported.`)}})(),ne=()=>{let $e=`\n // reuse a data\n var input_offset = ${G.indicesToOffset(`${G.type.indices}(batch, row, word_offset)`)};\n var a_data: ${ee};\n for (var j: u32 = 0; j < ${8/h}; j++) {\n a_data[j] = ${G.getByOffset(\"input_offset\")};\n input_offset++;\n }\n `;for(let de=0;de> 4) & b_mask);\n b_quantized_values = ${ee}(${Array.from({length:4},(V,j)=>`${re}(b_value_lower[${j}]), ${re}(b_value_upper[${j}])`).join(\", \")});\n b_dequantized_values = ${(()=>h===1?`${ee}(${Array.from({length:8},(V,j)=>`(b_quantized_values[${j}] - ${Y?`zero_point${de}`:\"zero_point\"}) * scale${de}`).join(\", \")});`:`(b_quantized_values - ${ee}(${Array(8).fill(`${Y?`zero_point${de}`:\"zero_point\"}`).join(\",\")})) * scale${de};`)()};\n workgroup_shared[local_id.x * ${x} + ${Math.floor(de/y)}]${y>1?`[${de%y}]`:\"\"} += ${Array.from({length:8/h},(V,j)=>`${h===1?`a_data[${j}] * b_dequantized_values[${j}]`:`dot(a_data[${j}], b_dequantized_values[${j}])`}`).join(\" + \")};\n `;return $e},ve=()=>{let $e=`\n var col_index = col * ${y};\n ${Y?`\n let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2;\n var zero_point_byte_count: u32;\n var zero_point_word_index: u32;\n var zero_point_byte_offset: u32;\n let zero_point_nibble_offset: u32 = block & 0x1u;\n var zero_point_bits_offset: u32;\n var zero_point_word: u32;`:`\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${re}(8);`}\n `;for(let de=0;de> 0x1u);\n zero_point_word_index = zero_point_byte_count >> 0x2u;\n zero_point_byte_offset = zero_point_byte_count & 0x3u;\n zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n zero_point_word = ${Y.getByOffset(\"zero_point_word_index\")} >> zero_point_bits_offset;\n let zero_point${de} = ${re}((zero_point_word) & 0xFu);`:\"\"}\n col_index += 1;`;return $e},Be=()=>{let $e=`col_index = col * ${y};`;for(let de=0;de;\n var b_value_upper: vec4;\n var b_quantized_values: ${ee};\n var b_dequantized_values: ${ee};`,$e};return`\n var workgroup_shared: array<${X.type.value}, ${x*v}>;\n ${O.declareVariables(...W,X)}\n ${O.mainStart([v,1,1])}\n let output_indices = ${X.offsetToIndices(`(global_idx / ${v}) * ${x}`)};\n let col = output_indices[2];\n let row = output_indices[1];\n let batch = output_indices[0];\n let nBlocksPerCol = uniforms.b_shape[1];\n\n for (var block = local_id.x; block < nBlocksPerCol; block += ${v}) {\n //process one block\n var word_offset: u32 = block * ${t.blockSize/h};\n ${ve()}\n for (var word: u32 = 0; word < ${m}; word += ${_}) {\n ${Be()}\n for (var i: u32 = 0; i < ${_}; i++) {\n ${ne()}\n word_offset += ${8/h};\n }\n }\n }\n workgroupBarrier();\n\n if (local_id.x < ${x}) {\n var output_value: ${X.type.value} = ${X.type.value}(0);\n var workgroup_shared_offset: u32 = local_id.x;\n for (var b: u32 = 0u; b < ${v}u; b++) {\n output_value += workgroup_shared[workgroup_shared_offset];\n workgroup_shared_offset += ${x};\n }\n ${X.setByIndices(`${X.type.indices}(batch, row, col + local_id.x)`,\"output_value\")};\n }\n }`};return{name:\"MatMulNBits\",shaderCache:{hint:`${t.blockSize};${t.bits};${h};${_};${y};${x};${v}`,inputDependencies:Array(e.length).fill(\"rank\")},getRunData:()=>({outputs:[{dims:g,dataType:u}],dispatchGroup:{x:$},programUniforms:S}),getShaderSource:P}},uh=(e,t)=>{let r=e[0].dims,n=r.length,o=r[n-2],i=t.k,a=t.n,l=r.slice(0,n-2),d=k.size(l),m=e[1].dims[2]/4,u=e[0].dataType,h=me(t.k),_=me(m),y=l.concat([o,a]),g=128,x=a%8===0?8:a%4===0?4:1,$=g/x,v=$*_*8,S=v/h,T=v/t.blockSize,C=k.size(y)/x,A=[],P=[d,o,i/h],O=k.convertShape(e[1].dims).slice();O.splice(-1,1,m/_),A.push(...N(P)),A.push(...N(O)),A.push(...N(e[2].dims)),e.length===4&&A.push(...N(k.convertShape(e[3].dims)));let U=[d,o,a];A.push(...N(U));let G=q=>{let K=P.length,W=E(\"a\",e[0].dataType,K,h),Y=E(\"b\",12,O.length,_),se=E(\"scales\",e[2].dataType,e[2].dims.length),X=[W,Y,se],re=e.length===4?E(\"zero_points\",12,e[3].dims.length):void 0;re&&X.push(re);let ee=U.length,ne=M(\"output\",e[0].dataType,ee),ve=ye(e[0].dataType),Be=()=>{switch(h){case 1:return`\n let a_data0 = vec4<${ve}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]);\n let a_data1 = vec4<${ve}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return`\n let a_data0 = vec4<${ve}>(sub_a[word_offset], sub_a[word_offset + 1]);\n let a_data1 = vec4<${ve}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return`\n let a_data0 = sub_a[word_offset];\n let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${h}-component is not supported.`)}};return`\n var sub_a: array<${W.type.value}, ${S}>;\n var inter_results: array, ${x}>;\n ${q.declareVariables(...X,ne)}\n ${q.mainStart([$,x,1])}\n let output_indices = ${ne.offsetToIndices(`workgroup_index * ${x}`)};\n let col = output_indices[2];\n let row = output_indices[1];\n let batch = output_indices[0];\n let n_blocks_per_col = uniforms.b_shape[1];\n let num_tiles = (n_blocks_per_col - 1) / ${T} + 1;\n\n // Loop over shared dimension.\n for (var tile: u32 = 0; tile < num_tiles; tile += 1) {\n let a_col_start = tile * ${S};\n // load one tile A data into shared memory.\n for (var a_offset = local_idx; a_offset < ${S}; a_offset += ${g})\n {\n let a_col = a_col_start + a_offset;\n if (a_col < uniforms.a_shape[2])\n {\n sub_a[a_offset] = ${W.getByIndices(`${W.type.indices}(batch, row, a_col)`)};\n } else {\n sub_a[a_offset] = ${W.type.value}(0);\n }\n }\n workgroupBarrier();\n\n // each thread process one block\n let b_row = col + local_id.y;\n let block = tile * ${T} + local_id.x;\n ${re?`\n let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2;\n let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u);\n let zero_point_word_index = zero_point_byte_count >> 0x2u;\n let zero_point_byte_offset = zero_point_byte_count & 0x3u;\n let zero_point_nibble_offset: u32 = block & 0x1u;\n let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n let zero_point_word = ${re.getByOffset(\"zero_point_word_index\")} >> zero_point_bits_offset;\n let zero_point = ${ve}((zero_point_word) & 0xFu);`:`\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${ve}(8);`}\n let scale = ${se.getByOffset(\"b_row * n_blocks_per_col + block\")};\n let b_data = ${Y.getByIndices(`${Y.type.indices}(b_row, block, 0)`)};\n var word_offset = local_id.x * ${t.blockSize/h};\n for (var i: u32 = 0; i < ${_}; i++) {\n ${Be()}\n let b_value = ${_===1?\"b_data\":\"b_data[i]\"};\n let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu);\n let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu);\n let b_quantized_values = mat2x4<${ve}>(${Array.from({length:4},($e,de)=>`${ve}(b_value_lower[${de}]), ${ve}(b_value_upper[${de}])`).join(\", \")});\n let b_dequantized_values = (b_quantized_values - mat2x4<${ve}>(${Array(8).fill(\"zero_point\").join(\",\")})) * scale;\n inter_results[local_id.y][local_id.x] += ${Array.from({length:2},($e,de)=>`${`dot(a_data${de}, b_dequantized_values[${de}])`}`).join(\" + \")};\n word_offset += ${8/h};\n }\n workgroupBarrier();\n }\n\n if (local_idx < ${x}) {\n var output_value: ${ne.type.value} = ${ne.type.value}(0);\n for (var b = 0u; b < ${$}; b++) {\n output_value += inter_results[local_idx][b];\n }\n if (col + local_idx < uniforms.output_shape[2])\n {\n ${ne.setByIndices(`${ne.type.indices}(batch, row, col + local_idx)`,\"output_value\")}\n }\n }\n }`};return{name:\"BlockwiseMatMulNBits32\",shaderCache:{hint:`${t.blockSize};${h};${_};${$};${x}`,inputDependencies:Array(e.length).fill(\"rank\")},getRunData:()=>({outputs:[{dims:y,dataType:u}],dispatchGroup:{x:C},programUniforms:A}),getShaderSource:G}},Yl=(e,t)=>{ah(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor(\"intel\")&&e.adapterInfo.isArchitecture(\"gen-12lp\")?e.compute(uh(e.inputs,t)):e.compute(sh(e.inputs,t))},Zl=e=>J(e)});var lh,dh,ch,ph,mh,fh,hh,gh,Xl,Jl=R(()=>{\"use strict\";te();oe();ae();lh=e=>{if(!e||e.length<1)throw new Error(\"Too few inputs\");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error(\"Input type must be float or float16.\");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error(\"The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].\")}},dh=(e,t,r)=>{let n=\"\";for(let o=t-1;o>=0;--o)n+=`\n k = i32(${e.indicesGet(\"indices\",o)}) - ${F(\"uniforms.pads\",o,r)};\n if (k < 0) {\n break;\n }\n if (k >= i32(${F(\"uniforms.x_shape\",o,t)})) {\n break;\n }\n offset += k * i32(${F(\"uniforms.x_strides\",o,t)});\n `;return`\n value = ${e.type.value}(uniforms.constant_value);\n for (var i = 0; i < 1; i++) {\n var offset = 0;\n var k = 0;\n ${n}\n value = x[offset];\n }\n `},ch=(e,t,r)=>{let n=\"\";for(let o=t-1;o>=0;--o)n+=`\n k = i32(${e.indicesGet(\"indices\",o)}) - ${F(\"uniforms.pads\",o,r)};\n if (k < 0) {\n k = -k;\n }\n {\n let _2n_1 = 2 * (i32(${F(\"uniforms.x_shape\",o,t)}) - 1);\n k = k % _2n_1;\n if(k >= i32(${F(\"uniforms.x_shape\",o,t)})) {\n k = _2n_1 - k;\n }\n }\n offset += k * i32(${F(\"uniforms.x_strides\",o,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${n}\n value = x[offset];\n `},ph=(e,t,r)=>{let n=\"\";for(let o=t-1;o>=0;--o)n+=`\n k = i32(${e.indicesGet(\"indices\",o)}) - ${F(\"uniforms.pads\",o,r)};\n if (k < 0) {\n k = 0;\n }\n if (k >= i32(${F(\"uniforms.x_shape\",o,t)})) {\n k = i32(${F(\"uniforms.x_shape\",o,t)}) - 1;\n }\n offset += k * i32(${F(\"uniforms.x_strides\",o,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${n}\n value = x[offset];\n `},mh=(e,t,r)=>{let n=\"\";for(let o=t-1;o>=0;--o)n+=`\n k = i32(${e.indicesGet(\"indices\",o)}) - ${F(\"uniforms.pads\",o,r)};\n if (k < 0) {\n k += i32(${F(\"uniforms.x_shape\",o,t)}]);\n }\n if (k >= i32(${F(\"uniforms.x_shape\",o,t)})) {\n k -= i32(${F(\"uniforms.x_shape\",o,t)});\n }\n offset += k * i32(${F(\"uniforms.x_strides\",o,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${n}\n value = x[offset];\n `},fh=(e,t,r)=>{switch(r.mode){case 0:return dh(e,t,r.pads.length);case 1:return ch(e,t,r.pads.length);case 2:return ph(e,t,r.pads.length);case 3:return mh(e,t,r.pads.length);default:throw new Error(\"Invalid mode\")}},hh=(e,t)=>{let r=k.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,o=k.size(r),i=[{type:12,data:o},{type:6,data:t.pads}],a=e.length>=3&&e[2].data;t.mode===0&&i.push({type:a?e[2].dataType:1,data:t.value}),i.push(...N(e[0].dims,r));let l=[\"rank\"],d=p=>{let m=M(\"output\",e[0].dataType,r.length),u=E(\"x\",e[0].dataType,n.length),h=u.type.value,_=fh(m,n.length,t),y=[{name:\"output_size\",type:\"u32\"},{name:\"pads\",type:\"i32\",length:t.pads.length}];return t.mode===0&&y.push({name:\"constant_value\",type:a?h:\"f32\"}),`\n ${p.registerUniforms(y).declareVariables(u,m)}\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let indices = ${m.offsetToIndices(\"global_idx\")};\n\n var value = ${h}(0);\n ${_}\n output[global_idx] = value;\n }`};return{name:\"Pad\",shaderCache:{hint:`${t.mode}${a}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k.size(r)/64)},programUniforms:i}),getShaderSource:d}},gh=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,i=new Int32Array(2*o).fill(0);if(e.length>=4){let l=e[3].getBigInt64Array();for(let d=0;di[Number(d)]=Number(l));let a=[];return i.forEach(l=>a.push(l)),{mode:t.mode,value:n,pads:a}}else return t},Xl=(e,t)=>{lh(e.inputs);let r=gh(e.inputs,t);e.compute(hh(e.inputs,r),{inputs:[0]})}});var on,ed,td,rd,nd,bh,yh,od,id,ad,sd,ud,ld,dd,cd,pd,md,fd,hd,gd=R(()=>{\"use strict\";We();te();oe();ae();on=e=>{if(we.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error(\"Pool ops requires 1 input.\")},ed=(e,t,r)=>{let n=t.format===\"NHWC\",o=e.dims.slice();n&&o.splice(1,0,o.pop());let i=Object.hasOwnProperty.call(t,\"dilations\"),a=t.kernelShape.slice(),l=t.strides.slice(),d=i?t.dilations.slice():[],p=t.pads.slice();It.adjustPoolAttributes(r,o,a,l,d,p);let m=It.computePoolOutputShape(r,o,l,d,a,p,t.autoPad),u=Object.assign({},t);i?Object.assign(u,{kernelShape:a,strides:l,pads:p,dilations:d,cacheKey:t.cacheKey}):Object.assign(u,{kernelShape:a,strides:l,pads:p,cacheKey:t.cacheKey});let h=m.slice();return h.push(h.splice(1,1)[0]),[u,n?h:m]},td=(e,t)=>{let r=t.format===\"NHWC\",n=k.size(e),o=k.size(t.kernelShape),i=[{type:12,data:n},{type:12,data:o}],a=[{name:\"outputSize\",type:\"u32\"},{name:\"kernelSize\",type:\"u32\"}];if(t.kernelShape.length<=2){let l=t.kernelShape[t.kernelShape.length-1],d=t.strides[t.strides.length-1],p=t.pads[t.pads.length/2-1],m=t.pads[t.pads.length-1],u=!!(p+m);i.push({type:12,data:l},{type:12,data:d},{type:12,data:p},{type:12,data:m}),a.push({name:\"kw\",type:\"u32\"},{name:\"sw\",type:\"u32\"},{name:\"pwStart\",type:\"u32\"},{name:\"pwEnd\",type:\"u32\"});let h=!1;if(t.kernelShape.length===2){let _=t.kernelShape[t.kernelShape.length-2],y=t.strides[t.strides.length-2],g=t.pads[t.pads.length/2-2],x=t.pads[t.pads.length-2];h=!!(g+x),i.push({type:12,data:_},{type:12,data:y},{type:12,data:g},{type:12,data:x}),a.push({name:\"kh\",type:\"u32\"},{name:\"sh\",type:\"u32\"},{name:\"phStart\",type:\"u32\"},{name:\"phEnd\",type:\"u32\"})}return[i,a,!0,u,h]}else{if(r)throw new Error(\"Pooling with kernelShape.length > 2 is not supported for NHWC format.\");let l=k.computeStrides(t.kernelShape);i.push({type:12,data:l},{type:12,data:t.pads},{type:12,data:t.strides}),a.push({name:\"kernelStrides\",type:\"u32\",length:l.length},{name:\"pads\",type:\"u32\",length:t.pads.length},{name:\"strides\",type:\"u32\",length:t.strides.length});let d=t.pads.reduce((p,m)=>p+m);return[i,a,!!d,!1,!1]}},rd=(e,t,r,n,o,i,a,l,d,p,m,u)=>{let h=o.format===\"NHWC\",_=t.type.value,y=M(\"output\",t.type.tensor,n);if(o.kernelShape.length<=2){let g=\"\",x=\"\",$=\"\",v=r-(h?2:1);if(m?g=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i;\n if (xIndices[${v}] < 0 || xIndices[${v}]\n >= uniforms.x_shape[${v}]) {\n pad++;\n continue;\n }\n let x_val = x[${t.indicesToOffset(\"xIndices\")}];\n ${i}\n }`:g=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i;\n let x_val = x[${t.indicesToOffset(\"xIndices\")}];\n ${i}\n }`,o.kernelShape.length===2){let T=r-(h?3:2);u?x=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j;\n if (xIndices[${T}] < 0 || xIndices[${T}] >= uniforms.x_shape[${T}]) {\n pad += i32(uniforms.kw);\n continue;\n }\n `:x=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j;\n `,$=`\n }\n `}return`\n ${e.registerUniforms(d).declareVariables(t,y)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n\n let indices = ${y.offsetToIndices(\"global_idx\")};\n var xIndices = ${y.offsetToIndices(\"global_idx\")};\n\n var value = ${_}(${l});\n var pad = 0;\n ${x}\n ${g}\n ${$}\n ${a}\n\n output[global_idx] = value;\n }`}else{if(h)throw new Error(\"Pooling with kernelShape.length > 2 is not supported for NHWC format.\");let g=o.kernelShape.length,x=o.pads.length,$=\"\";return p?$=`\n if (xIndices[j] >= uniforms.x_shape[j]) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n let x_val = x[${t.indicesToOffset(\"xIndices\")}];\n ${i}\n }`:$=`\n }\n let x_val = x[${t.indicesToOffset(\"xIndices\")}];\n ${i}\n `,`\n ${e.registerUniforms(d).declareVariables(t,y)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n let indices = ${y.offsetToIndices(\"global_idx\")};\n var xIndices = ${y.offsetToIndices(\"global_idx\")};\n\n var offsets: array;\n\n var value = ${_}(${l});\n var pad = 0;\n var isPad = false;\n\n for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {\n var offset = i;\n for (var j = 0u; j < ${g-1}u; j++) {\n offsets[j] = offset / ${F(\"uniforms.kernelStrides\",\"j\",g)};\n offset -= offsets[j] * ${F(\"uniforms.kernelStrides\",\"j\",g)};\n }\n offsets[${g-1}] = offset;\n\n isPad = false;\n for (var j = ${r-g}u; j < ${r}u; j++) {\n xIndices[j] = indices[j] * ${F(\"uniforms.strides\",`j - ${r-g}u`,g)}\n + offsets[j - ${r-g}u] - ${F(\"uniforms.pads\",\"j - 2u\",x)};\n ${$}\n }\n ${a}\n\n output[global_idx] = value;\n }`}},nd=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,bh=e=>`${nd(e)};${e.countIncludePad}`,yh=e=>`${nd(e)};${e.storageOrder};${e.dilations}`,od=e=>({format:e.format,autoPad:[\"NOTSET\",\"VALID\",\"SAME_UPPER\",\"SAME_LOWER\"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),id=(e,t,r,n)=>{let[o,i]=ed(t,n,r),a=E(\"x\",t.dataType,t.dims.length),l=a.type.value,d=\"value += x_val;\",p=\"\";o.countIncludePad?p+=`value /= ${l}(uniforms.kernelSize);`:p+=`value /= ${l}(i32(uniforms.kernelSize) - pad);`;let[m,u,h,_,y]=td(i,o);m.push(...N(t.dims,i));let g=[\"rank\"];return{name:e,shaderCache:{hint:`${n.cacheKey};${h};${_};${y}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(k.size(i)/64)},programUniforms:m}),getShaderSource:x=>rd(x,a,t.dims.length,i.length,o,d,p,0,u,h,_,y)}},ad=e=>{let t=e.count_include_pad!==0,r=od(e);if(r.ceilMode!==0)throw new Error(\"using ceil() in shape computation is not yet supported for AveragePool\");let n={countIncludePad:t,...r,cacheKey:\"\"};return{...n,cacheKey:bh(n)}},sd=(e,t)=>{on(e.inputs),e.compute(id(\"AveragePool\",e.inputs[0],!1,t))},ud={autoPad:\"\",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},ld=e=>{let t=e.format;return{format:t,...ud,cacheKey:t}},dd=(e,t)=>{on(e.inputs),e.compute(id(\"GlobalAveragePool\",e.inputs[0],!0,t))},cd=(e,t,r,n)=>{let[o,i]=ed(t,n,r),a=`\n value = max(x_val, value);\n `,l=\"\",d=E(\"x\",t.dataType,t.dims.length),p=[\"rank\"],[m,u,h,_,y]=td(i,o);return m.push(...N(t.dims,i)),{name:e,shaderCache:{hint:`${n.cacheKey};${h};${_};${y}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(k.size(i)/64)},programUniforms:m}),getShaderSource:g=>rd(g,d,t.dims.length,i.length,o,a,l,t.dataType===10?-65504:-1e5,u,h,_,y)}},pd=(e,t)=>{on(e.inputs),e.compute(cd(\"MaxPool\",e.inputs[0],!1,t))},md=e=>{let t=e.storage_order,r=e.dilations,n=od(e);if(t!==0)throw new Error(\"column major storage order is not yet supported for MaxPool\");if(n.ceilMode!==0)throw new Error(\"using ceil() in shape computation is not yet supported for MaxPool\");let o={storageOrder:t,dilations:r,...n,cacheKey:\"\"};return{...o,cacheKey:yh(o)}},fd=e=>{let t=e.format;return{format:t,...ud,cacheKey:t}},hd=(e,t)=>{on(e.inputs),e.compute(cd(\"GlobalMaxPool\",e.inputs[0],!0,t))}});var wh,vh,bd,yd,_d=R(()=>{\"use strict\";te();oe();Se();ae();wh=(e,t)=>{if(e.length<2||e.length>3)throw new Error(\"DequantizeLinear requires 2 or 3 inputs.\");if(e.length===3&&e[1].dims===e[2].dims)throw new Error(\"x-scale and x-zero-point must have the same shape.\");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error(\"x and x-zero-point must have the same data type.\");if(e[0].dataType===6&&e.length>2)throw new Error(\"In the case of dequantizing int32 there is no zero point.\");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error(\"scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.\");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error(\"x and x-zero-point must have the same data type.\");if(e[1].dims.length!==e[2].dims.length)throw new Error(\"scale and zero-point inputs must have the same rank.\");if(!e[1].dims.map((r,n)=>r===e[2].dims[n]).reduce((r,n)=>r&&n,!0))throw new Error(\"scale and zero-point inputs must have the same shape.\")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error(\"blockSize must be set only for block quantization.\");if(!e[1].dims.map((o,i)=>i===t.axis||o===e[0].dims[i]).reduce((o,i)=>o&&i,!0))throw new Error(\"For block qunatization, scale input shape to match the input shape except for the axis\");if(e[1].dims.length!==e[0].dims.length)throw new Error(\"For block qunatization the scale input rank must be the same as the x rank.\");let r=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(n-1)-1))throw new Error(\"blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].\")}},vh=(e,t)=>{let r=k.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,o=n===3,i=e[0].dims,a=e[1].dataType,l=k.size(i),d=n===3||n===2,p=d?[Math.ceil(k.size(e[0].dims)/4)]:e[0].dims,m=e[1].dims,u=e.length>2?e[2]:void 0,h=u?d?[Math.ceil(k.size(u.dims)/4)]:u.dims:void 0,_=m.length===0||m.length===1&&m[0]===1,y=_===!1&&m.length===1,g=me(l),x=_&&(!d||g===4),$=x?g:1,v=x&&!d?g:1,S=E(\"input\",d?12:n,p.length,v),T=E(\"scale\",a,m.length),C=u?E(\"zero_point\",d?12:n,h.length):void 0,A=M(\"output\",a,i.length,$),P=[S,T];C&&P.push(C);let O=[p,m];u&&O.push(h);let U=[{type:12,data:l/$},{type:12,data:r},{type:12,data:t.blockSize},...N(...O,i)],G=q=>{let K=[{name:\"output_size\",type:\"u32\"},{name:\"axis\",type:\"u32\"},{name:\"block_size\",type:\"u32\"}];return`\n ${q.registerUniforms(K).declareVariables(...P,A)}\n ${q.mainStart()}\n ${q.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let output_indices = ${A.offsetToIndices(\"global_idx\")};\n\n // Set input x\n ${(()=>d?`\n let input = ${S.getByOffset(\"global_idx / 4\")};\n let x_vec = ${o?\"unpack4xI8(input)\":\"unpack4xU8(input)\"};\n let x_value = ${$===1?\"x_vec[global_idx % 4]\":\"x_vec\"};`:`let x_value = ${S.getByOffset(\"global_idx\")};`)()};\n\n // Set scale input\n ${(()=>_?`let scale_value= ${T.getByOffset(\"0\")}`:y?`\n let scale_index = ${A.indicesGet(\"output_indices\",\"uniforms.axis\")};\n let scale_value= ${T.getByOffset(\"scale_index\")};`:`\n var scale_indices: ${T.type.indices} = output_indices;\n let index = ${T.indicesGet(\"scale_indices\",\"uniforms.axis\")} / uniforms.block_size;\n ${T.indicesSet(\"scale_indices\",\"uniforms.axis\",\"index\")};\n let scale_value= ${T.getByIndices(\"scale_indices\")};`)()};\n\n // Set zero-point input\n ${(()=>C?_?d?`\n let zero_point_input = ${C.getByOffset(\"0\")};\n let zero_point_vec = ${o?\"unpack4xI8(zero_point_input)\":\"unpack4xU8(zero_point_input)\"};\n let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${C.getByOffset(\"0\")}`:y?d?`\n let zero_point_index = ${A.indicesGet(\"output_indices\",\"uniforms.axis\")};\n let zero_point_input = ${C.getByOffset(\"zero_point_index / 4\")};\n let zero_point_vec = ${o?\"unpack4xI8(zero_point_input)\":\"unpack4xU8(zero_point_input)\"};\n let zero_point_value = zero_point_vec[zero_point_index % 4]`:`\n let zero_point_index = ${A.indicesGet(\"output_indices\",\"uniforms.axis\")};\n let zero_point_value = ${C.getByOffset(\"zero_point_index\")};`:d?`\n let zero_point_offset = ${T.indicesToOffset(\"scale_indices\")};\n let zero_point_input = ${C.getByOffset(\"zero_point_offset / 4\")};\n let zero_point_vec = ${o?\"unpack4xI8(zero_point_input)\":\"unpack4xU8(zero_point_input)\"};\n let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${C.getByIndices(\"scale_indices\")};`:`let zero_point_value = ${d?o?\"i32\":\"u32\":S.type.value}(0);`)()};\n // Compute and write output\n ${A.setByOffset(\"global_idx\",`${A.type.value}(x_value - zero_point_value) * scale_value`)};\n }`};return{name:\"DequantizeLinear\",shaderCache:{hint:t.cacheKey,inputDependencies:C?[\"rank\",\"rank\",\"rank\"]:[\"rank\",\"rank\"]},getShaderSource:G,getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:Math.ceil(l/$/64),y:1,z:1},programUniforms:U})}},bd=(e,t)=>{wh(e.inputs,t),e.compute(vh(e.inputs,t))},yd=e=>J({axis:e.axis,blockSize:e.blockSize})});var $h,xh,wd,vd=R(()=>{\"use strict\";We();te();ae();$h=(e,t,r)=>{let n=e===t,o=et&&r>0;if(n||o||i)throw new Error(\"Range these inputs' contents are invalid.\")},xh=(e,t,r,n)=>{let o=Math.abs(Math.ceil((t-e)/r)),i=[o],a=o,l=[{type:12,data:a},{type:n,data:e},{type:n,data:r},...N(i)],d=p=>{let m=M(\"output\",n,i.length),u=m.type.value,h=[{name:\"outputSize\",type:\"u32\"},{name:\"start\",type:u},{name:\"delta\",type:u}];return`\n ${p.registerUniforms(h).declareVariables(m)}\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n output[global_idx] = uniforms.start + ${u}(global_idx) * uniforms.delta;\n }`};return{name:\"Range\",shaderCache:{hint:`${n}`},getShaderSource:d,getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l})}},wd=e=>{let t=0,r=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),we.webgpu.validateInputContent&&$h(t,r,n),e.compute(xh(t,r,n,e.inputs[0].dataType),{inputs:[]})}});var Sh,Th,$d,xd,Sd=R(()=>{\"use strict\";te();oe();Se();ae();Sh=(e,t,r,n)=>{if(e!==\"none\"&&n!==\"i32\"&&n!==\"u32\"&&n!==\"f32\")throw new Error(`Input ${n} is not supported with reduction ${e}.`);let o=`{\n var oldValue = 0;\n loop {\n let newValueF32 =`,i=`;\n let newValue = bitcast(newValueF32);\n let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue);\n if res.exchanged {\n break;\n }\n oldValue = res.old_value;\n }\n }`;switch(e){case\"none\":return`${t}=${r};`;case\"add\":return n===\"i32\"||n===\"u32\"?`atomicAdd(&${t}, bitcast<${n}>(${r}));`:`\n ${o}bitcast<${n}>(oldValue) + (${r})${i}`;case\"max\":return n===\"i32\"||n===\"u32\"?`atomicMax(&${t}, bitcast<${n}>(${r}));`:`\n ${o}max(bitcast(oldValue), (${r}))${i}`;case\"min\":return n===\"i32\"||n===\"u32\"?`atomicMin(&${t}, bitcast<${n}>(${r}));`:`${o}min(bitcast<${n}>(oldValue), (${r}))${i}`;case\"mul\":return`${o}(bitcast<${n}>(oldValue) * (${r}))${i}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Th=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r,i=1,a=Math.ceil(k.size(n)/i),l=n[n.length-1],d=k.sizeFromDimension(r,l),p=[{type:12,data:a},{type:12,data:l},{type:12,data:d},...N(e[1].dims,e[2].dims,o)],m=u=>{let h=E(\"indices\",e[1].dataType,e[1].dims.length),_=E(\"updates\",e[2].dataType,e[2].dims.length,i),y=t.reduction!==\"none\"&&t.reduction!==\"\"?es(\"output\",e[0].dataType,o.length):M(\"output\",e[0].dataType,o.length,i);return`\n ${u.registerUniform(\"output_size\",\"u32\").registerUniform(\"last_index_dimension\",\"u32\").registerUniform(\"num_updates_elements\",\"u32\").declareVariables(h,_,y)}\n ${u.mainStart()}\n ${u.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n var data_offset = 0u;\n let indices_start = uniforms.last_index_dimension * global_idx;\n let indices_end = indices_start + uniforms.last_index_dimension;\n for (var i = indices_start; i < indices_end; i++) {\n var index = i32(indices[i].x);\n ${e[0].dims.length===1?`\n let element_count_dim = uniforms.output_strides;\n let dim_value = uniforms.output_shape;`:`\n let element_count_dim = uniforms.output_strides[i - indices_start];\n let dim_value = uniforms.output_shape[i - indices_start + uniforms.last_index_dimension];`}\n if (index >= 0) {\n if (index >= i32(dim_value)) {\n index = i32(dim_value - 1);\n }\n } else {\n if (index < -i32(dim_value)) {\n index = 0;\n } else {\n index += i32(dim_value);\n }\n }\n data_offset += u32((u32(index) * element_count_dim));\n }\n\n for (var i = 0u; i < uniforms.num_updates_elements; i++) {\n let value = updates[uniforms.num_updates_elements * global_idx + i];\n ${Sh(t.reduction,\"output[data_offset + i]\",\"value\",y.type.value)}\n }\n\n }`};return{name:\"ScatterND\",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:[\"rank\",\"rank\"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p}),getShaderSource:m}},$d=e=>J({reduction:e.reduction}),xd=(e,t)=>{e.compute(Th(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}});var Ih,Ch,Ah,kh,Eh,Ph,zh,Oh,Bh,Dh,Mh,Td,Rh,Uh,Nh,Vh,Wh,Id,Cd,Ad=R(()=>{\"use strict\";te();oe();Se();ae();Ih=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error(\"Resize requires scales input values to be positive\")})),e.length>0){if(t.mode===\"linear\"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and\n one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode===\"cubic\"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error(\"Resize requires scales input size to be 2 or 4 for cubic mode\")}},Ch=(e,t,r)=>{t.every(o=>o>=0&&o{throw new Error(\"Resize requires axes input values to be positive and less than rank\")}));let n=new Array(r).fill(1);return t.forEach((o,i)=>n[o]=e[i]),n},Ah=(e,t,r,n,o,i)=>{let[a,l,d]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],p=e[0].dims.length;if(a>0&&e.length>a&&e[a].dims.length>0)e[a].getFloat32Array().forEach(m=>i.push(m));else if(t.coordinateTransformMode===\"tf_crop_and_resize\")throw new Error(\"Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize\");if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0){if(e[l].getFloat32Array().forEach(m=>n.push(m)),n.length!==0&&n.length!==p&&r>=18&&n.length!==t.axes.length)throw new Error(\"Resize requires scales input size to be same as input rank or axes size for opset 18 and up\");Ih(n,t),t.axes.length>0&&Ch(n,t.axes,p).forEach((m,u)=>n[u]=m)}if(d>0&&e.length>d&&e[d].dims.length===1&&e[d].dims[0]>0&&(e[d].getBigInt64Array().forEach(m=>o.push(Number(m))),o.length!==0&&o.length!==p&&r>=18&&o.length!==t.axes.length))throw new Error(\"Resize requires sizes input size to be same as input rank or axes size for opset 18 and up\");if(t.axes.length>0){if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires \"scales\" input size to be of axes rank when axes attributes is specified');if(o.length!==0&&o.length!==t.axes.length)throw new Error('Resize requires \"sizes\" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<\"u\"&&typeof o<\"u\"&&n.length>0&&o.length>p)throw new Error(\"Resize requires only of scales or sizes to be specified\")},kh=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,\n lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case\"asymmetric\":return`return ${t}(xResized) / ${t}(xScale);`;case\"pytorch_half_pixel\":return`if (lengthResized > 1) {\n return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;\n } else {\n return 0.0;\n }`;case\"tf_half_pixel_for_nn\":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case\"align_corners\":return`if (lengthResized == 1) {\n return 0.0;\n } else {\n // The whole part and the fractional part are calculated separately due to inaccuracy of floating\n // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an\n // offset-by-one error later in floor().\n let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1));\n let fract =\n ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1);\n return whole + fract;\n }`;case\"tf_crop_and_resize\":return`if (lengthResized > 1) {\n return ${t}(roiStart) * ${t}(lengthOriginal - 1) +\n (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /\n ${t}(lengthResized - 1);\n } else {\n return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);\n }`;case\"half_pixel_symmetric\":return`const outputWidth = ${t}xScale * ${t}(lengthResized);\n const adjustment = ${t}(lengthResized) / outputWidth;\n const center = ${t}(lengthOriginal) / 2;\n const offset = center * (1 - adjustment);\n return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case\"half_pixel\":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+\"}\",Eh=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case\"round_prefer_ceil\":return\"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }\";case\"floor\":return\"return floor(xOriginal);\";case\"ceil\":return\"return ceil(xOriginal);\";case\"round_prefer_floor\":return\"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }\";case\"simple\":default:if(t<11)return\"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }\";throw new Error(`Nearest mode ${e} is not supported`)}})()+\"}\",Ph=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),o=e.length===0?n:e.slice();return t.length>0?(t.forEach((i,a)=>{n[i]=o[a],n[a+r]=o[t.length+a]}),n):o},zh=(e,t,r,n)=>{let o=[];if(r.length>0)if(n.length>0){if(e.forEach(i=>o.push(i)),Math.max(...n)>e.length)throw new Error(\"axes is out of bound\");n.forEach((i,a)=>o[i]=r[a])}else r.forEach(i=>o.push(i));else{if(t.length===0)throw new Error(\"Resize requires either scales or sizes.\");o=e.map((i,a)=>Math.round(i*t[a]))}return o},Oh=(e,t,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case\"not_larger\":return r.axes.length>0?Math.min(...r.axes.map(i=>t[i]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case\"not_smaller\":return r.axes.length>0?Math.max(...r.axes.map(i=>t[i]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let o=e.slice();return r.axes.length>0?(r.axes.forEach(i=>t[i]=n),r.axes.forEach(i=>o[i]=Math.round(e[i]*t[i]))):(t.fill(n,0,t.length),o.forEach((i,a)=>o[a]=Math.round(i*t[a]))),o},Bh=(e,t,r,n,o)=>`\n fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> {\n var original_indices: array<${e.type.value}, ${r.length}>;\n for (var i:u32 = 0; i < ${r.length}; i++) {\n var output_index = ${e.indicesGet(\"output_indices\",\"i\")};\n var scale = ${F(\"uniforms.scales\",\"i\",n)};\n var roi_low = ${F(\"uniforms.roi\",\"i\",o)};\n var roi_hi = ${F(\"uniforms.roi\",`i + ${t.length}`,o)};\n if (scale == 1.0) {\n original_indices[i] = ${e.type.value}(output_index);\n } else {\n var input_shape_i = ${F(\"uniforms.input_shape\",\"i\",t.length)};\n var output_shape_i = ${F(\"uniforms.output_shape\",\"i\",r.length)};\n original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n }\n }\n return original_indices;\n }`,Dh=(e,t,r,n,o,i,a)=>`\n fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n for (var i:u32 = 0; i < ${n.length}; i++) {\n var output_index = ${t.indicesGet(\"output_indices\",\"i\")};\n var input_index: u32;\n var scale = ${F(\"uniforms.scales\",\"i\",o)};\n if (scale == 1.0) {\n input_index = output_index;\n } else {\n var roi_low = ${F(\"uniforms.roi\",\"i\",i)};\n var roi_hi = ${F(\"uniforms.roi\",`i + ${r.length}`,i)};\n var input_shape_i = ${F(\"uniforms.input_shape\",\"i\",r.length)};\n var output_shape_i = ${F(\"uniforms.output_shape\",\"i\",n.length)};\n var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n if (!${a} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {\n if (original_idx < 0) {\n input_index = 0;\n } else if (original_idx > ${t.type.value}(input_shape_i - 1)) {\n input_index = input_shape_i - 1;\n } else {\n input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));\n }\n } else {\n input_index = u32(original_idx);\n }\n }\n ${e.indicesSet(\"input_indices\",\"i\",\" input_index\")}\n }\n return input_indices;\n }`,Mh=(e,t)=>`\n fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {\n for (var i:u32 = 0; i < ${t.length}; i++) {\n var input_index = ${e.indicesGet(\"input_indices\",\"i\")};\n if (input_index < 0 || input_index >= ${F(\"uniforms.input_shape\",\"i\",t.length)}) {\n return false;\n }\n }\n return true;\n }`,Td=(e,t,r,n)=>e.rank>n?`\n ${e.indicesSet(\"input_indices\",t,\"channel\")};\n ${e.indicesSet(\"input_indices\",r,\"batch\")};\n`:\"\",Rh=(e,t,r,n,o)=>{let[a,l,d,p]=r.length===2?[-1,0,1,-1]:[0,2,3,1],m=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${m} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet(\"input_indices\",l,`max(0, min(row, ${r[l]} - 1))`)};\n ${e.indicesSet(\"input_indices\",d,`max(0, min(col, ${r[d]} - 1))`)};\n ${Td(e,p,a,2)}\n return ${e.getByIndices(\"input_indices\")};\n }\n\n fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${m} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var row:${m} = originalIndices[${l}];\n var col:${m} = originalIndices[${d}];\n ${n?`if (row < 0 || row > (${r[l]} - 1) || col < 0 || col > (${r[d]} - 1)) {\n return ${o};\n }`:\"\"};\n row = max(0, min(row, ${r[l]} - 1));\n col = max(0, min(col, ${r[d]} - 1));\n var row1: u32 = u32(row);\n var col1: u32 = u32(col);\n var row2: u32 = u32(row + 1);\n var col2: u32 = u32(col + 1);\n var channel: u32 = ${r.length>2?`u32(originalIndices[${p}])`:\"0\"};\n var batch: u32 = ${r.length>2?`u32(originalIndices[${a}])`:\"0\"};\n var x11: ${m} = getInputValue(batch, channel, row1, col1);\n var x12: ${m} = getInputValue(batch, channel, row1, col2);\n var x21: ${m} = getInputValue(batch, channel, row2, col1);\n var x22: ${m} = getInputValue(batch, channel, row2, col2);\n var dx1: ${m} = abs(row - ${m}(row1));\n var dx2: ${m} = abs(${m}(row2) - row);\n var dy1: ${m} = abs(col - ${m}(col1));\n var dy2: ${m} = abs(${m}(col2) - col);\n if (row1 == row2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (col1 == col2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);\n }`},Uh=(e,t,r,n,o,i,a,l,d,p)=>{let m=r.length===2,u=!0,[h,_]=m?[0,1]:u?[2,3]:[1,2],y=e.type.value,g=x=>{let $=x===h?\"row\":\"col\";return`\n fn ${$}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${y} {\n var output_index = ${t.indicesGet(\"output_indices\",x)};\n var originalIdx: ${y} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[x]},\n ${n[x]}, ${r[x]}, ${i[x]}, ${i[x]} + ${r.length});\n var fractOriginalIdx: ${y} = originalIdx - floor(originalIdx);\n var coefs = getCubicInterpolationCoefs(fractOriginalIdx);\n\n if (${l} && (originalIdx < 0 || originalIdx > (${r[x]} - 1))) {\n return ${d};\n }\n var data: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0);\n for (var i: i32 = -1; i < 3; i++) {\n var ${$}: ${y} = originalIdx + ${y}(i);\n if (${$} < 0 || ${$} >= ${r[x]}) {\n ${(()=>p?`coefs[i + 1] = 0.0;\n continue;`:l?`return ${d};`:`${$} = max(0, min(${$}, ${r[x]} - 1));`)()};\n }\n var input_indices_copy: ${e.type.indices} = input_indices;\n ${e.indicesSet(\"input_indices_copy\",x,`u32(${$})`)};\n data[i + 1] = ${x===h?e.getByIndices(\"input_indices_copy\"):\"rowCubicInterpolation(input_indices_copy, output_indices)\"};\n }\n return cubicInterpolation1D(data, coefs);\n }`};return`\n ${g(h)};\n ${g(_)};\n fn getCubicInterpolationCoefs(s: ${y}) -> array<${y}, 4> {\n var absS = abs(s);\n var coeffs: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0);\n var oneMinusAbsS: ${y} = 1.0 - absS;\n var twoMinusAbsS: ${y} = 2.0 - absS;\n var onePlusAbsS: ${y} = 1.0 + absS;\n coeffs[0] = ((${a} * onePlusAbsS - 5 * ${a}) * onePlusAbsS + 8 * ${a}) * onePlusAbsS - 4 * ${a};\n coeffs[1] = ((${a} + 2) * absS - (${a} + 3)) * absS * absS + 1;\n coeffs[2] = ((${a} + 2) * oneMinusAbsS - (${a} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;\n coeffs[3] = ((${a} * twoMinusAbsS - 5 * ${a}) * twoMinusAbsS + 8 * ${a}) * twoMinusAbsS - 4 * ${a};\n return coeffs;\n }\n\n fn cubicInterpolation1D(x: array<${y}, 4>, coefs: array<${y}, 4>) -> ${y} {\n var coefsSum: ${y} = coefs[0] + coefs[1] + coefs[2] + coefs[3];\n return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;\n }\n\n fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${y} {\n var input_indices: ${e.type.indices} = output_indices;\n return colCubicInterpolation(input_indices, output_indices);\n }\n `},Nh=(e,t,r,n,o)=>{let[a,l,d,p,m]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],u=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${u} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet(\"input_indices\",l,`max(0, min(depth, ${r[l]} - 1))`)};\n ${e.indicesSet(\"input_indices\",d,`max(0, min(height, ${r[d]} - 1))`)};\n ${e.indicesSet(\"input_indices\",p,`max(0, min(width, ${r[p]} - 1))`)};\n ${Td(e,m,a,3)}\n return ${e.getByIndices(\"input_indices\")};\n }\n\n fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${u} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var depth:${u} = originalIndices[${l}];\n var height:${u} = originalIndices[${d}];\n var width:${u} = originalIndices[${p}];\n ${n?`if (depth < 0 || depth > (${r[l]} - 1) || height < 0 || height > (${r[d]} - 1) || width < 0 || (width > ${r[p]} - 1)) {\n return ${o};\n }`:\"\"};\n\n depth = max(0, min(depth, ${r[l]} - 1));\n height = max(0, min(height, ${r[d]} - 1));\n width = max(0, min(width, ${r[p]} - 1));\n var depth1: u32 = u32(depth);\n var height1: u32 = u32(height);\n var width1: u32 = u32(width);\n var depth2: u32 = u32(depth + 1);\n var height2: u32 = u32(height + 1);\n var width2: u32 = u32(width + 1);\n var channel: u32 = ${r.length>3?`u32(originalIndices[${m}])`:\"0\"};\n var batch: u32 = ${r.length>3?`u32(originalIndices[${a}])`:\"0\"};\n\n var x111: ${u} = getInputValue(batch, channel, depth1, height1, width1);\n var x112: ${u} = getInputValue(batch, channel, depth1, height1, width2);\n var x121: ${u} = getInputValue(batch, channel, depth1, height2, width1);\n var x122: ${u} = getInputValue(batch, channel, depth1, height2, width2);\n var x211: ${u} = getInputValue(batch, channel, depth2, height1, width1);\n var x212: ${u} = getInputValue(batch, channel, depth2, height1, width2);\n var x221: ${u} = getInputValue(batch, channel, depth2, height2, width1);\n var x222: ${u} = getInputValue(batch, channel, depth2, height2, width2);\n var dx1: ${u} = abs(depth - ${u}(depth1));\n var dx2: ${u} = abs(${u}(depth2) - depth);\n var dy1: ${u} = abs(height - ${u}(height1));\n var dy2: ${u} = abs(${u}(height2) - height);\n var dz1: ${u} = abs(width - ${u}(width1));\n var dz2: ${u} = abs(${u}(width2) - width);\n if (depth1 == depth2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (height1 == height2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n if (width1 == width2) {\n dz1 = 0.5;\n dz2 = 0.5;\n }\n return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +\n x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);\n }`},Vh=(e,t,r,n,o,i)=>{let a=e.dims,l=Ph(i,t.axes,a.length),d=zh(a,n,o,t.axes),p=n.slice();n.length===0&&(p=a.map((v,S)=>v===0?1:d[S]/v),t.keepAspectRatioPolicy!==\"stretch\"&&(d=Oh(a,p,t)));let m=M(\"output\",e.dataType,d.length),u=E(\"input\",e.dataType,a.length),h=k.size(d),_=a.length===d.length&&a.every((v,S)=>v===d[S]),y=t.coordinateTransformMode===\"tf_crop_and_resize\",g=t.extrapolationValue,x=u.type.value,$=v=>`\n ${_?\"\":`\n ${kh(t.coordinateTransformMode,x)};\n ${(()=>{switch(t.mode){case\"nearest\":return`\n ${Mh(u,a)};\n ${Eh(t.nearestMode,r,x)};\n ${Dh(u,m,a,d,p.length,l.length,y)};\n `;case\"linear\":return`\n ${Bh(m,a,d,p.length,l.length)};\n ${(()=>{if(a.length===2||a.length===4)return`${Rh(u,m,a,y,g)}`;if(a.length===3||a.length===5)return`${Nh(u,m,a,y,g)}`;throw Error(\"Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.\")})()};\n `;case\"cubic\":return`\n ${(()=>{if(a.length===2||a.length===4)return`${Uh(u,m,a,d,p,l,t.cubicCoeffA,y,t.extrapolationValue,t.excludeOutside)}`;throw Error(\"Cubic mode only supports input dims 2 and 4 are supported in linear mode.\")})()};\n `;default:throw Error(\"Invalid resize mode\")}})()};\n `}\n ${v.registerUniform(\"output_size\",\"u32\").registerUniform(\"scales\",\"f32\",p.length).registerUniform(\"roi\",\"f32\",l.length).declareVariables(u,m)}\n ${v.mainStart()}\n ${v.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n ${_?\"output[global_idx] = input[global_idx];\":`\n let output_indices = ${m.offsetToIndices(\"global_idx\")};\n var input_indices: ${u.type.indices};\n ${(()=>{switch(t.mode){case\"nearest\":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);\n if (checkInputIndices(input_indices)) {\n output[global_idx] = ${u.getByIndices(\"input_indices\")};\n } else {\n output[global_idx] = ${t.extrapolationValue};\n }`;case\"linear\":return`output[global_idx] = ${a.length===2||a.length===4?\"bilinearInterpolation\":\"trilinearInterpolation\"}(output_indices);`;case\"cubic\":return\"output[global_idx] = bicubicInterpolation(output_indices);\";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};\n`}\n }`;return{name:\"Resize\",shaderCache:{hint:`${t.cacheKey}|${r}|${p.length>0?p:\"\"}|${o.length>0?o:\"\"}|${l.length>0?l:\"\"}|${_}|${a}`,inputDependencies:[\"rank\"]},getShaderSource:$,getRunData:()=>({outputs:[{dims:d,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:[{type:12,data:h},{type:1,data:p},{type:1,data:l},...N(a,d)]})}},Wh=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Id=(e,t)=>{let r=[],n=[],o=[],i=Wh(e);if(t.antialias!==0)throw Error(\"Only default value (0) for Antialias attribute is supported\");Ah(e.inputs,t,i,r,n,o),e.compute(Vh(e.inputs[0],t,i,r,n,o),{inputs:[0]})},Cd=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,o=e.cubicCoeffA,i=e.excludeOutside!==0,a=e.extrapolationValue,l=e.keepAspectRatioPolicy,d=e.mode,p=e.nearestMode===\"\"?\"simple\":e.nearestMode;return J({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:o,excludeOutside:i,extrapolationValue:a,keepAspectRatioPolicy:l,mode:d,nearestMode:p})}});var Lh,Gh,kd,Ed=R(()=>{\"use strict\";te();oe();Se();ae();Lh=(e,t)=>{let[r,n,o,i]=e,{numHeads:a,rotaryEmbeddingDim:l}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!k.areEqual(n.dims,[])&&!k.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(!k.areEqual(o.dims,i.dims))throw new Error(\"Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape\");if(l>0&&a===0)throw new Error(\"num_heads must be provided if rotary_embedding_dim is specified\");let d=r.dims[0],p=r.dims[r.dims.length-2],m=o.dims[0],u=k.sizeFromDimension(r.dims,1)/p,h=l===0?o.dims[1]*2:u/a;if(l>h)throw new Error(\"rotary_embedding_dim must be less than or equal to head_size\");if(n.dims.length===2){if(d!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(p!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(h/2!==o.dims[1]&&l/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(p>m)throw new Error(\"Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported\")},Gh=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:o,scale:i}=t,a=e[0].dims[0],l=k.sizeFromDimension(e[0].dims,1),d=e[0].dims[e[0].dims.length-2],p=l/d,m=e[2].dims[1],u=o===0?m*2:p/n,h=new Array(a,d,p/u,u-m),_=k.computeStrides(h),y=[{type:1,data:i},{type:12,data:h},{type:12,data:_},...e[0].dims.length===3?new Array({type:12,data:[l,p,u,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[l,u,d*u,1]}):[],...N(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],g=x=>{let $=E(\"input\",e[0].dataType,e[0].dims.length),v=E(\"position_ids\",e[1].dataType,e[1].dims.length),S=E(\"cos_cache\",e[2].dataType,e[2].dims.length),T=E(\"sin_cache\",e[3].dataType,e[3].dims.length),C=M(\"output\",e[0].dataType,e[0].dims.length);return x.registerUniforms([{name:\"scale\",type:\"f32\"},{name:\"global_shape\",type:\"u32\",length:h.length},{name:\"global_strides\",type:\"u32\",length:_.length},{name:\"input_output_strides\",type:\"u32\",length:_.length}]),`\n ${x.declareVariables($,v,S,T,C)}\n\n ${x.mainStart(Ct)}\n let half_rotary_emb_dim = uniforms.${S.name}_shape[1];\n let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;\n let size = uniforms.global_shape[0] * uniforms.global_strides[0];\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(\"size\")}\n\n if (bsnh[3] < half_rotary_emb_dim) {\n let position_ids_idx =\n ${v.broadcastedIndicesToOffset(\"bsnh.xy\",M(\"\",v.type.tensor,2))};\n let position_id =\n u32(${v.getByOffset(\"position_ids_idx\")}) + select(0, bsnh[1], position_ids_idx == 0);\n let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r});\n let j = i + select(half_rotary_emb_dim, 1, ${r});\n let re = ${$.getByOffset(\"i\")} * ${S.get(\"position_id\",\"bsnh[3]\")} -\n ${$.getByOffset(\"j\")} * ${T.get(\"position_id\",\"bsnh[3]\")};\n ${C.setByOffset(\"i\",\"re\")}\n let im = ${$.getByOffset(\"i\")} * ${T.get(\"position_id\",\"bsnh[3]\")} +\n ${$.getByOffset(\"j\")} * ${S.get(\"position_id\",\"bsnh[3]\")};\n ${C.setByOffset(\"j\",\"im\")}\n } else {\n let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;\n ${C.setByOffset(\"k\",$.getByOffset(\"k\"))}\n }\n }`};return{name:\"RotaryEmbedding\",shaderCache:{hint:J({interleaved:r}).cacheKey,inputDependencies:[\"rank\",\"rank\",\"rank\",\"rank\"]},getShaderSource:g,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k.size(h)/Ct)},programUniforms:y})}},kd=(e,t)=>{Lh(e.inputs,t),e.compute(Gh(e.inputs,t))}});var Hh,Fh,Pd,zd=R(()=>{\"use strict\";te();oe();ae();Hh=e=>{if(!e||e.length<3)throw new Error(\"layerNorm requires at least 3 inputs.\");let t=e[0],r=e[1],n=e[2];if(t.dataType!==r.dataType||t.dataType!==n.dataType)throw new Error(\"All inputs must have the same data type\");if(t.dims.length!==3&&t.dims.length!==2)throw new Error(\"Input must be 2D or 3D\");if(r.dims.length!==3&&r.dims.length!==2)throw new Error(\"Skip must be 2D or 3D\");let o=t.dims[t.dims.length-1],i=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==o)throw new Error(\"Skip must have the same hidden size as input\");if(r.dims[r.dims.length-2]!==i)throw new Error(\"Skip must have the same sequence length as input\");if(n.dims.length!==1)throw new Error(\"Gamma must be 1D\");if(n.dims[n.dims.length-1]!==o)throw new Error(\"Gamma must have the same hidden size as input\");if(e.length>3){let a=e[3];if(a.dims.length!==1)throw new Error(\"Beta must be 1D\");if(a.dims[a.dims.length-1]!==o)throw new Error(\"Beta must have the same hidden size as input\")}if(e.length>4){let a=e[4];if(a.dims.length!==1)throw new Error(\"Bias must be 1D\");if(a.dims[a.dims.length-1]!==o)throw new Error(\"Bias must have the same hidden size as input\")}},Fh=(e,t,r,n)=>{let o=t.simplified,i=e[0].dims,a=k.size(i),l=i,d=a,p=i.slice(-1)[0],m=n?i.slice(0,-1).concat(1):[],u=!o&&e.length>3,h=e.length>4,_=n&&r>1,y=n&&r>2,g=r>3,x=64,$=me(p),v=[{type:12,data:d},{type:12,data:$},{type:12,data:p},{type:1,data:t.epsilon}],S=C=>{let A=[{name:\"output_size\",type:\"u32\"},{name:\"components\",type:\"u32\"},{name:\"hidden_size\",type:\"u32\"},{name:\"epsilon\",type:\"f32\"}],P=[E(\"x\",e[0].dataType,e[0].dims,$),E(\"skip\",e[1].dataType,e[1].dims,$),E(\"gamma\",e[2].dataType,e[2].dims,$)];u&&P.push(E(\"beta\",e[3].dataType,e[3].dims,$)),h&&P.push(E(\"bias\",e[4].dataType,e[4].dims,$)),P.push(M(\"output\",e[0].dataType,l,$)),_&&P.push(M(\"mean_output\",1,m)),y&&P.push(M(\"inv_std_output\",1,m)),g&&P.push(M(\"input_skip_bias_sum\",e[0].dataType,l,$));let O=ye(e[0].dataType),U=ye(1,$);return`\n\n ${C.registerUniforms(A).declareVariables(...P)}\n var sum_shared : array<${U}, ${x}>;\n var sum_squared_shared : array<${U}, ${x}>;\n\n ${C.mainStart([x,1,1])}\n let ix = local_id.x;\n let iy = global_id.x / ${x};\n\n let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;\n var stride = hidden_size_vectorized / ${x};\n let offset = ix * stride + iy * hidden_size_vectorized;\n let offset1d = stride * ix;\n if (ix == ${x-1}) {\n stride = hidden_size_vectorized - stride * ix;\n }\n for (var i: u32 = 0; i < stride; i++) {\n let skip_value = skip[offset + i];\n let bias_value = ${h?\"bias[offset1d + i]\":O+\"(0.0)\"};\n let input_value = x[offset + i];\n let value = input_value + skip_value + bias_value;\n ${g?\"input_skip_bias_sum[offset + i] = value;\":\"\"}\n output[offset + i] = value;\n let f32_value = ${At(O,$,\"value\")};\n sum_shared[ix] += f32_value;\n sum_squared_shared[ix] += f32_value * f32_value;\n }\n workgroupBarrier();\n\n var reduce_size : u32 = ${x};\n for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) {\n reduce_size = curr_size + (reduce_size & 1);\n if (ix < curr_size) {\n sum_shared[ix] += sum_shared[ix + reduce_size];\n sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size];\n }\n workgroupBarrier();\n }\n\n let sum = sum_shared[0];\n let square_sum = sum_squared_shared[0];\n let mean = ${He(\"sum\",$)} / f32(uniforms.hidden_size);\n let inv_std_dev = inverseSqrt(${He(\"square_sum\",$)} / f32(uniforms.hidden_size) ${o?\"\":\"- mean * mean\"} + uniforms.epsilon);\n ${_?\"mean_output[global_idx] = mean;\":\"\"}\n ${y?\"inv_std_output[global_idx] = inv_std_dev;\":\"\"}\n\n for (var i: u32 = 0; i < stride; i++) {\n output[offset + i] = (output[offset + i] ${o?\"\":`- ${O}(mean)`}) *\n ${O}(inv_std_dev) * gamma[offset1d + i]\n ${u?\"+ beta[offset1d + i]\":\"\"};\n }\n }`},T=[{dims:l,dataType:e[0].dataType}];return r>1&&T.push({dims:m,dataType:1}),r>2&&T.push({dims:m,dataType:1}),r>3&&T.push({dims:i,dataType:e[0].dataType}),{name:\"SkipLayerNormalization\",shaderCache:{hint:`${$};${_};${y};${g}`,inputDependencies:e.map((C,A)=>\"type\")},getShaderSource:S,getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(d/p)},programUniforms:v})}},Pd=(e,t)=>{Hh(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(Fh(e.inputs,t,e.outputCount,!1),{outputs:n})}});var qh,an,jh,Od,Kh,Yh,Bd,Dd,Md=R(()=>{\"use strict\";te();oe();Se();ae();qh=(e,t)=>{if(!e||e.length<1)throw new Error(\"too few inputs\");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error(\"axes, starts and ends must have the same length\")}else if(t.starts.length!==t.ends.length)throw new Error(\"starts and ends must have the same length\");e.slice(1).forEach((r,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},an=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>r.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>r.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},jh=(e,t)=>{if(e.length>1){let r=an(e,1),n=an(e,2),o=an(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),J({starts:r,ends:n,axes:o})}else return t},Od=(e,t,r,n,o)=>{let i=e;return e<0&&(i+=r[n[t]]),o[t]<0?Math.max(0,Math.min(i,r[n[t]]-1)):Math.max(0,Math.min(i,r[n[t]]))},Kh=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n var carry = 0u;\n for (var i = ${r.length}; i >= 0; i--) {\n let input_shape_i = ${F(\"uniforms.input_shape\",\"i\",r.length)};\n let steps_i = ${F(\"uniforms.steps\",\"i\",r.length)};\n let signs_i = ${F(\"uniforms.signs\",\"i\",r.length)};\n let starts_i = ${F(\"uniforms.starts\",\"i\",r.length)};\n var output_index = ${t.indicesGet(\"output_indices\",\"i\")};\n var input_index = output_index * steps_i + starts_i + carry;\n carry = input_index / input_shape_i;\n input_index = input_index % input_shape_i;\n if (signs_i < 0) {\n input_index = input_shape_i - input_index - 1u + starts_i;\n }\n ${e.indicesSet(\"input_indices\",\"i\",\"input_index\")};\n }\n return input_indices;\n }`,Yh=(e,t)=>{let r=e[0].dims,n=k.size(r),o=t.axes.length>0?k.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],i=an(e,4);i.forEach($=>$!==0||(()=>{throw new Error(\"step cannot be 0\")})),i.length===0&&(i=Array(o.length).fill(1));let a=t.starts.map(($,v)=>Od($,v,r,o,i)),l=t.ends.map(($,v)=>Od($,v,r,o,i));if(o.length!==a.length||o.length!==l.length)throw new Error(\"start, ends and axes should have the same number of elements\");if(o.length!==r.length)for(let $=0;$Math.sign($));i.forEach(($,v,S)=>{if($<0){let T=(l[v]-a[v])/$,C=a[v],A=C+T*i[v];a[v]=A,l[v]=C,S[v]=-$}});let p=r.slice(0);o.forEach(($,v)=>{p[$]=Math.ceil((l[$]-a[$])/i[$])});let m={dims:p,dataType:e[0].dataType},u=M(\"output\",e[0].dataType,p.length),h=E(\"input\",e[0].dataType,e[0].dims.length),_=k.size(p),y=[{name:\"outputSize\",type:\"u32\"},{name:\"starts\",type:\"u32\",length:a.length},{name:\"signs\",type:\"i32\",length:d.length},{name:\"steps\",type:\"u32\",length:i.length}],g=[{type:12,data:_},{type:12,data:a},{type:6,data:d},{type:12,data:i},...N(e[0].dims,p)],x=$=>`\n ${$.registerUniforms(y).declareVariables(h,u)}\n ${Kh(h,u,r)}\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n let output_indices = ${u.offsetToIndices(\"global_idx\")};\n let input_indices = calculateInputIndices(output_indices);\n ${u.setByOffset(\"global_idx\",h.getByIndices(\"input_indices\"))}\n }`;return{name:\"Slice\",shaderCache:{hint:`${d.length}_${a.length}_${i.length}`,inputDependencies:[\"rank\"]},getShaderSource:x,getRunData:()=>({outputs:[m],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:g})}},Bd=(e,t)=>{qh(e.inputs,t);let r=jh(e.inputs,t);e.compute(Yh(e.inputs,r),{inputs:[0]})},Dd=e=>{let t=e.starts,r=e.ends,n=e.axes;return J({starts:t,ends:r,axes:n})}});var Zh,Qh,Rd,Ud,Nd=R(()=>{\"use strict\";te();oe();Se();ut();ae();Zh=e=>{if(!e||e.length!==1)throw new Error(\"Softmax op requires 1 input.\")},Qh=(e,t)=>{let r=e.inputs[0],n=r.dims,o=k.size(n),i=n.length,a=k.normalizeAxis(t.axis,i),l=aO),p[a]=i-1,p[i-1]=a,d=e.compute(Ee(r,p),{inputs:[r],outputs:[-1]})[0]):d=r;let m=d.dims,u=m[i-1],h=o/u,_=me(u),y=u/_,g=64;h===1&&(g=256);let x=(P,O)=>O===4?`max(max(${P}.x, ${P}.y), max(${P}.z, ${P}.w))`:O===2?`max(${P}.x, ${P}.y)`:O===3?`max(max(${P}.x, ${P}.y), ${P}.z)`:P,$=E(\"x\",d.dataType,d.dims,_),v=M(\"result\",d.dataType,d.dims,_),S=$.type.value,T=ye(d.dataType)===\"f32\"?`var threadMax = ${S}(-3.402823e+38f);`:`var threadMax = ${S}(-65504.0h);`,C=P=>`\n var rowMaxShared : ${S};\n var rowSumShared : ${S};\n var threadShared : array<${S}, ${g}>;\n\n fn getValue(row: i32, col: i32, row_stride: i32) -> ${S} {\n let index = row * row_stride + col;\n return x[index];\n }\n\n fn setValue(row: i32, col: i32, row_stride: i32, value: ${S}) {\n let index = row * row_stride + col;\n result[index] = value;\n }\n ${P.registerUniform(\"packedCols\",\"i32\").declareVariables($,v)}\n ${P.mainStart(g)}\n let gindex = i32(global_idx);\n let lindex = i32(local_idx);\n const wg = ${g};\n let row = gindex / wg;\n let cols = uniforms.packedCols;\n let row_stride : i32 = uniforms.packedCols;\n\n // find the rows max\n ${T}\n for (var col = lindex; col < cols; col += wg) {\n let value = getValue(row, col, row_stride);\n threadMax = max(threadMax, value);\n }\n if (lindex < cols) {\n threadShared[lindex] = threadMax;\n }\n workgroupBarrier();\n\n var reduceSize = min(cols, wg);\n for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {\n reduceSize = currSize + (reduceSize & 1);\n if (lindex < currSize) {\n threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowMaxShared = ${S}(${x(\"threadShared[0]\",_)});\n }\n workgroupBarrier();\n\n // find the rows sum\n var threadSum = ${S}(0.0);\n for (var col = lindex; col < cols; col += wg) {\n let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);\n threadSum += subExp;\n }\n threadShared[lindex] = threadSum;\n workgroupBarrier();\n\n for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {\n if (lindex < currSize) {\n threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowSumShared = ${S}(${He(\"threadShared[0]\",_)});\n }\n workgroupBarrier();\n\n // calculate final value for each element in the row\n for (var col = lindex; col < cols; col += wg) {\n let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;\n setValue(row, col, row_stride, value);\n }\n }`,A=e.compute({name:\"Softmax\",shaderCache:{hint:`${_};${g}`,inputDependencies:[\"type\"]},getRunData:()=>({outputs:[{dims:m,dataType:d.dataType}],dispatchGroup:{x:h},programUniforms:[{type:6,data:y}]}),getShaderSource:C},{inputs:[d],outputs:[l?-1:0]})[0];l&&e.compute(Ee(A,p),{inputs:[A]})},Rd=(e,t)=>{Zh(e.inputs),Qh(e,t)},Ud=e=>J({axis:e.axis})});var Vd,Xh,Jh,eg,Wd,Ld=R(()=>{\"use strict\";te();oe();ae();Vd=e=>Array.from(e.getBigInt64Array(),Number),Xh=e=>{if(!e||e.length!==2)throw new Error(\"Tile requires 2 inputs.\");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error(\"Tile only support float, float16, int32, and uint32 data types\");if(e[1].dataType!==7)throw new Error(\"Tile `repeats` input should be of int64 data type\");if(e[1].dims.length!==1)throw new Error(\"Tile `repeats` input should be 1-D\");if(Vd(e[1]).length!==e[0].dims.length)throw new Error(\"Tile `repeats` input should have same number of elements as rank of input data tensor\")},Jh=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??Vd(e[1]),o=Jh(r,n),i=k.size(o),a=e[0].dataType,l=E(\"input\",a,r.length),d=M(\"output\",a,o.length),p=m=>`\n const inputShape = ${l.indices(...r)};\n ${m.registerUniform(\"output_size\",\"u32\").declareVariables(l,d)}\n ${m.mainStart()}\n ${m.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let output_indices = ${d.offsetToIndices(\"global_idx\")};\n var input_indices: ${l.type.indices};\n for (var i = 0; i < ${r.length}; i++) {\n let input_dim_i = ${l.indicesGet(\"uniforms.input_shape\",\"i\")};\n let input_dim_value = ${d.indicesGet(\"output_indices\",\"i\")} % input_dim_i;\n\n ${l.indicesSet(\"input_indices\",\"i\",\"input_dim_value\")}\n }\n ${d.setByOffset(\"global_idx\",l.getByIndices(\"input_indices\"))}\n }`;return{name:\"Tile\",shaderCache:{hint:`${n}`,inputDependencies:[\"rank\"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...N(e[0].dims,o)]}),getShaderSource:p}},Wd=e=>{Xh(e.inputs),e.compute(eg(e.inputs),{inputs:[0]})}});var tg,rg,Gd,Hd=R(()=>{\"use strict\";te();oe();ae();tg=(e,t,r,n,o)=>{let i=M(\"output_data\",o,r.length,4),a=E(\"a_data\",t[1].dataType,t[1].dims.length,4),l=E(\"b_data\",t[2].dataType,t[2].dims.length,4),d=E(\"c_data\",t[0].dataType,t[0].dims.length,4),p,m=(u,h,_)=>`select(${h}, ${u}, ${_})`;if(!n)p=i.setByOffset(\"global_idx\",m(a.getByOffset(\"global_idx\"),l.getByOffset(\"global_idx\"),d.getByOffset(\"global_idx\")));else{let u=(h,_,y=\"\")=>{let g=`a_data[index_a${_}][component_a${_}]`,x=`b_data[index_b${_}][component_b${_}]`,$=`bool(c_data[index_c${_}] & (0xffu << (component_c${_} * 8)))`;return`\n let output_indices${_} = ${i.offsetToIndices(`global_idx * 4u + ${_}u`)};\n let offset_a${_} = ${a.broadcastedIndicesToOffset(`output_indices${_}`,i)};\n let offset_b${_} = ${l.broadcastedIndicesToOffset(`output_indices${_}`,i)};\n let offset_c${_} = ${d.broadcastedIndicesToOffset(`output_indices${_}`,i)};\n let index_a${_} = offset_a${_} / 4u;\n let index_b${_} = offset_b${_} / 4u;\n let index_c${_} = offset_c${_} / 4u;\n let component_a${_} = offset_a${_} % 4u;\n let component_b${_} = offset_b${_} % 4u;\n let component_c${_} = offset_c${_} % 4u;\n ${h}[${_}] = ${y}(${m(g,x,$)});\n `};o===9?p=`\n var data = vec4(0);\n ${u(\"data\",0,\"u32\")}\n ${u(\"data\",1,\"u32\")}\n ${u(\"data\",2,\"u32\")}\n ${u(\"data\",3,\"u32\")}\n output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:p=`\n ${u(\"output_data[global_idx]\",0)}\n ${u(\"output_data[global_idx]\",1)}\n ${u(\"output_data[global_idx]\",2)}\n ${u(\"output_data[global_idx]\",3)}\n `}return`\n ${e.registerUniform(\"vec_size\",\"u32\").declareVariables(d,a,l,i)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.vec_size\")}\n ${p}\n }`},rg=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,o=e[1].dataType,i=!(k.areEqual(t,r)&&k.areEqual(r,n)),a=t,l=k.size(t);if(i){let p=et.calcShape(et.calcShape(t,r,!1),n,!1);if(!p)throw new Error(\"Can't perform where op on the given tensors\");a=p,l=k.size(a)}let d=Math.ceil(l/4);return{name:\"Where\",shaderCache:{inputDependencies:[\"rank\",\"rank\",\"rank\"]},getShaderSource:p=>tg(p,e,a,i,o),getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:Math.ceil(l/64/4)},programUniforms:[{type:12,data:d},...N(n,t,r,a)]})}},Gd=e=>{e.compute(rg(e.inputs))}});var Fd,qd=R(()=>{\"use strict\";ks();Kr();zs();Bs();_u();Eu();Ou();Yu();rl();il();ul();ml();gl();yl();vl();Sl();Cl();El();Ol();Wl();Hl();ql();Kl();Ql();To();Jl();gd();_d();vd();Sd();qr();Ad();Ed();zd();Md();Nd();Co();Ld();ut();Zr();Hd();Fd=new Map([[\"Abs\",[Ds]],[\"Acos\",[Ms]],[\"Acosh\",[Rs]],[\"Add\",[wu]],[\"ArgMax\",[As,po]],[\"ArgMin\",[Cs,po]],[\"Asin\",[Us]],[\"Asinh\",[Ns]],[\"Atan\",[Vs]],[\"Atanh\",[Ws]],[\"Attention\",[Es]],[\"AveragePool\",[sd,ad]],[\"BatchNormalization\",[Ps]],[\"BiasAdd\",[Os]],[\"BiasSplitGelu\",[yu]],[\"Cast\",[Gs,Ls]],[\"Ceil\",[Fs]],[\"Clip\",[Hs]],[\"Concat\",[Pu,zu]],[\"Conv\",[vo,wo]],[\"ConvTranspose\",[tl,Ju]],[\"Cos\",[qs]],[\"Cosh\",[js]],[\"CumSum\",[nl,ol]],[\"DepthToSpace\",[al,sl]],[\"DequantizeLinear\",[bd,yd]],[\"Div\",[vu]],[\"Einsum\",[cl,pl]],[\"Elu\",[Ks,Jt]],[\"Equal\",[$u]],[\"Erf\",[Ys]],[\"Exp\",[Zs]],[\"Expand\",[hl]],[\"FastGelu\",[bl]],[\"Floor\",[Qs]],[\"FusedConv\",[vo,wo]],[\"Gather\",[wl,_l]],[\"GatherElements\",[Il,Tl]],[\"GatherBlockQuantized\",[$l,xl]],[\"Gelu\",[Xs]],[\"Gemm\",[kl,Al]],[\"GlobalAveragePool\",[dd,ld]],[\"GlobalMaxPool\",[hd,fd]],[\"Greater\",[Iu]],[\"GreaterOrEqual\",[Au]],[\"GridSample\",[Pl,zl]],[\"GroupQueryAttention\",[Vl]],[\"HardSigmoid\",[au,iu]],[\"InstanceNormalization\",[Gl]],[\"LayerNormalization\",[Fl]],[\"LeakyRelu\",[Js,Jt]],[\"Less\",[Cu]],[\"LessOrEqual\",[ku]],[\"Log\",[hu]],[\"MatMul\",[jl]],[\"MatMulNBits\",[Yl,Zl]],[\"MaxPool\",[pd,md]],[\"Mul\",[xu]],[\"MultiHeadAttention\",[Ml,Dl]],[\"Neg\",[tu]],[\"Not\",[eu]],[\"Pad\",[Xl]],[\"Pow\",[Su]],[\"QuickGelu\",[gu,Jt]],[\"Range\",[wd]],[\"Reciprocal\",[ru]],[\"ReduceMin\",[vs]],[\"ReduceMean\",[gs]],[\"ReduceMax\",[ws]],[\"ReduceSum\",[xs]],[\"ReduceProd\",[$s]],[\"ReduceL1\",[bs]],[\"ReduceL2\",[ys]],[\"ReduceLogSum\",[Ts]],[\"ReduceLogSumExp\",[_s]],[\"ReduceSumSquare\",[Ss]],[\"Relu\",[nu]],[\"Resize\",[Id,Cd]],[\"RotaryEmbedding\",[kd]],[\"ScatterND\",[xd,$d]],[\"Sigmoid\",[ou]],[\"Sin\",[su]],[\"Sinh\",[uu]],[\"Slice\",[Bd,Dd]],[\"SkipLayerNormalization\",[Pd]],[\"Split\",[Rl,Ul]],[\"Sqrt\",[lu]],[\"Softmax\",[Rd,Ud]],[\"Sub\",[Tu]],[\"Tan\",[du]],[\"Tanh\",[pu]],[\"ThresholdedRelu\",[fu,Jt]],[\"Tile\",[Wd]],[\"Transpose\",[ns,os]],[\"Where\",[Gd]]])});var sn,jd=R(()=>{\"use strict\";We();Je();ae();sn=class{constructor(t){this.backend=t;this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,r){this.repo.set(t,r)}run(t,r,n,o,i){Ue(t.programInfo.name);let a=this.backend.device,l=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let d=[];for(let m of r)d.push({binding:d.length,resource:{buffer:m.buffer}});for(let m of n)d.push({binding:d.length,resource:{buffer:m.buffer}});i&&d.push({binding:d.length,resource:i});let p=a.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:d,label:t.programInfo.name});if(this.backend.sessionStatus===\"capturing\"){let m={kernelId:this.backend.currentKernelId,computePipeline:t.computePipeline,bindGroup:p,dispatchGroup:o};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(m)}l.setPipeline(t.computePipeline),l.setBindGroup(0,p),l.dispatchWorkgroups(...o),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType===\"at-passes\")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),De(t.programInfo.name)}dispose(){}build(t,r){Ue(t.name);let n=this.backend.device,o=[];[{feature:\"shader-f16\",extension:\"f16\"},{feature:\"subgroups\",extension:\"subgroups\"},{feature:\"subgroups-f16\",extension:\"subgroups_f16\"}].forEach(u=>{n.features.has(u.feature)&&o.push(`enable ${u.extension};`)});let a=ts(r,this.backend.device.limits),l=t.getShaderSource(a),d=`${o.join(`\n`)}\n${a.additionalImplementations}\n${l}`,p=n.createShaderModule({code:d,label:t.name});ue(\"verbose\",()=>`[WebGPU] ${t.name} shader code: ${d}`);let m=n.createComputePipeline({compute:{module:p,entryPoint:\"main\"},layout:\"auto\",label:t.name});return De(t.name),{programInfo:t,computePipeline:m,uniformVariablesInfo:a.variablesInfo}}normalizeDispatchGroupSize(t){let r=typeof t==\"number\"?t:t.x,n=typeof t==\"number\"?1:t.y||1,o=typeof t==\"number\"?1:t.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=i&&n<=i&&o<=i)return[r,n,o];let a=r*n*o,l=Math.ceil(Math.sqrt(a));if(l>i){if(l=Math.ceil(Math.cbrt(a)),l>i)throw new Error(\"Total dispatch size exceeds WebGPU maximum.\");return[l,l,l]}else return[l,l,1]}}});var ng,og,Ao,ko,un,Kd=R(()=>{\"use strict\";We();te();Je();eo();Qa();qd();jd();ng=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let n=0;n{let n=e.name;return e.shaderCache?.hint&&(n+=\"[\"+e.shaderCache.hint+\"]\"),n+=\":\"+r+`:${ng(t,e.shaderCache?.inputDependencies??new Array(t.length).fill(\"dims\"))}`,n},Ao=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},ko=class{constructor(t){this.subgroupsSupported=t.features.has(\"subgroups\"),this.subgroupsF16Supported=t.features.has(\"subgroups\");let r=t.limits;!this.subgroupsSupported||!r.minSubgroupSize||!r.maxSubgroupSize?this.subgroupSizeRange=void 0:this.subgroupSizeRange=[r.minSubgroupSize,r.maxSubgroupSize]}},un=class{constructor(){this.currentSessionId=null;this.currentKernelId=null;this.commandEncoder=null;this.computePassEncoder=null;this.maxDispatchNumber=16;this.pendingDispatchNumber=0;this.pendingKernels=[];this.pendingQueries=new Map;this.sessionStatus=\"default\";this.capturedCommandList=new Map;this.capturedPendingKernels=new Map;this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error(\"currentKernelCustomData(): currentKernelId is null. (should not happen)\");let t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,r){this.env=t;let n=[],o={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},i=a=>r.features.has(a)&&n.push(a)&&!0;i(\"chromium-experimental-timestamp-query-inside-passes\")||i(\"timestamp-query\"),i(\"shader-f16\"),i(\"subgroups\")&&i(\"subgroups-f16\"),this.device=await r.requestDevice(o),this.deviceInfo=new ko(this.device),this.adapterInfo=new Ao(r.info||await r.requestAdapterInfo()),this.gpuDataManager=Za(this),this.programManager=new sn(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Vr(t.logLevel,!!t.debug),this.device.onuncapturederror=a=>{a.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${a.error.message}`)},Object.defineProperty(this.env.webgpu,\"device\",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,\"adapter\",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<\"u\"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t=this.getCommandEncoder(),r={};this.queryType===\"at-passes\"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ue(),this.endComputePass();let t;this.queryType!==\"none\"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),t=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(t,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,t,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!==\"none\"&&t.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(t.getMappedRange()),n=this.pendingQueries.get(t);for(let o=0;o\"u\"&&(this.queryTimeBase=_);let g=Number(_-this.queryTimeBase),x=Number(y-this.queryTimeBase);if(!Number.isSafeInteger(g)||!Number.isSafeInteger(x))throw new RangeError(\"incorrect timestamp range\");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:u.map($=>({dims:$.dims,dataType:gt($.dataType)})),outputsMetadata:h.map($=>({dims:$.dims,dataType:gt($.dataType)})),kernelId:a,kernelType:d,kernelName:p,programName:m,startTime:g,endTime:x});else{let $=\"\";u.forEach((S,T)=>{$+=`input[${T}]: [${S.dims}] | ${gt(S.dataType)}, `});let v=\"\";h.forEach((S,T)=>{v+=`output[${T}]: [${S.dims}] | ${gt(S.dataType)}, `}),console.log(`[profiling] kernel \"${a}|${d}|${p}|${m}\" ${$}${v}execution time: ${x-g} ns`)}xr(\"GPU\",`${m}::${_}::${y}`)}t.unmap(),this.pendingQueries.delete(t)}),De()}run(t,r,n,o,i,a){Ue(t.name);let l=[];for(let S=0;ST):n;if(u.length!==d.length)throw new Error(`Output size ${u.length} must be equal to ${d.length}.`);let h=[],_=[];for(let S=0;S=a)throw new Error(`Invalid output index: ${u[S]}`);if(u[S]===-3)continue;let T=u[S]===-1,C=u[S]===-2,A=T||C?i(d[S].dataType,d[S].dims):o(u[S],d[S].dataType,d[S].dims);if(h.push(A),A.data===0)continue;let P=this.gpuDataManager.get(A.data);if(!P)throw new Error(`no GPU data for output: ${A.data}`);if(T&&this.temporaryData.push(P),C){let O=this.kernelPersistentData.get(this.currentKernelId);O||(O=[],this.kernelPersistentData.set(this.currentKernelId,O)),O.push(P)}_.push(P)}if(l.length!==r.length||_.length!==h.length){if(_.length===0)return De(t.name),h;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let y;if(m){let S=0,T=[];m.forEach(O=>{let U=typeof O.data==\"number\"?[O.data]:O.data;if(U.length===0)return;let G=O.type===10?2:4,q,K;O.type===10?(K=U.length>4?16:U.length>2?8:U.length*G,q=U.length>4?16:G*U.length):(K=U.length<=2?U.length*G:16,q=16),S=Math.ceil(S/K)*K,T.push(S);let W=O.type===10?8:4;S+=U.length>4?Math.ceil(U.length/W)*q:U.length*G});let C=16;S=Math.ceil(S/C)*C;let A=new ArrayBuffer(S);m.forEach((O,U)=>{let G=T[U],q=typeof O.data==\"number\"?[O.data]:O.data;if(O.type===6)new Int32Array(A,G,q.length).set(q);else if(O.type===12)new Uint32Array(A,G,q.length).set(q);else if(O.type===10)new Uint16Array(A,G,q.length).set(q);else if(O.type===1)new Float32Array(A,G,q.length).set(q);else throw new Error(`Unsupported uniform type: ${gt(O.type)}`)});let P=this.gpuDataManager.create(S,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(P.buffer,0,A,0,S),this.gpuDataManager.release(P.id),y={offset:0,size:S,buffer:P.buffer}}let g=this.programManager.normalizeDispatchGroupSize(p),x=g[1]===1&&g[2]===1,$=og(t,r,x),v=this.programManager.getArtifact($);if(v||(v=this.programManager.build(t,g),this.programManager.setArtifact($,v),ue(\"info\",()=>`[artifact] key: ${$}, programName: ${t.name}`)),m&&v.uniformVariablesInfo){if(m.length!==v.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${v.uniformVariablesInfo.length}, got ${m.length} in program \"${v.programInfo.name}\".`);for(let S=0;S`[ProgramManager] run \"${t.name}\" (key=${$}) with ${g[0]}x${g[1]}x${g[2]}`),this.queryType!==\"none\"||this.sessionStatus===\"capturing\"){let S={kernelId:this.currentKernelId,programName:v.programInfo.name,inputTensorViews:r,outputTensorViews:h};this.pendingKernels.push(S),this.sessionStatus===\"capturing\"&&this.capturedPendingKernels.get(this.currentSessionId).push(S)}return this.programManager.run(v,l,_,g,y),De(t.name),h}upload(t,r){this.gpuDataManager.upload(t,r)}memcpy(t,r){this.gpuDataManager.memcpy(t,r)}async download(t,r){await this.gpuDataManager.download(t,r)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,r,n,o){let i=Fd.get(t);if(!i)throw new Error(`kernel not implemented: ${t}`);let a={kernelType:t,kernelName:o,kernelEntry:i[0],attributes:[i[1],n]};this.kernels.set(r,a)}releaseKernel(t){let r=this.kernelPersistentData.get(t);if(r){for(let n of r)this.gpuDataManager.release(n.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,r,n){let o=this.kernels.get(t);if(!o)throw new Error(`kernel not created: ${t}`);let i=o.kernelType,a=o.kernelName,l=o.kernelEntry,d=o.attributes;if(this.currentKernelId!==null)throw new Error(`kernel \"[${i}] ${a}\" is not allowed to be called recursively`);this.currentKernelId=t,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),ue(\"info\",()=>`[WebGPU] Start to run kernel \"[${i}] ${a}\"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope(\"validation\"),l(r,d[1]),0}catch(m){return n.push(Promise.resolve(`[WebGPU] Kernel \"[${i}] ${a}\" failed. ${m}`)),1}finally{p&&n.push(this.device.popErrorScope().then(m=>m?`GPU validation error for kernel \"[${i}] ${a}\": ${m.message}`:null));for(let m of this.temporaryData)this.gpuDataManager.release(m.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,r,n,o){let i=this.sessionExternalDataMapping.get(t);i||(i=new Map,this.sessionExternalDataMapping.set(t,i));let a=i.get(r),l=this.gpuDataManager.registerExternalBuffer(n,o,a);return i.set(r,[l,n]),l}unregisterBuffers(t){let r=this.sessionExternalDataMapping.get(t);r&&(r.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[0])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let r=this.gpuDataManager.get(t);if(!r)throw new Error(`no GPU data for buffer: ${t}`);return r.buffer}createDownloader(t,r,n){return async()=>{let o=await oo(this,t,r);return Wr(o.buffer,n)}}writeTimestamp(t){this.queryType===\"inside-passes\"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}setQueryType(){this.queryType=\"none\",(this.env.webgpu.profiling?.mode===\"default\"||(typeof this.env.trace>\"u\"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has(\"chromium-experimental-timestamp-query-inside-passes\")?this.queryType=\"inside-passes\":this.device.features.has(\"timestamp-query\")&&(this.queryType=\"at-passes\"),this.queryType!==\"none\"&&typeof this.querySet>\"u\"&&(this.querySet=this.device.createQuerySet({type:\"timestamp\",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){ue(\"info\",\"captureBegin\"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus=\"capturing\"}captureEnd(){ue(\"info\",\"captureEnd\"),this.flush(),this.sessionStatus=\"default\"}replay(){ue(\"info\",\"replay\"),this.sessionStatus=\"replaying\";let t=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),n=t.length;this.pendingKernels=[];for(let o=0;o=this.maxDispatchNumber||this.queryType===\"at-passes\")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus=\"default\"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}});var ig,Yd,ag,Zd,ln,dn,Eo,Qd,Xd=R(()=>{\"use strict\";Je();ig=1,Yd=()=>ig++,ag=new Map([[\"float32\",32],[\"float16\",16],[\"int32\",32],[\"uint32\",32],[\"int64\",64],[\"uint64\",64],[\"int8\",8],[\"uint8\",8],[\"int4\",4],[\"uint4\",4]]),Zd=(e,t)=>{let r=ag.get(e);if(!r)throw new Error(\"Unsupported data type.\");return Math.ceil(t.reduce((n,o)=>n*o)*r/8)},ln=class{constructor(t){this.sessionId=t.sessionId,this.mlContext=t.context,this.mlTensor=t.tensor,this.dataType=t.dataType,this.tensorShape=t.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Zd(this.dataType,this.tensorShape)}destroy(){ue(\"verbose\",()=>\"[WebNN] TensorWrapper.destroy\"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t){return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}sameTypeAndShape(t,r){return this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((n,o)=>n===r[o])}},dn=class{constructor(t,r){this.tensorManager=t;this.wrapper=r}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(t,r,n){if(this.wrapper){if(this.wrapper.sameTypeAndShape(t,r))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==Zd(t,r))throw new Error(\"Unable to copy data to tensor with different size.\");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let o=typeof MLTensorUsage>\"u\"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,r,o,!0,!0),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(t){if(this.wrapper)if(t.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else ue(\"verbose\",()=>\"Data size does not match tensor size. Releasing tensor.\"),this.releaseTensor();this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(t){if(this.activeUpload)if(t){t instanceof ArrayBuffer?new Uint8Array(t).set(this.activeUpload):new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.wrapper)throw new Error(\"Tensor has not been created.\");return t?this.wrapper.read(t):this.wrapper.read()}},Eo=class{constructor(t){this.backend=t;this.tensorTrackersById=new Map;this.freeTensors=[];this.externalTensors=new Set}reserveTensorId(){let t=Yd();return this.tensorTrackersById.set(t,new dn(this)),t}releaseTensorId(t){let r=this.tensorTrackersById.get(t);r&&(this.tensorTrackersById.delete(t),r.tensorWrapper&&this.releaseTensor(r.tensorWrapper))}async ensureTensor(t,r,n,o){ue(\"verbose\",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${n}, copyOld: ${o}}`);let i=this.tensorTrackersById.get(t);if(!i)throw new Error(\"Tensor not found.\");return i.ensureTensor(r,n,o)}upload(t,r){let n=this.tensorTrackersById.get(t);if(!n)throw new Error(\"Tensor not found.\");n.upload(r)}async download(t,r){ue(\"verbose\",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${r?.byteLength}}`);let n=this.tensorTrackersById.get(t);if(!n)throw new Error(\"Tensor not found.\");return n.download(r)}releaseTensorsForSession(t){for(let r of this.freeTensors)r.sessionId===t&&r.destroy();this.freeTensors=this.freeTensors.filter(r=>r.sessionId!==t)}registerTensor(t,r,n,o){let i=Yd(),a=new ln({sessionId:this.backend.currentSessionId,context:t,tensor:r,dataType:n,shape:o});return this.tensorTrackersById.set(i,new dn(this,a)),this.externalTensors.add(a),i}async getCachedTensor(t,r,n,o,i){let a=this.backend.currentSessionId;for(let[p,m]of this.freeTensors.entries())if(m.sameTypeAndShape(t,r)){ue(\"verbose\",()=>`[WebNN] Reusing tensor {dataType: ${t}, shape: ${r}}`);let u=this.freeTensors.splice(p,1)[0];return u.sessionId=a,u}let l=this.backend.currentContext;ue(\"verbose\",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, shape: ${r}}`);let d=await l.createTensor({dataType:t,shape:r,dimensions:r,usage:n,writable:o,readable:i});return new ln({sessionId:a,context:l,tensor:d,dataType:t,shape:r})}releaseTensor(t){this.externalTensors.has(t)&&this.externalTensors.delete(t),this.freeTensors.push(t)}},Qd=(...e)=>new Eo(...e)});var Jd,sg,cn,ec=R(()=>{\"use strict\";te();ht();eo();Xd();Je();Jd=new Map([[1,\"float32\"],[10,\"float16\"],[6,\"int32\"],[12,\"uint32\"],[7,\"int64\"],[13,\"uint64\"],[22,\"int4\"],[21,\"uint4\"],[3,\"int8\"],[2,\"uint8\"],[9,\"uint8\"]]),sg=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.length===n.length&&r.every((o,i)=>o===n[i]&&e[o]===t[o])},cn=class{constructor(t){this.tensorManager=Qd(this);this.mlContextBySessionId=new Map;this.sessionIdsByMLContext=new Map;this.mlContextCache=[];Vr(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error(\"No active session\");return this.activeSessionId}onRunStart(t){this.activeSessionId=t}async createMLContext(t){if(t instanceof GPUDevice){let n=this.mlContextCache.findIndex(o=>o.gpuDevice===t);if(n!==-1)return this.mlContextCache[n].mlContext;{let o=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:o}),o}}else if(t===void 0){let n=this.mlContextCache.findIndex(o=>o.options===void 0&&o.gpuDevice===void 0);if(n!==-1)return this.mlContextCache[n].mlContext;{let o=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:o}),o}}let r=this.mlContextCache.findIndex(n=>sg(n.options,t));if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:n}),n}}get currentContext(){let t=this.getMLContext(this.currentSessionId);if(!t)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return t}registerMLContext(t,r){this.mlContextBySessionId.set(t,r);let n=this.sessionIdsByMLContext.get(r);n||(n=new Set,this.sessionIdsByMLContext.set(r,n)),n.add(t)}onReleaseSession(t){let r=this.mlContextBySessionId.get(t);if(!r)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t);let n=this.sessionIdsByMLContext.get(r);if(n.delete(t),n.size===0){this.sessionIdsByMLContext.delete(r);let o=this.mlContextCache.findIndex(i=>i.mlContext===r);o!==-1&&this.mlContextCache.splice(o,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){ue(\"verbose\",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,r,n,o){let i=Jd.get(r);if(!i)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(t,i,n,o)}uploadTensor(t,r){if(!Ce().shouldTransferToMLTensor)throw new Error(\"Trying to upload to a MLTensor while shouldTransferToMLTensor is false\");ue(\"verbose\",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${r.byteLength}}`),this.tensorManager.upload(t,r)}async downloadTensor(t,r){return this.tensorManager.download(t,r)}createMLTensorDownloader(t,r){return async()=>{let n=await this.tensorManager.download(t);return Wr(n,r)}}registerMLTensor(t,r,n){let o=Jd.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);let i=this.tensorManager.registerTensor(this.currentContext,t,o,n);return ue(\"verbose\",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${o}, dimensions: ${n}} -> {tensorId: ${i}}`),i}registerMLConstant(t,r,n,o,i,a){if(!a)throw new Error(\"External mounted files are not available.\");let l=t;t.startsWith(\"./\")&&(l=t.substring(2));let d=a.get(l);if(!d)throw new Error(`File with name ${l} not found in preloaded files.`);if(r+n>d.byteLength)throw new Error(\"Out of bounds: data offset and length exceed the external file data size.\");let p=d.slice(r,r+n).buffer,m;switch(i.dataType){case\"float32\":m=new Float32Array(p);break;case\"float16\":m=new Uint16Array(p);break;case\"int32\":m=new Int32Array(p);break;case\"uint32\":m=new Uint32Array(p);break;case\"int64\":m=new BigInt64Array(p);break;case\"uint64\":m=new BigUint64Array(p);break;case\"int8\":m=new Int8Array(p);break;case\"int4\":case\"uint4\":case\"uint8\":m=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return ue(\"verbose\",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`),o.constant(i,m)}flush(){}}});var tc={};Ft(tc,{init:()=>ug});var nr,Po,ug,rc=R(()=>{\"use strict\";te();Kd();Je();oe();ec();nr=class e{constructor(t,r,n,o){this.module=t;this.dataType=r;this.data=n;this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error(\"Invalid data type\");let t=k.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error(\"Invalid data type\");let t=k.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error(\"Invalid data type\");let t=k.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error(\"Invalid data type\");let t=k.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(k.size(t)!==k.size(this.dims))throw new Error(\"Invalid new shape\");return new e(this.module,this.dataType,this.data,t)}},Po=class{constructor(t,r,n){this.module=t;this.backend=r;this.customDataOffset=0;this.customDataSize=0;this.adapterInfo=r.adapterInfo,this.deviceInfo=r.deviceInfo;let o=t.PTR_SIZE,i=n/t.PTR_SIZE,a=o===4?\"i32\":\"i64\";this.opKernelContext=Number(t.getValue(o*i++,a));let l=Number(t.getValue(o*i++,a));this.outputCount=Number(t.getValue(o*i++,a)),this.customDataOffset=Number(t.getValue(o*i++,\"*\")),this.customDataSize=Number(t.getValue(o*i++,a));let d=[];for(let p=0;ptypeof l==\"number\"?this.inputs[l]:l)??this.inputs,o=r?.outputs??[],i=(l,d,p)=>new nr(this.module,d,this.output(l,p),p),a=(l,d)=>{let p=Tt(l,d);if(!p)throw new Error(`Unsupported data type: ${l}`);let m=p>0?this.backend.gpuDataManager.create(p).id:0;return new nr(this.module,l,m,d)};return this.backend.run(t,n,o,i,a,this.outputCount)}output(t,r){let n=this.module.stackSave();try{let o=this.module.PTR_SIZE,i=o===4?\"i32\":\"i64\",a=this.module.stackAlloc((1+r.length)*o);this.module.setValue(a,r.length,i);for(let l=0;l{let o=t.jsepInit;if(!o)throw new Error(\"Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.\");if(e===\"webgpu\"){let i=new un;await i.initialize(r,n),o(\"webgpu\",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,d,p=!1)=>{if(p)ue(\"verbose\",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(d)}`),i.memcpy(Number(a),Number(l));else{ue(\"verbose\",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(d)}`);let m=t.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(d));i.upload(Number(l),m)}},async(a,l,d)=>{ue(\"verbose\",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${d}`),await i.download(Number(a),()=>t.HEAPU8.subarray(Number(l)>>>0,Number(l+d)>>>0))},(a,l,d)=>i.createKernel(a,Number(l),d,t.UTF8ToString(t._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,d,p)=>{ue(\"verbose\",()=>`[WebGPU] jsepRun: sessionHandle=${d}, kernel=${a}, contextDataOffset=${l}`);let m=new Po(t,i,Number(l));return i.computeKernel(Number(a),m,p)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let i=new cn(r);o(\"webnn\",[i,()=>i.reserveTensorId(),a=>i.releaseTensorId(a),async(a,l,d,p)=>i.ensureTensor(a,l,d,p),(a,l)=>{i.uploadTensor(a,l)},async(a,l)=>i.downloadTensor(a,l)])}}});var lg,Ar,kr,kt,dg,Kt,Er,Pr,nc,zr,Or,Br,Kn=R(()=>{\"use strict\";La();Ha();te();ht();Mr();Jn();lg=(e,t)=>{Ce()._OrtInit(e,t)!==0&&pe(\"Can't initialize onnxruntime.\")},Ar=async e=>{lg(e.wasm.numThreads,Qt(e.logLevel))},kr=async(e,t)=>{{let r=(rc(),br(tc)).init;if(t===\"webgpu\"){if(typeof navigator>\"u\"||!navigator.gpu)throw new Error(\"WebGPU is not supported in current environment\");let n=e.webgpu.adapter;if(n){if(typeof n.limits!=\"object\"||typeof n.features!=\"object\"||typeof n.requestDevice!=\"function\")throw new Error(\"Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.\")}else{let o=e.webgpu.powerPreference;if(o!==void 0&&o!==\"low-power\"&&o!==\"high-performance\")throw new Error(`Invalid powerPreference setting: \"${o}\"`);let i=e.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!=\"boolean\")throw new Error(`Invalid forceFallbackAdapter setting: \"${i}\"`);if(n=await navigator.gpu.requestAdapter({powerPreference:o,forceFallbackAdapter:i}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag \"--enable-unsafe-webgpu\" if you are using Chrome.')}await r(\"webgpu\",Ce(),e,n)}if(t===\"webnn\"){if(typeof navigator>\"u\"||!navigator.ml)throw new Error(\"WebNN is not supported in current environment\");await r(\"webnn\",Ce(),e)}}},kt=new Map,dg=e=>{let t=Ce(),r=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,o,o+n)!==0&&pe(\"Can't get session input/output count.\");let a=n===4?\"i32\":\"i64\";return[Number(t.getValue(o,a)),Number(t.getValue(o+n,a))]}finally{t.stackRestore(r)}},Kt=e=>{let t=Ce(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},Er=async(e,t)=>{let r,n,o=Ce();Array.isArray(e)?[r,n]=e:e.buffer===o.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=Kt(e);let i=0,a=0,l=0,d=[],p=[],m=[];try{if([a,d]=Ga(t),t?.externalData&&o.mountExternalData){let v=[];for(let S of t.externalData){let T=typeof S==\"string\"?S:S.path;v.push(Xt(typeof S==\"string\"?S:S.data).then(C=>{o.mountExternalData(T,C)}))}await Promise.all(v)}for(let v of t?.executionProviders??[])if((typeof v==\"string\"?v:v.name)===\"webnn\"){if(o.shouldTransferToMLTensor=!1,typeof v!=\"string\"){let T=v,C=T?.context,A=T?.gpuDevice,P=T?.deviceType,O=T?.powerPreference;C?o.currentContext=C:A?o.currentContext=await o.jsepCreateMLContext(A):o.currentContext=await o.jsepCreateMLContext({deviceType:P,powerPreference:O})}else o.currentContext=await o.jsepCreateMLContext();break}i=await o._OrtCreateSession(r,n,a),i===0&&pe(\"Can't create a session.\"),o.jsepOnCreateSession?.(),o.currentContext&&(o.jsepRegisterMLContext(i,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[u,h]=dg(i),_=!!t?.enableGraphCapture,y=[],g=[],x=[];for(let v=0;vv===\"gpu-buffer\"||v===\"ml-tensor\")&&(l=o._OrtCreateBinding(i),l===0&&pe(\"Can't create IO binding.\"),$={handle:l,outputPreferredLocations:x,outputPreferredLocationsEncoded:x.map(v=>Xn(v))}),kt.set(i,[i,p,m,$,_,!1]),[i,y,g]}catch(u){throw p.forEach(h=>o._OrtFree(h)),m.forEach(h=>o._OrtFree(h)),l!==0&&o._OrtReleaseBinding(l)!==0&&pe(\"Can't release IO binding.\"),i!==0&&o._OrtReleaseSession(i)!==0&&pe(\"Can't release session.\"),u}finally{o._free(r),a!==0&&o._OrtReleaseSessionOptions(a)!==0&&pe(\"Can't release session options.\"),d.forEach(u=>o._free(u)),o.unmountExternalData?.()}},Pr=e=>{let t=Ce(),r=kt.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,o,i,a,l]=r;a&&(l&&t._OrtClearBoundOutputs(a.handle)!==0&&pe(\"Can't clear bound outputs.\"),t._OrtReleaseBinding(a.handle)!==0&&pe(\"Can't release IO binding.\")),t.jsepOnReleaseSession?.(e),o.forEach(d=>t._OrtFree(d)),i.forEach(d=>t._OrtFree(d)),t._OrtReleaseSession(n)!==0&&pe(\"Can't release session.\"),kt.delete(e)},nc=(e,t,r,n,o,i=!1)=>{if(!e){t.push(0);return}let a=Ce(),l=a.PTR_SIZE,d=e[0],p=e[1],m=e[3],u,h;if(d===\"string\"&&(m===\"gpu-buffer\"||m===\"ml-tensor\"))throw new Error(\"String tensor is not supported on GPU.\");if(i&&m!==\"gpu-buffer\")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(m===\"gpu-buffer\"){let g=e[2].gpuBuffer;h=Tt(Zt(d),p);let x=a.jsepRegisterBuffer;if(!x)throw new Error('Tensor location \"gpu-buffer\" is not supported without using WebGPU.');u=x(n,o,g,h)}else if(m===\"ml-tensor\"){let g=e[2].mlTensor;h=Tt(Zt(d),p);let x=a.jsepRegisterMLTensor;if(!x)throw new Error('Tensor location \"ml-tensor\" is not supported without using WebNN.');u=x(g,Zt(d),p)}else{let g=e[2];if(Array.isArray(g)){h=l*g.length,u=a._malloc(h),r.push(u);for(let x=0;xa.setValue(y+$*l,x,l===4?\"i32\":\"i64\"));let g=a._OrtCreateTensor(Zt(d),u,h,y,p.length,Xn(m));g===0&&pe(`Can't create tensor for input/output. session=${n}, index=${o}.`),t.push(g)}finally{a.stackRestore(_)}},zr=async(e,t,r,n,o,i)=>{let a=Ce(),l=a.PTR_SIZE,d=kt.get(e);if(!d)throw new Error(`cannot run inference. invalid session id: ${e}`);let p=d[0],m=d[1],u=d[2],h=d[3],_=d[4],y=d[5],g=t.length,x=n.length,$=0,v=[],S=[],T=[],C=[],A=a.stackSave(),P=a.stackAlloc(g*l),O=a.stackAlloc(g*l),U=a.stackAlloc(x*l),G=a.stackAlloc(x*l);try{a.jsepOnRunStart?.(p),[$,v]=Wa(i);for(let W=0;W_e*be,1);ee=gt($e);let Ge=h?.outputPreferredLocations[n[W]];if(ee===\"string\"){if(Ge===\"gpu-buffer\"||Ge===\"ml-tensor\")throw new Error(\"String tensor is not supported on GPU.\");let _e=[];for(let be=0;be0){let _e=a.jsepGetBuffer;if(!_e)throw new Error('preferredLocation \"gpu-buffer\" is not supported without using WebGPU.');let be=_e(ne),Ke=Tt($e,he);if(Ke===void 0||!Ur(ee))throw new Error(`Unsupported data type: ${ee}`);re=!0,K.push([ee,j,{gpuBuffer:be,download:a.jsepCreateDownloader(be,Ke,ee),dispose:()=>{a._OrtReleaseTensor(Y)!==0&&pe(\"Can't release tensor.\")}},\"gpu-buffer\"])}else if(Ge===\"ml-tensor\"&&he>0){let _e=a.jsepEnsureTensor;if(!_e)throw new Error('preferredLocation \"ml-tensor\" is not supported without using WebNN.');if(Tt($e,he)===void 0||!Nr(ee))throw new Error(`Unsupported data type: ${ee}`);let Ke=await _e(ne,$e,j,!1);re=!0,K.push([ee,j,{mlTensor:Ke,download:a.jsepCreateMLTensorDownloader(ne,ee),dispose:()=>{a.jsepReleaseTensorId(ne),a._OrtReleaseTensor(Y)}},\"ml-tensor\"])}else{let _e=Rr(ee),be=new _e(he);new Uint8Array(be.buffer,be.byteOffset,be.byteLength).set(a.HEAPU8.subarray(ne,ne+be.byteLength)),K.push([ee,j,be,\"cpu\"])}}finally{a.stackRestore(se),ee===\"string\"&&ne&&a._free(ne),re||a._OrtReleaseTensor(Y)}}return h&&!_&&(a._OrtClearBoundOutputs(h.handle)!==0&&pe(\"Can't clear bound outputs.\"),kt.set(e,[p,m,u,h,_,!1])),K}finally{a.stackRestore(A),S.forEach(q=>a._OrtReleaseTensor(q)),T.forEach(q=>a._OrtReleaseTensor(q)),C.forEach(q=>a._free(q)),$!==0&&a._OrtReleaseRunOptions($),v.forEach(q=>a._free(q))}},Or=e=>{let t=Ce(),r=kt.get(e);if(!r)throw new Error(\"invalid session id\");let n=r[0],o=t._OrtEndProfiling(n);o===0&&pe(\"Can't get an profile file name.\"),t._OrtFree(o)},Br=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&\"buffer\"in n&&t.push(n.buffer)}return t}});var Et,Le,or,mn,fn,pn,zo,Oo,Vt,Wt,pg,oc,ic,ac,sc,uc,lc,dc,Bo=R(()=>{\"use strict\";We();Kn();ht();jt();Et=()=>!!we.wasm.proxy&&typeof document<\"u\",or=!1,mn=!1,fn=!1,Oo=new Map,Vt=(e,t)=>{let r=Oo.get(e);r?r.push(t):Oo.set(e,[t])},Wt=()=>{if(or||!mn||fn||!Le)throw new Error(\"worker not ready\")},pg=e=>{switch(e.data.type){case\"init-wasm\":or=!1,e.data.err?(fn=!0,zo[1](e.data.err)):(mn=!0,zo[0]()),pn&&(URL.revokeObjectURL(pn),pn=void 0);break;case\"init-ep\":case\"copy-from\":case\"create\":case\"release\":case\"run\":case\"end-profiling\":{let t=Oo.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},oc=async()=>{if(!mn){if(or)throw new Error(\"multiple calls to 'initWasm()' detected.\");if(fn)throw new Error(\"previous call to 'initWasm()' failed.\");if(or=!0,Et())return new Promise((e,t)=>{Le?.terminate(),Ua().then(([r,n])=>{try{Le=n,Le.onerror=i=>t(i),Le.onmessage=pg,zo=[e,t];let o={type:\"init-wasm\",in:we};Le.postMessage(o),pn=r}catch(o){t(o)}},t)});try{await Cr(we.wasm),await Ar(we),mn=!0}catch(e){throw fn=!0,e}finally{or=!1}}},ic=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Vt(\"init-ep\",[t,r]);let n={type:\"init-ep\",in:{epName:e,env:we}};Le.postMessage(n)});await kr(we,e)},ac=async e=>Et()?(Wt(),new Promise((t,r)=>{Vt(\"copy-from\",[t,r]);let n={type:\"copy-from\",in:{buffer:e}};Le.postMessage(n,[e.buffer])})):Kt(e),sc=async(e,t)=>{if(Et()){if(t?.preferredOutputLocation)throw new Error('session option \"preferredOutputLocation\" is not supported for proxy.');return Wt(),new Promise((r,n)=>{Vt(\"create\",[r,n]);let o={type:\"create\",in:{model:e,options:{...t}}},i=[];e instanceof Uint8Array&&i.push(e.buffer),Le.postMessage(o,i)})}else return Er(e,t)},uc=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Vt(\"release\",[t,r]);let n={type:\"release\",in:e};Le.postMessage(n)});Pr(e)},lc=async(e,t,r,n,o,i)=>{if(Et()){if(r.some(a=>a[3]!==\"cpu\"))throw new Error(\"input tensor on GPU is not supported for proxy.\");if(o.some(a=>a))throw new Error(\"pre-allocated output tensor is not supported for proxy.\");return Wt(),new Promise((a,l)=>{Vt(\"run\",[a,l]);let d=r,p={type:\"run\",in:{sessionId:e,inputIndices:t,inputs:d,outputIndices:n,options:i}};Le.postMessage(p,Br(d))})}else return zr(e,t,r,n,o,i)},dc=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Vt(\"end-profiling\",[t,r]);let n={type:\"end-profiling\",in:e};Le.postMessage(n)});Or(e)}});var cc,mg,hn,pc=R(()=>{\"use strict\";We();Bo();te();Ir();Jn();cc=(e,t)=>{switch(e.location){case\"cpu\":return[e.type,e.dims,e.data,\"cpu\"];case\"gpu-buffer\":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},\"gpu-buffer\"];case\"ml-tensor\":return[e.type,e.dims,{mlTensor:e.mlTensor},\"ml-tensor\"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},mg=e=>{switch(e[3]){case\"cpu\":return new Oe(e[0],e[2],e[1]);case\"gpu-buffer\":{let t=e[0];if(!Ur(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:o}=e[2];return Oe.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:o})}case\"ml-tensor\":{let t=e[0];if(!Nr(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:o}=e[2];return Oe.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},hn=class{async fetchModelAndCopyToWasmMemory(t){return ac(await Xt(t))}async loadModel(t,r){Ue();let n;typeof t==\"string\"?!1?n=await Xt(t):n=await this.fetchModelAndCopyToWasmMemory(t):n=t,[this.sessionId,this.inputNames,this.outputNames]=await sc(n,r),De()}async dispose(){return uc(this.sessionId)}async run(t,r,n){Ue();let o=[],i=[];Object.entries(t).forEach(h=>{let _=h[0],y=h[1],g=this.inputNames.indexOf(_);if(g===-1)throw new Error(`invalid input '${_}'`);o.push(y),i.push(g)});let a=[],l=[];Object.entries(r).forEach(h=>{let _=h[0],y=h[1],g=this.outputNames.indexOf(_);if(g===-1)throw new Error(`invalid output '${_}'`);a.push(y),l.push(g)});let d=o.map((h,_)=>cc(h,()=>`input \"${this.inputNames[i[_]]}\"`)),p=a.map((h,_)=>h?cc(h,()=>`output \"${this.outputNames[l[_]]}\"`):null),m=await lc(this.sessionId,i,d,l,p,n),u={};for(let h=0;hgn,initializeFlags:()=>mc,wasmBackend:()=>fg});var mc,gn,fg,hc=R(()=>{\"use strict\";We();Bo();pc();jt();mc=()=>{if((typeof we.wasm.initTimeout!=\"number\"||we.wasm.initTimeout<0)&&(we.wasm.initTimeout=0),we.wasm.simd===!1&&console.warn('Deprecated property \"env.wasm.simd\" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof we.wasm.proxy!=\"boolean\"&&(we.wasm.proxy=!1),typeof we.wasm.trace!=\"boolean\"&&(we.wasm.trace=!1),typeof we.wasm.numThreads!=\"number\"||!Number.isInteger(we.wasm.numThreads)||we.wasm.numThreads<=0)if(typeof self<\"u\"&&!self.crossOriginIsolated)we.wasm.numThreads=1;else{let e=typeof navigator>\"u\"?Gn(\"node:os\").cpus().length:navigator.hardwareConcurrency;we.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},gn=class{async init(t){mc(),await oc(),await ic(t)}async createInferenceSessionHandler(t,r){let n=new hn;return await n.loadModel(t,r),Promise.resolve(n)}},fg=new gn});We();We();We();var ka=\"1.21.0-dev.20241122-a2ba3cb547\";var bS=jn;{let e=(hc(),br(fc)).wasmBackend;xt(\"webgpu\",e,5),xt(\"webnn\",e,5),xt(\"cpu\",e,10),xt(\"wasm\",e,10)}Object.defineProperty(we.versions,\"web\",{value:ka,enumerable:!0});export{Np as InferenceSession,xr as TRACE,Ue as TRACE_FUNC_BEGIN,De as TRACE_FUNC_END,Oe as Tensor,Wp as TrainingSession,bS as default,we as env,xt as registerBackend};\n/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n//# sourceMappingURL=ort.webgpu.bundle.min.mjs.map\n","/**\n * @file Handler file for choosing the correct version of ONNX Runtime, based on the environment.\n * Ideally, we could import the `onnxruntime-web` and `onnxruntime-node` packages only when needed,\n * but dynamic imports don't seem to work with the current webpack version and/or configuration.\n * This is possibly due to the experimental nature of top-level await statements.\n * So, we just import both packages, and use the appropriate one based on the environment:\n * - When running in node, we use `onnxruntime-node`.\n * - When running in the browser, we use `onnxruntime-web` (`onnxruntime-node` is not bundled).\n * \n * This module is not directly exported, but can be accessed through the environment variables:\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * console.log(env.backends.onnx);\n * ```\n * \n * @module backends/onnx\n */\n\nimport { env, apis } from '../env.js';\n\n// NOTE: Import order matters here. We need to import `onnxruntime-node` before `onnxruntime-web`.\n// In either case, we select the default export if it exists, otherwise we use the named export.\nimport * as ONNX_NODE from 'onnxruntime-node';\n\n// Use subpath-imports to ensure Node.js and browser interoperability.\n// See package.json and https://nodejs.org/api/packages.html#subpath-imports\n// for more information.\n// @ts-ignore\nimport * as ONNX_WEB from '#onnxruntime-webgpu';\n\nexport { Tensor } from 'onnxruntime-common';\n\n/**\n * @typedef {import('onnxruntime-common').InferenceSession.ExecutionProviderConfig} ONNXExecutionProviders\n */\n\n/** @type {Record} */\nconst DEVICE_TO_EXECUTION_PROVIDER_MAPPING = Object.freeze({\n auto: null, // Auto-detect based on device and environment\n gpu: null, // Auto-detect GPU\n cpu: 'cpu', // CPU\n wasm: 'wasm', // WebAssembly\n webgpu: 'webgpu', // WebGPU\n cuda: 'cuda', // CUDA\n dml: 'dml', // DirectML\n\n webnn: { name: 'webnn', deviceType: 'cpu' }, // WebNN (default)\n 'webnn-npu': { name: 'webnn', deviceType: 'npu' }, // WebNN NPU\n 'webnn-gpu': { name: 'webnn', deviceType: 'gpu' }, // WebNN GPU\n 'webnn-cpu': { name: 'webnn', deviceType: 'cpu' }, // WebNN CPU\n});\n\n/** \n * The list of supported devices, sorted by priority/performance.\n * @type {import(\"../utils/devices.js\").DeviceType[]}\n */\nconst supportedDevices = [];\n\n/** @type {ONNXExecutionProviders[]} */\nlet defaultDevices;\nlet ONNX;\nconst ORT_SYMBOL = Symbol.for('onnxruntime');\n\nif (ORT_SYMBOL in globalThis) {\n // If the JS runtime exposes their own ONNX runtime, use it\n ONNX = globalThis[ORT_SYMBOL];\n\n} else if (apis.IS_NODE_ENV) {\n ONNX = ONNX_NODE.default ?? ONNX_NODE;\n\n // Updated as of ONNX Runtime 1.18.0\n // The following table lists the supported versions of ONNX Runtime Node.js binding provided with pre-built binaries.\n // | EPs/Platforms | Windows x64 | Windows arm64 | Linux x64 | Linux arm64 | MacOS x64 | MacOS arm64 |\n // | ------------- | ----------- | ------------- | ----------------- | ----------- | --------- | ----------- |\n // | CPU | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |\n // | DirectML | ✔️ | ✔️ | ❌ | ❌ | ❌ | ❌ |\n // | CUDA | ❌ | ❌ | ✔️ (CUDA v11.8) | ❌ | ❌ | ❌ |\n switch (process.platform) {\n case 'win32': // Windows x64 and Windows arm64\n supportedDevices.push('dml');\n break;\n case 'linux': // Linux x64 and Linux arm64\n if (process.arch === 'x64') {\n supportedDevices.push('cuda');\n }\n break;\n case 'darwin': // MacOS x64 and MacOS arm64\n break;\n }\n\n supportedDevices.push('cpu');\n defaultDevices = ['cpu'];\n} else {\n ONNX = ONNX_WEB;\n\n if (apis.IS_WEBNN_AVAILABLE) {\n // TODO: Only push supported providers (depending on available hardware)\n supportedDevices.push('webnn-npu', 'webnn-gpu', 'webnn-cpu', 'webnn');\n }\n\n if (apis.IS_WEBGPU_AVAILABLE) {\n supportedDevices.push('webgpu');\n }\n\n supportedDevices.push('wasm');\n defaultDevices = ['wasm'];\n}\n\n// @ts-ignore\nconst InferenceSession = ONNX.InferenceSession;\n\n/**\n * Map a device to the execution providers to use for the given device.\n * @param {import(\"../utils/devices.js\").DeviceType|\"auto\"|null} [device=null] (Optional) The device to run the inference on.\n * @returns {ONNXExecutionProviders[]} The execution providers to use for the given device.\n */\nexport function deviceToExecutionProviders(device = null) {\n // Use the default execution providers if the user hasn't specified anything\n if (!device) return defaultDevices;\n\n // Handle overloaded cases\n switch (device) {\n case \"auto\":\n return supportedDevices;\n case \"gpu\":\n return supportedDevices.filter(x =>\n [\"webgpu\", \"cuda\", \"dml\", \"webnn-gpu\"].includes(x),\n );\n }\n\n if (supportedDevices.includes(device)) {\n return [DEVICE_TO_EXECUTION_PROVIDER_MAPPING[device] ?? device];\n }\n\n throw new Error(`Unsupported device: \"${device}\". Should be one of: ${supportedDevices.join(', ')}.`)\n}\n\n\n/**\n * To prevent multiple calls to `initWasm()`, we store the first call in a Promise\n * that is resolved when the first InferenceSession is created. Subsequent calls\n * will wait for this Promise to resolve before creating their own InferenceSession.\n * @type {Promise|null}\n */\nlet wasmInitPromise = null;\n\n/**\n * Create an ONNX inference session.\n * @param {Uint8Array} buffer The ONNX model buffer.\n * @param {import('onnxruntime-common').InferenceSession.SessionOptions} session_options ONNX inference session options.\n * @param {Object} session_config ONNX inference session configuration.\n * @returns {Promise} The ONNX inference session.\n */\nexport async function createInferenceSession(buffer, session_options, session_config) {\n if (wasmInitPromise) {\n // A previous session has already initialized the WASM runtime\n // so we wait for it to resolve before creating this new session.\n await wasmInitPromise;\n }\n\n const sessionPromise = InferenceSession.create(buffer, session_options);\n wasmInitPromise ??= sessionPromise;\n const session = await sessionPromise;\n session.config = session_config;\n return session;\n}\n\n/**\n * Check if an object is an ONNX tensor.\n * @param {any} x The object to check\n * @returns {boolean} Whether the object is an ONNX tensor.\n */\nexport function isONNXTensor(x) {\n return x instanceof ONNX.Tensor;\n}\n\n/** @type {import('onnxruntime-common').Env} */\n// @ts-ignore\nconst ONNX_ENV = ONNX?.env;\nif (ONNX_ENV?.wasm) {\n // Initialize wasm backend with suitable default settings.\n\n // (Optional) Set path to wasm files. This is needed when running in a web worker.\n // https://onnxruntime.ai/docs/api/js/interfaces/Env.WebAssemblyFlags.html#wasmPaths\n // We use remote wasm files by default to make it easier for newer users.\n // In practice, users should probably self-host the necessary .wasm files.\n ONNX_ENV.wasm.wasmPaths = `https://cdn.jsdelivr.net/npm/@huggingface/transformers@${env.version}/dist/`;\n\n // TODO: Add support for loading WASM files from cached buffer when we upgrade to onnxruntime-web@1.19.0\n // https://github.com/microsoft/onnxruntime/pull/21534\n\n // Users may wish to proxy the WASM backend to prevent the UI from freezing,\n // However, this is not necessary when using WebGPU, so we default to false.\n ONNX_ENV.wasm.proxy = false;\n\n // https://developer.mozilla.org/en-US/docs/Web/API/crossOriginIsolated\n if (typeof crossOriginIsolated === 'undefined' || !crossOriginIsolated) {\n ONNX_ENV.wasm.numThreads = 1;\n }\n}\n\nif (ONNX_ENV?.webgpu) {\n ONNX_ENV.webgpu.powerPreference = 'high-performance';\n}\n\n/**\n * Check if ONNX's WASM backend is being proxied.\n * @returns {boolean} Whether ONNX's WASM backend is being proxied.\n */\nexport function isONNXProxy() {\n // TODO: Update this when allowing non-WASM backends.\n return ONNX_ENV?.wasm?.proxy;\n}\n\n// Expose ONNX environment variables to `env.backends.onnx`\nenv.backends.onnx = ONNX_ENV;\n","\n/**\n * @file Helper module for using model configs. For more information, see the corresponding\n * [Python documentation](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoConfig).\n * \n * **Example:** Load an `AutoConfig`.\n * \n * ```javascript\n * import { AutoConfig } from '@huggingface/transformers';\n * const config = await AutoConfig.from_pretrained('bert-base-uncased');\n * console.log(config);\n * // PretrainedConfig {\n * // \"model_type\": \"bert\",\n * // \"is_encoder_decoder\": false,\n * // \"architectures\": [\n * // \"BertForMaskedLM\"\n * // ],\n * // \"vocab_size\": 30522\n * // \"num_attention_heads\": 12,\n * // \"num_hidden_layers\": 12,\n * // \"hidden_size\": 768,\n * // \"max_position_embeddings\": 512,\n * // ...\n * // }\n * ```\n * \n * @module configs\n */\n\nimport { pick } from './utils/core.js';\nimport {\n getModelJSON,\n} from './utils/hub.js';\n\n/**\n * @typedef {import('./utils/hub.js').PretrainedOptions} PretrainedOptions\n */\n\n\n/**\n * Loads a config from the specified path.\n * @param {string} pretrained_model_name_or_path The path to the config directory.\n * @param {PretrainedOptions} options Additional options for loading the config.\n * @returns {Promise} A promise that resolves with information about the loaded config.\n */\nasync function loadConfig(pretrained_model_name_or_path, options) {\n return await getModelJSON(pretrained_model_name_or_path, 'config.json', true, options);\n}\n\n/**\n * \n * @param {PretrainedConfig} config \n * @returns {Object} The normalized configuration.\n */\nfunction getNormalizedConfig(config) {\n const mapping = {};\n\n let init_normalized_config = {};\n switch (config.model_type) {\n // Sub-configs\n case 'llava':\n case 'paligemma':\n case 'florence2':\n init_normalized_config = getNormalizedConfig(config.text_config);\n break;\n case 'moondream1':\n init_normalized_config = getNormalizedConfig(config.phi_config);\n break;\n case 'musicgen':\n init_normalized_config = getNormalizedConfig(config.decoder);\n break;\n\n // Decoder-only models\n case 'gpt2':\n case 'gptj':\n case 'jais':\n case 'codegen':\n case 'gpt_bigcode':\n mapping['num_heads'] = 'n_head';\n mapping['num_layers'] = 'n_layer';\n mapping['hidden_size'] = 'n_embd';\n break;\n case 'gpt_neox':\n case 'stablelm':\n case 'opt':\n case 'phi':\n case 'phi3':\n case 'falcon':\n mapping['num_heads'] = 'num_attention_heads';\n mapping['num_layers'] = 'num_hidden_layers';\n mapping['hidden_size'] = 'hidden_size';\n break;\n case 'llama':\n case 'granite':\n case 'cohere':\n case 'mistral':\n case 'starcoder2':\n case 'qwen2':\n mapping['num_heads'] = 'num_key_value_heads';\n mapping['num_layers'] = 'num_hidden_layers';\n mapping['hidden_size'] = 'hidden_size';\n mapping['num_attention_heads'] = 'num_attention_heads';\n break;\n case 'gemma':\n case 'gemma2':\n mapping['num_heads'] = 'num_key_value_heads';\n mapping['num_layers'] = 'num_hidden_layers';\n mapping['dim_kv'] = 'head_dim';\n break;\n case 'openelm':\n mapping['num_heads'] = 'num_kv_heads';\n mapping['num_layers'] = 'num_transformer_layers';\n mapping['dim_kv'] = 'head_dim';\n break;\n case 'gpt_neo':\n case 'donut-swin':\n mapping['num_heads'] = 'num_heads';\n mapping['num_layers'] = 'num_layers';\n mapping['hidden_size'] = 'hidden_size';\n break;\n case 'bloom':\n mapping['num_heads'] = 'n_head';\n mapping['num_layers'] = 'n_layer';\n mapping['hidden_size'] = 'hidden_size';\n break;\n case 'mpt':\n mapping['num_heads'] = 'n_heads';\n mapping['num_layers'] = 'n_layers';\n mapping['hidden_size'] = 'd_model';\n break;\n\n // Encoder-decoder models\n case 't5':\n case 'mt5':\n case 'longt5':\n mapping['num_decoder_layers'] = 'num_decoder_layers';\n mapping['num_decoder_heads'] = 'num_heads';\n mapping['decoder_dim_kv'] = 'd_kv';\n mapping['num_encoder_layers'] = 'num_layers';\n mapping['num_encoder_heads'] = 'num_heads';\n mapping['encoder_dim_kv'] = 'd_kv';\n break;\n case 'bart':\n case 'mbart':\n case 'marian':\n case 'whisper':\n case 'm2m_100':\n case 'blenderbot':\n case 'blenderbot-small':\n case 'florence2_language':\n mapping['num_decoder_layers'] = 'decoder_layers';\n mapping['num_decoder_heads'] = 'decoder_attention_heads';\n mapping['decoder_hidden_size'] = 'd_model';\n mapping['num_encoder_layers'] = 'encoder_layers';\n mapping['num_encoder_heads'] = 'encoder_attention_heads';\n mapping['encoder_hidden_size'] = 'd_model';\n break;\n case 'speecht5':\n mapping['num_decoder_layers'] = 'decoder_layers';\n mapping['num_decoder_heads'] = 'decoder_attention_heads';\n mapping['decoder_hidden_size'] = 'hidden_size';\n mapping['num_encoder_layers'] = 'encoder_layers';\n mapping['num_encoder_heads'] = 'encoder_attention_heads';\n mapping['encoder_hidden_size'] = 'hidden_size';\n break;\n case 'trocr':\n mapping['num_encoder_layers'] = mapping['num_decoder_layers'] = 'decoder_layers';\n mapping['num_encoder_heads'] = mapping['num_decoder_heads'] = 'decoder_attention_heads';\n mapping['encoder_hidden_size'] = mapping['decoder_hidden_size'] = 'd_model';\n break;\n case 'musicgen_decoder':\n mapping['num_encoder_layers'] = mapping['num_decoder_layers'] = 'num_hidden_layers';\n mapping['num_encoder_heads'] = mapping['num_decoder_heads'] = 'num_attention_heads';\n mapping['encoder_hidden_size'] = mapping['decoder_hidden_size'] = 'hidden_size';\n break;\n\n case 'vision-encoder-decoder':\n const decoderConfig = getNormalizedConfig(config.decoder);\n\n const add_encoder_pkv = 'num_decoder_layers' in decoderConfig;\n const result = pick(config, ['model_type', 'is_encoder_decoder']);\n if (add_encoder_pkv) {\n // Decoder is part of an encoder-decoder model\n result.num_decoder_layers = decoderConfig.num_decoder_layers;\n result.num_decoder_heads = decoderConfig.num_decoder_heads;\n result.decoder_hidden_size = decoderConfig.decoder_hidden_size;\n\n result.num_encoder_layers = decoderConfig.num_encoder_layers;\n result.num_encoder_heads = decoderConfig.num_encoder_heads;\n result.encoder_hidden_size = decoderConfig.encoder_hidden_size;\n } else {\n // Decoder is a decoder-only model\n result.num_layers = decoderConfig.num_layers;\n result.num_heads = decoderConfig.num_heads;\n result.hidden_size = decoderConfig.hidden_size;\n }\n return result;\n\n }\n\n // NOTE: If `num_attention_heads` is not set, it is assumed to be equal to `num_heads`\n const normalized_config = {\n ...init_normalized_config,\n ...pick(config, ['model_type', 'multi_query', 'is_encoder_decoder']),\n };\n for (const key in mapping) {\n normalized_config[key] = config[mapping[key]];\n }\n return normalized_config;\n}\n\n/**\n * \n * @param {PretrainedConfig} config \n * @returns {Record}\n */\nexport function getKeyValueShapes(config, {\n prefix = 'past_key_values',\n} = {}) {\n /** @type {Record} */\n const decoderFeeds = {};\n const normalized_config = config.normalized_config;\n\n // TODO support batches (i.e., batch_size > 1)\n const batch_size = 1;\n\n if (normalized_config.is_encoder_decoder && (\n 'num_encoder_heads' in normalized_config && 'num_decoder_heads' in normalized_config\n )) {\n const encoder_dim_kv = normalized_config.encoder_dim_kv ?? (\n normalized_config.encoder_hidden_size / normalized_config.num_encoder_heads\n );\n const decoder_dim_kv = normalized_config.decoder_dim_kv ?? (\n normalized_config.decoder_hidden_size / normalized_config.num_decoder_heads\n );\n\n const encoder_dims = [batch_size, normalized_config.num_encoder_heads, 0, encoder_dim_kv];\n const decoder_dims = [batch_size, normalized_config.num_decoder_heads, 0, decoder_dim_kv];\n for (let i = 0; i < normalized_config.num_decoder_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.encoder.key`] = encoder_dims;\n decoderFeeds[`${prefix}.${i}.encoder.value`] = encoder_dims;\n decoderFeeds[`${prefix}.${i}.decoder.key`] = decoder_dims;\n decoderFeeds[`${prefix}.${i}.decoder.value`] = decoder_dims;\n }\n } else { // Decoders\n const num_heads = normalized_config.num_heads;\n const num_layers = normalized_config.num_layers;\n const dim_kv = normalized_config.dim_kv ?? (\n normalized_config.hidden_size /\n (normalized_config.num_attention_heads ?? num_heads)\n );\n\n if (normalized_config.model_type === 'falcon') {\n // NOTE: Custom implementation for Falcon\n const dims = [batch_size * num_heads, 0, dim_kv]\n for (let i = 0; i < num_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.key`] = dims;\n decoderFeeds[`${prefix}.${i}.value`] = dims;\n }\n } else if (normalized_config.multi_query) { // e.g., for `gpt_bigcode`\n const dims = [batch_size * num_heads, 0, 2 * dim_kv]\n\n for (let i = 0; i < num_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.key_value`] = dims;\n }\n } else if (normalized_config.model_type === 'bloom') {\n // NOTE: Custom implementation for Bloom\n\n const keyDims = [batch_size * num_heads, dim_kv, 0] // [batch_size x num_heads,64,past_sequence_length]\n const valueDims = [batch_size * num_heads, 0, dim_kv] // [batch_size x num_heads,past_sequence_length,64]\n for (let i = 0; i < num_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.key`] = keyDims;\n decoderFeeds[`${prefix}.${i}.value`] = valueDims;\n }\n } else if (normalized_config.model_type === 'openelm') {\n for (let i = 0; i < num_layers; ++i) {\n const dims = [batch_size, num_heads[i], 0, dim_kv]\n\n decoderFeeds[`${prefix}.${i}.key`] = dims;\n decoderFeeds[`${prefix}.${i}.value`] = dims;\n }\n } else { // Decoder-only\n const dims = [batch_size, num_heads, 0, dim_kv]\n for (let i = 0; i < num_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.key`] = dims;\n decoderFeeds[`${prefix}.${i}.value`] = dims;\n }\n }\n }\n\n return decoderFeeds;\n}\n/**\n * Base class for all configuration classes. For more information, see the corresponding\n * [Python documentation](https://huggingface.co/docs/transformers/main/en/main_classes/configuration#transformers.PretrainedConfig).\n */\nexport class PretrainedConfig {\n // NOTE: Typo in original\n\n /** @type {string|null} */\n model_type = null;\n\n /** @type {boolean} */\n is_encoder_decoder = false;\n\n /** @type {number} */\n max_position_embeddings;\n\n /** @type {TransformersJSConfig} */\n 'transformers.js_config';\n\n /**\n * Create a new PreTrainedTokenizer instance.\n * @param {Object} configJSON The JSON of the config.\n */\n constructor(configJSON) {\n Object.assign(this, configJSON);\n this.normalized_config = getNormalizedConfig(this);\n }\n\n /**\n * Loads a pre-trained config from the given `pretrained_model_name_or_path`. \n * \n * @param {string} pretrained_model_name_or_path The path to the pre-trained config.\n * @param {PretrainedOptions} options Additional options for loading the config.\n * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.\n * \n * @returns {Promise} A new instance of the `PretrainedConfig` class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n } = {}) {\n if (config && !(config instanceof PretrainedConfig)) {\n config = new PretrainedConfig(config);\n }\n\n const data = config ?? await loadConfig(pretrained_model_name_or_path, {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n })\n return new this(data);\n }\n}\n\n/**\n * Helper class which is used to instantiate pretrained configs with the `from_pretrained` function.\n * \n * @example\n * const config = await AutoConfig.from_pretrained('Xenova/bert-base-uncased'); \n */\nexport class AutoConfig {\n /** @type {typeof PretrainedConfig.from_pretrained} */\n static async from_pretrained(...args) {\n return PretrainedConfig.from_pretrained(...args);\n }\n}\n\n/**\n * Transformers.js-specific configuration, possibly present in config.json under the key `transformers.js_config`.\n * @typedef {Object} TransformersJSConfig\n * @property {import('./utils/tensor.js').DataType|Record} [kv_cache_dtype] The data type of the key-value cache.\n * @property {Record} [free_dimension_overrides] Override the free dimensions of the model.\n * See https://onnxruntime.ai/docs/tutorials/web/env-flags-and-session-options.html#freedimensionoverrides\n * for more information.\n * @property {import('./utils/devices.js').DeviceType} [device] The default device to use for the model.\n * @property {import('./utils/dtypes.js').DataType} [dtype] The default data type to use for the model.\n * @property {boolean|Record} [use_external_data_format=false] Whether to load the model using the external data format (used for models >= 2GB in size).\n */\n","/**\n * @file Module used to configure Transformers.js.\n * \n * **Example:** Disable remote models.\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * env.allowRemoteModels = false;\n * ```\n * \n * **Example:** Set local model path.\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * env.localModelPath = '/path/to/local/models/';\n * ```\n * \n * **Example:** Set cache directory.\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * env.cacheDir = '/path/to/cache/directory/';\n * ```\n * \n * @module env\n */\n\nimport fs from 'fs';\nimport path from 'path';\nimport url from 'url';\n\nconst VERSION = '3.0.0';\n\n// Check if various APIs are available (depends on environment)\nconst IS_BROWSER_ENV = typeof self !== 'undefined';\nconst IS_WEBWORKER_ENV = IS_BROWSER_ENV && self.constructor.name === 'DedicatedWorkerGlobalScope';\nconst IS_WEB_CACHE_AVAILABLE = IS_BROWSER_ENV && 'caches' in self;\nconst IS_WEBGPU_AVAILABLE = typeof navigator !== 'undefined' && 'gpu' in navigator;\nconst IS_WEBNN_AVAILABLE = typeof navigator !== 'undefined' && 'ml' in navigator;\n\nconst IS_PROCESS_AVAILABLE = typeof process !== 'undefined';\nconst IS_NODE_ENV = IS_PROCESS_AVAILABLE && process?.release?.name === 'node';\nconst IS_FS_AVAILABLE = !isEmpty(fs);\nconst IS_PATH_AVAILABLE = !isEmpty(path);\n\n/**\n * A read-only object containing information about the APIs available in the current environment.\n */\nexport const apis = Object.freeze({\n /** Whether we are running in a browser environment */\n IS_BROWSER_ENV,\n\n /** Whether we are running in a web worker environment */\n IS_WEBWORKER_ENV,\n\n /** Whether the Cache API is available */\n IS_WEB_CACHE_AVAILABLE,\n\n /** Whether the WebGPU API is available */\n IS_WEBGPU_AVAILABLE,\n\n /** Whether the WebNN API is available */\n IS_WEBNN_AVAILABLE,\n\n /** Whether the Node.js process API is available */\n IS_PROCESS_AVAILABLE,\n\n /** Whether we are running in a Node.js environment */\n IS_NODE_ENV,\n\n /** Whether the filesystem API is available */\n IS_FS_AVAILABLE,\n\n /** Whether the path API is available */\n IS_PATH_AVAILABLE,\n});\n\nconst RUNNING_LOCALLY = IS_FS_AVAILABLE && IS_PATH_AVAILABLE;\nconst dirname__ = RUNNING_LOCALLY\n ? path.dirname(path.dirname(url.fileURLToPath(import.meta.url)))\n : './';\n\n// Only used for environments with access to file system\nconst DEFAULT_CACHE_DIR = RUNNING_LOCALLY\n ? path.join(dirname__, '/.cache/')\n : null;\n\n// Set local model path, based on available APIs\nconst DEFAULT_LOCAL_MODEL_PATH = '/models/';\nconst localModelPath = RUNNING_LOCALLY\n ? path.join(dirname__, DEFAULT_LOCAL_MODEL_PATH)\n : DEFAULT_LOCAL_MODEL_PATH;\n\n/**\n * Global variable given visible to users to control execution. This provides users a simple way to configure Transformers.js.\n * @typedef {Object} TransformersEnvironment\n * @property {string} version This version of Transformers.js.\n * @property {{onnx: Partial}} backends Expose environment variables of different backends,\n * allowing users to set these variables if they want to.\n * @property {boolean} allowRemoteModels Whether to allow loading of remote files, defaults to `true`.\n * If set to `false`, it will have the same effect as setting `local_files_only=true` when loading pipelines, models, tokenizers, processors, etc.\n * @property {string} remoteHost Host URL to load models from. Defaults to the Hugging Face Hub.\n * @property {string} remotePathTemplate Path template to fill in and append to `remoteHost` when loading models.\n * @property {boolean} allowLocalModels Whether to allow loading of local files, defaults to `false` if running in-browser, and `true` otherwise.\n * If set to `false`, it will skip the local file check and try to load the model from the remote host.\n * @property {string} localModelPath Path to load local models from. Defaults to `/models/`.\n * @property {boolean} useFS Whether to use the file system to load files. By default, it is `true` if available.\n * @property {boolean} useBrowserCache Whether to use Cache API to cache models. By default, it is `true` if available.\n * @property {boolean} useFSCache Whether to use the file system to cache files. By default, it is `true` if available.\n * @property {string} cacheDir The directory to use for caching files with the file system. By default, it is `./.cache`.\n * @property {boolean} useCustomCache Whether to use a custom cache system (defined by `customCache`), defaults to `false`.\n * @property {Object} customCache The custom cache to use. Defaults to `null`. Note: this must be an object which\n * implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache\n */\n\n/** @type {TransformersEnvironment} */\nexport const env = {\n version: VERSION,\n\n /////////////////// Backends settings ///////////////////\n // NOTE: These will be populated later by the backends themselves.\n backends: {\n // onnxruntime-web/onnxruntime-node\n onnx: {},\n },\n\n /////////////////// Model settings ///////////////////\n allowRemoteModels: true,\n remoteHost: 'https://huggingface.co/',\n remotePathTemplate: '{model}/resolve/{revision}/',\n\n allowLocalModels: !IS_BROWSER_ENV,\n localModelPath: localModelPath,\n useFS: IS_FS_AVAILABLE,\n\n /////////////////// Cache settings ///////////////////\n useBrowserCache: IS_WEB_CACHE_AVAILABLE,\n\n useFSCache: IS_FS_AVAILABLE,\n cacheDir: DEFAULT_CACHE_DIR,\n\n useCustomCache: false,\n customCache: null,\n //////////////////////////////////////////////////////\n}\n\n\n/**\n * @param {Object} obj\n * @private\n */\nfunction isEmpty(obj) {\n return Object.keys(obj).length === 0;\n}\n\n","\n/**\n * @module generation/configuration_utils\n */\n\nimport { pick } from \"../utils/core.js\";\n\n/**\n * Class that holds a configuration for a generation task.\n */\nexport class GenerationConfig {\n // Parameters that control the length of the output\n /**\n * The maximum length the generated tokens can have.\n * Corresponds to the length of the input prompt + `max_new_tokens`.\n * Its effect is overridden by `max_new_tokens`, if also set.\n * @type {number}\n * @default 20\n */\n max_length = 20;\n\n /**\n * The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt.\n * @type {number}\n * @default null\n */\n max_new_tokens = null;\n\n /**\n * The minimum length of the sequence to be generated.\n * Corresponds to the length of the input prompt + `min_new_tokens`.\n * Its effect is overridden by `min_new_tokens`, if also set.\n * @type {number}\n * @default 0\n */\n min_length = 0;\n\n /**\n * The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt.\n * @type {number}\n * @default null\n */\n min_new_tokens = null;\n\n /**\n * Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:\n * - `true`, where the generation stops as soon as there are `num_beams` complete candidates;\n * - `false`, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates;\n * - `\"never\"`, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm).\n * @type {boolean|\"never\"}\n * @default false\n */\n early_stopping = false;\n\n /**\n * The maximum amount of time you allow the computation to run for in seconds.\n * Generation will still finish the current pass after allocated time has been passed.\n * @type {number}\n * @default null\n */\n max_time = null;\n\n // Parameters that control the generation strategy used\n /**\n * Whether or not to use sampling; use greedy decoding otherwise.\n * @type {boolean}\n * @default false\n */\n do_sample = false;\n\n /**\n * Number of beams for beam search. 1 means no beam search.\n * @type {number}\n * @default 1\n */\n num_beams = 1;\n\n /**\n * Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams.\n * See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.\n * @type {number}\n * @default 1\n */\n num_beam_groups = 1;\n\n /**\n * The values balance the model confidence and the degeneration penalty in contrastive search decoding.\n * @type {number}\n * @default null\n */\n penalty_alpha = null;\n\n /**\n * Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding.\n * @type {boolean}\n * @default true\n */\n use_cache = true;\n\n // Parameters for manipulation of the model output logits\n /**\n * The value used to modulate the next token probabilities.\n * @type {number}\n * @default 1.0\n */\n temperature = 1.0;\n\n /**\n * The number of highest probability vocabulary tokens to keep for top-k-filtering.\n * @type {number}\n * @default 50\n */\n top_k = 50;\n\n /**\n * If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation.\n * @type {number}\n * @default 1.0\n */\n top_p = 1.0;\n\n /**\n * Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated.\n * If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to `typical_p` or higher are kept for generation.\n * See [this paper](https://arxiv.org/pdf/2202.00666.pdf) for more details.\n * @type {number}\n * @default 1.0\n */\n typical_p = 1.0;\n\n /**\n * If set to float strictly between 0 and 1, only tokens with a conditional probability greater than `epsilon_cutoff` will be sampled.\n * In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model.\n * See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.\n * @type {number}\n * @default 0.0\n */\n epsilon_cutoff = 0.0;\n\n /**\n * Eta sampling is a hybrid of locally typical sampling and epsilon sampling.\n * If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`.\n * The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model.\n * See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.\n * @type {number}\n * @default 0.0\n */\n eta_cutoff = 0.0;\n\n /**\n * This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time.\n * Note that `diversity_penalty` is only effective if `group beam search` is enabled.\n * @type {number}\n * @default 0.0\n */\n diversity_penalty = 0.0;\n\n /**\n * The parameter for repetition penalty. 1.0 means no penalty.\n * See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.\n * @type {number}\n * @default 1.0\n */\n repetition_penalty = 1.0;\n\n /**\n * The paramater for encoder_repetition_penalty.\n * An exponential penalty on sequences that are not in the original input.\n * 1.0 means no penalty.\n * @type {number}\n * @default 1.0\n */\n encoder_repetition_penalty = 1.0;\n\n /**\n * Exponential penalty to the length that is used with beam-based generation.\n * It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence.\n * Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences.\n * @type {number}\n * @default 1.0\n */\n length_penalty = 1.0;\n\n /**\n * If set to int > 0, all ngrams of that size can only occur once.\n * @type {number}\n * @default 0\n */\n no_repeat_ngram_size = 0;\n\n /**\n * List of token ids that are not allowed to be generated.\n * In order to get the token ids of the words that should not appear in the generated text, use\n * `tokenizer(bad_words, { add_prefix_space: true, add_special_tokens: false }).input_ids`.\n * @type {number[][]}\n * @default null\n */\n bad_words_ids = null;\n\n /**\n * List of token ids that must be generated.\n * If given a `number[][]`, this is treated as a simple list of words that must be included, the opposite to `bad_words_ids`.\n * If given `number[][][]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one can allow different forms of each word.\n * @type {number[][]|number[][][]}\n * @default null\n */\n force_words_ids = null;\n\n /**\n * Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones).\n * It's highly recommended to set this flag to `true` as the search algorithms suppose the score logits are normalized but some logit processors or warpers break the normalization.\n * @type {boolean}\n * @default false\n */\n renormalize_logits = false;\n\n /**\n * Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by `Constraint` objects, in the most sensible way possible.\n * @type {Object[]}\n * @default null\n */\n constraints = null;\n\n /**\n * The id of the token to force as the first generated token after the `decoder_start_token_id`.\n * Useful for multilingual models like mBART where the first generated token needs to be the target language token.\n * @type {number}\n * @default null\n */\n forced_bos_token_id = null;\n\n /**\n * The id of the token to force as the last generated token when `max_length` is reached.\n * Optionally, use a list to set multiple *end-of-sequence* tokens.\n * @type {number|number[]}\n * @default null\n */\n forced_eos_token_id = null;\n\n /**\n * Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash. Note that using `remove_invalid_values` can slow down generation.\n * @type {boolean}\n */\n remove_invalid_values = false;\n\n /**\n * This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been generated.\n * The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty starts and `decay_factor` represents the factor of exponential decay.\n * @type {[number, number]}\n * @default null\n */\n exponential_decay_length_penalty = null;\n\n /**\n * A list of tokens that will be suppressed at generation.\n * The `SuppressTokens` logit processor will set their log probs to `-inf` so that they are not sampled.\n * @type {number[]}\n * @default null\n */\n suppress_tokens = null;\n\n /**\n * A list of tokens that will be suppressed at the beginning of the generation.\n * The `SuppressBeginTokens` logit processor will set their log probs to `-inf` so that they are not sampled.\n * @type {number[]}\n * @default null\n */\n begin_suppress_tokens = null;\n\n /**\n * A list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling.\n * For example, `[[1, 123]]` means the second generated token will always be a token of index 123.\n * @type {[number, number][]}\n * @default null\n */\n forced_decoder_ids = null;\n\n /**\n * The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.\n * Higher guidance scale encourages the model to generate samples that are more closely linked to the input\n * prompt, usually at the expense of poorer quality.\n * @type {number}\n * @default null\n */\n guidance_scale = null;\n\n // Parameters that define the output variables of `generate`\n /**\n * The number of independently computed returned sequences for each element in the batch.\n * @type {number}\n * @default 1\n */\n num_return_sequences = 1;\n\n /**\n * Whether or not to return the attentions tensors of all attention layers.\n * See `attentions` under returned tensors for more details.\n * @type {boolean}\n * @default false\n */\n output_attentions = false;\n\n /**\n * Whether or not to return the hidden states of all layers.\n * See `hidden_states` under returned tensors for more details.\n * @type {boolean}\n * @default false\n */\n output_hidden_states = false;\n\n /**\n * Whether or not to return the prediction scores.\n * See `scores` under returned tensors for more details.\n * @type {boolean}\n * @default false\n */\n output_scores = false;\n\n /**\n * Whether or not to return a `ModelOutput` instead of a plain tuple.\n * @type {boolean}\n * @default false\n */\n return_dict_in_generate = false;\n\n // Special tokens that can be used at generation time\n /**\n * The id of the *padding* token.\n * @type {number}\n * @default null\n */\n pad_token_id = null;\n\n /**\n * The id of the *beginning-of-sequence* token.\n * @type {number}\n * @default null\n */\n bos_token_id = null;\n\n /**\n * The id of the *end-of-sequence* token.\n * Optionally, use a list to set multiple *end-of-sequence* tokens.\n * @type {number|number[]}\n * @default null\n */\n eos_token_id = null;\n\n // Generation parameters exclusive to encoder-decoder models\n /**\n * If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`.\n * @type {number}\n * @default 0\n */\n encoder_no_repeat_ngram_size = 0;\n\n /**\n * If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token.\n * @type {number}\n * @default null\n */\n decoder_start_token_id = null;\n\n // Wild card\n /**\n * Additional generation kwargs will be forwarded to the `generate` function of the model.\n * Kwargs that are not present in `generate`'s signature will be used in the model forward pass.\n * @type {Object}\n * @default {}\n */\n generation_kwargs = {};\n\n /**\n * \n * @param {GenerationConfig|import('../configs.js').PretrainedConfig} config \n */\n constructor(config) {\n Object.assign(this, pick(config, Object.getOwnPropertyNames(this)));\n }\n}\n\n","\n/**\n * @module generation/logits_process\n */\n\nimport { Callable } from \"../utils/generic.js\";\nimport { Tensor } from \"../utils/tensor.js\";\n\nimport { max, log_softmax } from \"../utils/maths.js\";\n\n/**\n * Abstract base class for all logit processors that can be applied during generation.\n */\nexport class LogitsProcessor extends Callable {\n /**\n * Apply the processor to the input logits.\n *\n * @abstract\n * @param {bigint[][]} input_ids The input ids.\n * @param {Tensor} logits The logits to process.\n * @throws {Error} Throws an error if `_call` is not implemented in the subclass.\n */\n _call(input_ids, logits) {\n throw Error(\"`_call` should be implemented in a subclass\")\n }\n}\n\n\n/**\n * Abstract base class for all logit warpers that can be applied during generation with multinomial sampling.\n */\nexport class LogitsWarper extends Callable {\n /**\n * Apply the processor to the input logits.\n *\n * @abstract\n * @param {bigint[][]} input_ids The input ids.\n * @param {Tensor} logits The logits to process.\n * @throws {Error} Throws an error if `_call` is not implemented in the subclass.\n */\n _call(input_ids, logits) {\n throw Error(\"`_call` should be implemented in a subclass\")\n }\n}\n\n\n/**\n * A class representing a list of logits processors. A logits processor is a function that modifies the logits\n * output of a language model. This class provides methods for adding new processors and applying all processors to a\n * batch of logits.\n */\nexport class LogitsProcessorList extends Callable {\n /**\n * Constructs a new instance of `LogitsProcessorList`.\n */\n constructor() {\n super();\n this.processors = [];\n }\n\n /**\n * Adds a new logits processor to the list.\n *\n * @param {LogitsProcessor} item The logits processor function to add.\n */\n push(item) {\n this.processors.push(item);\n }\n\n /**\n * Adds multiple logits processors to the list.\n *\n * @param {LogitsProcessor[]} items The logits processor functions to add.\n */\n extend(items) {\n this.processors.push(...items);\n }\n\n /**\n * Applies all logits processors in the list to a batch of logits, modifying them in-place.\n *\n * @param {bigint[][]} input_ids The input IDs for the language model.\n * @param {Tensor} logits\n */\n _call(input_ids, logits) {\n let toReturn = logits;\n // NOTE: Most processors modify logits inplace\n for (const processor of this.processors) {\n toReturn = processor(input_ids, toReturn);\n }\n return toReturn;\n }\n\n [Symbol.iterator]() {\n return this.processors.values();\n }\n}\n\n// DEPRECATED: https://github.com/huggingface/transformers/pull/29485\n// /**\n// * A logits processor that forces a specific token to be generated by the decoder.\n// */\n// export class ForceTokensLogitsProcessor extends LogitsProcessor {\n// /**\n// * Constructs a new instance of `ForceTokensLogitsProcessor`.\n// * \n// * @param {[number, number][]} forced_decoder_ids The ids of tokens that should be forced.\n// */\n// constructor(forced_decoder_ids) {\n// super();\n// // TODO: convert to `new Map(forced_decoder_ids)`\n// this.force_token_map = Object.fromEntries(forced_decoder_ids ?? []);\n// }\n\n// /**\n// * Apply the processor to the input logits.\n// *\n// * @param {bigint[][]} input_ids The input ids.\n// * @param {Tensor} logits The logits to process.\n// * @returns {Tensor} The processed logits.\n// */\n// _call(input_ids, logits) {\n// console.log('this.force_token_map', this.force_token_map)\n// console.log('call ForceTokensLogitsProcessor', input_ids, logits)\n// console.log('input_ids.length', input_ids.length)\n// let map = this.force_token_map[input_ids.length];\n// if (map) { // There exists a mapping\n// logits.data.fill(-Infinity)\n// logits.data[map] = 0;\n// }\n// console.log('map', map)\n// // throw Error(\"Not implemented\")\n// return logits;\n// }\n// }\n\n/**\n * A LogitsProcessor that forces a BOS token at the beginning of the generated sequence.\n */\nexport class ForcedBOSTokenLogitsProcessor extends LogitsProcessor {\n /**\n * Create a ForcedBOSTokenLogitsProcessor.\n * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced.\n */\n constructor(bos_token_id) {\n super();\n this.bos_token_id = bos_token_id;\n }\n\n /**\n * Apply the BOS token forcing to the logits.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The logits with BOS token forcing.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n if (input_ids[i].length === 1) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n batch_logits_data.fill(-Infinity);\n batch_logits_data[this.bos_token_id] = 0;\n }\n }\n return logits;\n }\n}\n\n/**\n * A logits processor that enforces the specified token as the last generated token when `max_length` is reached.\n */\nexport class ForcedEOSTokenLogitsProcessor extends LogitsProcessor {\n /**\n * Create a ForcedEOSTokenLogitsProcessor.\n * @param {number} max_length The maximum length of the sequence to be generated.\n * @param {number|number[]} eos_token_id The id(s) of the *end-of-sequence* token.\n */\n constructor(max_length, eos_token_id) {\n super();\n this.max_length = max_length;\n this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];\n }\n\n /**\n * Apply the processor to input_ids and logits.\n * \n * @param {bigint[][]} input_ids The input ids.\n * @param {Tensor} logits The logits tensor.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n if (input_ids[i].length === this.max_length - 1) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n batch_logits_data.fill(-Infinity);\n for (const eos_token of this.eos_token_id) {\n batch_logits_data[eos_token] = 0;\n }\n }\n }\n return logits;\n }\n}\n\n/**\n * A LogitsProcessor that suppresses a list of tokens as soon as the `generate` function starts\n * generating using `begin_index` tokens. This should ensure that the tokens defined by\n * `begin_suppress_tokens` at not sampled at the begining of the generation.\n */\nexport class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor {\n /**\n * Create a SuppressTokensAtBeginLogitsProcessor.\n * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress.\n * @param {number} begin_index The number of tokens to generate before suppressing tokens.\n */\n constructor(begin_suppress_tokens, begin_index) {\n super();\n this.begin_suppress_tokens = begin_suppress_tokens;\n this.begin_index = begin_index;\n }\n\n /**\n * Apply the BOS token forcing to the logits.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The logits with BOS token forcing.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n if (input_ids[i].length === this.begin_index) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n for (const token_id of this.begin_suppress_tokens) {\n batch_logits_data[token_id] = -Infinity;\n }\n }\n }\n return logits;\n }\n}\n\n/**\n * A LogitsProcessor that handles adding timestamps to generated text.\n */\nexport class WhisperTimeStampLogitsProcessor extends LogitsProcessor {\n /**\n * Constructs a new WhisperTimeStampLogitsProcessor.\n * @param {import('../models/whisper/generation_whisper.js').WhisperGenerationConfig} generate_config The config object passed to the `generate()` method of a transformer model.\n * @param {number[]} init_tokens The initial tokens of the input sequence.\n */\n constructor(generate_config, init_tokens) {\n super();\n this.eos_token_id =\n Array.isArray(generate_config.eos_token_id)\n ? generate_config.eos_token_id[0]\n : generate_config.eos_token_id;\n\n this.no_timestamps_token_id = generate_config.no_timestamps_token_id;\n this.timestamp_begin = this.no_timestamps_token_id + 1;\n\n this.begin_index = init_tokens.length;\n if (init_tokens.at(-1) === this.no_timestamps_token_id) {\n this.begin_index -= 1;\n }\n this.max_initial_timestamp_index = generate_config.max_initial_timestamp_index;\n }\n\n /**\n * Modify the logits to handle timestamp tokens.\n * @param {bigint[][]} input_ids The input sequence of tokens.\n * @param {Tensor} logits The logits output by the model.\n * @returns {Tensor} The modified logits.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n\n // suppress <|notimestamps|> which is handled by without_timestamps\n batch_logits_data[this.no_timestamps_token_id] = -Infinity;\n\n if (input_ids[i].length === this.begin_index - 1) {\n batch_logits_data.fill(-Infinity);\n batch_logits_data[this.timestamp_begin] = 0;\n continue;\n }\n\n // timestamps have to appear in pairs, except directly before eos_token; mask logits accordingly\n const seq = input_ids[i].slice(this.begin_index);\n const last_was_timestamp = seq.length >= 1 && seq[seq.length - 1] >= this.timestamp_begin;\n const penultimate_was_timestamp = seq.length < 2 || seq[seq.length - 2] >= this.timestamp_begin;\n\n if (last_was_timestamp) {\n if (penultimate_was_timestamp) { // has to be non-timestamp\n batch_logits_data.subarray(this.timestamp_begin).fill(-Infinity);\n } else { // cannot be normal text tokens\n batch_logits_data.subarray(0, this.eos_token_id).fill(-Infinity);\n }\n }\n\n // apply the `max_initial_timestamp` option\n if (input_ids[i].length === this.begin_index && this.max_initial_timestamp_index !== null) {\n const last_allowed = this.timestamp_begin + this.max_initial_timestamp_index;\n batch_logits_data.subarray(last_allowed + 1).fill(-Infinity);\n }\n\n // if sum of probability over timestamps is above any other token, sample timestamp\n const logprobs = log_softmax(batch_logits_data);\n const timestamp_logprob = Math.log(logprobs.subarray(this.timestamp_begin).map(Math.exp).reduce((a, b) => a + b));\n const max_text_token_logprob = max(logprobs.subarray(0, this.timestamp_begin))[0];\n\n if (timestamp_logprob > max_text_token_logprob) {\n batch_logits_data.subarray(0, this.timestamp_begin).fill(-Infinity);\n }\n }\n\n return logits;\n }\n}\n\n/**\n * A logits processor that disallows ngrams of a certain size to be repeated.\n */\nexport class NoRepeatNGramLogitsProcessor extends LogitsProcessor {\n /**\n * Create a NoRepeatNGramLogitsProcessor.\n * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once.\n */\n constructor(no_repeat_ngram_size) {\n super();\n this.no_repeat_ngram_size = no_repeat_ngram_size;\n }\n\n /**\n * Generate n-grams from a sequence of token ids.\n * @param {bigint[]} prevInputIds List of previous input ids\n * @returns {Map} Map of generated n-grams\n */\n getNgrams(prevInputIds) {\n const curLen = prevInputIds.length;\n\n /**@type {number[][]} */\n const ngrams = [];\n for (let j = 0; j < curLen + 1 - this.no_repeat_ngram_size; ++j) {\n const ngram = [];\n for (let k = 0; k < this.no_repeat_ngram_size; ++k) {\n ngram.push(prevInputIds[j + k]);\n }\n ngrams.push(ngram.map(Number));\n }\n\n /** @type {Map} */\n const generatedNgram = new Map();\n for (const ngram of ngrams) {\n const prevNgram = ngram.slice(0, ngram.length - 1);\n const prevNgramKey = JSON.stringify(prevNgram);\n const prevNgramValue = generatedNgram.get(prevNgramKey) ?? [];\n prevNgramValue.push(ngram[ngram.length - 1]);\n generatedNgram.set(prevNgramKey, prevNgramValue);\n }\n return generatedNgram;\n }\n\n /**\n * Generate n-grams from a sequence of token ids.\n * @param {Map} bannedNgrams Map of banned n-grams\n * @param {bigint[]} prevInputIds List of previous input ids\n * @returns {number[]} Map of generated n-grams\n */\n getGeneratedNgrams(bannedNgrams, prevInputIds) {\n const ngramIdx = prevInputIds.slice(prevInputIds.length + 1 - this.no_repeat_ngram_size, prevInputIds.length);\n const banned = bannedNgrams.get(JSON.stringify(ngramIdx.map(Number))) ?? [];\n return banned;\n }\n\n /**\n * Calculate banned n-gram tokens\n * @param {bigint[]} prevInputIds List of previous input ids\n * @returns {number[]} Map of generated n-grams\n */\n calcBannedNgramTokens(prevInputIds) {\n const bannedTokens = [];\n if (prevInputIds.length + 1 < this.no_repeat_ngram_size) {\n // return no banned tokens if we haven't generated no_repeat_ngram_size tokens yet\n return bannedTokens;\n\n } else {\n const generatedNgrams = this.getNgrams(prevInputIds);\n const bannedTokens = this.getGeneratedNgrams(generatedNgrams, prevInputIds);\n return bannedTokens;\n }\n }\n\n /**\n * Apply the no-repeat-ngram processor to the logits.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The logits with no-repeat-ngram processing.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n const bannedTokens = this.calcBannedNgramTokens(input_ids[i]);\n for (const token of bannedTokens) {\n batch_logits_data[token] = -Infinity;\n }\n }\n return logits;\n }\n}\n\n/**\n * A logits processor that penalises repeated output tokens.\n */\nexport class RepetitionPenaltyLogitsProcessor extends LogitsProcessor {\n /**\n * Create a RepetitionPenaltyLogitsProcessor.\n * @param {number} penalty The penalty to apply for repeated tokens.\n */\n constructor(penalty) {\n super();\n this.penalty = penalty;\n }\n\n /**\n * Apply the repetition penalty to the logits.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The logits with repetition penalty processing.\n */\n _call(input_ids, logits) {\n // Modify the logits corresponding to each element in `input_ids`.\n // As a consequence, the logits corresponding to tokens that appear\n // many times in the output will be penalised more.\n\n for (let i = 0; i < input_ids.length; ++i) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n for (const input_id of input_ids[i]) {\n const token = Number(input_id);\n if (batch_logits_data[token] < 0) {\n batch_logits_data[token] *= this.penalty;\n } else {\n batch_logits_data[token] /= this.penalty;\n }\n }\n }\n\n return logits\n }\n}\n\n/**\n * A logits processor that enforces a minimum number of tokens.\n */\nexport class MinLengthLogitsProcessor extends LogitsProcessor {\n /**\n * Create a MinLengthLogitsProcessor.\n * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity.\n * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.\n */\n constructor(min_length, eos_token_id) {\n super();\n this.min_length = min_length;\n this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];\n }\n\n /**\n * Apply logit processor.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n if (input_ids[i].length < this.min_length) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n\n for (const eos_token of this.eos_token_id) {\n batch_logits_data[eos_token] = -Infinity;\n }\n }\n }\n\n return logits\n }\n}\n\n/**\n * A logits processor that enforces a minimum number of new tokens.\n */\nexport class MinNewTokensLengthLogitsProcessor extends LogitsProcessor {\n /**\n * Create a MinNewTokensLengthLogitsProcessor.\n * @param {number} prompt_length_to_skip The input tokens length.\n * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity.\n * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.\n */\n constructor(prompt_length_to_skip, min_new_tokens, eos_token_id) {\n super();\n this.prompt_length_to_skip = prompt_length_to_skip;\n this.min_new_tokens = min_new_tokens;\n this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];\n }\n\n /**\n * Apply logit processor.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n const new_tokens_length = input_ids[i].length - this.prompt_length_to_skip;\n if (new_tokens_length < this.min_new_tokens) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n\n for (const eos_token of this.eos_token_id) {\n batch_logits_data[eos_token] = -Infinity;\n }\n }\n }\n return logits\n }\n}\n\nexport class NoBadWordsLogitsProcessor extends LogitsProcessor {\n /**\n * Create a `NoBadWordsLogitsProcessor`.\n * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated.\n * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.\n */\n constructor(bad_words_ids, eos_token_id) {\n super();\n this.bad_words_ids = bad_words_ids;\n this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];\n }\n\n /**\n * Apply logit processor.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n const ids = input_ids[i];\n for (const bad_word_ids of this.bad_words_ids) {\n // Whether to modify the logits of the last token in the bad word id sequence\n let mark = true;\n\n // For each bad word in the list, if the current sequence of input ids ends with this sequence (excluding the last),\n // then we set the logits of the last bad word id to -Infinity.\n for (let j = 1; j <= bad_word_ids.length - 1 && bad_word_ids.length < ids.length; ++j) {\n\n // NOTE: We use != instead of !== to compare bigint and number\n // @ts-ignore\n if (bad_word_ids.at(-j - 1) != ids.at(-j)) {\n // We have found a mismatch\n mark = false;\n break;\n }\n }\n if (mark) {\n batch_logits_data[bad_word_ids.at(-1)] = -Infinity;\n }\n }\n }\n return logits\n }\n}\n\n/**\n * [`LogitsProcessor`] for classifier free guidance (CFG). The scores are split over the batch dimension,\n * where the first half correspond to the conditional logits (predicted from the input prompt) and the second half\n * correspond to the unconditional logits (predicted from an empty or 'null' prompt). The processor computes a\n * weighted average across the conditional and unconditional logits, parameterised by the `guidance_scale`.\n * \n * See [the paper](https://arxiv.org/abs/2306.05284) for more information.\n */\nexport class ClassifierFreeGuidanceLogitsProcessor extends LogitsProcessor {\n\n /**\n * Create a `ClassifierFreeGuidanceLogitsProcessor`.\n * @param {number} guidance_scale The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.\n * Higher guidance scale encourages the model to generate samples that are more closely linked to the input\n * prompt, usually at the expense of poorer quality.\n */\n constructor(guidance_scale) {\n super();\n if (guidance_scale <= 1) {\n throw new Error(\n `Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${guidance_scale}.`\n )\n }\n this.guidance_scale = guidance_scale;\n }\n\n /**\n * Apply logit processor.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n if (logits.dims[0] !== 2 * input_ids.length) {\n throw new Error(\n `Logits should have twice the batch size of the input ids, the first half of batches corresponding to ` +\n `the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got ` +\n `batch size ${logits.dims[0]} for the logits and ${input_ids.length} for the input ids.`\n )\n }\n\n const unguided_bsz = input_ids.length;\n const cond_logits = logits.slice([0, unguided_bsz], null);\n const uncond_logits = logits.slice([unguided_bsz, logits.dims[0]], null);\n\n // Merge into uncond_logits (to save memory). This is equivalent to the following:\n // scores = uncond_logits + (cond_logits - uncond_logits) * guidance_scale\n for (let i = 0; i < uncond_logits.data.length; ++i) {\n uncond_logits.data[i] += (cond_logits.data[i] - uncond_logits.data[i]) * this.guidance_scale;\n }\n\n return uncond_logits;\n }\n}\n\n/**\n * [`LogitsWarper`] for temperature (exponential scaling output probability distribution), which effectively means\n * that it can control the randomness of the predicted tokens. Often used together with [`TopPLogitsWarper`] and [`TopKLogitsWarper`].\n */\nexport class TemperatureLogitsWarper extends LogitsWarper {\n /**\n * Create a `TemperatureLogitsWarper`.\n * @param {number} temperature Strictly positive float value used to modulate the logits distribution.\n * A value smaller than `1` decreases randomness (and vice versa), with `0` being equivalent to shifting\n * all probability mass to the most likely token.\n */\n constructor(temperature) {\n super();\n\n if (typeof temperature !== 'number' || temperature <= 0) {\n let errorMessage =\n `\\`temperature\\` (=${temperature}) must be a strictly positive float, otherwise your next token scores will be invalid.`;\n\n if (temperature === 0) {\n errorMessage += \" If you're looking for greedy decoding strategies, set `do_sample=false`.\"\n }\n }\n this.temperature = temperature;\n }\n\n /**\n * Apply logit warper.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n const batch_logits_data = /** @type {Float32Array} */(logits.data);\n for (let i = 0; i < batch_logits_data.length; ++i) {\n batch_logits_data[i] /= this.temperature;\n }\n return logits;\n }\n}\n\n/**\n * [`LogitsWarper`] that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off.\n * Often used together with [`TemperatureLogitsWarper`] and [`TopKLogitsWarper`].\n */\nexport class TopPLogitsWarper extends LogitsWarper {\n /**\n * Create a `TopPLogitsWarper`.\n * @param {number} top_p If set to < 1, only the smallest set of most probable tokens with\n * probabilities that add up to `top_p` or higher are kept for generation.\n * @param {Object} options Additional options for the top-p sampling.\n * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value.\n * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered.\n */\n constructor(top_p, {\n filter_value = -Infinity,\n min_tokens_to_keep = 1,\n } = {}) {\n super();\n if (top_p < 0 || top_p > 1.0) {\n throw new Error(`\\`top_p\\` must be a float > 0 and < 1, but is ${top_p}`)\n }\n if (!Number.isInteger(min_tokens_to_keep) || min_tokens_to_keep < 1) {\n throw new Error(`\\`min_tokens_to_keep\\` must be a positive integer, but is ${min_tokens_to_keep}`)\n }\n\n this.top_p = top_p\n this.filter_value = filter_value\n this.min_tokens_to_keep = min_tokens_to_keep\n }\n}\n\n/**\n * [`LogitsWarper`] that performs top-k, i.e. restricting to the k highest probability elements.\n * Often used together with [`TemperatureLogitsWarper`] and [`TopPLogitsWarper`].\n */\nexport class TopKLogitsWarper extends LogitsWarper {\n /**\n * Create a `TopKLogitsWarper`.\n * @param {number} top_k If set to > 0, only the top `top_k` tokens are kept for generation.\n * @param {Object} options Additional options for the top-k sampling.\n * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value.\n * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered.\n */\n constructor(top_k, {\n filter_value = -Infinity,\n min_tokens_to_keep = 1,\n } = {}) {\n super();\n if (!Number.isInteger(top_k) || top_k < 0) {\n throw new Error(`\\`top_k\\` must be a positive integer, but is ${top_k}`)\n }\n\n this.top_k = Math.max(top_k, min_tokens_to_keep)\n this.filter_value = filter_value\n }\n}","\n/**\n * @module generation/logits_sampler\n */\n\nimport { Callable } from \"../utils/generic.js\";\nimport { Tensor, topk } from \"../utils/tensor.js\";\n\nimport {\n max,\n softmax,\n} from '../utils/maths.js';\nimport { GenerationConfig } from '../generation/configuration_utils.js';\n\n/**\n * Sampler is a base class for all sampling methods used for text generation.\n */\nexport class LogitsSampler extends Callable {\n /**\n * Creates a new Sampler object with the specified generation config.\n * @param {GenerationConfig} generation_config The generation config.\n */\n constructor(generation_config) {\n super();\n this.generation_config = generation_config;\n }\n\n /**\n * Executes the sampler, using the specified logits.\n * @param {Tensor} logits\n * @returns {Promise<[bigint, number][]>}\n */\n async _call(logits) {\n // Sample from logits, of dims [batch, sequence_length, vocab_size].\n // If index is specified, sample from [batch, index, vocab_size].\n return this.sample(logits);\n }\n\n /**\n * Abstract method for sampling the logits.\n * @param {Tensor} logits\n * @throws {Error} If not implemented in subclass.\n * @returns {Promise<[bigint, number][]>}\n */\n async sample(logits) {\n throw Error(\"sample should be implemented in subclasses.\")\n }\n\n /**\n * Returns the specified logits as an array, with temperature applied.\n * @param {Tensor} logits\n * @param {number} index\n * @returns {Float32Array}\n */\n getLogits(logits, index) {\n let vocabSize = logits.dims.at(-1);\n\n let logs = /** @type {Float32Array} */(logits.data);\n\n if (index === -1) {\n logs = logs.slice(-vocabSize);\n } else {\n let startIndex = index * vocabSize;\n logs = logs.slice(startIndex, startIndex + vocabSize);\n }\n return logs;\n }\n\n /**\n * Selects an item randomly based on the specified probabilities.\n * @param {import(\"../transformers.js\").DataArray} probabilities An array of probabilities to use for selection.\n * @returns {number} The index of the selected item.\n */\n randomSelect(probabilities) {\n // Return index of chosen item\n let sumProbabilities = 0;\n for (let i = 0; i < probabilities.length; ++i) {\n sumProbabilities += probabilities[i];\n }\n\n let r = Math.random() * sumProbabilities;\n for (let i = 0; i < probabilities.length; ++i) {\n r -= probabilities[i];\n if (r <= 0) {\n return i;\n }\n }\n return 0; // return first (most probable) as a fallback\n }\n\n /**\n * Returns a Sampler object based on the specified options.\n * @param {GenerationConfig} generation_config An object containing options for the sampler.\n * @returns {LogitsSampler} A Sampler object.\n */\n static getSampler(generation_config) {\n // - *greedy decoding*: `num_beams=1` and `do_sample=False`\n // - *contrastive search*: `penalty_alpha>0` and `top_k>1`\n // - *multinomial sampling*: `num_beams=1` and `do_sample=True`\n // - *beam-search decoding*: `num_beams>1` and `do_sample=False`\n // - *beam-search multinomial sampling*: `num_beams>1` and `do_sample=True`\n // - *diverse beam-search decoding*: `num_beams>1` and `num_beam_groups>1`\n // - *constrained beam-search decoding*: `constraints!=None` or `force_words_ids!=None`\n\n // NOTE: beam search is implemented directly into the generation function\n if (generation_config.do_sample) {\n return new MultinomialSampler(generation_config);\n\n } else if (generation_config.num_beams > 1) {\n return new BeamSearchSampler(generation_config);\n\n } else {\n if (generation_config.num_return_sequences > 1) {\n throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${generation_config.num_return_sequences}.`)\n }\n return new GreedySampler(generation_config);\n }\n }\n}\n\n/**\n * Class representing a Greedy Sampler.\n */\nclass GreedySampler extends LogitsSampler {\n /**\n * Sample the maximum probability of a given logits tensor.\n * @param {Tensor} logits\n * @returns {Promise<[bigint, number][]>} An array with a single tuple, containing the index of the maximum value and a meaningless score (since this is a greedy search).\n */\n async sample(logits) {\n // NOTE: no need to do log_softmax here since we only take the maximum\n const argmax = max(logits.data)[1];\n\n // Note: score is meaningless in this context, since we are performing\n // greedy search (p = 1 => log(p) = 0)\n return [\n [BigInt(argmax), 0]\n ];\n }\n}\n\n/**\n * Class representing a MultinomialSampler.\n */\nclass MultinomialSampler extends LogitsSampler {\n\n /**\n * Sample from the logits.\n * @param {Tensor} logits\n * @returns {Promise<[bigint, number][]>}\n */\n async sample(logits) {\n let k = logits.dims.at(-1); // defaults to vocab size\n if (this.generation_config.top_k > 0) {\n k = Math.min(this.generation_config.top_k, k);\n }\n\n // Get top k tokens\n const [v, i] = await topk(logits, k);\n\n // Compute softmax over logits\n const probabilities = softmax(/** @type {Float32Array} */(v.data));\n\n return Array.from({ length: this.generation_config.num_beams }, () => {\n const sampledIndex = this.randomSelect(probabilities);\n return [\n i.data[sampledIndex], // token id\n Math.log(probabilities[sampledIndex]), // score\n ];\n });\n }\n}\n\n\n/**\n * Class representing a BeamSearchSampler.\n */\nclass BeamSearchSampler extends LogitsSampler {\n\n /**\n * Sample from the logits.\n * @param {Tensor} logits\n * @returns {Promise<[bigint, number][]>}\n */\n async sample(logits) {\n let k = logits.dims.at(-1); // defaults to vocab size\n if (this.generation_config.top_k > 0) {\n k = Math.min(this.generation_config.top_k, k);\n }\n\n // Get top k tokens\n const [v, i] = await topk(logits, k);\n\n // Compute softmax over logits\n const probabilities = softmax(/** @type {Float32Array} */(v.data));\n\n return Array.from({ length: this.generation_config.num_beams }, (_, x) => {\n return [\n i.data[x], // token id\n Math.log(probabilities[x]), // score\n ];\n });\n }\n}\n","\n/**\n * @module generation/stopping_criteria\n */\n\nimport { Callable } from \"../utils/generic.js\";\n\n// NOTE:\n// Stopping Criteria returns a list of `batch_size` booleans, indicating whether each sequence in the batch should be stopped.\n\n/**\n * Abstract base class for all stopping criteria that can be applied during generation.\n */\nexport class StoppingCriteria extends Callable {\n /**\n * \n * @param {number[][]} input_ids (`number[][]` of shape `(batch_size, sequence_length)`):\n * Indices of input sequence tokens in the vocabulary.\n * @param {number[][]} scores scores (`number[][]` of shape `(batch_size, config.vocab_size)`):\n * Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax\n * or scores for each vocabulary token after SoftMax.\n * @returns {boolean[]} A list of booleans indicating whether each sequence should be stopped.\n */\n _call(input_ids, scores) {\n throw Error(\"StoppingCriteria needs to be subclassed\");\n }\n}\n/**\n */\nexport class StoppingCriteriaList extends Callable {\n /**\n * Constructs a new instance of `StoppingCriteriaList`.\n */\n constructor() {\n super();\n this.criteria = [];\n }\n\n /**\n * Adds a new stopping criterion to the list.\n *\n * @param {StoppingCriteria} item The stopping criterion to add.\n */\n push(item) {\n this.criteria.push(item);\n }\n\n /**\n * Adds multiple stopping criteria to the list.\n *\n * @param {StoppingCriteria|StoppingCriteriaList|StoppingCriteria[]} items The stopping criteria to add.\n */\n extend(items) {\n if (items instanceof StoppingCriteriaList) {\n items = items.criteria;\n } else if (items instanceof StoppingCriteria) {\n items = [items];\n }\n this.criteria.push(...items);\n }\n\n _call(input_ids, scores) {\n const is_done = new Array(input_ids.length).fill(false);\n for (const criterion of this.criteria) {\n const criterion_done = criterion(input_ids, scores);\n for (let i = 0; i < is_done.length; ++i) {\n is_done[i] ||= criterion_done[i];\n }\n }\n return is_done;\n }\n\n [Symbol.iterator]() {\n return this.criteria.values();\n }\n}\n\n/**\n * This class can be used to stop generation whenever the full generated number of tokens exceeds `max_length`.\n * Keep in mind for decoder-only type of transformers, this will include the initial prompted tokens.\n */\nexport class MaxLengthCriteria extends StoppingCriteria {\n\n /**\n * \n * @param {number} max_length The maximum length that the output sequence can have in number of tokens.\n * @param {number} [max_position_embeddings=null] The maximum model length, as defined by the model's `config.max_position_embeddings` attribute.\n */\n constructor(max_length, max_position_embeddings = null) {\n super();\n this.max_length = max_length;\n this.max_position_embeddings = max_position_embeddings;\n }\n\n _call(input_ids) {\n return input_ids.map(ids => ids.length >= this.max_length);\n }\n}\n\n// TODO: add MaxTimeCriteria\n\n/**\n * This class can be used to stop generation whenever the \"end-of-sequence\" token is generated.\n * By default, it uses the `model.generation_config.eos_token_id`.\n */\nexport class EosTokenCriteria extends StoppingCriteria {\n\n /**\n * \n * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token.\n * Optionally, use a list to set multiple *end-of-sequence* tokens.\n */\n constructor(eos_token_id) {\n super();\n if (!Array.isArray(eos_token_id)) {\n eos_token_id = [eos_token_id];\n }\n this.eos_token_id = eos_token_id;\n }\n\n /**\n * \n * @param {number[][]} input_ids \n * @param {number[][]} scores \n * @returns {boolean[]}\n */\n _call(input_ids, scores) {\n return input_ids.map(ids => {\n const last = ids.at(-1);\n // NOTE: We use == instead of === to allow for number/bigint comparison\n return this.eos_token_id.some(eos_id => last == eos_id);\n });\n }\n}\n\n/**\n * This class can be used to stop generation whenever the user interrupts the process.\n */\nexport class InterruptableStoppingCriteria extends StoppingCriteria {\n constructor() {\n super();\n this.interrupted = false;\n }\n\n interrupt() {\n this.interrupted = true;\n }\n\n reset() {\n this.interrupted = false;\n }\n\n _call(input_ids, scores) {\n return new Array(input_ids.length).fill(this.interrupted);\n }\n}\n","\n/**\n * @module generation/streamers\n */\n\nimport { mergeArrays } from '../utils/core.js';\nimport { is_chinese_char } from '../tokenizers.js';\nimport { apis } from '../env.js';\n\nexport class BaseStreamer {\n /**\n * Function that is called by `.generate()` to push new tokens\n * @param {bigint[][]} value \n */\n put(value) {\n throw Error('Not implemented');\n }\n\n /**\n * Function that is called by `.generate()` to signal the end of generation\n */\n end() {\n throw Error('Not implemented');\n }\n}\n\nconst stdout_write = apis.IS_PROCESS_AVAILABLE\n ? x => process.stdout.write(x)\n : x => console.log(x);\n\n/**\n * Simple text streamer that prints the token(s) to stdout as soon as entire words are formed.\n */\nexport class TextStreamer extends BaseStreamer {\n /**\n * \n * @param {import('../tokenizers.js').PreTrainedTokenizer} tokenizer \n */\n constructor(tokenizer, {\n skip_prompt = false,\n callback_function = null,\n token_callback_function = null,\n decode_kwargs = {},\n ...kwargs\n } = {}) {\n super();\n this.tokenizer = tokenizer;\n this.skip_prompt = skip_prompt;\n this.callback_function = callback_function ?? stdout_write;\n this.token_callback_function = token_callback_function;\n this.decode_kwargs = { ...decode_kwargs, ...kwargs };\n\n // variables used in the streaming process\n this.token_cache = [];\n this.print_len = 0;\n this.next_tokens_are_prompt = true;\n }\n\n /**\n * Receives tokens, decodes them, and prints them to stdout as soon as they form entire words.\n * @param {bigint[][]} value \n */\n put(value) {\n if (value.length > 1) {\n throw Error('TextStreamer only supports batch size of 1');\n }\n\n if (this.skip_prompt && this.next_tokens_are_prompt) {\n this.next_tokens_are_prompt = false;\n return;\n }\n\n const tokens = value[0];\n this.token_callback_function?.(tokens)\n\n // Add the new token to the cache and decodes the entire thing.\n this.token_cache = mergeArrays(this.token_cache, tokens);\n const text = this.tokenizer.decode(this.token_cache, this.decode_kwargs);\n\n let printable_text;\n if (text.endsWith('\\n')) {\n // After the symbol for a new line, we flush the cache.\n printable_text = text.slice(this.print_len);\n this.token_cache = [];\n this.print_len = 0;\n } else if (text.length > 0 && is_chinese_char(text.charCodeAt(text.length - 1))) {\n // If the last token is a CJK character, we print the characters.\n printable_text = text.slice(this.print_len);\n this.print_len += printable_text.length;\n } else {\n // Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words,\n // which may change with the subsequent token -- there are probably smarter ways to do this!)\n printable_text = text.slice(this.print_len, text.lastIndexOf(' ') + 1);\n this.print_len += printable_text.length;\n }\n\n this.on_finalized_text(printable_text, false);\n }\n\n /**\n * Flushes any remaining cache and prints a newline to stdout.\n */\n end() {\n let printable_text;\n if (this.token_cache.length > 0) {\n const text = this.tokenizer.decode(this.token_cache, this.decode_kwargs);\n printable_text = text.slice(this.print_len);\n this.token_cache = [];\n this.print_len = 0;\n } else {\n printable_text = '';\n }\n this.next_tokens_are_prompt = true;\n this.on_finalized_text(printable_text, true);\n }\n\n /**\n * Prints the new text to stdout. If the stream is ending, also prints a newline.\n * @param {string} text \n * @param {boolean} stream_end \n */\n on_finalized_text(text, stream_end) {\n if (text.length > 0) {\n this.callback_function?.(text);\n }\n if (stream_end && this.callback_function === stdout_write && apis.IS_PROCESS_AVAILABLE) {\n this.callback_function?.('\\n');\n }\n }\n}\n\n/**\n * Utility class to handle streaming of tokens generated by whisper speech-to-text models.\n * Callback functions are invoked when each of the following events occur:\n * - A new chunk starts (on_chunk_start)\n * - A new token is generated (callback_function)\n * - A chunk ends (on_chunk_end)\n * - The stream is finalized (on_finalize)\n */\nexport class WhisperTextStreamer extends TextStreamer {\n /**\n * @param {import('../tokenizers.js').WhisperTokenizer} tokenizer\n * @param {Object} options\n * @param {boolean} [options.skip_prompt=false] Whether to skip the prompt tokens\n * @param {function(string): void} [options.callback_function=null] Function to call when a piece of text is ready to display\n * @param {function(string): void} [options.token_callback_function=null] Function to call when a new token is generated\n * @param {function(number): void} [options.on_chunk_start=null] Function to call when a new chunk starts\n * @param {function(number): void} [options.on_chunk_end=null] Function to call when a chunk ends\n * @param {function(): void} [options.on_finalize=null] Function to call when the stream is finalized\n * @param {number} [options.time_precision=0.02] Precision of the timestamps\n * @param {boolean} [options.skip_special_tokens=true] Whether to skip special tokens when decoding\n * @param {Object} [options.decode_kwargs={}] Additional keyword arguments to pass to the tokenizer's decode method\n */\n constructor(tokenizer, {\n skip_prompt = false,\n callback_function = null,\n token_callback_function = null,\n on_chunk_start = null,\n on_chunk_end = null,\n on_finalize = null,\n time_precision = 0.02,\n skip_special_tokens = true,\n decode_kwargs = {},\n } = {}) {\n super(tokenizer, {\n skip_prompt,\n callback_function,\n token_callback_function,\n decode_kwargs: { skip_special_tokens, ...decode_kwargs },\n });\n this.timestamp_begin = tokenizer.timestamp_begin;\n\n this.on_chunk_start = on_chunk_start;\n this.on_chunk_end = on_chunk_end;\n this.on_finalize = on_finalize;\n\n this.time_precision = time_precision;\n\n this.waiting_for_timestamp = false;\n }\n\n /**\n * @param {bigint[][]} value \n */\n put(value) {\n if (value.length > 1) {\n throw Error('WhisperTextStreamer only supports batch size of 1');\n }\n const tokens = value[0];\n\n // Check if the token is a timestamp\n if (tokens.length === 1) {\n const offset = Number(tokens[0]) - this.timestamp_begin;\n if (offset >= 0) {\n const time = offset * this.time_precision;\n if (this.waiting_for_timestamp) {\n this.on_chunk_end?.(time);\n } else {\n this.on_chunk_start?.(time);\n }\n this.waiting_for_timestamp = !this.waiting_for_timestamp; // Toggle\n value = [[]]; // Skip timestamp\n }\n }\n return super.put(value);\n }\n\n end() {\n super.end();\n this.on_finalize?.();\n }\n}\n","\n/**\n * @file Definitions of all models available in Transformers.js.\n * \n * **Example:** Load and run an `AutoModel`.\n * \n * ```javascript\n * import { AutoModel, AutoTokenizer } from '@huggingface/transformers';\n * \n * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');\n * let model = await AutoModel.from_pretrained('Xenova/bert-base-uncased');\n * \n * let inputs = await tokenizer('I love transformers!');\n * let { logits } = await model(inputs);\n * // Tensor {\n * // data: Float32Array(183132) [-7.117443084716797, -7.107812881469727, -7.092104911804199, ...]\n * // dims: (3) [1, 6, 30522],\n * // type: \"float32\",\n * // size: 183132,\n * // }\n * ```\n * \n * We also provide other `AutoModel`s (listed below), which you can use in the same way as the Python library. For example:\n * \n * **Example:** Load and run an `AutoModelForSeq2SeqLM`.\n * ```javascript\n * import { AutoModelForSeq2SeqLM, AutoTokenizer } from '@huggingface/transformers';\n * \n * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/t5-small');\n * let model = await AutoModelForSeq2SeqLM.from_pretrained('Xenova/t5-small');\n * \n * let { input_ids } = await tokenizer('translate English to German: I love transformers!');\n * let outputs = await model.generate(input_ids);\n * let decoded = tokenizer.decode(outputs[0], { skip_special_tokens: true });\n * // 'Ich liebe Transformatoren!'\n * ```\n * \n * @module models\n */\n\nimport {\n AutoConfig,\n getKeyValueShapes,\n} from './configs.js';\n\nimport {\n deviceToExecutionProviders,\n createInferenceSession,\n isONNXTensor,\n isONNXProxy,\n} from './backends/onnx.js';\nimport {\n DATA_TYPES,\n DEFAULT_DEVICE_DTYPE_MAPPING,\n DEFAULT_DTYPE_SUFFIX_MAPPING,\n isWebGpuFp16Supported,\n} from './utils/dtypes.js';\n\nimport {\n Callable,\n} from './utils/generic.js';\n\nimport {\n isIntegralNumber,\n mergeArrays,\n pick,\n} from './utils/core.js';\n\nimport {\n getModelFile,\n getModelJSON,\n} from './utils/hub.js';\n\nimport {\n GITHUB_ISSUE_URL,\n} from './utils/constants.js';\n\nimport {\n LogitsProcessorList,\n ForcedBOSTokenLogitsProcessor,\n ForcedEOSTokenLogitsProcessor,\n SuppressTokensAtBeginLogitsProcessor,\n WhisperTimeStampLogitsProcessor,\n NoRepeatNGramLogitsProcessor,\n RepetitionPenaltyLogitsProcessor,\n NoBadWordsLogitsProcessor,\n MinLengthLogitsProcessor,\n MinNewTokensLengthLogitsProcessor,\n\n TemperatureLogitsWarper,\n TopKLogitsWarper,\n TopPLogitsWarper,\n ClassifierFreeGuidanceLogitsProcessor,\n} from './generation/logits_process.js';\n\nimport {\n GenerationConfig,\n} from './generation/configuration_utils.js';\n\nimport {\n cat,\n full_like,\n mean,\n ones,\n ones_like,\n stack,\n std_mean,\n Tensor,\n zeros_like,\n} from './utils/tensor.js';\n\nimport { dynamic_time_warping, medianFilter } from './utils/maths.js';\nimport { EosTokenCriteria, MaxLengthCriteria, StoppingCriteriaList } from './generation/stopping_criteria.js';\nimport { LogitsSampler } from './generation/logits_sampler.js';\nimport { apis } from './env.js';\n\nimport { WhisperGenerationConfig } from './models/whisper/generation_whisper.js';\nimport { whisper_language_to_code } from './models/whisper/common_whisper.js';\n\n//////////////////////////////////////////////////\n// Model types: used internally\nconst MODEL_TYPES = {\n EncoderOnly: 0,\n EncoderDecoder: 1,\n Seq2Seq: 2,\n Vision2Seq: 3,\n DecoderOnly: 4,\n MaskGeneration: 5,\n ImageTextToText: 6,\n Musicgen: 7,\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Helper functions\n\n// NOTE: These will be populated fully later\nconst MODEL_TYPE_MAPPING = new Map();\nconst MODEL_NAME_TO_CLASS_MAPPING = new Map();\nconst MODEL_CLASS_TO_NAME_MAPPING = new Map();\n\n\n/**\n * Constructs an InferenceSession using a model file located at the specified path.\n * @param {string} pretrained_model_name_or_path The path to the directory containing the model file.\n * @param {string} fileName The name of the model file.\n * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the model.\n * @returns {Promise<{buffer: Uint8Array, session_options: Object, session_config: Object}>} A Promise that resolves to the data needed to create an InferenceSession object.\n * @private\n */\nasync function getSession(pretrained_model_name_or_path, fileName, options) {\n const custom_config = options.config?.['transformers.js_config'] ?? {};\n let device = options.device ?? custom_config.device;\n if (device && typeof device !== 'string') {\n if (device.hasOwnProperty(fileName)) {\n device = device[fileName];\n } else {\n console.warn(`device not specified for \"${fileName}\". Using the default device.`);\n device = null;\n }\n }\n\n // If the device is not specified, we use the default (supported) execution providers.\n const selectedDevice = /** @type {import(\"./utils/devices.js\").DeviceType} */(\n device ?? (apis.IS_NODE_ENV ? 'cpu' : 'wasm')\n );\n const executionProviders = deviceToExecutionProviders(selectedDevice);\n\n // If options.dtype is specified, we use it to choose the suffix for the model file.\n // Otherwise, we use the default dtype for the device.\n let dtype = options.dtype ?? custom_config.dtype;\n if (typeof dtype !== 'string') {\n if (dtype && dtype.hasOwnProperty(fileName)) {\n dtype = dtype[fileName];\n } else {\n dtype = DEFAULT_DEVICE_DTYPE_MAPPING[selectedDevice] ?? DATA_TYPES.fp32;\n console.warn(`dtype not specified for \"${fileName}\". Using the default dtype (${dtype}) for this device (${selectedDevice}).`);\n }\n }\n\n const selectedDtype = /** @type {import(\"./utils/dtypes.js\").DataType} */(dtype);\n\n if (!DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(selectedDtype)) {\n throw new Error(`Invalid dtype: ${selectedDtype}. Should be one of: ${Object.keys(DATA_TYPES).join(', ')}`);\n } else if (selectedDtype === DATA_TYPES.fp16 && selectedDevice === 'webgpu' && !(await isWebGpuFp16Supported())) {\n throw new Error(`The device (${selectedDevice}) does not support fp16.`);\n }\n\n // Only valid for models with a decoder\n const kv_cache_dtype = custom_config.kv_cache_dtype\n ? (typeof custom_config.kv_cache_dtype === 'string'\n ? custom_config.kv_cache_dtype\n : custom_config.kv_cache_dtype[selectedDtype] ?? 'float32')\n : undefined;\n\n if (kv_cache_dtype && !['float32', 'float16'].includes(kv_cache_dtype)) {\n throw new Error(`Invalid kv_cache_dtype: ${kv_cache_dtype}. Should be one of: float32, float16`);\n }\n\n const session_config = {\n dtype: selectedDtype,\n kv_cache_dtype,\n }\n\n // Construct the model file name\n const suffix = DEFAULT_DTYPE_SUFFIX_MAPPING[selectedDtype];\n const modelFileName = `${options.subfolder ?? ''}/${fileName}${suffix}.onnx`;\n\n const session_options = { ...options.session_options };\n\n // Overwrite `executionProviders` if not specified\n session_options.executionProviders ??= executionProviders;\n\n // Overwrite `freeDimensionOverrides` if specified in config and not set in session options\n const free_dimension_overrides = custom_config.free_dimension_overrides;\n if (free_dimension_overrides) {\n session_options.freeDimensionOverrides ??= free_dimension_overrides;\n } else if (selectedDevice.startsWith('webnn') && !session_options.freeDimensionOverrides) {\n console.warn(\n 'WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within \"transformers.js_config\". ' +\n 'When `free_dimension_overrides` is not set, you may experience significant performance degradation.'\n );\n }\n\n const bufferPromise = getModelFile(pretrained_model_name_or_path, modelFileName, true, options);\n\n // handle onnx external data files\n const use_external_data_format = options.use_external_data_format ?? custom_config.use_external_data_format;\n /** @type {Promise<{path: string, data: Uint8Array}>[]} */\n let externalDataPromises = [];\n if (use_external_data_format && (\n use_external_data_format === true ||\n (\n typeof use_external_data_format === 'object' &&\n use_external_data_format.hasOwnProperty(fileName) &&\n use_external_data_format[fileName] === true\n )\n )) {\n if (apis.IS_NODE_ENV) {\n throw new Error('External data format is not yet supported in Node.js');\n }\n const path = `${fileName}${suffix}.onnx_data`;\n const fullPath = `${options.subfolder ?? ''}/${path}`;\n externalDataPromises.push(new Promise(async (resolve, reject) => {\n const data = await getModelFile(pretrained_model_name_or_path, fullPath, true, options);\n resolve({ path, data })\n }));\n\n } else if (session_options.externalData !== undefined) {\n externalDataPromises = session_options.externalData.map(async (ext) => {\n // if the external data is a string, fetch the file and replace the string with its content\n if (typeof ext.data === \"string\") {\n const ext_buffer = await getModelFile(pretrained_model_name_or_path, ext.data, true, options);\n return { ...ext, data: ext_buffer };\n }\n return ext;\n });\n }\n\n if (externalDataPromises.length > 0) {\n session_options.externalData = await Promise.all(externalDataPromises);\n }\n\n if (selectedDevice === 'webgpu') {\n const shapes = getKeyValueShapes(options.config, {\n prefix: 'present',\n });\n if (Object.keys(shapes).length > 0 && !isONNXProxy()) {\n // Only set preferredOutputLocation if shapes are present and we aren't proxying ONNX\n /** @type {Record} */\n const preferredOutputLocation = {};\n for (const key in shapes) {\n preferredOutputLocation[key] = 'gpu-buffer';\n }\n session_options.preferredOutputLocation = preferredOutputLocation;\n }\n }\n\n const buffer = await bufferPromise;\n\n return { buffer, session_options, session_config };\n}\n\n/**\n * Helper function to create multiple InferenceSession objects.\n * \n * @param {string} pretrained_model_name_or_path The path to the directory containing the model file.\n * @param {Record} names The names of the model files to load.\n * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the model.\n * @returns {Promise>} A Promise that resolves to a dictionary of InferenceSession objects.\n * @private\n */\nasync function constructSessions(pretrained_model_name_or_path, names, options) {\n return Object.fromEntries(await Promise.all(\n Object.keys(names).map(async (name) => {\n const { buffer, session_options, session_config } = await getSession(pretrained_model_name_or_path, names[name], options);\n const session = await createInferenceSession(buffer, session_options, session_config);\n return [name, session];\n })\n ));\n}\n\n/**\n * Helper function to load multiple optional configuration files\n * @param {string} pretrained_model_name_or_path The path to the directory containing the config file.\n * @param {Record} names The names of the config files to load.\n * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the configs.\n * @returns {Promise>} A Promise that resolves to a dictionary of configuration objects.\n * @private\n */\nasync function getOptionalConfigs(pretrained_model_name_or_path, names, options) {\n return Object.fromEntries(await Promise.all(\n Object.keys(names).map(async (name) => {\n const config = await getModelJSON(pretrained_model_name_or_path, names[name], false, options);\n return [name, config];\n })\n ));\n}\n\n/**\n * Validate model inputs\n * @param {Object} session The InferenceSession object that will be run.\n * @param {Object} inputs The inputs to check.\n * @returns {Record} The checked inputs.\n * @throws {Error} If any inputs are missing.\n * @private\n */\nfunction validateInputs(session, inputs) {\n /**\n * NOTE: Create either a shallow or deep copy based on `onnx.wasm.proxy`\n * @type {Record}\n */\n const checkedInputs = Object.create(null);\n const missingInputs = [];\n for (const inputName of session.inputNames) {\n const tensor = inputs[inputName];\n // Rare case where one of the model's input names corresponds to a built-in\n // object name (e.g., toString), which would cause a simple (!tensor) check to fail,\n // because it's not undefined but a function.\n if (!(tensor instanceof Tensor)) {\n missingInputs.push(inputName);\n continue;\n }\n // NOTE: When `env.wasm.proxy is true` the tensor is moved across the Worker\n // boundary, transferring ownership to the worker and invalidating the tensor.\n // So, in this case, we simply sacrifice a clone for it.\n checkedInputs[inputName] = isONNXProxy() ? tensor.clone() : tensor;\n }\n if (missingInputs.length > 0) {\n throw new Error(\n `An error occurred during model execution: \"Missing the following inputs: ${missingInputs.join(', ')}.`);\n }\n\n const numInputsProvided = Object.keys(inputs).length;\n const numInputsNeeded = session.inputNames.length;\n if (numInputsProvided > numInputsNeeded) {\n // No missing inputs, but too many inputs were provided.\n // Warn the user and ignore the extra inputs.\n let ignored = Object.keys(inputs).filter(inputName => !session.inputNames.includes(inputName));\n console.warn(`WARNING: Too many inputs were provided (${numInputsProvided} > ${numInputsNeeded}). The following inputs will be ignored: \"${ignored.join(', ')}\".`);\n }\n\n return checkedInputs;\n}\n\nconst getQueryValue = (name) => {\n const urlParams = new URLSearchParams(window.location.search);\n return urlParams.get(name);\n};\n\nlet runs = 1;\n\nlet perf = {\n warmup: 0,\n inference: [],\n throughput: 0\n};\n\nexport function getPerf() {\n return perf;\n}\n\n/**\n * Executes an InferenceSession using the specified inputs.\n * NOTE: `inputs` must contain at least the input names of the model.\n * - If additional inputs are passed, they will be ignored.\n * - If inputs are missing, an error will be thrown.\n * \n * @param {Object} session The InferenceSession object to run.\n * @param {Object} inputs An object that maps input names to input tensors.\n * @returns {Promise} A Promise that resolves to an object that maps output names to output tensors.\n * @private\n */\nasync function sessionRun(session, inputs) {\n perf = {\n warmup: 0,\n inference: [],\n throughput: 0\n };\n const checkedInputs = validateInputs(session, inputs);\n try {\n // pass the original ort tensor\n const ortFeed = Object.fromEntries(Object.entries(checkedInputs).map(([k, v]) => [k, v.ort_tensor]));\n let output;\n let numOfWarmups = 1;\n // let numOfRuns = 100;\n console.log(`-- number of test runs --`);\n if (getQueryValue(\"run\")) {\n runs = parseInt(getQueryValue(\"run\"));\n } else {\n runs = 1;\n }\n console.log(runs);\n let start = performance.now();\n let loopStart;\n let current;\n let arrayInference = [];\n for(let i=0; i < numOfWarmups + runs; i++) {\n loopStart = performance.now();\n output = await session.run(ortFeed);\n current = performance.now() - loopStart;\n if(i==0) {\n perf.warmup = current;\n } else {\n arrayInference.push(current);\n }\n console.log(`Session run time: ${current}ms`);\n }\n perf.inference = arrayInference;\n perf.throughput = parseFloat((1000.00 / ((performance.now() - start) / (numOfWarmups + runs))).toFixed(2));\n output = replaceTensors(output);\n return output;\n } catch (e) {\n // This usually occurs when the inputs are of the wrong type.\n console.error(`An error occurred during model execution: \"${e}\".`);\n console.error('Inputs given to model:', checkedInputs);\n throw e;\n }\n}\n\n/**\n * Replaces ONNX Tensor objects with custom Tensor objects to support additional functions.\n * @param {Object} obj The object to replace tensor objects in.\n * @returns {Object} The object with tensor objects replaced by custom Tensor objects.\n * @private\n */\nfunction replaceTensors(obj) {\n for (let prop in obj) {\n if (isONNXTensor(obj[prop])) {\n obj[prop] = new Tensor(obj[prop]);\n } else if (typeof obj[prop] === 'object') {\n replaceTensors(obj[prop]);\n }\n }\n return obj;\n}\n\n\n/**\n * Converts an array or Tensor of integers to an int64 Tensor.\n * @param {Array|Tensor} items The input integers to be converted.\n * @returns {Tensor} The int64 Tensor with the converted values.\n * @throws {Error} If the input array is empty or the input is a batched Tensor and not all sequences have the same length.\n * @private\n */\nfunction toI64Tensor(items) {\n if (items instanceof Tensor) {\n return items;\n }\n // items is an array\n if (items.length === 0) {\n throw Error(\"items must be non-empty\");\n }\n\n if (Array.isArray(items[0])) {\n // batched\n if (items.some(x => x.length !== items[0].length)) {\n throw Error(\"Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.\")\n }\n\n return new Tensor('int64',\n BigInt64Array.from(items.flat().map(x => BigInt(x))),\n [items.length, items[0].length]\n );\n } else {\n //flat\n return new Tensor('int64',\n BigInt64Array.from(items.map(x => BigInt(x))),\n [1, items.length]\n );\n }\n}\n\n/**\n * Creates a boolean tensor with a single value.\n * @param {boolean} value The value of the tensor.\n * @returns {Tensor} The boolean tensor.\n * @private\n */\nfunction boolTensor(value) {\n return new Tensor('bool', [value], [1]);\n}\n\n// JS doesn't support mixins, so we define some reused functions here, and allow \"this\" to be passed in\n/**\n * Perform forward pass on the seq2seq model (both encoder and decoder).\n * @param {Object} self The seq2seq model object.\n * @param {Object} model_inputs The input object for the model containing encoder and decoder inputs.\n * @returns {Promise} Promise that resolves with the output of the seq2seq model.\n * @private\n */\nasync function seq2seqForward(self, model_inputs) {\n let { encoder_outputs, input_ids, decoder_input_ids, ...other_decoder_inputs } = model_inputs;\n // Encode if needed\n if (!encoder_outputs) {\n const encoder_inputs = pick(model_inputs, self.sessions['model'].inputNames);\n // Encoder outputs are not given, so we must compute them.\n encoder_outputs = (await encoderForward(self, encoder_inputs)).last_hidden_state;\n }\n\n other_decoder_inputs.input_ids = decoder_input_ids;\n other_decoder_inputs.encoder_hidden_states = encoder_outputs;\n\n if (self.sessions['decoder_model_merged'].inputNames.includes('encoder_attention_mask')) {\n other_decoder_inputs.encoder_attention_mask = model_inputs.attention_mask\n }\n\n const decoderResults = await decoderForward(self, other_decoder_inputs, true);\n\n return decoderResults;\n}\n\n/**\n * Forward pass of an encoder model.\n * @param {Object} self The encoder model.\n * @param {Object} model_inputs The input data to be used for the forward pass.\n * @returns {Promise} The model's outputs.\n * @private\n */\nasync function encoderForward(self, model_inputs) {\n const session = self.sessions['model'];\n const encoderFeeds = pick(model_inputs, session.inputNames);\n\n if (session.inputNames.includes('inputs_embeds') && !encoderFeeds.inputs_embeds) {\n if (!model_inputs.input_ids) {\n throw new Error('Both `input_ids` and `inputs_embeds` are missing in the model inputs.');\n }\n encoderFeeds.inputs_embeds = await self.encode_text({ input_ids: model_inputs.input_ids });\n }\n if (session.inputNames.includes('token_type_ids') && !encoderFeeds.token_type_ids) {\n // Assign default `token_type_ids` (all zeroes) to the `encoderFeeds` if the model expects it,\n // but they weren't created by the tokenizer.\n encoderFeeds.token_type_ids = new Tensor(\n 'int64',\n new BigInt64Array(encoderFeeds.input_ids.data.length),\n encoderFeeds.input_ids.dims\n )\n }\n return await sessionRun(session, encoderFeeds);\n}\n\n/**\n * Forward pass of a decoder model.\n * @param {Object} self The decoder model.\n * @param {Object} model_inputs The input data to be used for the forward pass.\n * @returns {Promise} The logits and past key values.\n * @private\n */\nasync function decoderForward(self, model_inputs, is_encoder_decoder = false) {\n\n const session = self.sessions[\n is_encoder_decoder ? 'decoder_model_merged' : 'model'\n ]\n\n const { past_key_values, ...new_model_inputs } = model_inputs;\n\n if (session.inputNames.includes('use_cache_branch')) {\n new_model_inputs.use_cache_branch = boolTensor(!!past_key_values);\n }\n if (session.inputNames.includes('position_ids') && new_model_inputs.attention_mask && !new_model_inputs.position_ids) {\n new_model_inputs.position_ids = createPositionIds(new_model_inputs, past_key_values);\n }\n\n // Unpack the `past_key_values` object into model inputs\n self.addPastKeyValues(new_model_inputs, past_key_values);\n\n // Select only the inputs that are needed for the current session\n const fixed = pick(new_model_inputs, session.inputNames);\n return await sessionRun(session, fixed);\n}\n\n\n/**\n * Forward pass of an image-text-to-text model.\n * @param {Object} self The image-text-to-text model model.\n * @param {Object} model_inputs The input data to be used for the forward pass.\n * @param {Tensor} [model_inputs.input_ids=null]\n * @param {Tensor} [model_inputs.attention_mask=null]\n * @param {Tensor} [model_inputs.pixel_values=null]\n * @param {Tensor} [model_inputs.position_ids=null]\n * @param {Tensor} [model_inputs.inputs_embeds=null]\n * @param {Tensor} [model_inputs.past_key_values=null]\n * @param {Object} [model_inputs.generation_config=null]\n * @param {Object} [model_inputs.logits_processor=null]\n * @returns {Promise} The model's output tensor\n * @private\n */\nasync function imageTextToTextForward(self, {\n // Produced by the tokenizer/processor:\n input_ids = null,\n attention_mask = null,\n pixel_values = null,\n\n // Used during generation:\n position_ids = null,\n inputs_embeds = null,\n past_key_values = null,\n\n // Generic generation parameters\n generation_config = null,\n logits_processor = null,\n\n // TODO: needed?\n ...kwargs\n}) {\n\n if (!inputs_embeds) {\n // 1. Extract the input embeddings\n inputs_embeds = await self.encode_text({ input_ids });\n\n // 2. Possibly, merge text and images\n if (pixel_values && input_ids.dims[1] !== 1) {\n const image_features = await self.encode_image({ pixel_values });\n\n ({ inputs_embeds, attention_mask } = self._merge_input_ids_with_image_features({\n image_features,\n inputs_embeds,\n input_ids,\n attention_mask,\n }));\n\n } else if (past_key_values && pixel_values && input_ids.dims[1] === 1) {\n // This is the case when we are generating with cache\n const target_length = input_ids.dims[1]; // always 1\n const past_length = Object.values(past_key_values)[0].dims.at(-2);\n\n attention_mask = cat([\n ones([input_ids.dims[0], past_length]),\n attention_mask.slice(null, [attention_mask.dims[1] - target_length, attention_mask.dims[1]]),\n ], 1);\n }\n }\n\n const outputs = await decoderForward(self, {\n inputs_embeds,\n past_key_values,\n attention_mask,\n position_ids,\n generation_config,\n logits_processor,\n }, true);\n return outputs;\n}\n\nfunction createPositionIds(model_inputs, past_key_values = null) {\n // If the model supports providing position_ids, we create position_ids on the fly for batch generation,\n // by computing the cumulative sum of the attention mask along the sequence length dimension.\n // \n // Equivalent to:\n // position_ids = attention_mask.long().cumsum(-1) - 1\n // position_ids.masked_fill_(attention_mask == 0, 1)\n // if past_key_values:\n // position_ids = position_ids[:, -input_ids.shape[1] :]\n const { input_ids, inputs_embeds, attention_mask } = model_inputs;\n const [bz, seq_len] = attention_mask.dims;\n\n const data = new BigInt64Array(attention_mask.data.length);\n for (let i = 0; i < bz; ++i) {\n const start = i * seq_len;\n let sum = BigInt(0);\n for (let j = 0; j < seq_len; ++j) {\n const index = start + j;\n if (attention_mask.data[index] === 0n) {\n data[index] = BigInt(1);\n } else { // === 1n\n data[index] = sum;\n sum += attention_mask.data[index];\n }\n }\n }\n\n let position_ids = new Tensor('int64', data, attention_mask.dims);\n if (past_key_values) {\n const offset = -(input_ids ?? inputs_embeds).dims.at(1);\n position_ids = position_ids.slice(null, [offset, null]);\n }\n return position_ids;\n}\n\nfunction decoder_prepare_inputs_for_generation(self, input_ids, model_inputs, generation_config) {\n if (model_inputs.past_key_values) {\n const past_length = Object.values(model_inputs.past_key_values)[0].dims.at(-2);\n const { input_ids, attention_mask } = model_inputs;\n\n // Keep only the unprocessed tokens:\n // 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where\n // some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as\n // input)\n if (attention_mask && attention_mask.dims[1] > input_ids.dims[1]) {\n // NOTE: not needed since we only pass the generated tokens to the next forward pass\n // const offset = -(attention_mask.dims[1] - past_length);\n // model_inputs.input_ids = input_ids.slice(null, [offset, null]);\n }\n // 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens.\n // We can discard input_ids based on the past_length.\n else if (past_length < input_ids.dims[1]) {\n // NOTE: Required for phi models.\n // See https://github.com/huggingface/transformers/issues/30809#issuecomment-2111918479 for more information.\n model_inputs.input_ids = input_ids.slice(null, [past_length, null]);\n }\n // 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.\n else {\n if (\n // NOTE: Only used by VLMs (!= so that null matches undefined)\n self.config.image_token_index != null &&\n // Equivalent to `self.config.image_token_index in input_ids` (== so that int matches bigint)\n input_ids.data.some(x => x == self.config.image_token_index)\n ) {\n // TODO: Support multiple image tokens\n const num_image_tokens = self.config.num_image_tokens;\n if (!num_image_tokens) {\n throw new Error('`num_image_tokens` is missing in the model configuration.');\n }\n\n const num_new_tokens = input_ids.dims[1] - (past_length - num_image_tokens);\n model_inputs.input_ids = input_ids.slice(null, [-num_new_tokens, null]);\n\n // TODO: The attention mask should be formed from the attention mask passed in model_inputs\n model_inputs.attention_mask = ones([1, past_length + num_new_tokens]);\n }\n }\n }\n\n return model_inputs;\n}\n\nfunction encoder_decoder_prepare_inputs_for_generation(self, input_ids, model_inputs, generation_config) {\n if (model_inputs.past_key_values) {\n input_ids = input_ids.map(x => [x.at(-1)]);\n }\n\n return {\n ...model_inputs,\n decoder_input_ids: toI64Tensor(input_ids),\n };\n}\n\nfunction image_text_to_text_prepare_inputs_for_generation(self, ...args) {\n if (self.config.is_encoder_decoder) {\n return encoder_decoder_prepare_inputs_for_generation(self, ...args);\n } else {\n return decoder_prepare_inputs_for_generation(self, ...args);\n }\n}\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n/**\n * A base class for pre-trained models that provides the model configuration and an ONNX session.\n */\nexport class PreTrainedModel extends Callable {\n main_input_name = 'input_ids';\n forward_params = ['input_ids', 'attention_mask'];\n /**\n * Creates a new instance of the `PreTrainedModel` class.\n * @param {import('./configs.js').PretrainedConfig} config The model configuration.\n * @param {Record} sessions The inference sessions for the model.\n * @param {Record} configs Additional configuration files (e.g., generation_config.json).\n */\n constructor(config, sessions, configs) {\n super();\n\n this.config = config;\n this.sessions = sessions;\n this.configs = configs;\n\n const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);\n const modelType = MODEL_TYPE_MAPPING.get(modelName);\n\n this.can_generate = false;\n this._forward = null;\n\n this._prepare_inputs_for_generation = null;\n switch (modelType) {\n case MODEL_TYPES.DecoderOnly:\n this.can_generate = true;\n this._forward = decoderForward;\n this._prepare_inputs_for_generation = decoder_prepare_inputs_for_generation;\n break;\n case MODEL_TYPES.Seq2Seq:\n case MODEL_TYPES.Vision2Seq:\n case MODEL_TYPES.Musicgen:\n this.can_generate = true;\n\n this._forward = seq2seqForward;\n this._prepare_inputs_for_generation = encoder_decoder_prepare_inputs_for_generation;\n break;\n\n case MODEL_TYPES.EncoderDecoder:\n this._forward = seq2seqForward;\n break;\n case MODEL_TYPES.ImageTextToText:\n this.can_generate = true;\n this._forward = imageTextToTextForward;\n this._prepare_inputs_for_generation = image_text_to_text_prepare_inputs_for_generation;\n break;\n\n default:\n // should be MODEL_TYPES.EncoderOnly\n this._forward = encoderForward;\n break;\n }\n\n if (this.can_generate) {\n this.forward_params.push('past_key_values');\n }\n\n /** @type {import('./configs.js').TransformersJSConfig} */\n this.custom_config = this.config['transformers.js_config'] ?? {};\n }\n\n /**\n * Disposes of all the ONNX sessions that were created during inference.\n * @returns {Promise} An array of promises, one for each ONNX session that is being disposed.\n * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n */\n async dispose() {\n const promises = [];\n for (const session of Object.values(this.sessions)) {\n if (session?.handler?.dispose) {\n promises.push(session.handler.dispose())\n }\n }\n return await Promise.all(promises);\n }\n\n /**\n * Instantiate one of the model classes of the library from a pretrained model.\n * \n * The model class to instantiate is selected based on the `model_type` property of the config object\n * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)\n * \n * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:\n * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.\n * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a\n * user or organization name, like `dbmdz/bert-base-german-cased`.\n * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`.\n * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the model.\n * \n * @returns {Promise} A new instance of the `PreTrainedModel` class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n model_file_name = null,\n subfolder = 'onnx',\n device = null,\n dtype = null,\n use_external_data_format = null,\n session_options = {},\n } = {}) {\n\n let options = {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n model_file_name,\n subfolder,\n device,\n dtype,\n use_external_data_format,\n session_options,\n }\n\n const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this);\n const modelType = MODEL_TYPE_MAPPING.get(modelName);\n\n config = options.config = await AutoConfig.from_pretrained(pretrained_model_name_or_path, options);\n\n let info;\n if (modelType === MODEL_TYPES.DecoderOnly) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: options.model_file_name ?? 'model',\n }, options),\n getOptionalConfigs(pretrained_model_name_or_path, {\n generation_config: 'generation_config.json',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: 'encoder_model',\n decoder_model_merged: 'decoder_model_merged',\n }, options),\n getOptionalConfigs(pretrained_model_name_or_path, {\n generation_config: 'generation_config.json',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.MaskGeneration) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: 'vision_encoder',\n prompt_encoder_mask_decoder: 'prompt_encoder_mask_decoder',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.EncoderDecoder) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: 'encoder_model',\n decoder_model_merged: 'decoder_model_merged',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.ImageTextToText) {\n const sessions = {\n embed_tokens: 'embed_tokens',\n vision_encoder: 'vision_encoder',\n decoder_model_merged: 'decoder_model_merged',\n }\n if (config.is_encoder_decoder) {\n sessions['model'] = 'encoder_model';\n }\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, sessions, options),\n getOptionalConfigs(pretrained_model_name_or_path, {\n generation_config: 'generation_config.json',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.Musicgen) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: 'text_encoder',\n decoder_model_merged: 'decoder_model_merged',\n encodec_decode: 'encodec_decode',\n }, options),\n getOptionalConfigs(pretrained_model_name_or_path, {\n generation_config: 'generation_config.json',\n }, options),\n ]);\n\n } else { // should be MODEL_TYPES.EncoderOnly\n if (modelType !== MODEL_TYPES.EncoderOnly) {\n console.warn(`Model type for '${modelName ?? config?.model_type}' not found, assuming encoder-only architecture. Please report this at ${GITHUB_ISSUE_URL}.`)\n }\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: options.model_file_name ?? 'model',\n }, options),\n ]);\n }\n\n // @ts-ignore\n return new this(config, ...info);\n }\n\n /**\n * Runs the model with the provided inputs\n * @param {Object} model_inputs Object containing input tensors\n * @returns {Promise} Object containing output tensors\n */\n async _call(model_inputs) {\n return await this.forward(model_inputs);\n }\n\n /**\n * Forward method for a pretrained model. If not overridden by a subclass, the correct forward method\n * will be chosen based on the model type.\n * @param {Object} model_inputs The input data to the model in the format specified in the ONNX model.\n * @returns {Promise} The output data from the model in the format specified in the ONNX model.\n * @throws {Error} This method must be implemented in subclasses.\n */\n async forward(model_inputs) {\n return await this._forward(this, model_inputs);\n }\n\n /**\n * Get the model's generation config, if it exists.\n * @returns {GenerationConfig|null} The model's generation config if it exists, otherwise `null`.\n */\n get generation_config() {\n return this.configs?.generation_config ?? null;\n }\n\n /**\n * This function returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsWarper`]\n * instances used for multinomial sampling.\n * @param {GenerationConfig} generation_config The generation config.\n * @returns {LogitsProcessorList} generation_config \n */\n _get_logits_warper(generation_config) {\n\n // instantiate warpers list\n const warpers = new LogitsProcessorList();\n\n if (generation_config.temperature !== null && generation_config.temperature !== 1.0) {\n warpers.push(new TemperatureLogitsWarper(generation_config.temperature));\n }\n if (generation_config.top_k !== null && generation_config.top_k !== 0) {\n // TODO: add min_tokens_to_keep\n warpers.push(new TopKLogitsWarper(generation_config.top_k));\n }\n if (generation_config.top_p !== null && generation_config.top_p < 1.0) {\n // TODO: add min_tokens_to_keep\n warpers.push(new TopPLogitsWarper(generation_config.top_p));\n }\n\n return warpers;\n }\n\n /**\n * @param {GenerationConfig} generation_config \n * @param {number} input_ids_seq_length The starting sequence length for the input ids.\n * @returns {LogitsProcessorList}\n * @private\n */\n _get_logits_processor(\n generation_config,\n input_ids_seq_length,\n // encoder_input_ids, TODO\n // prefix_allowed_tokens_fn, TODO\n logits_processor = null\n ) {\n const processors = new LogitsProcessorList();\n\n // if (generation_config.diversity_penalty !== null && generation_config.diversity_penalty > 0.0) {\n // processors.push(new HammingDiversityLogitsProcessor(\n // generation_config.diversity_penalty,\n // generation_config.num_beams,\n // generation_config.num_beam_groups\n // ));\n // }\n\n // if (generation_config.encoder_repetition_penalty !== null && generation_config.encoder_repetition_penalty !== 1.0) {\n // processors.push(new EncoderRepetitionPenaltyLogitsProcessor(\n // generation_config.encoder_repetition_penalty,\n // encoder_input_ids\n // ));\n // }\n\n if (generation_config.repetition_penalty !== null && generation_config.repetition_penalty !== 1.0) {\n processors.push(new RepetitionPenaltyLogitsProcessor(generation_config.repetition_penalty));\n }\n\n if (generation_config.no_repeat_ngram_size !== null && generation_config.no_repeat_ngram_size > 0) {\n processors.push(new NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size));\n }\n\n // if (generation_config.encoder_no_repeat_ngram_size !== null && generation_config.encoder_no_repeat_ngram_size > 0) {\n // if (this.config.is_encoder_decoder) {\n // processors.push(new EncoderNoRepeatNGramLogitsProcessor(\n // generation_config.encoder_no_repeat_ngram_size,\n // encoder_input_ids\n // ));\n // } else {\n // throw new Error(\"It's impossible to use `encoder_no_repeat_ngram_size` with decoder-only architecture\");\n // }\n // }\n\n if (generation_config.bad_words_ids !== null) {\n processors.push(new NoBadWordsLogitsProcessor(generation_config.bad_words_ids, generation_config.eos_token_id));\n }\n\n if (generation_config.min_length !== null && generation_config.eos_token_id !== null && generation_config.min_length > 0) {\n processors.push(new MinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id));\n }\n\n if (generation_config.min_new_tokens !== null && generation_config.eos_token_id !== null && generation_config.min_new_tokens > 0) {\n processors.push(new MinNewTokensLengthLogitsProcessor(\n input_ids_seq_length,\n generation_config.min_new_tokens,\n generation_config.eos_token_id\n ));\n }\n\n // if (prefix_allowed_tokens_fn !== null) {\n // processors.push(new PrefixConstrainedLogitsProcessor(\n // prefix_allowed_tokens_fn,\n // generation_config.num_beams / generation_config.num_beam_groups\n // ));\n // }\n\n\n if (generation_config.forced_bos_token_id !== null) {\n processors.push(new ForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id));\n }\n\n if (generation_config.forced_eos_token_id !== null) {\n processors.push(new ForcedEOSTokenLogitsProcessor(\n generation_config.max_length,\n generation_config.forced_eos_token_id\n ));\n }\n\n // if (generation_config.remove_invalid_values === true) {\n // processors.push(new InfNanRemoveLogitsProcessor());\n // }\n\n // if (generation_config.exponential_decay_length_penalty !== null) {\n // processors.push(new ExponentialDecayLengthPenalty(\n // generation_config.exponential_decay_length_penalty,\n // generation_config.eos_token_id,\n // input_ids_seq_length\n // ));\n // }\n\n // if (generation_config.suppress_tokens !== null) {\n // processors.push(new SuppressTokensLogitsProcessor(generation_config.suppress_tokens));\n // }\n\n if (generation_config.begin_suppress_tokens !== null) {\n const begin_index = (input_ids_seq_length > 1 || generation_config.forced_bos_token_id === null)\n ? input_ids_seq_length\n : input_ids_seq_length + 1;\n\n processors.push(new SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index));\n }\n\n // DEPRECATED: https://github.com/huggingface/transformers/pull/29485\n // if (generation_config.forced_decoder_ids !== null) {\n // processors.push(new ForceTokensLogitsProcessor(generation_config.forced_decoder_ids));\n // }\n\n\n // 8. prepare batched CFG externally\n if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) {\n processors.push(new ClassifierFreeGuidanceLogitsProcessor(generation_config.guidance_scale));\n }\n\n if (logits_processor !== null) {\n processors.extend(logits_processor)\n }\n\n // `LogitNormalization` should always be the last logit processor, when present\n // if (generation_config.renormalize_logits === true) {\n // processors.push(new LogitNormalization());\n // }\n\n return processors;\n }\n\n /**\n * This function merges multiple generation configs together to form a final generation config to be used by the model for text generation.\n * It first creates an empty `GenerationConfig` object, then it applies the model's own `generation_config` property to it. Finally, if a `generation_config` object was passed in the arguments, it overwrites the corresponding properties in the final config with those of the passed config object.\n * @param {GenerationConfig|null} generation_config A `GenerationConfig` object containing generation parameters.\n * @param {Object} kwargs Additional generation parameters to be used in place of those in the `generation_config` object.\n * @returns {GenerationConfig} The final generation config object to be used by the model for text generation.\n */\n _prepare_generation_config(generation_config, kwargs, cls = GenerationConfig) {\n // Create empty generation config (contains defaults)\n // We pass `this.config` so that if `eos_token_id` or `bos_token_id` exist in the model's config, we will use them\n const config = { ...this.config };\n for (const key of [\"decoder\", \"generator\", \"text_config\"]) {\n // Special case: some models have generation attributes set in the decoder.\n // Use them if still unset in the generation config.\n if (key in config) {\n Object.assign(config, config[key]);\n }\n }\n\n const gen_config = new cls(config);\n\n // Apply model's generation config, if it exists\n Object.assign(gen_config, this.generation_config ?? {});\n\n // Next, use any generation config specified by the user\n // when calling `generate`\n if (generation_config) {\n Object.assign(gen_config, generation_config);\n }\n\n // Finally, if any kwargs were passed, use them to overwrite\n if (kwargs) {\n Object.assign(gen_config, pick(kwargs, Object.getOwnPropertyNames(gen_config)));\n }\n\n return gen_config;\n }\n\n /**\n * \n * @param {GenerationConfig} generation_config \n * @param {StoppingCriteriaList} [stopping_criteria=null] \n */\n _get_stopping_criteria(generation_config, stopping_criteria = null) {\n const criteria = new StoppingCriteriaList();\n\n if (generation_config.max_length !== null) {\n criteria.push(new MaxLengthCriteria(\n generation_config.max_length,\n this.config.max_position_embeddings ?? null,\n ));\n }\n // if (generation_config.max_time !== null) {\n // criteria.push(new MaxTimeCriteria(generation_config.max_time));\n // }\n if (generation_config.eos_token_id !== null) {\n criteria.push(new EosTokenCriteria(generation_config.eos_token_id));\n }\n\n if (stopping_criteria) {\n criteria.extend(stopping_criteria);\n }\n return criteria;\n\n }\n\n /**\n * Confirms that the model class is compatible with generation.\n * If not, raises an exception that points to the right class to use.\n */\n _validate_model_class() {\n if (!this.can_generate) {\n const generate_compatible_mappings = [\n MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,\n // MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING, // TODO\n MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,\n MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,\n MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES,\n ];\n\n const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);\n\n const generate_compatible_classes = new Set();\n const modelType = this.config.model_type;\n for (const model_mapping of generate_compatible_mappings) {\n const supported_models = model_mapping.get(modelType);\n if (supported_models) {\n generate_compatible_classes.add(supported_models[0]);\n }\n }\n\n let errorMessage = `The current model class (${modelName}) is not compatible with \\`.generate()\\`, as it doesn't have a language model head.`\n if (generate_compatible_classes.size > 0) {\n errorMessage += ` Please use the following class instead: ${[...generate_compatible_classes].join(', ')}`;\n }\n throw Error(errorMessage);\n }\n }\n\n prepare_inputs_for_generation(...args) {\n return this._prepare_inputs_for_generation(this, ...args);\n }\n\n /**\n * \n * @param {Object} inputs\n * @param {bigint[][]} inputs.generated_input_ids\n * @param {Object} inputs.outputs\n * @param {Object} inputs.model_inputs\n * @param {boolean} inputs.is_encoder_decoder\n * @returns {Object} The updated model inputs for the next generation iteration.\n */\n _update_model_kwargs_for_generation({ generated_input_ids, outputs, model_inputs, is_encoder_decoder }) {\n // update past_key_values\n model_inputs['past_key_values'] = this.getPastKeyValues(outputs, model_inputs.past_key_values);\n\n // update inputs for next run\n model_inputs['input_ids'] = new Tensor('int64', generated_input_ids.flat(), [generated_input_ids.length, 1]);\n\n if (!is_encoder_decoder) {\n // update attention mask\n model_inputs.attention_mask = cat(\n [\n model_inputs.attention_mask,\n ones([model_inputs.attention_mask.dims[0], 1]),\n ], 1\n );\n } else if ('decoder_attention_mask' in model_inputs) {\n // TODO: update decoder attention mask if the model requires it\n }\n\n // force recreate position_ids in next iteration\n model_inputs['position_ids'] = null;\n\n return model_inputs;\n }\n\n /**\n * This function extracts the model-specific `inputs` for generation.\n * @param {Object} params\n * @param {Tensor} [params.inputs=null]\n * @param {number} [params.bos_token_id=null]\n * @param {Record} [params.model_kwargs]\n * @returns {{inputs_tensor: Tensor, model_inputs: Record, model_input_name: string}} The model-specific inputs for generation.\n */\n _prepare_model_inputs({ inputs, bos_token_id, model_kwargs }) {\n const model_inputs = pick(model_kwargs, this.forward_params);\n const input_name = this.main_input_name;\n if (input_name in model_inputs) {\n if (inputs) {\n throw new Error(\n \"`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. \" +\n \"Make sure to either pass {inputs} or {input_name}=...\"\n );\n }\n } else {\n model_inputs[input_name] = inputs;\n }\n\n const inputs_tensor = model_inputs[input_name];\n\n return { inputs_tensor, model_inputs, model_input_name: input_name };\n }\n\n async _prepare_encoder_decoder_kwargs_for_generation({ inputs_tensor, model_inputs, model_input_name, generation_config }) {\n if (\n this.sessions['model'].inputNames.includes('inputs_embeds')\n && !model_inputs.inputs_embeds\n && '_prepare_inputs_embeds' in this\n ) {\n // Encoder expects `inputs_embeds` instead of `input_ids`\n const { input_ids, pixel_values, attention_mask, ...kwargs } = model_inputs;\n // @ts-ignore\n const prepared_inputs = await this._prepare_inputs_embeds(model_inputs);\n model_inputs = {\n ...kwargs,\n ...pick(prepared_inputs, ['inputs_embeds', 'attention_mask']),\n };\n }\n let { last_hidden_state } = await encoderForward(this, model_inputs);\n\n // for classifier free guidance we need to add a 'null' input to our encoder hidden states\n if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) {\n\n last_hidden_state = cat([\n last_hidden_state,\n full_like(last_hidden_state, 0.0),\n ], 0);\n\n if ('attention_mask' in model_inputs) {\n model_inputs['attention_mask'] = cat([\n model_inputs['attention_mask'],\n zeros_like(model_inputs['attention_mask']),\n ], 0);\n }\n\n } else if (model_inputs.decoder_input_ids) {\n // Ensure that the encoder outputs have the same batch size as the decoder inputs,\n // allowing for more efficient batched generation for single inputs\n const decoder_input_ids_batch_size = toI64Tensor(model_inputs.decoder_input_ids).dims[0];\n if (decoder_input_ids_batch_size !== last_hidden_state.dims[0]) {\n if (last_hidden_state.dims[0] !== 1) {\n throw new Error(\n `The encoder outputs have a different batch size (${last_hidden_state.dims[0]}) than the decoder inputs (${decoder_input_ids_batch_size}).`\n )\n }\n last_hidden_state = cat(Array.from({ length: decoder_input_ids_batch_size }, () => last_hidden_state), 0);\n }\n }\n model_inputs['encoder_outputs'] = last_hidden_state;\n\n return model_inputs;\n }\n\n /**\n * Prepares `decoder_input_ids` for generation with encoder-decoder models\n * @param {*} param0 \n */\n _prepare_decoder_input_ids_for_generation({ batch_size, model_input_name, model_kwargs, decoder_start_token_id, bos_token_id, generation_config }) {\n let { decoder_input_ids, ...model_inputs } = model_kwargs;\n\n // Prepare input ids if the user has not defined `decoder_input_ids` manually.\n if (!decoder_input_ids) {\n decoder_start_token_id ??= bos_token_id;\n\n if (this.config.model_type === 'musicgen') {\n // Custom logic (TODO: move to Musicgen class)\n decoder_input_ids = Array.from({\n length: batch_size * this.config.decoder.num_codebooks\n }, () => [decoder_start_token_id]);\n\n } else if (Array.isArray(decoder_start_token_id)) {\n if (decoder_start_token_id.length !== batch_size) {\n throw new Error(\n `\\`decoder_start_token_id\\` expcted to have length ${batch_size} but got ${decoder_start_token_id.length}`\n )\n }\n decoder_input_ids = decoder_start_token_id;\n } else {\n decoder_input_ids = Array.from({\n length: batch_size,\n }, () => [decoder_start_token_id]);\n }\n } else if (!Array.isArray(decoder_input_ids[0])) {\n // Correct batch size\n decoder_input_ids = Array.from({\n length: batch_size,\n }, () => decoder_input_ids);\n }\n\n decoder_input_ids = toI64Tensor(decoder_input_ids);\n model_kwargs['decoder_attention_mask'] = ones_like(decoder_input_ids);\n\n return { input_ids: decoder_input_ids, model_inputs };\n }\n\n /**\n * Generates sequences of token ids for models with a language modeling head.\n * @param {import('./generation/parameters.js').GenerationFunctionParameters} options\n * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores.\n */\n async generate({\n inputs = null,\n generation_config = null,\n logits_processor = null,\n stopping_criteria = null,\n streamer = null,\n\n // inputs_attention_mask = null,\n ...kwargs\n }) {\n this._validate_model_class();\n\n // Update generation config with defaults and kwargs\n generation_config = this._prepare_generation_config(generation_config, kwargs);\n\n // 3. Define model inputs\n let { inputs_tensor, model_inputs, model_input_name } = this._prepare_model_inputs({\n inputs,\n model_kwargs: kwargs,\n });\n\n const is_encoder_decoder = this.config.is_encoder_decoder;\n\n // 4. Define other model kwargs\n if (!is_encoder_decoder) {\n // decoder-only models should use left-padding for generation\n } else if (!('encoder_outputs' in model_inputs)) {\n // if model is encoder decoder encoder_outputs are created\n // and added to `model_kwargs`\n model_inputs = await this._prepare_encoder_decoder_kwargs_for_generation(\n { inputs_tensor, model_inputs, model_input_name, generation_config }\n )\n }\n\n // 5. Prepare `input_ids` which will be used for auto-regressive generation\n // TODO: Update to align with HF transformers' implementation\n let input_ids;\n if (is_encoder_decoder) {\n // Generating from the encoder outputs\n ({ input_ids, model_inputs } = this._prepare_decoder_input_ids_for_generation({\n batch_size: model_inputs[model_input_name].dims.at(0),\n model_input_name,\n model_kwargs: model_inputs,\n decoder_start_token_id: generation_config.decoder_start_token_id,\n bos_token_id: generation_config.bos_token_id,\n generation_config,\n }));\n } else {\n input_ids = model_inputs[model_input_name]\n }\n\n // 6. Prepare `max_length` depending on other stopping criteria.\n let input_ids_length = input_ids.dims.at(-1);\n\n if (generation_config.max_new_tokens !== null) {\n generation_config.max_length = input_ids_length + generation_config.max_new_tokens;\n }\n\n // input_ids_length = model_inputs[model_input_name].dims.at(1);\n // // inputs instanceof Tensor ? : inputs.length;\n\n // // decoder-only\n // if (input_ids_length === 0) {\n // throw Error(\"Must supply a non-empty array of input token ids.\")\n // }\n\n // let decoder_input_ids =\n // generation_config.decoder_input_ids\n // ?? generation_config.decoder_start_token_id\n // ?? generation_config.bos_token_id\n // ?? generation_config.eos_token_id;\n\n // Update logits processor\n // 8. prepare distribution pre_processing samplers\n const prepared_logits_processor = this._get_logits_processor(\n generation_config,\n input_ids_length,\n logits_processor,\n )\n\n // 9. prepare stopping criteria\n const prepared_stopping_criteria = this._get_stopping_criteria(\n generation_config, stopping_criteria\n )\n\n // /** @type {number[]} */\n // let eos_token_ids = generation_config.eos_token_id;\n // if (eos_token_ids !== null && !Array.isArray(eos_token_ids)) {\n // eos_token_ids = [eos_token_ids];\n // }\n\n const numInputs = model_inputs[model_input_name].dims.at(0);\n\n // TODO:\n // done is a list of booleans to keep track of which inputs are done\n // const done = new Array(numInputs).fill(false);\n // For efficiency purposes, we remove completed rows from model_inputs\n // when the beam is complete, and we keep track of the row index\n // const rowIndexToBatchIndex = new Map();\n\n const sampler = LogitsSampler.getSampler(generation_config);\n\n // TODO make > numInputs\n const scores = new Array(numInputs).fill(0);\n /** @type {bigint[][]} */\n const all_input_ids = input_ids.tolist();\n if (streamer) {\n streamer.put(all_input_ids);\n }\n // const all_generated_input_ids = Array.from({ length: numInputs }, () => []);\n\n // NOTE: For now, we don't support spawning new beams\n // TODO: when we do, we simply copy past key values and accumulate into single large tensor\n\n ////////////////////////////////////////////////////\n // Generic search which handles 4 generation modes:\n // - GenerationMode.GREEDY_SEARCH\n // - GenerationMode.SAMPLE\n // - GenerationMode.BEAM_SEARCH\n // - GenerationMode.BEAM_SAMPLE\n ////////////////////////////////////////////////////\n let outputs;\n let attentions = {};\n while (true) {\n // prepare model inputs\n model_inputs = this.prepare_inputs_for_generation(all_input_ids, model_inputs, generation_config);\n outputs = await this.forward(model_inputs);\n\n if (generation_config.output_attentions && generation_config.return_dict_in_generate) {\n // Get attentions if they are present\n const token_attentions = this.getAttentions(outputs);\n for (const key in token_attentions) {\n if (!(key in attentions)) {\n attentions[key] = [];\n }\n attentions[key].push(token_attentions[key]);\n }\n }\n\n // Logits are of the form [batch_size, out_seq_length, vocab_size]\n // In most cases, this will be [batch_size, 1, vocab_size]\n // So, we select the last token's logits:\n // (equivalent to `logits = outputs.logits[:, -1, :]`)\n const logits = outputs.logits.slice(null, -1, null);\n\n const next_tokens_scores = prepared_logits_processor(all_input_ids, logits);\n\n /** @type {[bigint][]} */\n const generated_input_ids = [];\n // const new_kv_cache = [];// NOTE: Only used for beam search when concatenating new kv\n // Loop over each batch\n for (let batch_idx = 0; batch_idx < next_tokens_scores.dims.at(0); ++batch_idx) {\n const logs = next_tokens_scores[batch_idx];\n\n const sampledTokens = await sampler(logs);\n for (const [newTokenId, logProb] of sampledTokens) {\n const bigint = BigInt(newTokenId);\n // TODO: If branching, use previous beam as a starting point\n // update generated ids, model inputs, and length for next step\n scores[batch_idx] += logProb;\n all_input_ids[batch_idx].push(bigint);\n generated_input_ids.push([bigint]);\n\n // TODO: Support beam search\n break;\n }\n }\n if (streamer) {\n streamer.put(generated_input_ids);\n }\n\n const stop = prepared_stopping_criteria(all_input_ids);\n if (stop.every(x => x)) {\n break;\n }\n\n model_inputs = this._update_model_kwargs_for_generation({\n generated_input_ids, outputs, model_inputs, is_encoder_decoder,\n });\n }\n\n if (streamer) {\n streamer.end();\n }\n\n // Retrieve and dispose all final past key values (including encoder attentions)\n const past_key_values = this.getPastKeyValues(outputs, model_inputs.past_key_values, true);\n\n // TODO: ensure all_input_ids is padded correctly...\n const sequences = new Tensor('int64', all_input_ids.flat(), [all_input_ids.length, all_input_ids[0].length]);\n\n if (generation_config.return_dict_in_generate) {\n return {\n sequences,\n past_key_values,\n ...attentions,\n // TODO:\n // scores,\n // logits,\n }\n } else {\n // Dispose all remaining tensors\n for (const tensor of Object.values(outputs)) {\n if (tensor.location === 'gpu-buffer') {\n tensor.dispose();\n }\n }\n return sequences;\n }\n }\n\n /**\n * Returns an object containing past key values from the given decoder results object.\n *\n * @param {Object} decoderResults The decoder results object.\n * @param {Object} pastKeyValues The previous past key values.\n * @returns {Object} An object containing past key values.\n */\n getPastKeyValues(decoderResults, pastKeyValues, disposeEncoderPKVs = false) {\n const pkvs = Object.create(null);\n\n for (const name in decoderResults) {\n if (name.startsWith('present')) {\n const newName = name.replace('present', 'past_key_values');\n const is_encoder_pkv = name.includes('encoder');\n if (is_encoder_pkv && pastKeyValues) {\n // Optimization introduced by optimum to reuse past key values.\n // So, we just replace the constant outputs (`decoderResults[name]`) with the previous past key values.\n // https://github.com/huggingface/optimum/blob/0bf2c05fb7e1182b52d21b703cfc95fd9e4ea3dc/optimum/onnxruntime/base.py#L677-L704\n pkvs[newName] = pastKeyValues[newName];\n } else { // decoder or using first encoder PKVs\n pkvs[newName] = decoderResults[name];\n }\n\n if (pastKeyValues && (!is_encoder_pkv || disposeEncoderPKVs)) {\n // - Always dispose decoder PKVs\n // - Only dispose encoder past key values when requested (after generation)\n const t = pastKeyValues[newName];\n if (t.location === 'gpu-buffer') {\n t.dispose();\n }\n }\n }\n }\n return pkvs;\n }\n\n /**\n * Returns an object containing attentions from the given model output object.\n *\n * @param {Object} model_output The output of the model.\n * @returns {{cross_attentions?: Tensor[]}} An object containing attentions.\n */\n getAttentions(model_output) {\n const attentions = {};\n\n for (const attnName of ['cross_attentions', 'encoder_attentions', 'decoder_attentions']) {\n for (const name in model_output) {\n if (name.startsWith(attnName)) {\n if (!(attnName in attentions)) {\n attentions[attnName] = [];\n }\n attentions[attnName].push(model_output[name]);\n }\n }\n }\n return attentions;\n }\n\n /**\n * Adds past key values to the decoder feeds object. If pastKeyValues is null, creates new tensors for past key values.\n *\n * @param {Object} decoderFeeds The decoder feeds object to add past key values to.\n * @param {Object} pastKeyValues An object containing past key values.\n */\n addPastKeyValues(decoderFeeds, pastKeyValues) {\n if (pastKeyValues) {\n Object.assign(decoderFeeds, pastKeyValues)\n } else {\n const session = this.sessions['decoder_model_merged'] ?? this.sessions['model'];\n const dtype = session?.config?.kv_cache_dtype ?? 'float32';\n const empty = (dtype === 'float16') ? new Uint16Array() : [];\n\n const shapes = getKeyValueShapes(this.config);\n\n for (const name in shapes) {\n decoderFeeds[name] = new Tensor(dtype, empty, shapes[name]);\n }\n }\n }\n\n async encode_image({ pixel_values }) {\n // image_inputs === { pixel_values }\n const features = (await sessionRun(this.sessions['vision_encoder'], { pixel_values })).image_features;\n if (!this.config.num_image_tokens) {\n console.warn(\n 'The number of image tokens was not set in the model configuration. ' +\n `Setting it to the number of features detected by the vision encoder (${features.dims[1]}).`\n )\n this.config.num_image_tokens = features.dims[1];\n }\n return features;\n }\n\n async encode_text({ input_ids }) {\n // text_inputs === { input_ids, attention_mask }\n return (await sessionRun(this.sessions['embed_tokens'], { input_ids })).inputs_embeds;\n }\n}\n\n//////////////////////////////////////////////////\n// Base model output class\nexport class ModelOutput { }\n\n/**\n * Base class for model's outputs, with potential hidden states and attentions.\n */\nexport class BaseModelOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.last_hidden_state Sequence of hidden-states at the output of the last layer of the model.\n * @param {Tensor} [output.hidden_states] Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.\n * @param {Tensor} [output.attentions] Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n */\n constructor({ last_hidden_state, hidden_states = null, attentions = null }) {\n super();\n this.last_hidden_state = last_hidden_state;\n this.hidden_states = hidden_states;\n this.attentions = attentions;\n }\n}\n//////////////////////////////////////////////////\n// Bert models\nexport class BertPreTrainedModel extends PreTrainedModel { }\nexport class BertModel extends BertPreTrainedModel { }\n\n/**\n * BertForMaskedLM is a class representing a BERT model for masked language modeling.\n */\nexport class BertForMaskedLM extends BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * BertForSequenceClassification is a class representing a BERT model for sequence classification.\n */\nexport class BertForSequenceClassification extends BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * BertForTokenClassification is a class representing a BERT model for token classification.\n */\nexport class BertForTokenClassification extends BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * BertForQuestionAnswering is a class representing a BERT model for question answering.\n */\nexport class BertForQuestionAnswering extends BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// NomicBert models\nexport class NomicBertPreTrainedModel extends PreTrainedModel { }\nexport class NomicBertModel extends NomicBertPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// RoFormer models\nexport class RoFormerPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare RoFormer Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class RoFormerModel extends RoFormerPreTrainedModel { }\n\n/**\n * RoFormer Model with a `language modeling` head on top.\n */\nexport class RoFormerForMaskedLM extends RoFormerPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RoFormer Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class RoFormerForSequenceClassification extends RoFormerPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RoFormer Model with a token classification head on top (a linear layer on top of the hidden-states output)\n * e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class RoFormerForTokenClassification extends RoFormerPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RoFormer Model with a span classification head on top for extractive question-answering tasks like SQuAD\n * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n */\nexport class RoFormerForQuestionAnswering extends RoFormerPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n// TODO: Add RoFormerForCausalLM and RoFormerForMultipleChoice\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// ConvBert models\nexport class ConvBertPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ConvBERT Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class ConvBertModel extends ConvBertPreTrainedModel { }\n\n/**\n * ConvBERT Model with a language modeling head on top.\n */\nexport class ConvBertForMaskedLM extends ConvBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ConvBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class ConvBertForSequenceClassification extends ConvBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ConvBERT Model with a token classification head on top (a linear layer on top of the hidden-states output)\n * e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class ConvBertForTokenClassification extends ConvBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ConvBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD\n * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`)\n */\nexport class ConvBertForQuestionAnswering extends ConvBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Electra models\nexport class ElectraPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Electra Model transformer outputting raw hidden-states without any specific head on top.\n * Identical to the BERT model except that it uses an additional linear layer between the embedding\n * layer and the encoder if the hidden size and embedding size are different.\n */\nexport class ElectraModel extends ElectraPreTrainedModel { }\n// TODO add ElectraForPreTraining\n/**\n * Electra model with a language modeling head on top.\n */\nexport class ElectraForMaskedLM extends ElectraPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ELECTRA Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class ElectraForSequenceClassification extends ElectraPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * Electra model with a token classification head on top.\n */\nexport class ElectraForTokenClassification extends ElectraPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * LECTRA Model with a span classification head on top for extractive question-answering tasks like SQuAD\n * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n */\nexport class ElectraForQuestionAnswering extends ElectraPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// CamemBERT models\nexport class CamembertPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare CamemBERT Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class CamembertModel extends CamembertPreTrainedModel { }\n\n/**\n * CamemBERT Model with a `language modeling` head on top.\n */\nexport class CamembertForMaskedLM extends CamembertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * CamemBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.\n */\nexport class CamembertForSequenceClassification extends CamembertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * CamemBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class CamembertForTokenClassification extends CamembertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * CamemBERT Model with a span classification head on top for extractive question-answering tasks\n */\nexport class CamembertForQuestionAnswering extends CamembertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// DeBERTa models\nexport class DebertaPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare DeBERTa Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class DebertaModel extends DebertaPreTrainedModel { }\n\n/**\n * DeBERTa Model with a `language modeling` head on top.\n */\nexport class DebertaForMaskedLM extends DebertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class DebertaForSequenceClassification extends DebertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class DebertaForTokenClassification extends DebertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear\n * layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n */\nexport class DebertaForQuestionAnswering extends DebertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// DeBERTa-v2 models\nexport class DebertaV2PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare DeBERTa-V2 Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class DebertaV2Model extends DebertaV2PreTrainedModel { }\n\n/**\n * DeBERTa-V2 Model with a `language modeling` head on top.\n */\nexport class DebertaV2ForMaskedLM extends DebertaV2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa-V2 Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class DebertaV2ForSequenceClassification extends DebertaV2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa-V2 Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class DebertaV2ForTokenClassification extends DebertaV2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa-V2 Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear\n * layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n */\nexport class DebertaV2ForQuestionAnswering extends DebertaV2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// DistilBert models\nexport class DistilBertPreTrainedModel extends PreTrainedModel { }\nexport class DistilBertModel extends DistilBertPreTrainedModel { }\n\n/**\n * DistilBertForSequenceClassification is a class representing a DistilBERT model for sequence classification.\n */\nexport class DistilBertForSequenceClassification extends DistilBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DistilBertForTokenClassification is a class representing a DistilBERT model for token classification.\n */\nexport class DistilBertForTokenClassification extends DistilBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n\n/**\n * DistilBertForQuestionAnswering is a class representing a DistilBERT model for question answering.\n */\nexport class DistilBertForQuestionAnswering extends DistilBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DistilBertForMaskedLM is a class representing a DistilBERT model for masking task.\n */\nexport class DistilBertForMaskedLM extends DistilBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// ESM models\nexport class EsmPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ESM Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class EsmModel extends EsmPreTrainedModel { }\n\n/**\n * ESM Model with a `language modeling` head on top.\n */\nexport class EsmForMaskedLM extends EsmPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ESM Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class EsmForSequenceClassification extends EsmPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ESM Model with a token classification head on top (a linear layer on top of the hidden-states output)\n * e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class EsmForTokenClassification extends EsmPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// MobileBert models\nexport class MobileBertPreTrainedModel extends PreTrainedModel { }\nexport class MobileBertModel extends MobileBertPreTrainedModel { }\n\n/**\n * MobileBertForMaskedLM is a class representing a MobileBERT model for masking task.\n */\nexport class MobileBertForMaskedLM extends MobileBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class MobileBertForSequenceClassification extends MobileBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MobileBert Model with a span classification head on top for extractive question-answering tasks\n */\nexport class MobileBertForQuestionAnswering extends MobileBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MPNet models\nexport class MPNetPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MPNet Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class MPNetModel extends MPNetPreTrainedModel { }\n\n/**\n * MPNetForMaskedLM is a class representing a MPNet model for masked language modeling.\n */\nexport class MPNetForMaskedLM extends MPNetPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MPNetForSequenceClassification is a class representing a MPNet model for sequence classification.\n */\nexport class MPNetForSequenceClassification extends MPNetPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MPNetForTokenClassification is a class representing a MPNet model for token classification.\n */\nexport class MPNetForTokenClassification extends MPNetPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MPNetForQuestionAnswering is a class representing a MPNet model for question answering.\n */\nexport class MPNetForQuestionAnswering extends MPNetPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// SqueezeBert models\nexport class SqueezeBertPreTrainedModel extends PreTrainedModel { }\nexport class SqueezeBertModel extends SqueezeBertPreTrainedModel { }\nexport class SqueezeBertForMaskedLM extends SqueezeBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\nexport class SqueezeBertForSequenceClassification extends SqueezeBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\nexport class SqueezeBertForQuestionAnswering extends SqueezeBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Albert models\nexport class AlbertPreTrainedModel extends PreTrainedModel { }\nexport class AlbertModel extends AlbertPreTrainedModel { }\nexport class AlbertForSequenceClassification extends AlbertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\nexport class AlbertForQuestionAnswering extends AlbertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\nexport class AlbertForMaskedLM extends AlbertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// T5 models\nexport class T5PreTrainedModel extends PreTrainedModel {\n forward_params = [\n 'input_ids',\n 'attention_mask',\n 'encoder_outputs',\n 'decoder_input_ids',\n 'decoder_attention_mask',\n 'past_key_values',\n ];\n};\n\nexport class T5Model extends T5PreTrainedModel { }\n\n/**\n * T5Model is a class representing a T5 model for conditional generation.\n */\nexport class T5ForConditionalGeneration extends T5PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// LONGT5 models\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class LongT5PreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare LONGT5 Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class LongT5Model extends LongT5PreTrainedModel { }\n\n/**\n * LONGT5 Model with a `language modeling` head on top.\n */\nexport class LongT5ForConditionalGeneration extends LongT5PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// MT5 models\nexport class MT5PreTrainedModel extends PreTrainedModel { };\n\nexport class MT5Model extends MT5PreTrainedModel { }\n\n/**\n * A class representing a conditional sequence-to-sequence model based on the MT5 architecture.\n */\nexport class MT5ForConditionalGeneration extends MT5PreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Bart models\nexport class BartPretrainedModel extends PreTrainedModel { };\n\n/**\n * The bare BART Model outputting raw hidden-states without any specific head on top.\n */\nexport class BartModel extends BartPretrainedModel { }\n\n/**\n * The BART Model with a language modeling head. Can be used for summarization.\n */\nexport class BartForConditionalGeneration extends BartPretrainedModel { }\n\n/**\n * Bart model with a sequence classification/head on top (a linear layer on top of the pooled output)\n */\nexport class BartForSequenceClassification extends BartPretrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MBart models\nexport class MBartPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare MBART Model outputting raw hidden-states without any specific head on top.\n */\nexport class MBartModel extends MBartPreTrainedModel { }\n\n/**\n * The MBART Model with a language modeling head. Can be used for summarization, after fine-tuning the pretrained models.\n */\nexport class MBartForConditionalGeneration extends MBartPreTrainedModel { }\n\n/**\n * MBart model with a sequence classification/head on top (a linear layer on top of the pooled output).\n */\nexport class MBartForSequenceClassification extends MBartPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n\nexport class MBartForCausalLM extends MBartPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Blenderbot models\nexport class BlenderbotPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare Blenderbot Model outputting raw hidden-states without any specific head on top.\n */\nexport class BlenderbotModel extends BlenderbotPreTrainedModel { }\n\n/**\n * The Blenderbot Model with a language modeling head. Can be used for summarization.\n */\nexport class BlenderbotForConditionalGeneration extends BlenderbotPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Blenderbot models\nexport class BlenderbotSmallPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare BlenderbotSmall Model outputting raw hidden-states without any specific head on top.\n */\nexport class BlenderbotSmallModel extends BlenderbotSmallPreTrainedModel { }\n\n/**\n * The BlenderbotSmall Model with a language modeling head. Can be used for summarization.\n */\nexport class BlenderbotSmallForConditionalGeneration extends BlenderbotSmallPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Roberta models\nexport class RobertaPreTrainedModel extends PreTrainedModel { }\nexport class RobertaModel extends RobertaPreTrainedModel { }\n\n/**\n * RobertaForMaskedLM class for performing masked language modeling on Roberta models.\n */\nexport class RobertaForMaskedLM extends RobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RobertaForSequenceClassification class for performing sequence classification on Roberta models.\n */\nexport class RobertaForSequenceClassification extends RobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RobertaForTokenClassification class for performing token classification on Roberta models.\n */\nexport class RobertaForTokenClassification extends RobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RobertaForQuestionAnswering class for performing question answering on Roberta models.\n */\nexport class RobertaForQuestionAnswering extends RobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// XLM models\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class XLMPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare XLM Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class XLMModel extends XLMPreTrainedModel { }\n\n/**\n * The XLM Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class XLMWithLMHeadModel extends XLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLM Model with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class XLMForSequenceClassification extends XLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLM Model with a token classification head on top (a linear layer on top of the hidden-states output)\n */\nexport class XLMForTokenClassification extends XLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLM Model with a span classification head on top for extractive question-answering tasks\n */\nexport class XLMForQuestionAnswering extends XLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// XLMRoberta models\nexport class XLMRobertaPreTrainedModel extends PreTrainedModel { }\nexport class XLMRobertaModel extends XLMRobertaPreTrainedModel { }\n\n/**\n * XLMRobertaForMaskedLM class for performing masked language modeling on XLMRoberta models.\n */\nexport class XLMRobertaForMaskedLM extends XLMRobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLMRobertaForSequenceClassification class for performing sequence classification on XLMRoberta models.\n */\nexport class XLMRobertaForSequenceClassification extends XLMRobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLMRobertaForTokenClassification class for performing token classification on XLMRoberta models.\n */\nexport class XLMRobertaForTokenClassification extends XLMRobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLMRobertaForQuestionAnswering class for performing question answering on XLMRoberta models.\n */\nexport class XLMRobertaForQuestionAnswering extends XLMRobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Audio Spectrogram Transformer (AST) models\nexport class ASTPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare AST Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class ASTModel extends ASTPreTrainedModel { }\n\n/**\n * Audio Spectrogram Transformer model with an audio classification head on top\n * (a linear layer on top of the pooled output) e.g. for datasets like AudioSet, Speech Commands v2.\n */\nexport class ASTForAudioClassification extends ASTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Whisper models\nexport class WhisperPreTrainedModel extends PreTrainedModel {\n\n requires_attention_mask = false;\n main_input_name = 'input_features';\n forward_params = [\n 'input_features',\n 'attention_mask',\n 'decoder_input_ids',\n 'decoder_attention_mask',\n 'past_key_values',\n ];\n};\n\n/**\n * WhisperModel class for training Whisper models without a language model head.\n */\nexport class WhisperModel extends WhisperPreTrainedModel { }\n\n\n/**\n * WhisperForConditionalGeneration class for generating conditional outputs from Whisper models.\n */\nexport class WhisperForConditionalGeneration extends WhisperPreTrainedModel {\n\n _prepare_generation_config(generation_config, kwargs) {\n return /** @type {WhisperGenerationConfig} */ (super._prepare_generation_config(generation_config, kwargs, WhisperGenerationConfig));\n }\n\n /**\n * \n * @param {WhisperGenerationConfig} generation_config \n */\n _retrieve_init_tokens(generation_config) {\n // prefix tokens are of the form: \n // - Multilingual: <|startoftranscript|> <|lang_id|> <|task|> [<|notimestamps|>]\n // - English-only: <|startoftranscript|> [<|notimestamps|>]\n\n // 1. Handle <|startoftranscript|> token\n const init_tokens = [generation_config.decoder_start_token_id];\n\n // 2. Handle <|lang_id|> and <|task> tokens\n let language = generation_config.language;\n const task = generation_config.task;\n if (generation_config.is_multilingual) {\n if (!language) {\n // TODO: Implement language detection\n console.warn('No language specified - defaulting to English (en).');\n language = 'en';\n }\n\n // Add language token\n const language_code = whisper_language_to_code(language);\n const language_token = `<|${language_code}|>`;\n init_tokens.push(generation_config.lang_to_id[language_token])\n\n // Add task token\n // NOTE: Defaults to 'transcribe' if no task is specified\n init_tokens.push(generation_config.task_to_id[task ?? 'transcribe']);\n\n } else if (language || task) {\n throw new Error(\n \"Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.\"\n )\n }\n\n // 3. Handle <|notimestamps|> token\n if (\n !generation_config.return_timestamps\n && generation_config.no_timestamps_token_id\n && init_tokens.at(-1) !== generation_config.no_timestamps_token_id\n ) {\n init_tokens.push(generation_config.no_timestamps_token_id);\n } else if (\n generation_config.return_timestamps\n &&\n init_tokens.at(-1) === generation_config.no_timestamps_token_id\n ) {\n console.warn(\"<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`.\");\n init_tokens.pop();\n }\n\n // let's make sure we don't pass `null` tokens as prompt tokens\n return init_tokens.filter(token => token != null);\n }\n\n /**\n * Transcribes or translates log-mel input features to a sequence of auto-regressively generated token ids.\n * @param {import('./models/whisper/generation_whisper.js').WhisperGenerationFunctionParameters} options\n * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores.\n */\n async generate({\n inputs = null,\n generation_config = null,\n logits_processor = null,\n stopping_criteria = null,\n\n // Whisper-specific options (passed to kwargs)\n // prompt_ids = null,\n // language = null,\n // task = null,\n\n ...kwargs\n }) {\n generation_config = this._prepare_generation_config(generation_config, kwargs);\n\n const init_tokens = kwargs.decoder_input_ids ?? this._retrieve_init_tokens(generation_config);\n\n if (generation_config.return_timestamps) {\n logits_processor ??= new LogitsProcessorList();\n logits_processor.push(\n new WhisperTimeStampLogitsProcessor(generation_config, init_tokens)\n );\n }\n\n if (generation_config.begin_suppress_tokens) {\n logits_processor ??= new LogitsProcessorList();\n logits_processor.push(\n new SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, init_tokens.length)\n );\n }\n\n if (generation_config.return_token_timestamps) {\n if (!generation_config.alignment_heads) {\n throw new Error(\n \"Model generation config has no `alignment_heads`, token-level timestamps not available. \" +\n \"See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.\"\n )\n }\n\n if (generation_config.task === 'translate') {\n console.warn(\"Token-level timestamps may not be reliable for task 'translate'.\")\n }\n\n generation_config.output_attentions = true;\n generation_config.return_dict_in_generate = true;\n }\n\n const outputs = await super.generate({\n inputs,\n generation_config,\n logits_processor,\n decoder_input_ids: init_tokens,\n ...kwargs\n });\n\n if (generation_config.return_token_timestamps) {\n outputs[\"token_timestamps\"] = this._extract_token_timestamps(\n outputs,\n generation_config.alignment_heads,\n generation_config.num_frames,\n );\n }\n\n return outputs;\n }\n\n /**\n * Calculates token-level timestamps using the encoder-decoder cross-attentions and\n * dynamic time-warping (DTW) to map each output token to a position in the input audio.\n * If `num_frames` is specified, the encoder-decoder cross-attentions will be cropped before applying DTW.\n * @param {Object} generate_outputs Outputs generated by the model\n * @param {Tensor[][]} generate_outputs.cross_attentions The cross attentions output by the model\n * @param {Tensor} generate_outputs.sequences The sequences output by the model\n * @param {number[][]} alignment_heads Alignment heads of the model\n * @param {number} [num_frames=null] Number of frames in the input audio.\n * @param {number} [time_precision=0.02] Precision of the timestamps in seconds\n * @returns {Tensor} tensor containing the timestamps in seconds for each predicted token\n */\n _extract_token_timestamps(generate_outputs, alignment_heads, num_frames = null, time_precision = 0.02) {\n if (!generate_outputs.cross_attentions) {\n throw new Error(\n \"Model outputs must contain cross attentions to extract timestamps. \" +\n \"This is most likely because the model was not exported with `output_attentions=True`.\"\n )\n }\n if (num_frames == null) {\n console.warn(\n \"`num_frames` has not been set, meaning the entire audio will be analyzed. \" +\n \"This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).\"\n );\n }\n\n let median_filter_width = this.config.median_filter_width;\n if (median_filter_width === undefined) {\n console.warn(\"Model config has no `median_filter_width`, using default value of 7.\")\n median_filter_width = 7;\n }\n\n // TODO: Improve batch processing\n const batch = generate_outputs.cross_attentions;\n // Create a list with `decoder_layers` elements, each a tensor of shape\n // (batch size, attention_heads, output length, input length).\n const cross_attentions = Array.from({ length: this.config.decoder_layers },\n // Concatenate the cross attentions for each layer across sequence length dimension.\n (_, i) => cat(batch.map(x => x[i]), 2)\n );\n\n const weights = stack(alignment_heads.map(([l, h]) => {\n if (l >= cross_attentions.length) {\n throw new Error(`Layer index ${l} is out of bounds for cross attentions (length ${cross_attentions.length}).`)\n }\n return num_frames\n ? cross_attentions[l].slice(null, h, null, [0, num_frames])\n : cross_attentions[l].slice(null, h);\n })).transpose(1, 0, 2, 3);\n\n const [std, calculatedMean] = std_mean(weights, -2, 0, true);\n\n // Normalize and smoothen the weights.\n const smoothedWeights = weights.clone(); // [1, 8, seqLength, 1500]\n\n for (let a = 0; a < smoothedWeights.dims[0]; ++a) {\n const aTensor = smoothedWeights[a]; // [8, seqLength, 1500]\n\n for (let b = 0; b < aTensor.dims[0]; ++b) {\n const bTensor = aTensor[b]; // [seqLength, 1500]\n\n const stdTensorData = std[a][b][0].data; // [1500]\n const meanTensorData = calculatedMean[a][b][0].data; // [1500]\n\n for (let c = 0; c < bTensor.dims[0]; ++c) {\n\n let cTensorData = bTensor[c].data; // [1500]\n for (let d = 0; d < cTensorData.length; ++d) {\n cTensorData[d] = (cTensorData[d] - meanTensorData[d]) / stdTensorData[d]\n }\n\n // Apply median filter.\n cTensorData.set(medianFilter(cTensorData, median_filter_width))\n }\n }\n }\n\n // Average the different cross-attention heads.\n const batchedMatrices = [mean(smoothedWeights, 1)];\n\n const timestampsShape = generate_outputs.sequences.dims;\n\n const timestamps = new Tensor(\n 'float32',\n new Float32Array(timestampsShape[0] * timestampsShape[1]),\n timestampsShape\n );\n\n // Perform dynamic time warping on each element of the batch.\n for (let batch_idx = 0; batch_idx < timestampsShape[0]; ++batch_idx) {\n // NOTE: Since we run only one batch at a time, we can squeeze to get the same dimensions\n // as the python implementation\n const matrix = batchedMatrices[batch_idx].neg().squeeze_(0);\n const [text_indices, time_indices] = dynamic_time_warping(matrix.tolist());\n\n const diffs = Array.from({ length: text_indices.length - 1 }, (v, i) => text_indices[i + 1] - text_indices[i]);\n const jumps = mergeArrays([1], diffs).map(x => !!x); // convert to boolean\n\n const jump_times = [];\n for (let i = 0; i < jumps.length; ++i) {\n if (jumps[i]) {\n // NOTE: No point in rounding here, since we set to Float32Array later\n jump_times.push(time_indices[i] * time_precision);\n }\n }\n timestamps[batch_idx].data.set(jump_times, 1)\n }\n\n return timestamps;\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n/**\n * Vision Encoder-Decoder model based on OpenAI's GPT architecture for image captioning and other vision tasks\n */\nexport class VisionEncoderDecoderModel extends PreTrainedModel {\n main_input_name = 'pixel_values';\n forward_params = [\n 'pixel_values',\n 'input_ids',\n 'encoder_hidden_states',\n 'past_key_values',\n ];\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// LLaVa Models\nexport class LlavaPreTrainedModel extends PreTrainedModel {\n forward_params = [\n 'input_ids',\n 'pixel_values',\n 'attention_mask',\n 'position_ids',\n 'past_key_values',\n ];\n}\n\n/**\n * The LLAVA model which consists of a vision backbone and a language model.\n */\nexport class LlavaForConditionalGeneration extends LlavaPreTrainedModel {\n\n _merge_input_ids_with_image_features({\n inputs_embeds,\n image_features,\n input_ids,\n attention_mask,\n }) {\n\n const image_token_index = this.config.image_token_index;\n\n const idsList = input_ids.tolist();\n\n // NOTE: we use .findIndex instead of .indexOf to perform weak comparison (==) between BigInt and Number\n const indexOfImage = idsList.map(x => x.findIndex(x => x == image_token_index));\n\n const noImages = indexOfImage.every(x => x === -1);\n const allImages = indexOfImage.every(x => x !== -1);\n if (!noImages && !allImages) {\n // Check for padding reasons\n throw new Error('Every input should contain either 0 or 1 image token.');\n }\n\n if (noImages) {\n return {\n inputs_embeds,\n attention_mask,\n }\n }\n\n const stacked = [];\n const stacked_attention_mask = [];\n for (let i = 0; i < indexOfImage.length; ++i) {\n const index = indexOfImage[i];\n\n const e = inputs_embeds[i];\n const im = image_features[i];\n const am = attention_mask[i];\n stacked.push(\n cat([\n e.slice([0, index]),\n im,\n e.slice([index + 1, e.dims[0]]),\n ], 0)\n );\n\n stacked_attention_mask.push(\n cat([\n am.slice([0, index]),\n ones([im.dims[0]]),\n am.slice([index + 1, am.dims[0]])\n ], 0)\n )\n }\n\n return {\n inputs_embeds: stack(stacked, 0),\n attention_mask: stack(stacked_attention_mask, 0),\n }\n }\n}\n//////////////////////////////////////////////////\n\nexport class Moondream1ForConditionalGeneration extends LlavaForConditionalGeneration { } // NOTE: extends LlavaForConditionalGeneration\n\nexport class Florence2PreTrainedModel extends PreTrainedModel {\n forward_params = [\n // Encoder inputs\n 'input_ids',\n 'inputs_embeds',\n 'attention_mask',\n 'pixel_values',\n\n // Decoder inputs\n 'encoder_outputs',\n 'decoder_input_ids',\n 'decoder_inputs_embeds',\n 'decoder_attention_mask',\n 'past_key_values',\n ];\n main_input_name = 'inputs_embeds';\n}\n\nexport class Florence2ForConditionalGeneration extends Florence2PreTrainedModel {\n\n _merge_input_ids_with_image_features({\n inputs_embeds,\n image_features,\n input_ids,\n attention_mask,\n }) {\n return {\n inputs_embeds: cat([\n image_features, // image embeds\n inputs_embeds, // task prefix embeds\n ], 1),\n attention_mask: cat([\n ones(image_features.dims.slice(0, 2)), // image attention mask\n attention_mask, // task prefix attention mask\n ], 1),\n }\n }\n\n async _prepare_inputs_embeds({ input_ids, pixel_values, inputs_embeds, attention_mask }) {\n if (!input_ids && !pixel_values) {\n throw new Error('Either `input_ids` or `pixel_values` should be provided.');\n }\n\n // 1. Possibly, extract the input embeddings\n let text_features, image_features;\n if (input_ids) {\n text_features = await this.encode_text({ input_ids });\n }\n if (pixel_values) {\n image_features = await this.encode_image({ pixel_values });\n }\n\n // 2. Possibly, merge text and images\n if (text_features && image_features) {\n ({ inputs_embeds, attention_mask } = this._merge_input_ids_with_image_features({\n inputs_embeds: text_features,\n image_features,\n input_ids,\n attention_mask,\n }));\n } else {\n inputs_embeds = text_features || image_features;\n }\n\n return { inputs_embeds, attention_mask };\n }\n\n async forward({\n input_ids,\n pixel_values,\n attention_mask,\n decoder_input_ids,\n decoder_attention_mask,\n encoder_outputs,\n past_key_values,\n\n inputs_embeds,\n decoder_inputs_embeds,\n }) {\n if (!inputs_embeds) {\n ({ inputs_embeds, attention_mask } = await this._prepare_inputs_embeds({ input_ids, pixel_values, inputs_embeds, attention_mask }));\n }\n\n if (!encoder_outputs) {\n // Must compute encoder outputs\n let { last_hidden_state } = await encoderForward(this, { inputs_embeds, attention_mask });\n encoder_outputs = last_hidden_state;\n }\n\n if (!decoder_inputs_embeds) {\n if (!decoder_input_ids) {\n throw new Error('Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.');\n }\n decoder_inputs_embeds = await this.encode_text({ input_ids: decoder_input_ids });\n }\n\n const decoderFeeds = {\n inputs_embeds: decoder_inputs_embeds,\n attention_mask: decoder_attention_mask,\n encoder_attention_mask: attention_mask,\n encoder_hidden_states: encoder_outputs,\n past_key_values,\n };\n const decoder_outputs = await decoderForward(this, decoderFeeds, true);\n return decoder_outputs;\n }\n}\nexport class CLIPPreTrainedModel extends PreTrainedModel { }\n\n/**\n * CLIP Text and Vision Model with a projection layers on top\n * \n * **Example:** Perform zero-shot image classification with a `CLIPModel`.\n * \n * ```javascript\n * import { AutoTokenizer, AutoProcessor, CLIPModel, RawImage } from '@huggingface/transformers';\n * \n * // Load tokenizer, processor, and model\n * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/clip-vit-base-patch16');\n * let processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16');\n * let model = await CLIPModel.from_pretrained('Xenova/clip-vit-base-patch16');\n * \n * // Run tokenization\n * let texts = ['a photo of a car', 'a photo of a football match']\n * let text_inputs = tokenizer(texts, { padding: true, truncation: true });\n * \n * // Read image and run processor\n * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * let image_inputs = await processor(image);\n * \n * // Run model with both text and pixel inputs\n * let output = await model({ ...text_inputs, ...image_inputs });\n * // {\n * // logits_per_image: Tensor {\n * // dims: [ 1, 2 ],\n * // data: Float32Array(2) [ 18.579734802246094, 24.31830596923828 ],\n * // },\n * // logits_per_text: Tensor {\n * // dims: [ 2, 1 ],\n * // data: Float32Array(2) [ 18.579734802246094, 24.31830596923828 ],\n * // },\n * // text_embeds: Tensor {\n * // dims: [ 2, 512 ],\n * // data: Float32Array(1024) [ ... ],\n * // },\n * // image_embeds: Tensor {\n * // dims: [ 1, 512 ],\n * // data: Float32Array(512) [ ... ],\n * // }\n * // }\n * ```\n */\nexport class CLIPModel extends CLIPPreTrainedModel { }\n\n/**\n * The text model from CLIP without any head or projection on top.\n */\nexport class CLIPTextModel extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'text_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * CLIP Text Model with a projection layer on top (a linear layer on top of the pooled output)\n * \n * **Example:** Compute text embeddings with `CLIPTextModelWithProjection`.\n * \n * ```javascript\n * import { AutoTokenizer, CLIPTextModelWithProjection } from '@huggingface/transformers';\n * \n * // Load tokenizer and text model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clip-vit-base-patch16');\n * const text_model = await CLIPTextModelWithProjection.from_pretrained('Xenova/clip-vit-base-patch16');\n * \n * // Run tokenization\n * let texts = ['a photo of a car', 'a photo of a football match'];\n * let text_inputs = tokenizer(texts, { padding: true, truncation: true });\n * \n * // Compute embeddings\n * const { text_embeds } = await text_model(text_inputs);\n * // Tensor {\n * // dims: [ 2, 512 ],\n * // type: 'float32',\n * // data: Float32Array(1024) [ ... ],\n * // size: 1024\n * // }\n * ```\n */\nexport class CLIPTextModelWithProjection extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'text_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * The vision model from CLIP without any head or projection on top.\n */\nexport class CLIPVisionModel extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'vision_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * CLIP Vision Model with a projection layer on top (a linear layer on top of the pooled output)\n * \n * **Example:** Compute vision embeddings with `CLIPVisionModelWithProjection`.\n * \n * ```javascript\n * import { AutoProcessor, CLIPVisionModelWithProjection, RawImage} from '@huggingface/transformers';\n * \n * // Load processor and vision model\n * const processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16');\n * const vision_model = await CLIPVisionModelWithProjection.from_pretrained('Xenova/clip-vit-base-patch16');\n * \n * // Read image and run processor\n * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * let image_inputs = await processor(image);\n * \n * // Compute embeddings\n * const { image_embeds } = await vision_model(image_inputs);\n * // Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [ ... ],\n * // size: 512\n * // }\n * ```\n */\nexport class CLIPVisionModelWithProjection extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'vision_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// SigLIP models\nexport class SiglipPreTrainedModel extends PreTrainedModel { }\n\n/**\n * SigLIP Text and Vision Model with a projection layers on top\n * \n * **Example:** Perform zero-shot image classification with a `SiglipModel`.\n * \n * ```javascript\n * import { AutoTokenizer, AutoProcessor, SiglipModel, RawImage } from '@huggingface/transformers';\n * \n * // Load tokenizer, processor, and model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/siglip-base-patch16-224');\n * const processor = await AutoProcessor.from_pretrained('Xenova/siglip-base-patch16-224');\n * const model = await SiglipModel.from_pretrained('Xenova/siglip-base-patch16-224');\n * \n * // Run tokenization\n * const texts = ['a photo of 2 cats', 'a photo of 2 dogs'];\n * const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true });\n * \n * // Read image and run processor\n * const image = await RawImage.read('http://images.cocodataset.org/val2017/000000039769.jpg');\n * const image_inputs = await processor(image);\n * \n * // Run model with both text and pixel inputs\n * const output = await model({ ...text_inputs, ...image_inputs });\n * // {\n * // logits_per_image: Tensor {\n * // dims: [ 1, 2 ],\n * // data: Float32Array(2) [ -1.6019744873046875, -10.720091819763184 ],\n * // },\n * // logits_per_text: Tensor {\n * // dims: [ 2, 1 ],\n * // data: Float32Array(2) [ -1.6019744873046875, -10.720091819763184 ],\n * // },\n * // text_embeds: Tensor {\n * // dims: [ 2, 768 ],\n * // data: Float32Array(1536) [ ... ],\n * // },\n * // image_embeds: Tensor {\n * // dims: [ 1, 768 ],\n * // data: Float32Array(768) [ ... ],\n * // }\n * // }\n * ```\n */\nexport class SiglipModel extends SiglipPreTrainedModel { }\n\n/**\n * The text model from SigLIP without any head or projection on top.\n * \n * **Example:** Compute text embeddings with `SiglipTextModel`.\n * \n * ```javascript\n * import { AutoTokenizer, SiglipTextModel } from '@huggingface/transformers';\n * \n * // Load tokenizer and text model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/siglip-base-patch16-224');\n * const text_model = await SiglipTextModel.from_pretrained('Xenova/siglip-base-patch16-224');\n * \n * // Run tokenization\n * const texts = ['a photo of 2 cats', 'a photo of 2 dogs'];\n * const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true });\n * \n * // Compute embeddings\n * const { pooler_output } = await text_model(text_inputs);\n * // Tensor {\n * // dims: [ 2, 768 ],\n * // type: 'float32',\n * // data: Float32Array(1536) [ ... ],\n * // size: 1536\n * // }\n * ```\n */\nexport class SiglipTextModel extends SiglipPreTrainedModel {\n\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'text_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * The vision model from SigLIP without any head or projection on top.\n * \n * **Example:** Compute vision embeddings with `SiglipVisionModel`.\n * \n * ```javascript\n * import { AutoProcessor, SiglipVisionModel, RawImage} from '@huggingface/transformers';\n * \n * // Load processor and vision model\n * const processor = await AutoProcessor.from_pretrained('Xenova/siglip-base-patch16-224');\n * const vision_model = await SiglipVisionModel.from_pretrained('Xenova/siglip-base-patch16-224');\n * \n * // Read image and run processor\n * const image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * const image_inputs = await processor(image);\n * \n * // Compute embeddings\n * const { pooler_output } = await vision_model(image_inputs);\n * // Tensor {\n * // dims: [ 1, 768 ],\n * // type: 'float32',\n * // data: Float32Array(768) [ ... ],\n * // size: 768\n * // }\n * ```\n */\nexport class SiglipVisionModel extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'vision_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n//////////////////////////////////////////////////\n// ChineseCLIP models\nexport class ChineseCLIPPreTrainedModel extends PreTrainedModel { }\n\nexport class ChineseCLIPModel extends ChineseCLIPPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// CLIPSeg models\nexport class CLIPSegPreTrainedModel extends PreTrainedModel { }\n\nexport class CLIPSegModel extends CLIPSegPreTrainedModel { }\n\n/**\n * CLIPSeg model with a Transformer-based decoder on top for zero-shot and one-shot image segmentation.\n * \n * **Example:** Perform zero-shot image segmentation with a `CLIPSegForImageSegmentation` model.\n * \n * ```javascript\n * import { AutoTokenizer, AutoProcessor, CLIPSegForImageSegmentation, RawImage } from '@huggingface/transformers';\n * \n * // Load tokenizer, processor, and model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clipseg-rd64-refined');\n * const processor = await AutoProcessor.from_pretrained('Xenova/clipseg-rd64-refined');\n * const model = await CLIPSegForImageSegmentation.from_pretrained('Xenova/clipseg-rd64-refined');\n * \n * // Run tokenization\n * const texts = ['a glass', 'something to fill', 'wood', 'a jar'];\n * const text_inputs = tokenizer(texts, { padding: true, truncation: true });\n * \n * // Read image and run processor\n * const image = await RawImage.read('https://github.com/timojl/clipseg/blob/master/example_image.jpg?raw=true');\n * const image_inputs = await processor(image);\n * \n * // Run model with both text and pixel inputs\n * const { logits } = await model({ ...text_inputs, ...image_inputs });\n * // logits: Tensor {\n * // dims: [4, 352, 352],\n * // type: 'float32',\n * // data: Float32Array(495616) [ ... ],\n * // size: 495616\n * // }\n * ```\n * \n * You can visualize the predictions as follows:\n * ```javascript\n * const preds = logits\n * .unsqueeze_(1)\n * .sigmoid_()\n * .mul_(255)\n * .round_()\n * .to('uint8');\n * \n * for (let i = 0; i < preds.dims[0]; ++i) {\n * const img = RawImage.fromTensor(preds[i]);\n * img.save(`prediction_${i}.png`);\n * }\n * ```\n */\nexport class CLIPSegForImageSegmentation extends CLIPSegPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// GPT2 models\nexport class GPT2PreTrainedModel extends PreTrainedModel { }\n\nexport class GPT2Model extends GPT2PreTrainedModel { }\n\n/**\n * GPT-2 language model head on top of the GPT-2 base model. This model is suitable for text generation tasks.\n */\nexport class GPT2LMHeadModel extends GPT2PreTrainedModel { }\n// export class GPT2ForSequenceClassification extends GPT2PreTrainedModel {\n// TODO\n// }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// JAIS models\nexport class JAISPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare JAIS Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class JAISModel extends JAISPreTrainedModel { }\n\n/**\n * The JAIS Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class JAISLMHeadModel extends JAISPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// GPTNeo models\nexport class GPTNeoPreTrainedModel extends PreTrainedModel { }\nexport class GPTNeoModel extends GPTNeoPreTrainedModel { }\n\nexport class GPTNeoForCausalLM extends GPTNeoPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// GPTNeoX models\nexport class GPTNeoXPreTrainedModel extends PreTrainedModel { }\nexport class GPTNeoXModel extends GPTNeoXPreTrainedModel { }\n\nexport class GPTNeoXForCausalLM extends GPTNeoXPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// GPT-J models\nexport class GPTJPreTrainedModel extends PreTrainedModel { }\n\nexport class GPTJModel extends GPTJPreTrainedModel { }\n\nexport class GPTJForCausalLM extends GPTJPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// GPTBigCode models\nexport class GPTBigCodePreTrainedModel extends PreTrainedModel { }\n\nexport class GPTBigCodeModel extends GPTBigCodePreTrainedModel { }\n\nexport class GPTBigCodeForCausalLM extends GPTBigCodePreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// CodeGen models\nexport class CodeGenPreTrainedModel extends PreTrainedModel { }\n/**\n * CodeGenModel is a class representing a code generation model without a language model head.\n */\nexport class CodeGenModel extends CodeGenPreTrainedModel { }\n\n/**\n * CodeGenForCausalLM is a class that represents a code generation model based on the GPT-2 architecture. It extends the `CodeGenPreTrainedModel` class.\n */\nexport class CodeGenForCausalLM extends CodeGenPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// LLama models\n\n/**\n * The bare LLama Model outputting raw hidden-states without any specific head on top.\n */\nexport class LlamaPreTrainedModel extends PreTrainedModel { }\n/**\n * The bare LLaMA Model outputting raw hidden-states without any specific head on top.\n */\nexport class LlamaModel extends LlamaPreTrainedModel { }\n\nexport class LlamaForCausalLM extends LlamaPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Granite models\nexport class GranitePreTrainedModel extends PreTrainedModel { }\nexport class GraniteModel extends GranitePreTrainedModel { }\nexport class GraniteForCausalLM extends GranitePreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Cohere models\n\n/**\n * The bare Cohere Model outputting raw hidden-states without any specific head on top.\n */\nexport class CoherePreTrainedModel extends PreTrainedModel { }\nexport class CohereModel extends CoherePreTrainedModel { }\n\nexport class CohereForCausalLM extends CoherePreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Gemma models\n\n/**\n * The bare Gemma Model outputting raw hidden-states without any specific head on top.\n */\nexport class GemmaPreTrainedModel extends PreTrainedModel { }\n/**\n * The bare Gemma Model outputting raw hidden-states without any specific head on top.\n */\nexport class GemmaModel extends GemmaPreTrainedModel { }\n\nexport class GemmaForCausalLM extends GemmaPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Gemma2 models\n\n/**\n * The bare Gemma2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Gemma2PreTrainedModel extends PreTrainedModel { }\n/**\n * The bare Gemma2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Gemma2Model extends Gemma2PreTrainedModel { }\n\nexport class Gemma2ForCausalLM extends Gemma2PreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class OpenELMPreTrainedModel extends PreTrainedModel { }\nexport class OpenELMModel extends OpenELMPreTrainedModel { }\n\nexport class OpenELMForCausalLM extends OpenELMPreTrainedModel { }\n\n\n//////////////////////////////////////////////////\n// Qwen2 models\n\n/**\n * The bare Qwen2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Qwen2PreTrainedModel extends PreTrainedModel { }\n/**\n * The bare Qwen2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Qwen2Model extends Qwen2PreTrainedModel { }\n\nexport class Qwen2ForCausalLM extends Qwen2PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Phi models\nexport class PhiPreTrainedModel extends PreTrainedModel { }\n/**\n * The bare Phi Model outputting raw hidden-states without any specific head on top.\n */\nexport class PhiModel extends PhiPreTrainedModel { }\n\nexport class PhiForCausalLM extends PhiPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Phi3 models\nexport class Phi3PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Phi3 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Phi3Model extends Phi3PreTrainedModel { }\n\nexport class Phi3ForCausalLM extends Phi3PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Bloom models\n/**\n * The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class BloomPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Bloom Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class BloomModel extends BloomPreTrainedModel { }\n\n/**\n * The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class BloomForCausalLM extends BloomPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MPT models\nexport class MptPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Mpt Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class MptModel extends MptPreTrainedModel { }\n\n/**\n * The MPT Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class MptForCausalLM extends MptPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// OPT models\nexport class OPTPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare OPT Model outputting raw hidden-states without any specific head on top.\n */\nexport class OPTModel extends OPTPreTrainedModel { }\n\n/**\n * The OPT Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class OPTForCausalLM extends OPTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class ViTPreTrainedModel extends PreTrainedModel { }\nexport class ViTModel extends ViTPreTrainedModel { }\nexport class ViTForImageClassification extends ViTPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class PvtPreTrainedModel extends PreTrainedModel { }\nexport class PvtModel extends PvtPreTrainedModel { }\nexport class PvtForImageClassification extends PvtPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class ViTMAEPreTrainedModel extends PreTrainedModel { }\nexport class ViTMAEModel extends ViTMAEPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class ViTMSNPreTrainedModel extends PreTrainedModel { }\nexport class ViTMSNModel extends ViTMSNPreTrainedModel { }\nexport class ViTMSNForImageClassification extends ViTMSNPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class GroupViTPreTrainedModel extends PreTrainedModel { }\nexport class GroupViTModel extends GroupViTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class FastViTPreTrainedModel extends PreTrainedModel { }\nexport class FastViTModel extends FastViTPreTrainedModel { }\nexport class FastViTForImageClassification extends FastViTPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class VitMattePreTrainedModel extends PreTrainedModel { }\n\n/**\n * ViTMatte framework leveraging any vision backbone e.g. for ADE20k, CityScapes.\n * \n * **Example:** Perform image matting with a `VitMatteForImageMatting` model.\n * ```javascript\n * import { AutoProcessor, VitMatteForImageMatting, RawImage } from '@huggingface/transformers';\n * \n * // Load processor and model\n * const processor = await AutoProcessor.from_pretrained('Xenova/vitmatte-small-distinctions-646');\n * const model = await VitMatteForImageMatting.from_pretrained('Xenova/vitmatte-small-distinctions-646');\n * \n * // Load image and trimap\n * const image = await RawImage.fromURL('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/vitmatte_image.png');\n * const trimap = await RawImage.fromURL('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/vitmatte_trimap.png');\n * \n * // Prepare image + trimap for the model\n * const inputs = await processor(image, trimap);\n * \n * // Predict alpha matte\n * const { alphas } = await model(inputs);\n * // Tensor {\n * // dims: [ 1, 1, 640, 960 ],\n * // type: 'float32',\n * // size: 614400,\n * // data: Float32Array(614400) [ 0.9894027709960938, 0.9970508813858032, ... ]\n * // }\n * ```\n * \n * You can visualize the alpha matte as follows:\n * ```javascript\n * import { Tensor, cat } from '@huggingface/transformers';\n * \n * // Visualize predicted alpha matte\n * const imageTensor = image.toTensor();\n * \n * // Convert float (0-1) alpha matte to uint8 (0-255)\n * const alphaChannel = alphas\n * .squeeze(0)\n * .mul_(255)\n * .clamp_(0, 255)\n * .round_()\n * .to('uint8');\n * \n * // Concatenate original image with predicted alpha\n * const imageData = cat([imageTensor, alphaChannel], 0);\n * \n * // Save output image\n * const outputImage = RawImage.fromTensor(imageData);\n * outputImage.save('output.png');\n * ```\n */\nexport class VitMatteForImageMatting extends VitMattePreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new ImageMattingOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class MobileViTPreTrainedModel extends PreTrainedModel { }\nexport class MobileViTModel extends MobileViTPreTrainedModel { }\nexport class MobileViTForImageClassification extends MobileViTPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n// TODO: MobileViTForSemanticSegmentation\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class MobileViTV2PreTrainedModel extends PreTrainedModel { }\nexport class MobileViTV2Model extends MobileViTV2PreTrainedModel { }\nexport class MobileViTV2ForImageClassification extends MobileViTV2PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n// TODO: MobileViTV2ForSemanticSegmentation\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class OwlViTPreTrainedModel extends PreTrainedModel { }\nexport class OwlViTModel extends OwlViTPreTrainedModel { }\nexport class OwlViTForObjectDetection extends OwlViTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class Owlv2PreTrainedModel extends PreTrainedModel { }\nexport class Owlv2Model extends Owlv2PreTrainedModel { }\nexport class Owlv2ForObjectDetection extends Owlv2PreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Beit Models\nexport class BeitPreTrainedModel extends PreTrainedModel { }\nexport class BeitModel extends BeitPreTrainedModel { }\nexport class BeitForImageClassification extends BeitPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class DetrPreTrainedModel extends PreTrainedModel { }\nexport class DetrModel extends DetrPreTrainedModel { }\nexport class DetrForObjectDetection extends DetrPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new DetrObjectDetectionOutput(await super._call(model_inputs));\n }\n}\n\nexport class DetrForSegmentation extends DetrPreTrainedModel {\n /**\n * Runs the model with the provided inputs\n * @param {Object} model_inputs Model inputs\n * @returns {Promise} Object containing segmentation outputs\n */\n async _call(model_inputs) {\n return new DetrSegmentationOutput(await super._call(model_inputs));\n }\n}\n\nexport class DetrObjectDetectionOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification logits (including no-object) for all queries.\n * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).\n * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).\n */\n constructor({ logits, pred_boxes }) {\n super();\n this.logits = logits;\n this.pred_boxes = pred_boxes;\n }\n}\n\nexport class DetrSegmentationOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits The output logits of the model.\n * @param {Tensor} output.pred_boxes Predicted boxes.\n * @param {Tensor} output.pred_masks Predicted masks.\n */\n constructor({ logits, pred_boxes, pred_masks }) {\n super();\n this.logits = logits;\n this.pred_boxes = pred_boxes;\n this.pred_masks = pred_masks;\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class RTDetrPreTrainedModel extends PreTrainedModel { }\nexport class RTDetrModel extends RTDetrPreTrainedModel { }\nexport class RTDetrForObjectDetection extends RTDetrPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new RTDetrObjectDetectionOutput(await super._call(model_inputs));\n }\n}\n\nexport class RTDetrObjectDetectionOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification logits (including no-object) for all queries.\n * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).\n * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).\n */\n constructor({ logits, pred_boxes }) {\n super();\n this.logits = logits;\n this.pred_boxes = pred_boxes;\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class TableTransformerPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Table Transformer Model (consisting of a backbone and encoder-decoder Transformer)\n * outputting raw hidden-states without any specific head on top.\n */\nexport class TableTransformerModel extends TableTransformerPreTrainedModel { }\n\n/**\n * Table Transformer Model (consisting of a backbone and encoder-decoder Transformer)\n * with object detection heads on top, for tasks such as COCO detection.\n */\nexport class TableTransformerForObjectDetection extends TableTransformerPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new TableTransformerObjectDetectionOutput(await super._call(model_inputs));\n }\n}\nexport class TableTransformerObjectDetectionOutput extends DetrObjectDetectionOutput { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class DeiTPreTrainedModel extends PreTrainedModel { }\nexport class DeiTModel extends DeiTPreTrainedModel { }\nexport class DeiTForImageClassification extends DeiTPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class HieraPreTrainedModel extends PreTrainedModel { }\nexport class HieraModel extends HieraPreTrainedModel { }\nexport class HieraForImageClassification extends HieraPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class ResNetPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ResNet model outputting raw features without any specific head on top.\n */\nexport class ResNetModel extends ResNetPreTrainedModel { }\n\n/**\n * ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.\n */\nexport class ResNetForImageClassification extends ResNetPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class SwinPreTrainedModel extends PreTrainedModel { }\nexport class SwinModel extends SwinPreTrainedModel { }\nexport class SwinForImageClassification extends SwinPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class Swin2SRPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Swin2SR Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class Swin2SRModel extends Swin2SRPreTrainedModel { }\n\n/**\n * Swin2SR Model transformer with an upsampler head on top for image super resolution and restoration.\n * \n * **Example:** Super-resolution w/ `Xenova/swin2SR-classical-sr-x2-64`.\n * \n * ```javascript\n * import { AutoProcessor, Swin2SRForImageSuperResolution, RawImage } from '@huggingface/transformers';\n * \n * // Load processor and model\n * const model_id = 'Xenova/swin2SR-classical-sr-x2-64';\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * const model = await Swin2SRForImageSuperResolution.from_pretrained(model_id);\n * \n * // Prepare model inputs\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg';\n * const image = await RawImage.fromURL(url);\n * const inputs = await processor(image);\n * \n * // Run model\n * const outputs = await model(inputs);\n * \n * // Convert Tensor to RawImage\n * const output = outputs.reconstruction.squeeze().clamp_(0, 1).mul_(255).round_().to('uint8');\n * const outputImage = RawImage.fromTensor(output);\n * // RawImage {\n * // data: Uint8Array(786432) [ 41, 31, 24, ... ],\n * // width: 512,\n * // height: 512,\n * // channels: 3\n * // }\n * ```\n */\nexport class Swin2SRForImageSuperResolution extends Swin2SRPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class DPTPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare DPT Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class DPTModel extends DPTPreTrainedModel { }\n\n/**\n * DPT Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2.\n * \n * **Example:** Depth estimation w/ `Xenova/dpt-hybrid-midas`.\n * ```javascript\n * import { DPTForDepthEstimation, AutoProcessor, RawImage, interpolate, max } from '@huggingface/transformers';\n * \n * // Load model and processor\n * const model_id = 'Xenova/dpt-hybrid-midas';\n * const model = await DPTForDepthEstimation.from_pretrained(model_id);\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * \n * // Load image from URL\n * const url = 'http://images.cocodataset.org/val2017/000000039769.jpg';\n * const image = await RawImage.fromURL(url);\n * \n * // Prepare image for the model\n * const inputs = await processor(image);\n * \n * // Run model\n * const { predicted_depth } = await model(inputs);\n * \n * // Interpolate to original size\n * const prediction = interpolate(predicted_depth, image.size.reverse(), 'bilinear', false);\n * \n * // Visualize the prediction\n * const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8');\n * const depth = RawImage.fromTensor(formatted);\n * // RawImage {\n * // data: Uint8Array(307200) [ 85, 85, 84, ... ],\n * // width: 640,\n * // height: 480,\n * // channels: 1\n * // }\n * ```\n */\nexport class DPTForDepthEstimation extends DPTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class DepthAnythingPreTrainedModel extends PreTrainedModel { }\n\n/**\n * Depth Anything Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2.\n */\nexport class DepthAnythingForDepthEstimation extends DepthAnythingPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class SapiensPreTrainedModel extends PreTrainedModel { }\nexport class SapiensForSemanticSegmentation extends SapiensPreTrainedModel { }\nexport class SapiensForDepthEstimation extends SapiensPreTrainedModel { }\nexport class SapiensForNormalEstimation extends SapiensPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class DepthProPreTrainedModel extends PreTrainedModel { }\nexport class DepthProForDepthEstimation extends DepthProPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class MaskFormerPreTrainedModel extends PreTrainedModel { }\nexport class MaskFormerModel extends MaskFormerPreTrainedModel { }\nexport class MaskFormerForInstanceSegmentation extends MaskFormerPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class GLPNPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare GLPN encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top.\n */\nexport class GLPNModel extends GLPNPreTrainedModel { }\n\n/**\n * GLPN Model transformer with a lightweight depth estimation head on top e.g. for KITTI, NYUv2.\n * \n * **Example:** Depth estimation w/ `Xenova/glpn-kitti`.\n * ```javascript\n * import { GLPNForDepthEstimation, AutoProcessor, RawImage, interpolate, max } from '@huggingface/transformers';\n * \n * // Load model and processor\n * const model_id = 'Xenova/glpn-kitti';\n * const model = await GLPNForDepthEstimation.from_pretrained(model_id);\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * \n * // Load image from URL\n * const url = 'http://images.cocodataset.org/val2017/000000039769.jpg';\n * const image = await RawImage.fromURL(url);\n * \n * // Prepare image for the model\n * const inputs = await processor(image);\n * \n * // Run model\n * const { predicted_depth } = await model(inputs);\n * \n * // Interpolate to original size\n * const prediction = interpolate(predicted_depth, image.size.reverse(), 'bilinear', false);\n * \n * // Visualize the prediction\n * const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8');\n * const depth = RawImage.fromTensor(formatted);\n * // RawImage {\n * // data: Uint8Array(307200) [ 207, 169, 154, ... ],\n * // width: 640,\n * // height: 480,\n * // channels: 1\n * // }\n * ```\n */\nexport class GLPNForDepthEstimation extends GLPNPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class DonutSwinPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Donut Swin Model transformer outputting raw hidden-states without any specific head on top.\n * \n * **Example:** Step-by-step Document Parsing.\n * \n * ```javascript\n * import { AutoProcessor, AutoTokenizer, AutoModelForVision2Seq, RawImage } from '@huggingface/transformers';\n * \n * // Choose model to use\n * const model_id = 'Xenova/donut-base-finetuned-cord-v2';\n * \n * // Prepare image inputs\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/receipt.png';\n * const image = await RawImage.read(url);\n * const image_inputs = await processor(image);\n * \n * // Prepare decoder inputs\n * const tokenizer = await AutoTokenizer.from_pretrained(model_id);\n * const task_prompt = '';\n * const decoder_input_ids = tokenizer(task_prompt, {\n * add_special_tokens: false,\n * }).input_ids;\n * \n * // Create the model\n * const model = await AutoModelForVision2Seq.from_pretrained(model_id);\n * \n * // Run inference\n * const output = await model.generate(image_inputs.pixel_values, {\n * decoder_input_ids,\n * max_length: model.config.decoder.max_position_embeddings,\n * });\n * \n * // Decode output\n * const decoded = tokenizer.batch_decode(output)[0];\n * // CINNAMON SUGAR 17,000 1 x 17,000 17,000 17,000 20,000 3,000\n * ```\n * \n * **Example:** Step-by-step Document Visual Question Answering (DocVQA)\n * \n * ```javascript\n * import { AutoProcessor, AutoTokenizer, AutoModelForVision2Seq, RawImage } from '@huggingface/transformers';\n * \n * // Choose model to use\n * const model_id = 'Xenova/donut-base-finetuned-docvqa';\n * \n * // Prepare image inputs\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/invoice.png';\n * const image = await RawImage.read(url);\n * const image_inputs = await processor(image);\n * \n * // Prepare decoder inputs\n * const tokenizer = await AutoTokenizer.from_pretrained(model_id);\n * const question = 'What is the invoice number?';\n * const task_prompt = `${question}`;\n * const decoder_input_ids = tokenizer(task_prompt, {\n * add_special_tokens: false,\n * }).input_ids;\n * \n * // Create the model\n * const model = await AutoModelForVision2Seq.from_pretrained(model_id);\n * \n * // Run inference\n * const output = await model.generate(image_inputs.pixel_values, {\n * decoder_input_ids,\n * max_length: model.config.decoder.max_position_embeddings,\n * });\n * \n * // Decode output\n * const decoded = tokenizer.batch_decode(output)[0];\n * // What is the invoice number? us-001\n * ```\n */\nexport class DonutSwinModel extends DonutSwinPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class ConvNextPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ConvNext model outputting raw features without any specific head on top.\n */\nexport class ConvNextModel extends ConvNextPreTrainedModel { }\n\n/**\n * ConvNext Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.\n */\nexport class ConvNextForImageClassification extends ConvNextPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class ConvNextV2PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ConvNextV2 model outputting raw features without any specific head on top.\n */\nexport class ConvNextV2Model extends ConvNextV2PreTrainedModel { }\n\n/**\n * ConvNextV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.\n */\nexport class ConvNextV2ForImageClassification extends ConvNextV2PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class Dinov2PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare DINOv2 Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class Dinov2Model extends Dinov2PreTrainedModel { }\n\n/**\n * Dinov2 Model transformer with an image classification head on top (a linear layer on top of the final hidden state of the [CLS] token) e.g. for ImageNet.\n */\nexport class Dinov2ForImageClassification extends Dinov2PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class YolosPreTrainedModel extends PreTrainedModel { }\nexport class YolosModel extends YolosPreTrainedModel { }\nexport class YolosForObjectDetection extends YolosPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new YolosObjectDetectionOutput(await super._call(model_inputs));\n }\n}\n\nexport class YolosObjectDetectionOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification logits (including no-object) for all queries.\n * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).\n * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).\n */\n constructor({ logits, pred_boxes }) {\n super();\n this.logits = logits;\n this.pred_boxes = pred_boxes;\n }\n}\n//////////////////////////////////////////////////\n\n\n\n\n//////////////////////////////////////////////////\nexport class SamPreTrainedModel extends PreTrainedModel { }\n\n/**\n * Segment Anything Model (SAM) for generating segmentation masks, given an input image\n * and optional 2D location and bounding boxes.\n * \n * **Example:** Perform mask generation w/ `Xenova/sam-vit-base`.\n * ```javascript\n * import { SamModel, AutoProcessor, RawImage } from '@huggingface/transformers';\n * \n * const model = await SamModel.from_pretrained('Xenova/sam-vit-base');\n * const processor = await AutoProcessor.from_pretrained('Xenova/sam-vit-base');\n * \n * const img_url = 'https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png';\n * const raw_image = await RawImage.read(img_url);\n * const input_points = [[[450, 600]]] // 2D localization of a window\n * \n * const inputs = await processor(raw_image, { input_points });\n * const outputs = await model(inputs);\n * \n * const masks = await processor.post_process_masks(outputs.pred_masks, inputs.original_sizes, inputs.reshaped_input_sizes);\n * // [\n * // Tensor {\n * // dims: [ 1, 3, 1764, 2646 ],\n * // type: 'bool',\n * // data: Uint8Array(14002632) [ ... ],\n * // size: 14002632\n * // }\n * // ]\n * const scores = outputs.iou_scores;\n * // Tensor {\n * // dims: [ 1, 1, 3 ],\n * // type: 'float32',\n * // data: Float32Array(3) [\n * // 0.8892380595207214,\n * // 0.9311248064041138,\n * // 0.983696699142456\n * // ],\n * // size: 3\n * // }\n * ```\n */\nexport class SamModel extends SamPreTrainedModel {\n\n /**\n * Compute image embeddings and positional image embeddings, given the pixel values of an image.\n * @param {Object} model_inputs Object containing the model inputs.\n * @param {Tensor} model_inputs.pixel_values Pixel values obtained using a `SamProcessor`.\n * @returns {Promise<{ image_embeddings: Tensor, image_positional_embeddings: Tensor }>} The image embeddings and positional image embeddings.\n */\n async get_image_embeddings({ pixel_values }) {\n // in:\n // - pixel_values: tensor.float32[batch_size,3,1024,1024]\n // \n // out:\n // - image_embeddings: tensor.float32[batch_size,256,64,64]\n // - image_positional_embeddings: tensor.float32[batch_size,256,64,64]\n return await encoderForward(this, { pixel_values })\n }\n\n /**\n * @typedef {Object} SamModelInputs Object containing the model inputs.\n * @property {Tensor} pixel_values Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`.\n * These can be obtained using a `SamProcessor`.\n * @property {Tensor} [input_points] Input 2D spatial points with shape `(batch_size, num_points, 2)`.\n * This is used by the prompt encoder to encode the prompt.\n * @property {Tensor} [input_labels] Input labels for the points, as a Tensor of shape `(batch_size, point_batch_size, num_points)`.\n * This is used by the prompt encoder to encode the prompt. There are 4 types of labels:\n * - `1`: the point is a point that contains the object of interest\n * - `0`: the point is a point that does not contain the object of interest\n * - `-1`: the point corresponds to the background\n * - `-10`: the point is a padding point, thus should be ignored by the prompt encoder\n * @property {Tensor} [input_boxes] Input bounding boxes with shape `(batch_size, num_boxes, 4)`.\n * @property {Tensor} [image_embeddings] Image embeddings used by the mask decoder.\n * @property {Tensor} [image_positional_embeddings] Image positional embeddings used by the mask decoder.\n */\n\n /**\n * @param {SamModelInputs} model_inputs Object containing the model inputs.\n * @returns {Promise} The output of the model.\n */\n async forward(model_inputs) {\n if (!model_inputs.image_embeddings || !model_inputs.image_positional_embeddings) {\n // Compute the image embeddings if they are missing\n model_inputs = {\n ...model_inputs,\n ...(await this.get_image_embeddings(model_inputs))\n }\n }\n\n if (!model_inputs.input_labels && model_inputs.input_points) {\n // Set default input labels if they are missing\n const shape = model_inputs.input_points.dims.slice(0, -1);\n const numElements = shape.reduce((a, b) => a * b, 1);\n model_inputs.input_labels = new Tensor(\n 'int64',\n new BigInt64Array(numElements).fill(1n),\n shape\n );\n }\n\n const decoder_inputs = {\n image_embeddings: model_inputs.image_embeddings,\n image_positional_embeddings: model_inputs.image_positional_embeddings,\n };\n if (model_inputs.input_points) {\n decoder_inputs.input_points = model_inputs.input_points;\n }\n if (model_inputs.input_labels) {\n decoder_inputs.input_labels = model_inputs.input_labels;\n }\n if (model_inputs.input_boxes) {\n decoder_inputs.input_boxes = model_inputs.input_boxes;\n }\n\n // Returns:\n // - iou_scores: tensor.float32[batch_size,point_batch_size,3]\n // - pred_masks: tensor.float32[batch_size,point_batch_size,3,256,256]\n return await sessionRun(this.sessions['prompt_encoder_mask_decoder'], decoder_inputs);\n }\n\n /**\n * Runs the model with the provided inputs\n * @param {Object} model_inputs Model inputs\n * @returns {Promise} Object containing segmentation outputs\n */\n async _call(model_inputs) {\n return new SamImageSegmentationOutput(await super._call(model_inputs));\n }\n}\n\n\n/**\n * Base class for Segment-Anything model's output.\n */\nexport class SamImageSegmentationOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.iou_scores The output logits of the model.\n * @param {Tensor} output.pred_masks Predicted boxes.\n */\n constructor({ iou_scores, pred_masks }) {\n super();\n this.iou_scores = iou_scores;\n this.pred_masks = pred_masks;\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// MarianMT models\nexport class MarianPreTrainedModel extends PreTrainedModel { };\n\nexport class MarianModel extends MarianPreTrainedModel { }\n\nexport class MarianMTModel extends MarianPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// M2M100 models\nexport class M2M100PreTrainedModel extends PreTrainedModel { };\n\nexport class M2M100Model extends M2M100PreTrainedModel { }\n\nexport class M2M100ForConditionalGeneration extends M2M100PreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Wav2Vec2 models\nexport class Wav2Vec2PreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare Wav2Vec2 Model transformer outputting raw hidden-states without any specific head on top.\n * \n * **Example:** Load and run a `Wav2Vec2Model` for feature extraction.\n * \n * ```javascript\n * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/mms-300m');\n * const audio = await read_audio('https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac', 16000);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const model = await AutoModel.from_pretrained('Xenova/mms-300m');\n * const output = await model(inputs);\n * // {\n * // last_hidden_state: Tensor {\n * // dims: [ 1, 1144, 1024 ],\n * // type: 'float32',\n * // data: Float32Array(1171456) [ ... ],\n * // size: 1171456\n * // }\n * // }\n * ```\n */\nexport class Wav2Vec2Model extends Wav2Vec2PreTrainedModel { }\n\nexport class Wav2Vec2ForCTC extends Wav2Vec2PreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\nexport class Wav2Vec2ForSequenceClassification extends Wav2Vec2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * Wav2Vec2 Model with a frame classification head on top for tasks like Speaker Diarization.\n */\nexport class Wav2Vec2ForAudioFrameClassification extends Wav2Vec2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// PyAnnote models\nexport class PyAnnotePreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare PyAnnote Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class PyAnnoteModel extends PyAnnotePreTrainedModel { }\n\n/**\n * PyAnnote Model with a frame classification head on top for tasks like Speaker Diarization.\n * \n * **Example:** Load and run a `PyAnnoteForAudioFrameClassification` for speaker diarization.\n * \n * ```javascript\n * import { AutoProcessor, AutoModelForAudioFrameClassification, read_audio } from '@huggingface/transformers';\n * \n * // Load model and processor\n * const model_id = 'onnx-community/pyannote-segmentation-3.0';\n * const model = await AutoModelForAudioFrameClassification.from_pretrained(model_id);\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * \n * // Read and preprocess audio\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/mlk.wav';\n * const audio = await read_audio(url, processor.feature_extractor.config.sampling_rate);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const { logits } = await model(inputs);\n * // {\n * // logits: Tensor {\n * // dims: [ 1, 767, 7 ], // [batch_size, num_frames, num_classes]\n * // type: 'float32',\n * // data: Float32Array(5369) [ ... ],\n * // size: 5369\n * // }\n * // }\n * \n * const result = processor.post_process_speaker_diarization(logits, audio.length);\n * // [\n * // [\n * // { id: 0, start: 0, end: 1.0512535626298245, confidence: 0.8220156481664611 },\n * // { id: 2, start: 1.0512535626298245, end: 2.3398869619825127, confidence: 0.9008811707860472 },\n * // ...\n * // ]\n * // ]\n * \n * // Display result\n * console.table(result[0], ['start', 'end', 'id', 'confidence']);\n * // ┌─────────┬────────────────────┬────────────────────┬────┬─────────────────────┐\n * // │ (index) │ start │ end │ id │ confidence │\n * // ├─────────┼────────────────────┼────────────────────┼────┼─────────────────────┤\n * // │ 0 │ 0 │ 1.0512535626298245 │ 0 │ 0.8220156481664611 │\n * // │ 1 │ 1.0512535626298245 │ 2.3398869619825127 │ 2 │ 0.9008811707860472 │\n * // │ 2 │ 2.3398869619825127 │ 3.5946089560890773 │ 0 │ 0.7521651315796233 │\n * // │ 3 │ 3.5946089560890773 │ 4.578039708226655 │ 2 │ 0.8491978128022479 │\n * // │ 4 │ 4.578039708226655 │ 4.594995410849717 │ 0 │ 0.2935352600416393 │\n * // │ 5 │ 4.594995410849717 │ 6.121008646925269 │ 3 │ 0.6788051309866024 │\n * // │ 6 │ 6.121008646925269 │ 6.256654267909762 │ 0 │ 0.37125512393851134 │\n * // │ 7 │ 6.256654267909762 │ 8.630452635138397 │ 2 │ 0.7467035186353542 │\n * // │ 8 │ 8.630452635138397 │ 10.088643060721703 │ 0 │ 0.7689364814666032 │\n * // │ 9 │ 10.088643060721703 │ 12.58113134631177 │ 2 │ 0.9123324509131324 │\n * // │ 10 │ 12.58113134631177 │ 13.005023911888312 │ 0 │ 0.4828358177572041 │\n * // └─────────┴────────────────────┴────────────────────┴────┴─────────────────────┘\n * ```\n */\nexport class PyAnnoteForAudioFrameClassification extends PyAnnotePreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// WeSpeakerResNet models\nexport class WeSpeakerResNetPreTrainedModel extends PreTrainedModel { };\nexport class WeSpeakerResNetModel extends WeSpeakerResNetPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// UniSpeech models\nexport class UniSpeechPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare UniSpeech Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class UniSpeechModel extends UniSpeechPreTrainedModel { }\n\n/**\n * UniSpeech Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class UniSpeechForCTC extends UniSpeechPreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * UniSpeech Model with a sequence classification head on top (a linear layer over the pooled output).\n */\nexport class UniSpeechForSequenceClassification extends UniSpeechPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// UniSpeechSat models\nexport class UniSpeechSatPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare UniSpeechSat Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class UniSpeechSatModel extends UniSpeechSatPreTrainedModel { }\n\n/**\n * UniSpeechSat Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class UniSpeechSatForCTC extends UniSpeechSatPreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * UniSpeechSat Model with a sequence classification head on top (a linear layer over the pooled output).\n */\nexport class UniSpeechSatForSequenceClassification extends UniSpeechSatPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * UniSpeechSat Model with a frame classification head on top for tasks like Speaker Diarization.\n */\nexport class UniSpeechSatForAudioFrameClassification extends UniSpeechSatPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Wav2Vec2Bert models\nexport class Wav2Vec2BertPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare Wav2Vec2Bert Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class Wav2Vec2BertModel extends Wav2Vec2BertPreTrainedModel { }\n\n/**\n * Wav2Vec2Bert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class Wav2Vec2BertForCTC extends Wav2Vec2BertPreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_features Float values of input mel-spectrogram.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * Wav2Vec2Bert Model with a sequence classification head on top (a linear layer over the pooled output).\n */\nexport class Wav2Vec2BertForSequenceClassification extends Wav2Vec2BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Hubert models\nexport class HubertPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Hubert Model transformer outputting raw hidden-states without any specific head on top.\n * \n * **Example:** Load and run a `HubertModel` for feature extraction.\n * \n * ```javascript\n * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/hubert-base-ls960');\n * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav', 16000);\n * const inputs = await processor(audio);\n * \n * // Load and run model with inputs\n * const model = await AutoModel.from_pretrained('Xenova/hubert-base-ls960');\n * const output = await model(inputs);\n * // {\n * // last_hidden_state: Tensor {\n * // dims: [ 1, 549, 768 ],\n * // type: 'float32',\n * // data: Float32Array(421632) [0.0682469978928566, 0.08104046434164047, -0.4975186586380005, ...],\n * // size: 421632\n * // }\n * // }\n * ```\n */\nexport class HubertModel extends Wav2Vec2PreTrainedModel { }\n\n/**\n * Hubert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class HubertForCTC extends Wav2Vec2PreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * Hubert Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like SUPERB Keyword Spotting.\n */\nexport class HubertForSequenceClassification extends Wav2Vec2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// WavLM models\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class WavLMPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare WavLM Model transformer outputting raw hidden-states without any specific head on top.\n * \n * **Example:** Load and run a `WavLMModel` for feature extraction.\n * \n * ```javascript\n * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base');\n * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav', 16000);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const model = await AutoModel.from_pretrained('Xenova/wavlm-base');\n * const output = await model(inputs);\n * // {\n * // last_hidden_state: Tensor {\n * // dims: [ 1, 549, 768 ],\n * // type: 'float32',\n * // data: Float32Array(421632) [-0.349443256855011, -0.39341306686401367, 0.022836603224277496, ...],\n * // size: 421632\n * // }\n * // }\n * ```\n */\nexport class WavLMModel extends WavLMPreTrainedModel { }\n\n/**\n * WavLM Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class WavLMForCTC extends WavLMPreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * WavLM Model with a sequence classification head on top (a linear layer over the pooled output).\n */\nexport class WavLMForSequenceClassification extends WavLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * WavLM Model with an XVector feature extraction head on top for tasks like Speaker Verification.\n * \n * **Example:** Extract speaker embeddings with `WavLMForXVector`.\n * ```javascript\n * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base-plus-sv');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const audio = await read_audio(url, 16000);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const model = await AutoModel.from_pretrained('Xenova/wavlm-base-plus-sv');\n * const outputs = await model(inputs);\n * // {\n * // logits: Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [0.5847219228744507, ...],\n * // size: 512\n * // },\n * // embeddings: Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [-0.09079201519489288, ...],\n * // size: 512\n * // }\n * // }\n * ```\n */\nexport class WavLMForXVector extends WavLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits and speaker embeddings.\n */\n async _call(model_inputs) {\n return new XVectorOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * WavLM Model with a frame classification head on top for tasks like Speaker Diarization.\n * \n * **Example:** Perform speaker diarization with `WavLMForAudioFrameClassification`.\n * ```javascript\n * import { AutoProcessor, AutoModelForAudioFrameClassification, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base-plus-sd');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const audio = await read_audio(url, 16000);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const model = await AutoModelForAudioFrameClassification.from_pretrained('Xenova/wavlm-base-plus-sd');\n * const { logits } = await model(inputs);\n * // {\n * // logits: Tensor {\n * // dims: [ 1, 549, 2 ], // [batch_size, num_frames, num_speakers]\n * // type: 'float32',\n * // data: Float32Array(1098) [-3.5301010608673096, ...],\n * // size: 1098\n * // }\n * // }\n * \n * const labels = logits[0].sigmoid().tolist().map(\n * frames => frames.map(speaker => speaker > 0.5 ? 1 : 0)\n * );\n * console.log(labels); // labels is a one-hot array of shape (num_frames, num_speakers)\n * // [\n * // [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],\n * // [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],\n * // [0, 0], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1],\n * // ...\n * // ]\n * ```\n */\nexport class WavLMForAudioFrameClassification extends WavLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n//////////////////////////////////////////////////\n// SpeechT5 models\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class SpeechT5PreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare SpeechT5 Encoder-Decoder Model outputting raw hidden-states without any specific pre- or post-nets.\n */\nexport class SpeechT5Model extends SpeechT5PreTrainedModel { };\n\n/**\n * SpeechT5 Model with a speech encoder and a text decoder.\n * \n * **Example:** Generate speech from text with `SpeechT5ForSpeechToText`.\n * ```javascript\n * import { AutoTokenizer, AutoProcessor, SpeechT5ForTextToSpeech, SpeechT5HifiGan, Tensor } from '@huggingface/transformers';\n * \n * // Load the tokenizer and processor\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/speecht5_tts');\n * const processor = await AutoProcessor.from_pretrained('Xenova/speecht5_tts');\n * \n * // Load the models\n * // NOTE: We use the full-precision versions as they are more accurate\n * const model = await SpeechT5ForTextToSpeech.from_pretrained('Xenova/speecht5_tts', { dtype: 'fp32' });\n * const vocoder = await SpeechT5HifiGan.from_pretrained('Xenova/speecht5_hifigan', { dtype: 'fp32' });\n * \n * // Load speaker embeddings from URL\n * const speaker_embeddings_data = new Float32Array(\n * await (await fetch('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin')).arrayBuffer()\n * );\n * const speaker_embeddings = new Tensor(\n * 'float32',\n * speaker_embeddings_data,\n * [1, speaker_embeddings_data.length]\n * )\n * \n * // Run tokenization\n * const { input_ids } = tokenizer('Hello, my dog is cute');\n * \n * // Generate waveform\n * const { waveform } = await model.generate_speech(input_ids, speaker_embeddings, { vocoder });\n * console.log(waveform)\n * // Tensor {\n * // dims: [ 26112 ],\n * // type: 'float32',\n * // size: 26112,\n * // data: Float32Array(26112) [ -0.00043630177970044315, -0.00018082228780258447, ... ],\n * // }\n * ```\n */\nexport class SpeechT5ForSpeechToText extends SpeechT5PreTrainedModel { }\n\n/**\n * SpeechT5 Model with a text encoder and a speech decoder.\n */\nexport class SpeechT5ForTextToSpeech extends SpeechT5PreTrainedModel {\n\n /**\n * @typedef {Object} SpeechOutput\n * @property {Tensor} [spectrogram] The predicted log-mel spectrogram of shape\n * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided\n * @property {Tensor} [waveform] The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided.\n * @property {Tensor} [cross_attentions] The outputs of the decoder's cross-attention layers of shape\n * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`.\n */\n\n /**\n * Converts a sequence of input tokens into a sequence of mel spectrograms, which are subsequently turned into a speech waveform using a vocoder.\n * @param {Tensor} input_values Indices of input sequence tokens in the vocabulary.\n * @param {Tensor} speaker_embeddings Tensor containing the speaker embeddings.\n * @param {Object} options Optional parameters for generating speech.\n * @param {number} [options.threshold=0.5] The generated sequence ends when the predicted stop token probability exceeds this value.\n * @param {number} [options.minlenratio=0.0] Used to calculate the minimum required length for the output sequence.\n * @param {number} [options.maxlenratio=20.0] Used to calculate the maximum allowed length for the output sequence.\n * @param {Object} [options.vocoder=null] The vocoder that converts the mel spectrogram into a speech waveform. If `null`, the output is the mel spectrogram.\n * @param {boolean} [options.output_cross_attentions=false] Whether or not to return the attentions tensors of the decoder's cross-attention layers.\n * @returns {Promise} A promise which resolves to an object containing the spectrogram, waveform, and cross-attention tensors.\n */\n async generate_speech(input_values, speaker_embeddings, {\n threshold = 0.5,\n minlenratio = 0.0,\n maxlenratio = 20.0,\n vocoder = null,\n // output_cross_attentions = false, // TODO add\n } = {}) {\n\n const model_inputs = {\n input_ids: input_values\n }\n\n const { encoder_outputs, encoder_attention_mask } = await encoderForward(this, model_inputs);\n\n const r = encoder_outputs.dims[1] / this.config.reduction_factor;\n const maxlen = Math.floor(r * maxlenratio);\n const minlen = Math.floor(r * minlenratio);\n\n const num_mel_bins = this.config.num_mel_bins;\n\n let spectrogramParts = [];\n let past_key_values = null;\n let decoder_outputs = null;\n let idx = 0;\n\n while (true) {\n ++idx;\n\n const use_cache_branch = boolTensor(!!decoder_outputs);\n let output_sequence;\n if (decoder_outputs) {\n output_sequence = decoder_outputs.output_sequence_out;\n } else {\n output_sequence = new Tensor(\n 'float32',\n new Float32Array(num_mel_bins),\n [1, 1, num_mel_bins],\n )\n }\n let decoderFeeds = {\n use_cache_branch,\n output_sequence,\n encoder_attention_mask: encoder_attention_mask,\n speaker_embeddings: speaker_embeddings,\n encoder_hidden_states: encoder_outputs,\n };\n\n this.addPastKeyValues(decoderFeeds, past_key_values);\n decoder_outputs = await sessionRun(this.sessions['decoder_model_merged'], decoderFeeds);\n past_key_values = this.getPastKeyValues(decoder_outputs, past_key_values);\n\n const { prob, spectrum } = decoder_outputs;\n spectrogramParts.push(spectrum);\n\n if (idx >= minlen && (\n // Finished when stop token or maximum length is reached.\n Array.from(prob.data).filter(p => p >= threshold).length > 0 || idx >= maxlen\n )) {\n break;\n }\n }\n\n const spectrogram = cat(spectrogramParts);\n const { waveform } = await sessionRun(vocoder.sessions['model'], { spectrogram });\n\n return {\n spectrogram,\n waveform,\n // cross_attentions: null, // TODO add\n }\n }\n}\n\n/**\n * HiFi-GAN vocoder.\n * \n * See [SpeechT5ForSpeechToText](./models#module_models.SpeechT5ForSpeechToText) for example usage.\n */\nexport class SpeechT5HifiGan extends PreTrainedModel {\n main_input_name = 'spectrogram';\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// TrOCR models\nexport class TrOCRPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The TrOCR Decoder with a language modeling head.\n */\nexport class TrOCRForCausalLM extends TrOCRPreTrainedModel { }\n\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Mistral models\n/**\n * The bare Mistral Model outputting raw hidden-states without any specific head on top.\n */\nexport class MistralPreTrainedModel extends PreTrainedModel { }\n\nexport class MistralModel extends MistralPreTrainedModel { }\n\nexport class MistralForCausalLM extends MistralPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Starcoder2 models\n/**\n * The bare Starcoder2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Starcoder2PreTrainedModel extends PreTrainedModel { }\n\nexport class Starcoder2Model extends Starcoder2PreTrainedModel { }\n\nexport class Starcoder2ForCausalLM extends Starcoder2PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Falcon models\n/**\n * The bare Falcon Model outputting raw hidden-states without any specific head on top.\n */\nexport class FalconPreTrainedModel extends PreTrainedModel { }\n\nexport class FalconModel extends FalconPreTrainedModel { }\n\nexport class FalconForCausalLM extends FalconPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// CLAP models\nexport class ClapPreTrainedModel extends PreTrainedModel { }\n\nexport class ClapModel extends ClapPreTrainedModel { }\n\n/**\n * CLAP Text Model with a projection layer on top (a linear layer on top of the pooled output).\n * \n * **Example:** Compute text embeddings with `ClapTextModelWithProjection`.\n * \n * ```javascript\n * import { AutoTokenizer, ClapTextModelWithProjection } from '@huggingface/transformers';\n * \n * // Load tokenizer and text model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clap-htsat-unfused');\n * const text_model = await ClapTextModelWithProjection.from_pretrained('Xenova/clap-htsat-unfused');\n * \n * // Run tokenization\n * const texts = ['a sound of a cat', 'a sound of a dog'];\n * const text_inputs = tokenizer(texts, { padding: true, truncation: true });\n * \n * // Compute embeddings\n * const { text_embeds } = await text_model(text_inputs);\n * // Tensor {\n * // dims: [ 2, 512 ],\n * // type: 'float32',\n * // data: Float32Array(1024) [ ... ],\n * // size: 1024\n * // }\n * ```\n */\nexport class ClapTextModelWithProjection extends ClapPreTrainedModel {\n\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'text_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * CLAP Audio Model with a projection layer on top (a linear layer on top of the pooled output).\n * \n * **Example:** Compute audio embeddings with `ClapAudioModelWithProjection`.\n * \n * ```javascript\n * import { AutoProcessor, ClapAudioModelWithProjection, read_audio } from '@huggingface/transformers';\n * \n * // Load processor and audio model\n * const processor = await AutoProcessor.from_pretrained('Xenova/clap-htsat-unfused');\n * const audio_model = await ClapAudioModelWithProjection.from_pretrained('Xenova/clap-htsat-unfused');\n * \n * // Read audio and run processor\n * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cat_meow.wav');\n * const audio_inputs = await processor(audio);\n * \n * // Compute embeddings\n * const { audio_embeds } = await audio_model(audio_inputs);\n * // Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [ ... ],\n * // size: 512\n * // }\n * ```\n */\nexport class ClapAudioModelWithProjection extends ClapPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'audio_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// VITS models\nexport class VitsPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The complete VITS model, for text-to-speech synthesis.\n * \n * **Example:** Generate speech from text with `VitsModel`.\n * ```javascript\n * import { AutoTokenizer, VitsModel } from '@huggingface/transformers';\n * \n * // Load the tokenizer and model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/mms-tts-eng');\n * const model = await VitsModel.from_pretrained('Xenova/mms-tts-eng');\n * \n * // Run tokenization\n * const inputs = tokenizer('I love transformers');\n * \n * // Generate waveform\n * const { waveform } = await model(inputs);\n * // Tensor {\n * // dims: [ 1, 35328 ],\n * // type: 'float32',\n * // data: Float32Array(35328) [ ... ],\n * // size: 35328,\n * // }\n * ```\n */\nexport class VitsModel extends VitsPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} The outputs for the VITS model.\n */\n async _call(model_inputs) {\n return new VitsModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Segformer models\nexport class SegformerPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare SegFormer encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top.\n */\nexport class SegformerModel extends SegformerPreTrainedModel { }\n\n/**\n * SegFormer Model transformer with an image classification head on top (a linear layer on top of the final hidden states) e.g. for ImageNet.\n */\nexport class SegformerForImageClassification extends SegformerPreTrainedModel { }\n\n/**\n * SegFormer Model transformer with an all-MLP decode head on top e.g. for ADE20k, CityScapes.\n */\nexport class SegformerForSemanticSegmentation extends SegformerPreTrainedModel { }\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// StableLm models\nexport class StableLmPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare StableLm Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class StableLmModel extends StableLmPreTrainedModel { }\n\n/**\n * StableLm Model with a `language modeling` head on top for Causal Language Modeling (with past).\n */\nexport class StableLmForCausalLM extends StableLmPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class EfficientNetPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare EfficientNet model outputting raw features without any specific head on top.\n */\nexport class EfficientNetModel extends EfficientNetPreTrainedModel { }\n\n/**\n * EfficientNet Model with an image classification head on top (a linear layer on top of the pooled features).\n */\nexport class EfficientNetForImageClassification extends EfficientNetPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Musicgen models\nexport class MusicgenPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Musicgen decoder model outputting raw hidden-states without any specific head on top.\n */\nexport class MusicgenModel extends MusicgenPreTrainedModel { }\n\n/**\n * The MusicGen decoder model with a language modelling head on top.\n */\nexport class MusicgenForCausalLM extends MusicgenPreTrainedModel { }\n\n/**\n * The composite MusicGen model with a text encoder, audio encoder and Musicgen decoder,\n * for music generation tasks with one or both of text and audio prompts.\n * \n * **Example:** Generate music from text with `Xenova/musicgen-small`.\n * ```javascript\n * import { AutoTokenizer, MusicgenForConditionalGeneration } from '@huggingface/transformers';\n * \n * // Load tokenizer and model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/musicgen-small');\n * const model = await MusicgenForConditionalGeneration.from_pretrained(\n * 'Xenova/musicgen-small', { dtype: 'fp32' }\n * );\n * \n * // Prepare text input\n * const prompt = '80s pop track with bassy drums and synth';\n * const inputs = tokenizer(prompt);\n * \n * // Generate audio\n * const audio_values = await model.generate({\n * ...inputs,\n * max_new_tokens: 512,\n * do_sample: true,\n * guidance_scale: 3,\n * });\n * \n * // (Optional) Write the output to a WAV file\n * import wavefile from 'wavefile';\n * import fs from 'fs';\n * \n * const wav = new wavefile.WaveFile();\n * wav.fromScratch(1, model.config.audio_encoder.sampling_rate, '32f', audio_values.data);\n * fs.writeFileSync('musicgen_out.wav', wav.toBuffer());\n * ```\n */\nexport class MusicgenForConditionalGeneration extends PreTrainedModel { // NOTE: not MusicgenPreTrainedModel\n forward_params = [\n 'input_ids',\n 'attention_mask',\n 'encoder_outputs',\n 'decoder_input_ids',\n 'decoder_attention_mask',\n 'past_key_values',\n ];\n\n /**\n * Apply the pattern mask to the final ids,\n * then revert the pattern delay mask by filtering the pad token id in a single step.\n * @param {Tensor} outputs The output tensor from the model.\n * @returns {Tensor} The filtered output tensor.\n */\n _apply_and_filter_by_delay_pattern_mask(outputs) {\n const [bs_x_codebooks, seqLength] = outputs.dims;\n const num_codebooks = this.config.decoder.num_codebooks;\n const upperBound = (seqLength - num_codebooks);\n\n let newDataSize = 0;\n for (let i = 0; i < outputs.size; ++i) {\n if (outputs.data[i] === this.config.decoder.pad_token_id) {\n continue;\n }\n\n const row = (i % seqLength);\n const col = Math.floor(i / seqLength) % num_codebooks;\n\n const diff = row - col;\n if (diff > 0 && diff <= upperBound) {\n outputs.data[newDataSize++] = outputs.data[i];\n }\n }\n\n const batch_size = Math.floor(bs_x_codebooks / num_codebooks);\n const inferred = newDataSize / (batch_size * num_codebooks);\n // TODO: assert `inferred` is an integer\n return new Tensor(\n outputs.type,\n outputs.data.slice(0, newDataSize),\n [batch_size, num_codebooks, inferred]\n );\n }\n\n\n prepare_inputs_for_generation(input_ids, model_inputs, generation_config) {\n // apply the delay pattern mask\n let clonedInputIds = structuredClone(input_ids);\n for (let i = 0; i < clonedInputIds.length; ++i) {\n for (let j = 0; j < clonedInputIds[i].length; ++j) {\n if ((i % this.config.decoder.num_codebooks) >= j) {\n clonedInputIds[i][j] = BigInt(this.config.decoder.pad_token_id);\n }\n }\n }\n // for classifier free guidance we need to replicate the decoder args across the batch dim\n // (we'll split these before sampling)\n if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) {\n // [batch, seqLength] -> [2 * batch, seqLength]\n clonedInputIds = clonedInputIds.concat(clonedInputIds);\n }\n\n const prepped = super.prepare_inputs_for_generation(clonedInputIds, model_inputs, generation_config);\n return prepped;\n }\n\n /**\n * Generates sequences of token ids for models with a language modeling head.\n * @param {import('./generation/parameters.js').GenerationFunctionParameters} options\n * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores.\n */\n async generate(options) {\n\n const output_ids = await super.generate(options);\n\n // apply the pattern mask to the final ids\n // tensor: int64[1,batch_size,4,chunk_length]\n const audio_codes = this._apply_and_filter_by_delay_pattern_mask(\n /** @type {Tensor} */(output_ids)\n ).unsqueeze_(0); // append the frame dimension back to the audio codes\n\n const { audio_values } = await sessionRun(this.sessions['encodec_decode'], { audio_codes })\n\n return audio_values;\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MobileNetV1 models\nexport class MobileNetV1PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.\n */\nexport class MobileNetV1Model extends MobileNetV1PreTrainedModel { }\n\n/**\n * MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features),\n * e.g. for ImageNet.\n */\nexport class MobileNetV1ForImageClassification extends MobileNetV1PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MobileNetV2 models\nexport class MobileNetV2PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MobileNetV2 model outputting raw hidden-states without any specific head on top.\n */\nexport class MobileNetV2Model extends MobileNetV2PreTrainedModel { }\n\n/**\n * MobileNetV2 model with an image classification head on top (a linear layer on top of the pooled features),\n * e.g. for ImageNet.\n */\nexport class MobileNetV2ForImageClassification extends MobileNetV2PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MobileNetV3 models\nexport class MobileNetV3PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MobileNetV3 model outputting raw hidden-states without any specific head on top.\n */\nexport class MobileNetV3Model extends MobileNetV3PreTrainedModel { }\n\n/**\n * MobileNetV3 model with an image classification head on top (a linear layer on top of the pooled features),\n * e.g. for ImageNet.\n */\nexport class MobileNetV3ForImageClassification extends MobileNetV3PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MobileNetV4 models\nexport class MobileNetV4PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MobileNetV4 model outputting raw hidden-states without any specific head on top.\n */\nexport class MobileNetV4Model extends MobileNetV4PreTrainedModel { }\n\n/**\n * MobileNetV4 model with an image classification head on top (a linear layer on top of the pooled features),\n * e.g. for ImageNet.\n */\nexport class MobileNetV4ForImageClassification extends MobileNetV4PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Decision Transformer models\nexport class DecisionTransformerPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The model builds upon the GPT2 architecture to perform autoregressive prediction of actions in an offline RL setting.\n * Refer to the paper for more details: https://arxiv.org/abs/2106.01345\n */\nexport class DecisionTransformerModel extends DecisionTransformerPreTrainedModel { }\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// AutoModels, used to simplify construction of PreTrainedModels\n// (uses config to instantiate correct class)\n\n/**\n * Base class of all AutoModels. Contains the `from_pretrained` function\n * which is used to instantiate pretrained models.\n */\nexport class PretrainedMixin {\n /**\n * Mapping from model type to model class.\n * @type {Map[]}\n */\n static MODEL_CLASS_MAPPINGS = null;\n\n /**\n * Whether to attempt to instantiate the base class (`PretrainedModel`) if \n * the model type is not found in the mapping.\n */\n static BASE_IF_FAIL = false;\n\n\n /** @type {typeof PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n model_file_name = null,\n subfolder = 'onnx',\n device = null,\n dtype = null,\n use_external_data_format = null,\n session_options = {},\n } = {}) {\n\n const options = {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n model_file_name,\n subfolder,\n device,\n dtype,\n use_external_data_format,\n session_options,\n }\n options.config = await AutoConfig.from_pretrained(pretrained_model_name_or_path, options);\n\n if (!this.MODEL_CLASS_MAPPINGS) {\n throw new Error(\"`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: \" + this.name);\n }\n\n for (const MODEL_CLASS_MAPPING of this.MODEL_CLASS_MAPPINGS) {\n const modelInfo = MODEL_CLASS_MAPPING.get(options.config.model_type);\n if (!modelInfo) {\n continue; // Item not found in this mapping\n }\n return await modelInfo[1].from_pretrained(pretrained_model_name_or_path, options);\n }\n\n if (this.BASE_IF_FAIL) {\n console.warn(`Unknown model class \"${options.config.model_type}\", attempting to construct from base class.`);\n return await PreTrainedModel.from_pretrained(pretrained_model_name_or_path, options);\n } else {\n throw Error(`Unsupported model type: ${options.config.model_type}`)\n }\n }\n}\n\nconst MODEL_MAPPING_NAMES_ENCODER_ONLY = new Map([\n ['bert', ['BertModel', BertModel]],\n ['nomic_bert', ['NomicBertModel', NomicBertModel]],\n ['roformer', ['RoFormerModel', RoFormerModel]],\n ['electra', ['ElectraModel', ElectraModel]],\n ['esm', ['EsmModel', EsmModel]],\n ['convbert', ['ConvBertModel', ConvBertModel]],\n ['camembert', ['CamembertModel', CamembertModel]],\n ['deberta', ['DebertaModel', DebertaModel]],\n ['deberta-v2', ['DebertaV2Model', DebertaV2Model]],\n ['mpnet', ['MPNetModel', MPNetModel]],\n ['albert', ['AlbertModel', AlbertModel]],\n ['distilbert', ['DistilBertModel', DistilBertModel]],\n ['roberta', ['RobertaModel', RobertaModel]],\n ['xlm', ['XLMModel', XLMModel]],\n ['xlm-roberta', ['XLMRobertaModel', XLMRobertaModel]],\n ['clap', ['ClapModel', ClapModel]],\n ['clip', ['CLIPModel', CLIPModel]],\n ['clipseg', ['CLIPSegModel', CLIPSegModel]],\n ['chinese_clip', ['ChineseCLIPModel', ChineseCLIPModel]],\n ['siglip', ['SiglipModel', SiglipModel]],\n ['mobilebert', ['MobileBertModel', MobileBertModel]],\n ['squeezebert', ['SqueezeBertModel', SqueezeBertModel]],\n ['wav2vec2', ['Wav2Vec2Model', Wav2Vec2Model]],\n ['wav2vec2-bert', ['Wav2Vec2BertModel', Wav2Vec2BertModel]],\n ['unispeech', ['UniSpeechModel', UniSpeechModel]],\n ['unispeech-sat', ['UniSpeechSatModel', UniSpeechSatModel]],\n ['hubert', ['HubertModel', HubertModel]],\n ['wavlm', ['WavLMModel', WavLMModel]],\n ['audio-spectrogram-transformer', ['ASTModel', ASTModel]],\n ['vits', ['VitsModel', VitsModel]],\n ['pyannote', ['PyAnnoteModel', PyAnnoteModel]],\n ['wespeaker-resnet', ['WeSpeakerResNetModel', WeSpeakerResNetModel]],\n\n ['detr', ['DetrModel', DetrModel]],\n ['rt_detr', ['RTDetrModel', RTDetrModel]],\n ['table-transformer', ['TableTransformerModel', TableTransformerModel]],\n ['vit', ['ViTModel', ViTModel]],\n ['pvt', ['PvtModel', PvtModel]],\n ['vit_msn', ['ViTMSNModel', ViTMSNModel]],\n ['vit_mae', ['ViTMAEModel', ViTMAEModel]],\n ['groupvit', ['GroupViTModel', GroupViTModel]],\n ['fastvit', ['FastViTModel', FastViTModel]],\n ['mobilevit', ['MobileViTModel', MobileViTModel]],\n ['mobilevitv2', ['MobileViTV2Model', MobileViTV2Model]],\n ['owlvit', ['OwlViTModel', OwlViTModel]],\n ['owlv2', ['Owlv2Model', Owlv2Model]],\n ['beit', ['BeitModel', BeitModel]],\n ['deit', ['DeiTModel', DeiTModel]],\n ['hiera', ['HieraModel', HieraModel]],\n ['convnext', ['ConvNextModel', ConvNextModel]],\n ['convnextv2', ['ConvNextV2Model', ConvNextV2Model]],\n ['dinov2', ['Dinov2Model', Dinov2Model]],\n ['resnet', ['ResNetModel', ResNetModel]],\n ['swin', ['SwinModel', SwinModel]],\n ['swin2sr', ['Swin2SRModel', Swin2SRModel]],\n ['donut-swin', ['DonutSwinModel', DonutSwinModel]],\n ['yolos', ['YolosModel', YolosModel]],\n ['dpt', ['DPTModel', DPTModel]],\n ['glpn', ['GLPNModel', GLPNModel]],\n\n ['hifigan', ['SpeechT5HifiGan', SpeechT5HifiGan]],\n ['efficientnet', ['EfficientNetModel', EfficientNetModel]],\n\n ['decision_transformer', ['DecisionTransformerModel', DecisionTransformerModel]],\n\n ['mobilenet_v1', ['MobileNetV1Model', MobileNetV1Model]],\n ['mobilenet_v2', ['MobileNetV2Model', MobileNetV2Model]],\n ['mobilenet_v3', ['MobileNetV3Model', MobileNetV3Model]],\n ['mobilenet_v4', ['MobileNetV4Model', MobileNetV4Model]],\n\n ['maskformer', ['MaskFormerModel', MaskFormerModel]],\n]);\n\nconst MODEL_MAPPING_NAMES_ENCODER_DECODER = new Map([\n ['t5', ['T5Model', T5Model]],\n ['longt5', ['LongT5Model', LongT5Model]],\n ['mt5', ['MT5Model', MT5Model]],\n ['bart', ['BartModel', BartModel]],\n ['mbart', ['MBartModel', MBartModel]],\n ['marian', ['MarianModel', MarianModel]],\n ['whisper', ['WhisperModel', WhisperModel]],\n ['m2m_100', ['M2M100Model', M2M100Model]],\n ['blenderbot', ['BlenderbotModel', BlenderbotModel]],\n ['blenderbot-small', ['BlenderbotSmallModel', BlenderbotSmallModel]],\n]);\n\n\nconst MODEL_MAPPING_NAMES_DECODER_ONLY = new Map([\n ['bloom', ['BloomModel', BloomModel]],\n ['jais', ['JAISModel', JAISModel]],\n ['gpt2', ['GPT2Model', GPT2Model]],\n ['gptj', ['GPTJModel', GPTJModel]],\n ['gpt_bigcode', ['GPTBigCodeModel', GPTBigCodeModel]],\n ['gpt_neo', ['GPTNeoModel', GPTNeoModel]],\n ['gpt_neox', ['GPTNeoXModel', GPTNeoXModel]],\n ['codegen', ['CodeGenModel', CodeGenModel]],\n ['llama', ['LlamaModel', LlamaModel]],\n ['granite', ['GraniteModel', GraniteModel]],\n ['cohere', ['CohereModel', CohereModel]],\n ['gemma', ['GemmaModel', GemmaModel]],\n ['gemma2', ['Gemma2Model', Gemma2Model]],\n ['openelm', ['OpenELMModel', OpenELMModel]],\n ['qwen2', ['Qwen2Model', Qwen2Model]],\n ['phi', ['PhiModel', PhiModel]],\n ['phi3', ['Phi3Model', Phi3Model]],\n ['mpt', ['MptModel', MptModel]],\n ['opt', ['OPTModel', OPTModel]],\n ['mistral', ['MistralModel', MistralModel]],\n ['starcoder2', ['Starcoder2Model', Starcoder2Model]],\n ['falcon', ['FalconModel', FalconModel]],\n ['stablelm', ['StableLmModel', StableLmModel]],\n]);\n\nconst MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = new Map([\n ['speecht5', ['SpeechT5ForSpeechToText', SpeechT5ForSpeechToText]],\n ['whisper', ['WhisperForConditionalGeneration', WhisperForConditionalGeneration]],\n]);\n\nconst MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES = new Map([\n ['speecht5', ['SpeechT5ForTextToSpeech', SpeechT5ForTextToSpeech]],\n]);\n\nconst MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES = new Map([\n ['vits', ['VitsModel', VitsModel]],\n ['musicgen', ['MusicgenForConditionalGeneration', MusicgenForConditionalGeneration]],\n]);\n\nconst MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['bert', ['BertForSequenceClassification', BertForSequenceClassification]],\n ['roformer', ['RoFormerForSequenceClassification', RoFormerForSequenceClassification]],\n ['electra', ['ElectraForSequenceClassification', ElectraForSequenceClassification]],\n ['esm', ['EsmForSequenceClassification', EsmForSequenceClassification]],\n ['convbert', ['ConvBertForSequenceClassification', ConvBertForSequenceClassification]],\n ['camembert', ['CamembertForSequenceClassification', CamembertForSequenceClassification]],\n ['deberta', ['DebertaForSequenceClassification', DebertaForSequenceClassification]],\n ['deberta-v2', ['DebertaV2ForSequenceClassification', DebertaV2ForSequenceClassification]],\n ['mpnet', ['MPNetForSequenceClassification', MPNetForSequenceClassification]],\n ['albert', ['AlbertForSequenceClassification', AlbertForSequenceClassification]],\n ['distilbert', ['DistilBertForSequenceClassification', DistilBertForSequenceClassification]],\n ['roberta', ['RobertaForSequenceClassification', RobertaForSequenceClassification]],\n ['xlm', ['XLMForSequenceClassification', XLMForSequenceClassification]],\n ['xlm-roberta', ['XLMRobertaForSequenceClassification', XLMRobertaForSequenceClassification]],\n ['bart', ['BartForSequenceClassification', BartForSequenceClassification]],\n ['mbart', ['MBartForSequenceClassification', MBartForSequenceClassification]],\n ['mobilebert', ['MobileBertForSequenceClassification', MobileBertForSequenceClassification]],\n ['squeezebert', ['SqueezeBertForSequenceClassification', SqueezeBertForSequenceClassification]],\n]);\n\nconst MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['bert', ['BertForTokenClassification', BertForTokenClassification]],\n ['roformer', ['RoFormerForTokenClassification', RoFormerForTokenClassification]],\n ['electra', ['ElectraForTokenClassification', ElectraForTokenClassification]],\n ['esm', ['EsmForTokenClassification', EsmForTokenClassification]],\n ['convbert', ['ConvBertForTokenClassification', ConvBertForTokenClassification]],\n ['camembert', ['CamembertForTokenClassification', CamembertForTokenClassification]],\n ['deberta', ['DebertaForTokenClassification', DebertaForTokenClassification]],\n ['deberta-v2', ['DebertaV2ForTokenClassification', DebertaV2ForTokenClassification]],\n ['mpnet', ['MPNetForTokenClassification', MPNetForTokenClassification]],\n ['distilbert', ['DistilBertForTokenClassification', DistilBertForTokenClassification]],\n ['roberta', ['RobertaForTokenClassification', RobertaForTokenClassification]],\n ['xlm', ['XLMForTokenClassification', XLMForTokenClassification]],\n ['xlm-roberta', ['XLMRobertaForTokenClassification', XLMRobertaForTokenClassification]],\n]);\n\nconst MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = new Map([\n ['t5', ['T5ForConditionalGeneration', T5ForConditionalGeneration]],\n ['longt5', ['LongT5ForConditionalGeneration', LongT5ForConditionalGeneration]],\n ['mt5', ['MT5ForConditionalGeneration', MT5ForConditionalGeneration]],\n ['bart', ['BartForConditionalGeneration', BartForConditionalGeneration]],\n ['mbart', ['MBartForConditionalGeneration', MBartForConditionalGeneration]],\n ['marian', ['MarianMTModel', MarianMTModel]],\n ['m2m_100', ['M2M100ForConditionalGeneration', M2M100ForConditionalGeneration]],\n ['blenderbot', ['BlenderbotForConditionalGeneration', BlenderbotForConditionalGeneration]],\n ['blenderbot-small', ['BlenderbotSmallForConditionalGeneration', BlenderbotSmallForConditionalGeneration]],\n]);\n\nconst MODEL_FOR_CAUSAL_LM_MAPPING_NAMES = new Map([\n ['bloom', ['BloomForCausalLM', BloomForCausalLM]],\n ['gpt2', ['GPT2LMHeadModel', GPT2LMHeadModel]],\n ['jais', ['JAISLMHeadModel', JAISLMHeadModel]],\n ['gptj', ['GPTJForCausalLM', GPTJForCausalLM]],\n ['gpt_bigcode', ['GPTBigCodeForCausalLM', GPTBigCodeForCausalLM]],\n ['gpt_neo', ['GPTNeoForCausalLM', GPTNeoForCausalLM]],\n ['gpt_neox', ['GPTNeoXForCausalLM', GPTNeoXForCausalLM]],\n ['codegen', ['CodeGenForCausalLM', CodeGenForCausalLM]],\n ['llama', ['LlamaForCausalLM', LlamaForCausalLM]],\n ['granite', ['GraniteForCausalLM', GraniteForCausalLM]],\n ['cohere', ['CohereForCausalLM', CohereForCausalLM]],\n ['gemma', ['GemmaForCausalLM', GemmaForCausalLM]],\n ['gemma2', ['Gemma2ForCausalLM', Gemma2ForCausalLM]],\n ['openelm', ['OpenELMForCausalLM', OpenELMForCausalLM]],\n ['qwen2', ['Qwen2ForCausalLM', Qwen2ForCausalLM]],\n ['phi', ['PhiForCausalLM', PhiForCausalLM]],\n ['phi3', ['Phi3ForCausalLM', Phi3ForCausalLM]],\n ['mpt', ['MptForCausalLM', MptForCausalLM]],\n ['opt', ['OPTForCausalLM', OPTForCausalLM]],\n ['mbart', ['MBartForCausalLM', MBartForCausalLM]],\n ['mistral', ['MistralForCausalLM', MistralForCausalLM]],\n ['starcoder2', ['Starcoder2ForCausalLM', Starcoder2ForCausalLM]],\n ['falcon', ['FalconForCausalLM', FalconForCausalLM]],\n ['trocr', ['TrOCRForCausalLM', TrOCRForCausalLM]],\n ['stablelm', ['StableLmForCausalLM', StableLmForCausalLM]],\n]);\n\nconst MODEL_FOR_MASKED_LM_MAPPING_NAMES = new Map([\n ['bert', ['BertForMaskedLM', BertForMaskedLM]],\n ['roformer', ['RoFormerForMaskedLM', RoFormerForMaskedLM]],\n ['electra', ['ElectraForMaskedLM', ElectraForMaskedLM]],\n ['esm', ['EsmForMaskedLM', EsmForMaskedLM]],\n ['convbert', ['ConvBertForMaskedLM', ConvBertForMaskedLM]],\n ['camembert', ['CamembertForMaskedLM', CamembertForMaskedLM]],\n ['deberta', ['DebertaForMaskedLM', DebertaForMaskedLM]],\n ['deberta-v2', ['DebertaV2ForMaskedLM', DebertaV2ForMaskedLM]],\n ['mpnet', ['MPNetForMaskedLM', MPNetForMaskedLM]],\n ['albert', ['AlbertForMaskedLM', AlbertForMaskedLM]],\n ['distilbert', ['DistilBertForMaskedLM', DistilBertForMaskedLM]],\n ['roberta', ['RobertaForMaskedLM', RobertaForMaskedLM]],\n ['xlm', ['XLMWithLMHeadModel', XLMWithLMHeadModel]],\n ['xlm-roberta', ['XLMRobertaForMaskedLM', XLMRobertaForMaskedLM]],\n ['mobilebert', ['MobileBertForMaskedLM', MobileBertForMaskedLM]],\n ['squeezebert', ['SqueezeBertForMaskedLM', SqueezeBertForMaskedLM]],\n]);\n\nconst MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = new Map([\n ['bert', ['BertForQuestionAnswering', BertForQuestionAnswering]],\n ['roformer', ['RoFormerForQuestionAnswering', RoFormerForQuestionAnswering]],\n ['electra', ['ElectraForQuestionAnswering', ElectraForQuestionAnswering]],\n ['convbert', ['ConvBertForQuestionAnswering', ConvBertForQuestionAnswering]],\n ['camembert', ['CamembertForQuestionAnswering', CamembertForQuestionAnswering]],\n ['deberta', ['DebertaForQuestionAnswering', DebertaForQuestionAnswering]],\n ['deberta-v2', ['DebertaV2ForQuestionAnswering', DebertaV2ForQuestionAnswering]],\n ['mpnet', ['MPNetForQuestionAnswering', MPNetForQuestionAnswering]],\n ['albert', ['AlbertForQuestionAnswering', AlbertForQuestionAnswering]],\n ['distilbert', ['DistilBertForQuestionAnswering', DistilBertForQuestionAnswering]],\n ['roberta', ['RobertaForQuestionAnswering', RobertaForQuestionAnswering]],\n ['xlm', ['XLMForQuestionAnswering', XLMForQuestionAnswering]],\n ['xlm-roberta', ['XLMRobertaForQuestionAnswering', XLMRobertaForQuestionAnswering]],\n ['mobilebert', ['MobileBertForQuestionAnswering', MobileBertForQuestionAnswering]],\n ['squeezebert', ['SqueezeBertForQuestionAnswering', SqueezeBertForQuestionAnswering]],\n]);\n\nconst MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = new Map([\n ['vision-encoder-decoder', ['VisionEncoderDecoderModel', VisionEncoderDecoderModel]],\n]);\n\nconst MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES = new Map([\n ['llava', ['LlavaForConditionalGeneration', LlavaForConditionalGeneration]],\n ['moondream1', ['Moondream1ForConditionalGeneration', Moondream1ForConditionalGeneration]],\n ['florence2', ['Florence2ForConditionalGeneration', Florence2ForConditionalGeneration]],\n]);\n\nconst MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES = new Map([\n ['vision-encoder-decoder', ['VisionEncoderDecoderModel', VisionEncoderDecoderModel]],\n]);\n\nconst MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['vit', ['ViTForImageClassification', ViTForImageClassification]],\n ['pvt', ['PvtForImageClassification', PvtForImageClassification]],\n ['vit_msn', ['ViTMSNForImageClassification', ViTMSNForImageClassification]],\n ['fastvit', ['FastViTForImageClassification', FastViTForImageClassification]],\n ['mobilevit', ['MobileViTForImageClassification', MobileViTForImageClassification]],\n ['mobilevitv2', ['MobileViTV2ForImageClassification', MobileViTV2ForImageClassification]],\n ['beit', ['BeitForImageClassification', BeitForImageClassification]],\n ['deit', ['DeiTForImageClassification', DeiTForImageClassification]],\n ['hiera', ['HieraForImageClassification', HieraForImageClassification]],\n ['convnext', ['ConvNextForImageClassification', ConvNextForImageClassification]],\n ['convnextv2', ['ConvNextV2ForImageClassification', ConvNextV2ForImageClassification]],\n ['dinov2', ['Dinov2ForImageClassification', Dinov2ForImageClassification]],\n ['resnet', ['ResNetForImageClassification', ResNetForImageClassification]],\n ['swin', ['SwinForImageClassification', SwinForImageClassification]],\n ['segformer', ['SegformerForImageClassification', SegformerForImageClassification]],\n ['efficientnet', ['EfficientNetForImageClassification', EfficientNetForImageClassification]],\n ['mobilenet_v1', ['MobileNetV1ForImageClassification', MobileNetV1ForImageClassification]],\n ['mobilenet_v2', ['MobileNetV2ForImageClassification', MobileNetV2ForImageClassification]],\n ['mobilenet_v3', ['MobileNetV3ForImageClassification', MobileNetV3ForImageClassification]],\n ['mobilenet_v4', ['MobileNetV4ForImageClassification', MobileNetV4ForImageClassification]],\n]);\n\nconst MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = new Map([\n ['detr', ['DetrForObjectDetection', DetrForObjectDetection]],\n ['rt_detr', ['RTDetrForObjectDetection', RTDetrForObjectDetection]],\n ['table-transformer', ['TableTransformerForObjectDetection', TableTransformerForObjectDetection]],\n ['yolos', ['YolosForObjectDetection', YolosForObjectDetection]],\n]);\n\nconst MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = new Map([\n ['owlvit', ['OwlViTForObjectDetection', OwlViTForObjectDetection]],\n ['owlv2', ['Owlv2ForObjectDetection', Owlv2ForObjectDetection]],\n]);\n\nconst MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = new Map([\n // TODO: Do not add new models here\n ['detr', ['DetrForSegmentation', DetrForSegmentation]],\n ['clipseg', ['CLIPSegForImageSegmentation', CLIPSegForImageSegmentation]],\n]);\n\nconst MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = new Map([\n ['segformer', ['SegformerForSemanticSegmentation', SegformerForSemanticSegmentation]],\n ['sapiens', ['SapiensForSemanticSegmentation', SapiensForSemanticSegmentation]],\n]);\n\nconst MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES = new Map([\n ['detr', ['DetrForSegmentation', DetrForSegmentation]],\n ['maskformer', ['MaskFormerForInstanceSegmentation', MaskFormerForInstanceSegmentation]],\n]);\n\nconst MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = new Map([\n ['sam', ['SamModel', SamModel]],\n]);\n\nconst MODEL_FOR_CTC_MAPPING_NAMES = new Map([\n ['wav2vec2', ['Wav2Vec2ForCTC', Wav2Vec2ForCTC]],\n ['wav2vec2-bert', ['Wav2Vec2BertForCTC', Wav2Vec2BertForCTC]],\n ['unispeech', ['UniSpeechForCTC', UniSpeechForCTC]],\n ['unispeech-sat', ['UniSpeechSatForCTC', UniSpeechSatForCTC]],\n ['wavlm', ['WavLMForCTC', WavLMForCTC]],\n ['hubert', ['HubertForCTC', HubertForCTC]],\n]);\n\nconst MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['wav2vec2', ['Wav2Vec2ForSequenceClassification', Wav2Vec2ForSequenceClassification]],\n ['wav2vec2-bert', ['Wav2Vec2BertForSequenceClassification', Wav2Vec2BertForSequenceClassification]],\n ['unispeech', ['UniSpeechForSequenceClassification', UniSpeechForSequenceClassification]],\n ['unispeech-sat', ['UniSpeechSatForSequenceClassification', UniSpeechSatForSequenceClassification]],\n ['wavlm', ['WavLMForSequenceClassification', WavLMForSequenceClassification]],\n ['hubert', ['HubertForSequenceClassification', HubertForSequenceClassification]],\n ['audio-spectrogram-transformer', ['ASTForAudioClassification', ASTForAudioClassification]],\n]);\n\nconst MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES = new Map([\n ['wavlm', ['WavLMForXVector', WavLMForXVector]],\n]);\n\nconst MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['unispeech-sat', ['UniSpeechSatForAudioFrameClassification', UniSpeechSatForAudioFrameClassification]],\n ['wavlm', ['WavLMForAudioFrameClassification', WavLMForAudioFrameClassification]],\n ['wav2vec2', ['Wav2Vec2ForAudioFrameClassification', Wav2Vec2ForAudioFrameClassification]],\n ['pyannote', ['PyAnnoteForAudioFrameClassification', PyAnnoteForAudioFrameClassification]],\n]);\n\nconst MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES = new Map([\n ['vitmatte', ['VitMatteForImageMatting', VitMatteForImageMatting]],\n]);\n\nconst MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES = new Map([\n ['swin2sr', ['Swin2SRForImageSuperResolution', Swin2SRForImageSuperResolution]],\n])\n\nconst MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = new Map([\n ['dpt', ['DPTForDepthEstimation', DPTForDepthEstimation]],\n ['depth_anything', ['DepthAnythingForDepthEstimation', DepthAnythingForDepthEstimation]],\n ['glpn', ['GLPNForDepthEstimation', GLPNForDepthEstimation]],\n ['sapiens', ['SapiensForDepthEstimation', SapiensForDepthEstimation]],\n ['depth_pro', ['DepthProForDepthEstimation', DepthProForDepthEstimation]],\n])\n\nconst MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES = new Map([\n ['sapiens', ['SapiensForNormalEstimation', SapiensForNormalEstimation]],\n])\n\n// NOTE: This is custom to Transformers.js, and is necessary because certain models\n// (e.g., CLIP) are split into vision and text components\nconst MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES = new Map([\n ['clip', ['CLIPVisionModelWithProjection', CLIPVisionModelWithProjection]],\n ['siglip', ['SiglipVisionModel', SiglipVisionModel]],\n])\n\nconst MODEL_CLASS_TYPE_MAPPING = [\n [MODEL_MAPPING_NAMES_ENCODER_ONLY, MODEL_TYPES.EncoderOnly],\n [MODEL_MAPPING_NAMES_ENCODER_DECODER, MODEL_TYPES.EncoderDecoder],\n [MODEL_MAPPING_NAMES_DECODER_ONLY, MODEL_TYPES.DecoderOnly],\n [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],\n [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],\n [MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.DecoderOnly],\n [MODEL_FOR_MASKED_LM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Vision2Seq],\n [MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES, MODEL_TYPES.ImageTextToText],\n [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES, MODEL_TYPES.MaskGeneration],\n [MODEL_FOR_CTC_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],\n [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n\n // Custom:\n [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n];\n\nfor (const [mappings, type] of MODEL_CLASS_TYPE_MAPPING) {\n // @ts-ignore\n for (const [name, model] of mappings.values()) {\n MODEL_TYPE_MAPPING.set(name, type);\n MODEL_CLASS_TO_NAME_MAPPING.set(model, name);\n MODEL_NAME_TO_CLASS_MAPPING.set(name, model);\n }\n}\n\nconst CUSTOM_MAPPING = [\n // OVERRIDE:\n // TODO: Refactor to allow class to specify model\n ['MusicgenForConditionalGeneration', MusicgenForConditionalGeneration, MODEL_TYPES.Musicgen],\n\n ['CLIPTextModelWithProjection', CLIPTextModelWithProjection, MODEL_TYPES.EncoderOnly],\n ['SiglipTextModel', SiglipTextModel, MODEL_TYPES.EncoderOnly],\n ['ClapTextModelWithProjection', ClapTextModelWithProjection, MODEL_TYPES.EncoderOnly],\n ['ClapAudioModelWithProjection', ClapAudioModelWithProjection, MODEL_TYPES.EncoderOnly],\n]\nfor (const [name, model, type] of CUSTOM_MAPPING) {\n MODEL_TYPE_MAPPING.set(name, type);\n MODEL_CLASS_TO_NAME_MAPPING.set(model, name);\n MODEL_NAME_TO_CLASS_MAPPING.set(name, model);\n}\n\n\n/**\n * Helper class which is used to instantiate pretrained models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModel.from_pretrained('Xenova/bert-base-uncased');\n */\nexport class AutoModel extends PretrainedMixin {\n /** @type {Map[]} */\n // @ts-ignore\n static MODEL_CLASS_MAPPINGS = MODEL_CLASS_TYPE_MAPPING.map(x => x[0]);\n static BASE_IF_FAIL = true;\n}\n\n/**\n * Helper class which is used to instantiate pretrained sequence classification models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForSequenceClassification.from_pretrained('Xenova/distilbert-base-uncased-finetuned-sst-2-english');\n */\nexport class AutoModelForSequenceClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained token classification models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForTokenClassification.from_pretrained('Xenova/distilbert-base-multilingual-cased-ner-hrl');\n */\nexport class AutoModelForTokenClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained sequence-to-sequence models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForSeq2SeqLM.from_pretrained('Xenova/t5-small');\n */\nexport class AutoModelForSeq2SeqLM extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained sequence-to-sequence speech-to-text models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForSpeechSeq2Seq.from_pretrained('openai/whisper-tiny.en');\n */\nexport class AutoModelForSpeechSeq2Seq extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained sequence-to-sequence text-to-spectrogram models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForTextToSpectrogram.from_pretrained('microsoft/speecht5_tts');\n */\nexport class AutoModelForTextToSpectrogram extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained text-to-waveform models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForTextToSpectrogram.from_pretrained('facebook/mms-tts-eng');\n */\nexport class AutoModelForTextToWaveform extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained causal language models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForCausalLM.from_pretrained('Xenova/gpt2');\n */\nexport class AutoModelForCausalLM extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_CAUSAL_LM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained masked language models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForMaskedLM.from_pretrained('Xenova/bert-base-uncased');\n */\nexport class AutoModelForMaskedLM extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_MASKED_LM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained question answering models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForQuestionAnswering.from_pretrained('Xenova/distilbert-base-cased-distilled-squad');\n */\nexport class AutoModelForQuestionAnswering extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained vision-to-sequence models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForVision2Seq.from_pretrained('Xenova/vit-gpt2-image-captioning');\n */\nexport class AutoModelForVision2Seq extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained image classification models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForImageClassification.from_pretrained('Xenova/vit-base-patch16-224');\n */\nexport class AutoModelForImageClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained image segmentation models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForImageSegmentation.from_pretrained('Xenova/detr-resnet-50-panoptic');\n */\nexport class AutoModelForImageSegmentation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained image segmentation models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForSemanticSegmentation.from_pretrained('nvidia/segformer-b3-finetuned-cityscapes-1024-1024');\n */\nexport class AutoModelForSemanticSegmentation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained universal image segmentation models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForUniversalSegmentation.from_pretrained('hf-internal-testing/tiny-random-MaskFormerForInstanceSegmentation');\n */\nexport class AutoModelForUniversalSegmentation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained object detection models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForObjectDetection.from_pretrained('Xenova/detr-resnet-50');\n */\nexport class AutoModelForObjectDetection extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES];\n}\n\nexport class AutoModelForZeroShotObjectDetection extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES];\n}\n\n\n/**\n * Helper class which is used to instantiate pretrained mask generation models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForMaskGeneration.from_pretrained('Xenova/sam-vit-base');\n */\nexport class AutoModelForMaskGeneration extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForCTC extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_CTC_MAPPING_NAMES];\n}\n\nexport class AutoModelForAudioClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForXVector extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES];\n}\n\nexport class AutoModelForAudioFrameClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForDocumentQuestionAnswering extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES];\n}\n\nexport class AutoModelForImageMatting extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES];\n}\n\nexport class AutoModelForImageToImage extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES];\n}\n\nexport class AutoModelForDepthEstimation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForNormalEstimation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForImageFeatureExtraction extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES];\n}\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class Seq2SeqLMOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits The output logits of the model.\n * @param {Tensor} output.past_key_values An tensor of key/value pairs that represent the previous state of the model.\n * @param {Tensor} output.encoder_outputs The output of the encoder in a sequence-to-sequence model.\n * @param {Tensor} [output.decoder_attentions] Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.\n * @param {Tensor} [output.cross_attentions] Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.\n */\n constructor({ logits, past_key_values, encoder_outputs, decoder_attentions = null, cross_attentions = null }) {\n super();\n this.logits = logits;\n this.past_key_values = past_key_values;\n this.encoder_outputs = encoder_outputs;\n this.decoder_attentions = decoder_attentions;\n this.cross_attentions = cross_attentions;\n }\n}\n\n/**\n * Base class for outputs of sentence classification models.\n */\nexport class SequenceClassifierOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits classification (or regression if config.num_labels==1) scores (before SoftMax).\n */\n constructor({ logits }) {\n super();\n this.logits = logits;\n }\n}\n\n/**\n * Base class for outputs of XVector models.\n */\nexport class XVectorOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification hidden states before AMSoftmax, of shape `(batch_size, config.xvector_output_dim)`.\n * @param {Tensor} output.embeddings Utterance embeddings used for vector similarity-based retrieval, of shape `(batch_size, config.xvector_output_dim)`.\n */\n constructor({ logits, embeddings }) {\n super();\n this.logits = logits;\n this.embeddings = embeddings;\n }\n}\n\n/**\n * Base class for outputs of token classification models.\n */\nexport class TokenClassifierOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification scores (before SoftMax).\n */\n constructor({ logits }) {\n super();\n this.logits = logits;\n }\n}\n\n/**\n * Base class for masked language models outputs.\n */\nexport class MaskedLMOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).\n */\n constructor({ logits }) {\n super();\n this.logits = logits;\n }\n}\n\n/**\n * Base class for outputs of question answering models.\n */\nexport class QuestionAnsweringModelOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.start_logits Span-start scores (before SoftMax).\n * @param {Tensor} output.end_logits Span-end scores (before SoftMax).\n */\n constructor({ start_logits, end_logits }) {\n super();\n this.start_logits = start_logits;\n this.end_logits = end_logits;\n }\n}\n\n\n/**\n * Base class for causal language model (or autoregressive) outputs.\n */\nexport class CausalLMOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax).\n */\n constructor({ logits }) {\n super();\n this.logits = logits;\n }\n}\n\n/**\n * Base class for causal language model (or autoregressive) outputs.\n */\nexport class CausalLMOutputWithPast extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax).\n * @param {Tensor} output.past_key_values Contains pre-computed hidden-states (key and values in the self-attention blocks)\n * that can be used (see `past_key_values` input) to speed up sequential decoding.\n */\n constructor({ logits, past_key_values }) {\n super();\n this.logits = logits;\n this.past_key_values = past_key_values;\n }\n}\n\nexport class ImageMattingOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.alphas Estimated alpha values, of shape `(batch_size, num_channels, height, width)`.\n */\n constructor({ alphas }) {\n super();\n this.alphas = alphas;\n }\n}\n\n/**\n * Describes the outputs for the VITS model.\n */\nexport class VitsModelOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.waveform The final audio waveform predicted by the model, of shape `(batch_size, sequence_length)`.\n * @param {Tensor} output.spectrogram The log-mel spectrogram predicted at the output of the flow model.\n * This spectrogram is passed to the Hi-Fi GAN decoder model to obtain the final audio waveform.\n */\n constructor({ waveform, spectrogram }) {\n super();\n this.waveform = waveform;\n this.spectrogram = spectrogram;\n }\n}\n","\n\nconst WHISPER_LANGUAGES = [\n [\"en\", \"english\"],\n [\"zh\", \"chinese\"],\n [\"de\", \"german\"],\n [\"es\", \"spanish\"],\n [\"ru\", \"russian\"],\n [\"ko\", \"korean\"],\n [\"fr\", \"french\"],\n [\"ja\", \"japanese\"],\n [\"pt\", \"portuguese\"],\n [\"tr\", \"turkish\"],\n [\"pl\", \"polish\"],\n [\"ca\", \"catalan\"],\n [\"nl\", \"dutch\"],\n [\"ar\", \"arabic\"],\n [\"sv\", \"swedish\"],\n [\"it\", \"italian\"],\n [\"id\", \"indonesian\"],\n [\"hi\", \"hindi\"],\n [\"fi\", \"finnish\"],\n [\"vi\", \"vietnamese\"],\n [\"he\", \"hebrew\"],\n [\"uk\", \"ukrainian\"],\n [\"el\", \"greek\"],\n [\"ms\", \"malay\"],\n [\"cs\", \"czech\"],\n [\"ro\", \"romanian\"],\n [\"da\", \"danish\"],\n [\"hu\", \"hungarian\"],\n [\"ta\", \"tamil\"],\n [\"no\", \"norwegian\"],\n [\"th\", \"thai\"],\n [\"ur\", \"urdu\"],\n [\"hr\", \"croatian\"],\n [\"bg\", \"bulgarian\"],\n [\"lt\", \"lithuanian\"],\n [\"la\", \"latin\"],\n [\"mi\", \"maori\"],\n [\"ml\", \"malayalam\"],\n [\"cy\", \"welsh\"],\n [\"sk\", \"slovak\"],\n [\"te\", \"telugu\"],\n [\"fa\", \"persian\"],\n [\"lv\", \"latvian\"],\n [\"bn\", \"bengali\"],\n [\"sr\", \"serbian\"],\n [\"az\", \"azerbaijani\"],\n [\"sl\", \"slovenian\"],\n [\"kn\", \"kannada\"],\n [\"et\", \"estonian\"],\n [\"mk\", \"macedonian\"],\n [\"br\", \"breton\"],\n [\"eu\", \"basque\"],\n [\"is\", \"icelandic\"],\n [\"hy\", \"armenian\"],\n [\"ne\", \"nepali\"],\n [\"mn\", \"mongolian\"],\n [\"bs\", \"bosnian\"],\n [\"kk\", \"kazakh\"],\n [\"sq\", \"albanian\"],\n [\"sw\", \"swahili\"],\n [\"gl\", \"galician\"],\n [\"mr\", \"marathi\"],\n [\"pa\", \"punjabi\"],\n [\"si\", \"sinhala\"],\n [\"km\", \"khmer\"],\n [\"sn\", \"shona\"],\n [\"yo\", \"yoruba\"],\n [\"so\", \"somali\"],\n [\"af\", \"afrikaans\"],\n [\"oc\", \"occitan\"],\n [\"ka\", \"georgian\"],\n [\"be\", \"belarusian\"],\n [\"tg\", \"tajik\"],\n [\"sd\", \"sindhi\"],\n [\"gu\", \"gujarati\"],\n [\"am\", \"amharic\"],\n [\"yi\", \"yiddish\"],\n [\"lo\", \"lao\"],\n [\"uz\", \"uzbek\"],\n [\"fo\", \"faroese\"],\n [\"ht\", \"haitian creole\"],\n [\"ps\", \"pashto\"],\n [\"tk\", \"turkmen\"],\n [\"nn\", \"nynorsk\"],\n [\"mt\", \"maltese\"],\n [\"sa\", \"sanskrit\"],\n [\"lb\", \"luxembourgish\"],\n [\"my\", \"myanmar\"],\n [\"bo\", \"tibetan\"],\n [\"tl\", \"tagalog\"],\n [\"mg\", \"malagasy\"],\n [\"as\", \"assamese\"],\n [\"tt\", \"tatar\"],\n [\"haw\", \"hawaiian\"],\n [\"ln\", \"lingala\"],\n [\"ha\", \"hausa\"],\n [\"ba\", \"bashkir\"],\n [\"jw\", \"javanese\"],\n [\"su\", \"sundanese\"],\n]\n\n// @ts-ignore\nexport const WHISPER_LANGUAGE_MAPPING = new Map(WHISPER_LANGUAGES);\n// @ts-ignore\nexport const WHISPER_TO_LANGUAGE_CODE_MAPPING = new Map([\n ...WHISPER_LANGUAGES.map(([k, v]) => [v, k]),\n ...[\n [\"burmese\", \"my\"],\n [\"valencian\", \"ca\"],\n [\"flemish\", \"nl\"],\n [\"haitian\", \"ht\"],\n [\"letzeburgesch\", \"lb\"],\n [\"pushto\", \"ps\"],\n [\"panjabi\", \"pa\"],\n [\"moldavian\", \"ro\"],\n [\"moldovan\", \"ro\"],\n [\"sinhalese\", \"si\"],\n [\"castilian\", \"es\"],\n ]\n]);\n\n/**\n * @param {string} language The language name or code\n * @returns {string} The language code\n */\nexport function whisper_language_to_code(language) {\n language = language.toLowerCase();\n\n // Map to code from user-friendly name (e.g., \"english\" -> \"en\")\n let language_code = WHISPER_TO_LANGUAGE_CODE_MAPPING.get(language);\n\n if (language_code === undefined) {\n // User provided something that is not a language name\n\n if (WHISPER_LANGUAGE_MAPPING.has(language)) {\n // User provided the language code directly (e.g., \"en\")\n language_code = language;\n\n } else {\n // User provided something that is not a language code or name\n const is_language_code = language.length === 2;\n const langs = is_language_code ? WHISPER_LANGUAGE_MAPPING.keys() : WHISPER_LANGUAGE_MAPPING.values();\n\n throw new Error(`Language \"${language}\" is not supported. Must be one of: ${JSON.stringify(langs)}`);\n }\n }\n return language_code;\n}\n","import { GenerationConfig } from \"../../generation/configuration_utils.js\";\n\nexport class WhisperGenerationConfig extends GenerationConfig {\n\n /**\n * Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`.\n * @type {boolean}\n */\n return_timestamps = null;\n\n /**\n * Whether to return token-level timestamps\n * with the text. This can be used with or without the `return_timestamps` option. To get word-level\n * timestamps, use the tokenizer to group the tokens into words.\n * @type {boolean}\n */\n return_token_timestamps = null;\n\n /**\n * The number of audio frames available in this chunk. This is only used generating word-level timestamps.\n * @type {number}\n */\n num_frames = null;\n\n /**\n * Alignment heads to predict word-level timestamps. This is a list of [layer, head] pairs that\n * select the cross-attention heads that are highly correlated to word-level timing.\n * @type {[number, number][]}\n */\n alignment_heads = null;\n\n /**\n * Task to use for generation, either \"translate\" or \"transcribe\".\n * @type {string}\n */\n task = null;\n\n /**\n * Language token to use for generation, can be either in the form of `<|en|>`, `en` or `english`.\n * You can find all the possible language tokens in the `model.generation_config.lang_to_id` dictionary.\n * @type {string}\n */\n language = null;\n\n /**\n * The id of the `\"<|notimestamps|>\"` token.\n * @type {number}\n */\n no_timestamps_token_id = null;\n\n /**\n * Rank-1 list of token IDs created by passing text to [`~WhisperProcessor.get_prompt_ids`] that is\n * provided as a prompt to each chunk. This can be used to provide or \"prompt-engineer\" a context for\n * transcription, e.g. custom vocabularies or proper nouns to make it more likely to predict those words\n * correctly. It cannot be used in conjunction with `decoder_start_token_id` as it overwrites this value.\n * @type {number[]}\n */\n prompt_ids = null;\n\n /**\n * Whether the model is multilingual or not.\n * @type {boolean}\n */\n is_multilingual = null;\n\n /**\n * (Optional) A mapping from language tokens to their corresponding IDs.\n * Only required if the model is multilingual.\n * @type {Record|null}\n */\n lang_to_id = null;\n\n /**\n * (Optional) A mapping from task tokens to their corresponding IDs.\n * @type {Record|null}\n */\n task_to_id = null;\n\n /**\n * Used to set the maximum value of the initial timestamp. This is used to prevent the model from\n * predicting timestamps that are too far in the future.\n * @type {number}\n */\n max_initial_timestamp_index = 1;\n}\n\n/**\n * @typedef {import('../../generation/parameters.js').GenerationFunctionParameters & {generation_config: WhisperGenerationConfig} & WhisperGenerationConfig} WhisperGenerationFunctionParameters\n */\n","import { createInferenceSession } from \"../backends/onnx.js\";\nimport { Tensor } from \"../utils/tensor.js\";\n\n/**\n * Asynchronously creates a wrapper function for running an ONNX inference session.\n *\n * @param {number[]} session_bytes The session data in bytes.\n * @param {import('onnxruntime-common').InferenceSession.SessionOptions} session_options The options for the ONNX session.\n * @template {string | [string] | string[]} T\n * @param {T} names The name(s) of the output tensor(s).\n * \n * @returns {Promise): Promise>}\n * The wrapper function for running the ONNX inference session.\n */\nconst wrap = async (session_bytes, session_options, names) => {\n const session = await createInferenceSession(\n new Uint8Array(session_bytes), session_options,\n );\n return /** @type {any} */(async (/** @type {Record} */ inputs) => {\n const ortFeed = Object.fromEntries(Object.entries(inputs).map(([k, v]) => [k, v.ort_tensor]));\n const outputs = await session.run(ortFeed);\n\n if (Array.isArray(names)) {\n return names.map((n) => new Tensor(outputs[n]));\n } else {\n return new Tensor(outputs[/** @type {string} */(names)]);\n }\n })\n}\n\n// In-memory registry of initialized ONNX operators\nexport class TensorOpRegistry {\n static session_options = {\n // TODO: Allow for multiple execution providers\n // executionProviders: ['webgpu'],\n };\n\n static get bilinear_interpolate_4d() {\n if (!this._bilinear_interpolate_4d) {\n this._bilinear_interpolate_4d = wrap(\n [8, 9, 18, 0, 58, 128, 1, 10, 40, 10, 1, 120, 10, 0, 10, 0, 10, 1, 115, 18, 1, 121, 34, 6, 82, 101, 115, 105, 122, 101, 42, 17, 10, 4, 109, 111, 100, 101, 34, 6, 108, 105, 110, 101, 97, 114, 160, 1, 3, 18, 1, 114, 90, 31, 10, 1, 120, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 90, 15, 10, 1, 115, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 4, 98, 31, 10, 1, 121, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 66, 2, 16, 20],\n this.session_options,\n 'y',\n );\n }\n return this._bilinear_interpolate_4d;\n }\n\n static get bicubic_interpolate_4d() {\n if (!this._bicubic_interpolate_4d) {\n this._bicubic_interpolate_4d = wrap(\n [8, 9, 18, 0, 58, 127, 10, 39, 10, 1, 120, 10, 0, 10, 0, 10, 1, 115, 18, 1, 121, 34, 6, 82, 101, 115, 105, 122, 101, 42, 16, 10, 4, 109, 111, 100, 101, 34, 5, 99, 117, 98, 105, 99, 160, 1, 3, 18, 1, 114, 90, 31, 10, 1, 120, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 90, 15, 10, 1, 115, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 4, 98, 31, 10, 1, 121, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 66, 2, 16, 20],\n this.session_options,\n 'y',\n );\n }\n return this._bicubic_interpolate_4d;\n }\n\n static get matmul() {\n if (!this._matmul) {\n this._matmul = wrap(\n [8, 9, 18, 0, 58, 55, 10, 17, 10, 1, 97, 10, 1, 98, 18, 1, 99, 34, 6, 77, 97, 116, 77, 117, 108, 18, 1, 114, 90, 9, 10, 1, 97, 18, 4, 10, 2, 8, 1, 90, 9, 10, 1, 98, 18, 4, 10, 2, 8, 1, 98, 9, 10, 1, 99, 18, 4, 10, 2, 8, 1, 66, 2, 16, 20],\n this.session_options,\n 'c',\n );\n }\n return this._matmul;\n }\n\n static get stft() {\n if (!this._stft) {\n this._stft = wrap(\n [8, 7, 18, 0, 58, 148, 1, 10, 38, 10, 1, 115, 10, 1, 106, 10, 1, 119, 10, 1, 108, 18, 1, 111, 34, 4, 83, 84, 70, 84, 42, 15, 10, 8, 111, 110, 101, 115, 105, 100, 101, 100, 24, 1, 160, 1, 2, 18, 1, 115, 90, 26, 10, 1, 115, 18, 21, 10, 19, 8, 1, 18, 15, 10, 3, 18, 1, 98, 10, 3, 18, 1, 115, 10, 3, 18, 1, 99, 90, 11, 10, 1, 106, 18, 6, 10, 4, 8, 7, 18, 0, 90, 16, 10, 1, 119, 18, 11, 10, 9, 8, 1, 18, 5, 10, 3, 18, 1, 119, 90, 11, 10, 1, 108, 18, 6, 10, 4, 8, 7, 18, 0, 98, 31, 10, 1, 111, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 102, 10, 3, 18, 1, 100, 10, 3, 18, 1, 99, 66, 2, 16, 17],\n this.session_options,\n 'o',\n )\n }\n return this._stft;\n }\n\n static get rfft() {\n if (!this._rfft) {\n this._rfft = wrap(\n [8, 9, 18, 0, 58, 97, 10, 33, 10, 1, 120, 10, 0, 10, 1, 97, 18, 1, 121, 34, 3, 68, 70, 84, 42, 15, 10, 8, 111, 110, 101, 115, 105, 100, 101, 100, 24, 1, 160, 1, 2, 18, 1, 100, 90, 21, 10, 1, 120, 18, 16, 10, 14, 8, 1, 18, 10, 10, 3, 18, 1, 115, 10, 3, 18, 1, 99, 90, 11, 10, 1, 97, 18, 6, 10, 4, 8, 7, 18, 0, 98, 21, 10, 1, 121, 18, 16, 10, 14, 8, 1, 18, 10, 10, 3, 18, 1, 115, 10, 3, 18, 1, 99, 66, 2, 16, 20],\n this.session_options,\n 'y',\n )\n }\n return this._rfft;\n }\n\n static get top_k() {\n if (!this._top_k) {\n this._top_k = wrap(\n [8, 10, 18, 0, 58, 73, 10, 18, 10, 1, 120, 10, 1, 107, 18, 1, 118, 18, 1, 105, 34, 4, 84, 111, 112, 75, 18, 1, 116, 90, 9, 10, 1, 120, 18, 4, 10, 2, 8, 1, 90, 15, 10, 1, 107, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 1, 98, 9, 10, 1, 118, 18, 4, 10, 2, 8, 1, 98, 9, 10, 1, 105, 18, 4, 10, 2, 8, 7, 66, 2, 16, 21],\n this.session_options,\n [ /* Values */ 'v', /* Indices */ 'i']\n )\n }\n return this._top_k;\n }\n}\n","/**\n * @file Pipelines provide a high-level, easy to use, API for running machine learning models.\n * \n * **Example:** Instantiate pipeline using the `pipeline` function.\n * ```javascript\n * import { pipeline } from '@huggingface/transformers';\n * \n * const classifier = await pipeline('sentiment-analysis');\n * const output = await classifier('I love transformers!');\n * // [{'label': 'POSITIVE', 'score': 0.999817686}]\n * ```\n * \n * @module pipelines\n */\n\nimport {\n AutoTokenizer,\n PreTrainedTokenizer,\n} from './tokenizers.js';\nimport {\n AutoModel,\n AutoModelForSequenceClassification,\n AutoModelForAudioClassification,\n AutoModelForTokenClassification,\n AutoModelForQuestionAnswering,\n AutoModelForMaskedLM,\n AutoModelForSeq2SeqLM,\n AutoModelForSpeechSeq2Seq,\n AutoModelForTextToWaveform,\n AutoModelForTextToSpectrogram,\n AutoModelForCTC,\n AutoModelForCausalLM,\n AutoModelForVision2Seq,\n AutoModelForImageClassification,\n AutoModelForImageSegmentation,\n AutoModelForSemanticSegmentation,\n AutoModelForUniversalSegmentation,\n AutoModelForObjectDetection,\n AutoModelForZeroShotObjectDetection,\n AutoModelForDocumentQuestionAnswering,\n AutoModelForImageToImage,\n AutoModelForDepthEstimation,\n AutoModelForImageFeatureExtraction,\n PreTrainedModel,\n} from './models.js';\nimport {\n AutoProcessor,\n Processor\n} from './processors.js';\n\nimport {\n Callable,\n} from './utils/generic.js';\n\nimport {\n dispatchCallback,\n pop,\n product,\n} from './utils/core.js';\nimport {\n softmax,\n max,\n round,\n} from './utils/maths.js';\nimport {\n read_audio\n} from './utils/audio.js';\nimport {\n Tensor,\n mean_pooling,\n interpolate,\n quantize_embeddings,\n topk,\n} from './utils/tensor.js';\nimport { RawImage } from './utils/image.js';\n\n\n/**\n * @typedef {string | RawImage | URL} ImageInput\n * @typedef {ImageInput|ImageInput[]} ImagePipelineInputs\n */\n\n/**\n * Prepare images for further tasks.\n * @param {ImagePipelineInputs} images images to prepare.\n * @returns {Promise} returns processed images.\n * @private\n */\nasync function prepareImages(images) {\n if (!Array.isArray(images)) {\n images = [images];\n }\n\n // Possibly convert any non-images to images\n return await Promise.all(images.map(x => RawImage.read(x)));\n}\n\n/**\n * @typedef {string | URL | Float32Array | Float64Array} AudioInput\n * @typedef {AudioInput|AudioInput[]} AudioPipelineInputs\n */\n\n/**\n * Prepare audios for further tasks.\n * @param {AudioPipelineInputs} audios audios to prepare.\n * @param {number} sampling_rate sampling rate of the audios.\n * @returns {Promise} The preprocessed audio data.\n * @private\n */\nasync function prepareAudios(audios, sampling_rate) {\n if (!Array.isArray(audios)) {\n audios = [audios];\n }\n\n return await Promise.all(audios.map(x => {\n if (typeof x === 'string' || x instanceof URL) {\n return read_audio(x, sampling_rate);\n } else if (x instanceof Float64Array) {\n return new Float32Array(x);\n }\n return x;\n }));\n}\n\n/**\n * @typedef {Object} BoundingBox\n * @property {number} xmin The minimum x coordinate of the bounding box.\n * @property {number} ymin The minimum y coordinate of the bounding box.\n * @property {number} xmax The maximum x coordinate of the bounding box.\n * @property {number} ymax The maximum y coordinate of the bounding box.\n */\n\n/**\n * Helper function to convert list [xmin, xmax, ymin, ymax] into object { \"xmin\": xmin, ... }\n * @param {number[]} box The bounding box as a list.\n * @param {boolean} asInteger Whether to cast to integers.\n * @returns {BoundingBox} The bounding box as an object.\n * @private\n */\nfunction get_bounding_box(box, asInteger) {\n if (asInteger) {\n box = box.map(x => x | 0);\n }\n const [xmin, ymin, xmax, ymax] = box;\n\n return { xmin, ymin, xmax, ymax };\n}\n\n\n/**\n * @callback DisposeType Disposes the item.\n * @returns {Promise} A promise that resolves when the item has been disposed.\n * \n * @typedef {Object} Disposable\n * @property {DisposeType} dispose A promise that resolves when the pipeline has been disposed.\n */\n\n/**\n * The Pipeline class is the class from which all pipelines inherit.\n * Refer to this class for methods shared across different pipelines.\n * @extends Callable\n */\nexport class Pipeline extends Callable {\n /**\n * Create a new Pipeline.\n * @param {Object} options An object containing the following properties:\n * @param {string} [options.task] The task of the pipeline. Useful for specifying subtasks.\n * @param {PreTrainedModel} [options.model] The model used by the pipeline.\n * @param {PreTrainedTokenizer} [options.tokenizer=null] The tokenizer used by the pipeline (if any).\n * @param {Processor} [options.processor=null] The processor used by the pipeline (if any).\n */\n constructor({ task, model, tokenizer = null, processor = null }) {\n super();\n this.task = task;\n this.model = model;\n this.tokenizer = tokenizer;\n this.processor = processor;\n }\n\n /** @type {DisposeType} */\n async dispose() {\n await this.model.dispose();\n }\n}\n\n/**\n * @typedef {Object} ModelTokenizerConstructorArgs\n * @property {string} task The task of the pipeline. Useful for specifying subtasks.\n * @property {PreTrainedModel} model The model used by the pipeline.\n * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline.\n * \n * @typedef {ModelTokenizerConstructorArgs} TextPipelineConstructorArgs An object used to instantiate a text-based pipeline.\n */\n\n/**\n * @typedef {Object} ModelProcessorConstructorArgs\n * @property {string} task The task of the pipeline. Useful for specifying subtasks.\n * @property {PreTrainedModel} model The model used by the pipeline.\n * @property {Processor} processor The processor used by the pipeline.\n * \n * @typedef {ModelProcessorConstructorArgs} AudioPipelineConstructorArgs An object used to instantiate an audio-based pipeline.\n * @typedef {ModelProcessorConstructorArgs} ImagePipelineConstructorArgs An object used to instantiate an image-based pipeline.\n */\n\n\n/**\n * @typedef {Object} ModelTokenizerProcessorConstructorArgs\n * @property {string} task The task of the pipeline. Useful for specifying subtasks.\n * @property {PreTrainedModel} model The model used by the pipeline.\n * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline.\n * @property {Processor} processor The processor used by the pipeline.\n * \n * @typedef {ModelTokenizerProcessorConstructorArgs} TextAudioPipelineConstructorArgs An object used to instantiate a text- and audio-based pipeline.\n * @typedef {ModelTokenizerProcessorConstructorArgs} TextImagePipelineConstructorArgs An object used to instantiate a text- and image-based pipeline.\n */\n\n/**\n * @typedef {Object} TextClassificationSingle\n * @property {string} label The label predicted.\n * @property {number} score The corresponding probability.\n * @typedef {TextClassificationSingle[]} TextClassificationOutput\n * \n * @typedef {Object} TextClassificationPipelineOptions Parameters specific to text classification pipelines.\n * @property {number} [top_k=1] The number of top predictions to be returned.\n * \n * @callback TextClassificationPipelineCallback Classify the text(s) given as inputs.\n * @param {string|string[]} texts The input text(s) to be classified.\n * @param {TextClassificationPipelineOptions} [options] The options to use for text classification.\n * @returns {Promise} An array or object containing the predicted labels and scores.\n * \n * @typedef {TextPipelineConstructorArgs & TextClassificationPipelineCallback & Disposable} TextClassificationPipelineType\n */\n\n/**\n * Text classification pipeline using any `ModelForSequenceClassification`.\n *\n * **Example:** Sentiment-analysis w/ `Xenova/distilbert-base-uncased-finetuned-sst-2-english`.\n * ```javascript\n * const classifier = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english');\n * const output = await classifier('I love transformers!');\n * // [{ label: 'POSITIVE', score: 0.999788761138916 }]\n * ```\n * \n * **Example:** Multilingual sentiment-analysis w/ `Xenova/bert-base-multilingual-uncased-sentiment` (and return top 5 classes).\n * ```javascript\n * const classifier = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment');\n * const output = await classifier('Le meilleur film de tous les temps.', { top_k: 5 });\n * // [\n * // { label: '5 stars', score: 0.9610759615898132 },\n * // { label: '4 stars', score: 0.03323351591825485 },\n * // { label: '3 stars', score: 0.0036155181005597115 },\n * // { label: '1 star', score: 0.0011325967498123646 },\n * // { label: '2 stars', score: 0.0009423971059732139 }\n * // ]\n * ```\n * \n * **Example:** Toxic comment classification w/ `Xenova/toxic-bert` (and return all classes).\n * ```javascript\n * const classifier = await pipeline('text-classification', 'Xenova/toxic-bert');\n * const output = await classifier('I hate you!', { top_k: null });\n * // [\n * // { label: 'toxic', score: 0.9593140482902527 },\n * // { label: 'insult', score: 0.16187334060668945 },\n * // { label: 'obscene', score: 0.03452680632472038 },\n * // { label: 'identity_hate', score: 0.0223250575363636 },\n * // { label: 'threat', score: 0.019197041168808937 },\n * // { label: 'severe_toxic', score: 0.005651099607348442 }\n * // ]\n * ```\n */\nexport class TextClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TextClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new TextClassificationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {TextClassificationPipelineCallback} */\n async _call(texts, {\n top_k = 1\n } = {}) {\n\n // Run tokenization\n const model_inputs = this.tokenizer(texts, {\n padding: true,\n truncation: true,\n });\n\n // Run model\n const outputs = await this.model(model_inputs)\n\n // TODO: Use softmax tensor function\n const function_to_apply =\n this.model.config.problem_type === 'multi_label_classification'\n ? batch => batch.sigmoid()\n : batch => new Tensor(\n 'float32',\n softmax(batch.data),\n batch.dims,\n ); // single_label_classification (default)\n\n const id2label = this.model.config.id2label;\n\n const toReturn = [];\n for (const batch of outputs.logits) {\n const output = function_to_apply(batch);\n\n const scores = await topk(output, top_k);\n\n const values = scores[0].tolist();\n const indices = scores[1].tolist();\n const vals = indices.map((x, i) => ({\n label: id2label ? id2label[x] : `LABEL_${x}`,\n score: values[i],\n }));\n if (top_k === 1) {\n toReturn.push(...vals);\n } else {\n toReturn.push(vals);\n }\n }\n\n return Array.isArray(texts) || top_k === 1 ? /** @type {TextClassificationOutput} */ (toReturn) : /** @type {TextClassificationOutput[]} */ (toReturn)[0];\n }\n}\n\n/**\n * @typedef {Object} TokenClassificationSingle\n * @property {string} word The token/word classified. This is obtained by decoding the selected tokens.\n * @property {number} score The corresponding probability for `entity`.\n * @property {string} entity The entity predicted for that token/word.\n * @property {number} index The index of the corresponding token in the sentence.\n * @property {number} [start] The index of the start of the corresponding entity in the sentence.\n * @property {number} [end] The index of the end of the corresponding entity in the sentence.\n * @typedef {TokenClassificationSingle[]} TokenClassificationOutput\n * \n * @typedef {Object} TokenClassificationPipelineOptions Parameters specific to token classification pipelines.\n * @property {string[]} [ignore_labels] A list of labels to ignore.\n * \n * @callback TokenClassificationPipelineCallback Classify each token of the text(s) given as inputs.\n * @param {string|string[]} texts One or several texts (or one list of texts) for token classification.\n * @param {TokenClassificationPipelineOptions} [options] The options to use for token classification.\n * @returns {Promise} The result.\n * \n * @typedef {TextPipelineConstructorArgs & TokenClassificationPipelineCallback & Disposable} TokenClassificationPipelineType\n */\n\n/**\n * Named Entity Recognition pipeline using any `ModelForTokenClassification`.\n * \n * **Example:** Perform named entity recognition with `Xenova/bert-base-NER`.\n * ```javascript\n * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER');\n * const output = await classifier('My name is Sarah and I live in London');\n * // [\n * // { entity: 'B-PER', score: 0.9980202913284302, index: 4, word: 'Sarah' },\n * // { entity: 'B-LOC', score: 0.9994474053382874, index: 9, word: 'London' }\n * // ]\n * ```\n * \n * **Example:** Perform named entity recognition with `Xenova/bert-base-NER` (and return all labels).\n * ```javascript\n * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER');\n * const output = await classifier('Sarah lives in the United States of America', { ignore_labels: [] });\n * // [\n * // { entity: 'B-PER', score: 0.9966587424278259, index: 1, word: 'Sarah' },\n * // { entity: 'O', score: 0.9987385869026184, index: 2, word: 'lives' },\n * // { entity: 'O', score: 0.9990072846412659, index: 3, word: 'in' },\n * // { entity: 'O', score: 0.9988298416137695, index: 4, word: 'the' },\n * // { entity: 'B-LOC', score: 0.9995510578155518, index: 5, word: 'United' },\n * // { entity: 'I-LOC', score: 0.9990395307540894, index: 6, word: 'States' },\n * // { entity: 'I-LOC', score: 0.9986724853515625, index: 7, word: 'of' },\n * // { entity: 'I-LOC', score: 0.9975294470787048, index: 8, word: 'America' }\n * // ]\n * ```\n */\nexport class TokenClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TokenClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new TokenClassificationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {TokenClassificationPipelineCallback} */\n async _call(texts, {\n ignore_labels = ['O'],\n } = {}) {\n\n const isBatched = Array.isArray(texts);\n\n // Run tokenization\n const model_inputs = this.tokenizer(isBatched ? texts : [texts], {\n padding: true,\n truncation: true,\n });\n\n // Run model\n const outputs = await this.model(model_inputs)\n\n const logits = outputs.logits;\n const id2label = this.model.config.id2label;\n\n const toReturn = [];\n for (let i = 0; i < logits.dims[0]; ++i) {\n const ids = model_inputs.input_ids[i];\n const batch = logits[i];\n\n // List of tokens that aren't ignored\n const tokens = [];\n for (let j = 0; j < batch.dims[0]; ++j) {\n const tokenData = batch[j];\n const topScoreIndex = max(tokenData.data)[1];\n\n const entity = id2label ? id2label[topScoreIndex] : `LABEL_${topScoreIndex}`;\n if (ignore_labels.includes(entity)) {\n // We predicted a token that should be ignored. So, we skip it.\n continue;\n }\n\n // TODO add option to keep special tokens?\n const word = this.tokenizer.decode([ids[j].item()], { skip_special_tokens: true });\n if (word === '') {\n // Was a special token. So, we skip it.\n continue;\n }\n\n const scores = softmax(tokenData.data);\n\n tokens.push({\n entity: entity,\n score: scores[topScoreIndex],\n index: j,\n word: word,\n\n // TODO: Add support for start and end\n // start: null,\n // end: null,\n });\n }\n toReturn.push(tokens);\n }\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} QuestionAnsweringOutput\n * @property {number} score The probability associated to the answer.\n * @property {number} [start] The character start index of the answer (in the tokenized version of the input).\n * @property {number} [end] The character end index of the answer (in the tokenized version of the input).\n * @property {string} answer The answer to the question.\n * \n * @typedef {Object} QuestionAnsweringPipelineOptions Parameters specific to question answering pipelines.\n * @property {number} [top_k=1] The number of top answer predictions to be returned.\n * \n * @callback QuestionAnsweringPipelineCallback Answer the question(s) given as inputs by using the context(s).\n * @param {string|string[]} question One or several question(s) (must be used in conjunction with the `context` argument).\n * @param {string|string[]} context One or several context(s) associated with the question(s) (must be used in conjunction with the `question` argument).\n * @param {QuestionAnsweringPipelineOptions} [options] The options to use for question answering.\n * @returns {Promise} An array or object containing the predicted answers and scores.\n * \n * @typedef {TextPipelineConstructorArgs & QuestionAnsweringPipelineCallback & Disposable} QuestionAnsweringPipelineType\n */\n\n/**\n * Question Answering pipeline using any `ModelForQuestionAnswering`.\n * \n * **Example:** Run question answering with `Xenova/distilbert-base-uncased-distilled-squad`.\n * ```javascript\n * const answerer = await pipeline('question-answering', 'Xenova/distilbert-base-uncased-distilled-squad');\n * const question = 'Who was Jim Henson?';\n * const context = 'Jim Henson was a nice puppet.';\n * const output = await answerer(question, context);\n * // {\n * // answer: \"a nice puppet\",\n * // score: 0.5768911502526741\n * // }\n * ```\n */\nexport class QuestionAnsweringPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => QuestionAnsweringPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new QuestionAnsweringPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {QuestionAnsweringPipelineCallback} */\n async _call(question, context, {\n top_k = 1\n } = {}) {\n\n // Run tokenization\n const inputs = this.tokenizer(question, {\n text_pair: context,\n padding: true,\n truncation: true,\n });\n\n const { start_logits, end_logits } = await this.model(inputs);\n const input_ids = inputs.input_ids.tolist();\n const attention_mask = inputs.attention_mask.tolist();\n\n // TODO: add support for `return_special_tokens_mask`\n const special_tokens = this.tokenizer.all_special_ids;\n\n /** @type {QuestionAnsweringOutput[]} */\n const toReturn = [];\n for (let j = 0; j < start_logits.dims[0]; ++j) {\n const ids = input_ids[j];\n const sepIndex = ids.findIndex(x =>\n // We use == to match bigint with number\n // @ts-ignore\n x == this.tokenizer.sep_token_id\n );\n\n\n const valid_mask = attention_mask[j].map((y, ix) => (\n y == 1\n && (\n ix === 0 // is cls_token\n || (\n ix > sepIndex\n && special_tokens.findIndex(x => x == ids[ix]) === -1 // token is not a special token (special_tokens_mask == 0)\n )\n )\n ));\n\n const start = start_logits[j].tolist();\n const end = end_logits[j].tolist();\n\n // Now, we mask out values that can't be in the answer\n // NOTE: We keep the cls_token unmasked (some models use it to indicate unanswerable questions)\n for (let i = 1; i < start.length; ++i) {\n if (\n attention_mask[j] == 0 // is part of padding\n || i <= sepIndex // is before the sep_token\n || special_tokens.findIndex(x => x == ids[i]) !== -1 // Is a special token\n ) {\n // Make sure non-context indexes in the tensor cannot contribute to the softmax\n start[i] = -Infinity;\n end[i] = -Infinity;\n }\n }\n\n // Normalize logits and spans to retrieve the answer\n const start_scores = softmax(start).map((x, i) => [x, i]);\n const end_scores = softmax(end).map((x, i) => [x, i]);\n\n // Mask CLS\n start_scores[0][0] = 0;\n end_scores[0][0] = 0;\n\n // Generate all valid spans and select best ones\n const options = product(start_scores, end_scores)\n .filter(x => x[0][1] <= x[1][1])\n .map(x => [x[0][1], x[1][1], x[0][0] * x[1][0]])\n .sort((a, b) => b[2] - a[2]);\n\n for (let k = 0; k < Math.min(options.length, top_k); ++k) {\n const [start, end, score] = options[k];\n\n const answer_tokens = ids.slice(start, end + 1)\n\n const answer = this.tokenizer.decode(answer_tokens, {\n skip_special_tokens: true,\n });\n\n // TODO add start and end?\n // NOTE: HF returns character index\n toReturn.push({\n answer, score\n });\n }\n }\n\n // Mimic HF's return type based on top_k\n return (top_k === 1) ? toReturn[0] : toReturn;\n }\n}\n\n\n/**\n * @typedef {Object} FillMaskSingle\n * @property {string} sequence The corresponding input with the mask token prediction.\n * @property {number} score The corresponding probability.\n * @property {number} token The predicted token id (to replace the masked one).\n * @property {string} token_str The predicted token (to replace the masked one).\n * @typedef {FillMaskSingle[]} FillMaskOutput\n * \n * @typedef {Object} FillMaskPipelineOptions Parameters specific to fill mask pipelines.\n * @property {number} [top_k=5] When passed, overrides the number of predictions to return.\n * \n * @callback FillMaskPipelineCallback Fill the masked token in the text(s) given as inputs.\n * @param {string|string[]} texts One or several texts (or one list of prompts) with masked tokens.\n * @param {FillMaskPipelineOptions} [options] The options to use for masked language modelling.\n * @returns {Promise} An array of objects containing the score, predicted token, predicted token string,\n * and the sequence with the predicted token filled in, or an array of such arrays (one for each input text).\n * If only one input text is given, the output will be an array of objects.\n * @throws {Error} When the mask token is not found in the input text.\n * \n * @typedef {TextPipelineConstructorArgs & FillMaskPipelineCallback & Disposable} FillMaskPipelineType\n */\n\n/**\n * Masked language modeling prediction pipeline using any `ModelWithLMHead`.\n * \n * **Example:** Perform masked language modelling (a.k.a. \"fill-mask\") with `Xenova/bert-base-uncased`.\n * ```javascript\n * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased');\n * const output = await unmasker('The goal of life is [MASK].');\n * // [\n * // { token_str: 'survival', score: 0.06137419492006302, token: 8115, sequence: 'The goal of life is survival.' },\n * // { token_str: 'love', score: 0.03902450203895569, token: 1567, sequence: 'The goal of life is love.' },\n * // { token_str: 'happiness', score: 0.03253183513879776, token: 9266, sequence: 'The goal of life is happiness.' },\n * // { token_str: 'freedom', score: 0.018736306577920914, token: 4438, sequence: 'The goal of life is freedom.' },\n * // { token_str: 'life', score: 0.01859794743359089, token: 1297, sequence: 'The goal of life is life.' }\n * // ]\n * ```\n * \n * **Example:** Perform masked language modelling (a.k.a. \"fill-mask\") with `Xenova/bert-base-cased` (and return top result).\n * ```javascript\n * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased');\n * const output = await unmasker('The Milky Way is a [MASK] galaxy.', { top_k: 1 });\n * // [{ token_str: 'spiral', score: 0.6299987435340881, token: 14061, sequence: 'The Milky Way is a spiral galaxy.' }]\n * ```\n */\nexport class FillMaskPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => FillMaskPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new FillMaskPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {FillMaskPipelineCallback} */\n async _call(texts, {\n top_k = 5\n } = {}) {\n\n // Run tokenization\n const model_inputs = this.tokenizer(texts, {\n padding: true,\n truncation: true,\n });\n\n // Run model\n const { logits } = await this.model(model_inputs)\n\n const toReturn = [];\n\n /** @type {bigint[][]} */\n const input_ids = model_inputs.input_ids.tolist();\n for (let i = 0; i < input_ids.length; ++i) {\n const ids = input_ids[i];\n const mask_token_index = ids.findIndex(x =>\n // We use == to match bigint with number\n // @ts-ignore\n x == this.tokenizer.mask_token_id\n );\n if (mask_token_index === -1) {\n throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`)\n }\n const itemLogits = logits[i][mask_token_index];\n\n const scores = await topk(new Tensor(\n 'float32',\n softmax(itemLogits.data),\n itemLogits.dims,\n ), top_k);\n const values = scores[0].tolist();\n const indices = scores[1].tolist();\n\n toReturn.push(indices.map((x, i) => {\n const sequence = ids.slice();\n sequence[mask_token_index] = x;\n\n return {\n score: values[i],\n token: Number(x),\n token_str: this.tokenizer.model.vocab[x],\n sequence: this.tokenizer.decode(sequence, { skip_special_tokens: true }),\n }\n }));\n }\n return Array.isArray(texts) ? toReturn : toReturn[0];\n }\n}\n\n\n/**\n * @typedef {Object} Text2TextGenerationSingle\n * @property {string} generated_text The generated text.\n * @typedef {Text2TextGenerationSingle[]} Text2TextGenerationOutput\n * \n * @callback Text2TextGenerationPipelineCallback Generate the output text(s) using text(s) given as inputs.\n * @param {string|string[]} texts Input text for the encoder.\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise}\n * \n * @typedef {TextPipelineConstructorArgs & Text2TextGenerationPipelineCallback & Disposable} Text2TextGenerationPipelineType\n */\n\n/**\n * Text2TextGenerationPipeline class for generating text using a model that performs text-to-text generation tasks.\n * \n * **Example:** Text-to-text generation w/ `Xenova/LaMini-Flan-T5-783M`.\n * ```javascript\n * const generator = await pipeline('text2text-generation', 'Xenova/LaMini-Flan-T5-783M');\n * const output = await generator('how can I become more healthy?', {\n * max_new_tokens: 100,\n * });\n * // [{ generated_text: \"To become more healthy, you can: 1. Eat a balanced diet with plenty of fruits, vegetables, whole grains, lean proteins, and healthy fats. 2. Stay hydrated by drinking plenty of water. 3. Get enough sleep and manage stress levels. 4. Avoid smoking and excessive alcohol consumption. 5. Regularly exercise and maintain a healthy weight. 6. Practice good hygiene and sanitation. 7. Seek medical attention if you experience any health issues.\" }]\n * ```\n */\nexport class Text2TextGenerationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => Text2TextGenerationPipelineType} */ (Pipeline)) {\n /** @type {'generated_text'} */\n _key = 'generated_text';\n\n /**\n * Create a new Text2TextGenerationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {Text2TextGenerationPipelineCallback} */\n async _call(texts, generate_kwargs = {}) {\n if (!Array.isArray(texts)) {\n texts = [texts];\n }\n\n\n // Add global prefix, if present\n if (this.model.config.prefix) {\n texts = texts.map(x => this.model.config.prefix + x)\n }\n\n // Handle task specific params:\n const task_specific_params = this.model.config.task_specific_params\n if (task_specific_params && task_specific_params[this.task]) {\n // Add prefixes, if present\n if (task_specific_params[this.task].prefix) {\n texts = texts.map(x => task_specific_params[this.task].prefix + x)\n }\n\n // TODO update generation config\n }\n\n const tokenizer = this.tokenizer;\n const tokenizer_options = {\n padding: true,\n truncation: true,\n }\n let inputs;\n if (this instanceof TranslationPipeline && '_build_translation_inputs' in tokenizer) {\n // TODO: move to Translation pipeline?\n // Currently put here to avoid code duplication\n // @ts-ignore\n inputs = tokenizer._build_translation_inputs(texts, tokenizer_options, generate_kwargs);\n\n } else {\n inputs = tokenizer(texts, tokenizer_options);\n }\n\n const outputTokenIds = await this.model.generate({ ...inputs, ...generate_kwargs });\n return tokenizer.batch_decode(/** @type {Tensor} */(outputTokenIds), {\n skip_special_tokens: true,\n }).map(text => ({ [this._key]: text }));\n }\n}\n\n\n/**\n * @typedef {Object} SummarizationSingle\n * @property {string} summary_text The summary text.\n * @typedef {SummarizationSingle[]} SummarizationOutput\n * \n * @callback SummarizationPipelineCallback Summarize the text(s) given as inputs.\n * @param {string|string[]} texts One or several articles (or one list of articles) to summarize.\n * @param {import('./generation/configuration_utils.js').GenerationConfig} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise}\n * \n * @typedef {TextPipelineConstructorArgs & SummarizationPipelineCallback & Disposable} SummarizationPipelineType\n */\n\n/**\n * A pipeline for summarization tasks, inheriting from Text2TextGenerationPipeline.\n * \n * **Example:** Summarization w/ `Xenova/distilbart-cnn-6-6`.\n * ```javascript\n * const generator = await pipeline('summarization', 'Xenova/distilbart-cnn-6-6');\n * const text = 'The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, ' +\n * 'and the tallest structure in Paris. Its base is square, measuring 125 metres (410 ft) on each side. ' +\n * 'During its construction, the Eiffel Tower surpassed the Washington Monument to become the tallest ' +\n * 'man-made structure in the world, a title it held for 41 years until the Chrysler Building in New ' +\n * 'York City was finished in 1930. It was the first structure to reach a height of 300 metres. Due to ' +\n * 'the addition of a broadcasting aerial at the top of the tower in 1957, it is now taller than the ' +\n * 'Chrysler Building by 5.2 metres (17 ft). Excluding transmitters, the Eiffel Tower is the second ' +\n * 'tallest free-standing structure in France after the Millau Viaduct.';\n * const output = await generator(text, {\n * max_new_tokens: 100,\n * });\n * // [{ summary_text: ' The Eiffel Tower is about the same height as an 81-storey building and the tallest structure in Paris. It is the second tallest free-standing structure in France after the Millau Viaduct.' }]\n * ```\n */\nexport class SummarizationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => SummarizationPipelineType} */ (/** @type {any} */ (Text2TextGenerationPipeline))) {\n /** @type {'summary_text'} */\n _key = 'summary_text';\n\n /**\n * Create a new SummarizationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n}\n\n\n/**\n * @typedef {Object} TranslationSingle\n * @property {string} translation_text The translated text.\n * @typedef {TranslationSingle[]} TranslationOutput\n * \n * @callback TranslationPipelineCallback Translate the text(s) given as inputs.\n * @param {string|string[]} texts Texts to be translated.\n * @param {import('./generation/configuration_utils.js').GenerationConfig} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise}\n * \n * @typedef {TextPipelineConstructorArgs & TranslationPipelineCallback & Disposable} TranslationPipelineType\n */\n\n/**\n * Translates text from one language to another.\n * \n * **Example:** Multilingual translation w/ `Xenova/nllb-200-distilled-600M`.\n * \n * See [here](https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200)\n * for the full list of languages and their corresponding codes.\n * \n * ```javascript\n * const translator = await pipeline('translation', 'Xenova/nllb-200-distilled-600M');\n * const output = await translator('जीवन एक चॉकलेट बॉक्स की तरह है।', {\n * src_lang: 'hin_Deva', // Hindi\n * tgt_lang: 'fra_Latn', // French\n * });\n * // [{ translation_text: 'La vie est comme une boîte à chocolat.' }]\n * ```\n * \n * **Example:** Multilingual translation w/ `Xenova/m2m100_418M`.\n * \n * See [here](https://huggingface.co/facebook/m2m100_418M#languages-covered)\n * for the full list of languages and their corresponding codes.\n * \n * ```javascript\n * const translator = await pipeline('translation', 'Xenova/m2m100_418M');\n * const output = await translator('生活就像一盒巧克力。', {\n * src_lang: 'zh', // Chinese\n * tgt_lang: 'en', // English\n * });\n * // [{ translation_text: 'Life is like a box of chocolate.' }]\n * ```\n * \n * **Example:** Multilingual translation w/ `Xenova/mbart-large-50-many-to-many-mmt`.\n * \n * See [here](https://huggingface.co/facebook/mbart-large-50-many-to-many-mmt#languages-covered)\n * for the full list of languages and their corresponding codes.\n * \n * ```javascript\n * const translator = await pipeline('translation', 'Xenova/mbart-large-50-many-to-many-mmt');\n * const output = await translator('संयुक्त राष्ट्र के प्रमुख का कहना है कि सीरिया में कोई सैन्य समाधान नहीं है', {\n * src_lang: 'hi_IN', // Hindi\n * tgt_lang: 'fr_XX', // French\n * });\n * // [{ translation_text: 'Le chef des Nations affirme qu 'il n 'y a military solution in Syria.' }]\n * ```\n */\nexport class TranslationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TranslationPipelineType} */ (/** @type {any} */ (Text2TextGenerationPipeline))) {\n /** @type {'translation_text'} */\n _key = 'translation_text';\n\n /**\n * Create a new TranslationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n}\n\nfunction isChat(x) {\n return Array.isArray(x) && x.every(x => 'role' in x && 'content' in x);\n}\n\n/**\n * @typedef {import('./tokenizers.js').Message[]} Chat\n * \n * @typedef {Object} TextGenerationSingle\n * @property {string|Chat} generated_text The generated text.\n * @typedef {TextGenerationSingle[]} TextGenerationOutput\n * \n * @typedef {Object} TextGenerationSpecificParams Parameters specific to text-generation pipelines.\n * @property {boolean} [add_special_tokens] Whether or not to add special tokens when tokenizing the sequences.\n * @property {boolean} [return_full_text=true] If set to `false` only added text is returned, otherwise the full text is returned.\n * @typedef {import('./generation/configuration_utils.js').GenerationConfig & TextGenerationSpecificParams} TextGenerationConfig\n * \n * @callback TextGenerationPipelineCallback Complete the prompt(s) given as inputs.\n * @param {string|string[]|Chat|Chat[]} texts One or several prompts (or one list of prompts) to complete.\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise} An array or object containing the generated texts.\n * \n * @typedef {TextPipelineConstructorArgs & TextGenerationPipelineCallback & Disposable} TextGenerationPipelineType\n */\n\n/**\n * Language generation pipeline using any `ModelWithLMHead` or `ModelForCausalLM`.\n * This pipeline predicts the words that will follow a specified text prompt.\n * NOTE: For the full list of generation parameters, see [`GenerationConfig`](./utils/generation#module_utils/generation.GenerationConfig).\n * \n * **Example:** Text generation with `Xenova/distilgpt2` (default settings).\n * ```javascript\n * const generator = await pipeline('text-generation', 'Xenova/distilgpt2');\n * const text = 'I enjoy walking with my cute dog,';\n * const output = await generator(text);\n * // [{ generated_text: \"I enjoy walking with my cute dog, and I love to play with the other dogs.\" }]\n * ```\n * \n * **Example:** Text generation with `Xenova/distilgpt2` (custom settings).\n * ```javascript\n * const generator = await pipeline('text-generation', 'Xenova/distilgpt2');\n * const text = 'Once upon a time, there was';\n * const output = await generator(text, {\n * temperature: 2,\n * max_new_tokens: 10,\n * repetition_penalty: 1.5,\n * no_repeat_ngram_size: 2,\n * num_beams: 2,\n * num_return_sequences: 2,\n * });\n * // [{\n * // \"generated_text\": \"Once upon a time, there was an abundance of information about the history and activities that\"\n * // }, {\n * // \"generated_text\": \"Once upon a time, there was an abundance of information about the most important and influential\"\n * // }]\n * ```\n * \n * **Example:** Run code generation with `Xenova/codegen-350M-mono`.\n * ```javascript\n * const generator = await pipeline('text-generation', 'Xenova/codegen-350M-mono');\n * const text = 'def fib(n):';\n * const output = await generator(text, {\n * max_new_tokens: 44,\n * });\n * // [{\n * // generated_text: 'def fib(n):\\n' +\n * // ' if n == 0:\\n' +\n * // ' return 0\\n' +\n * // ' elif n == 1:\\n' +\n * // ' return 1\\n' +\n * // ' else:\\n' +\n * // ' return fib(n-1) + fib(n-2)\\n'\n * // }]\n * ```\n */\nexport class TextGenerationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TextGenerationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new TextGenerationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {TextGenerationPipelineCallback} */\n async _call(texts, generate_kwargs = {}) {\n let isBatched = false;\n let isChatInput = false;\n\n // Normalize inputs\n /** @type {string[]} */\n let inputs;\n if (typeof texts === 'string') {\n inputs = texts = [texts];\n } else if (Array.isArray(texts) && texts.every(x => typeof x === 'string')) {\n isBatched = true;\n inputs = /** @type {string[]} */(texts);\n } else {\n if (isChat(texts)) {\n texts = [/** @type {Chat} */(texts)];\n } else if (Array.isArray(texts) && texts.every(isChat)) {\n isBatched = true;\n } else {\n throw new Error('Input must be a string, an array of strings, a Chat, or an array of Chats');\n }\n isChatInput = true;\n\n // If the input is a chat, we need to apply the chat template\n inputs = /** @type {string[]} */(/** @type {Chat[]} */ (texts).map(\n x => this.tokenizer.apply_chat_template(x, {\n tokenize: false,\n add_generation_prompt: true,\n })\n ));\n }\n\n // By default, do not add special tokens\n const add_special_tokens = generate_kwargs.add_special_tokens ?? false;\n\n // By default, return full text\n const return_full_text = isChatInput\n ? false\n : generate_kwargs.return_full_text ?? true;\n\n this.tokenizer.padding_side = 'left';\n const text_inputs = this.tokenizer(inputs, {\n add_special_tokens,\n padding: true,\n truncation: true,\n });\n\n const outputTokenIds = /** @type {Tensor} */(await this.model.generate({\n ...text_inputs,\n ...generate_kwargs\n }));\n\n const decoded = this.tokenizer.batch_decode(outputTokenIds, {\n skip_special_tokens: true,\n });\n\n let promptLengths;\n if (!return_full_text && text_inputs.input_ids.dims.at(-1) > 0) {\n promptLengths = this.tokenizer.batch_decode(text_inputs.input_ids, {\n skip_special_tokens: true,\n }).map(x => x.length);\n }\n\n /** @type {TextGenerationOutput[]} */\n const toReturn = Array.from({ length: texts.length }, _ => []);\n for (let i = 0; i < decoded.length; ++i) {\n const textIndex = Math.floor(i / outputTokenIds.dims[0] * texts.length);\n\n if (promptLengths) {\n // Trim the decoded text to only include the generated part\n decoded[i] = decoded[i].slice(promptLengths[textIndex]);\n }\n toReturn[textIndex].push({\n generated_text: isChatInput\n ? [\n ...((/** @type {Chat[]} */(texts)[textIndex])),\n { role: 'assistant', content: decoded[i] },\n ]\n : decoded[i]\n });\n }\n return (!isBatched && toReturn.length === 1) ? toReturn[0] : toReturn;\n }\n}\n\n/**\n * @typedef {Object} ZeroShotClassificationOutput\n * @property {string} sequence The sequence for which this is the output.\n * @property {string[]} labels The labels sorted by order of likelihood.\n * @property {number[]} scores The probabilities for each of the labels.\n * \n * @typedef {Object} ZeroShotClassificationPipelineOptions Parameters specific to zero-shot classification pipelines.\n * @property {string} [hypothesis_template=\"This example is {}.\"] The template used to turn each\n * candidate label into an NLI-style hypothesis. The candidate label will replace the {} placeholder.\n * @property {boolean} [multi_label=false] Whether or not multiple candidate labels can be true.\n * If `false`, the scores are normalized such that the sum of the label likelihoods for each sequence\n * is 1. If `true`, the labels are considered independent and probabilities are normalized for each\n * candidate by doing a softmax of the entailment score vs. the contradiction score.\n * \n * @callback ZeroShotClassificationPipelineCallback Classify the sequence(s) given as inputs.\n * @param {string|string[]} texts The sequence(s) to classify, will be truncated if the model input is too large.\n * @param {string|string[]} candidate_labels The set of possible class labels to classify each sequence into.\n * Can be a single label, a string of comma-separated labels, or a list of labels.\n * @param {ZeroShotClassificationPipelineOptions} [options] The options to use for zero-shot classification.\n * @returns {Promise} An array or object containing the predicted labels and scores.\n * \n * @typedef {TextPipelineConstructorArgs & ZeroShotClassificationPipelineCallback & Disposable} ZeroShotClassificationPipelineType\n */\n\n/**\n * NLI-based zero-shot classification pipeline using a `ModelForSequenceClassification`\n * trained on NLI (natural language inference) tasks. Equivalent of `text-classification`\n * pipelines, but these models don't require a hardcoded number of potential classes, they\n * can be chosen at runtime. It usually means it's slower but it is **much** more flexible.\n * \n * **Example:** Zero shot classification with `Xenova/mobilebert-uncased-mnli`.\n * ```javascript\n * const classifier = await pipeline('zero-shot-classification', 'Xenova/mobilebert-uncased-mnli');\n * const text = 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.';\n * const labels = [ 'mobile', 'billing', 'website', 'account access' ];\n * const output = await classifier(text, labels);\n * // {\n * // sequence: 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.',\n * // labels: [ 'mobile', 'website', 'billing', 'account access' ],\n * // scores: [ 0.5562091040482018, 0.1843621307860853, 0.13942646639336376, 0.12000229877234923 ]\n * // }\n * ```\n * \n * **Example:** Zero shot classification with `Xenova/nli-deberta-v3-xsmall` (multi-label).\n * ```javascript\n * const classifier = await pipeline('zero-shot-classification', 'Xenova/nli-deberta-v3-xsmall');\n * const text = 'I have a problem with my iphone that needs to be resolved asap!';\n * const labels = [ 'urgent', 'not urgent', 'phone', 'tablet', 'computer' ];\n * const output = await classifier(text, labels, { multi_label: true });\n * // {\n * // sequence: 'I have a problem with my iphone that needs to be resolved asap!',\n * // labels: [ 'urgent', 'phone', 'computer', 'tablet', 'not urgent' ],\n * // scores: [ 0.9958870956360275, 0.9923963400697035, 0.002333537946160235, 0.0015134138567598765, 0.0010699384208377163 ]\n * // }\n * ```\n */\nexport class ZeroShotClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => ZeroShotClassificationPipelineType} */ (Pipeline)) {\n /**\n * Create a new ZeroShotClassificationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n\n // Use model config to get label2id mapping\n this.label2id = Object.fromEntries(\n Object.entries((/** @type {any} */(this).model).config.label2id).map(\n ([k, v]) => [k.toLowerCase(), v]\n )\n );\n\n this.entailment_id = this.label2id['entailment'];\n if (this.entailment_id === undefined) {\n console.warn(\"Could not find 'entailment' in label2id mapping. Using 2 as entailment_id.\");\n this.entailment_id = 2;\n }\n\n this.contradiction_id = this.label2id['contradiction'] ?? this.label2id['not_entailment'];\n if (this.contradiction_id === undefined) {\n console.warn(\"Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id.\");\n this.contradiction_id = 0;\n }\n }\n\n /** @type {ZeroShotClassificationPipelineCallback} */\n async _call(texts, candidate_labels, {\n hypothesis_template = \"This example is {}.\",\n multi_label = false,\n } = {}) {\n\n const isBatched = Array.isArray(texts);\n if (!isBatched) {\n texts = [/** @type {string} */ (texts)];\n }\n if (!Array.isArray(candidate_labels)) {\n candidate_labels = [candidate_labels];\n }\n\n // Insert labels into hypothesis template\n const hypotheses = candidate_labels.map(\n x => hypothesis_template.replace('{}', x)\n );\n\n // How to perform the softmax over the logits:\n // - true: softmax over the entailment vs. contradiction dim for each label independently\n // - false: softmax the \"entailment\" logits over all candidate labels\n const softmaxEach = multi_label || candidate_labels.length === 1;\n\n /** @type {ZeroShotClassificationOutput[]} */\n const toReturn = [];\n for (const premise of texts) {\n const entails_logits = [];\n\n for (const hypothesis of hypotheses) {\n const inputs = this.tokenizer(premise, {\n text_pair: hypothesis,\n padding: true,\n truncation: true,\n })\n const outputs = await this.model(inputs)\n\n if (softmaxEach) {\n entails_logits.push([\n outputs.logits.data[this.contradiction_id],\n outputs.logits.data[this.entailment_id]\n ])\n } else {\n entails_logits.push(outputs.logits.data[this.entailment_id])\n }\n }\n\n /** @type {number[]} */\n const scores = softmaxEach\n ? entails_logits.map(x => softmax(x)[1])\n : softmax(entails_logits);\n\n // Sort by scores (desc) and return scores with indices\n const scores_sorted = scores\n .map((x, i) => [x, i])\n .sort((a, b) => (b[0] - a[0]));\n\n toReturn.push({\n sequence: premise,\n labels: scores_sorted.map(x => candidate_labels[x[1]]),\n scores: scores_sorted.map(x => x[0]),\n });\n }\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} FeatureExtractionPipelineOptions Parameters specific to feature extraction pipelines.\n * @property {'none'|'mean'|'cls'} [pooling=\"none\"] The pooling method to use.\n * @property {boolean} [normalize=false] Whether or not to normalize the embeddings in the last dimension.\n * @property {boolean} [quantize=false] Whether or not to quantize the embeddings.\n * @property {'binary'|'ubinary'} [precision='binary'] The precision to use for quantization. \n * \n * @callback FeatureExtractionPipelineCallback Extract the features of the input(s).\n * @param {string|string[]} texts One or several texts (or one list of texts) to get the features of.\n * @param {FeatureExtractionPipelineOptions} [options] The options to use for feature extraction.\n * @returns {Promise} The features computed by the model.\n * \n * @typedef {TextPipelineConstructorArgs & FeatureExtractionPipelineCallback & Disposable} FeatureExtractionPipelineType\n */\n\n/**\n * Feature extraction pipeline using no model head. This pipeline extracts the hidden\n * states from the base transformer, which can be used as features in downstream tasks.\n * \n * **Example:** Run feature extraction with `bert-base-uncased` (without pooling/normalization).\n * ```javascript\n * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' });\n * const output = await extractor('This is a simple test.');\n * // Tensor {\n * // type: 'float32',\n * // data: Float32Array [0.05939924716949463, 0.021655935794115067, ...],\n * // dims: [1, 8, 768]\n * // }\n * ```\n * \n * **Example:** Run feature extraction with `bert-base-uncased` (with pooling/normalization).\n * ```javascript\n * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' });\n * const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true });\n * // Tensor {\n * // type: 'float32',\n * // data: Float32Array [0.03373778983950615, -0.010106077417731285, ...],\n * // dims: [1, 768]\n * // }\n * ```\n * \n * **Example:** Calculating embeddings with `sentence-transformers` models.\n * ```javascript\n * const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');\n * const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true });\n * // Tensor {\n * // type: 'float32',\n * // data: Float32Array [0.09094982594251633, -0.014774246141314507, ...],\n * // dims: [1, 384]\n * // }\n * ```\n * **Example:** Calculating binary embeddings with `sentence-transformers` models.\n * ```javascript\n * const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');\n * const output = await extractor('This is a simple test.', { pooling: 'mean', quantize: true, precision: 'binary' });\n * // Tensor {\n * // type: 'int8',\n * // data: Int8Array [49, 108, 24, ...],\n * // dims: [1, 48]\n * // }\n * ```\n */\nexport class FeatureExtractionPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => FeatureExtractionPipelineType} */ (Pipeline)) {\n /**\n * Create a new FeatureExtractionPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {FeatureExtractionPipelineCallback} */\n async _call(texts, {\n pooling = /** @type {'none'} */('none'),\n normalize = false,\n quantize = false,\n precision = /** @type {'binary'} */('binary'),\n } = {}) {\n\n // Run tokenization\n const model_inputs = this.tokenizer(texts, {\n padding: true,\n truncation: true,\n });\n\n // Run model\n const outputs = await this.model(model_inputs)\n\n // TODO: Provide warning to the user that they might be using model which was not exported\n // specifically for feature extraction\n // console.log(this.model.config)\n // console.log(outputs)\n\n /** @type {Tensor} */\n let result = outputs.last_hidden_state ?? outputs.logits ?? outputs.token_embeddings;\n if (pooling === 'none') {\n // Skip pooling\n } else if (pooling === 'mean') {\n result = mean_pooling(result, model_inputs.attention_mask);\n } else if (pooling === 'cls') {\n result = result.slice(null, 0);\n } else {\n throw Error(`Pooling method '${pooling}' not supported.`);\n }\n\n if (normalize) {\n result = result.normalize(2, -1);\n }\n\n if (quantize) {\n result = quantize_embeddings(result, precision);\n }\n\n return result;\n }\n}\n\n\n/**\n * @typedef {Object} ImageFeatureExtractionPipelineOptions Parameters specific to image feature extraction pipelines.\n * @property {boolean} [pool=null] Whether or not to return the pooled output. If set to `false`, the model will return the raw hidden states.\n * \n * @callback ImageFeatureExtractionPipelineCallback Extract the features of the input(s).\n * @param {ImagePipelineInputs} images One or several images (or one list of images) to get the features of.\n * @param {ImageFeatureExtractionPipelineOptions} [options] The options to use for image feature extraction.\n * @returns {Promise} The image features computed by the model.\n * \n * @typedef {ImagePipelineConstructorArgs & ImageFeatureExtractionPipelineCallback & Disposable} ImageFeatureExtractionPipelineType\n */\n\n/**\n * Image feature extraction pipeline using no model head. This pipeline extracts the hidden\n * states from the base transformer, which can be used as features in downstream tasks.\n * \n * **Example:** Perform image feature extraction with `Xenova/vit-base-patch16-224-in21k`.\n * ```javascript\n * const image_feature_extractor = await pipeline('image-feature-extraction', 'Xenova/vit-base-patch16-224-in21k');\n * const url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png';\n * const features = await image_feature_extractor(url);\n * // Tensor {\n * // dims: [ 1, 197, 768 ],\n * // type: 'float32',\n * // data: Float32Array(151296) [ ... ],\n * // size: 151296\n * // }\n * ```\n * \n * **Example:** Compute image embeddings with `Xenova/clip-vit-base-patch32`.\n * ```javascript\n * const image_feature_extractor = await pipeline('image-feature-extraction', 'Xenova/clip-vit-base-patch32');\n * const url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png';\n * const features = await image_feature_extractor(url);\n * // Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [ ... ],\n * // size: 512\n * // }\n * ```\n */\nexport class ImageFeatureExtractionPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageFeatureExtractionPipelineType} */ (Pipeline)) {\n /**\n * Create a new ImageFeatureExtractionPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ImageFeatureExtractionPipelineCallback} */\n async _call(images, {\n pool = null,\n } = {}) {\n\n const preparedImages = await prepareImages(images);\n const { pixel_values } = await this.processor(preparedImages);\n const outputs = await this.model({ pixel_values });\n\n /** @type {Tensor} */\n let result;\n if (pool) {\n if (!('pooler_output' in outputs)) {\n throw Error(`No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.`);\n }\n result = outputs.pooler_output;\n\n } else {\n result = outputs.last_hidden_state ?? outputs.logits ?? outputs.image_embeds;\n }\n return result;\n }\n}\n\n// TODO\n// export class SentenceSimilarityPipeline extends Pipeline {\n// }\n\n/**\n * @typedef {Object} AudioClassificationSingle\n * @property {string} label The label predicted.\n * @property {number} score The corresponding probability.\n * @typedef {AudioClassificationSingle[]} AudioClassificationOutput\n * \n * @typedef {Object} AudioClassificationPipelineOptions Parameters specific to audio classification pipelines.\n * @property {number} [top_k=5] The number of top labels that will be returned by the pipeline.\n * If the provided number is `null` or higher than the number of labels available in the model configuration,\n * it will default to the number of labels.\n * \n * @callback AudioClassificationPipelineCallback Classify the sequence(s) given as inputs.\n * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either:\n * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate\n * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API.\n * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`.\n * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).\n * @param {AudioClassificationPipelineOptions} [options] The options to use for audio classification.\n * @returns {Promise} An array or object containing the predicted labels and scores.\n * \n * @typedef {AudioPipelineConstructorArgs & AudioClassificationPipelineCallback & Disposable} AudioClassificationPipelineType\n */\n\n/**\n * Audio classification pipeline using any `AutoModelForAudioClassification`.\n * This pipeline predicts the class of a raw waveform or an audio file.\n * \n * **Example:** Perform audio classification with `Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech`.\n * ```javascript\n * const classifier = await pipeline('audio-classification', 'Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const output = await classifier(url);\n * // [\n * // { label: 'male', score: 0.9981542229652405 },\n * // { label: 'female', score: 0.001845747814513743 }\n * // ]\n * ```\n * \n * **Example:** Perform audio classification with `Xenova/ast-finetuned-audioset-10-10-0.4593` and return top 4 results.\n * ```javascript\n * const classifier = await pipeline('audio-classification', 'Xenova/ast-finetuned-audioset-10-10-0.4593');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cat_meow.wav';\n * const output = await classifier(url, { top_k: 4 });\n * // [\n * // { label: 'Meow', score: 0.5617874264717102 },\n * // { label: 'Cat', score: 0.22365376353263855 },\n * // { label: 'Domestic animals, pets', score: 0.1141069084405899 },\n * // { label: 'Animal', score: 0.08985692262649536 },\n * // ]\n * ```\n */\nexport class AudioClassificationPipeline extends (/** @type {new (options: AudioPipelineConstructorArgs) => AudioClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new AudioClassificationPipeline.\n * @param {AudioPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {AudioClassificationPipelineCallback} */\n async _call(audio, {\n top_k = 5\n } = {}) {\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n const preparedAudios = await prepareAudios(audio, sampling_rate);\n\n const id2label = this.model.config.id2label;\n\n const toReturn = [];\n for (const aud of preparedAudios) {\n const inputs = await this.processor(aud);\n const output = await this.model(inputs);\n const logits = output.logits[0];\n\n const scores = await topk(new Tensor(\n 'float32',\n softmax(logits.data),\n logits.dims,\n ), top_k);\n\n const values = scores[0].tolist();\n const indices = scores[1].tolist();\n\n const vals = indices.map((x, i) => ({\n label: /** @type {string} */ (id2label ? id2label[x] : `LABEL_${x}`),\n score: /** @type {number} */ (values[i]),\n }));\n\n toReturn.push(vals);\n };\n return Array.isArray(audio) ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} ZeroShotAudioClassificationOutput\n * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`.\n * @property {number} score The score attributed by the model for that label (between 0 and 1).\n * \n * @typedef {Object} ZeroShotAudioClassificationPipelineOptions Parameters specific to zero-shot audio classification pipelines.\n * @property {string} [hypothesis_template=\"This is a sound of {}.\"] The sentence used in conjunction with `candidate_labels`\n * to attempt the audio classification by replacing the placeholder with the candidate_labels.\n * Then likelihood is estimated by using `logits_per_audio`.\n * \n * @callback ZeroShotAudioClassificationPipelineCallback Classify the sequence(s) given as inputs.\n * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either:\n * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate\n * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API.\n * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`.\n * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).\n * @param {string[]} candidate_labels The candidate labels for this audio.\n * @param {ZeroShotAudioClassificationPipelineOptions} [options] The options to use for zero-shot audio classification.\n * @returns {Promise} An array of objects containing the predicted labels and scores.\n * \n * @typedef {TextAudioPipelineConstructorArgs & ZeroShotAudioClassificationPipelineCallback & Disposable} ZeroShotAudioClassificationPipelineType\n */\n\n/**\n * Zero shot audio classification pipeline using `ClapModel`. This pipeline predicts the class of an audio when you\n * provide an audio and a set of `candidate_labels`.\n * \n * **Example**: Perform zero-shot audio classification with `Xenova/clap-htsat-unfused`.\n * ```javascript\n * const classifier = await pipeline('zero-shot-audio-classification', 'Xenova/clap-htsat-unfused');\n * const audio = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/dog_barking.wav';\n * const candidate_labels = ['dog', 'vaccum cleaner'];\n * const scores = await classifier(audio, candidate_labels);\n * // [\n * // { score: 0.9993992447853088, label: 'dog' },\n * // { score: 0.0006007603369653225, label: 'vaccum cleaner' }\n * // ]\n * ```\n */\nexport class ZeroShotAudioClassificationPipeline extends (/** @type {new (options: TextAudioPipelineConstructorArgs) => ZeroShotAudioClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ZeroShotAudioClassificationPipeline.\n * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ZeroShotAudioClassificationPipelineCallback} */\n async _call(audio, candidate_labels, {\n hypothesis_template = \"This is a sound of {}.\"\n } = {}) {\n\n const single = !Array.isArray(audio);\n if (single) {\n audio = [/** @type {AudioInput} */ (audio)];\n }\n\n // Insert label into hypothesis template \n const texts = candidate_labels.map(\n x => hypothesis_template.replace('{}', x)\n );\n\n // Run tokenization\n const text_inputs = this.tokenizer(texts, {\n padding: true,\n truncation: true,\n });\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n const preparedAudios = await prepareAudios(audio, sampling_rate);\n\n const toReturn = [];\n for (const aud of preparedAudios) {\n const audio_inputs = await this.processor(aud);\n\n // Run model with both text and audio inputs\n const output = await this.model({ ...text_inputs, ...audio_inputs });\n\n // Compute softmax per audio\n const probs = softmax(output.logits_per_audio.data);\n\n toReturn.push([...probs].map((x, i) => ({\n score: x,\n label: candidate_labels[i]\n })));\n }\n return single ? toReturn[0] : toReturn;\n }\n}\n\n/**\n * @typedef {Object} Chunk\n * @property {[number, number]} timestamp The start and end timestamp of the chunk in seconds.\n * @property {string} text The recognized text.\n */\n\n/**\n * @typedef {Object} AutomaticSpeechRecognitionOutput\n * @property {string} text The recognized text.\n * @property {Chunk[]} [chunks] When using `return_timestamps`, the `chunks` will become a list\n * containing all the various text chunks identified by the model.\n * \n * @typedef {Object} AutomaticSpeechRecognitionSpecificParams Parameters specific to automatic-speech-recognition pipelines.\n * @property {boolean|'word'} [return_timestamps] Whether to return timestamps or not. Default is `false`.\n * @property {number} [chunk_length_s] The length of audio chunks to process in seconds. Default is 0 (no chunking).\n * @property {number} [stride_length_s] The length of overlap between consecutive audio chunks in seconds. If not provided, defaults to `chunk_length_s / 6`.\n * @property {boolean} [force_full_sequences] Whether to force outputting full sequences or not. Default is `false`.\n * @property {string} [language] The source language. Default is `null`, meaning it should be auto-detected. Use this to potentially improve performance if the source language is known.\n * @property {string} [task] The task to perform. Default is `null`, meaning it should be auto-detected.\n * @property {number} [num_frames] The number of frames in the input audio.\n * @typedef {import('./generation/configuration_utils.js').GenerationConfig & AutomaticSpeechRecognitionSpecificParams} AutomaticSpeechRecognitionConfig\n * \n * @callback AutomaticSpeechRecognitionPipelineCallback Transcribe the audio sequence(s) given as inputs to text.\n * @param {AudioPipelineInputs} audio The input audio file(s) to be transcribed. The input is either:\n * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate\n * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API.\n * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`.\n * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise} An object containing the transcription text and optionally timestamps if `return_timestamps` is `true`.\n * \n * @typedef {TextAudioPipelineConstructorArgs & AutomaticSpeechRecognitionPipelineCallback & Disposable} AutomaticSpeechRecognitionPipelineType\n */\n\n/**\n * Pipeline that aims at extracting spoken text contained within some audio.\n *\n * **Example:** Transcribe English.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const output = await transcriber(url);\n * // { text: \" And so my fellow Americans ask not what your country can do for you, ask what you can do for your country.\" }\n * ```\n * \n * **Example:** Transcribe English w/ timestamps.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const output = await transcriber(url, { return_timestamps: true });\n * // {\n * // text: \" And so my fellow Americans ask not what your country can do for you, ask what you can do for your country.\"\n * // chunks: [\n * // { timestamp: [0, 8], text: \" And so my fellow Americans ask not what your country can do for you\" }\n * // { timestamp: [8, 11], text: \" ask what you can do for your country.\" }\n * // ]\n * // }\n * ```\n * \n * **Example:** Transcribe English w/ word-level timestamps.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const output = await transcriber(url, { return_timestamps: 'word' });\n * // {\n * // \"text\": \" And so my fellow Americans ask not what your country can do for you ask what you can do for your country.\",\n * // \"chunks\": [\n * // { \"text\": \" And\", \"timestamp\": [0, 0.78] },\n * // { \"text\": \" so\", \"timestamp\": [0.78, 1.06] },\n * // { \"text\": \" my\", \"timestamp\": [1.06, 1.46] },\n * // ...\n * // { \"text\": \" for\", \"timestamp\": [9.72, 9.92] },\n * // { \"text\": \" your\", \"timestamp\": [9.92, 10.22] },\n * // { \"text\": \" country.\", \"timestamp\": [10.22, 13.5] }\n * // ]\n * // }\n * ```\n * \n * **Example:** Transcribe French.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3';\n * const output = await transcriber(url, { language: 'french', task: 'transcribe' });\n * // { text: \" J'adore, j'aime, je n'aime pas, je déteste.\" }\n * ```\n * \n * **Example:** Translate French to English.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3';\n * const output = await transcriber(url, { language: 'french', task: 'translate' });\n * // { text: \" I love, I like, I don't like, I hate.\" }\n * ```\n * \n * **Example:** Transcribe/translate audio longer than 30 seconds.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/ted_60.wav';\n * const output = await transcriber(url, { chunk_length_s: 30, stride_length_s: 5 });\n * // { text: \" So in college, I was a government major, which means [...] So I'd start off light and I'd bump it up\" }\n * ```\n */\nexport class AutomaticSpeechRecognitionPipeline extends (/** @type {new (options: TextAudioPipelineConstructorArgs) => AutomaticSpeechRecognitionPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new AutomaticSpeechRecognitionPipeline.\n * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {AutomaticSpeechRecognitionPipelineCallback} */\n async _call(audio, kwargs = {}) {\n switch (this.model.config.model_type) {\n case 'whisper':\n return this._call_whisper(audio, kwargs)\n case 'wav2vec2':\n case 'wav2vec2-bert':\n case 'unispeech':\n case 'unispeech-sat':\n case 'hubert':\n return this._call_wav2vec2(audio, kwargs)\n default:\n throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)\n }\n }\n\n /**\n * @type {AutomaticSpeechRecognitionPipelineCallback}\n * @private\n */\n async _call_wav2vec2(audio, kwargs) {\n // TODO use kwargs\n\n if (kwargs.language) {\n console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to \"English\".');\n }\n if (kwargs.task) {\n console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to \"transcribe\".');\n }\n\n const single = !Array.isArray(audio);\n if (single) {\n audio = [/** @type {AudioInput} */ (audio)];\n }\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n const preparedAudios = await prepareAudios(audio, sampling_rate);\n\n const toReturn = [];\n for (const aud of preparedAudios) {\n const inputs = await this.processor(aud);\n const output = await this.model(inputs);\n const logits = output.logits[0];\n\n const predicted_ids = [];\n for (const item of logits) {\n predicted_ids.push(max(item.data)[1])\n }\n const predicted_sentences = this.tokenizer.decode(predicted_ids)\n toReturn.push({ text: predicted_sentences })\n }\n return single ? toReturn[0] : toReturn;\n }\n\n /**\n * @type {AutomaticSpeechRecognitionPipelineCallback}\n * @private\n */\n async _call_whisper(audio, kwargs) {\n const return_timestamps = kwargs.return_timestamps ?? false;\n const chunk_length_s = kwargs.chunk_length_s ?? 0;\n const force_full_sequences = kwargs.force_full_sequences ?? false;\n let stride_length_s = kwargs.stride_length_s ?? null;\n\n const generation_config = { ...kwargs }\n\n if (return_timestamps === 'word') {\n generation_config['return_token_timestamps'] = true;\n generation_config['return_timestamps'] = false; // Do not predict timestamp tokens\n }\n\n const single = !Array.isArray(audio);\n if (single) {\n audio = [/** @type {AudioInput} */ (audio)];\n }\n\n const time_precision = this.processor.feature_extractor.config.chunk_length / this.model.config.max_source_positions;\n const hop_length = this.processor.feature_extractor.config.hop_length;\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n const preparedAudios = await prepareAudios(audio, sampling_rate);\n\n const toReturn = [];\n for (const aud of preparedAudios) {\n /** @type {{stride: number[], input_features: Tensor, is_last: boolean, tokens?: bigint[], token_timestamps?: number[]}[]} */\n let chunks = [];\n if (chunk_length_s > 0) {\n if (stride_length_s === null) {\n stride_length_s = chunk_length_s / 6;\n } else if (chunk_length_s <= stride_length_s) {\n throw Error(\"`chunk_length_s` must be larger than `stride_length_s`.\")\n }\n\n // TODO support different stride_length_s (for left and right)\n\n const window = sampling_rate * chunk_length_s;\n const stride = sampling_rate * stride_length_s;\n const jump = window - 2 * stride;\n let offset = 0;\n\n // Create subarrays of audio with overlaps\n while (true) {\n const offset_end = offset + window;\n const subarr = aud.subarray(offset, offset_end);\n const feature = await this.processor(subarr);\n\n const is_first = offset === 0;\n const is_last = offset_end >= aud.length;\n chunks.push({\n stride: [\n subarr.length,\n is_first ? 0 : stride,\n is_last ? 0 : stride\n ],\n input_features: feature.input_features,\n is_last,\n })\n if (is_last) break;\n offset += jump;\n }\n\n } else {\n chunks = [{\n stride: [aud.length, 0, 0],\n input_features: (await this.processor(aud)).input_features,\n is_last: true\n }]\n }\n\n // Generate for each set of input features\n for (const chunk of chunks) {\n generation_config.num_frames = Math.floor(chunk.stride[0] / hop_length);\n\n // NOTE: doing sequentially for now\n const data = await this.model.generate({\n inputs: chunk.input_features,\n ...generation_config\n });\n\n // TODO: Right now we only get top beam\n if (return_timestamps === 'word') {\n chunk.tokens = data.sequences.tolist()[0];\n chunk.token_timestamps = data.token_timestamps.tolist()[0].map(\n (/** @type {number} */ x) => round(x, 2)\n );\n\n } else {\n chunk.tokens = (/** @type {Tensor} */(data))[0].tolist();\n }\n\n // convert stride to seconds\n chunk.stride = chunk.stride.map(x => x / sampling_rate);\n }\n\n // Merge text chunks\n // @ts-ignore\n const [full_text, optional] = this.tokenizer._decode_asr(chunks, {\n time_precision, return_timestamps, force_full_sequences\n });\n\n toReturn.push({ text: full_text, ...optional })\n }\n return single ? toReturn[0] : toReturn;\n }\n}\n\n/**\n * @typedef {Object} ImageToTextSingle\n * @property {string} generated_text The generated text.\n * @typedef {ImageToTextSingle[]} ImageToTextOutput\n * \n * @callback ImageToTextPipelineCallback Assign labels to the image(s) passed as inputs.\n * @param {ImagePipelineInputs} texts The images to be captioned.\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise} An object (or array of objects) containing the generated text(s).\n * \n * @typedef {TextImagePipelineConstructorArgs & ImageToTextPipelineCallback & Disposable} ImageToTextPipelineType\n */\n\n/**\n * Image To Text pipeline using a `AutoModelForVision2Seq`. This pipeline predicts a caption for a given image.\n * \n * **Example:** Generate a caption for an image w/ `Xenova/vit-gpt2-image-captioning`.\n * ```javascript\n * const captioner = await pipeline('image-to-text', 'Xenova/vit-gpt2-image-captioning');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';\n * const output = await captioner(url);\n * // [{ generated_text: 'a cat laying on a couch with another cat' }]\n * ```\n * \n * **Example:** Optical Character Recognition (OCR) w/ `Xenova/trocr-small-handwritten`.\n * ```javascript\n * const captioner = await pipeline('image-to-text', 'Xenova/trocr-small-handwritten');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/handwriting.jpg';\n * const output = await captioner(url);\n * // [{ generated_text: 'Mr. Brown commented icily.' }]\n * ```\n */\nexport class ImageToTextPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ImageToTextPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ImageToTextPipeline.\n * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ImageToTextPipelineCallback} */\n async _call(images, generate_kwargs = {}) {\n\n const isBatched = Array.isArray(images);\n const preparedImages = await prepareImages(images);\n\n const { pixel_values } = await this.processor(preparedImages);\n\n const toReturn = [];\n for (const batch of pixel_values) {\n batch.dims = [1, ...batch.dims]\n const output = await this.model.generate({ inputs: batch, ...generate_kwargs });\n const decoded = this.tokenizer.batch_decode(/** @type {Tensor} */(output), {\n skip_special_tokens: true,\n }).map(x => ({ generated_text: x.trim() }))\n toReturn.push(decoded);\n }\n\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} ImageClassificationSingle\n * @property {string} label The label identified by the model.\n * @property {number} score The score attributed by the model for that label.\n * @typedef {ImageClassificationSingle[]} ImageClassificationOutput\n * \n * @typedef {Object} ImageClassificationPipelineOptions Parameters specific to image classification pipelines.\n * @property {number} [top_k=1] The number of top labels that will be returned by the pipeline. \n * \n * @callback ImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The input images(s) to be classified.\n * @param {ImageClassificationPipelineOptions} [options] The options to use for image classification.\n * @returns {Promise} An array or object containing the predicted labels and scores.\n * \n * @typedef {ImagePipelineConstructorArgs & ImageClassificationPipelineCallback & Disposable} ImageClassificationPipelineType\n */\n\n/**\n * Image classification pipeline using any `AutoModelForImageClassification`.\n * This pipeline predicts the class of an image.\n * \n * **Example:** Classify an image.\n * ```javascript\n * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';\n * const output = await classifier(url);\n * // [\n * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 },\n * // ]\n * ```\n * \n * **Example:** Classify an image and return top `n` classes.\n * ```javascript\n * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';\n * const output = await classifier(url, { top_k: 3 });\n * // [\n * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 },\n * // { label: 'tiger cat', score: 0.3634825646877289 },\n * // { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 },\n * // ]\n * ```\n * \n * **Example:** Classify an image and return all classes.\n * ```javascript\n * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';\n * const output = await classifier(url, { top_k: 0 });\n * // [\n * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 },\n * // { label: 'tiger cat', score: 0.3634825646877289 },\n * // { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 },\n * // { label: 'jaguar, panther, Panthera onca, Felis onca', score: 0.00035465499968267977 },\n * // ...\n * // ]\n * ```\n */\nexport class ImageClassificationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ImageClassificationPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ImageClassificationPipelineCallback} */\n async _call(images, {\n top_k = 5\n } = {}) {\n\n const preparedImages = await prepareImages(images);\n\n const { pixel_values } = await this.processor(preparedImages);\n const output = await this.model({ pixel_values });\n\n const id2label = this.model.config.id2label;\n\n /** @type {ImageClassificationOutput[]} */\n const toReturn = [];\n for (const batch of output.logits) {\n const scores = await topk(new Tensor(\n 'float32',\n softmax(batch.data),\n batch.dims,\n ), top_k);\n\n const values = scores[0].tolist();\n const indices = scores[1].tolist();\n\n const vals = indices.map((x, i) => ({\n label: /** @type {string} */ (id2label ? id2label[x] : `LABEL_${x}`),\n score: /** @type {number} */ (values[i]),\n }));\n toReturn.push(vals);\n }\n\n return Array.isArray(images) ? toReturn : toReturn[0];\n }\n\n}\n\n/**\n * @typedef {Object} ImageSegmentationPipelineOutput\n * @property {string} label The label of the segment.\n * @property {number|null} score The score of the segment.\n * @property {RawImage} mask The mask of the segment.\n * \n * @typedef {Object} ImageSegmentationPipelineOptions Parameters specific to image segmentation pipelines.\n * @property {number} [threshold=0.5] Probability threshold to filter out predicted masks.\n * @property {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values.\n * @property {number} [overlap_mask_area_threshold=0.8] Mask overlap threshold to eliminate small, disconnected segments.\n * @property {null|string} [subtask=null] Segmentation task to be performed. One of [`panoptic`, `instance`, and `semantic`],\n * depending on model capabilities. If not set, the pipeline will attempt to resolve (in that order).\n * @property {number[]} [label_ids_to_fuse=null] List of label ids to fuse. If not set, do not fuse any labels.\n * @property {number[][]} [target_sizes=null] List of target sizes for the input images. If not set, use the original image sizes.\n * \n * @callback ImageSegmentationPipelineCallback Segment the input images.\n * @param {ImagePipelineInputs} images The input images.\n * @param {ImageSegmentationPipelineOptions} [options] The options to use for image segmentation.\n * @returns {Promise} The annotated segments.\n * \n * @typedef {ImagePipelineConstructorArgs & ImageSegmentationPipelineCallback & Disposable} ImageSegmentationPipelineType\n */\n\n/**\n * Image segmentation pipeline using any `AutoModelForXXXSegmentation`.\n * This pipeline predicts masks of objects and their classes.\n * \n * **Example:** Perform image segmentation with `Xenova/detr-resnet-50-panoptic`.\n * ```javascript\n * const segmenter = await pipeline('image-segmentation', 'Xenova/detr-resnet-50-panoptic');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';\n * const output = await segmenter(url);\n * // [\n * // { label: 'remote', score: 0.9984649419784546, mask: RawImage { ... } },\n * // { label: 'cat', score: 0.9994316101074219, mask: RawImage { ... } }\n * // ]\n * ```\n */\nexport class ImageSegmentationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageSegmentationPipelineType} */ (Pipeline)) {\n /**\n * Create a new ImageSegmentationPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n\n this.subtasks_mapping = {\n // Mapping of subtasks to their corresponding post-processing function names.\n panoptic: 'post_process_panoptic_segmentation',\n instance: 'post_process_instance_segmentation',\n semantic: 'post_process_semantic_segmentation'\n }\n }\n\n /** @type {ImageSegmentationPipelineCallback} */\n async _call(images, {\n threshold = 0.5,\n mask_threshold = 0.5,\n overlap_mask_area_threshold = 0.8,\n label_ids_to_fuse = null,\n target_sizes = null,\n subtask = null,\n } = {}) {\n const isBatched = Array.isArray(images);\n\n if (isBatched && images.length !== 1) {\n throw Error(\"Image segmentation pipeline currently only supports a batch size of 1.\");\n }\n\n const preparedImages = await prepareImages(images);\n const imageSizes = preparedImages.map(x => [x.height, x.width]);\n\n const { pixel_values, pixel_mask } = await this.processor(preparedImages);\n const output = await this.model({ pixel_values, pixel_mask });\n\n let fn = null;\n if (subtask !== null) {\n fn = this.subtasks_mapping[subtask];\n } else {\n for (let [task, func] of Object.entries(this.subtasks_mapping)) {\n if (func in this.processor.feature_extractor) {\n fn = this.processor.feature_extractor[func].bind(this.processor.feature_extractor);\n subtask = task;\n break;\n }\n }\n }\n\n const id2label = this.model.config.id2label;\n\n /** @type {ImageSegmentationPipelineOutput[]} */\n const annotation = [];\n if (subtask === 'panoptic' || subtask === 'instance') {\n const processed = fn(\n output,\n threshold,\n mask_threshold,\n overlap_mask_area_threshold,\n label_ids_to_fuse,\n target_sizes ?? imageSizes, // TODO FIX?\n )[0];\n\n const segmentation = processed.segmentation;\n\n for (const segment of processed.segments_info) {\n const maskData = new Uint8ClampedArray(segmentation.data.length);\n for (let i = 0; i < segmentation.data.length; ++i) {\n if (segmentation.data[i] === segment.id) {\n maskData[i] = 255;\n }\n }\n\n const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1)\n\n annotation.push({\n score: segment.score,\n label: id2label[segment.label_id],\n mask: mask\n })\n }\n\n } else if (subtask === 'semantic') {\n const { segmentation, labels } = fn(output, target_sizes ?? imageSizes)[0];\n\n for (const label of labels) {\n const maskData = new Uint8ClampedArray(segmentation.data.length);\n for (let i = 0; i < segmentation.data.length; ++i) {\n if (segmentation.data[i] === label) {\n maskData[i] = 255;\n }\n }\n\n const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1);\n\n annotation.push({\n score: null,\n label: id2label[label],\n mask: mask\n });\n }\n } else {\n throw Error(`Subtask ${subtask} not supported.`);\n }\n\n return annotation;\n }\n}\n\n/**\n * @typedef {Object} ZeroShotImageClassificationOutput\n * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`.\n * @property {number} score The score attributed by the model for that label (between 0 and 1).\n * \n * @typedef {Object} ZeroShotImageClassificationPipelineOptions Parameters specific to zero-shot image classification pipelines.\n * @property {string} [hypothesis_template=\"This is a photo of {}\"] The sentence used in conjunction with `candidate_labels`\n * to attempt the image classification by replacing the placeholder with the candidate_labels.\n * Then likelihood is estimated by using `logits_per_image`.\n * \n * @callback ZeroShotImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The input images.\n * @param {string[]} candidate_labels The candidate labels for this image.\n * @param {ZeroShotImageClassificationPipelineOptions} [options] The options to use for zero-shot image classification.\n * @returns {Promise} An array of objects containing the predicted labels and scores.\n * \n * @typedef {TextImagePipelineConstructorArgs & ZeroShotImageClassificationPipelineCallback & Disposable} ZeroShotImageClassificationPipelineType\n */\n\n/**\n * Zero shot image classification pipeline. This pipeline predicts the class of\n * an image when you provide an image and a set of `candidate_labels`.\n * \n * **Example:** Zero shot image classification w/ `Xenova/clip-vit-base-patch32`.\n * ```javascript\n * const classifier = await pipeline('zero-shot-image-classification', 'Xenova/clip-vit-base-patch32');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';\n * const output = await classifier(url, ['tiger', 'horse', 'dog']);\n * // [\n * // { score: 0.9993917942047119, label: 'tiger' },\n * // { score: 0.0003519294841680676, label: 'horse' },\n * // { score: 0.0002562698791734874, label: 'dog' }\n * // ]\n * ```\n */\nexport class ZeroShotImageClassificationPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotImageClassificationPipelineType} */ (Pipeline)) {\n /**\n * Create a new ZeroShotImageClassificationPipeline.\n * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ZeroShotImageClassificationPipelineCallback} */\n async _call(images, candidate_labels, {\n hypothesis_template = \"This is a photo of {}\"\n } = {}) {\n\n const isBatched = Array.isArray(images);\n const preparedImages = await prepareImages(images);\n\n // Insert label into hypothesis template \n const texts = candidate_labels.map(\n x => hypothesis_template.replace('{}', x)\n );\n\n // Run tokenization\n const text_inputs = this.tokenizer(texts, {\n padding: this.model.config.model_type === 'siglip' ? 'max_length' : true,\n truncation: true,\n });\n\n // Run processor\n const { pixel_values } = await this.processor(preparedImages);\n\n // Run model with both text and pixel inputs\n const output = await this.model({ ...text_inputs, pixel_values });\n\n const function_to_apply =\n this.model.config.model_type === 'siglip'\n ? batch => batch.sigmoid().data\n : batch => softmax(batch.data);\n\n // Compare each image with each candidate label\n const toReturn = [];\n for (const batch of output.logits_per_image) {\n // Compute softmax per image\n const probs = function_to_apply(batch);\n\n const result = [...probs].map((x, i) => ({\n score: x,\n label: candidate_labels[i]\n }));\n result.sort((a, b) => b.score - a.score); // sort by score in descending order\n toReturn.push(result);\n }\n\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n\n/**\n * @typedef {Object} ObjectDetectionPipelineSingle\n * @property {string} label The class label identified by the model.\n * @property {number} score The score attributed by the model for that label.\n * @property {BoundingBox} box The bounding box of detected object in image's original size, or as a percentage if `percentage` is set to true.\n * @typedef {ObjectDetectionPipelineSingle[]} ObjectDetectionPipelineOutput\n * \n * @typedef {Object} ObjectDetectionPipelineOptions Parameters specific to object detection pipelines.\n * @property {number} [threshold=0.9] The threshold used to filter boxes by score.\n * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false).\n * \n * @callback ObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The input images.\n * @param {ObjectDetectionPipelineOptions} [options] The options to use for object detection.\n * @returns {Promise} A list of objects or a list of list of objects. \n * \n * @typedef {ImagePipelineConstructorArgs & ObjectDetectionPipelineCallback & Disposable} ObjectDetectionPipelineType\n */\n\n/**\n * Object detection pipeline using any `AutoModelForObjectDetection`.\n * This pipeline predicts bounding boxes of objects and their classes.\n * \n * **Example:** Run object-detection with `Xenova/detr-resnet-50`.\n * ```javascript\n * const detector = await pipeline('object-detection', 'Xenova/detr-resnet-50');\n * const img = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';\n * const output = await detector(img, { threshold: 0.9 });\n * // [{\n * // score: 0.9976370930671692,\n * // label: \"remote\",\n * // box: { xmin: 31, ymin: 68, xmax: 190, ymax: 118 }\n * // },\n * // ...\n * // {\n * // score: 0.9984092116355896,\n * // label: \"cat\",\n * // box: { xmin: 331, ymin: 19, xmax: 649, ymax: 371 }\n * // }]\n * ```\n */\nexport class ObjectDetectionPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ObjectDetectionPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ObjectDetectionPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ObjectDetectionPipelineCallback} */\n async _call(images, {\n threshold = 0.9,\n percentage = false,\n } = {}) {\n\n const isBatched = Array.isArray(images);\n\n if (isBatched && images.length !== 1) {\n throw Error(\"Object detection pipeline currently only supports a batch size of 1.\");\n }\n const preparedImages = await prepareImages(images);\n\n const imageSizes = percentage ? null : preparedImages.map(x => [x.height, x.width]);\n\n const { pixel_values, pixel_mask } = await this.processor(preparedImages);\n const output = await this.model({ pixel_values, pixel_mask });\n\n // @ts-ignore\n const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSizes);\n\n // Add labels\n const id2label = this.model.config.id2label;\n\n // Format output\n /** @type {ObjectDetectionPipelineOutput[]} */\n const result = processed.map(batch => (\n batch.boxes.map((box, i) => ({\n score: batch.scores[i],\n label: id2label[batch.classes[i]],\n box: get_bounding_box(box, !percentage),\n }))\n ))\n\n return isBatched ? result : result[0];\n }\n}\n\n\n/**\n * @typedef {Object} ZeroShotObjectDetectionOutput\n * @property {string} label Text query corresponding to the found object.\n * @property {number} score Score corresponding to the object (between 0 and 1).\n * @property {BoundingBox} box Bounding box of the detected object in image's original size, or as a percentage if `percentage` is set to true.\n * \n * @typedef {Object} ZeroShotObjectDetectionPipelineOptions Parameters specific to zero-shot object detection pipelines.\n * @property {number} [threshold=0.1] The probability necessary to make a prediction.\n * @property {number} [top_k=null] The number of top predictions that will be returned by the pipeline.\n * If the provided number is `null` or higher than the number of predictions available, it will default\n * to the number of predictions.\n * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false).\n * \n * @callback ZeroShotObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The input images.\n * @param {string[]} candidate_labels What the model should recognize in the image.\n * @param {ZeroShotObjectDetectionPipelineOptions} [options] The options to use for zero-shot object detection.\n * @returns {Promise} An array of objects containing the predicted labels, scores, and bounding boxes.\n * \n * @typedef {TextImagePipelineConstructorArgs & ZeroShotObjectDetectionPipelineCallback & Disposable} ZeroShotObjectDetectionPipelineType\n */\n\n/**\n * Zero-shot object detection pipeline. This pipeline predicts bounding boxes of\n * objects when you provide an image and a set of `candidate_labels`.\n * \n * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32`.\n * ```javascript\n * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/astronaut.png';\n * const candidate_labels = ['human face', 'rocket', 'helmet', 'american flag'];\n * const output = await detector(url, candidate_labels);\n * // [\n * // {\n * // score: 0.24392342567443848,\n * // label: 'human face',\n * // box: { xmin: 180, ymin: 67, xmax: 274, ymax: 175 }\n * // },\n * // {\n * // score: 0.15129457414150238,\n * // label: 'american flag',\n * // box: { xmin: 0, ymin: 4, xmax: 106, ymax: 513 }\n * // },\n * // {\n * // score: 0.13649864494800568,\n * // label: 'helmet',\n * // box: { xmin: 277, ymin: 337, xmax: 511, ymax: 511 }\n * // },\n * // {\n * // score: 0.10262022167444229,\n * // label: 'rocket',\n * // box: { xmin: 352, ymin: -1, xmax: 463, ymax: 287 }\n * // }\n * // ]\n * ```\n * \n * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32` (returning top 4 matches and setting a threshold).\n * ```javascript\n * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/beach.png';\n * const candidate_labels = ['hat', 'book', 'sunglasses', 'camera'];\n * const output = await detector(url, candidate_labels, { top_k: 4, threshold: 0.05 });\n * // [\n * // {\n * // score: 0.1606510728597641,\n * // label: 'sunglasses',\n * // box: { xmin: 347, ymin: 229, xmax: 429, ymax: 264 }\n * // },\n * // {\n * // score: 0.08935828506946564,\n * // label: 'hat',\n * // box: { xmin: 38, ymin: 174, xmax: 258, ymax: 364 }\n * // },\n * // {\n * // score: 0.08530698716640472,\n * // label: 'camera',\n * // box: { xmin: 187, ymin: 350, xmax: 260, ymax: 411 }\n * // },\n * // {\n * // score: 0.08349756896495819,\n * // label: 'book',\n * // box: { xmin: 261, ymin: 280, xmax: 494, ymax: 425 }\n * // }\n * // ]\n * ```\n */\nexport class ZeroShotObjectDetectionPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotObjectDetectionPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ZeroShotObjectDetectionPipeline.\n * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ZeroShotObjectDetectionPipelineCallback} */\n async _call(images, candidate_labels, {\n threshold = 0.1,\n top_k = null,\n percentage = false,\n } = {}) {\n\n const isBatched = Array.isArray(images);\n const preparedImages = await prepareImages(images);\n\n // Run tokenization\n const text_inputs = this.tokenizer(candidate_labels, {\n padding: true,\n truncation: true,\n });\n\n // Run processor\n const model_inputs = await this.processor(preparedImages);\n\n // Since non-maximum suppression is performed for exporting, we need to\n // process each image separately. For more information, see:\n // https://github.com/huggingface/optimum/blob/e3b7efb1257c011db907ef40ab340e795cc5684c/optimum/exporters/onnx/model_configs.py#L1028-L1032\n const toReturn = [];\n for (let i = 0; i < preparedImages.length; ++i) {\n const image = preparedImages[i];\n const imageSize = percentage ? null : [[image.height, image.width]];\n const pixel_values = model_inputs.pixel_values[i].unsqueeze_(0);\n\n // Run model with both text and pixel inputs\n const output = await this.model({ ...text_inputs, pixel_values });\n\n // @ts-ignore\n const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSize, true)[0];\n let result = processed.boxes.map((box, i) => ({\n score: processed.scores[i],\n label: candidate_labels[processed.classes[i]],\n box: get_bounding_box(box, !percentage),\n })).sort((a, b) => b.score - a.score);\n if (top_k !== null) {\n result = result.slice(0, top_k);\n }\n toReturn.push(result)\n }\n\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} DocumentQuestionAnsweringSingle\n * @property {string} answer The generated text.\n * @typedef {DocumentQuestionAnsweringSingle[]} DocumentQuestionAnsweringOutput\n * \n * @callback DocumentQuestionAnsweringPipelineCallback Answer the question given as input by using the document.\n * @param {ImageInput} image The image of the document to use.\n * @param {string} question A question to ask of the document.\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise} An object (or array of objects) containing the answer(s).\n * \n * @typedef {TextImagePipelineConstructorArgs & DocumentQuestionAnsweringPipelineCallback & Disposable} DocumentQuestionAnsweringPipelineType\n */\n\n/**\n * Document Question Answering pipeline using any `AutoModelForDocumentQuestionAnswering`.\n * The inputs/outputs are similar to the (extractive) question answering pipeline; however,\n * the pipeline takes an image (and optional OCR'd words/boxes) as input instead of text context.\n * \n * **Example:** Answer questions about a document with `Xenova/donut-base-finetuned-docvqa`.\n * ```javascript\n * const qa_pipeline = await pipeline('document-question-answering', 'Xenova/donut-base-finetuned-docvqa');\n * const image = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/invoice.png';\n * const question = 'What is the invoice number?';\n * const output = await qa_pipeline(image, question);\n * // [{ answer: 'us-001' }]\n * ```\n */\nexport class DocumentQuestionAnsweringPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => DocumentQuestionAnsweringPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new DocumentQuestionAnsweringPipeline.\n * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {DocumentQuestionAnsweringPipelineCallback} */\n async _call(image, question, generate_kwargs = {}) {\n throw new Error('This pipeline is not yet supported in Transformers.js v3.'); // TODO: Remove when implemented\n\n // NOTE: For now, we only support a batch size of 1\n\n // Preprocess image\n const preparedImage = (await prepareImages(image))[0];\n const { pixel_values } = await this.processor(preparedImage);\n\n // Run tokenization\n const task_prompt = `${question}`;\n const decoder_input_ids = this.tokenizer(task_prompt, {\n add_special_tokens: false,\n padding: true,\n truncation: true,\n }).input_ids;\n\n // Run model\n const output = await this.model.generate({\n inputs: pixel_values,\n max_length: this.model.config.decoder.max_position_embeddings,\n decoder_input_ids,\n ...generate_kwargs,\n });\n\n // Decode output\n const decoded = this.tokenizer.batch_decode(/** @type {Tensor} */(output))[0];\n\n // Parse answer\n const match = decoded.match(/(.*?)<\\/s_answer>/);\n let answer = null;\n if (match && match.length >= 2) {\n answer = match[1].trim();\n }\n return [{ answer }];\n }\n}\n\n\n/**\n * @typedef {Object} VocoderOptions\n * @property {PreTrainedModel} [vocoder] The vocoder used by the pipeline (if the model uses one). If not provided, use the default HifiGan vocoder.\n * @typedef {TextAudioPipelineConstructorArgs & VocoderOptions} TextToAudioPipelineConstructorArgs\n */\n\n/**\n * @typedef {Object} TextToAudioOutput\n * @property {Float32Array} audio The generated audio waveform.\n * @property {number} sampling_rate The sampling rate of the generated audio waveform.\n * \n * @typedef {Object} TextToAudioPipelineOptions Parameters specific to text-to-audio pipelines.\n * @property {Tensor|Float32Array|string|URL} [speaker_embeddings=null] The speaker embeddings (if the model requires it).\n * \n * @callback TextToAudioPipelineCallback Generates speech/audio from the inputs.\n * @param {string|string[]} texts The text(s) to generate.\n * @param {TextToAudioPipelineOptions} options Parameters passed to the model generation/forward method.\n * @returns {Promise} An object containing the generated audio and sampling rate.\n * \n * @typedef {TextToAudioPipelineConstructorArgs & TextToAudioPipelineCallback & Disposable} TextToAudioPipelineType\n */\n\n/**\n * Text-to-audio generation pipeline using any `AutoModelForTextToWaveform` or `AutoModelForTextToSpectrogram`.\n * This pipeline generates an audio file from an input text and optional other conditional inputs.\n * \n * **Example:** Generate audio from text with `Xenova/speecht5_tts`.\n * ```javascript\n * const synthesizer = await pipeline('text-to-speech', 'Xenova/speecht5_tts', { quantized: false });\n * const speaker_embeddings = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin';\n * const out = await synthesizer('Hello, my dog is cute', { speaker_embeddings });\n * // {\n * // audio: Float32Array(26112) [-0.00005657337896991521, 0.00020583874720614403, ...],\n * // sampling_rate: 16000\n * // }\n * ```\n * \n * You can then save the audio to a .wav file with the `wavefile` package:\n * ```javascript\n * import wavefile from 'wavefile';\n * import fs from 'fs';\n * \n * const wav = new wavefile.WaveFile();\n * wav.fromScratch(1, out.sampling_rate, '32f', out.audio);\n * fs.writeFileSync('out.wav', wav.toBuffer());\n * ```\n * \n * **Example:** Multilingual speech generation with `Xenova/mms-tts-fra`. See [here](https://huggingface.co/models?pipeline_tag=text-to-speech&other=vits&sort=trending) for the full list of available languages (1107).\n * ```javascript\n * const synthesizer = await pipeline('text-to-speech', 'Xenova/mms-tts-fra');\n * const out = await synthesizer('Bonjour');\n * // {\n * // audio: Float32Array(23808) [-0.00037693005288019776, 0.0003325853613205254, ...],\n * // sampling_rate: 16000\n * // }\n * ```\n */\nexport class TextToAudioPipeline extends (/** @type {new (options: TextToAudioPipelineConstructorArgs) => TextToAudioPipelineType} */ (Pipeline)) {\n DEFAULT_VOCODER_ID = \"Xenova/speecht5_hifigan\"\n\n /**\n * Create a new TextToAudioPipeline.\n * @param {TextToAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n\n // TODO: Find a better way for `pipeline` to set the default vocoder\n this.vocoder = options.vocoder ?? null;\n }\n\n\n /** @type {TextToAudioPipelineCallback} */\n async _call(text_inputs, {\n speaker_embeddings = null,\n } = {}) {\n\n // If this.processor is not set, we are using a `AutoModelForTextToWaveform` model\n if (this.processor) {\n return this._call_text_to_spectrogram(text_inputs, { speaker_embeddings });\n } else {\n return this._call_text_to_waveform(text_inputs);\n }\n }\n\n async _call_text_to_waveform(text_inputs) {\n\n // Run tokenization\n const inputs = this.tokenizer(text_inputs, {\n padding: true,\n truncation: true,\n });\n\n // Generate waveform\n const { waveform } = await this.model(inputs);\n\n const sampling_rate = this.model.config.sampling_rate;\n return {\n audio: waveform.data,\n sampling_rate,\n }\n }\n\n async _call_text_to_spectrogram(text_inputs, { speaker_embeddings }) {\n\n // Load vocoder, if not provided\n if (!this.vocoder) {\n console.log('No vocoder specified, using default HifiGan vocoder.');\n this.vocoder = await AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID, { dtype: 'fp32' });\n }\n\n // Load speaker embeddings as Float32Array from path/URL\n if (typeof speaker_embeddings === 'string' || speaker_embeddings instanceof URL) {\n // Load from URL with fetch\n speaker_embeddings = new Float32Array(\n await (await fetch(speaker_embeddings)).arrayBuffer()\n );\n }\n\n if (speaker_embeddings instanceof Float32Array) {\n speaker_embeddings = new Tensor(\n 'float32',\n speaker_embeddings,\n [1, speaker_embeddings.length]\n )\n } else if (!(speaker_embeddings instanceof Tensor)) {\n throw new Error(\"Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.\")\n }\n\n // Run tokenization\n const { input_ids } = this.tokenizer(text_inputs, {\n padding: true,\n truncation: true,\n });\n\n // NOTE: At this point, we are guaranteed that `speaker_embeddings` is a `Tensor`\n // @ts-ignore\n const { waveform } = await this.model.generate_speech(input_ids, speaker_embeddings, { vocoder: this.vocoder });\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n return {\n audio: waveform.data,\n sampling_rate,\n }\n }\n}\n\n/**\n * @callback ImageToImagePipelineCallback Transform the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The images to transform.\n * @returns {Promise} The transformed image or list of images.\n * \n * @typedef {ImagePipelineConstructorArgs & ImageToImagePipelineCallback & Disposable} ImageToImagePipelineType\n */\n\n/**\n * Image to Image pipeline using any `AutoModelForImageToImage`. This pipeline generates an image based on a previous image input.\n * \n * **Example:** Super-resolution w/ `Xenova/swin2SR-classical-sr-x2-64`\n * ```javascript\n * const upscaler = await pipeline('image-to-image', 'Xenova/swin2SR-classical-sr-x2-64');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg';\n * const output = await upscaler(url);\n * // RawImage {\n * // data: Uint8Array(786432) [ 41, 31, 24, 43, ... ],\n * // width: 512,\n * // height: 512,\n * // channels: 3\n * // }\n * ```\n */\nexport class ImageToImagePipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageToImagePipelineType} */ (Pipeline)) {\n /**\n * Create a new ImageToImagePipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ImageToImagePipelineCallback} */\n async _call(images) {\n\n const preparedImages = await prepareImages(images);\n const inputs = await this.processor(preparedImages);\n const outputs = await this.model(inputs);\n\n /** @type {RawImage[]} */\n const toReturn = [];\n for (const batch of outputs.reconstruction) {\n const output = batch.squeeze().clamp_(0, 1).mul_(255).round_().to('uint8');\n toReturn.push(RawImage.fromTensor(output));\n }\n\n return toReturn.length > 1 ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} DepthEstimationPipelineOutput\n * @property {Tensor} predicted_depth The raw depth map predicted by the model.\n * @property {RawImage} depth The processed depth map as an image (with the same size as the input image).\n * \n * @callback DepthEstimationPipelineCallback Predicts the depth for the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The images to compute depth for.\n * @returns {Promise} An image or a list of images containing result(s).\n * \n * @typedef {ImagePipelineConstructorArgs & DepthEstimationPipelineCallback & Disposable} DepthEstimationPipelineType\n */\n\n/**\n * Depth estimation pipeline using any `AutoModelForDepthEstimation`. This pipeline predicts the depth of an image.\n * \n * **Example:** Depth estimation w/ `Xenova/dpt-hybrid-midas`\n * ```javascript\n * const depth_estimator = await pipeline('depth-estimation', 'Xenova/dpt-hybrid-midas');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';\n * const out = await depth_estimator(url);\n * // {\n * // predicted_depth: Tensor {\n * // dims: [ 384, 384 ],\n * // type: 'float32',\n * // data: Float32Array(147456) [ 542.859130859375, 545.2833862304688, 546.1649169921875, ... ],\n * // size: 147456\n * // },\n * // depth: RawImage {\n * // data: Uint8Array(307200) [ 86, 86, 86, ... ],\n * // width: 640,\n * // height: 480,\n * // channels: 1\n * // }\n * // }\n * ```\n */\nexport class DepthEstimationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => DepthEstimationPipelineType} */ (Pipeline)) {\n /**\n * Create a new DepthEstimationPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {DepthEstimationPipelineCallback} */\n async _call(images) {\n\n const preparedImages = await prepareImages(images);\n\n const inputs = await this.processor(preparedImages);\n const { predicted_depth } = await this.model(inputs);\n\n const toReturn = [];\n for (let i = 0; i < preparedImages.length; ++i) {\n const prediction = interpolate(predicted_depth[i], preparedImages[i].size.reverse(), 'bilinear', false);\n const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8');\n toReturn.push({\n predicted_depth: predicted_depth[i],\n depth: RawImage.fromTensor(formatted),\n });\n }\n\n return toReturn.length > 1 ? toReturn : toReturn[0];\n }\n}\n\nconst SUPPORTED_TASKS = Object.freeze({\n \"text-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TextClassificationPipeline,\n \"model\": AutoModelForSequenceClassification,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"distilbert-base-uncased-finetuned-sst-2-english\",\n \"model\": \"Xenova/distilbert-base-uncased-finetuned-sst-2-english\",\n },\n \"type\": \"text\",\n },\n \"token-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TokenClassificationPipeline,\n \"model\": AutoModelForTokenClassification,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"Davlan/bert-base-multilingual-cased-ner-hrl\",\n \"model\": \"Xenova/bert-base-multilingual-cased-ner-hrl\",\n },\n \"type\": \"text\",\n },\n \"question-answering\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": QuestionAnsweringPipeline,\n \"model\": AutoModelForQuestionAnswering,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"distilbert-base-cased-distilled-squad\",\n \"model\": \"Xenova/distilbert-base-cased-distilled-squad\",\n },\n \"type\": \"text\",\n },\n\n \"fill-mask\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": FillMaskPipeline,\n \"model\": AutoModelForMaskedLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"bert-base-uncased\",\n \"model\": \"Xenova/bert-base-uncased\",\n },\n \"type\": \"text\",\n },\n \"summarization\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": SummarizationPipeline,\n \"model\": AutoModelForSeq2SeqLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"sshleifer/distilbart-cnn-6-6\",\n \"model\": \"Xenova/distilbart-cnn-6-6\",\n },\n \"type\": \"text\",\n },\n \"translation\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TranslationPipeline,\n \"model\": AutoModelForSeq2SeqLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"t5-small\",\n \"model\": \"Xenova/t5-small\",\n },\n \"type\": \"text\",\n },\n \"text2text-generation\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": Text2TextGenerationPipeline,\n \"model\": AutoModelForSeq2SeqLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"google/flan-t5-small\",\n \"model\": \"Xenova/flan-t5-small\",\n },\n \"type\": \"text\",\n },\n \"text-generation\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TextGenerationPipeline,\n \"model\": AutoModelForCausalLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"gpt2\",\n \"model\": \"Xenova/gpt2\",\n },\n \"type\": \"text\",\n },\n \"zero-shot-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ZeroShotClassificationPipeline,\n \"model\": AutoModelForSequenceClassification,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"typeform/distilbert-base-uncased-mnli\",\n \"model\": \"Xenova/distilbert-base-uncased-mnli\",\n },\n \"type\": \"text\",\n },\n \"audio-classification\": {\n \"pipeline\": AudioClassificationPipeline,\n \"model\": AutoModelForAudioClassification,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"superb/wav2vec2-base-superb-ks\",\n \"model\": \"Xenova/wav2vec2-base-superb-ks\",\n },\n \"type\": \"audio\",\n },\n \"zero-shot-audio-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ZeroShotAudioClassificationPipeline,\n \"model\": AutoModel,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"laion/clap-htsat-fused\",\n \"model\": \"Xenova/clap-htsat-unfused\",\n },\n \"type\": \"multimodal\",\n },\n \"automatic-speech-recognition\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": AutomaticSpeechRecognitionPipeline,\n \"model\": [AutoModelForSpeechSeq2Seq, AutoModelForCTC],\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"openai/whisper-tiny.en\",\n \"model\": \"Xenova/whisper-tiny.en\",\n },\n \"type\": \"multimodal\",\n },\n \"text-to-audio\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TextToAudioPipeline,\n \"model\": [AutoModelForTextToWaveform, AutoModelForTextToSpectrogram],\n \"processor\": [AutoProcessor, /* Some don't use a processor */ null],\n \"default\": {\n // TODO: replace with original\n // \"model\": \"microsoft/speecht5_tts\",\n \"model\": \"Xenova/speecht5_tts\",\n },\n \"type\": \"text\",\n },\n \"image-to-text\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ImageToTextPipeline,\n \"model\": AutoModelForVision2Seq,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"nlpconnect/vit-gpt2-image-captioning\",\n \"model\": \"Xenova/vit-gpt2-image-captioning\",\n },\n \"type\": \"multimodal\",\n },\n\n \"image-classification\": {\n // no tokenizer\n \"pipeline\": ImageClassificationPipeline,\n \"model\": AutoModelForImageClassification,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"google/vit-base-patch16-224\",\n \"model\": \"Xenova/vit-base-patch16-224\",\n },\n \"type\": \"multimodal\",\n },\n\n \"image-segmentation\": {\n // no tokenizer\n \"pipeline\": ImageSegmentationPipeline,\n \"model\": [AutoModelForImageSegmentation, AutoModelForSemanticSegmentation, AutoModelForUniversalSegmentation],\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"facebook/detr-resnet-50-panoptic\",\n \"model\": \"Xenova/detr-resnet-50-panoptic\",\n },\n \"type\": \"multimodal\",\n },\n\n \"zero-shot-image-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ZeroShotImageClassificationPipeline,\n \"model\": AutoModel,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"openai/clip-vit-base-patch32\",\n \"model\": \"Xenova/clip-vit-base-patch32\",\n },\n \"type\": \"multimodal\",\n },\n\n \"object-detection\": {\n // no tokenizer\n \"pipeline\": ObjectDetectionPipeline,\n \"model\": AutoModelForObjectDetection,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"facebook/detr-resnet-50\",\n \"model\": \"Xenova/detr-resnet-50\",\n },\n \"type\": \"multimodal\",\n },\n \"zero-shot-object-detection\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ZeroShotObjectDetectionPipeline,\n \"model\": AutoModelForZeroShotObjectDetection,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"google/owlvit-base-patch32\",\n \"model\": \"Xenova/owlvit-base-patch32\",\n },\n \"type\": \"multimodal\",\n },\n \"document-question-answering\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": DocumentQuestionAnsweringPipeline,\n \"model\": AutoModelForDocumentQuestionAnswering,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"naver-clova-ix/donut-base-finetuned-docvqa\",\n \"model\": \"Xenova/donut-base-finetuned-docvqa\",\n },\n \"type\": \"multimodal\",\n },\n \"image-to-image\": {\n // no tokenizer\n \"pipeline\": ImageToImagePipeline,\n \"model\": AutoModelForImageToImage,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"caidas/swin2SR-classical-sr-x2-64\",\n \"model\": \"Xenova/swin2SR-classical-sr-x2-64\",\n },\n \"type\": \"image\",\n },\n \"depth-estimation\": {\n // no tokenizer\n \"pipeline\": DepthEstimationPipeline,\n \"model\": AutoModelForDepthEstimation,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"Intel/dpt-large\",\n \"model\": \"Xenova/dpt-large\",\n },\n \"type\": \"image\",\n },\n\n // This task serves as a useful interface for dealing with sentence-transformers (https://huggingface.co/sentence-transformers).\n \"feature-extraction\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": FeatureExtractionPipeline,\n \"model\": AutoModel,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"sentence-transformers/all-MiniLM-L6-v2\",\n \"model\": \"Xenova/all-MiniLM-L6-v2\",\n },\n \"type\": \"text\",\n },\n \"image-feature-extraction\": {\n \"processor\": AutoProcessor,\n \"pipeline\": ImageFeatureExtractionPipeline,\n \"model\": [AutoModelForImageFeatureExtraction, AutoModel],\n \"default\": {\n // TODO: replace with original\n // \"model\": \"google/vit-base-patch16-224\",\n \"model\": \"Xenova/vit-base-patch16-224-in21k\",\n },\n \"type\": \"image\",\n },\n})\n\n\n// TODO: Add types for TASK_ALIASES\nconst TASK_ALIASES = Object.freeze({\n \"sentiment-analysis\": \"text-classification\",\n \"ner\": \"token-classification\",\n // \"vqa\": \"visual-question-answering\", // TODO: Add\n \"asr\": \"automatic-speech-recognition\",\n \"text-to-speech\": \"text-to-audio\",\n\n // Add for backwards compatibility\n \"embeddings\": \"feature-extraction\",\n});\n\n/**\n * @typedef {keyof typeof SUPPORTED_TASKS} TaskType\n * @typedef {keyof typeof TASK_ALIASES} AliasType\n * @typedef {TaskType | AliasType} PipelineType All possible pipeline types.\n * @typedef {{[K in TaskType]: InstanceType}} SupportedTasks A mapping of pipeline names to their corresponding pipeline classes.\n * @typedef {{[K in AliasType]: InstanceType}} AliasTasks A mapping from pipeline aliases to their corresponding pipeline classes.\n * @typedef {SupportedTasks & AliasTasks} AllTasks A mapping from all pipeline names and aliases to their corresponding pipeline classes.\n */\n\n/**\n * Utility factory method to build a `Pipeline` object.\n * \n * @template {PipelineType} T The type of pipeline to return.\n * @param {T} task The task defining which pipeline will be returned. Currently accepted tasks are:\n * - `\"audio-classification\"`: will return a `AudioClassificationPipeline`.\n * - `\"automatic-speech-recognition\"`: will return a `AutomaticSpeechRecognitionPipeline`.\n * - `\"depth-estimation\"`: will return a `DepthEstimationPipeline`.\n * - `\"document-question-answering\"`: will return a `DocumentQuestionAnsweringPipeline`.\n * - `\"feature-extraction\"`: will return a `FeatureExtractionPipeline`.\n * - `\"fill-mask\"`: will return a `FillMaskPipeline`.\n * - `\"image-classification\"`: will return a `ImageClassificationPipeline`.\n * - `\"image-segmentation\"`: will return a `ImageSegmentationPipeline`.\n * - `\"image-to-text\"`: will return a `ImageToTextPipeline`.\n * - `\"object-detection\"`: will return a `ObjectDetectionPipeline`.\n * - `\"question-answering\"`: will return a `QuestionAnsweringPipeline`.\n * - `\"summarization\"`: will return a `SummarizationPipeline`.\n * - `\"text2text-generation\"`: will return a `Text2TextGenerationPipeline`.\n * - `\"text-classification\"` (alias \"sentiment-analysis\" available): will return a `TextClassificationPipeline`.\n * - `\"text-generation\"`: will return a `TextGenerationPipeline`.\n * - `\"token-classification\"` (alias \"ner\" available): will return a `TokenClassificationPipeline`.\n * - `\"translation\"`: will return a `TranslationPipeline`.\n * - `\"translation_xx_to_yy\"`: will return a `TranslationPipeline`.\n * - `\"zero-shot-classification\"`: will return a `ZeroShotClassificationPipeline`.\n * - `\"zero-shot-audio-classification\"`: will return a `ZeroShotAudioClassificationPipeline`.\n * - `\"zero-shot-image-classification\"`: will return a `ZeroShotImageClassificationPipeline`.\n * - `\"zero-shot-object-detection\"`: will return a `ZeroShotObjectDetectionPipeline`.\n * @param {string} [model=null] The name of the pre-trained model to use. If not specified, the default model for the task will be used.\n * @param {import('./utils/hub.js').PretrainedModelOptions} [options] Optional parameters for the pipeline.\n * @returns {Promise} A Pipeline object for the specified task.\n * @throws {Error} If an unsupported pipeline is requested.\n */\nexport async function pipeline(\n task,\n model = null,\n {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n device = null,\n dtype = null,\n model_file_name = null,\n session_options = {},\n } = {}\n) {\n // Helper method to construct pipeline\n\n // Apply aliases\n // @ts-ignore\n task = TASK_ALIASES[task] ?? task;\n\n // Get pipeline info\n const pipelineInfo = SUPPORTED_TASKS[task.split('_', 1)[0]];\n if (!pipelineInfo) {\n throw Error(`Unsupported pipeline: ${task}. Must be one of [${Object.keys(SUPPORTED_TASKS)}]`)\n }\n\n // Use model if specified, otherwise, use default\n if (!model) {\n model = pipelineInfo.default.model\n console.log(`No model specified. Using default model: \"${model}\".`);\n }\n\n const pretrainedOptions = {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n device,\n dtype,\n model_file_name,\n session_options,\n }\n\n const classes = new Map([\n ['tokenizer', pipelineInfo.tokenizer],\n ['model', pipelineInfo.model],\n ['processor', pipelineInfo.processor],\n ]);\n\n // Load model, tokenizer, and processor (if they exist)\n const results = await loadItems(classes, model, pretrainedOptions);\n results.task = task;\n\n dispatchCallback(progress_callback, {\n 'status': 'ready',\n 'task': task,\n 'model': model,\n });\n\n const pipelineClass = pipelineInfo.pipeline;\n return new pipelineClass(results);\n}\n\n\n/**\n * Helper function to get applicable model, tokenizer, or processor classes for a given model.\n * @param {Map} mapping The mapping of names to classes, arrays of classes, or null.\n * @param {string} model The name of the model to load.\n * @param {import('./utils/hub.js').PretrainedOptions} pretrainedOptions The options to pass to the `from_pretrained` method.\n * @private\n */\nasync function loadItems(mapping, model, pretrainedOptions) {\n\n const result = Object.create(null);\n\n /**@type {Promise[]} */\n const promises = [];\n for (const [name, cls] of mapping.entries()) {\n if (!cls) continue;\n\n /**@type {Promise} */\n let promise;\n if (Array.isArray(cls)) {\n promise = new Promise(async (resolve, reject) => {\n let e;\n for (const c of cls) {\n if (c === null) {\n // If null, we resolve it immediately, meaning the relevant\n // class was not found, but it is optional.\n resolve(null);\n return;\n }\n try {\n resolve(await c.from_pretrained(model, pretrainedOptions));\n return;\n } catch (err) {\n if (err.message?.includes('Unsupported model type')) {\n // If the error is due to an unsupported model type, we\n // save the error and try the next class.\n e = err;\n } else if (err.message?.includes('Could not locate file')) {\n e = err;\n } else {\n reject(err);\n return;\n }\n\n }\n }\n reject(e);\n })\n } else {\n promise = cls.from_pretrained(model, pretrainedOptions);\n }\n\n result[name] = promise;\n promises.push(promise);\n }\n\n // Wait for all promises to resolve (in parallel)\n await Promise.all(promises);\n\n // Then assign to result\n for (const [name, promise] of Object.entries(result)) {\n result[name] = await promise;\n }\n\n return result;\n}","\n/**\n * @file Processors are used to prepare non-textual inputs (e.g., image or audio) for a model.\n * \n * **Example:** Using a `WhisperProcessor` to prepare an audio input for a model.\n * ```javascript\n * import { AutoProcessor, read_audio } from '@huggingface/transformers';\n *\n * let processor = await AutoProcessor.from_pretrained('openai/whisper-tiny.en');\n * let audio = await read_audio('https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac', 16000);\n * let { input_features } = await processor(audio);\n * // Tensor {\n * // data: Float32Array(240000) [0.4752984642982483, 0.5597258806228638, 0.56434166431427, ...],\n * // dims: [1, 80, 3000],\n * // type: 'float32',\n * // size: 240000,\n * // }\n * ```\n * \n * @module processors\n */\nimport {\n Callable,\n} from './utils/generic.js';\n\nimport {\n calculateDimensions,\n calculateReflectOffset,\n} from './utils/core.js';\n\nimport {\n getModelJSON,\n} from './utils/hub.js';\n\nimport {\n min,\n max,\n softmax,\n bankers_round,\n} from './utils/maths.js';\n\n\nimport { Tensor, cat, interpolate, stack, interpolate_4d, full } from './utils/tensor.js';\n\nimport { RawImage } from './utils/image.js';\nimport {\n window_function,\n spectrogram,\n mel_filter_bank,\n} from './utils/audio.js';\n\n\n// Helper functions\n\n/**\n * Converts bounding boxes from center format to corners format.\n * \n * @param {number[]} arr The coordinate for the center of the box and its width, height dimensions (center_x, center_y, width, height)\n * @returns {number[]} The coodinates for the top-left and bottom-right corners of the box (top_left_x, top_left_y, bottom_right_x, bottom_right_y)\n */\nfunction center_to_corners_format([centerX, centerY, width, height]) {\n return [\n centerX - width / 2,\n centerY - height / 2,\n centerX + width / 2,\n centerY + height / 2\n ];\n}\n\n/**\n * Post-processes the outputs of the model (for object detection).\n * @param {Object} outputs The outputs of the model that must be post-processed\n * @param {Tensor} outputs.logits The logits\n * @param {Tensor} outputs.pred_boxes The predicted boxes.\n * @param {number} [threshold=0.5] The threshold to use for the scores.\n * @param {[number, number][]} [target_sizes=null] The sizes of the original images.\n * @param {boolean} [is_zero_shot=false] Whether zero-shot object detection was performed.\n * @return {Object[]} An array of objects containing the post-processed outputs.\n * @private\n */\nfunction post_process_object_detection(outputs, threshold = 0.5, target_sizes = null, is_zero_shot = false) {\n const out_logits = outputs.logits;\n const out_bbox = outputs.pred_boxes;\n const [batch_size, num_boxes, num_classes] = out_logits.dims;\n\n if (target_sizes !== null && target_sizes.length !== batch_size) {\n throw Error(\"Make sure that you pass in as many target sizes as the batch dimension of the logits\")\n }\n let toReturn = [];\n for (let i = 0; i < batch_size; ++i) {\n let target_size = target_sizes !== null ? target_sizes[i] : null;\n let info = {\n boxes: [],\n classes: [],\n scores: []\n }\n let logits = out_logits[i];\n let bbox = out_bbox[i];\n\n for (let j = 0; j < num_boxes; ++j) {\n let logit = logits[j];\n\n let indices = [];\n let probs;\n if (is_zero_shot) {\n // Get indices of classes with high enough probability\n probs = logit.sigmoid().data;\n for (let k = 0; k < probs.length; ++k) {\n if (probs[k] > threshold) {\n indices.push(k);\n }\n }\n\n } else {\n // Get most probable class\n let maxIndex = max(logit.data)[1];\n\n if (maxIndex === num_classes - 1) {\n // This is the background class, skip it\n continue;\n }\n // Compute softmax over classes\n probs = softmax(logit.data);\n\n if (probs[maxIndex] < threshold) {\n continue;\n }\n indices.push(maxIndex);\n }\n\n for (const index of indices) {\n\n // Some class has a high enough probability\n /** @type {number[]} */\n let box = bbox[j].data;\n\n // convert to [x0, y0, x1, y1] format\n box = center_to_corners_format(box)\n if (target_size !== null) {\n box = box.map((x, i) => x * target_size[(i + 1) % 2])\n }\n\n info.boxes.push(box);\n info.classes.push(index);\n info.scores.push(probs[index]);\n }\n }\n toReturn.push(info);\n }\n return toReturn;\n}\n\n\n/**\n * Post-processes the outputs of the model (for semantic segmentation).\n * @param {*} outputs Raw outputs of the model.\n * @param {[number, number][]} [target_sizes=null] List of tuples corresponding to the requested final size\n * (height, width) of each prediction. If unset, predictions will not be resized.\n * @returns {{segmentation: Tensor; labels: number[]}[]} The semantic segmentation maps.\n */\nfunction post_process_semantic_segmentation(outputs, target_sizes = null) {\n\n const logits = outputs.logits;\n const batch_size = logits.dims[0];\n\n if (target_sizes !== null && target_sizes.length !== batch_size) {\n throw Error(\"Make sure that you pass in as many target sizes as the batch dimension of the logits\")\n }\n\n const toReturn = [];\n for (let i = 0; i < batch_size; ++i) {\n const target_size = target_sizes !== null ? target_sizes[i] : null;\n\n let data = logits[i];\n\n // 1. If target_size is not null, we need to resize the masks to the target size\n if (target_size !== null) {\n // resize the masks to the target size\n data = interpolate(data, target_size, 'bilinear', false);\n }\n const [height, width] = target_size ?? data.dims.slice(-2);\n\n const segmentation = new Tensor(\n 'int32',\n new Int32Array(height * width),\n [height, width]\n );\n\n // Buffer to store current largest value\n const buffer = data[0].data;\n const segmentation_data = segmentation.data;\n for (let j = 1; j < data.dims[0]; ++j) {\n const row = data[j].data;\n for (let k = 0; k < row.length; ++k) {\n if (row[k] > buffer[k]) {\n buffer[k] = row[k];\n segmentation_data[k] = j;\n }\n }\n }\n\n // Store which objects have labels\n // This is much more efficient that creating a set of the final values\n const hasLabel = new Array(data.dims[0]);\n for (let j = 0; j < segmentation_data.length; ++j) {\n const index = segmentation_data[j];\n hasLabel[index] = index;\n }\n /** @type {number[]} The unique list of labels that were detected */\n const labels = hasLabel.filter(x => x !== undefined);\n\n toReturn.push({ segmentation, labels });\n }\n return toReturn;\n}\n\n\n/**\n * Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and `labels`.\n * @param {Tensor} class_logits The class logits.\n * @param {Tensor} mask_logits The mask logits.\n * @param {number} object_mask_threshold A number between 0 and 1 used to binarize the masks.\n * @param {number} num_labels The number of labels.\n * @returns {[Tensor[], number[], number[]]} The binarized masks, the scores, and the labels.\n * @private\n */\nfunction remove_low_and_no_objects(class_logits, mask_logits, object_mask_threshold, num_labels) {\n\n const mask_probs_item = [];\n const pred_scores_item = [];\n const pred_labels_item = [];\n\n for (let j = 0; j < class_logits.dims[0]; ++j) {\n const cls = class_logits[j];\n const mask = mask_logits[j];\n\n const pred_label = max(cls.data)[1];\n if (pred_label === num_labels) {\n // Is the background, so we ignore it\n continue;\n }\n\n const scores = softmax(cls.data);\n const pred_score = scores[pred_label];\n if (pred_score > object_mask_threshold) {\n mask_probs_item.push(mask);\n pred_scores_item.push(pred_score);\n pred_labels_item.push(pred_label);\n }\n }\n\n return [mask_probs_item, pred_scores_item, pred_labels_item];\n}\n\n/**\n * Checks whether the segment is valid or not.\n * @param {Int32Array} mask_labels Labels for each pixel in the mask.\n * @param {Tensor[]} mask_probs Probabilities for each pixel in the masks.\n * @param {number} k The class id of the segment.\n * @param {number} mask_threshold The mask threshold.\n * @param {number} overlap_mask_area_threshold The overlap mask area threshold.\n * @returns {[boolean, number[]]} Whether the segment is valid or not, and the indices of the valid labels.\n * @private\n */\nfunction check_segment_validity(\n mask_labels,\n mask_probs,\n k,\n mask_threshold = 0.5,\n overlap_mask_area_threshold = 0.8\n) {\n // mask_k is a 1D array of indices, indicating where the mask is equal to k\n const mask_k = [];\n let mask_k_area = 0;\n let original_area = 0;\n\n const mask_probs_k_data = mask_probs[k].data;\n\n // Compute the area of all the stuff in query k\n for (let i = 0; i < mask_labels.length; ++i) {\n if (mask_labels[i] === k) {\n mask_k.push(i);\n ++mask_k_area;\n }\n\n if (mask_probs_k_data[i] >= mask_threshold) {\n ++original_area;\n }\n }\n let mask_exists = mask_k_area > 0 && original_area > 0;\n\n // Eliminate disconnected tiny segments\n if (mask_exists) {\n // Perform additional check\n let area_ratio = mask_k_area / original_area;\n mask_exists = area_ratio > overlap_mask_area_threshold;\n }\n\n return [mask_exists, mask_k]\n}\n\n/**\n * Computes the segments.\n * @param {Tensor[]} mask_probs The mask probabilities.\n * @param {number[]} pred_scores The predicted scores.\n * @param {number[]} pred_labels The predicted labels.\n * @param {number} mask_threshold The mask threshold.\n * @param {number} overlap_mask_area_threshold The overlap mask area threshold.\n * @param {Set} label_ids_to_fuse The label ids to fuse.\n * @param {number[]} target_size The target size of the image.\n * @returns {[Tensor, Array<{id: number, label_id: number, score: number}>]} The computed segments.\n * @private\n */\nfunction compute_segments(\n mask_probs,\n pred_scores,\n pred_labels,\n mask_threshold,\n overlap_mask_area_threshold,\n label_ids_to_fuse = null,\n target_size = null,\n) {\n const [height, width] = target_size ?? mask_probs[0].dims;\n\n const segmentation = new Tensor(\n 'int32',\n new Int32Array(height * width),\n [height, width]\n );\n const segments = [];\n\n // 1. If target_size is not null, we need to resize the masks to the target size\n if (target_size !== null) {\n // resize the masks to the target size\n for (let i = 0; i < mask_probs.length; ++i) {\n mask_probs[i] = interpolate(mask_probs[i], target_size, 'bilinear', false);\n }\n }\n\n // 2. Weigh each mask by its prediction score\n // NOTE: `mask_probs` is updated in-place\n // \n // Temporary storage for the best label/scores for each pixel ([height, width]):\n const mask_labels = new Int32Array(mask_probs[0].data.length);\n const bestScores = new Float32Array(mask_probs[0].data.length);\n\n for (let i = 0; i < mask_probs.length; ++i) {\n let score = pred_scores[i];\n\n const mask_probs_i_data = mask_probs[i].data;\n\n for (let j = 0; j < mask_probs_i_data.length; ++j) {\n mask_probs_i_data[j] *= score\n if (mask_probs_i_data[j] > bestScores[j]) {\n mask_labels[j] = i;\n bestScores[j] = mask_probs_i_data[j];\n }\n }\n }\n\n let current_segment_id = 0;\n\n // let stuff_memory_list = {}\n const segmentation_data = segmentation.data;\n for (let k = 0; k < pred_labels.length; ++k) {\n const pred_class = pred_labels[k];\n\n // TODO add `should_fuse`\n // let should_fuse = pred_class in label_ids_to_fuse\n\n // Check if mask exists and large enough to be a segment\n const [mask_exists, mask_k] = check_segment_validity(\n mask_labels,\n mask_probs,\n k,\n mask_threshold,\n overlap_mask_area_threshold\n )\n\n if (!mask_exists) {\n // Nothing to see here\n continue;\n }\n\n // TODO\n // if (pred_class in stuff_memory_list) {\n // current_segment_id = stuff_memory_list[pred_class]\n // } else {\n // current_segment_id += 1;\n // }\n ++current_segment_id;\n\n\n // Add current object segment to final segmentation map\n for (const index of mask_k) {\n segmentation_data[index] = current_segment_id;\n }\n\n segments.push({\n id: current_segment_id,\n label_id: pred_class,\n // was_fused: should_fuse, TODO\n score: pred_scores[k],\n })\n\n // TODO\n // if(should_fuse){\n // stuff_memory_list[pred_class] = current_segment_id\n // }\n }\n\n return [segmentation, segments];\n}\n\n\n/**\n * Post-process the model output to generate the final panoptic segmentation.\n * @param {*} outputs The model output to post process\n * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks.\n * @param {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values.\n * @param {number} [overlap_mask_area_threshold=0.8] The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask.\n * @param {Set} [label_ids_to_fuse=null] The labels in this state will have all their instances be fused together.\n * @param {[number, number][]} [target_sizes=null] The target sizes to resize the masks to.\n * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>}\n */\nfunction post_process_panoptic_segmentation(\n outputs,\n threshold = 0.5,\n mask_threshold = 0.5,\n overlap_mask_area_threshold = 0.8,\n label_ids_to_fuse = null,\n target_sizes = null,\n) {\n if (label_ids_to_fuse === null) {\n console.warn(\"`label_ids_to_fuse` unset. No instance will be fused.\")\n label_ids_to_fuse = new Set();\n }\n\n const class_queries_logits = outputs.class_queries_logits ?? outputs.logits; // [batch_size, num_queries, num_classes+1]\n const masks_queries_logits = outputs.masks_queries_logits ?? outputs.pred_masks; // [batch_size, num_queries, height, width]\n\n const mask_probs = masks_queries_logits.sigmoid() // [batch_size, num_queries, height, width]\n\n let [batch_size, num_queries, num_labels] = class_queries_logits.dims;\n num_labels -= 1; // Remove last class (background)\n\n if (target_sizes !== null && target_sizes.length !== batch_size) {\n throw Error(\"Make sure that you pass in as many target sizes as the batch dimension of the logits\")\n }\n\n let toReturn = [];\n for (let i = 0; i < batch_size; ++i) {\n let target_size = target_sizes !== null ? target_sizes[i] : null;\n\n let class_logits = class_queries_logits[i];\n let mask_logits = mask_probs[i];\n\n let [mask_probs_item, pred_scores_item, pred_labels_item] = remove_low_and_no_objects(class_logits, mask_logits, threshold, num_labels);\n\n if (pred_labels_item.length === 0) {\n // No mask found\n let [height, width] = target_size ?? mask_logits.dims.slice(-2);\n\n let segmentation = new Tensor(\n 'int32',\n new Int32Array(height * width).fill(-1),\n [height, width]\n )\n toReturn.push({\n segmentation: segmentation,\n segments_info: []\n });\n continue;\n }\n\n\n // Get segmentation map and segment information of batch item\n let [segmentation, segments] = compute_segments(\n mask_probs_item,\n pred_scores_item,\n pred_labels_item,\n mask_threshold,\n overlap_mask_area_threshold,\n label_ids_to_fuse,\n target_size,\n )\n\n toReturn.push({\n segmentation: segmentation,\n segments_info: segments\n })\n }\n\n return toReturn;\n}\n\n\n/**\n * Post-processes the outputs of the model (for instance segmentation).\n * @param {*} outputs Raw outputs of the model.\n * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks.\n * @param {[number, number][]} [target_sizes=null] List of tuples corresponding to the requested final size\n * (height, width) of each prediction. If unset, predictions will not be resized.\n * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>}\n */\nfunction post_process_instance_segmentation(outputs, threshold = 0.5, target_sizes = null) {\n throw new Error('Not implemented yet');\n return [];\n}\n\n/**\n * Named tuple to indicate the order we are using is (height x width), even though\n * the Graphics’ industry standard is (width x height).\n * @typedef {[height: number, width: number]} HeightWidth\n */\n\n/**\n * Helper function to validate audio inputs.\n * @param {any} audio The audio data.\n * @param {string} feature_extractor The name of the feature extractor.\n * @private\n */\nfunction validate_audio_inputs(audio, feature_extractor) {\n if (!(audio instanceof Float32Array || audio instanceof Float64Array)) {\n throw new Error(\n `${feature_extractor} expects input to be a Float32Array or a Float64Array, but got ${audio?.constructor?.name ?? typeof audio} instead. ` +\n `If using the feature extractor directly, remember to use \\`read_audio(url, sampling_rate)\\` to obtain the raw audio data of the file/url.`\n )\n }\n}\n\n/**\n * Helper function to constrain a value to be a multiple of a number.\n * @param {number} val The value to constrain.\n * @param {number} multiple The number to constrain to.\n * @param {number} [minVal=0] The minimum value to constrain to.\n * @param {number} [maxVal=null] The maximum value to constrain to.\n * @returns {number} The constrained value.\n * @private\n */\nfunction constraint_to_multiple_of(val, multiple, minVal = 0, maxVal = null) {\n const a = val / multiple;\n let x = bankers_round(a) * multiple;\n\n if (maxVal !== null && x > maxVal) {\n x = Math.floor(a) * multiple;\n }\n\n if (x < minVal) {\n x = Math.ceil(a) * multiple;\n }\n\n return x;\n}\n\n/**\n * Rounds the height and width down to the closest multiple of size_divisibility\n * @param {[number, number]} size The size of the image\n * @param {number} divisor The divisor to use.\n * @returns {[number, number]} The rounded size.\n */\nfunction enforce_size_divisibility([width, height], divisor) {\n return [\n Math.max(Math.floor(width / divisor), 1) * divisor,\n Math.max(Math.floor(height / divisor), 1) * divisor\n ];\n}\n\n\n/**\n * Base class for feature extractors.\n *\n * @extends Callable\n */\nexport class FeatureExtractor extends Callable {\n /**\n * Constructs a new FeatureExtractor instance.\n *\n * @param {Object} config The configuration for the feature extractor.\n */\n constructor(config) {\n super();\n this.config = config\n }\n}\n\n/**\n * @typedef {object} ImageFeatureExtractorResult\n * @property {Tensor} pixel_values The pixel values of the batched preprocessed images.\n * @property {HeightWidth[]} original_sizes Array of two-dimensional tuples like [[480, 640]].\n * @property {HeightWidth[]} reshaped_input_sizes Array of two-dimensional tuples like [[1000, 1330]].\n */\n\n/**\n * Feature extractor for image models.\n *\n * @extends FeatureExtractor\n */\nexport class ImageFeatureExtractor extends FeatureExtractor {\n\n /**\n * Constructs a new ImageFeatureExtractor instance.\n *\n * @param {Object} config The configuration for the feature extractor.\n * @param {number[]} config.image_mean The mean values for image normalization.\n * @param {number[]} config.image_std The standard deviation values for image normalization.\n * @param {boolean} config.do_rescale Whether to rescale the image pixel values to the [0,1] range.\n * @param {number} config.rescale_factor The factor to use for rescaling the image pixel values.\n * @param {boolean} config.do_normalize Whether to normalize the image pixel values.\n * @param {boolean} config.do_resize Whether to resize the image.\n * @param {number} config.resample What method to use for resampling.\n * @param {number|Object} config.size The size to resize the image to.\n * @param {boolean} [config.do_flip_channel_order=false] Whether to flip the color channels from RGB to BGR.\n * Can be overridden by the `do_flip_channel_order` parameter in the `preprocess` method.\n */\n constructor(config) {\n super(config);\n\n this.image_mean = this.config.image_mean ?? this.config.mean;\n this.image_std = this.config.image_std ?? this.config.std;\n\n this.resample = this.config.resample ?? 2; // 2 => bilinear\n this.do_rescale = this.config.do_rescale ?? true;\n this.rescale_factor = this.config.rescale_factor ?? (1 / 255);\n this.do_normalize = this.config.do_normalize;\n\n this.do_resize = this.config.do_resize;\n this.do_thumbnail = this.config.do_thumbnail;\n this.size = this.config.size;\n this.size_divisibility = this.config.size_divisibility ?? this.config.size_divisor;\n\n this.do_center_crop = this.config.do_center_crop;\n this.crop_size = this.config.crop_size;\n this.do_convert_rgb = this.config.do_convert_rgb ?? true;\n this.do_crop_margin = this.config.do_crop_margin;\n\n this.pad_size = this.config.pad_size;\n this.do_pad = this.config.do_pad;\n\n if (this.do_pad && !this.pad_size && this.size && this.size.width !== undefined && this.size.height !== undefined) {\n // Should pad, but no pad size specified\n // We infer the pad size from the resize size\n this.pad_size = this.size\n }\n\n this.do_flip_channel_order = this.config.do_flip_channel_order ?? false;\n }\n\n /**\n * Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any\n * corresponding dimension of the specified size.\n * @param {RawImage} image The image to be resized.\n * @param {{height:number, width:number}} size The size `{\"height\": h, \"width\": w}` to resize the image to.\n * @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use.\n * @returns {Promise} The resized image.\n */\n async thumbnail(image, size, resample = 2) {\n const input_height = image.height;\n const input_width = image.width;\n\n const output_height = size.height;\n const output_width = size.width;\n\n // We always resize to the smallest of either the input or output size.\n let height = Math.min(input_height, output_height)\n let width = Math.min(input_width, output_width)\n\n if (height === input_height && width === input_width) {\n return image;\n }\n if (input_height > input_width) {\n width = Math.floor(input_width * height / input_height);\n } else if (input_width > input_height) {\n height = Math.floor(input_height * width / input_width);\n }\n return await image.resize(width, height, { resample });\n }\n\n\n /**\n * Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold).\n * @param {RawImage} image The image to be cropped.\n * @param {number} gray_threshold Value below which pixels are considered to be gray.\n * @returns {Promise} The cropped image.\n */\n async crop_margin(image, gray_threshold = 200) {\n\n const gray_image = image.clone().grayscale();\n\n const minValue = min(gray_image.data)[0];\n const maxValue = max(gray_image.data)[0];\n const diff = maxValue - minValue;\n\n if (diff === 0) {\n return image;\n }\n\n const threshold = gray_threshold / 255;\n\n let x_min = gray_image.width, y_min = gray_image.height, x_max = 0, y_max = 0;\n const gray_image_data = gray_image.data;\n for (let j = 0; j < gray_image.height; ++j) {\n const row = j * gray_image.width;\n for (let i = 0; i < gray_image.width; ++i) {\n if ((gray_image_data[row + i] - minValue) / diff < threshold) {\n // We have a non-zero pixel, so we update the min/max values accordingly\n x_min = Math.min(x_min, i);\n y_min = Math.min(y_min, j);\n x_max = Math.max(x_max, i);\n y_max = Math.max(y_max, j);\n }\n }\n }\n\n image = await image.crop([x_min, y_min, x_max, y_max]);\n return image;\n }\n\n /**\n * Pad the image by a certain amount.\n * @param {Float32Array} pixelData The pixel data to pad.\n * @param {number[]} imgDims The dimensions of the image (height, width, channels).\n * @param {{width:number; height:number}|number} padSize The dimensions of the padded image.\n * @param {Object} options The options for padding.\n * @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add.\n * @param {boolean} [options.center=false] Whether to center the image.\n * @param {number} [options.constant_values=0] The constant value to use for padding.\n * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions.\n */\n pad_image(pixelData, imgDims, padSize, {\n mode = 'constant',\n center = false,\n constant_values = 0,\n } = {}) {\n const [imageHeight, imageWidth, imageChannels] = imgDims;\n\n let paddedImageWidth, paddedImageHeight;\n if (typeof padSize === 'number') {\n paddedImageWidth = padSize;\n paddedImageHeight = padSize;\n } else {\n paddedImageWidth = padSize.width;\n paddedImageHeight = padSize.height;\n }\n\n // Only add padding if there is a difference in size\n if (paddedImageWidth !== imageWidth || paddedImageHeight !== imageHeight) {\n const paddedPixelData = new Float32Array(paddedImageWidth * paddedImageHeight * imageChannels);\n if (Array.isArray(constant_values)) {\n // Fill with constant values, cycling through the array\n for (let i = 0; i < paddedPixelData.length; ++i) {\n paddedPixelData[i] = constant_values[i % imageChannels];\n }\n } else if (constant_values !== 0) {\n paddedPixelData.fill(constant_values);\n }\n\n const [left, top] = center\n ? [Math.floor((paddedImageWidth - imageWidth) / 2), Math.floor((paddedImageHeight - imageHeight) / 2)]\n : [0, 0];\n\n // Copy the original image into the padded image\n for (let i = 0; i < imageHeight; ++i) {\n const a = (i + top) * paddedImageWidth;\n const b = i * imageWidth;\n for (let j = 0; j < imageWidth; ++j) {\n const c = (a + j + left) * imageChannels;\n const d = (b + j) * imageChannels;\n for (let k = 0; k < imageChannels; ++k) {\n paddedPixelData[c + k] = pixelData[d + k];\n }\n }\n }\n\n if (mode === 'symmetric') {\n if (center) {\n throw new Error('`center` padding is not supported when `mode` is set to `symmetric`.');\n // TODO: Implement this\n }\n const h1 = imageHeight - 1;\n const w1 = imageWidth - 1;\n for (let i = 0; i < paddedImageHeight; ++i) {\n const a = i * paddedImageWidth;\n const b = calculateReflectOffset(i, h1) * imageWidth;\n\n for (let j = 0; j < paddedImageWidth; ++j) {\n if (i < imageHeight && j < imageWidth) continue; // Do not overwrite original image\n const c = (a + j) * imageChannels;\n const d = (b + calculateReflectOffset(j, w1)) * imageChannels;\n\n // Copy channel-wise\n for (let k = 0; k < imageChannels; ++k) {\n paddedPixelData[c + k] = pixelData[d + k];\n }\n }\n }\n }\n\n\n // Update pixel data and image dimensions\n pixelData = paddedPixelData;\n imgDims = [paddedImageHeight, paddedImageWidth, imageChannels]\n }\n return [pixelData, imgDims];\n }\n\n /**\n * Rescale the image' pixel values by `this.rescale_factor`.\n * @param {Float32Array} pixelData The pixel data to rescale.\n * @returns {void}\n */\n rescale(pixelData) {\n for (let i = 0; i < pixelData.length; ++i) {\n pixelData[i] = this.rescale_factor * pixelData[i];\n }\n }\n\n /**\n * Find the target (width, height) dimension of the output image after\n * resizing given the input image and the desired size.\n * @param {RawImage} image The image to resize.\n * @param {any} size The size to use for resizing the image. \n * @returns {[number, number]} The target (width, height) dimension of the output image after resizing.\n */\n get_resize_output_image_size(image, size) {\n // `size` comes in many forms, so we need to handle them all here:\n // 1. `size` is an integer, in which case we resize the image to be a square \n\n const [srcWidth, srcHeight] = image.size;\n\n let shortest_edge;\n let longest_edge;\n\n if (this.do_thumbnail) {\n // NOTE: custom logic for `Donut` models\n const { height, width } = size;\n shortest_edge = Math.min(height, width)\n }\n // Support both formats for backwards compatibility\n else if (Number.isInteger(size)) {\n shortest_edge = size;\n longest_edge = this.config.max_size ?? shortest_edge;\n\n } else if (size !== undefined) {\n // Extract known properties from `size`\n shortest_edge = size.shortest_edge;\n longest_edge = size.longest_edge;\n }\n\n // If `longest_edge` and `shortest_edge` are set, maintain aspect ratio and resize to `shortest_edge`\n // while keeping the largest dimension <= `longest_edge`\n if (shortest_edge !== undefined || longest_edge !== undefined) {\n // http://opensourcehacker.com/2011/12/01/calculate-aspect-ratio-conserving-resize-for-images-in-javascript/\n // Try resize so that shortest edge is `shortest_edge` (target)\n const shortResizeFactor = shortest_edge === undefined\n ? 1 // If `shortest_edge` is not set, don't upscale\n : Math.max(shortest_edge / srcWidth, shortest_edge / srcHeight);\n\n const newWidth = srcWidth * shortResizeFactor;\n const newHeight = srcHeight * shortResizeFactor;\n\n // The new width and height might be greater than `longest_edge`, so\n // we downscale again to ensure the largest dimension is `longest_edge` \n const longResizeFactor = longest_edge === undefined\n ? 1 // If `longest_edge` is not set, don't downscale\n : Math.min(longest_edge / newWidth, longest_edge / newHeight);\n\n // To avoid certain floating point precision issues, we round to 2 decimal places\n let finalWidth = Math.floor(Number((newWidth * longResizeFactor).toFixed(2)));\n let finalHeight = Math.floor(Number((newHeight * longResizeFactor).toFixed(2)));\n\n if (this.size_divisibility !== undefined) {\n [finalWidth, finalHeight] = enforce_size_divisibility([finalWidth, finalHeight], this.size_divisibility)\n }\n return [finalWidth, finalHeight];\n\n } else if (size !== undefined && size.width !== undefined && size.height !== undefined) {\n // If `width` and `height` are set, resize to those dimensions\n\n let newWidth = size.width;\n let newHeight = size.height;\n\n // Custom for DPT models\n if (this.config.keep_aspect_ratio && this.config.ensure_multiple_of) {\n\n // determine new height and width\n let scale_height = newHeight / srcHeight;\n let scale_width = newWidth / srcWidth;\n\n // scale as little as possible\n if (Math.abs(1 - scale_width) < Math.abs(1 - scale_height)) {\n // fit width\n scale_height = scale_width;\n } else {\n // fit height\n scale_width = scale_height;\n }\n\n newHeight = constraint_to_multiple_of(scale_height * srcHeight, this.config.ensure_multiple_of);\n newWidth = constraint_to_multiple_of(scale_width * srcWidth, this.config.ensure_multiple_of);\n }\n\n return [newWidth, newHeight];\n\n } else if (this.size_divisibility !== undefined) {\n return enforce_size_divisibility([srcWidth, srcHeight], this.size_divisibility);\n } else {\n throw new Error(`Could not resize image due to unsupported \\`this.size\\` option in config: ${JSON.stringify(size)}`);\n }\n }\n\n /**\n * Resizes the image.\n * @param {RawImage} image The image to resize.\n * @returns {Promise} The resized image.\n */\n async resize(image) {\n const [newWidth, newHeight] = this.get_resize_output_image_size(image, this.size);\n return await image.resize(newWidth, newHeight, {\n resample: this.resample,\n });\n }\n\n /**\n * @typedef {object} PreprocessedImage\n * @property {HeightWidth} original_size The original size of the image.\n * @property {HeightWidth} reshaped_input_size The reshaped input size of the image.\n * @property {Tensor} pixel_values The pixel values of the preprocessed image.\n */\n\n /**\n * Preprocesses the given image.\n *\n * @param {RawImage} image The image to preprocess.\n * @param {Object} overrides The overrides for the preprocessing options.\n * @returns {Promise} The preprocessed image.\n */\n async preprocess(image, {\n do_normalize = null,\n do_pad = null,\n do_convert_rgb = null,\n do_convert_grayscale = null,\n do_flip_channel_order = null,\n } = {}) {\n if (this.do_crop_margin) {\n // NOTE: Specific to nougat processors. This is done before resizing,\n // and can be interpreted as a pre-preprocessing step.\n image = await this.crop_margin(image);\n }\n\n const [srcWidth, srcHeight] = image.size; // original image size\n\n // Convert image to RGB if specified in config.\n if (do_convert_rgb ?? this.do_convert_rgb) {\n image = image.rgb();\n } else if (do_convert_grayscale) {\n image = image.grayscale();\n }\n\n // TODO:\n // For efficiency reasons, it might be best to merge the resize and center crop operations into one.\n\n // Resize all images\n if (this.do_resize) {\n image = await this.resize(image);\n }\n\n // Resize the image using thumbnail method.\n if (this.do_thumbnail) {\n image = await this.thumbnail(image, this.size, this.resample);\n }\n\n if (this.do_center_crop) {\n\n let crop_width;\n let crop_height;\n if (Number.isInteger(this.crop_size)) {\n crop_width = this.crop_size;\n crop_height = this.crop_size;\n } else {\n crop_width = this.crop_size.width;\n crop_height = this.crop_size.height;\n }\n\n image = await image.center_crop(crop_width, crop_height);\n }\n\n /** @type {HeightWidth} */\n const reshaped_input_size = [image.height, image.width];\n\n // NOTE: All pixel-level manipulation (i.e., modifying `pixelData`)\n // occurs with data in the hwc format (height, width, channels), \n // to emulate the behavior of the original Python code (w/ numpy).\n let pixelData = Float32Array.from(image.data);\n let imgDims = [image.height, image.width, image.channels];\n\n if (this.do_rescale) {\n this.rescale(pixelData);\n }\n\n if (do_normalize ?? this.do_normalize) {\n let image_mean = this.image_mean;\n if (!Array.isArray(this.image_mean)) {\n image_mean = new Array(image.channels).fill(image_mean);\n }\n\n let image_std = this.image_std;\n if (!Array.isArray(this.image_std)) {\n image_std = new Array(image.channels).fill(image_mean);\n }\n\n if (image_mean.length !== image.channels || image_std.length !== image.channels) {\n throw new Error(`When set to arrays, the length of \\`image_mean\\` (${image_mean.length}) and \\`image_std\\` (${image_std.length}) must match the number of channels in the image (${image.channels}).`);\n }\n\n for (let i = 0; i < pixelData.length; i += image.channels) {\n for (let j = 0; j < image.channels; ++j) {\n pixelData[i + j] = (pixelData[i + j] - image_mean[j]) / image_std[j];\n }\n }\n }\n\n // do padding after rescaling/normalizing\n if (do_pad ?? this.do_pad) {\n if (this.pad_size) {\n const padded = this.pad_image(pixelData, [image.height, image.width, image.channels], this.pad_size);\n [pixelData, imgDims] = padded; // Update pixel data and image dimensions\n } else if (this.size_divisibility) {\n const [paddedWidth, paddedHeight] = enforce_size_divisibility([imgDims[1], imgDims[0]], this.size_divisibility);\n [pixelData, imgDims] = this.pad_image(pixelData, imgDims, { width: paddedWidth, height: paddedHeight });\n }\n }\n\n if (do_flip_channel_order ?? this.do_flip_channel_order) {\n if (imgDims[2] !== 3) {\n throw new Error('Flipping channel order is only supported for RGB images.');\n }\n // Convert RGB to BGR\n for (let i = 0; i < pixelData.length; i += 3) {\n const temp = pixelData[i];\n pixelData[i] = pixelData[i + 2];\n pixelData[i + 2] = temp;\n }\n }\n\n const pixel_values = new Tensor('float32', pixelData, imgDims)\n .permute(2, 0, 1); // convert to channel dimension format (hwc -> chw)\n\n return {\n original_size: [srcHeight, srcWidth],\n reshaped_input_size: reshaped_input_size,\n pixel_values,\n }\n }\n\n /**\n * Calls the feature extraction process on an array of images,\n * preprocesses each image, and concatenates the resulting\n * features into a single Tensor.\n * @param {RawImage[]} images The image(s) to extract features from.\n * @param {...any} args Additional arguments.\n * @returns {Promise} An object containing the concatenated pixel values (and other metadata) of the preprocessed images.\n */\n async _call(images, ...args) {\n if (!Array.isArray(images)) {\n images = [images];\n }\n /** @type {PreprocessedImage[]} */\n const imageData = await Promise.all(images.map(x => this.preprocess(x)));\n\n // Stack pixel values\n const pixel_values = stack(imageData.map(x => x.pixel_values), 0);\n\n return {\n pixel_values,\n\n // Original sizes of images\n original_sizes: imageData.map(x => x.original_size),\n\n // Reshaped sizes of images, before padding or cropping\n reshaped_input_sizes: imageData.map(x => x.reshaped_input_size),\n }\n }\n\n}\n\nexport class SapiensFeatureExtractor extends ImageFeatureExtractor {\n /** @type {typeof post_process_semantic_segmentation} */\n post_process_semantic_segmentation(...args) {\n return post_process_semantic_segmentation(...args);\n }\n}\nexport class SegformerFeatureExtractor extends ImageFeatureExtractor {\n /** @type {typeof post_process_semantic_segmentation} */\n post_process_semantic_segmentation(...args) {\n return post_process_semantic_segmentation(...args);\n }\n}\nexport class PvtImageProcessor extends ImageFeatureExtractor { }\nexport class DPTFeatureExtractor extends ImageFeatureExtractor { }\nexport class DPTImageProcessor extends DPTFeatureExtractor { } // NOTE: extends DPTFeatureExtractor\nexport class BitImageProcessor extends ImageFeatureExtractor { }\nexport class GLPNFeatureExtractor extends ImageFeatureExtractor { }\nexport class CLIPFeatureExtractor extends ImageFeatureExtractor { }\nexport class CLIPImageProcessor extends CLIPFeatureExtractor { } // NOTE: extends CLIPFeatureExtractor\nexport class ChineseCLIPFeatureExtractor extends ImageFeatureExtractor { }\nexport class SiglipImageProcessor extends ImageFeatureExtractor { }\nexport class ConvNextFeatureExtractor extends ImageFeatureExtractor {\n constructor(config) {\n super(config);\n\n /**\n * Percentage of the image to crop. Only has an effect if this.size < 384.\n */\n this.crop_pct = this.config.crop_pct ?? (224 / 256);\n }\n\n async resize(image) {\n const shortest_edge = this.size?.shortest_edge;\n if (shortest_edge === undefined) {\n throw new Error(`Size dictionary must contain 'shortest_edge' key.`);\n }\n\n if (shortest_edge < 384) {\n // maintain same ratio, resizing shortest edge to shortest_edge/crop_pct\n const resize_shortest_edge = Math.floor(shortest_edge / this.crop_pct);\n\n const [newWidth, newHeight] = this.get_resize_output_image_size(image, {\n shortest_edge: resize_shortest_edge,\n });\n\n image = await image.resize(newWidth, newHeight, {\n resample: this.resample,\n });\n\n // then crop to (shortest_edge, shortest_edge)\n image = await image.center_crop(shortest_edge, shortest_edge);\n } else {\n // warping (no cropping) when evaluated at 384 or larger\n image = await image.resize(shortest_edge, shortest_edge, {\n resample: this.resample,\n });\n }\n\n return image;\n }\n}\nexport class ConvNextImageProcessor extends ConvNextFeatureExtractor { } // NOTE extends ConvNextFeatureExtractor\nexport class ViTFeatureExtractor extends ImageFeatureExtractor { }\nexport class ViTImageProcessor extends ImageFeatureExtractor { }\n\nexport class EfficientNetImageProcessor extends ImageFeatureExtractor {\n constructor(config) {\n super(config);\n this.include_top = this.config.include_top ?? true;\n if (this.include_top) {\n this.image_std = this.image_std.map(x => x * x);\n }\n }\n}\n\nexport class MobileNetV1FeatureExtractor extends ImageFeatureExtractor { }\nexport class MobileNetV2FeatureExtractor extends ImageFeatureExtractor { }\nexport class MobileNetV3FeatureExtractor extends ImageFeatureExtractor { }\nexport class MobileNetV4FeatureExtractor extends ImageFeatureExtractor { }\n\nexport class MobileViTFeatureExtractor extends ImageFeatureExtractor { }\nexport class MobileViTImageProcessor extends MobileViTFeatureExtractor { } // NOTE extends MobileViTFeatureExtractor\nexport class OwlViTFeatureExtractor extends ImageFeatureExtractor {\n /** @type {typeof post_process_object_detection} */\n post_process_object_detection(...args) {\n return post_process_object_detection(...args);\n }\n}\nexport class Owlv2ImageProcessor extends OwlViTFeatureExtractor { } // NOTE extends OwlViTFeatureExtractor\n\nexport class RTDetrImageProcessor extends ImageFeatureExtractor {\n /** @type {typeof post_process_object_detection} */\n post_process_object_detection(...args) {\n return post_process_object_detection(...args);\n }\n}\n\nexport class DeiTFeatureExtractor extends ImageFeatureExtractor { }\nexport class BeitFeatureExtractor extends ImageFeatureExtractor { }\nexport class DonutFeatureExtractor extends ImageFeatureExtractor {\n pad_image(pixelData, imgDims, padSize, options = {}) {\n const [imageHeight, imageWidth, imageChannels] = imgDims;\n\n let image_mean = this.image_mean;\n if (!Array.isArray(this.image_mean)) {\n image_mean = new Array(imageChannels).fill(image_mean);\n }\n\n let image_std = this.image_std;\n if (!Array.isArray(image_std)) {\n image_std = new Array(imageChannels).fill(image_mean);\n }\n\n const constant_values = image_mean.map((x, i) => - x / image_std[i]);\n\n return super.pad_image(pixelData, imgDims, padSize, {\n center: true,\n\n // Since normalization is done after padding, we need to use certain constant values to ensure the same behaviour is observed.\n // For more information, see https://github.com/huggingface/transformers/blob/main/src/transformers/models/donut/image_processing_donut.py#L433-L451\n constant_values: constant_values,\n ...options,\n });\n }\n}\nexport class NougatImageProcessor extends DonutFeatureExtractor { } // NOTE extends DonutFeatureExtractor\n\n/**\n * @typedef {object} DetrFeatureExtractorResultProps\n * @property {Tensor} pixel_mask\n * @typedef {ImageFeatureExtractorResult & DetrFeatureExtractorResultProps} DetrFeatureExtractorResult\n */\n\n/**\n * Detr Feature Extractor.\n *\n * @extends ImageFeatureExtractor\n */\nexport class DetrFeatureExtractor extends ImageFeatureExtractor {\n /**\n * Calls the feature extraction process on an array of images, preprocesses\n * each image, and concatenates the resulting features into a single Tensor.\n * @param {RawImage[]} images The image(s) to extract features from.\n * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images.\n */\n async _call(images) {\n const result = await super._call(images);\n\n // TODO support differently-sized images, for now assume all images are the same size.\n // TODO support different mask sizes (not just 64x64)\n // Currently, just fill pixel mask with 1s\n const maskSize = [result.pixel_values.dims[0], 64, 64];\n const pixel_mask = full(maskSize, 1n);\n\n return { ...result, pixel_mask };\n }\n\n /** @type {typeof post_process_object_detection} */\n post_process_object_detection(...args) {\n return post_process_object_detection(...args);\n }\n\n /** @type {typeof post_process_panoptic_segmentation} */\n post_process_panoptic_segmentation(...args) {\n return post_process_panoptic_segmentation(...args);\n }\n\n post_process_instance_segmentation() {\n // TODO\n throw Error(\"Not implemented yet\");\n }\n}\n\nexport class MaskFormerFeatureExtractor extends ImageFeatureExtractor {\n\n /** @type {typeof post_process_panoptic_segmentation} */\n post_process_panoptic_segmentation(...args) {\n return post_process_panoptic_segmentation(...args);\n }\n\n post_process_instance_segmentation() {\n // TODO\n throw Error(\"Not implemented yet\");\n }\n}\n\n\nexport class YolosFeatureExtractor extends ImageFeatureExtractor {\n /** @type {typeof post_process_object_detection} */\n post_process_object_detection(...args) {\n return post_process_object_detection(...args);\n }\n}\n\n/**\n * @typedef {object} SamImageProcessorResult\n * @property {Tensor} pixel_values\n * @property {HeightWidth[]} original_sizes\n * @property {HeightWidth[]} reshaped_input_sizes\n * @property {Tensor} [input_points]\n * @property {Tensor} [input_labels]\n * @property {Tensor} [input_boxes]\n */\n\nexport class SamImageProcessor extends ImageFeatureExtractor {\n\n /**\n * \n * @param {any} input_points \n * @param {HeightWidth[]} original_sizes \n * @param {HeightWidth[]} reshaped_input_sizes \n * @returns {Tensor}\n */\n reshape_input_points(input_points, original_sizes, reshaped_input_sizes, is_bounding_box = false) {\n\n // Make deep copy to avoid altering user's input\n input_points = structuredClone(input_points);\n let shape = calculateDimensions(input_points);\n\n // TODO: add support for 2D input_points\n if (shape.length === 3) {\n // Correct user's input\n if (!is_bounding_box) {\n shape = [1, ...shape];\n }\n input_points = [input_points];\n } else if (shape.length !== 4) {\n throw Error(\"The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.\")\n }\n\n // Reshape input points\n for (let i = 0; i < input_points.length; ++i) { // batch_size\n let originalImageSize = original_sizes[i];\n let reshapedImageSize = reshaped_input_sizes[i];\n\n let resizeFactors = [\n reshapedImageSize[0] / originalImageSize[0],\n reshapedImageSize[1] / originalImageSize[1]\n ]\n\n for (let j = 0; j < input_points[i].length; ++j) { // point_batch_size\n for (let k = 0; k < input_points[i][j].length; ++k) { // nb_points_per_image\n for (let w = 0; w < input_points[i][j][k].length; ++w) { // 2 or 4\n input_points[i][j][k][w] *= resizeFactors[w % 2];\n }\n }\n }\n }\n\n return new Tensor(\n 'float32',\n Float32Array.from(input_points.flat(Infinity)),\n shape\n )\n\n }\n\n /**\n * \n * @param {any} input_labels \n * @param {Tensor} input_points \n * @returns {Tensor}\n */\n add_input_labels(input_labels, input_points) {\n let shape = calculateDimensions(input_labels);\n if (shape.length === 2) {\n // Correct user's input\n shape = [1, ...shape];\n input_labels = [input_labels];\n } else if (shape.length !== 3) {\n throw Error(\"The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.\")\n }\n\n if (shape.some((x, i) => x !== input_points.dims[i])) {\n throw Error(`The first ${shape.length} dimensions of 'input_points' and 'input_labels' must be the same.`)\n }\n return new Tensor(\n 'int64',\n input_labels.flat(Infinity).map(BigInt),\n shape,\n )\n }\n /**\n * @param {any[]} images The URL(s) of the image(s) to extract features from.\n * @param {Object} [options] Additional options for the processor.\n * @param {any} [options.input_points=null] A 3D or 4D array, representing the input points provided by the user.\n * - 3D: `[point_batch_size, nb_points_per_image, 2]`. In this case, `batch_size` is assumed to be 1.\n * - 4D: `[batch_size, point_batch_size, nb_points_per_image, 2]`.\n * @param {any} [options.input_labels=null] A 2D or 3D array, representing the input labels for the points, used by the prompt encoder to encode the prompt.\n * - 2D: `[point_batch_size, nb_points_per_image]`. In this case, `batch_size` is assumed to be 1.\n * - 3D: `[batch_size, point_batch_size, nb_points_per_image]`.\n * @param {number[][][]} [options.input_boxes=null] A 3D array of shape `(batch_size, num_boxes, 4)`, representing the input boxes provided by the user.\n * This is used by the prompt encoder to encode the prompt. Generally yields to much better generated masks.\n * The processor will generate a tensor, with each dimension corresponding respectively to the image batch size,\n * the number of boxes per image and the coordinates of the top left and botton right point of the box.\n * In the order (`x1`, `y1`, `x2`, `y2`):\n * - `x1`: the x coordinate of the top left point of the input box\n * - `y1`: the y coordinate of the top left point of the input box\n * - `x2`: the x coordinate of the bottom right point of the input box\n * - `y2`: the y coordinate of the bottom right point of the input box\n * @returns {Promise}\n */\n async _call(images, {\n input_points = null,\n input_labels = null,\n input_boxes = null\n } = {}) {\n // TODO allow user to use preprocessed images\n /** @type {SamImageProcessorResult} */\n const processed = await super._call(images);\n\n if (input_points) {\n processed.input_points = this.reshape_input_points(\n input_points, processed.original_sizes, processed.reshaped_input_sizes\n );\n }\n\n if (input_labels) {\n if (!processed.input_points) {\n throw Error(\"`input_points` must be provided if `input_labels` are provided.\")\n }\n processed.input_labels = this.add_input_labels(input_labels, processed.input_points);\n }\n\n if (input_boxes) {\n processed.input_boxes = this.reshape_input_points(\n input_boxes, processed.original_sizes, processed.reshaped_input_sizes, true,\n );\n }\n\n return processed;\n }\n\n /**\n * Remove padding and upscale masks to the original image size.\n * @param {Tensor} masks Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.\n * @param {[number, number][]} original_sizes The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format.\n * @param {[number, number][]} reshaped_input_sizes The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.\n * @param {Object} options Optional parameters for post-processing.\n * @param {number} [options.mask_threshold] The threshold to use for binarizing the masks.\n * @param {boolean} [options.binarize] Whether to binarize the masks.\n * @param {Object} [options.pad_size] The target size the images were padded to before being passed to the model. If `null`, the target size is assumed to be the processor's `pad_size`.\n * @param {number} [options.pad_size.height] The height the images were padded to.\n * @param {number} [options.pad_size.width] The width the images were padded to.\n * @returns {Promise} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size.\n */\n async post_process_masks(masks, original_sizes, reshaped_input_sizes, {\n mask_threshold = 0.0,\n binarize = true,\n pad_size = null,\n } = {}) {\n // masks: [1, 1, 3, 256, 256]\n\n const output_masks = [];\n\n pad_size = pad_size ?? this.pad_size;\n\n /** @type {[number, number]} */\n const target_image_size = [pad_size.height, pad_size.width];\n\n for (let i = 0; i < original_sizes.length; ++i) {\n const original_size = original_sizes[i];\n const reshaped_input_size = reshaped_input_sizes[i];\n\n // Upscale mask to padded size\n let interpolated_mask = (await interpolate_4d(\n masks[i],\n { mode: 'bilinear', size: target_image_size }\n ));\n\n // Crop mask\n interpolated_mask = interpolated_mask.slice(null, null, [0, reshaped_input_size[0]], [0, reshaped_input_size[1]]);\n\n // Downscale mask\n interpolated_mask = (await interpolate_4d(\n interpolated_mask,\n { mode: 'bilinear', size: original_size }\n ));\n\n if (binarize) {\n const data = interpolated_mask.data;\n const binarizedMaskData = new Uint8Array(data.length);\n for (let i = 0; i < data.length; ++i) {\n if (data[i] > mask_threshold) {\n binarizedMaskData[i] = 1;\n }\n }\n interpolated_mask = new Tensor(\n 'bool',\n binarizedMaskData,\n interpolated_mask.dims\n )\n }\n\n output_masks.push(interpolated_mask);\n }\n\n return output_masks;\n }\n\n /**\n * Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.\n * @param {RawImage} image Input original image\n * @param {number} target_size Target size of the resized image\n * @param {Object} options Options for generating crop boxes \n * @param {number} [options.crop_n_layers] If >0, mask prediction will be run again on crops of the image.\n * Sets the number of layers to run, where each layer has 2**i_layer number of image crops.\n * @param {number} [options.overlap_ratio] Sets the degree to which crops overlap. In the first crop layer,\n * crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap.\n * @param {number} [options.points_per_crop] Number of points to sample from each crop.\n * @param {number} [options.crop_n_points_downscale_factor] The number of points-per-side sampled in layer n is\n * scaled down by crop_n_points_downscale_factor**n.\n * @returns {Object} An object containing the crop boxes, number of points per crop, cropped images, and input labels.\n */\n generate_crop_boxes(image, target_size, {\n crop_n_layers = 0,\n overlap_ratio = 512 / 1500,\n points_per_crop = 32,\n crop_n_points_downscale_factor = 1,\n } = {}) {\n // TODO: Implement\n // return { crop_boxes, points_per_crop, cropped_images, input_labels }\n }\n}\n\nexport class Swin2SRImageProcessor extends ImageFeatureExtractor {\n pad_image(pixelData, imgDims, padSize, options = {}) {\n // NOTE: In this case, `padSize` represents the size of the sliding window for the local attention.\n // In other words, the image is padded so that its width and height are multiples of `padSize`.\n const [imageHeight, imageWidth, imageChannels] = imgDims;\n\n return super.pad_image(pixelData, imgDims, {\n // NOTE: For Swin2SR models, the original python implementation adds padding even when the image's width/height is already\n // a multiple of `pad_size`. However, this is most likely a bug (PR: https://github.com/mv-lab/swin2sr/pull/19).\n // For this reason, we only add padding when the image's width/height is not a multiple of `pad_size`.\n width: imageWidth + (padSize - imageWidth % padSize) % padSize,\n height: imageHeight + (padSize - imageHeight % padSize) % padSize,\n }, {\n mode: 'symmetric',\n center: false,\n constant_values: -1,\n ...options,\n })\n }\n}\n\nexport class VitMatteImageProcessor extends ImageFeatureExtractor {\n /**\n * Calls the feature extraction process on an array of images, preprocesses\n * each image, and concatenates the resulting features into a single Tensor.\n * @param {RawImage[]} images The image(s) to extract features from.\n * @param {RawImage[]} trimaps The trimaps(s) to extract features from.\n * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images.\n */\n async _call(images, trimaps) {\n if (!Array.isArray(images)) {\n images = [images];\n }\n if (!Array.isArray(trimaps)) {\n trimaps = [trimaps];\n }\n\n const imageData = await Promise.all(images.map(x => this.preprocess(x)));\n const trimapData = await Promise.all(trimaps.map(x => this.preprocess(x, {\n do_normalize: false,\n do_convert_rgb: false,\n do_convert_grayscale: true,\n })));\n\n\n // Stack pixel values\n const pixel_values = stack(imageData.map(\n // Concatenate images and trimaps\n (x, i) => cat([x.pixel_values, trimapData[i].pixel_values], 0)\n ), 0);\n\n return {\n pixel_values,\n\n // Original sizes of images\n original_sizes: imageData.map(x => x.original_size),\n\n // Reshaped sizes of images, before padding or cropping\n reshaped_input_sizes: imageData.map(x => x.reshaped_input_size),\n }\n }\n}\n\nexport class WhisperFeatureExtractor extends FeatureExtractor {\n\n constructor(config) {\n super(config);\n\n // Prefer given `mel_filters` from preprocessor_config.json, or calculate them if they don't exist.\n this.config.mel_filters ??= mel_filter_bank(\n Math.floor(1 + this.config.n_fft / 2), // num_frequency_bins\n this.config.feature_size, // num_mel_filters\n 0.0, // min_frequency\n 8000.0, // max_frequency\n this.config.sampling_rate, // sampling_rate\n \"slaney\", // norm\n \"slaney\", // mel_scale\n );\n\n this.window = window_function(this.config.n_fft, 'hann');\n }\n\n /**\n * Computes the log-Mel spectrogram of the provided audio waveform.\n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform) {\n const features = await spectrogram(\n waveform,\n this.window, // window\n this.config.n_fft, // frame_length\n this.config.hop_length, // hop_length\n {\n power: 2.0,\n mel_filters: this.config.mel_filters,\n log_mel: 'log10',\n\n // Custom\n max_num_frames: this.config.nb_max_frames, // 3000\n }\n )\n\n const data = features.data;\n const maxValue = max(data)[0];\n\n for (let i = 0; i < data.length; ++i) {\n data[i] = (Math.max(data[i], maxValue - 8.0) + 4.0) / 4.0;\n }\n\n return features;\n }\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'WhisperFeatureExtractor');\n\n let waveform;\n if (audio.length > this.config.n_samples) {\n console.warn(\n \"Attempting to extract features for audio longer than 30 seconds. \" +\n \"If using a pipeline to extract transcript from a long audio clip, \" +\n \"remember to specify `chunk_length_s` and/or `stride_length_s`.\"\n );\n waveform = audio.slice(0, this.config.n_samples);\n } else {\n // pad with zeros\n waveform = new Float32Array(this.config.n_samples);\n waveform.set(audio);\n }\n\n const features = await this._extract_fbank_features(waveform);\n\n return {\n input_features: features.unsqueeze_(0)\n };\n }\n}\n\nexport class Wav2Vec2FeatureExtractor extends FeatureExtractor {\n\n /**\n * @param {Float32Array} input_values \n * @returns {Float32Array} \n */\n _zero_mean_unit_var_norm(input_values) {\n // TODO support batch?\n const sum = input_values.reduce((a, b) => a + b, 0);\n const mean = sum / input_values.length;\n const variance = input_values.reduce((a, b) => a + (b - mean) ** 2, 0) / input_values.length;\n return input_values.map(x => (x - mean) / Math.sqrt(variance + 1e-7));\n }\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_values: Tensor; attention_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention mask as Tensors.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'Wav2Vec2FeatureExtractor');\n\n if (audio instanceof Float64Array) {\n audio = new Float32Array(audio);\n }\n\n let input_values = audio;\n\n // zero-mean and unit-variance normalization\n if (this.config.do_normalize) {\n input_values = this._zero_mean_unit_var_norm(input_values);\n }\n\n // TODO: allow user to pass in attention mask\n const shape = [1, input_values.length];\n return {\n input_values: new Tensor('float32', input_values, shape),\n attention_mask: new Tensor('int64', new BigInt64Array(input_values.length).fill(1n), shape)\n };\n }\n}\n\nexport class SeamlessM4TFeatureExtractor extends FeatureExtractor {\n\n constructor(config) {\n super(config);\n\n const sampling_rate = this.config.sampling_rate;\n const mel_filters = mel_filter_bank(\n 256, // num_frequency_bins\n this.config.num_mel_bins, // num_mel_filters\n 20, // min_frequency\n Math.floor(sampling_rate / 2), // max_frequency\n sampling_rate, // sampling_rate\n null, // norm\n \"kaldi\", // mel_scale\n true, // triangularize_in_mel_space\n );\n\n // Do padding:\n for (let i = 0; i < mel_filters.length; ++i) {\n mel_filters[i].push(0);\n }\n this.mel_filters = mel_filters;\n\n this.window = window_function(400, 'povey', {\n periodic: false,\n })\n }\n\n /**\n * Computes the log-Mel spectrogram of the provided audio waveform.\n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @param {number} max_length The maximum number of frames to return.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform, max_length) {\n // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`\n\n // Kaldi compliance: 16-bit signed integers\n // 32768 == 2 ** 15\n waveform = waveform.map((/** @type {number} */ x) => x * 32768)\n\n return spectrogram(\n waveform,\n this.window, // window\n 400, // frame_length\n 160, // hop_length\n {\n fft_length: 512,\n power: 2.0,\n center: false,\n preemphasis: 0.97,\n mel_filters: this.mel_filters,\n log_mel: 'log',\n mel_floor: 1.192092955078125e-07,\n remove_dc_offset: true,\n\n // Custom\n max_num_frames: max_length,\n transpose: true,\n }\n )\n }\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @param {Object} options Optional parameters for feature extraction.\n * @param {boolean} [options.padding=true] Whether to pad the sequence to a multiple of `pad_to_multiple_of`.\n * @param {number} [options.pad_to_multiple_of=2] The number to pad the sequence to a multiple of.\n * @param {boolean} [options.do_normalize_per_mel_bins=true] Whether or not to zero-mean unit-variance normalize the input per mel-channel.\n * @param {boolean} [options.return_attention_mask=true] Whether to return the attention mask.\n * @returns {Promise<{ input_features: Tensor, attention_mask?: Tensor }>} A Promise resolving to an object containing the extracted input features and attention masks as Tensors.\n */\n async _call(audio, {\n padding = true,\n pad_to_multiple_of = 2,\n do_normalize_per_mel_bins = true,\n return_attention_mask = true,\n } = {}) {\n validate_audio_inputs(audio, 'SeamlessM4TFeatureExtractor');\n\n let features = await this._extract_fbank_features(audio, this.config.max_length);\n\n if (do_normalize_per_mel_bins) {\n const [num_features, feature_size] = features.dims;\n const data = features.data;\n for (let i = 0; i < feature_size; ++i) {\n let sum = 0;\n for (let j = 0; j < num_features; ++j) {\n sum += data[j * feature_size + i];\n }\n\n const mean = sum / num_features;\n\n let variance = 0;\n for (let j = 0; j < num_features; ++j) {\n variance += (data[j * feature_size + i] - mean) ** 2;\n }\n variance /= num_features - 1; // NOTE: We use ddof=1\n\n const std = Math.sqrt(variance + 1e-7);\n for (let j = 0; j < num_features; ++j) {\n const index = j * feature_size + i;\n data[index] = (data[index] - mean) / std;\n }\n }\n }\n\n let padded_attention_mask;\n if (padding) {\n const [num_frames, num_channels] = features.dims;\n const data = /** @type {Float32Array} */(features.data);\n\n const pad_size = num_frames % pad_to_multiple_of;\n if (pad_size > 0) {\n const padded_data = new Float32Array(num_channels * (num_frames + pad_size));\n padded_data.set(data)\n padded_data.fill(this.config.padding_value, data.length)\n\n const numPaddedFrames = num_frames + pad_size;\n features = new Tensor(\n features.type,\n padded_data,\n [numPaddedFrames, num_channels],\n )\n\n if (return_attention_mask) {\n padded_attention_mask = new Tensor(\n 'int64',\n new BigInt64Array(numPaddedFrames),\n [1, numPaddedFrames],\n )\n padded_attention_mask.data.fill(1n, 0, num_frames);\n }\n }\n }\n\n const [num_frames, num_channels] = features.dims;\n\n const stride = this.config.stride;\n const remainder = num_frames % stride;\n if (remainder !== 0) {\n throw new Error(`The number of frames (${num_frames}) must be a multiple of the stride (${stride}).`)\n }\n\n const input_features = features.view(\n 1,\n Math.floor(num_frames / stride),\n num_channels * stride,\n );\n\n const result = { input_features }\n\n if (return_attention_mask) {\n const reshapedNumFrames = input_features.dims[1];\n\n const attention_mask_data = new BigInt64Array(reshapedNumFrames);\n\n if (padded_attention_mask) {\n const padded_attention_mask_data = padded_attention_mask.data;\n for (let i = 1, j = 0; i < num_frames; i += stride, ++j) {\n attention_mask_data[j] = padded_attention_mask_data[i];\n }\n } else {\n attention_mask_data.fill(1n);\n }\n result.attention_mask = new Tensor(\n 'int64',\n attention_mask_data,\n [1, reshapedNumFrames],\n );\n }\n\n return result;\n }\n}\n\nexport class ASTFeatureExtractor extends FeatureExtractor {\n\n\n constructor(config) {\n super(config);\n\n const sampling_rate = this.config.sampling_rate;\n const mel_filters = mel_filter_bank(\n 256, // num_frequency_bins\n this.config.num_mel_bins, // num_mel_filters\n 20, // min_frequency\n Math.floor(sampling_rate / 2), // max_frequency\n sampling_rate, // sampling_rate\n null, // norm\n \"kaldi\", // mel_scale\n true, // triangularize_in_mel_space\n );\n\n // Do padding:\n for (let i = 0; i < mel_filters.length; ++i) {\n mel_filters[i].push(0);\n }\n this.mel_filters = mel_filters;\n\n this.window = window_function(400, 'hann', {\n periodic: false,\n })\n\n this.mean = this.config.mean;\n this.std = this.config.std;\n }\n\n /**\n * Computes the log-Mel spectrogram of the provided audio waveform.\n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @param {number} max_length The maximum number of frames to return.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform, max_length) {\n // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`\n return spectrogram(\n waveform,\n this.window, // window\n 400, // frame_length\n 160, // hop_length\n {\n fft_length: 512,\n power: 2.0,\n center: false,\n preemphasis: 0.97,\n mel_filters: this.mel_filters,\n log_mel: 'log',\n mel_floor: 1.192092955078125e-07,\n remove_dc_offset: true,\n\n // Custom\n max_num_frames: max_length,\n transpose: true,\n }\n )\n }\n\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_values: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'ASTFeatureExtractor');\n\n const features = await this._extract_fbank_features(audio, this.config.max_length);\n if (this.config.do_normalize) {\n // Normalize the input audio spectrogram to have mean=0, std=0.5\n const denom = this.std * 2;\n const features_data = features.data;\n for (let i = 0; i < features_data.length; ++i) {\n features_data[i] = (features_data[i] - this.mean) / denom;\n }\n }\n\n return {\n input_values: features.unsqueeze_(0)\n };\n }\n}\n\nexport class ClapFeatureExtractor extends FeatureExtractor {\n\n constructor(config) {\n super(config);\n\n this.mel_filters = mel_filter_bank(\n this.config.nb_frequency_bins, // num_frequency_bins\n this.config.feature_size, // num_mel_filters\n this.config.frequency_min, // min_frequency\n this.config.frequency_max, // max_frequency\n this.config.sampling_rate, // sampling_rate\n null, // norm\n \"htk\", // mel_scale\n );\n\n this.mel_filters_slaney = mel_filter_bank(\n this.config.nb_frequency_bins, // num_frequency_bins\n this.config.feature_size, // num_mel_filters\n this.config.frequency_min, // min_frequency\n this.config.frequency_max, // max_frequency\n this.config.sampling_rate, // sampling_rate\n \"slaney\", // norm\n \"slaney\", // mel_scale\n );\n\n this.window = window_function(this.config.fft_window_size, 'hann')\n\n }\n\n\n /**\n * Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments.\n * \n * Four different path are possible:\n * - `truncation=\"fusion\"` and the length of the waveform is greater than the max length: the mel spectrogram\n * will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram\n * are then stacked together. They will later be used for `feature_fusion`.\n * - `truncation=\"rand_trunc\"` and the length of the waveform is smaller than the max length: the audio is\n * padded based on `padding`.\n * - `truncation=\"fusion\"` and the length of the waveform is smaller than the max length: the audio is padded\n * based on `padding`, and is repeated `4` times.\n * - `truncation=\"rand_trunc\"` and the length of the waveform is greater than the max length: the mel\n * spectrogram will be computed on a random crop of the waveform.\n * \n * @param {Float32Array|Float64Array} waveform The input waveform.\n * @param {number} max_length The maximum length of the waveform.\n * @param {string} truncation The truncation strategy to use.\n * @param {string} padding The padding strategy to use.\n * @returns {Promise} An object containing the mel spectrogram data as a Float32Array, its dimensions as an array of numbers, and a boolean indicating whether the waveform was longer than the max length.\n * @private\n */\n async _get_input_mel(waveform, max_length, truncation, padding) {\n\n /** @type {Tensor} */\n let input_mel;\n let longer = false;\n const diff = waveform.length - max_length;\n if (diff > 0) {\n if (truncation === 'rand_trunc') {\n longer = true;\n const idx = Math.floor(Math.random() * (diff + 1));\n waveform = waveform.subarray(idx, idx + max_length);\n\n input_mel = await this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples);\n } else {\n // TODO implement fusion strategy\n throw new Error(`Truncation strategy \"${truncation}\" not implemented`)\n }\n } else {\n if (diff < 0) {\n let padded = new Float64Array(max_length); // already padded with zeros\n padded.set(waveform);\n\n if (padding === 'repeat') {\n for (let i = waveform.length; i < max_length; i += waveform.length) {\n padded.set(waveform.subarray(0, Math.min(waveform.length, max_length - i)), i);\n }\n } else if (padding === 'repeatpad') {\n for (let i = waveform.length; i < -diff; i += waveform.length) {\n padded.set(waveform, i);\n }\n }\n waveform = padded;\n }\n\n if (truncation === 'fusion') {\n throw new Error(`Truncation strategy \"${truncation}\" not implemented`)\n }\n\n input_mel = await this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples);\n }\n\n return input_mel.unsqueeze_(0);\n }\n\n /**\n * Compute the log-mel spectrogram of the provided `waveform` using the Hann window.\n * In CLAP, two different filter banks are used depending on the truncation pattern:\n * - `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from\n * calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation`\n * is set to `\"fusion\"`.\n * - `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used\n * `librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original\n * implementation when the truncation mode is not `\"fusion\"`.\n * \n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @param {number[][]} mel_filters The mel filters to use.\n * @param {number} [max_length=null] The maximum number of frames to return.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform, mel_filters, max_length = null) {\n // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`\n return spectrogram(\n waveform,\n this.window, // window\n this.config.fft_window_size, // frame_length\n this.config.hop_length, // hop_length\n {\n power: 2.0,\n mel_filters,\n log_mel: 'dB',\n\n // Custom\n max_num_frames: max_length,\n do_pad: false,\n transpose: true,\n }\n )\n }\n\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.\n */\n async _call(audio, {\n max_length = null,\n } = {}) {\n validate_audio_inputs(audio, 'ClapFeatureExtractor');\n\n // convert to mel spectrogram, truncate and pad if needed.\n const padded_inputs = await this._get_input_mel(\n audio,\n max_length ?? this.config.nb_max_samples,\n this.config.truncation,\n this.config.padding,\n );\n\n return {\n input_features: padded_inputs.unsqueeze_(0),\n }\n }\n}\n\n\nexport class PyAnnoteFeatureExtractor extends FeatureExtractor {\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_values: Tensor; }>} The extracted input features.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'PyAnnoteFeatureExtractor');\n\n if (audio instanceof Float64Array) {\n audio = new Float32Array(audio);\n }\n\n const shape = [\n 1, /* batch_size */\n 1, /* num_channels */\n audio.length, /* num_samples */\n ];\n return {\n input_values: new Tensor('float32', audio, shape),\n };\n }\n\n /**\n * NOTE: Can return fractional values. `Math.ceil` will ensure correct value.\n * @param {number} samples The number of frames in the audio.\n * @returns {number} The number of frames in the audio.\n */\n samples_to_frames(samples) {\n return ((samples - this.config.offset) / this.config.step);\n }\n\n /**\n * Post-processes the speaker diarization logits output by the model.\n * @param {Tensor} logits The speaker diarization logits output by the model.\n * @param {number} num_samples Number of samples in the input audio.\n * @returns {Array>} The post-processed speaker diarization results.\n */\n post_process_speaker_diarization(logits, num_samples) {\n const ratio = (\n num_samples / this.samples_to_frames(num_samples)\n ) / this.config.sampling_rate;\n\n const results = [];\n for (const scores of logits.tolist()) {\n const accumulated_segments = [];\n\n let current_speaker = -1;\n for (let i = 0; i < scores.length; ++i) {\n const probabilities = softmax(scores[i]);\n const [score, id] = max(probabilities);\n const [start, end] = [i, i + 1];\n\n if (id !== current_speaker) {\n // Speaker has changed\n current_speaker = id;\n accumulated_segments.push({ id, start, end, score });\n } else {\n // Continue the current segment\n accumulated_segments.at(-1).end = end;\n accumulated_segments.at(-1).score += score;\n }\n }\n\n results.push(accumulated_segments.map(\n // Convert frame-space to time-space\n // and compute the confidence\n ({ id, start, end, score }) => ({\n id,\n start: start * ratio,\n end: end * ratio,\n confidence: score / (end - start),\n })\n ));\n }\n return results;\n }\n\n}\n\nexport class WeSpeakerFeatureExtractor extends FeatureExtractor {\n\n constructor(config) {\n super(config);\n\n const sampling_rate = this.config.sampling_rate;\n const mel_filters = mel_filter_bank(\n 256, // num_frequency_bins\n this.config.num_mel_bins, // num_mel_filters\n 20, // min_frequency\n Math.floor(sampling_rate / 2), // max_frequency\n sampling_rate, // sampling_rate\n null, // norm\n \"kaldi\", // mel_scale\n true, // triangularize_in_mel_space\n );\n\n // Do padding:\n for (let i = 0; i < mel_filters.length; ++i) {\n mel_filters[i].push(0);\n }\n this.mel_filters = mel_filters;\n\n this.window = window_function(400, 'hamming', {\n periodic: false,\n })\n this.min_num_frames = this.config.min_num_frames;\n }\n\n /**\n * Computes the log-Mel spectrogram of the provided audio waveform.\n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform) {\n // Kaldi compliance: 16-bit signed integers\n // 32768 == 2 ** 15\n waveform = waveform.map((/** @type {number} */ x) => x * 32768)\n\n return spectrogram(\n waveform,\n this.window, // window\n 400, // frame_length\n 160, // hop_length\n {\n fft_length: 512,\n power: 2.0,\n center: false,\n preemphasis: 0.97,\n mel_filters: this.mel_filters,\n log_mel: 'log',\n mel_floor: 1.192092955078125e-07,\n remove_dc_offset: true,\n\n // Custom\n transpose: true,\n min_num_frames: this.min_num_frames,\n }\n )\n }\n\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'WeSpeakerFeatureExtractor');\n\n const features = (await this._extract_fbank_features(audio)).unsqueeze_(0);\n\n if (this.config.fbank_centering_span === null) {\n // center features with global average\n const meanData = /** @type {Float32Array} */ (features.mean(1).data);\n const featuresData = /** @type {Float32Array} */(features.data);\n const [batch_size, num_frames, feature_size] = features.dims;\n\n for (let i = 0; i < batch_size; ++i) {\n const offset1 = i * num_frames * feature_size;\n const offset2 = i * feature_size;\n for (let j = 0; j < num_frames; ++j) {\n const offset3 = offset1 + j * feature_size;\n for (let k = 0; k < feature_size; ++k) {\n featuresData[offset3 + k] -= meanData[offset2 + k];\n }\n }\n }\n }\n\n return {\n input_features: features\n };\n }\n}\n\nexport class SpeechT5FeatureExtractor extends FeatureExtractor { }\n\n/**\n * Represents a Processor that extracts features from an input.\n * @extends Callable\n */\nexport class Processor extends Callable {\n /**\n * Creates a new Processor with the given feature extractor.\n * @param {FeatureExtractor} feature_extractor The function used to extract features from the input.\n */\n constructor(feature_extractor) {\n super();\n this.feature_extractor = feature_extractor;\n // TODO use tokenizer here?\n }\n\n /**\n * Calls the feature_extractor function with the given input.\n * @param {any} input The input to extract features from.\n * @param {...any} args Additional arguments.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(input, ...args) {\n return await this.feature_extractor(input, ...args);\n }\n}\n\nexport class SamProcessor extends Processor {\n /**\n * @borrows SamImageProcessor#_call as _call\n */\n async _call(...args) {\n return await this.feature_extractor(...args);\n }\n\n /**\n * @borrows SamImageProcessor#post_process_masks as post_process_masks\n */\n post_process_masks(...args) {\n // @ts-ignore\n return this.feature_extractor.post_process_masks(...args);\n }\n /**\n * @borrows SamImageProcessor#reshape_input_points as reshape_input_points\n */\n reshape_input_points(...args) {\n // @ts-ignore\n return this.feature_extractor.reshape_input_points(...args);\n }\n}\n\n/**\n * Represents a WhisperProcessor that extracts features from an audio input.\n * @extends Processor\n */\nexport class WhisperProcessor extends Processor {\n /**\n * Calls the feature_extractor function with the given audio input.\n * @param {any} audio The audio input to extract features from.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(audio) {\n return await this.feature_extractor(audio)\n }\n}\n\n\nexport class Wav2Vec2ProcessorWithLM extends Processor {\n /**\n * Calls the feature_extractor function with the given audio input.\n * @param {any} audio The audio input to extract features from.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(audio) {\n return await this.feature_extractor(audio)\n }\n}\n\nexport class PyAnnoteProcessor extends Processor {\n /**\n * Calls the feature_extractor function with the given audio input.\n * @param {any} audio The audio input to extract features from.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(audio) {\n return await this.feature_extractor(audio)\n }\n\n post_process_speaker_diarization(...args) {\n // @ts-ignore\n return this.feature_extractor.post_process_speaker_diarization(...args);\n }\n\n}\n\nexport class SpeechT5Processor extends Processor {\n /**\n * Calls the feature_extractor function with the given input.\n * @param {any} input The input to extract features from.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(input) {\n return await this.feature_extractor(input)\n }\n}\n\nexport class OwlViTProcessor extends Processor { }\n\nexport class Florence2Processor extends Processor {\n constructor(feature_extractor) {\n super(feature_extractor);\n\n const {\n tasks_answer_post_processing_type,\n task_prompts_without_inputs,\n task_prompts_with_input,\n } = feature_extractor.config;\n\n /** @type {Map} */\n this.tasks_answer_post_processing_type = new Map(Object.entries(tasks_answer_post_processing_type ?? {}));\n\n /** @type {Map} */\n this.task_prompts_without_inputs = new Map(Object.entries(task_prompts_without_inputs ?? {}));\n\n /** @type {Map} */\n this.task_prompts_with_input = new Map(Object.entries(task_prompts_with_input ?? {}));\n\n this.regexes = {\n quad_boxes: /(.+?)/gm,\n bboxes: /([^<]+)?/gm,\n }\n this.size_per_bin = 1000;\n }\n\n /**\n * Helper function to construct prompts from input texts\n * @param {string|string[]} text\n * @returns {string[]}\n */\n construct_prompts(text) {\n if (typeof text === 'string') {\n text = [text];\n }\n\n const prompts = [];\n for (const t of text) {\n // 1. fixed task prompts without additional inputs\n if (this.task_prompts_without_inputs.has(t)) {\n prompts.push(this.task_prompts_without_inputs.get(t));\n }\n // 2. task prompts with additional inputs \n else {\n for (const [task, prompt] of this.task_prompts_with_input) {\n if (t.includes(task)) {\n prompts.push(prompt.replaceAll('{input}', t).replaceAll(task, ''));\n break;\n }\n }\n\n // 3. default prompt\n if (prompts.length !== text.length) {\n prompts.push(t);\n }\n }\n }\n return prompts;\n }\n\n /**\n * Post-process the output of the model to each of the task outputs.\n * @param {string} text The text to post-process.\n * @param {string} task The task to post-process the text for.\n * @param {[number, number]} image_size The size of the image. height x width.\n */\n post_process_generation(text, task, image_size) {\n const task_answer_post_processing_type = this.tasks_answer_post_processing_type.get(task) ?? 'pure_text';\n\n // remove the special tokens\n text = text.replaceAll('', '').replaceAll('', '');\n\n let final_answer;\n switch (task_answer_post_processing_type) {\n case 'pure_text':\n final_answer = text;\n break;\n\n case 'description_with_bboxes':\n case 'bboxes':\n case 'phrase_grounding':\n case 'ocr':\n const key = task_answer_post_processing_type === 'ocr' ? 'quad_boxes' : 'bboxes';\n const matches = text.matchAll(this.regexes[key]);\n const labels = [];\n const items = [];\n for (const [_, label, ...locations] of matches) {\n // Push new label, or duplicate the last label\n labels.push(label ? label.trim() : labels.at(-1) ?? '');\n items.push(locations.map((x, i) =>\n // NOTE: Add 0.5 to use the center position of the bin as the coordinate.\n (Number(x) + 0.5) / this.size_per_bin * image_size[i % 2])\n );\n }\n final_answer = { labels, [key]: items };\n break;\n\n default:\n throw new Error(`Task \"${task}\" (of type \"${task_answer_post_processing_type}\") not yet implemented.`);\n }\n\n return { [task]: final_answer }\n }\n}\n\n//////////////////////////////////////////////////\n/**\n * Helper class which is used to instantiate pretrained processors with the `from_pretrained` function.\n * The chosen processor class is determined by the type specified in the processor config.\n * \n * **Example:** Load a processor using `from_pretrained`.\n * ```javascript\n * let processor = await AutoProcessor.from_pretrained('openai/whisper-tiny.en');\n * ```\n * \n * **Example:** Run an image through a processor.\n * ```javascript\n * let processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16');\n * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * let image_inputs = await processor(image);\n * // {\n * // \"pixel_values\": {\n * // \"dims\": [ 1, 3, 224, 224 ],\n * // \"type\": \"float32\",\n * // \"data\": Float32Array [ -1.558687686920166, -1.558687686920166, -1.5440893173217773, ... ],\n * // \"size\": 150528\n * // },\n * // \"original_sizes\": [\n * // [ 533, 800 ]\n * // ],\n * // \"reshaped_input_sizes\": [\n * // [ 224, 224 ]\n * // ]\n * // }\n * ```\n */\nexport class AutoProcessor {\n static FEATURE_EXTRACTOR_CLASS_MAPPING = {\n ImageFeatureExtractor,\n WhisperFeatureExtractor,\n ViTFeatureExtractor,\n MobileViTFeatureExtractor,\n MobileViTImageProcessor,\n MobileNetV1FeatureExtractor,\n MobileNetV2FeatureExtractor,\n MobileNetV3FeatureExtractor,\n MobileNetV4FeatureExtractor,\n OwlViTFeatureExtractor,\n Owlv2ImageProcessor,\n CLIPFeatureExtractor,\n CLIPImageProcessor,\n Florence2Processor,\n ChineseCLIPFeatureExtractor,\n SiglipImageProcessor,\n ConvNextFeatureExtractor,\n ConvNextImageProcessor,\n SegformerFeatureExtractor,\n SapiensFeatureExtractor,\n BitImageProcessor,\n DPTImageProcessor,\n DPTFeatureExtractor,\n PvtImageProcessor,\n GLPNFeatureExtractor,\n BeitFeatureExtractor,\n DeiTFeatureExtractor,\n DetrFeatureExtractor,\n RTDetrImageProcessor,\n MaskFormerFeatureExtractor,\n YolosFeatureExtractor,\n DonutFeatureExtractor,\n NougatImageProcessor,\n EfficientNetImageProcessor,\n\n ViTImageProcessor,\n VitMatteImageProcessor,\n SamImageProcessor,\n Swin2SRImageProcessor,\n Wav2Vec2FeatureExtractor,\n SeamlessM4TFeatureExtractor,\n SpeechT5FeatureExtractor,\n ASTFeatureExtractor,\n ClapFeatureExtractor,\n PyAnnoteFeatureExtractor,\n WeSpeakerFeatureExtractor,\n }\n\n static PROCESSOR_CLASS_MAPPING = {\n WhisperProcessor,\n Wav2Vec2ProcessorWithLM,\n PyAnnoteProcessor,\n SamProcessor,\n SpeechT5Processor,\n OwlViTProcessor,\n Florence2Processor,\n }\n\n /**\n * Instantiate one of the processor classes of the library from a pretrained model.\n * \n * The processor class to instantiate is selected based on the `feature_extractor_type` property of the config object\n * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)\n * \n * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:\n * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co.\n * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a\n * user or organization name, like `dbmdz/bert-base-german-cased`.\n * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`.\n * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the processor.\n * \n * @returns {Promise} A new instance of the Processor class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n } = {}) {\n\n let preprocessorConfig = config ?? await getModelJSON(pretrained_model_name_or_path, 'preprocessor_config.json', true, {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n })\n\n // Determine feature extractor class\n // TODO: Ensure backwards compatibility with old configs\n let key = preprocessorConfig.feature_extractor_type ?? preprocessorConfig.image_processor_type;\n let feature_extractor_class = this.FEATURE_EXTRACTOR_CLASS_MAPPING[key];\n\n if (!feature_extractor_class) {\n if (preprocessorConfig.size !== undefined) {\n // Assume ImageFeatureExtractor\n console.warn(`Feature extractor type \"${key}\" not found, assuming ImageFeatureExtractor due to size parameter in config.`);\n feature_extractor_class = ImageFeatureExtractor;\n } else {\n throw new Error(`Unknown Feature Extractor type: ${key}`);\n }\n }\n\n // If no associated processor class, use default\n let processor_class = this.PROCESSOR_CLASS_MAPPING[preprocessorConfig.processor_class] ?? Processor;\n\n // Instantiate processor and feature extractor\n let feature_extractor = new feature_extractor_class(preprocessorConfig);\n return new processor_class(feature_extractor);\n }\n}\n//////////////////////////////////////////////////\n\n","\n/**\n * @file Tokenizers are used to prepare textual inputs for a model.\n * \n * **Example:** Create an `AutoTokenizer` and use it to tokenize a sentence.\n * This will automatically detect the tokenizer type based on the tokenizer class defined in `tokenizer.json`.\n * ```javascript\n * import { AutoTokenizer } from '@huggingface/transformers';\n * \n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');\n * const { input_ids } = await tokenizer('I love transformers!');\n * // Tensor {\n * // data: BigInt64Array(6) [101n, 1045n, 2293n, 19081n, 999n, 102n],\n * // dims: [1, 6],\n * // type: 'int64',\n * // size: 6,\n * // }\n * ```\n * \n * @module tokenizers\n */\nimport {\n Callable,\n} from './utils/generic.js';\n\nimport {\n reverseDictionary,\n escapeRegExp,\n isIntegralNumber,\n mergeArrays,\n len,\n} from './utils/core.js';\n\nimport {\n getModelJSON,\n} from './utils/hub.js';\n\nimport { max, min, round } from './utils/maths.js';\nimport { Tensor } from './utils/tensor.js';\n\nimport {\n PriorityQueue,\n TokenLattice,\n CharTrie,\n} from './utils/data-structures.js';\n\nimport { Template } from '@huggingface/jinja';\n\nimport {\n WHISPER_LANGUAGE_MAPPING,\n whisper_language_to_code,\n} from './models/whisper/common_whisper.js';\nimport { GITHUB_ISSUE_URL } from './utils/constants.js';\n\n/**\n * @typedef {Object} TokenizerProperties Additional tokenizer-specific properties.\n * @property {boolean} [legacy=false] Whether or not the `legacy` behavior of the tokenizer should be used.\n * @typedef {import('./utils/hub.js').PretrainedOptions & TokenizerProperties} PretrainedTokenizerOptions\n */\n\n/**\n * Loads a tokenizer from the specified path.\n * @param {string} pretrained_model_name_or_path The path to the tokenizer directory.\n * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.\n * @returns {Promise} A promise that resolves with information about the loaded tokenizer.\n */\nasync function loadTokenizer(pretrained_model_name_or_path, options) {\n\n const info = await Promise.all([\n getModelJSON(pretrained_model_name_or_path, 'tokenizer.json', true, options),\n getModelJSON(pretrained_model_name_or_path, 'tokenizer_config.json', true, options),\n ])\n\n // Override legacy option if `options.legacy` is not null\n if (options.legacy !== null) {\n info[1].legacy = options.legacy;\n }\n return info;\n}\n\n\n/**\n * Helper function to split a string on a regex, but keep the delimiters.\n * This is required, because the JavaScript `.split()` method does not keep the delimiters,\n * and wrapping in a capturing group causes issues with existing capturing groups (due to nesting).\n * @param {string} text The text to split.\n * @param {RegExp} regex The regex to split on.\n * @returns {string[]} The split string.\n */\nfunction regexSplit(text, regex) {\n const result = [];\n let prev = 0;\n for (const match of text.matchAll(regex)) {\n const fullMatch = match[0];\n if (prev < match.index) {\n result.push(text.slice(prev, match.index));\n }\n if (fullMatch.length > 0) {\n result.push(fullMatch);\n }\n prev = match.index + fullMatch.length;\n }\n if (prev < text.length) {\n result.push(text.slice(prev));\n }\n return result;\n}\n\n\n/**\n * Helper method to construct a pattern from a config object.\n * @param {Object} pattern The pattern object.\n * @param {boolean} invert Whether to invert the pattern.\n * @returns {RegExp|null} The compiled pattern.\n */\nfunction createPattern(pattern, invert = true) {\n\n if (pattern.Regex !== undefined) {\n // In certain cases, the pattern may contain unnecessary escape sequences (e.g., \\# or \\& or \\~).\n // i.e., valid in Python (where the patterns are exported from) but invalid in JavaScript (where the patterns are parsed).\n // This isn't an issue when creating the regex w/o the 'u' flag, but it is when the 'u' flag is used.\n // For this reason, it is necessary to remove these backslashes before creating the regex.\n // See https://stackoverflow.com/a/63007777/13989043 for more information\n let regex = pattern.Regex.replace(/\\\\([#&~])/g, '$1'); // TODO: add more characters to this list if necessary\n\n // We also handle special cases where the regex contains invalid (non-JS compatible) syntax.\n for (const [key, value] of PROBLEMATIC_REGEX_MAP) {\n regex = regex.replaceAll(key, value);\n }\n\n return new RegExp(regex, 'gu');\n\n } else if (pattern.String !== undefined) {\n const escaped = escapeRegExp(pattern.String);\n // NOTE: if invert is true, we wrap the pattern in a group so that it is kept when performing .split()\n return new RegExp(invert ? escaped : `(${escaped})`, 'gu');\n\n } else {\n console.warn('Unknown pattern type:', pattern)\n return null;\n }\n}\n\n/**\n * Helper function to convert an Object to a Map\n * @param {Object} obj The object to convert.\n * @returns {Map} The map.\n */\nfunction objectToMap(obj) {\n return new Map(Object.entries(obj));\n}\n\n/**\n * Helper function to convert a tensor to a list before decoding.\n * @param {Tensor} tensor The tensor to convert.\n * @returns {number[]} The tensor as a list.\n */\nfunction prepareTensorForDecode(tensor) {\n const dims = tensor.dims;\n switch (dims.length) {\n case 1:\n return tensor.tolist();\n case 2:\n if (dims[0] !== 1) {\n throw new Error('Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.');\n }\n return tensor.tolist()[0];\n default:\n throw new Error(`Expected tensor to have 1-2 dimensions, got ${dims.length}.`)\n }\n}\n\n/**\n * Clean up a list of simple English tokenization artifacts like spaces before punctuations and abbreviated forms\n * @param {string} text The text to clean up.\n * @returns {string} The cleaned up text.\n */\nfunction clean_up_tokenization(text) {\n // Clean up a list of simple English tokenization artifacts\n // like spaces before punctuations and abbreviated forms\n return text.replace(/ \\./g, '.')\n .replace(/ \\?/g, '?')\n .replace(/ \\!/g, '!')\n .replace(/ ,/g, ',')\n .replace(/ \\' /g, \"'\")\n .replace(/ n\\'t/g, \"n't\")\n .replace(/ \\'m/g, \"'m\")\n .replace(/ \\'s/g, \"'s\")\n .replace(/ \\'ve/g, \"'ve\")\n .replace(/ \\'re/g, \"'re\");\n}\n\n/**\n * Helper function to remove accents from a string.\n * @param {string} text The text to remove accents from.\n * @returns {string} The text with accents removed.\n */\nfunction remove_accents(text) {\n return text.replace(/\\p{M}/gu, '');\n}\n\n/**\n * Helper function to lowercase a string and remove accents.\n * @param {string} text The text to lowercase and remove accents from.\n * @returns {string} The lowercased text with accents removed.\n */\nfunction lowercase_and_remove_accent(text) {\n return remove_accents(text.toLowerCase());\n}\n\n\n/**\n * Checks whether the given Unicode codepoint represents a CJK (Chinese, Japanese, or Korean) character.\n *\n * A \"chinese character\" is defined as anything in the CJK Unicode block:\n * https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)\n *\n * Note that the CJK Unicode block is NOT all Japanese and Korean characters, despite its name.\n * The modern Korean Hangul alphabet is a different block, as is Japanese Hiragana and Katakana.\n * Those alphabets are used to write space-separated words, so they are not treated specially\n * and are handled like all other languages.\n *\n * @param {number|bigint} cp The Unicode codepoint to check.\n * @returns {boolean} True if the codepoint represents a CJK character, false otherwise.\n */\nexport function is_chinese_char(cp) {\n return (\n (cp >= 0x4E00 && cp <= 0x9FFF)\n || (cp >= 0x3400 && cp <= 0x4DBF)\n || (cp >= 0x20000 && cp <= 0x2A6DF)\n || (cp >= 0x2A700 && cp <= 0x2B73F)\n || (cp >= 0x2B740 && cp <= 0x2B81F)\n || (cp >= 0x2B820 && cp <= 0x2CEAF)\n || (cp >= 0xF900 && cp <= 0xFAFF)\n || (cp >= 0x2F800 && cp <= 0x2FA1F)\n )\n}\n\n/**\n * Helper function to fuse consecutive unknown tokens.\n * @param {string[]} arr The list of input tokens\n * @param {Map} tokens_to_ids The mapping from tokens to token ids.\n * @param {number} unk_token_id The value to fuse on.\n * @private\n */\nfunction fuse_unk(arr, tokens_to_ids, unk_token_id) {\n const fused = [];\n let i = 0;\n while (i < arr.length) {\n fused.push(arr[i])\n if ((tokens_to_ids.get(arr[i]) ?? unk_token_id) !== unk_token_id) {\n ++i;\n continue;\n }\n\n while (++i < arr.length && (tokens_to_ids.get(arr[i]) ?? unk_token_id) === unk_token_id) {\n if (tokens_to_ids.get(fused.at(-1)) !== unk_token_id) {\n fused[fused.length - 1] += arr[i];\n }\n }\n }\n\n return fused;\n}\n\n/**\n * Split a string on whitespace.\n * @param {string} text The text to split.\n * @returns {string[]} The split string.\n */\nfunction whitespace_split(text) {\n return text.match(/\\S+/g) || [];\n}\n\nconst PUNCTUATION_REGEX = '\\\\p{P}\\\\u0021-\\\\u002F\\\\u003A-\\\\u0040\\\\u005B-\\\\u0060\\\\u007B-\\\\u007E';\nconst PUNCTUATION_ONLY_REGEX = new RegExp(`^[${PUNCTUATION_REGEX}]+$`, 'gu');\nconst BLOOM_SPLIT_CHARS = '.,!?\\u2026\\u3002\\uff0c\\u3001\\u0964\\u06d4\\u060c';\n\n// A mapping of regex patterns to their equivalent (but possibly longer) JS-compatible versions.\nconst PROBLEMATIC_REGEX_MAP = new Map([\n // This uses the case insensitive group modifier, which is not supported in JavaScript.\n // When parsing the regex, an \"Invalid group\" error is thrown.\n [\"(?i:'s|'t|'re|'ve|'m|'ll|'d)\", \"(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))\"],\n\n // Used to override the default (invalid) regex of the bloom pretokenizer.\n // For more information, see https://github.com/huggingface/transformers.js/issues/94\n [` ?[^(\\\\s|[${BLOOM_SPLIT_CHARS}])]+`, ` ?[^\\\\s${BLOOM_SPLIT_CHARS}]+`],\n])\n\n\n/**\n * Represent a token added by the user on top of the existing Model vocabulary.\n * AddedToken can be configured to specify the behavior they should have in various situations like:\n * - Whether they should only match single words\n * - Whether to include any whitespace on its left or right\n */\nclass AddedToken {\n /**\n * Creates a new instance of AddedToken.\n * @param {Object} config Added token configuration object.\n * @param {string} config.content The content of the added token.\n * @param {number} config.id The id of the added token.\n * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words.\n * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left.\n * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right.\n * @param {boolean} [config.normalized=false] Whether this token should be normalized.\n * @param {boolean} [config.special=false] Whether this token is special.\n */\n constructor(config) {\n this.content = config.content;\n this.id = config.id;\n this.single_word = config.single_word ?? false;\n this.lstrip = config.lstrip ?? false;\n this.rstrip = config.rstrip ?? false;\n this.special = config.special ?? false;\n this.normalized = config.normalized ?? null;\n }\n}\n\n/**\n * Abstract base class for tokenizer models.\n *\n * @extends Callable\n */\nexport class TokenizerModel extends Callable {\n /**\n * Creates a new instance of TokenizerModel.\n * @param {Object} config The configuration object for the TokenizerModel.\n */\n constructor(config) {\n super();\n this.config = config;\n\n /** @type {string[]} */\n this.vocab = [];\n\n /**\n * A mapping of tokens to ids.\n * @type {Map}\n */\n this.tokens_to_ids = new Map();\n\n this.unk_token_id = undefined;\n this.unk_token = undefined;\n this.end_of_word_suffix = undefined;\n\n /** @type {boolean} Whether to fuse unknown tokens when encoding. Defaults to false. */\n this.fuse_unk = this.config.fuse_unk ?? false;\n }\n\n /**\n * Instantiates a new TokenizerModel instance based on the configuration object provided.\n * @param {Object} config The configuration object for the TokenizerModel.\n * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor.\n * @returns {TokenizerModel} A new instance of a TokenizerModel.\n * @throws Will throw an error if the TokenizerModel type in the config is not recognized.\n */\n static fromConfig(config, ...args) {\n switch (config.type) {\n case 'WordPiece':\n return new WordPieceTokenizer(config);\n case 'Unigram':\n // @ts-ignore\n return new Unigram(config, ...args);\n case 'BPE':\n return new BPE(config);\n\n default:\n // Some tokenizers, like for google-t5/t5-small, do not have a `type` field.\n // In this case, we can infer the tokenizer type based on the structure of the `vocab` field.\n if (config.vocab) {\n if (Array.isArray(config.vocab)) {\n // config.vocab is of type `[string, number][]`\n // @ts-ignore\n return new Unigram(config, ...args);\n } else {\n // @ts-ignore\n return new LegacyTokenizerModel(config, ...args);\n }\n }\n throw new Error(`Unknown TokenizerModel type: ${config.type}`);\n }\n }\n\n /**\n * Internal function to call the TokenizerModel instance.\n * @param {string[]} tokens The tokens to encode.\n * @returns {string[]} The encoded tokens.\n */\n _call(tokens) {\n tokens = this.encode(tokens);\n if (this.fuse_unk) {\n // Fuse unknown tokens\n tokens = fuse_unk(tokens, this.tokens_to_ids, this.unk_token_id);\n }\n return tokens;\n }\n\n /**\n * Encodes a list of tokens into a list of token IDs.\n * @param {string[]} tokens The tokens to encode.\n * @returns {string[]} The encoded tokens.\n * @throws Will throw an error if not implemented in a subclass.\n */\n encode(tokens) {\n throw Error(\"encode should be implemented in subclass.\")\n }\n\n /**\n * Converts a list of tokens into a list of token IDs.\n * @param {string[]} tokens The tokens to convert.\n * @returns {number[]} The converted token IDs.\n */\n convert_tokens_to_ids(tokens) {\n return tokens.map(t => this.tokens_to_ids.get(t) ?? this.unk_token_id);\n }\n\n /**\n * Converts a list of token IDs into a list of tokens.\n * @param {number[]|bigint[]} ids The token IDs to convert.\n * @returns {string[]} The converted tokens.\n */\n convert_ids_to_tokens(ids) {\n return ids.map(i => this.vocab[i] ?? this.unk_token);\n }\n}\n\n/**\n * A subclass of TokenizerModel that uses WordPiece encoding to encode tokens.\n * @extends TokenizerModel\n */\nclass WordPieceTokenizer extends TokenizerModel {\n /**\n * @param {Object} config The configuration object.\n * @param {Object} config.vocab A mapping of tokens to ids.\n * @param {string} config.unk_token The unknown token string.\n * @param {string} config.continuing_subword_prefix The prefix to use for continuing subwords.\n * @param {number} [config.max_input_chars_per_word=100] The maximum number of characters per word.\n */\n constructor(config) {\n super(config);\n /**\n * A mapping of tokens to ids.\n * @type {Map}\n */\n this.tokens_to_ids = objectToMap(config.vocab);\n\n /**\n * The id of the unknown token.\n * @type {number}\n */\n this.unk_token_id = this.tokens_to_ids.get(config.unk_token);\n\n /**\n * The unknown token string.\n * @type {string}\n */\n this.unk_token = config.unk_token;\n\n /**\n * The maximum number of characters allowed per word.\n * @type {number}\n */\n this.max_input_chars_per_word = config.max_input_chars_per_word ?? 100;\n\n /**\n * An array of tokens.\n * @type {string[]}\n */\n this.vocab = new Array(this.tokens_to_ids.size);\n for (const [key, value] of this.tokens_to_ids) {\n this.vocab[value] = key;\n }\n }\n\n /**\n * Encodes an array of tokens using WordPiece encoding.\n * @param {string[]} tokens The tokens to encode.\n * @returns {string[]} An array of encoded tokens.\n */\n encode(tokens) {\n const outputTokens = [];\n for (const token of tokens) {\n const chars = [...token];\n if (chars.length > this.max_input_chars_per_word) {\n outputTokens.push(this.unk_token);\n continue;\n }\n\n let isUnknown = false;\n let start = 0;\n const subTokens = [];\n\n while (start < chars.length) {\n let end = chars.length;\n let currentSubstring = null;\n while (start < end) {\n let substr = chars.slice(start, end).join('');\n\n if (start > 0) {\n substr = this.config.continuing_subword_prefix + substr;\n }\n if (this.tokens_to_ids.has(substr)) {\n currentSubstring = substr;\n break;\n }\n\n --end;\n }\n if (currentSubstring === null) {\n isUnknown = true;\n break;\n }\n subTokens.push(currentSubstring);\n start = end;\n }\n if (isUnknown) {\n outputTokens.push(this.unk_token);\n } else {\n outputTokens.push(...subTokens);\n }\n }\n\n return outputTokens;\n }\n\n}\n\n/**\n * Class representing a Unigram tokenizer model.\n * @extends TokenizerModel\n */\nclass Unigram extends TokenizerModel {\n /**\n * Create a new Unigram tokenizer model.\n * @param {Object} config The configuration object for the Unigram model.\n * @param {number} config.unk_id The ID of the unknown token\n * @param {any[][]} config.vocab A 2D array representing a mapping of tokens to scores.\n * @param {Object} moreConfig Additional configuration object for the Unigram model.\n */\n constructor(config, moreConfig) {\n super(config);\n\n const vocabSize = config.vocab.length;\n this.vocab = new Array(vocabSize);\n this.scores = new Array(vocabSize);\n for (let i = 0; i < vocabSize; ++i) {\n const piece = config.vocab[i];\n this.vocab[i] = piece[0];\n this.scores[i] = piece[1];\n }\n\n this.unk_token_id = config.unk_id;\n this.unk_token = this.vocab[config.unk_id];\n\n this.tokens_to_ids = new Map(this.vocab.map((x, i) => [x, i]));\n this.bos_token = ' '; // beginning of a sentence token\n\n this.bos_token_id = this.tokens_to_ids.get(this.bos_token); // NOTE: may be undefined\n this.eos_token = moreConfig.eos_token;\n\n this.eos_token_id = this.tokens_to_ids.get(this.eos_token);\n this.unk_token = this.vocab[this.unk_token_id];\n\n this.minScore = min(this.scores)[0];\n\n this.unk_score = this.minScore - 10.0;\n this.scores[this.unk_token_id] = this.unk_score;\n\n this.trie = new CharTrie();\n this.trie.extend(this.vocab);\n\n // NOTE: `fuse_unk` is hardcoded to true for Unigram models\n // See: https://github.com/huggingface/tokenizers/blob/b58227c7f1ccf8b73ee2268354336da56d91e492/tokenizers/src/models/unigram/model.rs#L119\n this.fuse_unk = true;\n }\n\n /**\n * Populates lattice nodes.\n * @param {TokenLattice} lattice The token lattice to populate with nodes.\n */\n populateNodes(lattice) {\n const chars = lattice.chars;\n const mblen = 1;\n let beginPos = 0;\n while (beginPos < chars.length) {\n let hasSingleNode = false;\n\n const tokens = [];\n const sliced = chars.slice(beginPos).join('');\n const prefixedTokens = this.trie.commonPrefixSearch(sliced);\n for (const token of prefixedTokens) {\n tokens.push(token);\n const tokenId = this.tokens_to_ids.get(token);\n const tokenScore = this.scores[tokenId];\n const n = len(token);\n lattice.insert(beginPos, n, tokenScore, tokenId);\n if (!hasSingleNode && n === mblen) {\n hasSingleNode = true;\n }\n }\n if (!hasSingleNode) {\n lattice.insert(beginPos, mblen, this.unk_score, this.unk_token_id);\n }\n beginPos += mblen;\n }\n }\n\n /**\n * Encodes an array of tokens into an array of subtokens using the unigram model.\n *\n * @param {string} normalized The normalized string.\n * @returns {string[]} An array of subtokens obtained by encoding the input tokens using the unigram model.\n */\n tokenize(normalized) {\n const lattice = new TokenLattice(normalized, this.bos_token_id, this.eos_token_id);\n this.populateNodes(lattice);\n return lattice.tokens();\n }\n\n /**\n * Encodes an array of tokens using Unigram encoding.\n * @param {string[]} tokens The tokens to encode.\n * @returns {string[]} An array of encoded tokens.\n */\n encode(tokens) {\n const toReturn = [];\n for (const token of tokens) {\n const tokenized = this.tokenize(token);\n toReturn.push(...tokenized);\n }\n return toReturn;\n }\n\n}\n\n/**\n * Returns list of utf-8 byte and a mapping to unicode strings.\n * Specifically avoids mapping to whitespace/control characters the BPE code barfs on.\n * @returns {Object} Object with utf-8 byte keys and unicode string values.\n */\nconst BYTES_TO_UNICODE = (() => {\n // Returns list of utf-8 byte and a mapping to unicode strings.\n // We specifically avoids mapping to whitespace/control characters\n // the bpe code barfs on.\n\n const bs = [\n ...Array.from({ length: \"~\".charCodeAt(0) - \"!\".charCodeAt(0) + 1 }, (_, i) => i + \"!\".charCodeAt(0)),\n ...Array.from({ length: \"¬\".charCodeAt(0) - \"¡\".charCodeAt(0) + 1 }, (_, i) => i + \"¡\".charCodeAt(0)),\n ...Array.from({ length: \"ÿ\".charCodeAt(0) - \"®\".charCodeAt(0) + 1 }, (_, i) => i + \"®\".charCodeAt(0)),\n ];\n const cs = bs.slice();\n let n = 0;\n for (let b = 0; b < 256; ++b) {\n if (!bs.includes(b)) {\n bs.push(b);\n cs.push(256 + n);\n n += 1;\n }\n }\n const ccs = cs.map(n => String.fromCharCode(n));\n return Object.fromEntries(bs.map((b, i) => [b, ccs[i]]));\n})();\n\nconst UNICODE_TO_BYTES = reverseDictionary(BYTES_TO_UNICODE);\n\n\n/**\n * @typedef {Object} BPENode\n * @property {string} token The token associated with the node\n * @property {number} bias A positional bias for the node.\n * @property {number} [score] The score of the node.\n * @property {BPENode} [prev] The previous node in the linked list.\n * @property {BPENode} [next] The next node in the linked list.\n */\n\n/**\n * BPE class for encoding text into Byte-Pair-Encoding (BPE) tokens.\n * @extends TokenizerModel\n */\nclass BPE extends TokenizerModel {\n /**\n * Create a BPE instance.\n * @param {Object} config The configuration object for BPE.\n * @param {Object} config.vocab A mapping of tokens to ids.\n * @param {string[]|[string, string][]} config.merges An array of BPE merges as strings.\n * @param {string} config.unk_token The unknown token used for out of vocabulary words.\n * @param {string} config.end_of_word_suffix The suffix to place at the end of each word.\n * @param {string} [config.continuing_subword_suffix] The suffix to insert between words.\n * @param {boolean} [config.byte_fallback=false] Whether to use spm byte-fallback trick (defaults to False)\n * @param {boolean} [config.ignore_merges=false] Whether or not to match tokens with the vocab before using merges.\n */\n constructor(config) {\n super(config);\n\n /** @type {Map} */\n this.tokens_to_ids = objectToMap(config.vocab);\n\n this.unk_token_id = this.tokens_to_ids.get(config.unk_token);\n this.unk_token = config.unk_token;\n\n this.vocab = new Array(this.tokens_to_ids.size);\n for (const [key, value] of this.tokens_to_ids) {\n this.vocab[value] = key;\n }\n\n // Tokenizers >= 0.20.0 serializes BPE merges as a [string, string][] instead of a string[],\n // which resolves the ambiguity for merges containing spaces.\n const use_new_merge_format = Array.isArray(config.merges[0]);\n\n /** @type {[string, string][]} */\n this.merges = use_new_merge_format\n ? /** @type {[string, string][]} */(config.merges)\n : (/** @type {string[]} */(config.merges)).map(x => /** @type {[string, string]} */(x.split(' ', 2)));\n this.bpe_ranks = new Map(this.merges.map((x, i) => [JSON.stringify(x), i]));\n\n this.end_of_word_suffix = config.end_of_word_suffix;\n\n // NOTE: `continuing_subword_suffix` is custom (to support `BlenderbotSmallTokenizer`)\n this.continuing_subword_suffix = config.continuing_subword_suffix ?? null;\n\n this.byte_fallback = this.config.byte_fallback ?? false;\n\n if (this.byte_fallback) {\n this.text_encoder = new TextEncoder();\n }\n\n this.ignore_merges = this.config.ignore_merges ?? false;\n\n /** @type {Map} */\n this.cache = new Map();\n }\n\n /**\n * Apply Byte-Pair-Encoding (BPE) to a given token. Efficient heap-based priority\n * queue implementation adapted from https://github.com/belladoreai/llama-tokenizer-js.\n * @param {string} token The token to encode.\n * @returns {string[]} The BPE encoded tokens.\n */\n bpe(token) {\n if (token.length === 0) {\n return [];\n }\n\n const cached = this.cache.get(token);\n if (cached !== undefined) {\n return cached;\n }\n\n const word = Array.from(token);\n if (this.end_of_word_suffix) {\n word[word.length - 1] += this.end_of_word_suffix;\n }\n\n let result = [];\n if (word.length > 1) {\n // Create a priority queue to store the nodes that will be merged.\n // The comparator function compares the scores of the nodes.\n const queue = new PriorityQueue((a, b) => a.score < b.score);\n\n // Construct a doubly-linked list of nodes that will be inserted into the priority queue,\n // starting with the individual characters. We also populate each node with a positional\n // bias to break ties in the priority queue.\n let startingNode = {\n token: word[0],\n bias: 0,\n prev: null,\n next: null,\n }\n\n let previousNode = startingNode\n for (let i = 1; i < word.length; ++i) {\n const currentNode = {\n bias: i / word.length, // Add fractional component to break ties\n token: word[i],\n prev: previousNode,\n next: null,\n }\n previousNode.next = currentNode\n this._add_node(queue, previousNode)\n previousNode = currentNode\n }\n\n while (!queue.isEmpty()) {\n // Get the next node with the highest priority\n const node = queue.pop();\n\n // Check that this merge is still possible\n if (node.deleted || !node.next || node.next.deleted) continue;\n\n // Here, we mark the current node (left side of the merge) and the next node (right side of the merge) as deleted.\n // This is because they will both be replaced by a new node representing the merge result.\n node.deleted = true;\n node.next.deleted = true;\n\n // Next, we fix the node that comes before the current node (i.e., left side of the merge).\n if (node.prev) {\n\n // Make a shallow copy of the previous node\n const newPreviousNode = { ...node.prev };\n\n // Mark the old previous node as deleted. This avoids erroneous merges later,\n // because there may still be references to this node in the priority queue.\n node.prev.deleted = true;\n node.prev = newPreviousNode;\n\n // Update the reference of the previous node, by pointing its previous node to this new previous node.\n if (newPreviousNode.prev) {\n newPreviousNode.prev.next = newPreviousNode;\n } else {\n // If the previous of the previous node does not exist, it means that\n // `newPreviousNode` must be the new `startingNode`.\n startingNode = newPreviousNode;\n }\n }\n\n // Create a new node which represents the result of the merge.\n const merged = {\n token: node.token + node.next.token,\n bias: node.bias,\n prev: node.prev,\n next: node.next.next,\n }\n\n // We now consider where we can add the new merged node to the priority queue:\n // 1. prev <-> merged\n if (merged.prev) {\n merged.prev.next = merged;\n this._add_node(queue, merged.prev);\n } else {\n // If `merged.prev` does not exist, then `merged` must be the new `startingNode`.\n startingNode = merged;\n }\n\n // 2. merged <-> next\n if (merged.next) {\n merged.next.prev = merged;\n this._add_node(queue, merged);\n }\n }\n\n // Traverse the linked list, starting from the `startingNode`, and collect the tokens.\n for (let currentNode = startingNode; currentNode !== null; currentNode = currentNode.next) {\n result.push(currentNode.token);\n }\n } else {\n result = word;\n }\n\n // Possibly append suffix\n if (this.continuing_subword_suffix) {\n // Do not append suffix to the last token\n for (let i = 0; i < result.length - 1; ++i) {\n result[i] += this.continuing_subword_suffix;\n }\n }\n\n // Save the result to the cache\n this.cache.set(token, result);\n\n return result;\n }\n\n\n /**\n * Helper function to add a node to the priority queue.\n * @param {PriorityQueue} queue \n * @param {BPENode} node\n * @private\n */\n _add_node(queue, node) {\n // `score` is a measure of the merge priority: lower means higher priority\n // We use the BPE rank as a measure of priority (i.e., the local of the merge in the merges list)\n // We also add a fractional component to the score to break ties (with the earlier character having higher priority)\n const rank = this.bpe_ranks.get(JSON.stringify([node.token, node.next.token]));\n if (rank !== undefined) {\n node.score = rank + node.bias;\n queue.push(node);\n }\n }\n\n /**\n * Encodes the input sequence of tokens using the BPE algorithm and returns the resulting subword tokens.\n * @param {string[]} tokens The input sequence of tokens to encode.\n * @returns {string[]} The resulting subword tokens after applying the BPE algorithm to the input sequence of tokens.\n */\n encode(tokens) {\n const outputTokens = [];\n\n for (const token of tokens) {\n if (this.ignore_merges && this.tokens_to_ids.has(token)) {\n outputTokens.push(token);\n continue;\n }\n const bpe_token_list = this.bpe(token);\n\n for (const t of bpe_token_list) {\n if (this.tokens_to_ids.has(t)) {\n outputTokens.push(t);\n } else if (this.byte_fallback) {\n const byteTokens = Array.from(this.text_encoder.encode(t))\n .map(x => `<0x${x.toString(16).toUpperCase().padStart(2, '0')}>`);\n if (byteTokens.every(x => this.tokens_to_ids.has(x))) {\n // Ensure the byte tokens are actually in the vocabulary, otherwise\n // we fall back to the unknown token. For more information, see\n // https://github.com/huggingface/transformers/issues/28096.\n outputTokens.push(...byteTokens);\n } else {\n outputTokens.push(this.unk_token);\n }\n } else {\n outputTokens.push(this.unk_token);\n }\n }\n }\n\n return outputTokens;\n }\n\n}\n\n/**\n * Legacy tokenizer class for tokenizers with only a vocabulary.\n */\nclass LegacyTokenizerModel extends TokenizerModel {\n /**\n * Create a LegacyTokenizerModel instance.\n * @param {Object} config The configuration object for LegacyTokenizerModel.\n * @param {Object} config.vocab A (possibly nested) mapping of tokens to ids.\n * @param {Object} moreConfig Additional configuration object for the LegacyTokenizerModel model.\n */\n constructor(config, moreConfig) {\n super(config);\n\n /**@type {Map} */\n this.tokens_to_ids = objectToMap(\n moreConfig.target_lang\n ? config.vocab[moreConfig.target_lang]\n : config.vocab\n );\n\n this.bos_token = moreConfig.bos_token;\n this.bos_token_id = this.tokens_to_ids.get(this.bos_token);\n\n this.eos_token = moreConfig.eos_token;\n this.eos_token_id = this.tokens_to_ids.get(this.eos_token);\n\n this.pad_token = moreConfig.pad_token;\n this.pad_token_id = this.tokens_to_ids.get(this.pad_token);\n\n this.unk_token = moreConfig.unk_token;\n this.unk_token_id = this.tokens_to_ids.get(this.unk_token);\n\n this.vocab = new Array(this.tokens_to_ids.size);\n for (const [key, value] of this.tokens_to_ids) {\n this.vocab[value] = key;\n }\n }\n\n encode(tokens) {\n return tokens;\n }\n}\n\n\n/**\n * A base class for text normalization.\n * @abstract\n */\nclass Normalizer extends Callable {\n /**\n * @param {Object} config The configuration object for the normalizer.\n */\n constructor(config) {\n super();\n this.config = config;\n }\n\n /**\n * Factory method for creating normalizers from config objects.\n * @static\n * @param {Object} config The configuration object for the normalizer.\n * @returns {Normalizer} A Normalizer object.\n * @throws {Error} If an unknown Normalizer type is specified in the config.\n */\n static fromConfig(config) {\n if (config === null) return null;\n switch (config.type) {\n case 'BertNormalizer':\n return new BertNormalizer(config);\n case 'Precompiled':\n return new Precompiled(config);\n case 'Sequence':\n return new NormalizerSequence(config);\n case 'Replace':\n return new Replace(config);\n case 'NFC':\n return new NFC(config);\n case 'NFKC':\n return new NFKC(config);\n case 'NFKD':\n return new NFKD(config);\n case 'Strip':\n return new StripNormalizer(config);\n case 'StripAccents':\n return new StripAccents(config);\n case 'Lowercase':\n return new Lowercase(config);\n case 'Prepend':\n return new Prepend(config);\n default:\n throw new Error(`Unknown Normalizer type: ${config.type}`);\n }\n }\n\n /**\n * Normalize the input text.\n * @abstract\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n * @throws {Error} If this method is not implemented in a subclass.\n */\n normalize(text) {\n throw Error(\"normalize should be implemented in subclass.\")\n }\n\n /**\n * Alias for {@link Normalizer#normalize}.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n _call(text) {\n return this.normalize(text);\n }\n\n}\n\n/**\n * Replace normalizer that replaces occurrences of a pattern with a given string or regular expression.\n * @extends Normalizer\n */\nclass Replace extends Normalizer {\n /**\n * Normalize the input text by replacing the pattern with the content.\n * @param {string} text The input text to be normalized.\n * @returns {string} The normalized text after replacing the pattern with the content.\n */\n normalize(text) {\n const pattern = createPattern(this.config.pattern);\n return pattern === null\n ? text\n : text.replaceAll(pattern, this.config.content);\n }\n}\n\n/**\n * A normalizer that applies Unicode normalization form C (NFC) to the input text.\n * @extends Normalizer\n */\nclass NFC extends Normalizer {\n /**\n * Normalize the input text by applying Unicode normalization form C (NFC).\n * @param {string} text The input text to be normalized.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = text.normalize('NFC')\n return text;\n }\n}\n\n/**\n * NFKC Normalizer.\n * @extends Normalizer\n */\nclass NFKC extends Normalizer {\n /**\n * Normalize text using NFKC normalization.\n * @param {string} text The text to be normalized.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = text.normalize('NFKC')\n return text;\n }\n}\n/**\n * NFKD Normalizer.\n * @extends Normalizer\n */\nclass NFKD extends Normalizer {\n /**\n * Normalize text using NFKD normalization.\n * @param {string} text The text to be normalized.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = text.normalize('NFKD')\n return text;\n }\n}\n\n/**\n * A normalizer that strips leading and/or trailing whitespace from the input text.\n */\nclass StripNormalizer extends Normalizer {\n /**\n * Strip leading and/or trailing whitespace from the input text.\n * @param {string} text The input text.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n if (this.config.strip_left && this.config.strip_right) {\n // Fast path to avoid an extra trim call\n text = text.trim();\n } else {\n if (this.config.strip_left) {\n text = text.trimStart();\n }\n if (this.config.strip_right) {\n text = text.trimEnd();\n }\n }\n return text;\n }\n}\n\n/**\n * StripAccents normalizer removes all accents from the text.\n * @extends Normalizer\n */\nclass StripAccents extends Normalizer {\n /**\n * Remove all accents from the text.\n * @param {string} text The input text.\n * @returns {string} The normalized text without accents.\n */\n normalize(text) {\n text = remove_accents(text);\n return text;\n }\n}\n\n/**\n * A Normalizer that lowercases the input string.\n * @extends Normalizer\n */\nclass Lowercase extends Normalizer {\n /**\n * Lowercases the input string.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = text.toLowerCase();\n return text;\n }\n}\n\n/**\n * A Normalizer that prepends a string to the input string.\n * @extends Normalizer\n */\nclass Prepend extends Normalizer {\n /**\n * Prepends the input string.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = this.config.prepend + text;\n return text;\n }\n}\n\n/**\n * A Normalizer that applies a sequence of Normalizers.\n * @extends Normalizer\n */\nclass NormalizerSequence extends Normalizer {\n /**\n * Create a new instance of NormalizerSequence.\n * @param {Object} config The configuration object.\n * @param {Object[]} config.normalizers An array of Normalizer configuration objects.\n */\n constructor(config) {\n super(config);\n this.normalizers = config.normalizers.map(x => Normalizer.fromConfig(x));\n }\n /**\n * Apply a sequence of Normalizers to the input text.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n return this.normalizers.reduce((t, normalizer) => {\n return normalizer.normalize(t);\n }, text);\n }\n}\n\n/**\n * A class representing a normalizer used in BERT tokenization.\n * @extends Normalizer\n */\nclass BertNormalizer extends Normalizer {\n /**\n * Adds whitespace around any CJK (Chinese, Japanese, or Korean) character in the input text.\n *\n * @param {string} text The input text to tokenize.\n * @returns {string} The tokenized text with whitespace added around CJK characters.\n */\n _tokenize_chinese_chars(text) {\n /* Adds whitespace around any CJK character. */\n const output = [];\n for (let i = 0; i < text.length; ++i) {\n const char = text[i];\n const cp = char.charCodeAt(0);\n if (is_chinese_char(cp)) {\n output.push(\" \");\n output.push(char);\n output.push(\" \");\n } else {\n output.push(char);\n }\n }\n return output.join(\"\");\n }\n\n /**\n * Strips accents from the given text.\n * @param {string} text The text to strip accents from.\n * @returns {string} The text with accents removed.\n */\n stripAccents(text) {\n // \"Mark, Nonspacing\" (Mn)\n return text.normalize('NFD').replace(/\\p{Mn}/gu, '');\n }\n\n\n /**\n * Checks whether `char` is a control character.\n * @param {string} char The character to check.\n * @returns {boolean} Whether `char` is a control character.\n * @private\n */\n _is_control(char) {\n switch (char) {\n case '\\t':\n case '\\n':\n case '\\r':\n // These are technically control characters but we count them as whitespace characters.\n return false;\n\n default:\n // Check if unicode category starts with C:\n // Cc - Control\n // Cf - Format\n // Co - Private Use\n // Cs - Surrogate\n return /^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$/u.test(char);\n }\n }\n\n /**\n * Performs invalid character removal and whitespace cleanup on text.\n * @param {string} text The text to clean.\n * @returns {string} The cleaned text.\n * @private\n */\n _clean_text(text) {\n const output = [];\n for (const char of text) {\n const cp = char.charCodeAt(0);\n if (cp === 0 || cp === 0xFFFD || this._is_control(char)) {\n continue;\n }\n if (/^\\s$/.test(char)) { // is whitespace\n output.push(\" \");\n } else {\n output.push(char);\n }\n }\n return output.join(\"\");\n }\n /**\n * Normalizes the given text based on the configuration.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n if (this.config.clean_text) {\n text = this._clean_text(text);\n }\n\n if (this.config.handle_chinese_chars) {\n text = this._tokenize_chinese_chars(text);\n }\n\n if (this.config.lowercase) {\n text = text.toLowerCase();\n\n if (this.config.strip_accents !== false) {\n text = this.stripAccents(text);\n }\n } else if (this.config.strip_accents) {\n text = this.stripAccents(text);\n }\n\n return text;\n }\n}\n\n/**\n * A callable class representing a pre-tokenizer used in tokenization. Subclasses\n * should implement the `pre_tokenize_text` method to define the specific pre-tokenization logic.\n * @extends Callable\n */\nclass PreTokenizer extends Callable {\n /**\n * Factory method that returns an instance of a subclass of `PreTokenizer` based on the provided configuration.\n *\n * @static\n * @param {Object} config A configuration object for the pre-tokenizer.\n * @returns {PreTokenizer} An instance of a subclass of `PreTokenizer`.\n * @throws {Error} If the provided configuration object does not correspond to any known pre-tokenizer.\n */\n static fromConfig(config) {\n if (config === null) return null;\n\n switch (config.type) {\n case 'BertPreTokenizer':\n return new BertPreTokenizer(config);\n case 'Sequence':\n return new PreTokenizerSequence(config);\n case 'Whitespace':\n return new WhitespacePreTokenizer(config);\n case 'WhitespaceSplit':\n return new WhitespaceSplit(config);\n case 'Metaspace':\n return new MetaspacePreTokenizer(config);\n\n case 'ByteLevel':\n return new ByteLevelPreTokenizer(config);\n case 'Split':\n return new SplitPreTokenizer(config);\n case 'Punctuation':\n return new PunctuationPreTokenizer(config);\n case 'Digits':\n return new DigitsPreTokenizer(config);\n case 'Replace':\n return new ReplacePreTokenizer(config);\n default:\n throw new Error(`Unknown PreTokenizer type: ${config.type}`);\n }\n }\n\n /**\n * Method that should be implemented by subclasses to define the specific pre-tokenization logic.\n *\n * @abstract\n * @param {string} text The text to pre-tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} The pre-tokenized text.\n * @throws {Error} If the method is not implemented in the subclass.\n */\n pre_tokenize_text(text, options) {\n throw Error(\"pre_tokenize_text should be implemented in subclass.\")\n }\n\n /**\n * Tokenizes the given text into pre-tokens.\n * @param {string|string[]} text The text or array of texts to pre-tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of pre-tokens.\n */\n pre_tokenize(text, options) {\n return (Array.isArray(text)\n ? text.map(x => this.pre_tokenize_text(x, options))\n : this.pre_tokenize_text(text, options)\n ).flat();\n }\n\n /**\n * Alias for {@link PreTokenizer#pre_tokenize}.\n * @param {string|string[]} text The text or array of texts to pre-tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of pre-tokens.\n */\n _call(text, options) {\n return this.pre_tokenize(text, options);\n }\n}\n\n/**\n * @extends PreTokenizer\n */\nclass BertPreTokenizer extends PreTokenizer {\n /**\n * A PreTokenizer that splits text into wordpieces using a basic tokenization scheme\n * similar to that used in the original implementation of BERT.\n * \n * @param {Object} config The configuration object.\n */\n constructor(config) {\n super();\n // Construct a pattern which matches the rust implementation:\n // https://github.com/huggingface/tokenizers/blob/b4fcc9ce6e4ad5806e82826f816acfdfdc4fcc67/tokenizers/src/pre_tokenizers/bert.rs#L11\n // Equivalent to removing whitespace and splitting on punctuation (both \\p{P} and other ascii characters)\n this.pattern = new RegExp(`[^\\\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`, 'gu');\n }\n /**\n * Tokenizes a single text using the BERT pre-tokenization scheme.\n * \n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n return text.trim().match(this.pattern) || [];\n }\n}\n\n/**\n * A pre-tokenizer that splits text into Byte-Pair-Encoding (BPE) subwords.\n * @extends PreTokenizer\n */\nclass ByteLevelPreTokenizer extends PreTokenizer {\n /**\n * Creates a new instance of the `ByteLevelPreTokenizer` class.\n * @param {Object} config The configuration object.\n */\n constructor(config) {\n super();\n this.config = config;\n\n /**\n * @type {boolean} Whether to add a leading space to the first word.\n * This allows to treat the leading word just as any other word.\n */\n this.add_prefix_space = this.config.add_prefix_space;\n\n /**\n * @type {boolean} Whether the post processing step should trim offsets\n * to avoid including whitespaces.\n * @todo Use this in the pretokenization step.\n */\n this.trim_offsets = this.config.trim_offsets;\n\n /**\n * @type {boolean} Whether to use the standard GPT2 regex for whitespace splitting.\n * Set it to False if you want to use your own splitting. Defaults to true.\n */\n this.use_regex = this.config.use_regex ?? true;\n this.pattern = /'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+/gu;\n\n this.byte_encoder = BYTES_TO_UNICODE;\n this.text_encoder = new TextEncoder();\n }\n\n /**\n * Tokenizes a single piece of text using byte-level tokenization.\n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n // Add a leading space if the option is enabled\n if (this.add_prefix_space && !text.startsWith(' ')) {\n text = ' ' + text;\n }\n\n // Split on whitespace and punctuation\n const tokens = this.use_regex ? (text.match(this.pattern) || []) : [text];\n\n // Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)\n return tokens.map(\n token => Array.from(this.text_encoder.encode(token), byte => this.byte_encoder[byte]).join('')\n );\n }\n}\n\n/**\n * @typedef {'removed'|'isolated'|'mergedWithPrevious'|'mergedWithNext'|'contiguous'} SplitDelimiterBehavior\n */\n\n/**\n * Splits text using a given pattern.\n * @extends PreTokenizer\n */\nclass SplitPreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration options for the pre-tokenizer.\n * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.\n * @param {string|undefined} config.pattern.String The string to use for splitting. Only defined if the pattern is a string.\n * @param {string|undefined} config.pattern.Regex The regex to use for splitting. Only defined if the pattern is a regex.\n * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.\n * @param {boolean} config.invert Whether to split (invert=false) or match (invert=true) the pattern.\n */\n constructor(config) {\n super();\n this.config = config;\n // TODO support all behaviours (config.behavior)\n\n this.pattern = createPattern(this.config.pattern, this.config.invert);\n }\n\n /**\n * Tokenizes text by splitting it using the given pattern.\n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n if (this.pattern === null) {\n return [];\n }\n\n if (this.config.invert) {\n return text.match(this.pattern) || [];\n } else {\n return regexSplit(text, this.pattern);\n }\n }\n}\n\n/**\n * Splits text based on punctuation.\n * @extends PreTokenizer\n */\nclass PunctuationPreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration options for the pre-tokenizer.\n * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.\n */\n constructor(config) {\n super();\n this.config = config;\n this.pattern = new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`, 'gu');\n }\n\n /**\n * Tokenizes text by splitting it using the given pattern.\n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n return text.match(this.pattern) || [];\n }\n}\n\n\n/**\n * Splits text based on digits.\n * @extends PreTokenizer\n */\nclass DigitsPreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration options for the pre-tokenizer.\n * @param {boolean} config.individual_digits Whether to split on individual digits.\n */\n constructor(config) {\n super();\n this.config = config;\n\n // Construct a pattern which matches the rust implementation:\n const digit_pattern = `[^\\\\d]+|\\\\d${this.config.individual_digits ? '' : '+'}`;\n this.pattern = new RegExp(digit_pattern, 'gu');\n }\n\n /**\n * Tokenizes text by splitting it using the given pattern.\n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n return text.match(this.pattern) || [];\n }\n}\n\n/**\n * @typedef {Object} PostProcessedOutput\n * @property {string[]} tokens List of token produced by the post-processor.\n * @property {number[]} [token_type_ids] List of token type ids produced by the post-processor.\n */\n\n\n/**\n * @typedef {Object} EncodingSingle\n * @property {number[]} input_ids List of token ids to be fed to a model.\n * @property {number[]} attention_mask List of token type ids to be fed to a model\n * @property {number[]} [token_type_ids] List of indices specifying which tokens should be attended to by the model\n */\n\n\n/**\n * @extends Callable\n */\nclass PostProcessor extends Callable {\n\n /**\n * @param {Object} config The configuration for the post-processor.\n */\n constructor(config) {\n super();\n this.config = config;\n }\n\n /**\n * Factory method to create a PostProcessor object from a configuration object.\n *\n * @param {Object} config Configuration object representing a PostProcessor.\n * @returns {PostProcessor} A PostProcessor object created from the given configuration.\n * @throws {Error} If an unknown PostProcessor type is encountered.\n */\n static fromConfig(config) {\n if (config === null) return null;\n switch (config.type) {\n case 'TemplateProcessing':\n return new TemplateProcessing(config);\n\n case 'ByteLevel':\n return new ByteLevelPostProcessor(config);\n\n case 'RobertaProcessing':\n return new RobertaProcessing(config);\n case 'BertProcessing':\n return new BertProcessing(config);\n\n case 'Sequence':\n return new PostProcessorSequence(config);\n default:\n throw new Error(`Unknown PostProcessor type: ${config.type}`);\n }\n }\n\n /**\n * Method to be implemented in subclass to apply post-processing on the given tokens.\n *\n * @param {Array} tokens The input tokens to be post-processed.\n * @param {...*} args Additional arguments required by the post-processing logic.\n * @returns {PostProcessedOutput} The post-processed tokens.\n * @throws {Error} If the method is not implemented in subclass.\n */\n post_process(tokens, ...args) {\n throw Error(\"post_process should be implemented in subclass.\")\n }\n\n /**\n * Alias for {@link PostProcessor#post_process}.\n * @param {Array} tokens The text or array of texts to post-process.\n * @param {...*} args Additional arguments required by the post-processing logic.\n * @returns {PostProcessedOutput} The post-processed tokens.\n */\n _call(tokens, ...args) {\n return this.post_process(tokens, ...args);\n }\n}\n\n/**\n * A post-processor that adds special tokens to the beginning and end of the input.\n */\nclass BertProcessing extends PostProcessor {\n /**\n * @param {Object} config The configuration for the post-processor.\n * @param {string[]} config.cls The special tokens to add to the beginning of the input.\n * @param {string[]} config.sep The special tokens to add to the end of the input.\n */\n constructor(config) {\n super(config);\n // TODO use all of config: add_prefix_space, trim_offsets\n\n this.cls = config.cls[0];\n this.sep = config.sep[0];\n }\n\n /**\n * Adds the special tokens to the beginning and end of the input.\n * @param {string[]} tokens The input tokens.\n * @param {string[]} [tokens_pair=null] An optional second set of input tokens.\n * @returns {PostProcessedOutput} The post-processed tokens with the special tokens added to the beginning and end.\n */\n post_process(tokens, tokens_pair = null, {\n add_special_tokens = true,\n } = {}) {\n if (add_special_tokens) {\n tokens = mergeArrays([this.cls], tokens, [this.sep]);\n }\n\n let token_type_ids = new Array(tokens.length).fill(0);\n if (tokens_pair !== null) {\n // NOTE: It is intended to add 2 EOS tokens after the first set of tokens\n // https://github.com/huggingface/tokenizers/issues/983\n const middle = (add_special_tokens && this instanceof RobertaProcessing)\n ? [this.sep]\n : [];\n const after = add_special_tokens ? [this.sep] : [];\n\n tokens = mergeArrays(tokens, middle, tokens_pair, after);\n token_type_ids = mergeArrays(token_type_ids, new Array(tokens_pair.length + middle.length + after.length).fill(1));\n }\n return { tokens, token_type_ids };\n }\n}\nclass RobertaProcessing extends BertProcessing { } // NOTE: extends BertProcessing\n\n/**\n * Post processor that replaces special tokens in a template with actual tokens.\n * @extends PostProcessor\n */\nclass TemplateProcessing extends PostProcessor {\n /**\n * Creates a new instance of `TemplateProcessing`.\n * @param {Object} config The configuration options for the post processor.\n * @param {Array} config.single The template for a single sequence of tokens.\n * @param {Array} config.pair The template for a pair of sequences of tokens.\n */\n constructor(config) {\n super(config);\n\n this.single = config.single;\n this.pair = config.pair;\n }\n\n /**\n * Replaces special tokens in the template with actual tokens.\n * @param {string[]} tokens The list of tokens for the first sequence.\n * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).\n * @returns {PostProcessedOutput} An object containing the list of tokens with the special tokens replaced with actual tokens.\n */\n post_process(tokens, tokens_pair = null, {\n add_special_tokens = true,\n } = {}) {\n const type = tokens_pair === null ? this.single : this.pair\n\n let processedTokens = [];\n let types = [];\n for (const item of type) {\n if ('SpecialToken' in item) {\n if (add_special_tokens) {\n processedTokens.push(item.SpecialToken.id);\n types.push(item.SpecialToken.type_id);\n }\n } else if ('Sequence' in item) {\n if (item.Sequence.id === 'A') {\n processedTokens = mergeArrays(processedTokens, tokens);\n types = mergeArrays(types, new Array(tokens.length).fill(item.Sequence.type_id));\n\n } else if (item.Sequence.id === 'B') {\n processedTokens = mergeArrays(processedTokens, tokens_pair);\n types = mergeArrays(types, new Array(tokens_pair.length).fill(item.Sequence.type_id));\n }\n }\n }\n return { tokens: processedTokens, token_type_ids: types };\n }\n}\n\n/**\n * A PostProcessor that returns the given tokens as is.\n * @extends PostProcessor\n */\nclass ByteLevelPostProcessor extends PostProcessor {\n /**\n * Post process the given tokens.\n * @param {string[]} tokens The list of tokens for the first sequence.\n * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).\n * @returns {PostProcessedOutput} An object containing the post-processed tokens.\n */\n post_process(tokens, tokens_pair = null) {\n if (tokens_pair) {\n tokens = mergeArrays(tokens, tokens_pair);\n }\n return { tokens };\n }\n}\n\n\n/**\n * A post-processor that applies multiple post-processors in sequence.\n */\nclass PostProcessorSequence extends PostProcessor {\n\n /**\n * Creates a new instance of PostProcessorSequence.\n * @param {Object} config The configuration object.\n * @param {Object[]} config.processors The list of post-processors to apply.\n */\n constructor(config) {\n super(config);\n\n this.processors = config.processors.map(x => PostProcessor.fromConfig(x));\n }\n\n /**\n * Post process the given tokens.\n * @param {string[]} tokens The list of tokens for the first sequence.\n * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).\n * @returns {PostProcessedOutput} An object containing the post-processed tokens.\n */\n post_process(tokens, tokens_pair = null, options = {}) {\n let token_type_ids;\n for (const processor of this.processors) {\n if (processor instanceof ByteLevelPostProcessor) {\n // Special case where we need to pass the tokens_pair to the post-processor\n const output = processor.post_process(tokens);\n tokens = output.tokens;\n if (tokens_pair) {\n const pair_output = processor.post_process(tokens_pair);\n tokens_pair = pair_output.tokens;\n }\n } else {\n const output = processor.post_process(tokens, tokens_pair, options);\n tokens = output.tokens;\n token_type_ids = output.token_type_ids;\n }\n }\n return { tokens, token_type_ids };\n }\n}\n\n/**\n * The base class for token decoders.\n * @extends Callable\n */\nclass Decoder extends Callable {\n\n /**\n * Creates an instance of `Decoder`.\n *\n * @param {Object} config The configuration object.\n */\n constructor(config) {\n super();\n this.config = config;\n\n /** @type {AddedToken[]} */\n this.added_tokens = [];\n this.end_of_word_suffix = null;\n this.trim_offsets = config.trim_offsets;\n }\n\n /**\n * Creates a decoder instance based on the provided configuration.\n *\n * @param {Object} config The configuration object.\n * @returns {Decoder} A decoder instance.\n * @throws {Error} If an unknown decoder type is provided.\n */\n static fromConfig(config) {\n if (config === null) return null;\n switch (config.type) {\n case 'WordPiece':\n return new WordPieceDecoder(config);\n case 'Metaspace':\n return new MetaspaceDecoder(config);\n case 'ByteLevel':\n return new ByteLevelDecoder(config);\n\n case 'Replace':\n return new ReplaceDecoder(config);\n case 'ByteFallback':\n return new ByteFallback(config);\n case 'Fuse':\n return new FuseDecoder(config);\n case 'Strip':\n return new StripDecoder(config);\n\n case 'Sequence':\n return new DecoderSequence(config);\n\n case 'CTC':\n return new CTCDecoder(config);\n case 'BPEDecoder':\n return new BPEDecoder(config);\n default:\n throw new Error(`Unknown Decoder type: ${config.type}`);\n }\n }\n\n /**\n * Calls the `decode` method.\n *\n * @param {string[]} tokens The list of tokens.\n * @returns {string} The decoded string.\n */\n _call(tokens) {\n return this.decode(tokens);\n }\n\n /**\n * Decodes a list of tokens.\n * @param {string[]} tokens The list of tokens.\n * @returns {string} The decoded string.\n */\n decode(tokens) {\n return this.decode_chain(tokens).join('');\n }\n\n /**\n * Apply the decoder to a list of tokens.\n * \n * @param {string[]} tokens The list of tokens.\n * @returns {string[]} The decoded list of tokens.\n * @throws {Error} If the `decode_chain` method is not implemented in the subclass.\n */\n decode_chain(tokens) {\n throw Error(\"`decode_chain` should be implemented in subclass.\")\n }\n\n}\n\nclass ReplaceDecoder extends Decoder {\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n const pattern = createPattern(this.config.pattern);\n return pattern === null\n ? tokens\n : tokens.map(token => token.replaceAll(pattern, this.config.content))\n }\n}\n\n\nclass ByteFallback extends Decoder {\n constructor(config) {\n super(config);\n\n this.text_decoder = new TextDecoder();\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n\n const new_tokens = [];\n let previous_byte_tokens = [];\n\n for (const token of tokens) {\n let bytes = null;\n if (token.length === 6 && token.startsWith('<0x') && token.endsWith('>')) {\n const byte = parseInt(token.slice(3, 5), 16);\n if (!isNaN(byte)) {\n bytes = byte;\n }\n }\n if (bytes !== null) {\n previous_byte_tokens.push(bytes);\n } else {\n if (previous_byte_tokens.length > 0) {\n const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));\n new_tokens.push(string);\n previous_byte_tokens = [];\n }\n new_tokens.push(token);\n }\n }\n if (previous_byte_tokens.length > 0) {\n const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));\n new_tokens.push(string);\n previous_byte_tokens = [];\n }\n\n return new_tokens;\n }\n}\n\n/**\n * Fuse simply fuses all tokens into one big string.\n * It's usually the last decoding step anyway, but this decoder\n * exists incase some decoders need to happen after that step\n */\nclass FuseDecoder extends Decoder {\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return [tokens.join('')];\n }\n}\n\n\nclass StripDecoder extends Decoder {\n constructor(config) {\n super(config);\n\n this.content = this.config.content;\n this.start = this.config.start;\n this.stop = this.config.stop;\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return tokens.map(token => {\n let start_cut = 0;\n for (let i = 0; i < this.start; ++i) {\n if (token[i] === this.content) {\n start_cut = i + 1;\n continue;\n } else {\n break;\n }\n }\n\n let stop_cut = token.length;\n for (let i = 0; i < this.stop; ++i) {\n const index = token.length - i - 1;\n if (token[index] === this.content) {\n stop_cut = index;\n continue;\n } else {\n break;\n }\n }\n\n return token.slice(start_cut, stop_cut)\n });\n }\n}\n\n/**\n * A decoder that decodes a list of WordPiece tokens into a single string.\n * @extends Decoder\n */\nclass WordPieceDecoder extends Decoder {\n\n /**\n * Creates a new instance of WordPieceDecoder.\n * @param {Object} config The configuration object.\n * @param {string} config.prefix The prefix used for WordPiece encoding.\n * @param {boolean} config.cleanup Whether to cleanup the decoded string.\n */\n constructor(config) {\n super(config);\n this.cleanup = config.cleanup;\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return tokens.map((token, i) => {\n if (i !== 0) {\n if (token.startsWith(this.config.prefix)) {\n // NOTE: .replace() is intended; only replace first occurrence\n token = token.replace(this.config.prefix, '');\n } else {\n token = ' ' + token;\n }\n }\n if (this.cleanup) {\n token = clean_up_tokenization(token)\n }\n\n return token;\n });\n }\n}\n\n/**\n * Byte-level decoder for tokenization output. Inherits from the `Decoder` class.\n * @extends Decoder\n */\nclass ByteLevelDecoder extends Decoder {\n\n /**\n * Create a `ByteLevelDecoder` object.\n * @param {Object} config Configuration object.\n */\n constructor(config) {\n super(config);\n\n this.byte_decoder = UNICODE_TO_BYTES;\n this.text_decoder = new TextDecoder(\"utf-8\", {\n fatal: false,\n ignoreBOM: true,\n });\n\n this.end_of_word_suffix = null;\n }\n\n /**\n * Convert an array of tokens to string by decoding each byte.\n * @param {string[]} tokens Array of tokens to be decoded.\n * @returns {string} The decoded string.\n */\n convert_tokens_to_string(tokens) {\n const text = tokens.join('');\n const byteArray = new Uint8Array([...text].map(c => this.byte_decoder[c]));\n const decoded_text = this.text_decoder.decode(byteArray);\n return decoded_text;\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n // TODO move to base class (like HF)\n // tokens === filtered_tokens\n\n // To avoid mixing byte-level and unicode for byte-level BPT\n // we need to build string separately for added tokens and byte-level tokens\n // cf. https://github.com/huggingface/transformers/issues/1133\n const sub_texts = [];\n let current_sub_text = [];\n for (const token of tokens) {\n // tokens sent here are already filtered, so we don't need to do this\n // if (skip_special_tokens && this.all_special_ids.includes(token)) {\n // continue;\n // }\n\n if (this.added_tokens.find(x => x.content === token) !== undefined) {\n if (current_sub_text.length > 0) {\n sub_texts.push(this.convert_tokens_to_string(current_sub_text));\n current_sub_text = [];\n }\n sub_texts.push(token);\n } else {\n current_sub_text.push(token);\n }\n }\n if (current_sub_text.length > 0) {\n sub_texts.push(this.convert_tokens_to_string(current_sub_text));\n }\n\n // TODO add spaces_between_special_tokens and clean_up_tokenization_spaces options\n\n return sub_texts;\n }\n}\n\n/**\n * The CTC (Connectionist Temporal Classification) decoder.\n * See https://github.com/huggingface/tokenizers/blob/bb38f390a61883fc2f29d659af696f428d1cda6b/tokenizers/src/decoders/ctc.rs\n */\nclass CTCDecoder extends Decoder {\n\n constructor(config) {\n super(config);\n\n this.pad_token = this.config.pad_token;\n this.word_delimiter_token = this.config.word_delimiter_token;\n this.cleanup = this.config.cleanup;\n }\n /**\n * Converts a connectionist-temporal-classification (CTC) output tokens into a single string.\n * @param {string[]} tokens Array of tokens to be decoded.\n * @returns {string} The decoded string.\n */\n convert_tokens_to_string(tokens) {\n if (tokens.length === 0) return '';\n\n // group same tokens into non-repeating tokens in CTC style decoding\n const grouped_tokens = [tokens[0]];\n for (let i = 1; i < tokens.length; ++i) {\n if (tokens[i] !== grouped_tokens.at(-1)) {\n grouped_tokens.push(tokens[i]);\n }\n }\n\n // filter self.pad_token which is used as CTC-blank token\n const filtered_tokens = grouped_tokens.filter(token => token !== this.pad_token);\n\n let text = filtered_tokens.join('');\n if (this.cleanup) {\n // cleanup and replace delimiter token\n text = clean_up_tokenization(text)\n .replaceAll(this.word_delimiter_token, ' ')\n .trim();\n }\n return text;\n }\n\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return [this.convert_tokens_to_string(tokens)];\n }\n}\n\n/**\n * Apply a sequence of decoders.\n * @extends Decoder\n */\nclass DecoderSequence extends Decoder {\n\n /**\n * Creates a new instance of DecoderSequence.\n * @param {Object} config The configuration object.\n * @param {Object[]} config.decoders The list of decoders to apply.\n */\n constructor(config) {\n super(config);\n this.decoders = config.decoders.map(x => Decoder.fromConfig(x));\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n // Use reduce to apply each decoder to the tokens\n return this.decoders.reduce((toks, decoder) => {\n return decoder.decode_chain(toks);\n }, tokens);\n }\n\n}\n\nclass BPEDecoder extends Decoder {\n constructor(config) {\n super(config);\n\n this.suffix = this.config.suffix;\n }\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return tokens.map((token, i) => {\n return token.replaceAll(this.suffix, (i === tokens.length - 1) ? '' : ' ')\n });\n }\n}\n\n// Custom decoder for VITS\nclass VitsDecoder extends Decoder {\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n let decoded = '';\n for (let i = 1; i < tokens.length; i += 2) {\n decoded += tokens[i];\n }\n return [decoded];\n }\n}\n\n\n/**\n * This PreTokenizer replaces spaces with the given replacement character, adds a prefix space if requested,\n * and returns a list of tokens.\n * @extends PreTokenizer\n */\nclass MetaspacePreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration object for the MetaspacePreTokenizer.\n * @param {boolean} config.add_prefix_space Whether to add a prefix space to the first token.\n * @param {string} config.replacement The character to replace spaces with.\n * @param {string} [config.str_rep=config.replacement] An optional string representation of the replacement character.\n * @param {'first'|'never'|'always'} [config.prepend_scheme='always'] The metaspace prepending scheme.\n */\n constructor(config) {\n super();\n\n this.addPrefixSpace = config.add_prefix_space;\n this.replacement = config.replacement;\n this.strRep = config.str_rep || this.replacement;\n this.prepend_scheme = config.prepend_scheme ?? 'always';\n }\n\n /**\n * This method takes a string, replaces spaces with the replacement character,\n * adds a prefix space if requested, and returns a new list of tokens.\n * @param {string} text The text to pre-tokenize.\n * @param {Object} [options] The options for the pre-tokenization.\n * @param {number} [options.section_index] The index of the section to pre-tokenize.\n * @returns {string[]} A new list of pre-tokenized tokens.\n */\n pre_tokenize_text(text, {\n section_index = undefined,\n } = {}) {\n\n let normalized = text.replaceAll(' ', this.strRep);\n\n if (\n // We add a prefix space if:\n // (1) The addPrefixSpace option is enabled and the normalized\n // token does not already start with the replacement character.\n (this.addPrefixSpace && !normalized.startsWith(this.replacement))\n\n // and (2) either:\n // (a) prepend_scheme is 'always'\n // (b) prepend_scheme is 'first' and this is the first section\n && (\n this.prepend_scheme === 'always' ||\n (this.prepend_scheme === 'first' && section_index === 0)\n )\n ) {\n normalized = this.strRep + normalized;\n }\n return [normalized];\n }\n}\n\n/**\n * MetaspaceDecoder class extends the Decoder class and decodes Metaspace tokenization.\n * @extends Decoder\n */\nclass MetaspaceDecoder extends Decoder {\n /**\n * Constructs a new MetaspaceDecoder object.\n * @param {Object} config The configuration object for the MetaspaceDecoder.\n * @param {boolean} config.add_prefix_space Whether to add a prefix space to the decoded string.\n * @param {string} config.replacement The string to replace spaces with.\n */\n constructor(config) {\n super(config);\n\n this.addPrefixSpace = config.add_prefix_space;\n this.replacement = config.replacement;\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n const result = [];\n for (let i = 0; i < tokens.length; ++i) {\n let normalized = tokens[i].replaceAll(this.replacement, ' ');\n if (this.addPrefixSpace && i == 0 && normalized.startsWith(' ')) {\n normalized = normalized.substring(1);\n }\n result.push(normalized);\n }\n return result;\n }\n}\n\n/**\n * A normalizer that applies a precompiled charsmap.\n * This is useful for applying complex normalizations in C++ and exposing them to JavaScript.\n * @extends Normalizer\n * @param {Object} config The configuration object for the Precompiled normalizer.\n * @param {Object} config.precompiled_charsmap The precompiled charsmap object.\n */\nclass Precompiled extends Normalizer {\n /**\n * Create a new instance of Precompiled normalizer.\n * @param {Object} config The configuration object.\n * @param {any} config.precompiled_charsmap Precompiled chars mapping.\n */\n constructor(config) {\n super(config);\n this.charsmap = config.precompiled_charsmap;\n }\n\n /**\n * Normalizes the given text by applying the precompiled charsmap.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n // As stated in the sentencepiece normalization docs (https://github.com/google/sentencepiece/blob/master/doc/normalization.md#use-pre-defined-normalization-rule),\n // there are 5 pre-defined normalization rules:\n // 1. nmt_nfkc: NFKC normalization with some additional normalization around spaces. (default)\n // 2. nfkc: original NFKC normalization.\n // 3. nmt_nfkc_cf: nmt_nfkc + Unicode case folding (mostly lower casing)\n // 4. nfkc_cf: nfkc + Unicode case folding.\n // 5. identity: no normalization\n // \n // For now, we only implement the default (nmt_nfkc).\n // See https://raw.githubusercontent.com/google/sentencepiece/master/data/nmt_nfkc.tsv for the full list of rules.\n // TODO: detect when a different `this.charsmap` is used.\n\n text = text.replace(/[\\u0001-\\u0008\\u000B\\u000E-\\u001F\\u007F\\u008F\\u009F]/gm, ''); // Remove control characters\n text = text.replace(/[\\u0009\\u000A\\u000C\\u000D\\u00A0\\u1680\\u2000-\\u200F\\u2028\\u2029\\u202F\\u205F\\u2581\\u3000\\uFEFF\\uFFFD]/gm, '\\u0020'); // Replace certain characters with a space\n\n if (text.includes('\\uFF5E')) {\n // To match the sentencepiece implementation 100%, we must handle a very strange edge-case.\n // For some reason, the \"Fullwidth Tilde\" character (\\uFF5E) should not be converted to the standard Tilde character (\\u007E).\n // However, NFKC normalization does do this conversion. As a result, we split the string on the Fullwidth Tilde character,\n // perform NFKC normalization on each substring, and then join them back together with the Fullwidth Tilde character.\n const parts = text.split('\\uFF5E');\n text = parts.map(part => part.normalize('NFKC')).join('\\uFF5E');\n } else {\n text = text.normalize('NFKC');\n }\n\n return text;\n }\n}\n\n/**\n * A pre-tokenizer that applies a sequence of pre-tokenizers to the input text.\n * @extends PreTokenizer\n */\nclass PreTokenizerSequence extends PreTokenizer {\n /**\n * Creates an instance of PreTokenizerSequence.\n * @param {Object} config The configuration object for the pre-tokenizer sequence.\n * @param {Object[]} config.pretokenizers An array of pre-tokenizer configurations.\n */\n constructor(config) {\n super();\n this.tokenizers = config.pretokenizers.map(x => PreTokenizer.fromConfig(x));\n }\n\n /**\n * Applies each pre-tokenizer in the sequence to the input text in turn.\n * @param {string} text The text to pre-tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} The pre-tokenized text.\n */\n pre_tokenize_text(text, options) {\n // Use reduce to apply each tokenizer to the text\n return this.tokenizers.reduce((preTokenizedText, tokenizer) => {\n return tokenizer.pre_tokenize(preTokenizedText, options);\n }, [text]);\n }\n}\n\n/**\n * Splits on word boundaries (using the following regular expression: `\\w+|[^\\w\\s]+`).\n */\nclass WhitespacePreTokenizer extends PreTokenizer {\n /**\n * Creates an instance of WhitespacePreTokenizer.\n * @param {Object} config The configuration object for the pre-tokenizer.\n */\n constructor(config) {\n super();\n }\n /**\n * Pre-tokenizes the input text by splitting it on word boundaries.\n * @param {string} text The text to be pre-tokenized.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.\n */\n pre_tokenize_text(text, options) {\n return text.match(/\\w+|[^\\w\\s]+/g) || [];\n }\n}\n\n/**\n * Splits a string of text by whitespace characters into individual tokens.\n * @extends PreTokenizer\n */\nclass WhitespaceSplit extends PreTokenizer {\n /**\n * Creates an instance of WhitespaceSplit.\n * @param {Object} config The configuration object for the pre-tokenizer.\n */\n constructor(config) {\n super();\n }\n /**\n * Pre-tokenizes the input text by splitting it on whitespace characters.\n * @param {string} text The text to be pre-tokenized.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.\n */\n pre_tokenize_text(text, options) {\n return whitespace_split(text);\n }\n}\n\n// NOTE: `ReplacePreTokenizer` is custom (to support `BlenderbotSmallTokenizer`)\nclass ReplacePreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration options for the pre-tokenizer.\n * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.\n * @param {string} config.content What to replace the pattern with.\n */\n constructor(config) {\n super();\n this.config = config;\n this.pattern = createPattern(this.config.pattern);\n this.content = this.config.content;\n }\n\n /**\n * Pre-tokenizes the input text by replacing certain characters.\n * @param {string} text The text to be pre-tokenized.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens produced by replacing certain characters.\n */\n pre_tokenize_text(text, options) {\n if (this.pattern === null) {\n return [text];\n }\n return [text.replaceAll(this.pattern, this.config.content)];\n }\n}\n\nconst SPECIAL_TOKEN_ATTRIBUTES = [\n 'bos_token',\n 'eos_token',\n 'unk_token',\n 'sep_token',\n 'pad_token',\n 'cls_token',\n 'mask_token',\n // additional_special_tokens (TODO)\n]\n\n/**\n * \n * Helper function for padding values of an object, which are each arrays.\n * NOTE: No additional checks are made here for validity of arguments.\n * @param {Record} item The input object.\n * @param {number} length The length to pad to.\n * @param {(key: string) => any} value_fn Determine the value to fill the array, based on its key.\n * @param {string} side Which side to pad the array.\n * @private\n */\nfunction padHelper(item, length, value_fn, side) {\n for (const key of Object.keys(item)) {\n const diff = length - item[key].length;\n const value = value_fn(key);\n\n const padData = new Array(diff).fill(value);\n item[key] = side === 'right'\n ? mergeArrays(item[key], padData)\n : mergeArrays(padData, item[key]);\n }\n}\n\n/**\n * Helper function for truncating values of an object, which are each arrays.\n * NOTE: No additional checks are made here for validity of arguments.\n * @param {Record} item The input object.\n * @param {number} length The length to truncate to.\n * @private\n */\nfunction truncateHelper(item, length) {\n // Setting .length to a lower value truncates the array in-place:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length\n for (const key of Object.keys(item)) {\n item[key].length = length;\n }\n}\n\n\n/**\n * @typedef {Object} Message\n * @property {string} role The role of the message (e.g., \"user\" or \"assistant\" or \"system\").\n * @property {string} content The content of the message.\n */\n\nexport class PreTrainedTokenizer extends Callable {\n return_token_type_ids = false;\n\n padding_side = 'right';\n /**\n * Create a new PreTrainedTokenizer instance.\n * @param {Object} tokenizerJSON The JSON of the tokenizer.\n * @param {Object} tokenizerConfig The config of the tokenizer.\n */\n constructor(tokenizerJSON, tokenizerConfig) {\n super();\n\n this._tokenizer_config = tokenizerConfig;\n\n // Construct parts of the tokenizer from the JSON\n this.normalizer = Normalizer.fromConfig(tokenizerJSON.normalizer);\n this.pre_tokenizer = PreTokenizer.fromConfig(tokenizerJSON.pre_tokenizer);\n this.model = TokenizerModel.fromConfig(tokenizerJSON.model, tokenizerConfig);\n this.post_processor = PostProcessor.fromConfig(tokenizerJSON.post_processor);\n this.decoder = Decoder.fromConfig(tokenizerJSON.decoder);\n\n // Add added_tokens to model\n this.special_tokens = [];\n this.all_special_ids = [];\n\n /** @type {AddedToken[]} */\n this.added_tokens = [];\n for (const addedToken of tokenizerJSON.added_tokens) {\n const token = new AddedToken(addedToken);\n this.added_tokens.push(token);\n\n this.model.tokens_to_ids.set(token.content, token.id);\n this.model.vocab[token.id] = token.content;\n\n if (token.special) {\n this.special_tokens.push(token.content);\n this.all_special_ids.push(token.id);\n }\n }\n\n // Update additional_special_tokens\n this.additional_special_tokens = tokenizerConfig.additional_special_tokens ?? [];\n this.special_tokens.push(...this.additional_special_tokens);\n this.special_tokens = [...new Set(this.special_tokens)]; // Remove duplicates\n\n if (this.decoder) {\n // Slight hack, but it prevents code duplication:\n this.decoder.added_tokens = this.added_tokens;\n\n // Another slight hack to add `end_of_word_suffix` (if present) to the decoder\n // This is needed for cases where BPE model and ByteLevel decoder are used\n // For more information, see https://github.com/huggingface/transformers.js/issues/74\n // TODO: save this to the decoder when exporting?\n this.decoder.end_of_word_suffix = this.model.end_of_word_suffix;\n }\n\n this.added_tokens_regex = this.added_tokens.length > 0 ? new RegExp(\n this.added_tokens.slice()\n // Sort by length (desc) to avoid early partial matches\n .sort((a, b) => b.content.length - a.content.length)\n .map(x => `${x.lstrip ? '\\\\s*' : ''}(${escapeRegExp(x.content)})${x.rstrip ? '\\\\s*' : ''}`)\n .join('|')\n ) : null;\n\n // Set mask token if present (otherwise will be undefined, which is fine)\n this.mask_token = this.getToken('mask_token');\n this.mask_token_id = this.model.tokens_to_ids.get(this.mask_token);\n\n this.pad_token = this.getToken('pad_token', 'eos_token');\n this.pad_token_id = this.model.tokens_to_ids.get(this.pad_token);\n\n this.sep_token = this.getToken('sep_token');\n this.sep_token_id = this.model.tokens_to_ids.get(this.sep_token);\n\n this.unk_token = this.getToken('unk_token');\n this.unk_token_id = this.model.tokens_to_ids.get(this.unk_token);\n\n this.model_max_length = tokenizerConfig.model_max_length;\n\n /** @type {boolean} Whether or not to strip the text when tokenizing (removing excess spaces before and after the string). */\n this.remove_space = tokenizerConfig.remove_space;\n\n this.clean_up_tokenization_spaces = tokenizerConfig.clean_up_tokenization_spaces ?? true;\n this.do_lowercase_and_remove_accent = tokenizerConfig.do_lowercase_and_remove_accent ?? false;\n\n if (tokenizerConfig.padding_side) {\n this.padding_side = tokenizerConfig.padding_side;\n }\n\n this.legacy = false;\n\n this.chat_template = tokenizerConfig.chat_template ?? null;\n if (Array.isArray(this.chat_template)) {\n // Chat templates are stored as lists of dicts with fixed key names,\n // we reconstruct that into a single dict while loading them.\n const chat_template = Object.create(null);\n for (const { name, template } of this.chat_template) {\n if (typeof name !== 'string' || typeof template !== 'string') {\n throw new Error('Chat template must be a list of objects with \"name\" and \"template\" properties');\n }\n chat_template[name] = template;\n }\n this.chat_template = chat_template;\n }\n this._compiled_template_cache = new Map();\n }\n\n /**\n * Returns the value of the first matching key in the tokenizer config object.\n * @param {...string} keys One or more keys to search for in the tokenizer config object.\n * @returns {string|null} The value associated with the first matching key, or null if no match is found.\n * @throws {Error} If an object is found for a matching key and its __type property is not \"AddedToken\".\n * @private\n */\n getToken(...keys) {\n for (const key of keys) {\n const item = this._tokenizer_config[key];\n\n if (!item) continue;\n\n if (typeof item === 'object') {\n if (item.__type === 'AddedToken') {\n return item.content;\n } else {\n throw Error(`Unknown token: ${item}`);\n }\n } else {\n return item;\n }\n }\n return null;\n }\n\n /**\n * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`. \n * \n * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer.\n * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.\n * \n * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`.\n * @returns {Promise} A new instance of the `PreTrainedTokenizer` class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n legacy = null,\n } = {}) {\n\n const info = await loadTokenizer(pretrained_model_name_or_path, {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n legacy,\n })\n\n // @ts-ignore\n return new this(...info);\n }\n\n /**\n * @typedef {number[]|number[][]|Tensor} BatchEncodingItem\n * \n * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function.\n * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model.\n * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model.\n * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model.\n */\n\n /**\n * Encode/tokenize the given text(s).\n * @param {string|string[]} text The text to tokenize.\n * @param {Object} options An optional object containing the following properties:\n * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text.\n * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences.\n * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.\n * @param {boolean} [options.truncation=null] Whether to truncate the input sequences.\n * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length.\n * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays.\n * @param {boolean} [options.return_token_type_ids=null] Whether to return the token type ids.\n * @returns {BatchEncoding} Object to be passed to the model.\n */\n _call(\n // Required positional arguments\n text,\n\n // Optional keyword arguments\n {\n text_pair = null,\n add_special_tokens = true,\n padding = false,\n truncation = null,\n max_length = null,\n return_tensor = true, // Different to HF\n return_token_type_ids = null,\n } = {},\n ) {\n\n const isBatched = Array.isArray(text);\n\n /** @type {EncodingSingle[]} */\n let encodedTokens;\n\n if (isBatched) {\n if (text.length === 0) {\n throw Error('text array must be non-empty')\n }\n\n if (text_pair !== null) {\n if (!Array.isArray(text_pair)) {\n throw Error('text_pair must also be an array')\n\n } else if (text.length !== text_pair.length) {\n throw Error('text and text_pair must have the same length')\n }\n\n encodedTokens = text.map(\n (t, i) => this._encode_plus(t, { text_pair: text_pair[i], add_special_tokens, return_token_type_ids })\n )\n\n } else {\n encodedTokens = text.map(x => this._encode_plus(x, { add_special_tokens, return_token_type_ids }));\n }\n\n } else {\n if (text === null || text === undefined) {\n throw Error('text may not be null or undefined')\n }\n\n if (Array.isArray(text_pair)) {\n throw Error('When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).')\n }\n\n // For single input, we just wrap in an array, and then unwrap later.\n encodedTokens = [this._encode_plus(text, { text_pair, add_special_tokens, return_token_type_ids })];\n }\n // At this point, tokens is batched: [batch_size, tokens]\n // However, array may be jagged. So, we pad to max_length\n\n if (max_length === null) {\n if (padding === 'max_length') {\n max_length = this.model_max_length;\n } else {\n // Calculate max length from sequences\n max_length = max(encodedTokens.map(x => x.input_ids.length))[0];\n }\n } else {\n if (!truncation) {\n console.warn(`Truncation was not explicitly activated but \\`max_length\\` is provided a specific value, please use \\`truncation=true\\` to explicitly truncate examples to max length.`)\n }\n }\n\n // Ensure it is less than model max length\n max_length = Math.min(max_length, this.model_max_length ?? Infinity);\n\n if (padding || truncation) {\n\n // Perform padding and/or truncation\n for (let i = 0; i < encodedTokens.length; ++i) {\n if (encodedTokens[i].input_ids.length === max_length) {\n continue;\n\n } else if (encodedTokens[i].input_ids.length > max_length) {\n // possibly truncate\n if (truncation) {\n truncateHelper(encodedTokens[i], max_length);\n }\n\n } else { // t.length < max_length\n // possibly pad\n if (padding) {\n padHelper(\n encodedTokens[i],\n max_length,\n key => key === 'input_ids' ? this.pad_token_id : 0,\n this.padding_side\n );\n }\n }\n }\n }\n\n const result = {};\n\n if (return_tensor) {\n if (!(padding && truncation)) {\n // Not, guaranteed that all items have same length, so\n // we perform additional check\n\n if (\n encodedTokens.some(x => {\n for (const key of Object.keys(x)) {\n if (x[key].length !== encodedTokens[0][key]?.length) {\n return true;\n }\n }\n return false;\n })\n ) {\n throw Error(\n \"Unable to create tensor, you should probably activate truncation and/or padding \" +\n \"with 'padding=true' and 'truncation=true' to have batched tensors with the same length.\"\n )\n }\n }\n\n // Now we actually convert to tensor\n // NOTE: In the same way as the python library, we return a batched tensor, regardless of\n // whether we have a single input or multiple inputs.\n const dims = [encodedTokens.length, encodedTokens[0].input_ids.length];\n\n for (const key of Object.keys(encodedTokens[0])) {\n result[key] = new Tensor('int64',\n BigInt64Array.from(encodedTokens.flatMap(x => x[key]).map(BigInt)),\n dims\n );\n }\n\n } else {\n for (const key of Object.keys(encodedTokens[0])) {\n result[key] = encodedTokens.map(x => x[key]);\n }\n\n // If not returning a tensor, we match the input type\n if (!isBatched) {\n // Input was not batched, so we unwrap\n for (const key of Object.keys(result)) {\n result[key] = result[key][0];\n }\n }\n }\n\n return /** @type {BatchEncoding} */(result);\n }\n\n /**\n * Encodes a single text using the preprocessor pipeline of the tokenizer.\n *\n * @param {string|null} text The text to encode.\n * @returns {string[]|null} The encoded tokens.\n */\n _encode_text(text) {\n if (text === null) return null;\n\n // Actual function which does encoding, for a single text\n // First, we take care of special tokens. Needed to avoid issues arising from\n // normalization and/or pretokenization (which may not preserve special tokens)\n const sections = this.added_tokens_regex ? text.split(this.added_tokens_regex).filter(x => x) : [text];\n\n const tokens = sections.map((x, section_index) => {\n const addedToken = this.added_tokens.find(t => t.content === x);\n if (addedToken !== undefined) {\n // Ignore added tokens\n return x\n } else {\n if (this.remove_space === true) {\n x = x.trim().split(/\\s+/).join(' ');\n }\n if (this.do_lowercase_and_remove_accent) {\n x = lowercase_and_remove_accent(x);\n }\n\n if (this.normalizer !== null) {\n x = this.normalizer(x);\n }\n\n // If, after normalization, this section is empty (e.g., trimming whitespace),\n // we return an empty array\n if (x.length === 0) {\n return [];\n }\n\n const sectionTokens = (this.pre_tokenizer !== null) ? this.pre_tokenizer(x, {\n section_index,\n }) : [x];\n\n const tokens = this.model(sectionTokens);\n\n return tokens;\n }\n }).flat();\n\n return tokens;\n }\n\n /**\n * Encodes a single text or a pair of texts using the model's tokenizer.\n *\n * @param {string} text The text to encode.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.text_pair=null] The optional second text to encode.\n * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.\n * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids.\n * @returns {EncodingSingle} An object containing the encoded text.\n * @private\n */\n _encode_plus(text, {\n text_pair = null,\n add_special_tokens = true,\n return_token_type_ids = null,\n } = {}) {\n\n const { tokens, token_type_ids } = this._tokenize_helper(text, { pair: text_pair, add_special_tokens });\n\n const input_ids = this.model.convert_tokens_to_ids(tokens);\n\n const result = {\n input_ids,\n attention_mask: new Array(input_ids.length).fill(1),\n }\n if ((return_token_type_ids ?? this.return_token_type_ids) && token_type_ids) {\n result.token_type_ids = token_type_ids;\n }\n return result;\n }\n\n /**\n * Internal helper function to tokenize a text, and optionally a pair of texts.\n * @param {string} text The text to tokenize.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.pair=null] The optional second text to tokenize.\n * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model.\n * @returns {{tokens: string[], token_type_ids?: number[]}} An object containing the tokens and optionally the token type IDs.\n */\n _tokenize_helper(text, {\n pair = null,\n add_special_tokens = false,\n } = {}) {\n const tokens = this._encode_text(text);\n const tokens2 = this._encode_text(pair);\n\n return this.post_processor\n ? this.post_processor(tokens, tokens2, { add_special_tokens })\n : { tokens: mergeArrays(tokens ?? [], tokens2 ?? []) };\n }\n\n /**\n * Converts a string into a sequence of tokens.\n * @param {string} text The sequence to be encoded.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.pair] A second sequence to be encoded with the first.\n * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model.\n * @returns {string[]} The list of tokens.\n */\n tokenize(text, {\n pair = null,\n add_special_tokens = false,\n } = {}) {\n return this._tokenize_helper(text, { pair, add_special_tokens }).tokens;\n }\n\n /**\n * Encodes a single text or a pair of texts using the model's tokenizer.\n *\n * @param {string} text The text to encode.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.text_pair=null] The optional second text to encode.\n * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.\n * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids.\n * @returns {number[]} An array of token IDs representing the encoded text(s).\n */\n encode(text, {\n text_pair = null,\n add_special_tokens = true,\n return_token_type_ids = null,\n } = {}) {\n return this._encode_plus(text, {\n text_pair,\n add_special_tokens,\n return_token_type_ids,\n }).input_ids;\n }\n\n /**\n * Decode a batch of tokenized sequences.\n * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences.\n * @param {Object} decode_args (Optional) Object with decoding arguments.\n * @returns {string[]} List of decoded sequences.\n */\n batch_decode(batch, decode_args = {}) {\n if (batch instanceof Tensor) {\n batch = batch.tolist();\n }\n return batch.map(x => this.decode(x, decode_args));\n }\n\n /**\n * Decodes a sequence of token IDs back to a string.\n *\n * @param {number[]|bigint[]|Tensor} token_ids List/Tensor of token IDs to decode.\n * @param {Object} [decode_args={}]\n * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string.\n * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuations and abbreviated forms are removed.\n *\n * @returns {string} The decoded string.\n * @throws {Error} If `token_ids` is not a non-empty array of integers.\n */\n decode(\n token_ids,\n decode_args = {},\n ) {\n if (token_ids instanceof Tensor) {\n token_ids = prepareTensorForDecode(token_ids);\n }\n\n if (!Array.isArray(token_ids) || token_ids.length === 0 || !isIntegralNumber(token_ids[0])) {\n throw Error(\"token_ids must be a non-empty array of integers.\");\n }\n\n return this.decode_single(token_ids, decode_args)\n }\n\n /**\n * Decode a single list of token ids to a string.\n * @param {number[]|bigint[]} token_ids List of token ids to decode\n * @param {Object} decode_args Optional arguments for decoding\n * @param {boolean} [decode_args.skip_special_tokens=false] Whether to skip special tokens during decoding\n * @param {boolean} [decode_args.clean_up_tokenization_spaces=null] Whether to clean up tokenization spaces during decoding.\n * If null, the value is set to `this.decoder.cleanup` if it exists, falling back to `this.clean_up_tokenization_spaces` if it exists, falling back to `true`.\n * @returns {string} The decoded string\n */\n decode_single(\n token_ids,\n {\n skip_special_tokens = false,\n clean_up_tokenization_spaces = null,\n }\n ) {\n let tokens = this.model.convert_ids_to_tokens(token_ids);\n if (skip_special_tokens) {\n tokens = tokens.filter(x => !this.special_tokens.includes(x));\n }\n\n // If `this.decoder` is null, we just join tokens with a space:\n // https://github.com/huggingface/tokenizers/blob/8edec536a737cb04494b454805be16c020abb14f/tokenizers/src/tokenizer/mod.rs#L835\n /** @type {string} */\n let decoded = this.decoder ? this.decoder(tokens) : tokens.join(' ');\n\n // Slight hack, but prevents having to pass `skip_special_tokens` to\n // each call to `decode`, which would lead to code duplication.\n if (this.decoder && this.decoder.end_of_word_suffix) {\n decoded = decoded.replaceAll(this.decoder.end_of_word_suffix, ' ');\n if (skip_special_tokens) {\n decoded = decoded.trim();\n }\n }\n\n if (clean_up_tokenization_spaces ?? this.clean_up_tokenization_spaces) {\n decoded = clean_up_tokenization(decoded);\n }\n\n return decoded;\n }\n\n /**\n * Retrieve the chat template string used for tokenizing chat messages. This template is used\n * internally by the `apply_chat_template` method and can also be used externally to retrieve the model's chat\n * template for better generation tracking.\n * \n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.chat_template=null]\n * A Jinja template or the name of a template to use for this conversion.\n * It is usually not necessary to pass anything to this argument,\n * as the model's template will be used by default.\n * @param {Object[]} [options.tools=null]\n * A list of tools (callable functions) that will be accessible to the model. If the template does not\n * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema,\n * giving the name, description and argument types for the tool. See our\n * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use)\n * for more information.\n * @returns {string} The chat template string.\n */\n get_chat_template({\n chat_template = null,\n tools = null,\n } = {}) {\n\n // First, handle the cases when the model has a dict of multiple templates\n if (this.chat_template && typeof this.chat_template === 'object') {\n const template_dict = this.chat_template;\n\n if (chat_template !== null && Object.hasOwn(template_dict, chat_template)) {\n // The user can pass the name of a template to the chat template argument instead of an entire template\n chat_template = template_dict[chat_template];\n } else if (chat_template === null) {\n if (tools !== null && 'tool_use' in template_dict) {\n chat_template = template_dict['tool_use'];\n } else if ('default' in template_dict) {\n chat_template = template_dict['default'];\n } else {\n throw Error(\n `This model has multiple chat templates with no default specified! Please either pass a chat ` +\n `template or the name of the template you wish to use to the 'chat_template' argument. Available ` +\n `template names are ${Object.keys(template_dict).sort()}.`\n )\n }\n }\n } else if (chat_template === null) {\n // These are the cases when the model has a single template\n // priority: `chat_template` argument > `tokenizer.chat_template`\n if (this.chat_template) {\n chat_template = this.chat_template;\n } else {\n throw Error(\n \"Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template \" +\n \"argument was passed! For information about writing templates and setting the \" +\n \"tokenizer.chat_template attribute, please see the documentation at \" +\n \"https://huggingface.co/docs/transformers/main/en/chat_templating\"\n )\n }\n }\n return chat_template;\n }\n\n /**\n * Converts a list of message objects with `\"role\"` and `\"content\"` keys to a list of token\n * ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to\n * determine the format and control tokens to use when converting.\n * \n * See [here](https://huggingface.co/docs/transformers/chat_templating) for more information.\n * \n * **Example:** Applying a chat template to a conversation.\n * \n * ```javascript\n * import { AutoTokenizer } from \"@huggingface/transformers\";\n * \n * const tokenizer = await AutoTokenizer.from_pretrained(\"Xenova/mistral-tokenizer-v1\");\n * \n * const chat = [\n * { \"role\": \"user\", \"content\": \"Hello, how are you?\" },\n * { \"role\": \"assistant\", \"content\": \"I'm doing great. How can I help you today?\" },\n * { \"role\": \"user\", \"content\": \"I'd like to show off how chat templating works!\" },\n * ]\n * \n * const text = tokenizer.apply_chat_template(chat, { tokenize: false });\n * // \"[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today? [INST] I'd like to show off how chat templating works! [/INST]\"\n * \n * const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false });\n * // [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793]\n * ```\n * \n * @param {Message[]} conversation A list of message objects with `\"role\"` and `\"content\"` keys,\n * representing the chat history so far.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.chat_template=null] A Jinja template to use for this conversion. If\n * this is not passed, the model's chat template will be used instead.\n * @param {Object[]} [options.tools=null]\n * A list of tools (callable functions) that will be accessible to the model. If the template does not\n * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema,\n * giving the name, description and argument types for the tool. See our\n * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use)\n * for more information.\n * @param {Record[]} [options.documents=null]\n * A list of dicts representing documents that will be accessible to the model if it is performing RAG\n * (retrieval-augmented generation). If the template does not support RAG, this argument will have no\n * effect. We recommend that each document should be a dict containing \"title\" and \"text\" keys. Please\n * see the RAG section of the [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#arguments-for-RAG)\n * for examples of passing documents with chat templates.\n * @param {boolean} [options.add_generation_prompt=false] Whether to end the prompt with the token(s) that indicate\n * the start of an assistant message. This is useful when you want to generate a response from the model.\n * Note that this argument will be passed to the chat template, and so it must be supported in the\n * template for this argument to have any effect.\n * @param {boolean} [options.tokenize=true] Whether to tokenize the output. If false, the output will be a string.\n * @param {boolean} [options.padding=false] Whether to pad sequences to the maximum length. Has no effect if tokenize is false.\n * @param {boolean} [options.truncation=false] Whether to truncate sequences to the maximum length. Has no effect if tokenize is false.\n * @param {number} [options.max_length=null] Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is false.\n * If not specified, the tokenizer's `max_length` attribute will be used as a default.\n * @param {boolean} [options.return_tensor=true] Whether to return the output as a Tensor or an Array. Has no effect if tokenize is false.\n * @param {boolean} [options.return_dict=true] Whether to return a dictionary with named outputs. Has no effect if tokenize is false.\n * @param {Object} [options.tokenizer_kwargs={}] Additional options to pass to the tokenizer.\n * @returns {string | Tensor | number[]| number[][]|BatchEncoding} The tokenized output.\n */\n apply_chat_template(conversation, {\n tools = null,\n documents = null,\n chat_template = null,\n add_generation_prompt = false,\n tokenize = true,\n padding = false,\n truncation = false,\n max_length = null,\n return_tensor = true,\n return_dict = false,\n tokenizer_kwargs = {},\n ...kwargs\n } = {}) {\n\n chat_template = this.get_chat_template({ chat_template, tools });\n\n if (typeof chat_template !== 'string') {\n throw Error(`chat_template must be a string, but got ${typeof chat_template}`);\n }\n\n // Compilation function uses a cache to avoid recompiling the same template\n let compiledTemplate = this._compiled_template_cache.get(chat_template);\n if (compiledTemplate === undefined) {\n compiledTemplate = new Template(chat_template);\n this._compiled_template_cache.set(chat_template, compiledTemplate);\n }\n\n const special_tokens_map = Object.create(null);\n for (const key of SPECIAL_TOKEN_ATTRIBUTES) {\n const value = this.getToken(key);\n if (value) {\n special_tokens_map[key] = value;\n }\n }\n\n const rendered = compiledTemplate.render({\n messages: conversation,\n add_generation_prompt,\n tools,\n documents,\n ...special_tokens_map,\n ...kwargs,\n });\n\n if (tokenize) {\n const out = this._call(rendered, {\n add_special_tokens: false,\n padding,\n truncation,\n max_length,\n return_tensor,\n ...tokenizer_kwargs,\n });\n return return_dict ? out : out.input_ids;\n }\n\n return rendered;\n }\n}\n\n/**\n * BertTokenizer is a class used to tokenize text for BERT models.\n * @extends PreTrainedTokenizer\n */\nexport class BertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\n/**\n * Albert tokenizer\n * @extends PreTrainedTokenizer\n */\nexport class AlbertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class MobileBertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class SqueezeBertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class DebertaTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class DebertaV2Tokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class HerbertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class ConvBertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class RoFormerTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class DistilBertTokenizer extends PreTrainedTokenizer { }\nexport class CamembertTokenizer extends PreTrainedTokenizer { }\nexport class XLMTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\\'s \"fast\" tokenizers library. Therefore, you may experience slightly inaccurate results.')\n }\n}\nexport class ElectraTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\n\nexport class T5Tokenizer extends PreTrainedTokenizer { }\nexport class GPT2Tokenizer extends PreTrainedTokenizer { }\nexport class BartTokenizer extends PreTrainedTokenizer { }\nexport class MBartTokenizer extends PreTrainedTokenizer {\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.languageRegex = /^[a-z]{2}_[A-Z]{2}$/;\n this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x));\n this.lang_to_token = x => x; // Identity function\n }\n\n /**\n * Helper function to build translation inputs for an `MBartTokenizer`.\n * @param {string|string[]} raw_inputs The text to tokenize.\n * @param {Object} tokenizer_options Options to be sent to the tokenizer\n * @param {Object} generate_kwargs Generation options.\n * @returns {Object} Object to be passed to the model.\n */\n _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {\n return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);\n }\n}\nexport class MBart50Tokenizer extends MBartTokenizer { } // NOTE: extends MBartTokenizer\n\nexport class RobertaTokenizer extends PreTrainedTokenizer { }\n\nexport class BloomTokenizer extends PreTrainedTokenizer { }\n\nconst SPIECE_UNDERLINE = \"▁\";\n\nexport class LlamaTokenizer extends PreTrainedTokenizer {\n\n padding_side = 'left';\n\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.legacy = tokenizerConfig.legacy ?? true;\n if (!this.legacy) {\n // See https://github.com/huggingface/transformers/pull/24565 for more information\n this.normalizer = null;\n this.pre_tokenizer = new MetaspacePreTokenizer({\n replacement: SPIECE_UNDERLINE,\n add_prefix_space: true,\n prepend_scheme: \"first\",\n });\n }\n }\n\n /**\n * Helper function to handle legacy encoding of SPM tokenizers.\n * Adapted from https://github.com/huggingface/transformers/blob/e6dcf8abd6f65bb4b6dfc1831b20d9ba49ce00e2/src/transformers/models/t5/tokenization_t5.py#L374-L387\n * @param {string} text The text to encode.\n * @returns {string[]} The encoded tokens.\n */\n _encode_text(text) {\n if (text === null) return null;\n\n if (this.legacy || text.length === 0) {\n return super._encode_text(text);\n }\n\n let tokens = super._encode_text(SPIECE_UNDERLINE + text.replaceAll(SPIECE_UNDERLINE, \" \"));\n if (tokens.length > 1 && tokens[0] === SPIECE_UNDERLINE && this.special_tokens.includes(tokens[1])) {\n tokens = tokens.slice(1);\n }\n return tokens;\n }\n}\nexport class CodeLlamaTokenizer extends PreTrainedTokenizer { }\n\nexport class XLMRobertaTokenizer extends PreTrainedTokenizer { }\nexport class MPNetTokenizer extends PreTrainedTokenizer { }\n\nexport class FalconTokenizer extends PreTrainedTokenizer { }\n\nexport class GPTNeoXTokenizer extends PreTrainedTokenizer { }\n\nexport class EsmTokenizer extends PreTrainedTokenizer { }\n\nexport class Qwen2Tokenizer extends PreTrainedTokenizer { }\n\nexport class GemmaTokenizer extends PreTrainedTokenizer { }\n\nexport class Grok1Tokenizer extends PreTrainedTokenizer { }\n\n/**\n * Helper function to build translation inputs for an `NllbTokenizer` or `M2M100Tokenizer`.\n * @param {PreTrainedTokenizer} self The tokenizer instance.\n * @param {string|string[]} raw_inputs The text to tokenize.\n * @param {Object} tokenizer_options Options to be sent to the tokenizer\n * @param {Object} generate_kwargs Generation options.\n * @returns {Object} Object to be passed to the model.\n * @private\n */\nfunction _build_translation_inputs(self, raw_inputs, tokenizer_options, generate_kwargs) {\n if (!('language_codes' in self) || !Array.isArray(self.language_codes)) {\n throw new Error('Tokenizer must have `language_codes` attribute set and it should be an array of language ids.')\n }\n if (!('languageRegex' in self) || !(self.languageRegex instanceof RegExp)) {\n throw new Error('Tokenizer must have `languageRegex` attribute set and it should be a regular expression.')\n }\n if (!('lang_to_token' in self) || typeof self.lang_to_token !== 'function') {\n throw new Error('Tokenizer must have `lang_to_token` attribute set and it should be a function.')\n }\n const src_lang_token = generate_kwargs.src_lang;\n const tgt_lang_token = generate_kwargs.tgt_lang;\n\n // Check that the target language is valid:\n if (!self.language_codes.includes(tgt_lang_token)) {\n throw new Error(`Target language code \"${tgt_lang_token}\" is not valid. Must be one of: {${self.language_codes.join(', ')}}`);\n }\n\n // Allow `src_lang` to be optional. If not set, we'll use the tokenizer's default.\n if (src_lang_token !== undefined) {\n // Check that the source language is valid:\n if (!self.language_codes.includes(src_lang_token)) {\n throw new Error(`Source language code \"${src_lang_token}\" is not valid. Must be one of: {${self.language_codes.join(', ')}}`);\n }\n\n // In the same way as the Python library, we override the post-processor\n // to force the source language to be first:\n for (const item of self.post_processor.config.single) {\n if ('SpecialToken' in item && self.languageRegex.test(item.SpecialToken.id)) {\n item.SpecialToken.id = self.lang_to_token(src_lang_token);\n break;\n }\n }\n // TODO: Do the same for pair?\n }\n\n // Override the `forced_bos_token_id` to force the correct language\n generate_kwargs.forced_bos_token_id = self.model.convert_tokens_to_ids([self.lang_to_token(tgt_lang_token)])[0];\n\n return self._call(raw_inputs, tokenizer_options);\n}\n\n/**\n * The NllbTokenizer class is used to tokenize text for NLLB (\"No Language Left Behind\") models.\n * \n * No Language Left Behind (NLLB) is a first-of-its-kind, AI breakthrough project\n * that open-sources models capable of delivering high-quality translations directly\n * between any pair of 200+ languages — including low-resource languages like Asturian,\n * Luganda, Urdu and more. It aims to help people communicate with anyone, anywhere,\n * regardless of their language preferences. For more information, check out their\n * [paper](https://arxiv.org/abs/2207.04672).\n * \n * For a list of supported languages (along with their language codes),\n * @see {@link https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200}\n */\nexport class NllbTokenizer extends PreTrainedTokenizer {\n\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.languageRegex = /^[a-z]{3}_[A-Z][a-z]{3}$/;\n this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x));\n this.lang_to_token = x => x; // Identity function\n }\n\n /**\n * Helper function to build translation inputs for an `NllbTokenizer`.\n * @param {string|string[]} raw_inputs The text to tokenize.\n * @param {Object} tokenizer_options Options to be sent to the tokenizer\n * @param {Object} generate_kwargs Generation options.\n * @returns {Object} Object to be passed to the model.\n */\n _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {\n return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);\n }\n}\n\n/**\n * The M2M100Tokenizer class is used to tokenize text for M2M100 (\"Many-to-Many\") models.\n * \n * M2M100 is a multilingual encoder-decoder (seq-to-seq) model trained for Many-to-Many\n * multilingual translation. It was introduced in this [paper](https://arxiv.org/abs/2010.11125)\n * and first released in [this](https://github.com/pytorch/fairseq/tree/master/examples/m2m_100) repository.\n * \n * For a list of supported languages (along with their language codes),\n * @see {@link https://huggingface.co/facebook/m2m100_418M#languages-covered}\n */\nexport class M2M100Tokenizer extends PreTrainedTokenizer {\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.languageRegex = /^__[a-z]{2,3}__$/;\n this.language_codes = this.special_tokens\n .filter(x => this.languageRegex.test(x))\n .map(x => x.slice(2, -2));\n this.lang_to_token = x => `__${x}__`;\n }\n\n /**\n * Helper function to build translation inputs for an `M2M100Tokenizer`.\n * @param {string|string[]} raw_inputs The text to tokenize.\n * @param {Object} tokenizer_options Options to be sent to the tokenizer\n * @param {Object} generate_kwargs Generation options.\n * @returns {Object} Object to be passed to the model.\n */\n _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {\n return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);\n }\n}\n\n/**\n * WhisperTokenizer tokenizer\n * @extends PreTrainedTokenizer\n */\nexport class WhisperTokenizer extends PreTrainedTokenizer {\n\n get timestamp_begin() {\n return this.model.convert_tokens_to_ids([\"<|notimestamps|>\"])[0] + 1;\n }\n\n /**\n * Decodes automatic speech recognition (ASR) sequences.\n * @param {Array<{tokens: bigint[], token_timestamps?: number[], stride: number[]}>} sequences The sequences to decode.\n * @param {Object} options The options to use for decoding.\n * @returns {Array, text: string}>}>} The decoded sequences.\n */\n _decode_asr(sequences, {\n return_timestamps = false,\n return_language = false,\n time_precision = null,\n force_full_sequences = true\n } = {}) {\n // Set force_full_sequences=false if you want streaming\n // TODO add support for `return_language`\n\n // Internal method meant to only be used by asr pipeline.\n // Handles all the little quirks specific to whisper to handle\n // the various options not allowed in other seq2seq models\n\n // =========== Overview ============\n // - iterate over all outputs\n // - all tokens within output\n // - Each token can be\n // - language token\n // - special token\n // - timestamp token\n // - text token\n // - We accumulate the text tokens.\n // - We split on end timestamps\n // - Lots of complexity comes from stride and timestamps\n\n if (time_precision === null) {\n throw Error(\"Must specify time_precision\")\n }\n let last_language = null;\n\n const returnWordTimestamps = return_timestamps === \"word\";\n\n function new_chunk() {\n return { \"language\": last_language, \"timestamp\": [null, null], \"text\": \"\" };\n }\n\n // Welcome to the state machine!\n const chunks = [];\n let chunk = new_chunk();\n let time_offset = 0.0;\n const timestamp_begin = this.timestamp_begin;\n\n let previous_tokens = [];\n let previous_token_timestamps = [];\n\n let skip = false;\n let right_stride_start = null;\n\n\n const all_special_ids = new Set(this.all_special_ids);\n\n for (const output of sequences) {\n // NOTE: python version has batches, so it uses [0]\n const token_ids = output.tokens;\n const token_timestamps = returnWordTimestamps ? output.token_timestamps : null;\n\n // These keep track of timestamps within strides, which need\n // to be skipped and resolve all tokens in a single chunk.\n let last_timestamp = null;\n let first_timestamp = timestamp_begin;\n\n if (\"stride\" in output) {\n const [chunk_len, stride_left, stride_right] = output.stride;\n\n // Offset the timings to account for the other `model_outputs`.\n time_offset -= stride_left;\n right_stride_start = chunk_len - stride_right;\n\n // Keeping track of timestamps within strides\n // We're going to NOT split on those, and delay until we're\n // out of BOTH stride. Otherwise lots of issues occur and\n // corner cases\n if (stride_left) {\n first_timestamp = stride_left / time_precision + timestamp_begin;\n }\n\n if (stride_right) {\n for (let i = token_ids.length - 1; i >= 0; --i) {\n const token = Number(token_ids[i]);\n if (token >= timestamp_begin) {\n // There can be several token in the right stride\n // But the last one is ALWAYS going to be skipped\n if (last_timestamp !== null && (token - timestamp_begin) * time_precision < right_stride_start) {\n break;\n }\n last_timestamp = token;\n }\n }\n }\n }\n\n let current_tokens = [];\n let current_token_timestamps = [];\n\n // - all tokens within output\n for (let i = 0; i < token_ids.length; ++i) {\n const token = Number(token_ids[i]);\n // 4 possible states for each token\n // - 1/ Language code\n // - 2/ all other special tokens (which we ignore)\n // - 3/ Timestamp\n // - 4/ Regular text\n\n if (all_special_ids.has(token)) {\n const text = this.decode([token]);\n const language = WHISPER_LANGUAGE_MAPPING.get(text.slice(2, -2));\n\n if (language !== undefined) {\n // 1/ Indeed some language\n // TODO Handle when language is different from the previous\n // one, and we cannot use timestamped tokens to create chunks\n if (last_language !== null && language !== last_language && !return_timestamps) {\n previous_tokens.push(current_tokens);\n const resolved_tokens = this.findLongestCommonSequence(previous_tokens)[0];\n const resolved_text = this.decode(resolved_tokens);\n chunk.text = resolved_text;\n chunks.push(chunk);\n\n // Flush all our temporary context\n previous_tokens = [];\n current_tokens = [];\n chunk = new_chunk();\n }\n\n last_language = chunk.language = language;\n } else {\n // 2/ This is a regular special token, ignoring it\n }\n } else if (token >= timestamp_begin) {\n // 3/ Timestamp token\n const time = (token - timestamp_begin) * time_precision + time_offset;\n const rounded_time = round(time, 2);\n\n if (last_timestamp !== null && token >= last_timestamp) {\n // Whisper outputted a timestamp token, but it falls within\n // our stride, so we're going to skip it for the time being\n // and resolve this later\n // Skip is necessary because timestamp tokens always come\n // by pair, so we need to skip the next one too (which would mark the start of another chunk).\n skip = true;\n } else if (skip || (previous_tokens.length > 0 && token < first_timestamp)) {\n skip = false;\n } else if (chunk.timestamp[0] === null) {\n chunk.timestamp[0] = rounded_time;\n } else {\n // This is the end of the timestamp chunk\n if (rounded_time === chunk.timestamp[0]) {\n // This is a bug in timestamp token output\n // where we're taking the duplicate token\n // as a stop where it should be a start.\n // This is an issue in the underlying model output\n // Let's just skip it so it becomes de-factor a start agin\n } else {\n chunk.timestamp[1] = rounded_time;\n\n // Handling merges\n previous_tokens.push(current_tokens)\n\n if (returnWordTimestamps) {\n previous_token_timestamps.push(current_token_timestamps);\n }\n const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(\n previous_tokens, previous_token_timestamps\n )\n\n const resolved_text = this.decode(resolved_tokens)\n chunk.text = resolved_text\n\n if (returnWordTimestamps) {\n chunk.words = this.collateWordTimestamps(\n resolved_tokens, resolved_token_timestamps, last_language,\n )\n }\n\n chunks.push(chunk)\n\n // Flush all our temporary context\n previous_tokens = []\n current_tokens = []\n previous_token_timestamps = []\n current_token_timestamps = []\n chunk = new_chunk()\n }\n }\n\n } else {\n // 4/ Regular token\n // We just append to the list of all tokens so we can handle\n // merges later and decode into text.\n current_tokens.push(token)\n\n if (returnWordTimestamps) {\n let start_time = round(token_timestamps[i] + time_offset, 2);\n\n let end_time;\n if (i + 1 < token_timestamps.length) {\n end_time = round(token_timestamps[i + 1] + time_offset, 2);\n\n // Do not allow punctuation-only tokens to have a duration.\n // This prevents long pauses from messing up the timestamps.\n const decoded_text = this.decode([token]);\n if (PUNCTUATION_ONLY_REGEX.test(decoded_text)) {\n // Add `time_precision` to avoid overlapping timestamps\n end_time = round(Math.min(start_time + time_precision, end_time), 2);\n }\n } else {\n // should never happen\n end_time = null;\n }\n current_token_timestamps.push([start_time, end_time]);\n }\n\n }\n }\n\n if ('stride' in output) {\n const [chunk_len, stride_left, stride_right] = output.stride;\n time_offset += chunk_len - stride_right\n }\n\n // Leftover tokens\n if (current_tokens.length > 0) {\n previous_tokens.push(current_tokens)\n if (returnWordTimestamps) {\n previous_token_timestamps.push(current_token_timestamps);\n }\n } else if (previous_tokens.every(p => p.length === 0)) {\n // Flushing previous tokens (END)\"\n chunk = new_chunk()\n previous_tokens = []\n current_tokens = []\n previous_token_timestamps = [];\n current_token_timestamps = [];\n }\n\n }\n\n if (previous_tokens.length > 0) {\n if (force_full_sequences && return_timestamps) {\n // Last token should always be timestamps, so there shouldn't be\n // leftover\n throw new Error(\n \"Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. \" +\n \"Also make sure WhisperTimeStampLogitsProcessor was used during generation.\"\n );\n }\n\n // Happens when we don't use timestamps\n const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(previous_tokens, previous_token_timestamps);\n\n // Flushing previous tokens (FINAL)\n const resolved_text = this.decode(resolved_tokens);\n chunk.text = resolved_text;\n if (returnWordTimestamps) {\n chunk.words = this.collateWordTimestamps(\n resolved_tokens, resolved_token_timestamps, last_language,\n )\n }\n chunks.push(chunk);\n }\n\n let optional = Object.create(null);\n\n // Preparing and cleaning up the pipeline output\n const full_text = chunks.map(chunk => chunk.text).join('');\n if (return_timestamps || return_language) {\n for (let i = 0; i < chunks.length; ++i) {\n const chunk = chunks[i];\n if (!return_timestamps) {\n delete chunk[\"timestamp\"];\n }\n\n if (!return_language) {\n delete chunk[\"language\"];\n }\n }\n if (returnWordTimestamps) {\n const new_chunks = [];\n for (const chunk of chunks) {\n for (const word of chunk.words) {\n new_chunks.push(word);\n }\n }\n optional = { \"chunks\": new_chunks };\n } else {\n optional = { \"chunks\": chunks };\n }\n }\n return [full_text, optional];\n\n }\n\n /**\n * Finds the longest common sequence among the provided sequences.\n * @param {number[][]} sequences An array of sequences of token ids to compare.\n * @returns {number[][]} The longest common sequence found.\n * @throws {Error} If there is a bug within the function.\n * @private\n */\n findLongestCommonSequence(sequences, token_timestamp_sequences = null) {\n // It would be much harder to do O(n) because of fault tolerance.\n // We actually have a really good property which is that the total sequence\n // MUST be those subsequences in order.\n // If token_timestamp_sequences is provided, will split those sequences in\n // exactly the same way.\n let leftSequence = sequences[0];\n let leftLength = leftSequence.length;\n let totalSequence = [];\n\n const use_token_timestamp_sequences = Array.isArray(token_timestamp_sequences) && token_timestamp_sequences.length > 0;\n let total_token_timestamp_sequence = use_token_timestamp_sequences ? [] : null;\n let left_token_timestamp_sequence = use_token_timestamp_sequences ? token_timestamp_sequences[0] : null;\n for (let i = 1; i < sequences.length; ++i) {\n const rightSequence = sequences[i];\n let max = 0.0;\n let maxIndices = [leftLength, leftLength, 0, 0];\n // Here we're sliding matches\n // [a, b, c, d]\n // [c, d, f]\n // = [c] == [d]\n\n // [a, b, c, d]\n // [c, d, f]\n // = [c, d] == [c, d]\n\n\n // [a, b, c, d]\n // [c, d, f]\n\n // = [b, c, d] == [c, d, f]\n\n // [a, b, c, d]\n // [c, d, f]\n\n // [a, b, c] == [c, d, f]\n\n // [a, b, c, d]\n // [d, f]\n\n // [a, b] == [d, f]\n\n // [a, b, c, d]\n // [f]\n\n // [a] == [f]\n\n const rightLength = rightSequence.length;\n for (let j = 1; j < leftLength + rightLength; ++j) {\n // Slightly convoluted because we don't want out of bound indices\n // This will be necessary for a small conflict resolution optimization\n // later\n const leftStart = Math.max(0, leftLength - j);\n const leftStop = Math.min(leftLength, leftLength + rightLength - j);\n const left = leftSequence.slice(leftStart, leftStop);\n const rightStart = Math.max(0, j - leftLength);\n const rightStop = Math.min(rightLength, j);\n const right = rightSequence.slice(rightStart, rightStop);\n if (left.length !== right.length) {\n throw new Error(\"There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.\");\n }\n\n let matches;\n if (use_token_timestamp_sequences) {\n // Get length of longest subsequence of tokens that match\n // and have timestamps that are in order\n matches = left.filter((elem, idx) => (\n elem === right[idx]\n && left_token_timestamp_sequence[leftStart + idx] <= token_timestamp_sequences[i][rightStart + idx]\n )).length;\n } else {\n matches = left.filter((elem, idx) => elem === right[idx]).length;\n }\n\n // epsilon to favor long perfect matches\n const eps = j / 10000.0;\n const matching = matches / j + eps;\n if (matches > 1 && matching > max) {\n max = matching;\n maxIndices = [leftStart, leftStop, rightStart, rightStop];\n }\n }\n const [leftStart, leftStop, rightStart, rightStop] = maxIndices;\n const leftMid = Math.floor((leftStop + leftStart) / 2);\n const rightMid = Math.floor((rightStop + rightStart) / 2);\n totalSequence.push(...leftSequence.slice(0, leftMid));\n leftSequence = rightSequence.slice(rightMid);\n leftLength = leftSequence.length;\n\n if (use_token_timestamp_sequences) {\n total_token_timestamp_sequence.push(...left_token_timestamp_sequence.slice(0, leftMid));\n left_token_timestamp_sequence = token_timestamp_sequences[i].slice(rightMid);\n }\n }\n totalSequence.push(...leftSequence);\n\n if (use_token_timestamp_sequences) {\n total_token_timestamp_sequence.push(...left_token_timestamp_sequence);\n return [totalSequence, total_token_timestamp_sequence];\n } else {\n return [totalSequence, []];\n }\n }\n\n /** @private */\n collateWordTimestamps(tokens, token_timestamps, language) {\n\n const [words, _, token_indices] = this.combineTokensIntoWords(tokens, language);\n\n const timings = [];\n for (let i = 0; i < words.length; ++i) {\n const indices = token_indices[i];\n timings.push({\n text: words[i],\n timestamp: [\n token_timestamps[indices.at(0)][0],\n token_timestamps[indices.at(-1)][1],\n ],\n });\n }\n return timings;\n }\n\n /**\n * Groups tokens by word. Returns a tuple containing a list of strings with the words,\n * and a list of `token_id` sequences with the tokens making up each word.\n * @param {number[]} tokens \n * @param {string} [language] \n * @param {string} prepend_punctionations \n * @param {string} append_punctuations \n * \n * @private\n */\n combineTokensIntoWords(tokens, language, prepend_punctionations = \"\\\"'“¡¿([{-\", append_punctuations = \"\\\"'.。,,!!??::”)]}、\") {\n language = language ?? 'english';\n\n let words, word_tokens, token_indices;\n\n if ([\"chinese\", \"japanese\", \"thai\", \"lao\", \"myanmar\"].includes(language)) {\n // These languages don't typically use spaces.\n [words, word_tokens, token_indices] = this.splitTokensOnUnicode(tokens)\n } else {\n [words, word_tokens, token_indices] = this.splitTokensOnSpaces(tokens)\n }\n\n return this.mergePunctuations(words, word_tokens, token_indices, prepend_punctionations, append_punctuations);\n }\n\n /** @type {PreTrainedTokenizer['decode']} */\n decode(\n token_ids,\n decode_args,\n ) {\n let text;\n // @ts-ignore\n if (decode_args?.decode_with_timestamps) {\n if (token_ids instanceof Tensor) {\n token_ids = prepareTensorForDecode(token_ids);\n }\n text = this.decodeWithTimestamps(token_ids, decode_args);\n } else {\n text = super.decode(token_ids, decode_args);\n }\n // TODO: implement offsets\n // if (decode_args.output_offsets) {\n // let offsets = this.computeOffsets\n // }\n return text;\n }\n\n /**\n * @param {number[]|bigint[]} token_ids List of token IDs to decode.\n * @param {Object} decode_args Optional arguments for decoding\n * @private\n */\n decodeWithTimestamps(token_ids, decode_args) {\n const time_precision = decode_args?.time_precision ?? 0.02;\n\n const timestamp_begin = Array.from(this.all_special_ids).at(-1) + 1;\n /**@type {Array} */\n let outputs = [[]];\n for (let token of token_ids) {\n token = Number(token);\n if (token >= timestamp_begin) {\n const timestamp = ((token - timestamp_begin) * time_precision).toFixed(2);\n outputs.push(`<|${timestamp}|>`);\n outputs.push([]);\n } else {\n outputs[outputs.length - 1].push(token);\n }\n }\n outputs = outputs.map(\n s => typeof s === 'string' ? s : super.decode(s, decode_args)\n )\n\n return outputs.join('');\n }\n\n /**\n * Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points.\n * @param {number[]} tokens \n * @returns {*}\n * @private\n */\n splitTokensOnUnicode(tokens) {\n const decoded_full = this.decode(tokens, {\n // @ts-ignore\n decode_with_timestamps: true,\n });\n const replacement_char = '\\uFFFD';\n\n const words = []\n const word_tokens = []\n const token_indices = []\n let current_tokens = []\n let current_indices = []\n let unicode_offset = 0\n\n for (let token_idx = 0; token_idx < tokens.length; ++token_idx) {\n const token = tokens[token_idx];\n\n current_tokens.push(token);\n current_indices.push(token_idx);\n\n const decoded = this.decode(current_tokens, {\n // @ts-ignore\n decode_with_timestamps: true,\n });\n\n if (!decoded.includes(replacement_char) || decoded_full[unicode_offset + decoded.indexOf(replacement_char)] === replacement_char) {\n words.push(decoded)\n word_tokens.push(current_tokens)\n token_indices.push(current_indices)\n current_tokens = []\n current_indices = []\n unicode_offset += decoded.length;\n }\n\n }\n\n return [words, word_tokens, token_indices]\n }\n\n /**\n * Combine tokens into words by splitting at whitespace and punctuation tokens.\n * @param {number[]} tokens \n * @private\n */\n splitTokensOnSpaces(tokens) {\n\n const [subwords, subword_tokens_list, subword_indices_list] = this.splitTokensOnUnicode(tokens);\n\n const words = []\n const word_tokens = []\n const token_indices = []\n\n const punctuationRegex = new RegExp(`^[${PUNCTUATION_REGEX}]$`, 'gu');\n\n for (let i = 0; i < subwords.length; ++i) {\n\n const subword = subwords[i];\n const subword_tokens = subword_tokens_list[i];\n const subword_indices = subword_indices_list[i];\n\n // @ts-ignore\n const special = subword_tokens[0] >= this.model.tokens_to_ids.get('<|endoftext|>');\n const with_space = subword.startsWith(' ');\n const trimmed = subword.trim();\n const punctuation = punctuationRegex.test(trimmed);\n\n if (special || with_space || punctuation || words.length === 0) {\n words.push(subword);\n word_tokens.push(subword_tokens);\n token_indices.push(subword_indices);\n } else {\n const ix = words.length - 1;\n words[ix] += subword;\n word_tokens[ix].push(...subword_tokens);\n token_indices[ix].push(...subword_indices);\n }\n }\n\n return [words, word_tokens, token_indices];\n\n }\n\n /**\n * Merges punctuation tokens with neighboring words.\n * @param {string[]} words \n * @param {number[][]} tokens \n * @param {number[][]} indices \n * @param {string} prepended \n * @param {string} appended \n * @private\n */\n mergePunctuations(words, tokens, indices, prepended, appended) {\n\n const newWords = structuredClone(words);\n const newTokens = structuredClone(tokens);\n const newIndices = structuredClone(indices);\n\n\n // prepend punctuations\n let i = newWords.length - 2;\n let j = newWords.length - 1;\n\n while (i >= 0) {\n if (newWords[i].startsWith(' ') && prepended.includes(newWords[i].trim())) {\n newWords[j] = newWords[i] + newWords[j];\n newTokens[j] = mergeArrays(newTokens[i], newTokens[j]);\n newIndices[j] = mergeArrays(newIndices[i], newIndices[j]);\n newWords[i] = '';\n newTokens[i] = [];\n newIndices[i] = [];\n } else {\n j = i;\n }\n --i;\n }\n\n // append punctuations\n i = 0;\n j = 1;\n while (j < newWords.length) {\n if (!newWords[i].endsWith(' ') && appended.includes(newWords[j])) {\n newWords[i] += newWords[j];\n newTokens[i] = mergeArrays(newTokens[i], newTokens[j]);\n newIndices[i] = mergeArrays(newIndices[i], newIndices[j]);\n newWords[j] = '';\n newTokens[j] = [];\n newIndices[j] = [];\n } else {\n i = j;\n }\n ++j;\n }\n\n return [\n newWords.filter(x => x),\n newTokens.filter(x => x.length > 0),\n newIndices.filter(x => x.length > 0),\n ]\n }\n}\nexport class CodeGenTokenizer extends PreTrainedTokenizer { }\nexport class CLIPTokenizer extends PreTrainedTokenizer { }\nexport class SiglipTokenizer extends PreTrainedTokenizer { }\n\n/**\n * @todo This model is not yet supported by Hugging Face's \"fast\" tokenizers library (https://github.com/huggingface/tokenizers).\n * Therefore, this implementation (which is based on fast tokenizers) may produce slightly inaccurate results.\n */\nexport class MarianTokenizer extends PreTrainedTokenizer {\n /**\n * Create a new MarianTokenizer instance.\n * @param {Object} tokenizerJSON The JSON of the tokenizer.\n * @param {Object} tokenizerConfig The config of the tokenizer.\n */\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.languageRegex = /^(>>\\w+<<)\\s*/g;\n\n this.supported_language_codes = this.model.vocab.filter(\n x => this.languageRegex.test(x)\n );\n\n console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\\'s \"fast\" tokenizers library. Therefore, you may experience slightly inaccurate results.')\n }\n\n /**\n * Encodes a single text. Overriding this method is necessary since the language codes\n * must be removed before encoding with sentencepiece model.\n * @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213\n *\n * @param {string|null} text The text to encode.\n * @returns {Array} The encoded tokens.\n */\n _encode_text(text) {\n if (text === null) return null;\n\n // Check if text starts with language code:\n const [matchInfo, ...remainder] = text.trim().split(this.languageRegex);\n\n if (remainder.length === 0) {\n // No language code, encode normally\n return super._encode_text(matchInfo);\n\n } else if (remainder.length === 2) {\n // Text starts with language code, so we do not encode it with sentencepiece.\n const [language, text] = remainder;\n\n if (!this.supported_language_codes.includes(language)) {\n console.warn(`Unsupported language code \"${language}\" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`)\n }\n return mergeArrays([language], super._encode_text(text));\n }\n }\n\n}\n\nexport class Wav2Vec2CTCTokenizer extends PreTrainedTokenizer { }\n\nexport class BlenderbotTokenizer extends PreTrainedTokenizer { }\nexport class BlenderbotSmallTokenizer extends PreTrainedTokenizer { }\n\nexport class SpeechT5Tokenizer extends PreTrainedTokenizer { }\n\nexport class NougatTokenizer extends PreTrainedTokenizer { }\n\nexport class VitsTokenizer extends PreTrainedTokenizer {\n\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n // Custom decoder function\n this.decoder = new VitsDecoder({});\n }\n}\n\nexport class CohereTokenizer extends PreTrainedTokenizer { }\n\n/**\n * Helper class which is used to instantiate pretrained tokenizers with the `from_pretrained` function.\n * The chosen tokenizer class is determined by the type specified in the tokenizer config.\n * \n * @example\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');\n */\nexport class AutoTokenizer {\n static TOKENIZER_CLASS_MAPPING = {\n T5Tokenizer,\n DistilBertTokenizer,\n CamembertTokenizer,\n DebertaTokenizer,\n DebertaV2Tokenizer,\n BertTokenizer,\n HerbertTokenizer,\n ConvBertTokenizer,\n RoFormerTokenizer,\n XLMTokenizer,\n ElectraTokenizer,\n MobileBertTokenizer,\n SqueezeBertTokenizer,\n AlbertTokenizer,\n GPT2Tokenizer,\n BartTokenizer,\n MBartTokenizer,\n MBart50Tokenizer,\n RobertaTokenizer,\n WhisperTokenizer,\n CodeGenTokenizer,\n CLIPTokenizer,\n SiglipTokenizer,\n MarianTokenizer,\n BloomTokenizer,\n NllbTokenizer,\n M2M100Tokenizer,\n LlamaTokenizer,\n CodeLlamaTokenizer,\n XLMRobertaTokenizer,\n MPNetTokenizer,\n FalconTokenizer,\n GPTNeoXTokenizer,\n EsmTokenizer,\n Wav2Vec2CTCTokenizer,\n BlenderbotTokenizer,\n BlenderbotSmallTokenizer,\n SpeechT5Tokenizer,\n NougatTokenizer,\n VitsTokenizer,\n Qwen2Tokenizer,\n GemmaTokenizer,\n Grok1Tokenizer,\n CohereTokenizer,\n\n // Base case:\n PreTrainedTokenizer,\n }\n\n\n /**\n * Instantiate one of the tokenizer classes of the library from a pretrained model.\n * \n * The tokenizer class to instantiate is selected based on the `tokenizer_class` property of the config object\n * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)\n * \n * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:\n * - A string, the *model id* of a pretrained tokenizer hosted inside a model repo on huggingface.co.\n * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a\n * user or organization name, like `dbmdz/bert-base-german-cased`.\n * - A path to a *directory* containing tokenizer files, e.g., `./my_model_directory/`.\n * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.\n * \n * @returns {Promise} A new instance of the PreTrainedTokenizer class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n legacy = null,\n } = {}) {\n\n const [tokenizerJSON, tokenizerConfig] = await loadTokenizer(pretrained_model_name_or_path, {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n legacy,\n })\n\n // Some tokenizers are saved with the \"Fast\" suffix, so we remove that if present.\n const tokenizerName = tokenizerConfig.tokenizer_class?.replace(/Fast$/, '') ?? 'PreTrainedTokenizer';\n\n let cls = this.TOKENIZER_CLASS_MAPPING[tokenizerName];\n if (!cls) {\n console.warn(`Unknown tokenizer class \"${tokenizerName}\", attempting to construct from base class.`);\n cls = PreTrainedTokenizer;\n }\n return new cls(tokenizerJSON, tokenizerConfig);\n }\n}\n","/**\n * @file Helper module for audio processing. \n * \n * These functions and classes are only used internally, \n * meaning an end-user shouldn't need to access anything here.\n * \n * @module utils/audio\n */\n\nimport {\n getFile,\n} from './hub.js';\nimport { FFT, max } from './maths.js';\nimport {\n calculateReflectOffset,\n} from './core.js';\nimport { Tensor, matmul } from './tensor.js';\n\n\n/**\n * Helper function to read audio from a path/URL.\n * @param {string|URL} url The path/URL to load the audio from.\n * @param {number} sampling_rate The sampling rate to use when decoding the audio.\n * @returns {Promise} The decoded audio as a `Float32Array`.\n */\nexport async function read_audio(url, sampling_rate) {\n if (typeof AudioContext === 'undefined') {\n // Running in node or an environment without AudioContext\n throw Error(\n \"Unable to load audio from path/URL since `AudioContext` is not available in your environment. \" +\n \"Instead, audio data should be passed directly to the pipeline/processor. \" +\n \"For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.\"\n )\n }\n\n const response = await (await getFile(url)).arrayBuffer();\n const audioCTX = new AudioContext({ sampleRate: sampling_rate });\n if (typeof sampling_rate === 'undefined') {\n console.warn(`No sampling rate provided, using default of ${audioCTX.sampleRate}Hz.`)\n }\n const decoded = await audioCTX.decodeAudioData(response);\n\n /** @type {Float32Array} */\n let audio;\n\n // We now replicate HuggingFace's `ffmpeg_read` method:\n if (decoded.numberOfChannels === 2) {\n // When downmixing a stereo audio file to mono using the -ac 1 option in FFmpeg,\n // the audio signal is summed across both channels to create a single mono channel.\n // However, if the audio is at full scale (i.e. the highest possible volume level),\n // the summing of the two channels can cause the audio signal to clip or distort.\n\n // To prevent this clipping, FFmpeg applies a scaling factor of 1/sqrt(2) (~ 0.707)\n // to the audio signal before summing the two channels. This scaling factor ensures\n // that the combined audio signal will not exceed the maximum possible level, even\n // if both channels are at full scale.\n\n // After applying this scaling factor, the audio signal from both channels is summed\n // to create a single mono channel. It's worth noting that this scaling factor is\n // only applied when downmixing stereo audio to mono using the -ac 1 option in FFmpeg.\n // If you're using a different downmixing method, or if you're not downmixing the\n // audio at all, this scaling factor may not be needed.\n const SCALING_FACTOR = Math.sqrt(2);\n\n const left = decoded.getChannelData(0);\n const right = decoded.getChannelData(1);\n\n audio = new Float32Array(left.length);\n for (let i = 0; i < decoded.length; ++i) {\n audio[i] = SCALING_FACTOR * (left[i] + right[i]) / 2;\n }\n\n } else {\n // If the audio is not stereo, we can just use the first channel:\n audio = decoded.getChannelData(0);\n }\n\n return audio;\n}\n\n/**\n * Helper function to generate windows that are special cases of the generalized cosine window.\n * See https://www.mathworks.com/help/signal/ug/generalized-cosine-windows.html for more information.\n * @param {number} M Number of points in the output window. If zero or less, an empty array is returned.\n * @param {number} a_0 Offset for the generalized cosine window.\n * @returns {Float64Array} The generated window.\n */\nfunction generalized_cosine_window(M, a_0) {\n if (M < 1) {\n return new Float64Array();\n }\n if (M === 1) {\n return new Float64Array([1]);\n }\n\n const a_1 = 1 - a_0;\n const factor = 2 * Math.PI / (M - 1);\n\n const cos_vals = new Float64Array(M);\n for (let i = 0; i < M; ++i) {\n cos_vals[i] = a_0 - a_1 * Math.cos(i * factor);\n }\n return cos_vals;\n}\n\n/**\n * Generates a Hanning window of length M.\n * See https://numpy.org/doc/stable/reference/generated/numpy.hanning.html for more information.\n *\n * @param {number} M The length of the Hanning window to generate.\n * @returns {Float64Array} The generated Hanning window.\n */\nexport function hanning(M) {\n return generalized_cosine_window(M, 0.5);\n}\n\n\n/**\n * Generates a Hamming window of length M.\n * See https://numpy.org/doc/stable/reference/generated/numpy.hamming.html for more information.\n *\n * @param {number} M The length of the Hamming window to generate.\n * @returns {Float64Array} The generated Hamming window.\n */\nexport function hamming(M) {\n return generalized_cosine_window(M, 0.54);\n}\n\n\nconst HERTZ_TO_MEL_MAPPING = {\n \"htk\": (/** @type {number} */ freq) => 2595.0 * Math.log10(1.0 + (freq / 700.0)),\n \"kaldi\": (/** @type {number} */ freq) => 1127.0 * Math.log(1.0 + (freq / 700.0)),\n \"slaney\": (/** @type {number} */ freq, min_log_hertz = 1000.0, min_log_mel = 15.0, logstep = 27.0 / Math.log(6.4)) =>\n freq >= min_log_hertz\n ? min_log_mel + Math.log(freq / min_log_hertz) * logstep\n : 3.0 * freq / 200.0,\n}\n\n/**\n * @template {Float32Array|Float64Array|number} T \n * @param {T} freq \n * @param {string} [mel_scale]\n * @returns {T}\n */\nfunction hertz_to_mel(freq, mel_scale = \"htk\") {\n const fn = HERTZ_TO_MEL_MAPPING[mel_scale];\n if (!fn) {\n throw new Error('mel_scale should be one of \"htk\", \"slaney\" or \"kaldi\".');\n }\n\n return typeof freq === 'number' ? fn(freq) : freq.map(x => fn(x));\n}\n\nconst MEL_TO_HERTZ_MAPPING = {\n \"htk\": (/** @type {number} */ mels) => 700.0 * (10.0 ** (mels / 2595.0) - 1.0),\n \"kaldi\": (/** @type {number} */ mels) => 700.0 * (Math.exp(mels / 1127.0) - 1.0),\n \"slaney\": (/** @type {number} */ mels, min_log_hertz = 1000.0, min_log_mel = 15.0, logstep = Math.log(6.4) / 27.0) => mels >= min_log_mel\n ? min_log_hertz * Math.exp(logstep * (mels - min_log_mel))\n : 200.0 * mels / 3.0,\n}\n\n/**\n * @template {Float32Array|Float64Array|number} T \n * @param {T} mels \n * @param {string} [mel_scale]\n * @returns {T}\n */\nfunction mel_to_hertz(mels, mel_scale = \"htk\") {\n const fn = MEL_TO_HERTZ_MAPPING[mel_scale];\n if (!fn) {\n throw new Error('mel_scale should be one of \"htk\", \"slaney\" or \"kaldi\".');\n }\n\n return typeof mels === 'number' ? fn(mels) : mels.map(x => fn(x));\n}\n\n/**\n* Creates a triangular filter bank.\n*\n* Adapted from torchaudio and librosa.\n*\n* @param {Float64Array} fft_freqs Discrete frequencies of the FFT bins in Hz, of shape `(num_frequency_bins,)`.\n* @param {Float64Array} filter_freqs Center frequencies of the triangular filters to create, in Hz, of shape `(num_mel_filters,)`.\n* @returns {number[][]} of shape `(num_frequency_bins, num_mel_filters)`.\n*/\nfunction _create_triangular_filter_bank(fft_freqs, filter_freqs) {\n const filter_diff = Float64Array.from(\n { length: filter_freqs.length - 1 },\n (_, i) => filter_freqs[i + 1] - filter_freqs[i]\n );\n\n const slopes = Array.from({\n length: fft_freqs.length\n }, () => new Array(filter_freqs.length));\n\n for (let j = 0; j < fft_freqs.length; ++j) {\n const slope = slopes[j];\n for (let i = 0; i < filter_freqs.length; ++i) {\n slope[i] = filter_freqs[i] - fft_freqs[j];\n }\n }\n\n const numFreqs = filter_freqs.length - 2;\n const ret = Array.from({ length: numFreqs }, () => new Array(fft_freqs.length));\n\n for (let j = 0; j < fft_freqs.length; ++j) { // 201\n const slope = slopes[j];\n for (let i = 0; i < numFreqs; ++i) { // 80\n const down = -slope[i] / filter_diff[i];\n const up = slope[i + 2] / filter_diff[i + 1];\n ret[i][j] = Math.max(0, Math.min(down, up));\n }\n }\n return ret;\n}\n\n/**\n * Return evenly spaced numbers over a specified interval.\n * @param {number} start The starting value of the sequence.\n * @param {number} end The end value of the sequence.\n * @param {number} num Number of samples to generate.\n * @returns `num` evenly spaced samples, calculated over the interval `[start, stop]`.\n */\nfunction linspace(start, end, num) {\n const step = (end - start) / (num - 1);\n return Float64Array.from({ length: num }, (_, i) => start + step * i);\n}\n\n/**\n * Creates a frequency bin conversion matrix used to obtain a mel spectrogram. This is called a *mel filter bank*, and\n * various implementation exist, which differ in the number of filters, the shape of the filters, the way the filters\n * are spaced, the bandwidth of the filters, and the manner in which the spectrum is warped. The goal of these\n * features is to approximate the non-linear human perception of the variation in pitch with respect to the frequency.\n * @param {number} num_frequency_bins Number of frequencies used to compute the spectrogram (should be the same as in `stft`).\n * @param {number} num_mel_filters Number of mel filters to generate.\n * @param {number} min_frequency Lowest frequency of interest in Hz.\n * @param {number} max_frequency Highest frequency of interest in Hz. This should not exceed `sampling_rate / 2`.\n * @param {number} sampling_rate Sample rate of the audio waveform.\n * @param {string} [norm] If `\"slaney\"`, divide the triangular mel weights by the width of the mel band (area normalization).\n * @param {string} [mel_scale] The mel frequency scale to use, `\"htk\"` or `\"slaney\"`.\n * @param {boolean} [triangularize_in_mel_space] If this option is enabled, the triangular filter is applied in mel space rather than frequency space.\n * This should be set to `true` in order to get the same results as `torchaudio` when computing mel filters.\n * @returns {number[][]} Triangular filter bank matrix, which is a 2D array of shape (`num_frequency_bins`, `num_mel_filters`).\n * This is a projection matrix to go from a spectrogram to a mel spectrogram.\n */\nexport function mel_filter_bank(\n num_frequency_bins,\n num_mel_filters,\n min_frequency,\n max_frequency,\n sampling_rate,\n norm = null,\n mel_scale = \"htk\",\n triangularize_in_mel_space = false,\n) {\n if (norm !== null && norm !== \"slaney\") {\n throw new Error('norm must be one of null or \"slaney\"');\n }\n\n const mel_min = hertz_to_mel(min_frequency, mel_scale);\n const mel_max = hertz_to_mel(max_frequency, mel_scale);\n const mel_freqs = linspace(mel_min, mel_max, num_mel_filters + 2);\n\n let filter_freqs = mel_to_hertz(mel_freqs, mel_scale);\n let fft_freqs; // frequencies of FFT bins in Hz\n\n if (triangularize_in_mel_space) {\n const fft_bin_width = sampling_rate / (num_frequency_bins * 2);\n fft_freqs = hertz_to_mel(Float64Array.from({ length: num_frequency_bins }, (_, i) => i * fft_bin_width), mel_scale);\n filter_freqs = mel_freqs;\n } else {\n fft_freqs = linspace(0, Math.floor(sampling_rate / 2), num_frequency_bins);\n }\n\n const mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs);\n\n if (norm !== null && norm === \"slaney\") {\n // Slaney-style mel is scaled to be approx constant energy per channel\n for (let i = 0; i < num_mel_filters; ++i) {\n const filter = mel_filters[i];\n const enorm = 2.0 / (filter_freqs[i + 2] - filter_freqs[i]);\n for (let j = 0; j < num_frequency_bins; ++j) {\n // Apply this enorm to all frequency bins\n filter[j] *= enorm;\n }\n }\n }\n\n // TODO warn if there is a zero row\n\n return mel_filters;\n\n}\n\n/**\n * @template {Float32Array|Float64Array} T\n * Pads an array with a reflected version of itself on both ends.\n * @param {T} array The array to pad.\n * @param {number} left The amount of padding to add to the left.\n * @param {number} right The amount of padding to add to the right.\n * @returns {T} The padded array.\n */\nfunction padReflect(array, left, right) {\n // @ts-ignore\n const padded = new array.constructor(array.length + left + right);\n const w = array.length - 1;\n\n for (let i = 0; i < array.length; ++i) {\n padded[left + i] = array[i];\n }\n\n for (let i = 1; i <= left; ++i) {\n padded[left - i] = array[calculateReflectOffset(i, w)];\n }\n\n for (let i = 1; i <= right; ++i) {\n padded[w + left + i] = array[calculateReflectOffset(w - i, w)];\n }\n\n return padded;\n}\n\n/**\n * Helper function to compute `amplitude_to_db` and `power_to_db`.\n * @template {Float32Array|Float64Array} T\n * @param {T} spectrogram \n * @param {number} factor \n * @param {number} reference \n * @param {number} min_value \n * @param {number} db_range \n * @returns {T}\n */\nfunction _db_conversion_helper(spectrogram, factor, reference, min_value, db_range) {\n if (reference <= 0) {\n throw new Error('reference must be greater than zero');\n }\n\n if (min_value <= 0) {\n throw new Error('min_value must be greater than zero');\n }\n\n reference = Math.max(min_value, reference);\n\n const logReference = Math.log10(reference);\n for (let i = 0; i < spectrogram.length; ++i) {\n spectrogram[i] = factor * Math.log10(Math.max(min_value, spectrogram[i]) - logReference)\n }\n\n if (db_range !== null) {\n if (db_range <= 0) {\n throw new Error('db_range must be greater than zero');\n }\n const maxValue = max(spectrogram)[0] - db_range;\n for (let i = 0; i < spectrogram.length; ++i) {\n spectrogram[i] = Math.max(spectrogram[i], maxValue);\n }\n }\n\n return spectrogram;\n}\n\n/**\n * Converts an amplitude spectrogram to the decibel scale. This computes `20 * log10(spectrogram / reference)`,\n * using basic logarithm properties for numerical stability. NOTE: Operates in-place.\n * \n * The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a\n * linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.\n * This means that large variations in energy may not sound all that different if the sound is loud to begin with.\n * This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.\n * \n * @template {Float32Array|Float64Array} T\n * @param {T} spectrogram The input amplitude (mel) spectrogram.\n * @param {number} [reference=1.0] Sets the input spectrogram value that corresponds to 0 dB.\n * For example, use `np.max(spectrogram)` to set the loudest part to 0 dB. Must be greater than zero.\n * @param {number} [min_value=1e-5] The spectrogram will be clipped to this minimum value before conversion to decibels,\n * to avoid taking `log(0)`. The default of `1e-5` corresponds to a minimum of -100 dB. Must be greater than zero.\n * @param {number} [db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the\n * difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero.\n * @returns {T} The modified spectrogram in decibels.\n */\nfunction amplitude_to_db(spectrogram, reference = 1.0, min_value = 1e-5, db_range = null) {\n return _db_conversion_helper(spectrogram, 20.0, reference, min_value, db_range);\n}\n\n/**\n * Converts a power spectrogram to the decibel scale. This computes `10 * log10(spectrogram / reference)`,\n * using basic logarithm properties for numerical stability. NOTE: Operates in-place.\n * \n * The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a\n * linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.\n * This means that large variations in energy may not sound all that different if the sound is loud to begin with.\n * This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.\n * \n * Based on the implementation of `librosa.power_to_db`.\n * \n * @template {Float32Array|Float64Array} T\n * @param {T} spectrogram The input power (mel) spectrogram. Note that a power spectrogram has the amplitudes squared!\n * @param {number} [reference=1.0] Sets the input spectrogram value that corresponds to 0 dB.\n * For example, use `np.max(spectrogram)` to set the loudest part to 0 dB. Must be greater than zero.\n * @param {number} [min_value=1e-10] The spectrogram will be clipped to this minimum value before conversion to decibels,\n * to avoid taking `log(0)`. The default of `1e-10` corresponds to a minimum of -100 dB. Must be greater than zero.\n * @param {number} [db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the\n * difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero.\n * @returns {T} The modified spectrogram in decibels.\n */\nfunction power_to_db(spectrogram, reference = 1.0, min_value = 1e-10, db_range = null) {\n return _db_conversion_helper(spectrogram, 10.0, reference, min_value, db_range);\n}\n\n/**\n * Calculates a spectrogram over one waveform using the Short-Time Fourier Transform.\n * \n * This function can create the following kinds of spectrograms:\n * - amplitude spectrogram (`power = 1.0`)\n * - power spectrogram (`power = 2.0`)\n * - complex-valued spectrogram (`power = None`)\n * - log spectrogram (use `log_mel` argument)\n * - mel spectrogram (provide `mel_filters`)\n * - log-mel spectrogram (provide `mel_filters` and `log_mel`)\n *\n * In this implementation, the window is assumed to be zero-padded to have the same size as the analysis frame.\n * A padded window can be obtained from `window_function()`. The FFT input buffer may be larger than the analysis frame, \n * typically the next power of two.\n * \n * @param {Float32Array|Float64Array} waveform The input waveform of shape `(length,)`. This must be a single real-valued, mono waveform.\n * @param {Float32Array|Float64Array} window The windowing function to apply of shape `(frame_length,)`, including zero-padding if necessary. The actual window length may be\n * shorter than `frame_length`, but we're assuming the array has already been zero-padded.\n * @param {number} frame_length The length of the analysis frames in samples (a.k.a., `fft_length`).\n * @param {number} hop_length The stride between successive analysis frames in samples.\n * @param {Object} options\n * @param {number} [options.fft_length=null] The size of the FFT buffer in samples. This determines how many frequency bins the spectrogram will have.\n * For optimal speed, this should be a power of two. If `null`, uses `frame_length`.\n * @param {number} [options.power=1.0] If 1.0, returns the amplitude spectrogram. If 2.0, returns the power spectrogram. If `null`, returns complex numbers.\n * @param {boolean} [options.center=true] Whether to pad the waveform so that frame `t` is centered around time `t * hop_length`. If `false`, frame\n * `t` will start at time `t * hop_length`.\n * @param {string} [options.pad_mode=\"reflect\"] Padding mode used when `center` is `true`. Possible values are: `\"constant\"` (pad with zeros),\n * `\"edge\"` (pad with edge values), `\"reflect\"` (pads with mirrored values).\n * @param {boolean} [options.onesided=true] If `true`, only computes the positive frequencies and returns a spectrogram containing `fft_length // 2 + 1`\n * frequency bins. If `false`, also computes the negative frequencies and returns `fft_length` frequency bins.\n * @param {number} [options.preemphasis=null] Coefficient for a low-pass filter that applies pre-emphasis before the DFT.\n * @param {number[][]} [options.mel_filters=null] The mel filter bank of shape `(num_freq_bins, num_mel_filters)`.\n * If supplied, applies this filter bank to create a mel spectrogram.\n * @param {number} [options.mel_floor=1e-10] Minimum value of mel frequency banks.\n * @param {string} [options.log_mel=null] How to convert the spectrogram to log scale. Possible options are:\n * `null` (don't convert), `\"log\"` (take the natural logarithm) `\"log10\"` (take the base-10 logarithm), `\"dB\"` (convert to decibels).\n * Can only be used when `power` is not `null`.\n * @param {number} [options.reference=1.0] Sets the input spectrogram value that corresponds to 0 dB. For example, use `max(spectrogram)[0]` to set\n * the loudest part to 0 dB. Must be greater than zero.\n * @param {number} [options.min_value=1e-10] The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking `log(0)`.\n * For a power spectrogram, the default of `1e-10` corresponds to a minimum of -100 dB. For an amplitude spectrogram, the value `1e-5` corresponds to -100 dB.\n * Must be greater than zero.\n * @param {number} [options.db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the\n * peak value and the smallest value will never be more than 80 dB. Must be greater than zero.\n * @param {boolean} [options.remove_dc_offset=null] Subtract mean from waveform on each frame, applied before pre-emphasis. This should be set to `true` in\n * order to get the same results as `torchaudio.compliance.kaldi.fbank` when computing mel filters.\n * @param {number} [options.max_num_frames=null] If provided, limits the number of frames to compute to this value.\n * @param {number} [options.min_num_frames=null] If provided, ensures the number of frames to compute is at least this value.\n * @param {boolean} [options.do_pad=true] If `true`, pads the output spectrogram to have `max_num_frames` frames.\n * @param {boolean} [options.transpose=false] If `true`, the returned spectrogram will have shape `(num_frames, num_frequency_bins/num_mel_filters)`. If `false`, the returned spectrogram will have shape `(num_frequency_bins/num_mel_filters, num_frames)`.\n * @returns {Promise} Spectrogram of shape `(num_frequency_bins, length)` (regular spectrogram) or shape `(num_mel_filters, length)` (mel spectrogram).\n */\nexport async function spectrogram(\n waveform,\n window,\n frame_length,\n hop_length,\n {\n fft_length = null,\n power = 1.0,\n center = true,\n pad_mode = \"reflect\",\n onesided = true,\n preemphasis = null,\n mel_filters = null,\n mel_floor = 1e-10,\n log_mel = null,\n reference = 1.0,\n min_value = 1e-10,\n db_range = null,\n remove_dc_offset = null,\n\n // Custom parameters for efficiency reasons\n min_num_frames = null,\n max_num_frames = null,\n do_pad = true,\n transpose = false,\n } = {}\n) {\n const window_length = window.length;\n if (fft_length === null) {\n fft_length = frame_length;\n }\n if (frame_length > fft_length) {\n throw Error(`frame_length (${frame_length}) may not be larger than fft_length (${fft_length})`)\n }\n\n if (window_length !== frame_length) {\n throw new Error(`Length of the window (${window_length}) must equal frame_length (${frame_length})`);\n }\n\n if (hop_length <= 0) {\n throw new Error(\"hop_length must be greater than zero\");\n }\n\n if (power === null && mel_filters !== null) {\n throw new Error(\n \"You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. \" +\n \"Specify `power` to fix this issue.\"\n );\n }\n\n if (center) {\n if (pad_mode !== 'reflect') {\n throw new Error(`pad_mode=\"${pad_mode}\" not implemented yet.`)\n }\n const half_window = Math.floor((fft_length - 1) / 2) + 1;\n waveform = padReflect(waveform, half_window, half_window);\n }\n\n // split waveform into frames of frame_length size\n let num_frames = Math.floor(1 + Math.floor((waveform.length - frame_length) / hop_length))\n if (min_num_frames !== null && num_frames < min_num_frames) {\n num_frames = min_num_frames\n }\n const num_frequency_bins = onesided ? Math.floor(fft_length / 2) + 1 : fft_length\n\n let d1 = num_frames;\n let d1Max = num_frames;\n\n // If maximum number of frames is provided, we must either pad or truncate\n if (max_num_frames !== null) {\n if (max_num_frames > num_frames) { // input is too short, so we pad\n if (do_pad) {\n d1Max = max_num_frames;\n }\n } else { // input is too long, so we truncate\n d1Max = d1 = max_num_frames;\n }\n }\n\n // Preallocate arrays to store output.\n const fft = new FFT(fft_length);\n const inputBuffer = new Float64Array(fft_length);\n const outputBuffer = new Float64Array(fft.outputBufferSize);\n const transposedMagnitudeData = new Float32Array(num_frequency_bins * d1Max);\n\n for (let i = 0; i < d1; ++i) {\n // Populate buffer with waveform data\n const offset = i * hop_length;\n const buffer_size = Math.min(waveform.length - offset, frame_length);\n if (buffer_size !== frame_length) {\n // The full buffer is not needed, so we need to reset it (avoid overflow from previous iterations)\n // NOTE: We don't need to reset the buffer if it's full since we overwrite the first\n // `frame_length` values and the rest (`fft_length - frame_length`) remains zero.\n inputBuffer.fill(0, 0, frame_length);\n }\n\n for (let j = 0; j < buffer_size; ++j) {\n inputBuffer[j] = waveform[offset + j];\n }\n\n if (remove_dc_offset) {\n let sum = 0;\n for (let j = 0; j < buffer_size; ++j) {\n sum += inputBuffer[j];\n }\n const mean = sum / buffer_size;\n for (let j = 0; j < buffer_size; ++j) {\n inputBuffer[j] -= mean;\n }\n }\n\n if (preemphasis !== null) {\n // Done in reverse to avoid copies and distructive modification\n for (let j = buffer_size - 1; j >= 1; --j) {\n inputBuffer[j] -= preemphasis * inputBuffer[j - 1];\n }\n inputBuffer[0] *= 1 - preemphasis;\n }\n\n // Apply window function\n for (let j = 0; j < window.length; ++j) {\n inputBuffer[j] *= window[j];\n }\n\n fft.realTransform(outputBuffer, inputBuffer);\n\n // compute magnitudes\n for (let j = 0; j < num_frequency_bins; ++j) {\n const j2 = j << 1;\n\n // NOTE: We transpose the data here to avoid doing it later\n transposedMagnitudeData[j * d1Max + i] = outputBuffer[j2] ** 2 + outputBuffer[j2 + 1] ** 2;\n }\n }\n\n if (power !== null && power !== 2) {\n // slight optimization to not sqrt\n const pow = 2 / power; // we use 2 since we already squared\n for (let i = 0; i < transposedMagnitudeData.length; ++i) {\n transposedMagnitudeData[i] **= pow;\n }\n }\n\n // TODO: What if `mel_filters` is null?\n const num_mel_filters = mel_filters.length;\n\n // Perform matrix muliplication:\n // mel_spec = mel_filters @ magnitudes.T\n // - mel_filters.shape=(80, 201)\n // - magnitudes.shape=(3000, 201) => magnitudes.T.shape=(201, 3000)\n // - mel_spec.shape=(80, 3000)\n let mel_spec = await matmul(\n // TODO: Make `mel_filters` a Tensor during initialization\n new Tensor('float32', mel_filters.flat(), [num_mel_filters, num_frequency_bins]),\n new Tensor('float32', transposedMagnitudeData, [num_frequency_bins, d1Max]),\n );\n if (transpose) {\n mel_spec = mel_spec.transpose(1, 0);\n }\n\n const mel_spec_data = /** @type {Float32Array} */(mel_spec.data);\n for (let i = 0; i < mel_spec_data.length; ++i) {\n mel_spec_data[i] = Math.max(mel_floor, mel_spec_data[i]);\n }\n\n if (power !== null && log_mel !== null) {\n const o = Math.min(mel_spec_data.length, d1 * num_mel_filters);\n // NOTE: operates in-place\n switch (log_mel) {\n case 'log':\n for (let i = 0; i < o; ++i) {\n mel_spec_data[i] = Math.log(mel_spec_data[i]);\n }\n break;\n case 'log10':\n for (let i = 0; i < o; ++i) {\n mel_spec_data[i] = Math.log10(mel_spec_data[i]);\n }\n break;\n case 'dB':\n if (power === 1.0) {\n amplitude_to_db(mel_spec_data, reference, min_value, db_range);\n } else if (power === 2.0) {\n power_to_db(mel_spec_data, reference, min_value, db_range);\n } else {\n throw new Error(`Cannot use log_mel option '${log_mel}' with power ${power}`)\n }\n break;\n default:\n throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${log_mel}'`);\n }\n }\n\n return mel_spec;\n}\n\n/**\n * Returns an array containing the specified window.\n * @param {number} window_length The length of the window in samples.\n * @param {string} name The name of the window function.\n * @param {Object} options Additional options.\n * @param {boolean} [options.periodic=true] Whether the window is periodic or symmetric.\n * @param {number} [options.frame_length=null] The length of the analysis frames in samples.\n * Provide a value for `frame_length` if the window is smaller than the frame length, so that it will be zero-padded.\n * @param {boolean} [options.center=true] Whether to center the window inside the FFT buffer. Only used when `frame_length` is provided.\n * @returns {Float64Array} The window of shape `(window_length,)` or `(frame_length,)`.\n */\nexport function window_function(window_length, name, {\n periodic = true,\n frame_length = null,\n center = true,\n} = {}) {\n const length = periodic ? window_length + 1 : window_length;\n let window;\n switch (name) {\n case 'boxcar':\n window = new Float64Array(length).fill(1.0);\n break;\n case 'hann':\n case 'hann_window':\n window = hanning(length);\n break;\n case 'hamming':\n window = hamming(length);\n break;\n case 'povey':\n window = hanning(length).map(x => Math.pow(x, 0.85));\n break;\n default:\n throw new Error(`Unknown window type ${name}.`);\n }\n if (periodic) {\n window = window.subarray(0, window_length);\n }\n if (frame_length === null) {\n return window;\n }\n if (window_length > frame_length) {\n throw new Error(`Length of the window (${window_length}) may not be larger than frame_length (${frame_length})`);\n }\n\n return window;\n}\n","\nexport const GITHUB_ISSUE_URL = 'https://github.com/huggingface/transformers.js/issues/new/choose';","\n/**\n * @file Core utility functions/classes for Transformers.js.\n * \n * These are only used internally, meaning an end-user shouldn't\n * need to access anything here.\n * \n * @module utils/core\n */\n\n/**\n * Helper function to dispatch progress callbacks.\n *\n * @param {Function} progress_callback The progress callback function to dispatch.\n * @param {any} data The data to pass to the progress callback function.\n * @returns {void}\n * @private\n */\nexport function dispatchCallback(progress_callback, data) {\n if (progress_callback) progress_callback(data);\n}\n\n/**\n * Reverses the keys and values of an object.\n *\n * @param {Object} data The object to reverse.\n * @returns {Object} The reversed object.\n * @see https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript\n */\nexport function reverseDictionary(data) {\n // https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript\n return Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key]));\n}\n\n/**\n * Escapes regular expression special characters from a string by replacing them with their escaped counterparts.\n *\n * @param {string} string The string to escape.\n * @returns {string} The escaped string.\n */\nexport function escapeRegExp(string) {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); // $& means the whole matched string\n}\n\n/**\n * Check if a value is a typed array.\n * @param {*} val The value to check.\n * @returns {boolean} True if the value is a `TypedArray`, false otherwise.\n * \n * Adapted from https://stackoverflow.com/a/71091338/13989043\n */\nexport function isTypedArray(val) {\n return val?.prototype?.__proto__?.constructor?.name === 'TypedArray';\n}\n\n\n/**\n * Check if a value is an integer.\n * @param {*} x The value to check.\n * @returns {boolean} True if the value is a string, false otherwise.\n */\nexport function isIntegralNumber(x) {\n return Number.isInteger(x) || typeof x === 'bigint'\n}\n\n/**\n * Calculates the dimensions of a nested array.\n *\n * @param {any[]} arr The nested array to calculate dimensions for.\n * @returns {number[]} An array containing the dimensions of the input array.\n */\nexport function calculateDimensions(arr) {\n const dimensions = [];\n let current = arr;\n while (Array.isArray(current)) {\n dimensions.push(current.length);\n current = current[0];\n }\n return dimensions;\n}\n\n/**\n * Replicate python's .pop() method for objects.\n * @param {Object} obj The object to pop from.\n * @param {string} key The key to pop.\n * @param {*} defaultValue The default value to return if the key does not exist.\n * @returns {*} The value of the popped key.\n * @throws {Error} If the key does not exist and no default value is provided.\n */\nexport function pop(obj, key, defaultValue = undefined) {\n const value = obj[key];\n if (value !== undefined) {\n delete obj[key];\n return value;\n }\n if (defaultValue === undefined) {\n throw Error(`Key ${key} does not exist in object.`)\n }\n return defaultValue;\n}\n\n/**\n * Efficiently merge arrays, creating a new copy.\n * Adapted from https://stackoverflow.com/a/6768642/13989043\n * @param {Array[]} arrs Arrays to merge.\n * @returns {Array} The merged array.\n */\nexport function mergeArrays(...arrs) {\n return Array.prototype.concat.apply([], arrs);\n}\n\n/**\n * Compute the Cartesian product of given arrays\n * @param {...Array} a Arrays to compute the product\n * @returns {Array} Returns the computed Cartesian product as an array\n * @private\n */\nexport function product(...a) {\n // Cartesian product of items\n // Adapted from https://stackoverflow.com/a/43053803\n return a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e])));\n}\n\n/**\n * Calculates the index offset for a given index and window size.\n * @param {number} i The index.\n * @param {number} w The window size.\n * @returns {number} The index offset.\n */\nexport function calculateReflectOffset(i, w) {\n return Math.abs((i + w) % (2 * w) - w);\n}\n\n/**\n * \n * @param {Object} o \n * @param {string[]} props \n * @returns {Object}\n */\nexport function pick(o, props) {\n return Object.assign(\n {},\n ...props.map((prop) => {\n if (o[prop] !== undefined) {\n return { [prop]: o[prop] };\n }\n })\n );\n}\n\n/**\n * Calculate the length of a string, taking multi-byte characters into account.\n * This mimics the behavior of Python's `len` function.\n * @param {string} s The string to calculate the length of. \n * @returns {number} The length of the string.\n */\nexport function len(s) {\n let length = 0;\n for (const c of s) ++length;\n return length;\n}\n","\n/**\n * @file Custom data structures.\n * \n * These are only used internally, meaning an end-user shouldn't\n * need to access anything here.\n * \n * @module utils/data-structures\n */\n\n\n/**\n * Efficient Heap-based Implementation of a Priority Queue.\n * It uses an array-based binary heap, where the root is at index `0`, and the\n * children of node `i` are located at indices `2i + 1` and `2i + 2`, respectively.\n * \n * Adapted from the following sources:\n * - https://stackoverflow.com/a/42919752/13989043 (original)\n * - https://github.com/belladoreai/llama-tokenizer-js (minor improvements)\n */\nexport class PriorityQueue {\n\n /**\n * Create a new PriorityQueue.\n * @param {function(any, any): boolean} comparator Comparator function to determine priority. Defaults to a MaxHeap.\n */\n constructor(comparator = (a, b) => a > b, maxSize = Infinity) {\n this._heap = [];\n this._comparator = comparator;\n this._maxSize = maxSize;\n }\n\n /**\n * The size of the queue\n */\n get size() {\n return this._heap.length;\n }\n\n /**\n * Check if the queue is empty.\n * @returns {boolean} `true` if the queue is empty, `false` otherwise.\n */\n isEmpty() {\n return this.size === 0;\n }\n\n /**\n * Return the element with the highest priority in the queue.\n * @returns {any} The highest priority element in the queue.\n */\n peek() {\n return this._heap[0];\n }\n\n /**\n * Add one or more elements to the queue.\n * @param {...any} values The values to push into the queue.\n * @returns {number} The new size of the queue.\n */\n push(...values) {\n return this.extend(values);\n }\n\n /**\n * Add multiple elements to the queue.\n * @param {any[]} values The values to push into the queue.\n * @returns {number} The new size of the queue.\n */\n extend(values) {\n for (const value of values) {\n if (this.size < this._maxSize) {\n this._heap.push(value);\n this._siftUp();\n } else {\n // Get index of value with the lowest priority\n const smallest = this._smallest();\n\n // If the new value has higher priority than the smallest value in the heap\n // then replace the smallest value with the new value and update the heap\n if (this._comparator(value, this._heap[smallest])) {\n this._heap[smallest] = value;\n this._siftUpFrom(smallest);\n }\n }\n }\n return this.size;\n }\n\n /**\n * Remove and return the element with the highest priority in the queue.\n * @returns {any} The element with the highest priority in the queue.\n */\n pop() {\n const poppedValue = this.peek();\n const bottom = this.size - 1;\n if (bottom > 0) {\n this._swap(0, bottom);\n }\n this._heap.pop();\n this._siftDown();\n return poppedValue;\n }\n\n /**\n * Replace the element with the highest priority in the queue with a new value.\n * @param {*} value The new value.\n * @returns {*} The replaced value.\n */\n replace(value) {\n const replacedValue = this.peek();\n this._heap[0] = value;\n this._siftDown();\n return replacedValue;\n }\n\n /**\n * Compute the index for the parent of the node at index `i`.\n * @param {number} i The index of the node to get the parent of.\n * @returns {number} The index of the parent node.\n * @private\n */\n _parent(i) {\n return ((i + 1) >>> 1) - 1;\n }\n\n /**\n * Compute the index for the left child of the node at index `i`.\n * @param {number} i The index of the node to get the left child of.\n * @returns {number} The index of the left child.\n * @private\n */\n _left(i) {\n return (i << 1) + 1;\n }\n\n /**\n * Compute the index for the right child of the node at index `i`.\n * @param {number} i The index of the node to get the right child of.\n * @returns {number} The index of the right child.\n * @private\n */\n _right(i) {\n return (i + 1) << 1;\n }\n\n /**\n * Check if the element at index `i` is greater than the element at index `j`.\n * @param {number} i The index of the first element to compare.\n * @param {number} j The index of the second element to compare.\n * @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.\n * @private\n */\n _greater(i, j) {\n return this._comparator(this._heap[i], this._heap[j]);\n }\n\n /**\n * Swap the elements at indices `i` and `j`.\n * @param {number} i The index of the first element to swap.\n * @param {number} j The index of the second element to swap.\n * @private\n */\n _swap(i, j) {\n const temp = this._heap[i];\n this._heap[i] = this._heap[j];\n this._heap[j] = temp;\n }\n\n /**\n * Maintain the heap property by updating positions in the heap,\n * starting at the last element and moving up the heap.\n * @private\n */\n _siftUp() {\n this._siftUpFrom(this.size - 1);\n }\n\n /**\n * Helper function to sift up from a given node.\n * @param {number} node The index of the node to start sifting up from.\n */\n _siftUpFrom(node) {\n while (node > 0 && this._greater(node, this._parent(node))) {\n this._swap(node, this._parent(node));\n node = this._parent(node);\n }\n }\n\n /**\n * Maintain the heap property by updating positions in the heap,\n * starting at the first element and moving down the heap.\n * @private\n */\n _siftDown() {\n let node = 0;\n while (\n (this._left(node) < this.size && this._greater(this._left(node), node)) ||\n (this._right(node) < this.size && this._greater(this._right(node), node))\n ) {\n const maxChild = (this._right(node) < this.size && this._greater(this._right(node), this._left(node)))\n ? this._right(node)\n : this._left(node);\n this._swap(node, maxChild);\n node = maxChild;\n }\n }\n\n /**\n * Get the index of the smallest element in the heap. Since we use an array-based heap,\n * the index can be computed without needing to traverse the heap.\n * @private\n */\n _smallest() {\n return (2 ** (Math.floor(Math.log2(this.size))) - 1);\n }\n}\n\n/**\n * A trie structure to efficiently store and search for strings.\n */\nexport class CharTrie {\n constructor() {\n this.root = CharTrieNode.default();\n }\n\n /**\n * Adds one or more `texts` to the trie.\n * @param {string[]} texts The strings to add to the trie.\n */\n extend(texts) {\n for (const text of texts) {\n this.push(text);\n }\n }\n\n /**\n * Adds text to the trie.\n * @param {string} text The string to add to the trie.\n */\n push(text) {\n let node = this.root;\n for (const ch of text) {\n let child = node.children.get(ch);\n if (child === undefined) {\n child = CharTrieNode.default();\n node.children.set(ch, child);\n }\n node = child;\n }\n node.isLeaf = true;\n }\n\n /**\n * Searches the trie for all strings with a common prefix of `text`.\n * @param {string} text The common prefix to search for.\n * @yields {string} Each string in the trie that has `text` as a prefix.\n */\n *commonPrefixSearch(text) {\n let node = this.root;\n if (node === undefined) return;\n\n let prefix = \"\";\n for (const ch of text) {\n prefix += ch;\n node = node.children.get(ch);\n if (node === undefined) return;\n if (node.isLeaf) {\n yield prefix;\n }\n }\n }\n}\n\n/**\n * Represents a node in a character trie.\n */\nclass CharTrieNode {\n /**\n * Create a new CharTrieNode.\n * @param {boolean} isLeaf Whether the node is a leaf node or not.\n * @param {Map} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.\n */\n constructor(isLeaf, children) {\n this.isLeaf = isLeaf;\n this.children = children;\n }\n\n /**\n * Returns a new `CharTrieNode` instance with default values.\n * @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map.\n */\n static default() {\n return new CharTrieNode(false, new Map());\n }\n}\n\n/**\n * A lattice data structure to be used for tokenization.\n */\nexport class TokenLattice {\n /**\n * Creates a new TokenLattice instance.\n *\n * @param {string} sentence The input sentence to be tokenized.\n * @param {number} bosTokenId The beginning-of-sequence token ID.\n * @param {number} eosTokenId The end-of-sequence token ID.\n */\n constructor(sentence, bosTokenId, eosTokenId) {\n this.chars = Array.from(sentence);\n this.len = this.chars.length;\n this.bosTokenId = bosTokenId;\n this.eosTokenId = eosTokenId;\n this.nodes = [];\n this.beginNodes = Array.from({ length: this.len + 1 }, () => []);\n this.endNodes = Array.from({ length: this.len + 1 }, () => []);\n\n const bos = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0.0);\n const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0.0);\n this.nodes.push(bos.clone());\n this.nodes.push(eos.clone());\n this.beginNodes[this.len].push(eos);\n this.endNodes[0].push(bos);\n }\n\n /**\n * Inserts a new token node into the token lattice.\n *\n * @param {number} pos The starting position of the token.\n * @param {number} length The length of the token.\n * @param {number} score The score of the token.\n * @param {number} tokenId The token ID of the token.\n */\n insert(pos, length, score, tokenId) {\n const nodeId = this.nodes.length;\n const node = new TokenLatticeNode(tokenId, nodeId, pos, length, score);\n this.beginNodes[pos].push(node);\n this.endNodes[pos + length].push(node);\n this.nodes.push(node);\n }\n\n /**\n * Implements the Viterbi algorithm to compute the most likely sequence of tokens.\n *\n * @returns {TokenLatticeNode[]} The most likely sequence of tokens.\n */\n viterbi() {\n const len = this.len;\n let pos = 0;\n while (pos <= len) {\n if (this.beginNodes[pos].length == 0) {\n return [];\n }\n for (let rnode of this.beginNodes[pos]) {\n rnode.prev = null;\n let bestScore = 0.0;\n let bestNode = null;\n for (let lnode of this.endNodes[pos]) {\n const score = lnode.backtraceScore + rnode.score;\n if (bestNode === null || score > bestScore) {\n bestNode = lnode.clone();\n bestScore = score;\n }\n }\n\n if (bestNode !== null) {\n rnode.prev = bestNode;\n rnode.backtraceScore = bestScore;\n } else {\n return [];\n }\n }\n ++pos;\n }\n\n const results = [];\n const root = this.beginNodes[len][0];\n const prev = root.prev;\n if (prev === null) {\n return [];\n }\n\n let node = prev.clone();\n while (node.prev !== null) {\n results.push(node.clone());\n const n = node.clone();\n node = n.prev.clone();\n }\n\n results.reverse();\n return results;\n }\n\n /**\n * @param {TokenLatticeNode} node\n * @returns {string} The array of nodes representing the most likely sequence of tokens.\n */\n piece(node) {\n return this.chars.slice(node.pos, node.pos + node.length).join('');\n }\n\n /**\n * @returns {string[]} The most likely sequence of tokens.\n */\n tokens() {\n const nodes = this.viterbi();\n return nodes.map(x => this.piece(x));\n }\n\n /**\n * @returns {number[]} The most likely sequence of token ids.\n */\n tokenIds() {\n const nodes = this.viterbi();\n return nodes.map(x => x.tokenId);\n }\n}\nclass TokenLatticeNode {\n /**\n * Represents a node in a token lattice for a given sentence.\n * @param {number} tokenId The ID of the token associated with this node.\n * @param {number} nodeId The ID of this node.\n * @param {number} pos The starting position of the token in the sentence.\n * @param {number} length The length of the token.\n * @param {number} score The score associated with the token.\n */\n constructor(tokenId, nodeId, pos, length, score) {\n this.tokenId = tokenId;\n this.nodeId = nodeId;\n this.pos = pos;\n this.length = length;\n this.score = score;\n this.prev = null;\n this.backtraceScore = 0.0;\n }\n\n /**\n * Returns a clone of this node.\n * @returns {TokenLatticeNode} A clone of this node.\n */\n clone() {\n const n = new TokenLatticeNode(this.tokenId, this.nodeId, this.pos, this.length, this.score);\n n.prev = this.prev;\n n.backtraceScore = this.backtraceScore;\n return n;\n }\n}\n","\n/**\n * The list of devices supported by Transformers.js\n */\nexport const DEVICE_TYPES = Object.freeze({\n auto: 'auto', // Auto-detect based on device and environment\n gpu: 'gpu', // Auto-detect GPU\n cpu: 'cpu', // CPU\n wasm: 'wasm', // WebAssembly\n webgpu: 'webgpu', // WebGPU\n cuda: 'cuda', // CUDA\n dml: 'dml', // DirectML\n\n webnn: 'webnn', // WebNN (default)\n 'webnn-npu': 'webnn-npu', // WebNN NPU\n 'webnn-gpu': 'webnn-gpu', // WebNN GPU\n 'webnn-cpu': 'webnn-cpu', // WebNN CPU\n});\n\n/**\n * @typedef {keyof typeof DEVICE_TYPES} DeviceType\n */\n","import { apis } from \"../env.js\";\n\nimport { DEVICE_TYPES } from \"./devices.js\";\n\n// TODO: Use the adapter from `env.backends.onnx.webgpu.adapter` to check for `shader-f16` support,\n// when available in https://github.com/microsoft/onnxruntime/pull/19940.\n// For more information, see https://github.com/microsoft/onnxruntime/pull/19857#issuecomment-1999984753\n\n/**\n * Checks if WebGPU fp16 support is available in the current environment.\n */\nexport const isWebGpuFp16Supported = (function () {\n /** @type {boolean} */\n let cachedResult;\n\n return async function () {\n if (cachedResult === undefined) {\n if (!apis.IS_WEBGPU_AVAILABLE) {\n cachedResult = false;\n } else {\n try {\n const adapter = await navigator.gpu.requestAdapter();\n cachedResult = adapter.features.has('shader-f16');\n } catch (e) {\n cachedResult = false;\n }\n }\n }\n return cachedResult;\n };\n})();\n\nexport const DATA_TYPES = Object.freeze({\n fp32: 'fp32',\n fp16: 'fp16',\n q8: 'q8',\n int8: 'int8',\n uint8: 'uint8',\n q4: 'q4',\n bnb4: 'bnb4',\n q4f16: 'q4f16', // fp16 model with int4 block weight quantization\n});\n/** @typedef {keyof typeof DATA_TYPES} DataType */\n\nexport const DEFAULT_DEVICE_DTYPE_MAPPING = Object.freeze({\n // NOTE: If not specified, will default to fp32\n [DEVICE_TYPES.wasm]: DATA_TYPES.q8,\n});\n\n/** @type {Record} */\nexport const DEFAULT_DTYPE_SUFFIX_MAPPING = Object.freeze({\n [DATA_TYPES.fp32]: '',\n [DATA_TYPES.fp16]: '_fp16',\n [DATA_TYPES.int8]: '_int8',\n [DATA_TYPES.uint8]: '_uint8',\n [DATA_TYPES.q8]: '_quantized',\n [DATA_TYPES.q4]: '_q4',\n [DATA_TYPES.q4f16]: '_q4f16',\n [DATA_TYPES.bnb4]: '_bnb4',\n});\n","\n/**\n * A base class for creating callable objects.\n * See [here](https://stackoverflow.com/q/76073890) for more information.\n * \n * @type {new () => {(...args: any[]): any, _call(...args: any[]): any}}\n */\nexport const Callable = /** @type {any} */ (class {\n /**\n * Creates a new instance of the Callable class.\n */\n constructor() {\n /**\n * Creates a closure that delegates to a private method '_call' with the given arguments.\n * @type {any}\n * @param {...any} args Zero or more arguments to pass to the '_call' method.\n * @returns {*} The result of calling the '_call' method.\n */\n let closure = function (...args) {\n return closure._call(...args)\n }\n return Object.setPrototypeOf(closure, new.target.prototype)\n }\n\n /**\n * This method should be implemented in subclasses to provide the\n * functionality of the callable object.\n *\n * @param {any[]} args\n * @throws {Error} If the subclass does not implement the `_call` method.\n */\n _call(...args) {\n throw Error('Must implement _call method in subclass')\n }\n});\n","\n/**\n * @file Utility functions to interact with the Hugging Face Hub (https://huggingface.co/models)\n * \n * @module utils/hub\n */\n\nimport fs from 'fs';\nimport path from 'path';\n\nimport { env } from '../env.js';\nimport { dispatchCallback } from './core.js';\n\n/**\n * @typedef {Object} PretrainedOptions Options for loading a pretrained model. \n * @property {function} [progress_callback=null] If specified, this function will be called during model construction, to provide the user with progress updates.\n * @property {import('../configs.js').PretrainedConfig} [config=null] Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when:\n * - The model is a model provided by the library (loaded with the *model id* string of a pretrained model).\n * - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a configuration JSON file named *config.json* is found in the directory.\n * @property {string} [cache_dir=null] Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.\n * @property {boolean} [local_files_only=false] Whether or not to only look at local files (e.g., not try downloading the model).\n * @property {string} [revision='main'] The specific model version to use. It can be a branch name, a tag name, or a commit id,\n * since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git.\n * NOTE: This setting is ignored for local requests.\n */\n\n/**\n * @typedef {Object} ModelSpecificPretrainedOptions Options for loading a pretrained model.\n * @property {string} [subfolder='onnx'] In case the relevant files are located inside a subfolder of the model repo on huggingface.co,\n * you can specify the folder name here.\n * @property {string} [model_file_name=null] If specified, load the model with this name (excluding the .onnx suffix). Currently only valid for encoder- or decoder-only models.\n * @property {import(\"./devices.js\").DeviceType|Record} [device=null] The device to run the model on. If not specified, the device will be chosen from the environment settings.\n * @property {import(\"./dtypes.js\").DataType|Record} [dtype=null] The data type to use for the model. If not specified, the data type will be chosen from the environment settings.\n * @property {boolean|Record} [use_external_data_format=false] Whether to load the model using the external data format (used for models >= 2GB in size).\n * @property {import('onnxruntime-common').InferenceSession.SessionOptions} [session_options] (Optional) User-specified session options passed to the runtime. If not provided, suitable defaults will be chosen.\n */\n\n/**\n * @typedef {PretrainedOptions & ModelSpecificPretrainedOptions} PretrainedModelOptions Options for loading a pretrained model.\n */\n\n/**\n * Mapping from file extensions to MIME types.\n */\nconst CONTENT_TYPE_MAP = {\n 'txt': 'text/plain',\n 'html': 'text/html',\n 'css': 'text/css',\n 'js': 'text/javascript',\n 'json': 'application/json',\n 'png': 'image/png',\n 'jpg': 'image/jpeg',\n 'jpeg': 'image/jpeg',\n 'gif': 'image/gif',\n}\nclass FileResponse {\n\n /**\n * Creates a new `FileResponse` object.\n * @param {string|URL} filePath\n */\n constructor(filePath) {\n this.filePath = filePath;\n this.headers = new Headers();\n\n this.exists = fs.existsSync(filePath);\n if (this.exists) {\n this.status = 200;\n this.statusText = 'OK';\n\n let stats = fs.statSync(filePath);\n this.headers.set('content-length', stats.size.toString());\n\n this.updateContentType();\n\n let self = this;\n this.body = new ReadableStream({\n start(controller) {\n self.arrayBuffer().then(buffer => {\n controller.enqueue(new Uint8Array(buffer));\n controller.close();\n })\n }\n });\n } else {\n this.status = 404;\n this.statusText = 'Not Found';\n this.body = null;\n }\n }\n\n /**\n * Updates the 'content-type' header property of the response based on the extension of\n * the file specified by the filePath property of the current object.\n * @returns {void}\n */\n updateContentType() {\n // Set content-type header based on file extension\n const extension = this.filePath.toString().split('.').pop().toLowerCase();\n this.headers.set('content-type', CONTENT_TYPE_MAP[extension] ?? 'application/octet-stream');\n }\n\n /**\n * Clone the current FileResponse object.\n * @returns {FileResponse} A new FileResponse object with the same properties as the current object.\n */\n clone() {\n let response = new FileResponse(this.filePath);\n response.exists = this.exists;\n response.status = this.status;\n response.statusText = this.statusText;\n response.headers = new Headers(this.headers);\n return response;\n }\n\n /**\n * Reads the contents of the file specified by the filePath property and returns a Promise that\n * resolves with an ArrayBuffer containing the file's contents.\n * @returns {Promise} A Promise that resolves with an ArrayBuffer containing the file's contents.\n * @throws {Error} If the file cannot be read.\n */\n async arrayBuffer() {\n const data = await fs.promises.readFile(this.filePath);\n return data.buffer;\n }\n\n /**\n * Reads the contents of the file specified by the filePath property and returns a Promise that\n * resolves with a Blob containing the file's contents.\n * @returns {Promise} A Promise that resolves with a Blob containing the file's contents.\n * @throws {Error} If the file cannot be read.\n */\n async blob() {\n const data = await fs.promises.readFile(this.filePath);\n return new Blob([data], { type: this.headers.get('content-type') });\n }\n\n /**\n * Reads the contents of the file specified by the filePath property and returns a Promise that\n * resolves with a string containing the file's contents.\n * @returns {Promise} A Promise that resolves with a string containing the file's contents.\n * @throws {Error} If the file cannot be read.\n */\n async text() {\n const data = await fs.promises.readFile(this.filePath, 'utf8');\n return data;\n }\n\n /**\n * Reads the contents of the file specified by the filePath property and returns a Promise that\n * resolves with a parsed JavaScript object containing the file's contents.\n * \n * @returns {Promise} A Promise that resolves with a parsed JavaScript object containing the file's contents.\n * @throws {Error} If the file cannot be read.\n */\n async json() {\n return JSON.parse(await this.text());\n }\n}\n\n/**\n * Determines whether the given string is a valid URL.\n * @param {string|URL} string The string to test for validity as an URL.\n * @param {string[]} [protocols=null] A list of valid protocols. If specified, the protocol must be in this list.\n * @param {string[]} [validHosts=null] A list of valid hostnames. If specified, the URL's hostname must be in this list.\n * @returns {boolean} True if the string is a valid URL, false otherwise.\n */\nfunction isValidUrl(string, protocols = null, validHosts = null) {\n let url;\n try {\n url = new URL(string);\n } catch (_) {\n return false;\n }\n if (protocols && !protocols.includes(url.protocol)) {\n return false;\n }\n if (validHosts && !validHosts.includes(url.hostname)) {\n return false;\n }\n return true;\n}\n\n/**\n * Helper function to get a file, using either the Fetch API or FileSystem API.\n *\n * @param {URL|string} urlOrPath The URL/path of the file to get.\n * @returns {Promise} A promise that resolves to a FileResponse object (if the file is retrieved using the FileSystem API), or a Response object (if the file is retrieved using the Fetch API).\n */\nexport async function getFile(urlOrPath) {\n\n if (env.useFS && !isValidUrl(urlOrPath, ['http:', 'https:', 'blob:'])) {\n return new FileResponse(urlOrPath);\n\n } else if (typeof process !== 'undefined' && process?.release?.name === 'node') {\n const IS_CI = !!process.env?.TESTING_REMOTELY;\n const version = env.version;\n\n const headers = new Headers();\n headers.set('User-Agent', `transformers.js/${version}; is_ci/${IS_CI};`);\n\n // Check whether we are making a request to the Hugging Face Hub.\n const isHFURL = isValidUrl(urlOrPath, ['http:', 'https:'], ['huggingface.co', 'hf.co']);\n if (isHFURL) {\n // If an access token is present in the environment variables,\n // we add it to the request headers.\n // NOTE: We keep `HF_ACCESS_TOKEN` for backwards compatibility (as a fallback).\n const token = process.env?.HF_TOKEN ?? process.env?.HF_ACCESS_TOKEN;\n if (token) {\n headers.set('Authorization', `Bearer ${token}`);\n }\n }\n return fetch(urlOrPath, { headers });\n } else {\n // Running in a browser-environment, so we use default headers\n // NOTE: We do not allow passing authorization headers in the browser,\n // since this would require exposing the token to the client.\n return fetch(urlOrPath);\n }\n}\n\nconst ERROR_MAPPING = {\n // 4xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses)\n 400: 'Bad request error occurred while trying to load file',\n 401: 'Unauthorized access to file',\n 403: 'Forbidden access to file',\n 404: 'Could not locate file',\n 408: 'Request timeout error occurred while trying to load file',\n\n // 5xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses)\n 500: 'Internal server error error occurred while trying to load file',\n 502: 'Bad gateway error occurred while trying to load file',\n 503: 'Service unavailable error occurred while trying to load file',\n 504: 'Gateway timeout error occurred while trying to load file',\n}\n/**\n * Helper method to handle fatal errors that occur while trying to load a file from the Hugging Face Hub.\n * @param {number} status The HTTP status code of the error.\n * @param {string} remoteURL The URL of the file that could not be loaded.\n * @param {boolean} fatal Whether to raise an error if the file could not be loaded.\n * @returns {null} Returns `null` if `fatal = true`.\n * @throws {Error} If `fatal = false`.\n */\nfunction handleError(status, remoteURL, fatal) {\n if (!fatal) {\n // File was not loaded correctly, but it is optional.\n // TODO in future, cache the response?\n return null;\n }\n\n const message = ERROR_MAPPING[status] ?? `Error (${status}) occurred while trying to load file`;\n throw Error(`${message}: \"${remoteURL}\".`);\n}\n\nclass FileCache {\n /**\n * Instantiate a `FileCache` object.\n * @param {string} path \n */\n constructor(path) {\n this.path = path;\n }\n\n /**\n * Checks whether the given request is in the cache.\n * @param {string} request \n * @returns {Promise}\n */\n async match(request) {\n\n let filePath = path.join(this.path, request);\n let file = new FileResponse(filePath);\n\n if (file.exists) {\n return file;\n } else {\n return undefined;\n }\n }\n\n /**\n * Adds the given response to the cache.\n * @param {string} request \n * @param {Response|FileResponse} response \n * @returns {Promise}\n */\n async put(request, response) {\n const buffer = Buffer.from(await response.arrayBuffer());\n\n let outputPath = path.join(this.path, request);\n\n try {\n await fs.promises.mkdir(path.dirname(outputPath), { recursive: true });\n await fs.promises.writeFile(outputPath, buffer);\n\n } catch (err) {\n console.warn('An error occurred while writing the file to cache:', err)\n }\n }\n\n // TODO add the rest?\n // addAll(requests: RequestInfo[]): Promise;\n // delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise;\n // keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>;\n // match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise;\n // matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>;\n}\n\n/**\n * \n * @param {FileCache|Cache} cache The cache to search\n * @param {string[]} names The names of the item to search for\n * @returns {Promise} The item from the cache, or undefined if not found.\n */\nasync function tryCache(cache, ...names) {\n for (let name of names) {\n try {\n let result = await cache.match(name);\n if (result) return result;\n } catch (e) {\n continue;\n }\n }\n return undefined;\n}\n\n/**\n * \n * Retrieves a file from either a remote URL using the Fetch API or from the local file system using the FileSystem API.\n * If the filesystem is available and `env.useCache = true`, the file will be downloaded and cached.\n * \n * @param {string} path_or_repo_id This can be either:\n * - a string, the *model id* of a model repo on huggingface.co.\n * - a path to a *directory* potentially containing the file.\n * @param {string} filename The name of the file to locate in `path_or_repo`.\n * @param {boolean} [fatal=true] Whether to throw an error if the file is not found.\n * @param {PretrainedOptions} [options] An object containing optional parameters.\n * \n * @throws Will throw an error if the file is not found and `fatal` is true.\n * @returns {Promise} A Promise that resolves with the file content as a buffer.\n */\nexport async function getModelFile(path_or_repo_id, filename, fatal = true, options = {}) {\n\n if (!env.allowLocalModels) {\n // User has disabled local models, so we just make sure other settings are correct.\n\n if (options.local_files_only) {\n throw Error(\"Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).\")\n } else if (!env.allowRemoteModels) {\n throw Error(\"Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.\")\n }\n }\n\n // Initiate file retrieval\n dispatchCallback(options.progress_callback, {\n status: 'initiate',\n name: path_or_repo_id,\n file: filename\n })\n\n // First, check if the a caching backend is available\n // If no caching mechanism available, will download the file every time\n let cache;\n if (!cache && env.useBrowserCache) {\n if (typeof caches === 'undefined') {\n throw Error('Browser cache is not available in this environment.')\n }\n try {\n // In some cases, the browser cache may be visible, but not accessible due to security restrictions.\n // For example, when running an application in an iframe, if a user attempts to load the page in\n // incognito mode, the following error is thrown: `DOMException: Failed to execute 'open' on 'CacheStorage':\n // An attempt was made to break through the security policy of the user agent.`\n // So, instead of crashing, we just ignore the error and continue without using the cache.\n cache = await caches.open('transformers-cache');\n } catch (e) {\n console.warn('An error occurred while opening the browser cache:', e);\n }\n }\n\n if (!cache && env.useFSCache) {\n // TODO throw error if not available\n\n // If `cache_dir` is not specified, use the default cache directory\n cache = new FileCache(options.cache_dir ?? env.cacheDir);\n }\n\n if (!cache && env.useCustomCache) {\n // Allow the user to specify a custom cache system.\n if (!env.customCache) {\n throw Error('`env.useCustomCache=true`, but `env.customCache` is not defined.')\n }\n\n // Check that the required methods are defined:\n if (!env.customCache.match || !env.customCache.put) {\n throw new Error(\n \"`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. \" +\n \"For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache\"\n )\n }\n cache = env.customCache;\n }\n\n const revision = options.revision ?? 'main';\n\n let requestURL = pathJoin(path_or_repo_id, filename);\n let localPath = pathJoin(env.localModelPath, requestURL);\n\n let remoteURL = pathJoin(\n env.remoteHost,\n env.remotePathTemplate\n .replaceAll('{model}', path_or_repo_id)\n .replaceAll('{revision}', encodeURIComponent(revision)),\n filename\n );\n\n // Choose cache key for filesystem cache\n // When using the main revision (default), we use the request URL as the cache key.\n // If a specific revision is requested, we account for this in the cache key.\n let fsCacheKey = revision === 'main' ? requestURL : pathJoin(path_or_repo_id, revision, filename);\n\n /** @type {string} */\n let cacheKey;\n let proposedCacheKey = cache instanceof FileCache ? fsCacheKey : remoteURL;\n\n // Whether to cache the final response in the end.\n let toCacheResponse = false;\n\n /** @type {Response|FileResponse|undefined} */\n let response;\n\n if (cache) {\n // A caching system is available, so we try to get the file from it.\n // 1. We first try to get from cache using the local path. In some environments (like deno),\n // non-URL cache keys are not allowed. In these cases, `response` will be undefined.\n // 2. If no response is found, we try to get from cache using the remote URL or file system cache.\n response = await tryCache(cache, localPath, proposedCacheKey);\n }\n\n const cacheHit = response !== undefined;\n\n if (response === undefined) {\n // Caching not available, or file is not cached, so we perform the request\n\n if (env.allowLocalModels) {\n // Accessing local models is enabled, so we try to get the file locally.\n // If request is a valid HTTP URL, we skip the local file check. Otherwise, we try to get the file locally.\n const isURL = isValidUrl(requestURL, ['http:', 'https:']);\n if (!isURL) {\n try {\n response = await getFile(localPath);\n cacheKey = localPath; // Update the cache key to be the local path\n } catch (e) {\n // Something went wrong while trying to get the file locally.\n // NOTE: error handling is done in the next step (since `response` will be undefined)\n console.warn(`Unable to load from local path \"${localPath}\": \"${e}\"`);\n }\n } else if (options.local_files_only) {\n throw new Error(`\\`local_files_only=true\\`, but attempted to load a remote file from: ${requestURL}.`);\n } else if (!env.allowRemoteModels) {\n throw new Error(`\\`env.allowRemoteModels=false\\`, but attempted to load a remote file from: ${requestURL}.`);\n }\n }\n\n if (response === undefined || response.status === 404) {\n // File not found locally. This means either:\n // - The user has disabled local file access (`env.allowLocalModels=false`)\n // - the path is a valid HTTP url (`response === undefined`)\n // - the path is not a valid HTTP url and the file is not present on the file system or local server (`response.status === 404`)\n\n if (options.local_files_only || !env.allowRemoteModels) {\n // User requested local files only, but the file is not found locally.\n if (fatal) {\n throw Error(`\\`local_files_only=true\\` or \\`env.allowRemoteModels=false\\` and file was not found locally at \"${localPath}\".`);\n } else {\n // File not found, but this file is optional.\n // TODO in future, cache the response?\n return null;\n }\n }\n\n // File not found locally, so we try to download it from the remote server\n response = await getFile(remoteURL);\n\n if (response.status !== 200) {\n return handleError(response.status, remoteURL, fatal);\n }\n\n // Success! We use the proposed cache key from earlier\n cacheKey = proposedCacheKey;\n }\n\n // Only cache the response if:\n toCacheResponse =\n cache // 1. A caching system is available\n && typeof Response !== 'undefined' // 2. `Response` is defined (i.e., we are in a browser-like environment)\n && response instanceof Response // 3. result is a `Response` object (i.e., not a `FileResponse`)\n && response.status === 200 // 4. request was successful (status code 200)\n }\n\n // Start downloading\n dispatchCallback(options.progress_callback, {\n status: 'download',\n name: path_or_repo_id,\n file: filename\n })\n\n const progressInfo = {\n status: 'progress',\n name: path_or_repo_id,\n file: filename\n }\n\n /** @type {Uint8Array} */\n let buffer;\n\n if (!options.progress_callback) {\n // If no progress callback is specified, we can use the `.arrayBuffer()`\n // method to read the response.\n buffer = new Uint8Array(await response.arrayBuffer());\n\n } else if (\n cacheHit // The item is being read from the cache\n &&\n typeof navigator !== 'undefined' && /firefox/i.test(navigator.userAgent) // We are in Firefox\n ) {\n // Due to bug in Firefox, we cannot display progress when loading from cache.\n // Fortunately, since this should be instantaneous, this should not impact users too much.\n buffer = new Uint8Array(await response.arrayBuffer());\n\n // For completeness, we still fire the final progress callback\n dispatchCallback(options.progress_callback, {\n ...progressInfo,\n progress: 100,\n loaded: buffer.length,\n total: buffer.length,\n })\n } else {\n buffer = await readResponse(response, data => {\n dispatchCallback(options.progress_callback, {\n ...progressInfo,\n ...data,\n })\n })\n }\n\n if (\n // Only cache web responses\n // i.e., do not cache FileResponses (prevents duplication)\n toCacheResponse && cacheKey\n &&\n // Check again whether request is in cache. If not, we add the response to the cache\n (await cache.match(cacheKey) === undefined)\n ) {\n // NOTE: We use `new Response(buffer, ...)` instead of `response.clone()` to handle LFS files\n await cache.put(cacheKey, new Response(buffer, {\n headers: response.headers\n }))\n .catch(err => {\n // Do not crash if unable to add to cache (e.g., QuotaExceededError).\n // Rather, log a warning and proceed with execution.\n console.warn(`Unable to add response to browser cache: ${err}.`);\n });\n\n }\n\n dispatchCallback(options.progress_callback, {\n status: 'done',\n name: path_or_repo_id,\n file: filename\n });\n\n return buffer;\n}\n\n/**\n * Fetches a JSON file from a given path and file name.\n *\n * @param {string} modelPath The path to the directory containing the file.\n * @param {string} fileName The name of the file to fetch.\n * @param {boolean} [fatal=true] Whether to throw an error if the file is not found.\n * @param {PretrainedOptions} [options] An object containing optional parameters.\n * @returns {Promise} The JSON data parsed into a JavaScript object.\n * @throws Will throw an error if the file is not found and `fatal` is true.\n */\nexport async function getModelJSON(modelPath, fileName, fatal = true, options = {}) {\n let buffer = await getModelFile(modelPath, fileName, fatal, options);\n if (buffer === null) {\n // Return empty object\n return {}\n }\n\n let decoder = new TextDecoder('utf-8');\n let jsonData = decoder.decode(buffer);\n\n return JSON.parse(jsonData);\n}\n\n/**\n * Read and track progress when reading a Response object\n *\n * @param {any} response The Response object to read\n * @param {function} progress_callback The function to call with progress updates\n * @returns {Promise} A Promise that resolves with the Uint8Array buffer\n */\nasync function readResponse(response, progress_callback) {\n\n const contentLength = response.headers.get('Content-Length');\n if (contentLength === null) {\n console.warn('Unable to determine content-length from response headers. Will expand buffer when needed.')\n }\n let total = parseInt(contentLength ?? '0');\n let buffer = new Uint8Array(total);\n let loaded = 0;\n\n const reader = response.body.getReader();\n async function read() {\n const { done, value } = await reader.read();\n if (done) return;\n\n let newLoaded = loaded + value.length;\n if (newLoaded > total) {\n total = newLoaded;\n\n // Adding the new data will overflow buffer.\n // In this case, we extend the buffer\n let newBuffer = new Uint8Array(total);\n\n // copy contents\n newBuffer.set(buffer);\n\n buffer = newBuffer;\n }\n buffer.set(value, loaded)\n loaded = newLoaded;\n\n const progress = (loaded / total) * 100;\n\n // Call your function here\n progress_callback({\n progress: progress,\n loaded: loaded,\n total: total,\n })\n\n return read();\n }\n\n // Actually read\n await read();\n\n return buffer;\n}\n\n/**\n * Joins multiple parts of a path into a single path, while handling leading and trailing slashes.\n *\n * @param {...string} parts Multiple parts of a path.\n * @returns {string} A string representing the joined path.\n */\nfunction pathJoin(...parts) {\n // https://stackoverflow.com/a/55142565\n parts = parts.map((part, index) => {\n if (index) {\n part = part.replace(new RegExp('^/'), '');\n }\n if (index !== parts.length - 1) {\n part = part.replace(new RegExp('/$'), '');\n }\n return part;\n })\n return parts.join('/');\n}\n","\n/**\n * @file Helper module for image processing. \n * \n * These functions and classes are only used internally, \n * meaning an end-user shouldn't need to access anything here.\n * \n * @module utils/image\n */\n\nimport { getFile } from './hub.js';\nimport { env } from '../env.js';\nimport { Tensor } from './tensor.js';\n\n// Will be empty (or not used) if running in browser or web-worker\nimport sharp from 'sharp';\n\nconst BROWSER_ENV = typeof self !== 'undefined';\nconst WEBWORKER_ENV = BROWSER_ENV && self.constructor.name === 'DedicatedWorkerGlobalScope';\n\nlet createCanvasFunction;\nlet ImageDataClass;\nlet loadImageFunction;\nif (BROWSER_ENV) {\n // Running in browser or web-worker\n createCanvasFunction = (/** @type {number} */ width, /** @type {number} */ height) => {\n if (!self.OffscreenCanvas) {\n throw new Error('OffscreenCanvas not supported by this browser.');\n }\n return new self.OffscreenCanvas(width, height)\n };\n loadImageFunction = self.createImageBitmap;\n ImageDataClass = self.ImageData;\n\n} else if (sharp) {\n // Running in Node.js, electron, or other non-browser environment\n\n loadImageFunction = async (/**@type {sharp.Sharp}*/img) => {\n const metadata = await img.metadata();\n const rawChannels = metadata.channels;\n\n const { data, info } = await img.rotate().raw().toBuffer({ resolveWithObject: true });\n\n const newImage = new RawImage(new Uint8ClampedArray(data), info.width, info.height, info.channels);\n if (rawChannels !== undefined && rawChannels !== info.channels) {\n // Make sure the new image has the same number of channels as the input image.\n // This is necessary for grayscale images.\n newImage.convert(rawChannels);\n }\n return newImage;\n }\n\n} else {\n throw new Error('Unable to load image processing library.');\n}\n\n\n// Defined here: https://github.com/python-pillow/Pillow/blob/a405e8406b83f8bfb8916e93971edc7407b8b1ff/src/libImaging/Imaging.h#L262-L268\nconst RESAMPLING_MAPPING = {\n 0: 'nearest',\n 1: 'lanczos',\n 2: 'bilinear',\n 3: 'bicubic',\n 4: 'box',\n 5: 'hamming',\n}\n\n/**\n * Mapping from file extensions to MIME types.\n */\nconst CONTENT_TYPE_MAP = new Map([\n ['png', 'image/png'],\n ['jpg', 'image/jpeg'],\n ['jpeg', 'image/jpeg'],\n ['gif', 'image/gif'],\n]);\n\nexport class RawImage {\n\n /**\n * Create a new `RawImage` object.\n * @param {Uint8ClampedArray|Uint8Array} data The pixel data.\n * @param {number} width The width of the image.\n * @param {number} height The height of the image.\n * @param {1|2|3|4} channels The number of channels.\n */\n constructor(data, width, height, channels) {\n this.data = data;\n this.width = width;\n this.height = height;\n this.channels = channels;\n }\n\n /** \n * Returns the size of the image (width, height).\n * @returns {[number, number]} The size of the image (width, height).\n */\n get size() {\n return [this.width, this.height];\n }\n\n /**\n * Helper method for reading an image from a variety of input types.\n * @param {RawImage|string|URL} input \n * @returns The image object.\n * \n * **Example:** Read image from a URL.\n * ```javascript\n * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * // RawImage {\n * // \"data\": Uint8ClampedArray [ 25, 25, 25, 19, 19, 19, ... ],\n * // \"width\": 800,\n * // \"height\": 533,\n * // \"channels\": 3\n * // }\n * ```\n */\n static async read(input) {\n if (input instanceof RawImage) {\n return input;\n } else if (typeof input === 'string' || input instanceof URL) {\n return await this.fromURL(input);\n } else {\n throw new Error(`Unsupported input type: ${typeof input}`);\n }\n }\n\n /**\n * Read an image from a canvas.\n * @param {HTMLCanvasElement|OffscreenCanvas} canvas The canvas to read the image from.\n * @returns {RawImage} The image object.\n */\n static fromCanvas(canvas) {\n if (!BROWSER_ENV) {\n throw new Error('fromCanvas() is only supported in browser environments.')\n }\n\n const ctx = canvas.getContext('2d');\n const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;\n return new RawImage(data, canvas.width, canvas.height, 4);\n }\n\n /**\n * Read an image from a URL or file path.\n * @param {string|URL} url The URL or file path to read the image from.\n * @returns {Promise} The image object.\n */\n static async fromURL(url) {\n const response = await getFile(url);\n if (response.status !== 200) {\n throw new Error(`Unable to read image from \"${url}\" (${response.status} ${response.statusText})`);\n }\n const blob = await response.blob();\n return this.fromBlob(blob);\n }\n\n /**\n * Helper method to create a new Image from a blob.\n * @param {Blob} blob The blob to read the image from.\n * @returns {Promise} The image object.\n */\n static async fromBlob(blob) {\n if (BROWSER_ENV) {\n // Running in environment with canvas\n const img = await loadImageFunction(blob);\n\n const ctx = createCanvasFunction(img.width, img.height).getContext('2d');\n\n // Draw image to context\n ctx.drawImage(img, 0, 0);\n\n return new this(ctx.getImageData(0, 0, img.width, img.height).data, img.width, img.height, 4);\n\n } else {\n // Use sharp.js to read (and possible resize) the image.\n const img = sharp(await blob.arrayBuffer());\n\n return await loadImageFunction(img);\n }\n }\n\n /**\n * Helper method to create a new Image from a tensor\n * @param {Tensor} tensor \n */\n static fromTensor(tensor, channel_format = 'CHW') {\n if (tensor.dims.length !== 3) {\n throw new Error(`Tensor should have 3 dimensions, but has ${tensor.dims.length} dimensions.`);\n }\n\n if (channel_format === 'CHW') {\n tensor = tensor.transpose(1, 2, 0);\n } else if (channel_format === 'HWC') {\n // Do nothing\n } else {\n throw new Error(`Unsupported channel format: ${channel_format}`);\n }\n if (!(tensor.data instanceof Uint8ClampedArray || tensor.data instanceof Uint8Array)) {\n throw new Error(`Unsupported tensor type: ${tensor.type}`);\n }\n switch (tensor.dims[2]) {\n case 1:\n case 2:\n case 3:\n case 4:\n return new RawImage(tensor.data, tensor.dims[1], tensor.dims[0], tensor.dims[2]);\n default:\n throw new Error(`Unsupported number of channels: ${tensor.dims[2]}`);\n }\n }\n\n /**\n * Convert the image to grayscale format.\n * @returns {RawImage} `this` to support chaining.\n */\n grayscale() {\n if (this.channels === 1) {\n return this;\n }\n\n const newData = new Uint8ClampedArray(this.width * this.height * 1);\n switch (this.channels) {\n case 3: // rgb to grayscale\n case 4: // rgba to grayscale\n for (let i = 0, offset = 0; i < this.data.length; i += this.channels) {\n const red = this.data[i];\n const green = this.data[i + 1];\n const blue = this.data[i + 2];\n\n newData[offset++] = Math.round(0.2989 * red + 0.5870 * green + 0.1140 * blue);\n }\n break;\n default:\n throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);\n }\n return this._update(newData, this.width, this.height, 1);\n }\n\n /**\n * Convert the image to RGB format.\n * @returns {RawImage} `this` to support chaining.\n */\n rgb() {\n if (this.channels === 3) {\n return this;\n }\n\n const newData = new Uint8ClampedArray(this.width * this.height * 3);\n\n switch (this.channels) {\n case 1: // grayscale to rgb\n for (let i = 0, offset = 0; i < this.data.length; ++i) {\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i];\n }\n break;\n case 4: // rgba to rgb\n for (let i = 0, offset = 0; i < this.data.length; i += 4) {\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i + 1];\n newData[offset++] = this.data[i + 2];\n }\n break;\n default:\n throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);\n }\n return this._update(newData, this.width, this.height, 3);\n\n }\n\n /**\n * Convert the image to RGBA format.\n * @returns {RawImage} `this` to support chaining.\n */\n rgba() {\n if (this.channels === 4) {\n return this;\n }\n\n const newData = new Uint8ClampedArray(this.width * this.height * 4);\n\n switch (this.channels) {\n case 1: // grayscale to rgba\n for (let i = 0, offset = 0; i < this.data.length; ++i) {\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i];\n newData[offset++] = 255;\n }\n break;\n case 3: // rgb to rgba\n for (let i = 0, offset = 0; i < this.data.length; i += 3) {\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i + 1];\n newData[offset++] = this.data[i + 2];\n newData[offset++] = 255;\n }\n break;\n default:\n throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);\n }\n\n return this._update(newData, this.width, this.height, 4);\n }\n\n /**\n * Resize the image to the given dimensions. This method uses the canvas API to perform the resizing.\n * @param {number} width The width of the new image.\n * @param {number} height The height of the new image.\n * @param {Object} options Additional options for resizing.\n * @param {0|1|2|3|4|5|string} [options.resample] The resampling method to use.\n * @returns {Promise} `this` to support chaining.\n */\n async resize(width, height, {\n resample = 2,\n } = {}) {\n\n // Ensure resample method is a string\n let resampleMethod = RESAMPLING_MAPPING[resample] ?? resample;\n\n if (BROWSER_ENV) {\n // TODO use `resample` in browser environment\n\n // Store number of channels before resizing\n const numChannels = this.channels;\n\n // Create canvas object for this image\n const canvas = this.toCanvas();\n\n // Actually perform resizing using the canvas API\n const ctx = createCanvasFunction(width, height).getContext('2d');\n\n // Draw image to context, resizing in the process\n ctx.drawImage(canvas, 0, 0, width, height);\n\n // Create image from the resized data\n const resizedImage = new RawImage(ctx.getImageData(0, 0, width, height).data, width, height, 4);\n\n // Convert back so that image has the same number of channels as before\n return resizedImage.convert(numChannels);\n\n } else {\n // Create sharp image from raw data, and resize\n let img = this.toSharp();\n\n switch (resampleMethod) {\n case 'box':\n case 'hamming':\n if (resampleMethod === 'box' || resampleMethod === 'hamming') {\n console.warn(`Resampling method ${resampleMethod} is not yet supported. Using bilinear instead.`);\n resampleMethod = 'bilinear';\n }\n\n case 'nearest':\n case 'bilinear':\n case 'bicubic':\n // Perform resizing using affine transform. \n // This matches how the python Pillow library does it.\n img = img.affine([width / this.width, 0, 0, height / this.height], {\n interpolator: resampleMethod\n });\n break;\n\n case 'lanczos':\n // https://github.com/python-pillow/Pillow/discussions/5519\n // https://github.com/lovell/sharp/blob/main/docs/api-resize.md\n img = img.resize({\n width, height,\n fit: 'fill',\n kernel: 'lanczos3', // PIL Lanczos uses a kernel size of 3 \n });\n break;\n\n default:\n throw new Error(`Resampling method ${resampleMethod} is not supported.`);\n }\n\n return await loadImageFunction(img);\n }\n\n }\n\n async pad([left, right, top, bottom]) {\n left = Math.max(left, 0);\n right = Math.max(right, 0);\n top = Math.max(top, 0);\n bottom = Math.max(bottom, 0);\n\n if (left === 0 && right === 0 && top === 0 && bottom === 0) {\n // No padding needed\n return this;\n }\n\n if (BROWSER_ENV) {\n // Store number of channels before padding\n const numChannels = this.channels;\n\n // Create canvas object for this image\n const canvas = this.toCanvas();\n\n const newWidth = this.width + left + right;\n const newHeight = this.height + top + bottom;\n\n // Create a new canvas of the desired size.\n const ctx = createCanvasFunction(newWidth, newHeight).getContext('2d');\n\n // Draw image to context, padding in the process\n ctx.drawImage(canvas,\n 0, 0, this.width, this.height,\n left, top, newWidth, newHeight\n );\n\n // Create image from the padded data\n const paddedImage = new RawImage(\n ctx.getImageData(0, 0, newWidth, newHeight).data,\n newWidth, newHeight, 4);\n\n // Convert back so that image has the same number of channels as before\n return paddedImage.convert(numChannels);\n\n } else {\n const img = this.toSharp().extend({ left, right, top, bottom });\n return await loadImageFunction(img);\n }\n }\n\n async crop([x_min, y_min, x_max, y_max]) {\n // Ensure crop bounds are within the image\n x_min = Math.max(x_min, 0);\n y_min = Math.max(y_min, 0);\n x_max = Math.min(x_max, this.width - 1);\n y_max = Math.min(y_max, this.height - 1);\n\n // Do nothing if the crop is the entire image\n if (x_min === 0 && y_min === 0 && x_max === this.width - 1 && y_max === this.height - 1) {\n return this;\n }\n\n const crop_width = x_max - x_min + 1;\n const crop_height = y_max - y_min + 1;\n\n if (BROWSER_ENV) {\n // Store number of channels before resizing\n const numChannels = this.channels;\n\n // Create canvas object for this image\n const canvas = this.toCanvas();\n\n // Create a new canvas of the desired size. This is needed since if the \n // image is too small, we need to pad it with black pixels.\n const ctx = createCanvasFunction(crop_width, crop_height).getContext('2d');\n\n // Draw image to context, cropping in the process\n ctx.drawImage(canvas,\n x_min, y_min, crop_width, crop_height,\n 0, 0, crop_width, crop_height\n );\n\n // Create image from the resized data\n const resizedImage = new RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4);\n\n // Convert back so that image has the same number of channels as before\n return resizedImage.convert(numChannels);\n\n } else {\n // Create sharp image from raw data\n const img = this.toSharp().extract({\n left: x_min,\n top: y_min,\n width: crop_width,\n height: crop_height,\n });\n\n return await loadImageFunction(img);\n }\n\n }\n\n async center_crop(crop_width, crop_height) {\n // If the image is already the desired size, return it\n if (this.width === crop_width && this.height === crop_height) {\n return this;\n }\n\n // Determine bounds of the image in the new canvas\n const width_offset = (this.width - crop_width) / 2;\n const height_offset = (this.height - crop_height) / 2;\n\n\n if (BROWSER_ENV) {\n // Store number of channels before resizing\n const numChannels = this.channels;\n\n // Create canvas object for this image\n const canvas = this.toCanvas();\n\n // Create a new canvas of the desired size. This is needed since if the \n // image is too small, we need to pad it with black pixels.\n const ctx = createCanvasFunction(crop_width, crop_height).getContext('2d');\n\n let sourceX = 0;\n let sourceY = 0;\n let destX = 0;\n let destY = 0;\n\n if (width_offset >= 0) {\n sourceX = width_offset;\n } else {\n destX = -width_offset;\n }\n\n if (height_offset >= 0) {\n sourceY = height_offset;\n } else {\n destY = -height_offset;\n }\n\n // Draw image to context, cropping in the process\n ctx.drawImage(canvas,\n sourceX, sourceY, crop_width, crop_height,\n destX, destY, crop_width, crop_height\n );\n\n // Create image from the resized data\n const resizedImage = new RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4);\n\n // Convert back so that image has the same number of channels as before\n return resizedImage.convert(numChannels);\n\n } else {\n // Create sharp image from raw data\n let img = this.toSharp();\n\n if (width_offset >= 0 && height_offset >= 0) {\n // Cropped image lies entirely within the original image\n img = img.extract({\n left: Math.floor(width_offset),\n top: Math.floor(height_offset),\n width: crop_width,\n height: crop_height,\n })\n } else if (width_offset <= 0 && height_offset <= 0) {\n // Cropped image lies entirely outside the original image,\n // so we add padding\n const top = Math.floor(-height_offset);\n const left = Math.floor(-width_offset);\n img = img.extend({\n top: top,\n left: left,\n\n // Ensures the resulting image has the desired dimensions\n right: crop_width - this.width - left,\n bottom: crop_height - this.height - top,\n });\n } else {\n // Cropped image lies partially outside the original image.\n // We first pad, then crop.\n\n let y_padding = [0, 0];\n let y_extract = 0;\n if (height_offset < 0) {\n y_padding[0] = Math.floor(-height_offset);\n y_padding[1] = crop_height - this.height - y_padding[0];\n } else {\n y_extract = Math.floor(height_offset);\n }\n\n let x_padding = [0, 0];\n let x_extract = 0;\n if (width_offset < 0) {\n x_padding[0] = Math.floor(-width_offset);\n x_padding[1] = crop_width - this.width - x_padding[0];\n } else {\n x_extract = Math.floor(width_offset);\n }\n\n img = img.extend({\n top: y_padding[0],\n bottom: y_padding[1],\n left: x_padding[0],\n right: x_padding[1],\n }).extract({\n left: x_extract,\n top: y_extract,\n width: crop_width,\n height: crop_height,\n })\n }\n\n return await loadImageFunction(img);\n }\n }\n\n async toBlob(type = 'image/png', quality = 1) {\n if (!BROWSER_ENV) {\n throw new Error('toBlob() is only supported in browser environments.')\n }\n\n const canvas = this.toCanvas();\n return await canvas.convertToBlob({ type, quality });\n }\n\n toTensor(channel_format = 'CHW') {\n let tensor = new Tensor(\n 'uint8',\n new Uint8Array(this.data),\n [this.height, this.width, this.channels]\n );\n\n if (channel_format === 'HWC') {\n // Do nothing\n } else if (channel_format === 'CHW') { // hwc -> chw\n tensor = tensor.permute(2, 0, 1);\n } else {\n throw new Error(`Unsupported channel format: ${channel_format}`);\n }\n return tensor;\n }\n\n toCanvas() {\n if (!BROWSER_ENV) {\n throw new Error('toCanvas() is only supported in browser environments.')\n }\n\n // Clone, and convert data to RGBA before drawing to canvas.\n // This is because the canvas API only supports RGBA\n const cloned = this.clone().rgba();\n\n // Create canvas object for the cloned image\n const clonedCanvas = createCanvasFunction(cloned.width, cloned.height);\n\n // Draw image to context\n const data = new ImageDataClass(cloned.data, cloned.width, cloned.height);\n clonedCanvas.getContext('2d').putImageData(data, 0, 0);\n\n return clonedCanvas;\n }\n\n /**\n * Helper method to update the image data.\n * @param {Uint8ClampedArray} data The new image data.\n * @param {number} width The new width of the image.\n * @param {number} height The new height of the image.\n * @param {1|2|3|4|null} [channels] The new number of channels of the image.\n * @private\n */\n _update(data, width, height, channels = null) {\n this.data = data;\n this.width = width;\n this.height = height;\n if (channels !== null) {\n this.channels = channels;\n }\n return this;\n }\n\n /**\n * Clone the image\n * @returns {RawImage} The cloned image\n */\n clone() {\n return new RawImage(this.data.slice(), this.width, this.height, this.channels);\n }\n\n /**\n * Helper method for converting image to have a certain number of channels\n * @param {number} numChannels The number of channels. Must be 1, 3, or 4.\n * @returns {RawImage} `this` to support chaining.\n */\n convert(numChannels) {\n if (this.channels === numChannels) return this; // Already correct number of channels\n\n switch (numChannels) {\n case 1:\n this.grayscale();\n break;\n case 3:\n this.rgb();\n break;\n case 4:\n this.rgba();\n break;\n default:\n throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);\n }\n return this;\n }\n\n /**\n * Save the image to the given path.\n * @param {string} path The path to save the image to.\n */\n async save(path) {\n\n if (BROWSER_ENV) {\n if (WEBWORKER_ENV) {\n throw new Error('Unable to save an image from a Web Worker.')\n }\n\n const extension = path.split('.').pop().toLowerCase();\n const mime = CONTENT_TYPE_MAP.get(extension) ?? 'image/png';\n\n // Convert image to Blob\n const blob = await this.toBlob(mime);\n\n // Convert the canvas content to a data URL\n const dataURL = URL.createObjectURL(blob);\n\n // Create an anchor element with the data URL as the href attribute\n const downloadLink = document.createElement('a');\n downloadLink.href = dataURL;\n\n // Set the download attribute to specify the desired filename for the downloaded image\n downloadLink.download = path;\n\n // Trigger the download\n downloadLink.click();\n\n // Clean up: remove the anchor element from the DOM\n downloadLink.remove();\n\n } else if (!env.useFS) {\n throw new Error('Unable to save the image because filesystem is disabled in this environment.')\n\n } else {\n const img = this.toSharp();\n return await img.toFile(path);\n }\n }\n\n toSharp() {\n if (BROWSER_ENV) {\n throw new Error('toSharp() is only supported in server-side environments.')\n }\n\n return sharp(this.data, {\n raw: {\n width: this.width,\n height: this.height,\n channels: this.channels\n }\n });\n }\n}","\n/**\n * @file Helper module for mathematical processing. \n * \n * These functions and classes are only used internally, \n * meaning an end-user shouldn't need to access anything here.\n * \n * @module utils/maths\n */\n\n/**\n * @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array} TypedArray\n * @typedef {BigInt64Array | BigUint64Array} BigTypedArray\n * @typedef {TypedArray | BigTypedArray} AnyTypedArray\n */\n\n/**\n * @param {TypedArray} input\n */\nexport function interpolate_data(input, [in_channels, in_height, in_width], [out_height, out_width], mode = 'bilinear', align_corners = false) {\n // TODO use mode and align_corners\n\n // Output image dimensions\n const x_scale = out_width / in_width;\n const y_scale = out_height / in_height;\n\n // Output image\n // @ts-ignore\n const out_img = new input.constructor(out_height * out_width * in_channels);\n\n // Pre-calculate strides\n const inStride = in_height * in_width;\n const outStride = out_height * out_width;\n\n for (let i = 0; i < out_height; ++i) {\n for (let j = 0; j < out_width; ++j) {\n // Calculate output offset\n const outOffset = i * out_width + j;\n\n // Calculate input pixel coordinates\n const x = (j + 0.5) / x_scale - 0.5;\n const y = (i + 0.5) / y_scale - 0.5;\n\n // Calculate the four nearest input pixels\n // We also check if the input pixel coordinates are within the image bounds\n let x1 = Math.floor(x);\n let y1 = Math.floor(y);\n const x2 = Math.min(x1 + 1, in_width - 1);\n const y2 = Math.min(y1 + 1, in_height - 1);\n\n x1 = Math.max(x1, 0);\n y1 = Math.max(y1, 0);\n\n\n // Calculate the fractional distances between the input pixel and the four nearest pixels\n const s = x - x1;\n const t = y - y1;\n\n // Perform bilinear interpolation\n const w1 = (1 - s) * (1 - t);\n const w2 = s * (1 - t);\n const w3 = (1 - s) * t;\n const w4 = s * t;\n\n // Calculate the four nearest input pixel indices\n const yStride = y1 * in_width;\n const xStride = y2 * in_width;\n const idx1 = yStride + x1;\n const idx2 = yStride + x2;\n const idx3 = xStride + x1;\n const idx4 = xStride + x2;\n\n for (let k = 0; k < in_channels; ++k) {\n // Calculate channel offset\n const cOffset = k * inStride;\n\n out_img[k * outStride + outOffset] =\n w1 * input[cOffset + idx1] +\n w2 * input[cOffset + idx2] +\n w3 * input[cOffset + idx3] +\n w4 * input[cOffset + idx4];\n }\n }\n }\n\n return out_img;\n}\n\n\n/**\n * Helper method to permute a `AnyTypedArray` directly\n * @template {AnyTypedArray} T \n * @param {T} array \n * @param {number[]} dims \n * @param {number[]} axes \n * @returns {[T, number[]]} The permuted array and the new shape.\n */\nexport function permute_data(array, dims, axes) {\n // Calculate the new shape of the permuted array\n // and the stride of the original array\n const shape = new Array(axes.length);\n const stride = new Array(axes.length);\n\n for (let i = axes.length - 1, s = 1; i >= 0; --i) {\n stride[i] = s;\n shape[i] = dims[axes[i]];\n s *= shape[i];\n }\n\n // Precompute inverse mapping of stride\n const invStride = axes.map((_, i) => stride[axes.indexOf(i)]);\n\n // Create the permuted array with the new shape\n // @ts-ignore\n const permutedData = new array.constructor(array.length);\n\n // Permute the original array to the new array\n for (let i = 0; i < array.length; ++i) {\n let newIndex = 0;\n for (let j = dims.length - 1, k = i; j >= 0; --j) {\n newIndex += (k % dims[j]) * invStride[j];\n k = Math.floor(k / dims[j]);\n }\n permutedData[newIndex] = array[i];\n }\n\n return [permutedData, shape];\n}\n\n\n/**\n * Compute the softmax of an array of numbers.\n * @template {TypedArray|number[]} T\n * @param {T} arr The array of numbers to compute the softmax of.\n * @returns {T} The softmax array.\n */\nexport function softmax(arr) {\n // Compute the maximum value in the array\n const maxVal = max(arr)[0];\n\n // Compute the exponentials of the array values\n const exps = arr.map(x => Math.exp(x - maxVal));\n\n // Compute the sum of the exponentials\n // @ts-ignore\n const sumExps = exps.reduce((acc, val) => acc + val, 0);\n\n // Compute the softmax values\n const softmaxArr = exps.map(x => x / sumExps);\n\n return /** @type {T} */(softmaxArr);\n}\n\n/**\n * Calculates the logarithm of the softmax function for the input array.\n * @template {TypedArray|number[]} T\n * @param {T} arr The input array to calculate the log_softmax function for.\n * @returns {T} The resulting log_softmax array.\n */\nexport function log_softmax(arr) {\n // Compute the maximum value in the array\n const maxVal = max(arr)[0];\n\n // Compute the sum of the exponentials\n let sumExps = 0;\n for(let i = 0; i < arr.length; ++i) {\n sumExps += Math.exp(arr[i] - maxVal);\n }\n\n // Compute the log of the sum\n const logSum = Math.log(sumExps);\n\n // Compute the softmax values\n const logSoftmaxArr = arr.map(x => x - maxVal - logSum);\n\n return /** @type {T} */(logSoftmaxArr);\n}\n\n/**\n * Calculates the dot product of two arrays.\n * @param {number[]} arr1 The first array.\n * @param {number[]} arr2 The second array.\n * @returns {number} The dot product of arr1 and arr2.\n */\nexport function dot(arr1, arr2) {\n let result = 0;\n for (let i = 0; i < arr1.length; ++i) {\n result += arr1[i] * arr2[i];\n }\n return result;\n}\n\n/**\n * Computes the cosine similarity between two arrays.\n *\n * @param {number[]} arr1 The first array.\n * @param {number[]} arr2 The second array.\n * @returns {number} The cosine similarity between the two arrays.\n */\nexport function cos_sim(arr1, arr2) {\n // Calculate dot product of the two arrays\n const dotProduct = dot(arr1, arr2);\n\n // Calculate the magnitude of the first array\n const magnitudeA = magnitude(arr1);\n\n // Calculate the magnitude of the second array\n const magnitudeB = magnitude(arr2);\n\n // Calculate the cosine similarity\n const cosineSimilarity = dotProduct / (magnitudeA * magnitudeB);\n\n return cosineSimilarity;\n}\n\n/**\n * Calculates the magnitude of a given array.\n * @param {number[]} arr The array to calculate the magnitude of.\n * @returns {number} The magnitude of the array.\n */\nexport function magnitude(arr) {\n return Math.sqrt(arr.reduce((acc, val) => acc + val * val, 0));\n}\n\n\n/**\n * Returns the value and index of the minimum element in an array.\n * @param {number[]|TypedArray} arr array of numbers.\n * @returns {[number, number]} the value and index of the minimum element, of the form: [valueOfMin, indexOfMin]\n * @throws {Error} If array is empty.\n */\nexport function min(arr) {\n if (arr.length === 0) throw Error('Array must not be empty');\n let min = arr[0];\n let indexOfMin = 0;\n for (let i = 1; i < arr.length; ++i) {\n if (arr[i] < min) {\n min = arr[i];\n indexOfMin = i;\n }\n }\n return [min, indexOfMin];\n}\n\n\n/**\n * Returns the value and index of the maximum element in an array.\n * @param {number[]|AnyTypedArray} arr array of numbers.\n * @returns {[number, number]} the value and index of the maximum element, of the form: [valueOfMax, indexOfMax]\n * @throws {Error} If array is empty.\n */\nexport function max(arr) {\n if (arr.length === 0) throw Error('Array must not be empty');\n let max = arr[0];\n let indexOfMax = 0;\n for (let i = 1; i < arr.length; ++i) {\n if (arr[i] > max) {\n max = arr[i];\n indexOfMax = i;\n }\n }\n return [Number(max), indexOfMax];\n}\n\nfunction isPowerOfTwo(number) {\n // Check if the number is greater than 0 and has only one bit set to 1\n return (number > 0) && ((number & (number - 1)) === 0);\n}\n\n/**\n * Implementation of Radix-4 FFT.\n * \n * P2FFT class provides functionality for performing Fast Fourier Transform on arrays\n * which are a power of two in length.\n * Code adapted from https://www.npmjs.com/package/fft.js\n */\nclass P2FFT {\n /**\n * @param {number} size The size of the input array. Must be a power of two larger than 1.\n * @throws {Error} FFT size must be a power of two larger than 1.\n */\n constructor(size) {\n this.size = size | 0; // convert to a 32-bit signed integer\n if (this.size <= 1 || !isPowerOfTwo(this.size))\n throw new Error('FFT size must be a power of two larger than 1');\n\n this._csize = size << 1;\n\n this.table = new Float64Array(this.size * 2);\n for (let i = 0; i < this.table.length; i += 2) {\n const angle = Math.PI * i / this.size;\n this.table[i] = Math.cos(angle);\n this.table[i + 1] = -Math.sin(angle);\n }\n\n // Find size's power of two\n let power = 0;\n for (let t = 1; this.size > t; t <<= 1)\n ++power;\n\n // Calculate initial step's width:\n // * If we are full radix-4, it is 2x smaller to give inital len=8\n // * Otherwise it is the same as `power` to give len=4\n this._width = power % 2 === 0 ? power - 1 : power;\n\n // Pre-compute bit-reversal patterns\n this._bitrev = new Int32Array(1 << this._width);\n for (let j = 0; j < this._bitrev.length; ++j) {\n this._bitrev[j] = 0;\n for (let shift = 0; shift < this._width; shift += 2) {\n const revShift = this._width - shift - 2;\n this._bitrev[j] |= ((j >>> shift) & 3) << revShift;\n }\n }\n }\n\n /**\n * Create a complex number array with size `2 * size`\n *\n * @returns {Float64Array} A complex number array with size `2 * size`\n */\n createComplexArray() {\n return new Float64Array(this._csize);\n }\n\n /**\n * Converts a complex number representation stored in a Float64Array to an array of real numbers.\n * \n * @param {Float64Array} complex The complex number representation to be converted.\n * @param {number[]} [storage] An optional array to store the result in.\n * @returns {number[]} An array of real numbers representing the input complex number representation.\n */\n fromComplexArray(complex, storage) {\n const res = storage || new Array(complex.length >>> 1);\n for (let i = 0; i < complex.length; i += 2)\n res[i >>> 1] = complex[i];\n return res;\n }\n\n /**\n * Convert a real-valued input array to a complex-valued output array.\n * @param {Float64Array} input The real-valued input array.\n * @param {Float64Array} [storage] Optional buffer to store the output array.\n * @returns {Float64Array} The complex-valued output array.\n */\n toComplexArray(input, storage) {\n const res = storage || this.createComplexArray();\n for (let i = 0; i < res.length; i += 2) {\n res[i] = input[i >>> 1];\n res[i + 1] = 0;\n }\n return res;\n }\n\n /**\n * Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer.\n * \n * @param {Float64Array} out The output buffer to store the result.\n * @param {Float64Array} data The input data to transform.\n * \n * @throws {Error} Input and output buffers must be different.\n * \n * @returns {void}\n */\n transform(out, data) {\n if (out === data)\n throw new Error('Input and output buffers must be different');\n\n this._transform4(out, data, 1 /* DONE */);\n }\n\n /**\n * Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer.\n * The input buffer must contain real values only, while the output buffer will contain complex values. The input and\n * output buffers must be different.\n *\n * @param {Float64Array} out The output buffer.\n * @param {Float64Array} data The input buffer containing real values.\n *\n * @throws {Error} If the input and output buffers are the same.\n */\n realTransform(out, data) {\n if (out === data)\n throw new Error('Input and output buffers must be different');\n\n this._realTransform4(out, data, 1 /* DONE */);\n }\n\n /**\n * Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`.\n * The `out` array must be a different buffer than the `data` array. The `out` array will contain the\n * result of the transformation. The `data` array will not be modified.\n * \n * @param {Float64Array} out The output buffer for the transformed data.\n * @param {Float64Array} data The input data to transform.\n * @throws {Error} If `out` and `data` refer to the same buffer.\n * @returns {void}\n */\n inverseTransform(out, data) {\n if (out === data)\n throw new Error('Input and output buffers must be different');\n\n this._transform4(out, data, -1 /* DONE */);\n for (let i = 0; i < out.length; ++i)\n out[i] /= this.size;\n }\n\n /**\n * Performs a radix-4 implementation of a discrete Fourier transform on a given set of data.\n *\n * @param {Float64Array} out The output buffer for the transformed data.\n * @param {Float64Array} data The input buffer of data to be transformed.\n * @param {number} inv A scaling factor to apply to the transform.\n * @returns {void}\n */\n _transform4(out, data, inv) {\n // radix-4 implementation\n\n const size = this._csize;\n\n // Initial step (permute and transform)\n const width = this._width;\n let step = 1 << width;\n let len = (size / step) << 1;\n\n let outOff;\n let t;\n const bitrev = this._bitrev;\n if (len === 4) {\n for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n const off = bitrev[t];\n this._singleTransform2(data, out, outOff, off, step);\n }\n } else {\n // len === 8\n for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n const off = bitrev[t];\n this._singleTransform4(data, out, outOff, off, step, inv);\n }\n }\n\n // Loop through steps in decreasing order\n const table = this.table;\n for (step >>= 2; step >= 2; step >>= 2) {\n len = (size / step) << 1;\n const quarterLen = len >>> 2;\n\n // Loop through offsets in the data\n for (outOff = 0; outOff < size; outOff += len) {\n // Full case\n const limit = outOff + quarterLen - 1;\n for (let i = outOff, k = 0; i < limit; i += 2, k += step) {\n const A = i;\n const B = A + quarterLen;\n const C = B + quarterLen;\n const D = C + quarterLen;\n\n // Original values\n const Ar = out[A];\n const Ai = out[A + 1];\n const Br = out[B];\n const Bi = out[B + 1];\n const Cr = out[C];\n const Ci = out[C + 1];\n const Dr = out[D];\n const Di = out[D + 1];\n\n const tableBr = table[k];\n const tableBi = inv * table[k + 1];\n const MBr = Br * tableBr - Bi * tableBi;\n const MBi = Br * tableBi + Bi * tableBr;\n\n const tableCr = table[2 * k];\n const tableCi = inv * table[2 * k + 1];\n const MCr = Cr * tableCr - Ci * tableCi;\n const MCi = Cr * tableCi + Ci * tableCr;\n\n const tableDr = table[3 * k];\n const tableDi = inv * table[3 * k + 1];\n const MDr = Dr * tableDr - Di * tableDi;\n const MDi = Dr * tableDi + Di * tableDr;\n\n // Pre-Final values\n const T0r = Ar + MCr;\n const T0i = Ai + MCi;\n const T1r = Ar - MCr;\n const T1i = Ai - MCi;\n const T2r = MBr + MDr;\n const T2i = MBi + MDi;\n const T3r = inv * (MBr - MDr);\n const T3i = inv * (MBi - MDi);\n\n // Final values\n out[A] = T0r + T2r;\n out[A + 1] = T0i + T2i;\n out[B] = T1r + T3i;\n out[B + 1] = T1i - T3r;\n out[C] = T0r - T2r;\n out[C + 1] = T0i - T2i;\n out[D] = T1r - T3i;\n out[D + 1] = T1i + T3r;\n }\n }\n }\n }\n\n /**\n * Performs a radix-2 implementation of a discrete Fourier transform on a given set of data.\n *\n * @param {Float64Array} data The input buffer of data to be transformed.\n * @param {Float64Array} out The output buffer for the transformed data.\n * @param {number} outOff The offset at which to write the output data.\n * @param {number} off The offset at which to begin reading the input data.\n * @param {number} step The step size for indexing the input data.\n * @returns {void}\n */\n _singleTransform2(data, out, outOff, off, step) {\n // radix-2 implementation\n // NOTE: Only called for len=4\n\n const evenR = data[off];\n const evenI = data[off + 1];\n const oddR = data[off + step];\n const oddI = data[off + step + 1];\n\n out[outOff] = evenR + oddR;\n out[outOff + 1] = evenI + oddI;\n out[outOff + 2] = evenR - oddR;\n out[outOff + 3] = evenI - oddI;\n }\n\n /**\n * Performs radix-4 transformation on input data of length 8\n *\n * @param {Float64Array} data Input data array of length 8\n * @param {Float64Array} out Output data array of length 8\n * @param {number} outOff Index of output array to start writing from\n * @param {number} off Index of input array to start reading from\n * @param {number} step Step size between elements in input array\n * @param {number} inv Scaling factor for inverse transform\n * \n * @returns {void}\n */\n _singleTransform4(data, out, outOff, off, step, inv) {\n // radix-4\n // NOTE: Only called for len=8\n const step2 = step * 2;\n const step3 = step * 3;\n\n // Original values\n const Ar = data[off];\n const Ai = data[off + 1];\n const Br = data[off + step];\n const Bi = data[off + step + 1];\n const Cr = data[off + step2];\n const Ci = data[off + step2 + 1];\n const Dr = data[off + step3];\n const Di = data[off + step3 + 1];\n\n // Pre-Final values\n const T0r = Ar + Cr;\n const T0i = Ai + Ci;\n const T1r = Ar - Cr;\n const T1i = Ai - Ci;\n const T2r = Br + Dr;\n const T2i = Bi + Di;\n const T3r = inv * (Br - Dr);\n const T3i = inv * (Bi - Di);\n\n // Final values\n out[outOff] = T0r + T2r;\n out[outOff + 1] = T0i + T2i;\n out[outOff + 2] = T1r + T3i;\n out[outOff + 3] = T1i - T3r;\n out[outOff + 4] = T0r - T2r;\n out[outOff + 5] = T0i - T2i;\n out[outOff + 6] = T1r - T3i;\n out[outOff + 7] = T1i + T3r;\n }\n\n /**\n * Real input radix-4 implementation\n * @param {Float64Array} out Output array for the transformed data\n * @param {Float64Array} data Input array of real data to be transformed\n * @param {number} inv The scale factor used to normalize the inverse transform\n */\n _realTransform4(out, data, inv) {\n // Real input radix-4 implementation\n const size = this._csize;\n\n // Initial step (permute and transform)\n const width = this._width;\n let step = 1 << width;\n let len = (size / step) << 1;\n\n let outOff;\n let t;\n const bitrev = this._bitrev;\n if (len === 4) {\n for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n const off = bitrev[t];\n this._singleRealTransform2(data, out, outOff, off >>> 1, step >>> 1);\n }\n } else {\n // len === 8\n for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n const off = bitrev[t];\n this._singleRealTransform4(data, out, outOff, off >>> 1, step >>> 1, inv);\n }\n }\n\n // Loop through steps in decreasing order\n const table = this.table;\n for (step >>= 2; step >= 2; step >>= 2) {\n len = (size / step) << 1;\n const halfLen = len >>> 1;\n const quarterLen = halfLen >>> 1;\n const hquarterLen = quarterLen >>> 1;\n\n // Loop through offsets in the data\n for (outOff = 0; outOff < size; outOff += len) {\n for (let i = 0, k = 0; i <= hquarterLen; i += 2, k += step) {\n const A = outOff + i;\n const B = A + quarterLen;\n const C = B + quarterLen;\n const D = C + quarterLen;\n\n // Original values\n const Ar = out[A];\n const Ai = out[A + 1];\n const Br = out[B];\n const Bi = out[B + 1];\n const Cr = out[C];\n const Ci = out[C + 1];\n const Dr = out[D];\n const Di = out[D + 1];\n\n // Middle values\n const MAr = Ar;\n const MAi = Ai;\n\n const tableBr = table[k];\n const tableBi = inv * table[k + 1];\n const MBr = Br * tableBr - Bi * tableBi;\n const MBi = Br * tableBi + Bi * tableBr;\n\n const tableCr = table[2 * k];\n const tableCi = inv * table[2 * k + 1];\n const MCr = Cr * tableCr - Ci * tableCi;\n const MCi = Cr * tableCi + Ci * tableCr;\n\n const tableDr = table[3 * k];\n const tableDi = inv * table[3 * k + 1];\n const MDr = Dr * tableDr - Di * tableDi;\n const MDi = Dr * tableDi + Di * tableDr;\n\n // Pre-Final values\n const T0r = MAr + MCr;\n const T0i = MAi + MCi;\n const T1r = MAr - MCr;\n const T1i = MAi - MCi;\n const T2r = MBr + MDr;\n const T2i = MBi + MDi;\n const T3r = inv * (MBr - MDr);\n const T3i = inv * (MBi - MDi);\n\n // Final values\n out[A] = T0r + T2r;\n out[A + 1] = T0i + T2i;\n out[B] = T1r + T3i;\n out[B + 1] = T1i - T3r;\n\n // Output final middle point\n if (i === 0) {\n out[C] = T0r - T2r;\n out[C + 1] = T0i - T2i;\n continue;\n }\n\n // Do not overwrite ourselves\n if (i === hquarterLen)\n continue;\n\n const SA = outOff + quarterLen - i;\n const SB = outOff + halfLen - i;\n\n out[SA] = T1r - inv * T3i;\n out[SA + 1] = -T1i - inv * T3r;\n out[SB] = T0r - inv * T2r;\n out[SB + 1] = -T0i + inv * T2i;\n }\n }\n }\n\n // Complete the spectrum by adding its mirrored negative frequency components.\n const half = size >>> 1;\n for (let i = 2; i < half; i += 2) {\n out[size - i] = out[i];\n out[size - i + 1] = -out[i + 1];\n }\n }\n\n /**\n * Performs a single real input radix-2 transformation on the provided data\n * \n * @param {Float64Array} data The input data array\n * @param {Float64Array} out The output data array\n * @param {number} outOff The output offset\n * @param {number} off The input offset\n * @param {number} step The step\n * \n * @returns {void}\n */\n _singleRealTransform2(data, out, outOff, off, step) {\n // radix-2 implementation\n // NOTE: Only called for len=4\n\n const evenR = data[off];\n const oddR = data[off + step];\n\n out[outOff] = evenR + oddR;\n out[outOff + 1] = 0;\n out[outOff + 2] = evenR - oddR;\n out[outOff + 3] = 0;\n }\n\n /**\n * Computes a single real-valued transform using radix-4 algorithm.\n * This method is only called for len=8.\n *\n * @param {Float64Array} data The input data array.\n * @param {Float64Array} out The output data array.\n * @param {number} outOff The offset into the output array.\n * @param {number} off The offset into the input array.\n * @param {number} step The step size for the input array.\n * @param {number} inv The value of inverse.\n */\n _singleRealTransform4(data, out, outOff, off, step, inv) {\n // radix-4\n // NOTE: Only called for len=8\n const step2 = step * 2;\n const step3 = step * 3;\n\n // Original values\n const Ar = data[off];\n const Br = data[off + step];\n const Cr = data[off + step2];\n const Dr = data[off + step3];\n\n // Pre-Final values\n const T0r = Ar + Cr;\n const T1r = Ar - Cr;\n const T2r = Br + Dr;\n const T3r = inv * (Br - Dr);\n\n // Final values\n out[outOff] = T0r + T2r;\n out[outOff + 1] = 0;\n out[outOff + 2] = T1r;\n out[outOff + 3] = -T3r;\n out[outOff + 4] = T0r - T2r;\n out[outOff + 5] = 0;\n out[outOff + 6] = T1r;\n out[outOff + 7] = T3r;\n }\n}\n\n/**\n * NP2FFT class provides functionality for performing Fast Fourier Transform on arrays\n * which are not a power of two in length. In such cases, the chirp-z transform is used.\n * \n * For more information, see: https://math.stackexchange.com/questions/77118/non-power-of-2-ffts/77156#77156\n */\nclass NP2FFT {\n\n /**\n * Constructs a new NP2FFT object.\n * @param {number} fft_length The length of the FFT\n */\n constructor(fft_length) {\n // Helper variables\n const a = 2 * (fft_length - 1);\n const b = 2 * (2 * fft_length - 1);\n const nextP2 = 2 ** (Math.ceil(Math.log2(b)))\n this.bufferSize = nextP2;\n this._a = a;\n\n // Define buffers\n // Compute chirp for transform\n const chirp = new Float64Array(b);\n const ichirp = new Float64Array(nextP2);\n this._chirpBuffer = new Float64Array(nextP2);\n this._buffer1 = new Float64Array(nextP2);\n this._buffer2 = new Float64Array(nextP2);\n this._outBuffer1 = new Float64Array(nextP2);\n this._outBuffer2 = new Float64Array(nextP2);\n\n // Compute complex exponentiation\n const theta = -2 * Math.PI / fft_length;\n const baseR = Math.cos(theta);\n const baseI = Math.sin(theta);\n\n // Precompute helper for chirp-z transform\n for (let i = 0; i < b >> 1; ++i) {\n // Compute complex power:\n const e = (i + 1 - fft_length) ** 2 / 2.0;\n\n // Compute the modulus and argument of the result\n const result_mod = Math.sqrt(baseR ** 2 + baseI ** 2) ** e;\n const result_arg = e * Math.atan2(baseI, baseR);\n\n // Convert the result back to rectangular form\n // and assign to chirp and ichirp\n const i2 = 2 * i;\n chirp[i2] = result_mod * Math.cos(result_arg);\n chirp[i2 + 1] = result_mod * Math.sin(result_arg);\n\n // conjugate\n ichirp[i2] = chirp[i2];\n ichirp[i2 + 1] = - chirp[i2 + 1];\n }\n this._slicedChirpBuffer = chirp.subarray(a, b);\n\n // create object to perform Fast Fourier Transforms\n // with `nextP2` complex numbers\n this._f = new P2FFT(nextP2 >> 1);\n this._f.transform(this._chirpBuffer, ichirp);\n }\n\n _transform(output, input, real) {\n const ib1 = this._buffer1;\n const ib2 = this._buffer2;\n const ob2 = this._outBuffer1;\n const ob3 = this._outBuffer2;\n const cb = this._chirpBuffer;\n const sb = this._slicedChirpBuffer;\n const a = this._a;\n\n if (real) {\n // Real multiplication\n for (let j = 0; j < sb.length; j += 2) {\n const j2 = j + 1\n const j3 = j >> 1;\n\n const a_real = input[j3];\n ib1[j] = a_real * sb[j];\n ib1[j2] = a_real * sb[j2];\n }\n } else {\n // Complex multiplication\n for (let j = 0; j < sb.length; j += 2) {\n const j2 = j + 1\n ib1[j] = input[j] * sb[j] - input[j2] * sb[j2];\n ib1[j2] = input[j] * sb[j2] + input[j2] * sb[j];\n }\n }\n this._f.transform(ob2, ib1);\n\n for (let j = 0; j < cb.length; j += 2) {\n const j2 = j + 1;\n\n ib2[j] = ob2[j] * cb[j] - ob2[j2] * cb[j2];\n ib2[j2] = ob2[j] * cb[j2] + ob2[j2] * cb[j];\n }\n this._f.inverseTransform(ob3, ib2);\n\n for (let j = 0; j < ob3.length; j += 2) {\n const a_real = ob3[j + a];\n const a_imag = ob3[j + a + 1];\n const b_real = sb[j];\n const b_imag = sb[j + 1];\n\n output[j] = a_real * b_real - a_imag * b_imag;\n output[j + 1] = a_real * b_imag + a_imag * b_real;\n }\n }\n\n transform(output, input) {\n this._transform(output, input, false);\n }\n\n realTransform(output, input) {\n this._transform(output, input, true);\n }\n}\n\nexport class FFT {\n constructor(fft_length) {\n this.fft_length = fft_length;\n this.isPowerOfTwo = isPowerOfTwo(fft_length);\n if (this.isPowerOfTwo) {\n this.fft = new P2FFT(fft_length);\n this.outputBufferSize = 2 * fft_length;\n } else {\n this.fft = new NP2FFT(fft_length);\n this.outputBufferSize = this.fft.bufferSize;\n }\n }\n\n realTransform(out, input) {\n this.fft.realTransform(out, input);\n }\n\n transform(out, input) {\n this.fft.transform(out, input);\n }\n}\n\n\n/**\n * Performs median filter on the provided data. Padding is done by mirroring the data.\n * @param {AnyTypedArray} data The input array\n * @param {number} windowSize The window size\n */\nexport function medianFilter(data, windowSize) {\n\n if (windowSize % 2 === 0 || windowSize <= 0) {\n throw new Error('Window size must be a positive odd number');\n }\n\n // @ts-ignore\n const outputArray = new data.constructor(data.length);\n\n // @ts-ignore\n const buffer = new data.constructor(windowSize); // Reusable array for storing values\n\n const halfWindowSize = Math.floor(windowSize / 2);\n\n for (let i = 0; i < data.length; ++i) {\n let valuesIndex = 0;\n\n for (let j = -halfWindowSize; j <= halfWindowSize; ++j) {\n let index = i + j;\n if (index < 0) {\n index = Math.abs(index);\n } else if (index >= data.length) {\n index = 2 * (data.length - 1) - index;\n }\n\n buffer[valuesIndex++] = data[index];\n }\n\n buffer.sort();\n outputArray[i] = buffer[halfWindowSize];\n }\n\n return outputArray;\n}\n\n/**\n * Helper function to round a number to a given number of decimals\n * @param {number} num The number to round\n * @param {number} decimals The number of decimals\n * @returns {number} The rounded number\n */\nexport function round(num, decimals) {\n const pow = Math.pow(10, decimals);\n return Math.round(num * pow) / pow;\n}\n\n/**\n * Helper function to round a number to the nearest integer, with ties rounded to the nearest even number.\n * Also known as \"bankers' rounding\". This is the default rounding mode in python. For example:\n * 1.5 rounds to 2 and 2.5 rounds to 2.\n * \n * @param {number} x The number to round\n * @returns {number} The rounded number\n */\nexport function bankers_round(x) {\n const r = Math.round(x);\n const br = Math.abs(x) % 1 === 0.5 ? (r % 2 === 0 ? r : r - 1) : r;\n return br;\n}\n\n\n/**\n * Measures similarity between two temporal sequences (e.g., input audio and output tokens\n * to generate token-level timestamps).\n * @param {number[][]} matrix \n * @returns {number[][]}\n */\nexport function dynamic_time_warping(matrix) {\n const output_length = matrix.length;\n const input_length = matrix[0].length;\n\n const outputShape = [output_length + 1, input_length + 1];\n\n const cost = Array.from(\n { length: outputShape[0] },\n () => Array(outputShape[1]).fill(Infinity)\n );\n cost[0][0] = 0;\n\n const trace = Array.from(\n { length: outputShape[0] },\n () => Array(outputShape[1]).fill(-1)\n );\n\n for (let j = 1; j < outputShape[1]; ++j) {\n for (let i = 1; i < outputShape[0]; ++i) {\n const c0 = cost[i - 1][j - 1];\n const c1 = cost[i - 1][j];\n const c2 = cost[i][j - 1];\n\n let c, t;\n if (c0 < c1 && c0 < c2) {\n c = c0;\n t = 0;\n } else if (c1 < c0 && c1 < c2) {\n c = c1;\n t = 1;\n } else {\n c = c2;\n t = 2;\n }\n cost[i][j] = matrix[i - 1][j - 1] + c;\n trace[i][j] = t;\n }\n }\n\n for (let i = 0; i < outputShape[1]; ++i) { // trace[0, :] = 2\n trace[0][i] = 2;\n }\n for (let i = 0; i < outputShape[0]; ++i) { // trace[:, 0] = 1\n trace[i][0] = 1;\n }\n\n // backtrace\n let i = output_length;\n let j = input_length;\n let text_indices = [];\n let time_indices = [];\n while (i > 0 || j > 0) {\n text_indices.push(i - 1);\n time_indices.push(j - 1);\n\n switch (trace[i][j]) {\n case 0:\n --i; --j;\n break;\n case 1:\n --i;\n break;\n case 2:\n --j;\n break;\n default:\n throw new Error(\n `Internal error in dynamic time warping. Unexpected trace[${i}, ${j}]. Please file a bug report.`\n )\n }\n }\n\n text_indices.reverse();\n time_indices.reverse();\n\n return [text_indices, time_indices];\n\n}\n","/**\n * @file Helper module for `Tensor` processing.\n *\n * These functions and classes are only used internally,\n * meaning an end-user shouldn't need to access anything here.\n *\n * @module utils/tensor\n */\n\nimport {\n interpolate_data,\n permute_data\n} from './maths.js';\n\nimport {\n Tensor as ONNXTensor, isONNXTensor,\n} from '../backends/onnx.js';\n\nimport { TensorOpRegistry } from '../ops/registry.js';\n\nconst DataTypeMap = Object.freeze({\n float32: Float32Array,\n float16: Uint16Array,\n float64: Float64Array,\n string: Array, // string[]\n int8: Int8Array,\n uint8: Uint8Array,\n int16: Int16Array,\n uint16: Uint16Array,\n int32: Int32Array,\n uint32: Uint32Array,\n int64: BigInt64Array,\n uint64: BigUint64Array,\n bool: Uint8Array,\n});\n\n/**\n * @typedef {keyof typeof DataTypeMap} DataType\n * @typedef {import('./maths.js').AnyTypedArray | any[]} DataArray\n */\n\n\nexport class Tensor {\n /** @type {number[]} Dimensions of the tensor. */\n get dims() {\n // @ts-ignore\n return this.ort_tensor.dims;\n }\n set dims(value) {\n // FIXME: ONNXTensor declares dims as readonly so one needs to use the constructor() if dims change.\n // @ts-ignore\n this.ort_tensor.dims = value;\n }\n\n /** @type {DataType} Type of the tensor. */\n get type() {\n return this.ort_tensor.type;\n };\n\n /** @type {DataArray} The data stored in the tensor. */\n get data() {\n return this.ort_tensor.data;\n }\n\n /** @type {number} The number of elements in the tensor. */\n get size() {\n return this.ort_tensor.size;\n };\n\n /** @type {string} The location of the tensor data. */\n get location() {\n return this.ort_tensor.location;\n };\n\n ort_tensor;\n\n /**\n * Create a new Tensor or copy an existing Tensor.\n * @param {[DataType, DataArray, number[]]|[ONNXTensor]} args\n */\n constructor(...args) {\n if (isONNXTensor(args[0])) {\n this.ort_tensor = /** @type {ONNXTensor} */ (args[0]);\n } else {\n // Create new tensor\n this.ort_tensor = new ONNXTensor(\n /** @type {DataType} */(args[0]),\n /** @type {Exclude} */(args[1]),\n args[2]\n );\n }\n\n return new Proxy(this, {\n get: (obj, key) => {\n if (typeof key === 'string') {\n let index = Number(key);\n if (Number.isInteger(index)) {\n // key is an integer (i.e., index)\n return obj._getitem(index);\n }\n }\n // @ts-ignore\n return obj[key];\n },\n set: (obj, key, value) => {\n // TODO allow setting of data\n\n // @ts-ignore\n return obj[key] = value;\n }\n });\n }\n\n dispose() {\n this.ort_tensor.dispose();\n // this.ort_tensor = undefined;\n }\n\n /**\n * Returns an iterator object for iterating over the tensor data in row-major order.\n * If the tensor has more than one dimension, the iterator will yield subarrays.\n * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order.\n */\n *[Symbol.iterator]() {\n const [iterLength, ...iterDims] = this.dims;\n\n if (iterDims.length > 0) {\n const iterSize = iterDims.reduce((a, b) => a * b);\n for (let i = 0; i < iterLength; ++i) {\n yield this._subarray(i, iterSize, iterDims);\n }\n } else {\n yield* this.data\n }\n\n }\n\n /**\n * Index into a Tensor object.\n * @param {number} index The index to access.\n * @returns {Tensor} The data at the specified index.\n */\n _getitem(index) {\n const [iterLength, ...iterDims] = this.dims;\n\n index = safeIndex(index, iterLength);\n\n if (iterDims.length > 0) {\n const iterSize = iterDims.reduce((a, b) => a * b);\n return this._subarray(index, iterSize, iterDims);\n } else {\n return new Tensor(this.type, [this.data[index]], iterDims);\n }\n }\n\n /**\n * @param {number|bigint} item The item to search for in the tensor\n * @returns {number} The index of the first occurrence of item in the tensor data.\n */\n indexOf(item) {\n const this_data = this.data;\n for (let index = 0; index < this_data.length; ++index) {\n // Note: == instead of === so we can match Ints with BigInts\n if (this_data[index] == item) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * @param {number} index\n * @param {number} iterSize\n * @param {any} iterDims\n * @returns {Tensor}\n */\n _subarray(index, iterSize, iterDims) {\n const o1 = index * iterSize;\n const o2 = (index + 1) * iterSize;\n\n // We use subarray if available (typed array), otherwise we use slice (normal array)\n const data =\n ('subarray' in this.data)\n ? this.data.subarray(o1, o2)\n : this.data.slice(o1, o2);\n return new Tensor(this.type, data, iterDims);\n }\n\n /**\n * Returns the value of this tensor as a standard JavaScript Number. This only works\n * for tensors with one element. For other cases, see `Tensor.tolist()`.\n * @returns {number|bigint} The value of this tensor as a standard JavaScript Number.\n * @throws {Error} If the tensor has more than one element.\n */\n item() {\n const this_data = this.data;\n if (this_data.length !== 1) {\n throw new Error(`a Tensor with ${this_data.length} elements cannot be converted to Scalar`);\n }\n return this_data[0];\n }\n\n /**\n * Convert tensor data to a n-dimensional JS list\n * @returns {Array}\n */\n tolist() {\n return reshape(this.data, this.dims)\n }\n\n /**\n * Return a new Tensor with the sigmoid function applied to each element.\n * @returns {Tensor} The tensor with the sigmoid function applied.\n */\n sigmoid() {\n return this.clone().sigmoid_();\n }\n\n /**\n * Applies the sigmoid function to the tensor in place.\n * @returns {Tensor} Returns `this`.\n */\n sigmoid_() {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = 1 / (1 + Math.exp(-this_data[i]));\n }\n return this;\n }\n\n /**\n * Return a new Tensor with a callback function applied to each element.\n * @param {Function} callback - The function to apply to each element. It should take three arguments:\n * the current element, its index, and the tensor's data array.\n * @returns {Tensor} A new Tensor with the callback function applied to each element.\n */\n map(callback) {\n return this.clone().map_(callback);\n }\n\n /**\n * Apply a callback function to each element of the tensor in place.\n * @param {Function} callback - The function to apply to each element. It should take three arguments:\n * the current element, its index, and the tensor's data array.\n * @returns {Tensor} Returns `this`.\n */\n map_(callback) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = callback(this_data[i], i, this_data);\n }\n return this;\n }\n\n /**\n * Return a new Tensor with every element multiplied by a constant.\n * @param {number} val The value to multiply by.\n * @returns {Tensor} The new tensor.\n */\n mul(val) {\n return this.clone().mul_(val);\n }\n\n /**\n * Multiply the tensor by a constant in place.\n * @param {number} val The value to multiply by.\n * @returns {Tensor} Returns `this`.\n */\n mul_(val) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] *= val;\n }\n return this;\n }\n\n /**\n * Return a new Tensor with every element divided by a constant.\n * @param {number} val The value to divide by.\n * @returns {Tensor} The new tensor.\n */\n div(val) {\n return this.clone().div_(val);\n }\n\n /**\n * Divide the tensor by a constant in place.\n * @param {number} val The value to divide by.\n * @returns {Tensor} Returns `this`.\n */\n div_(val) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] /= val;\n }\n return this;\n }\n\n /**\n * Return a new Tensor with every element added by a constant.\n * @param {number} val The value to add by.\n * @returns {Tensor} The new tensor.\n */\n add(val) {\n return this.clone().add_(val);\n }\n\n /**\n * Add the tensor by a constant in place.\n * @param {number} val The value to add by.\n * @returns {Tensor} Returns `this`.\n */\n add_(val) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] += val;\n }\n return this;\n }\n\n /**\n * Return a new Tensor with every element subtracted by a constant.\n * @param {number} val The value to subtract by.\n * @returns {Tensor} The new tensor.\n */\n sub(val) {\n return this.clone().sub_(val);\n }\n\n /**\n * Subtract the tensor by a constant in place.\n * @param {number} val The value to subtract by.\n * @returns {Tensor} Returns `this`.\n */\n sub_(val) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] -= val;\n }\n return this;\n }\n\n clone() {\n return new Tensor(this.type, this.data.slice(), this.dims.slice());\n }\n\n slice(...slices) {\n // This allows for slicing with ranges and numbers\n const newTensorDims = [];\n const newOffsets = [];\n\n // slices is an array of numbers or arrays of numbers\n // e.g., slices = [0, [1, 3], null, [0, 3]]\n for (let sliceIndex = 0; sliceIndex < this.dims.length; ++sliceIndex) {\n let slice = slices[sliceIndex];\n\n if (slice === null || slice === undefined) {\n // null or undefined means take the whole dimension\n newOffsets.push([0, this.dims[sliceIndex]]);\n newTensorDims.push(this.dims[sliceIndex]);\n\n } else if (typeof slice === 'number') {\n slice = safeIndex(slice, this.dims[sliceIndex], sliceIndex);\n\n // A number means take a single element\n newOffsets.push([slice, slice + 1]);\n\n } else if (Array.isArray(slice) && slice.length === 2) {\n // An array of length 2 means take a range of elements\n let [start, end] = slice;\n start = start === null\n ? 0\n : safeIndex(start, this.dims[sliceIndex], sliceIndex, false);\n end = end === null\n ? this.dims[sliceIndex]\n : safeIndex(end, this.dims[sliceIndex], sliceIndex, false);\n\n if (start > end) {\n throw new Error(`Invalid slice: ${slice}`);\n }\n\n const offsets = [\n Math.max(start, 0),\n Math.min(end, this.dims[sliceIndex])\n ];\n\n newOffsets.push(offsets);\n newTensorDims.push(offsets[1] - offsets[0]);\n\n } else {\n throw new Error(`Invalid slice: ${slice}`);\n }\n }\n\n const newDims = newOffsets.map(([start, end]) => end - start);\n const newBufferSize = newDims.reduce((a, b) => a * b);\n\n const this_data = this.data;\n // Allocate memory\n // @ts-ignore\n const data = new this_data.constructor(newBufferSize);\n\n // Precompute strides\n const stride = this.stride();\n\n for (let i = 0; i < newBufferSize; ++i) {\n let originalIndex = 0;\n for (let j = newDims.length - 1, num = i; j >= 0; --j) {\n const size = newDims[j];\n originalIndex += ((num % size) + newOffsets[j][0]) * stride[j];\n num = Math.floor(num / size);\n }\n data[i] = this_data[originalIndex];\n }\n return new Tensor(this.type, data, newTensorDims);\n\n }\n\n /**\n * Return a permuted version of this Tensor, according to the provided dimensions.\n * @param {...number} dims Dimensions to permute.\n * @returns {Tensor} The permuted tensor.\n */\n permute(...dims) {\n return permute(this, dims);\n }\n\n // TODO: implement transpose. For now (backwards compatibility), it's just an alias for permute()\n transpose(...dims) {\n return this.permute(...dims);\n }\n\n // TODO add .max() and .min() methods\n\n /**\n * Returns the sum of each row of the input tensor in the given dimension dim.\n *\n * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced.\n * @param {boolean} keepdim Whether the output tensor has `dim` retained or not.\n * @returns The summed tensor\n */\n sum(dim = null, keepdim = false) {\n return this.norm(1, dim, keepdim);\n }\n\n /**\n * Returns the matrix norm or vector norm of a given tensor.\n * @param {number|string} [p='fro'] The order of norm\n * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across.\n * If dim is None, the norm will be calculated across all dimensions of input.\n * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not.\n * @returns {Tensor} The norm of the tensor.\n */\n norm(p = 'fro', dim = null, keepdim = false) {\n if (p === 'fro') {\n // NOTE: Since we only support integer dims, Frobenius norm produces the same result as p=2.\n p = 2;\n } else if (typeof p === 'string') {\n throw Error(`Unsupported norm: ${p}`);\n }\n\n const this_data = this.data;\n\n if (dim === null) {\n // @ts-ignore\n let val = this_data.reduce((a, b) => a + (b ** p), 0) ** (1 / p);\n return new Tensor(this.type, [val], []);\n }\n\n // Negative indexing\n dim = safeIndex(dim, this.dims.length);\n\n // Calculate the shape of the resulting array after summation\n const resultDims = this.dims.slice(); // Copy the original dimensions\n resultDims[dim] = 1; // Remove the specified axis\n\n // Create a new array to store the accumulated values\n // @ts-ignore\n const result = new this_data.constructor(this_data.length / this.dims[dim]);\n\n // Iterate over the data array\n for (let i = 0; i < this_data.length; ++i) {\n\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = this.dims[j];\n if (j !== dim) {\n const index = num % size;\n resultIndex += index * resultMultiplier;\n resultMultiplier *= resultDims[j];\n }\n num = Math.floor(num / size);\n }\n\n // Accumulate the value at the current index\n result[resultIndex] += (this_data[i]) ** p;\n }\n\n if (p !== 1) {\n for (let i = 0; i < result.length; ++i) {\n result[i] = result[i] ** (1 / p);\n }\n }\n\n if (!keepdim) {\n resultDims.splice(dim, 1);\n }\n\n return new Tensor(this.type, result, resultDims);\n }\n\n /**\n * Performs `L_p` normalization of inputs over specified dimension. Operates in place.\n * @param {number} [p=2] The exponent value in the norm formulation\n * @param {number} [dim=1] The dimension to reduce\n * @returns {Tensor} `this` for operation chaining.\n */\n normalize_(p = 2.0, dim = 1) {\n dim = safeIndex(dim, this.dims.length);\n\n const norm = this.norm(p, dim, true);\n\n const this_data = this.data;\n const norm_data = norm.data;\n for (let i = 0; i < this_data.length; ++i) {\n\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = this.dims[j];\n if (j !== dim) {\n const index = num % size;\n resultIndex += index * resultMultiplier;\n resultMultiplier *= this.dims[j];\n }\n num = Math.floor(num / size);\n }\n\n // Divide by normalized value\n this_data[i] /= norm_data[resultIndex];\n }\n\n return this;\n }\n\n /**\n * Performs `L_p` normalization of inputs over specified dimension.\n * @param {number} [p=2] The exponent value in the norm formulation\n * @param {number} [dim=1] The dimension to reduce\n * @returns {Tensor} The normalized tensor.\n */\n normalize(p = 2.0, dim = 1) {\n return this.clone().normalize_(p, dim);\n }\n\n /**\n * Compute and return the stride of this tensor.\n * Stride is the jump necessary to go from one element to the next one in the specified dimension dim.\n * @returns {number[]} The stride of this tensor.\n */\n stride() {\n return dimsToStride(this.dims);\n }\n\n /**\n * Returns a tensor with all specified dimensions of input of size 1 removed.\n *\n * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other.\n * If you would like a copy, use `tensor.clone()` before squeezing.\n *\n * @param {number} [dim=null] If given, the input will be squeezed only in the specified dimensions.\n * @returns {Tensor} The squeezed tensor\n */\n squeeze(dim = null) {\n return new Tensor(\n this.type,\n this.data,\n calc_squeeze_dims(this.dims, dim)\n )\n }\n\n /**\n * In-place version of @see {@link Tensor.squeeze}\n */\n squeeze_(dim = null) {\n this.dims = calc_squeeze_dims(this.dims, dim);\n return this;\n }\n\n /**\n * Returns a new tensor with a dimension of size one inserted at the specified position.\n *\n * NOTE: The returned tensor shares the same underlying data with this tensor.\n *\n * @param {number} dim The index at which to insert the singleton dimension\n * @returns {Tensor} The unsqueezed tensor\n */\n unsqueeze(dim = null) {\n return new Tensor(\n this.type,\n this.data,\n calc_unsqueeze_dims(this.dims, dim)\n );\n }\n\n /**\n * In-place version of @see {@link Tensor.unsqueeze}\n */\n unsqueeze_(dim = null) {\n this.dims = calc_unsqueeze_dims(this.dims, dim);\n return this;\n }\n\n /**\n * In-place version of @see {@link Tensor.flatten}\n */\n flatten_(start_dim = 0, end_dim = -1) {\n // TODO validate inputs\n end_dim = (end_dim + this.dims.length) % this.dims.length;\n\n let dimsToKeepBefore = this.dims.slice(0, start_dim);\n let dimsToFlatten = this.dims.slice(start_dim, end_dim + 1);\n let dimsToKeepAfter = this.dims.slice(end_dim + 1);\n\n this.dims = [...dimsToKeepBefore, dimsToFlatten.reduce((a, b) => a * b, 1), ...dimsToKeepAfter]\n return this;\n }\n\n /**\n * Flattens input by reshaping it into a one-dimensional tensor.\n * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim`\n * and ending with `end_dim` are flattened. The order of elements in input is unchanged.\n * @param {number} start_dim the first dim to flatten\n * @param {number} end_dim the last dim to flatten\n * @returns {Tensor} The flattened tensor.\n */\n flatten(start_dim = 0, end_dim = -1) {\n return this.clone().flatten_(start_dim, end_dim);\n }\n\n /**\n * Returns a new tensor with the same data as the `self` tensor but of a different `shape`.\n * @param {...number} dims the desired size\n * @returns {Tensor} The tensor with the same data but different shape\n */\n view(...dims) {\n // TODO: validate dims\n let inferredIndex = -1;\n for (let i = 0; i < dims.length; ++i) {\n if (dims[i] === -1) {\n if (inferredIndex !== -1) {\n throw new Error(\"Only one dimension can be inferred\");\n }\n inferredIndex = i;\n }\n }\n\n const this_data = this.data;\n if (inferredIndex !== -1) {\n // Some dimension must be inferred\n const productOther = dims.reduce((product, curr, index) => {\n return index !== inferredIndex ? product * curr : product\n }, 1);\n\n dims[inferredIndex] = this_data.length / productOther;\n }\n return new Tensor(this.type, this_data, dims); // NOTE: uses same underlying storage\n }\n\n neg_() {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = -this_data[i];\n }\n return this;\n }\n neg() {\n return this.clone().neg_();\n }\n\n /**\n * In-place version of @see {@link Tensor.clamp}\n */\n clamp_(min, max) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = Math.min(Math.max(this_data[i], min), max);\n }\n return this;\n }\n\n /**\n * Clamps all elements in input into the range [ min, max ]\n * @param {number} min lower-bound of the range to be clamped to\n * @param {number} max upper-bound of the range to be clamped to\n * @returns {Tensor} the output tensor.\n */\n clamp(min, max) {\n return this.clone().clamp_(min, max);\n }\n\n /**\n * In-place version of @see {@link Tensor.round}\n */\n round_() {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = Math.round(this_data[i]);\n }\n return this;\n }\n\n /**\n * Rounds elements of input to the nearest integer.\n * @returns {Tensor} the output tensor.\n */\n round() {\n return this.clone().round_();\n }\n\n mean(dim = null, keepdim = false) {\n return mean(this, dim, keepdim);\n }\n\n /**\n * Performs Tensor dtype conversion.\n * @param {DataType} type The desired data type.\n * @returns {Tensor} The converted tensor.\n */\n to(type) {\n // If the self Tensor already has the correct dtype, then self is returned.\n if (this.type === type) return this;\n\n // Otherwise, the returned tensor is a copy of self with the desired dtype.\n if (!DataTypeMap.hasOwnProperty(type)) {\n throw new Error(`Unsupported type: ${type}`);\n }\n // @ts-ignore\n return new Tensor(type, DataTypeMap[type].from(this.data), this.dims);\n }\n}\n\n/**\n * This creates a nested array of a given type and depth (see examples).\n *\n * @example\n * NestArray; // string[]\n * @example\n * NestArray; // number[][]\n * @example\n * NestArray; // string[][][] etc.\n * @template T\n * @template {number} Depth\n * @template {never[]} [Acc=[]]\n * @typedef {Acc['length'] extends Depth ? T : NestArray} NestArray\n */\n\n/**\n * Reshapes a 1-dimensional array into an n-dimensional array, according to the provided dimensions.\n *\n * @example\n * reshape([10 ], [1 ]); // Type: number[] Value: [10]\n * reshape([1, 2, 3, 4 ], [2, 2 ]); // Type: number[][] Value: [[1, 2], [3, 4]]\n * reshape([1, 2, 3, 4, 5, 6, 7, 8], [2, 2, 2]); // Type: number[][][] Value: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]\n * reshape([1, 2, 3, 4, 5, 6, 7, 8], [4, 2 ]); // Type: number[][] Value: [[1, 2], [3, 4], [5, 6], [7, 8]]\n * @param {T[]|DataArray} data The input array to reshape.\n * @param {DIM} dimensions The target shape/dimensions.\n * @template T\n * @template {[number]|number[]} DIM\n * @returns {NestArray} The reshaped array.\n */\nfunction reshape(data, dimensions) {\n\n const totalElements = data.length;\n const dimensionSize = dimensions.reduce((a, b) => a * b);\n\n if (totalElements !== dimensionSize) {\n throw Error(`cannot reshape array of size ${totalElements} into shape (${dimensions})`);\n }\n\n /** @type {any} */\n let reshapedArray = data;\n\n for (let i = dimensions.length - 1; i >= 0; i--) {\n reshapedArray = reshapedArray.reduce((acc, val) => {\n let lastArray = acc[acc.length - 1];\n\n if (lastArray.length < dimensions[i]) {\n lastArray.push(val);\n } else {\n acc.push([val]);\n }\n\n return acc;\n }, [[]]);\n }\n\n return reshapedArray[0];\n}\n\n/**\n * Permutes a tensor according to the provided axes.\n * @param {any} tensor The input tensor to permute.\n * @param {Array} axes The axes to permute the tensor along.\n * @returns {Tensor} The permuted tensor.\n */\nexport function permute(tensor, axes) {\n const [permutedData, shape] = permute_data(tensor.data, tensor.dims, axes);\n return new Tensor(tensor.type, permutedData, shape);\n}\n\n\n/**\n * Interpolates an Tensor to the given size.\n * @param {Tensor} input The input tensor to interpolate. Data must be channel-first (i.e., [c, h, w])\n * @param {number[]} size The output size of the image\n * @param {string} mode The interpolation mode\n * @param {boolean} align_corners Whether to align corners.\n * @returns {Tensor} The interpolated tensor.\n */\nexport function interpolate(input, [out_height, out_width], mode = 'bilinear', align_corners = false) {\n\n // Input image dimensions\n const in_channels = input.dims.at(-3) ?? 1;\n const in_height = input.dims.at(-2);\n const in_width = input.dims.at(-1);\n\n let output = interpolate_data(\n /** @type {import('./maths.js').TypedArray}*/(input.data),\n [in_channels, in_height, in_width],\n [out_height, out_width],\n mode,\n align_corners\n );\n return new Tensor(input.type, output, [in_channels, out_height, out_width]);\n}\n\n\n/**\n * Down/up samples the input.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html.\n * @param {Tensor} input the input tensor\n * @param {Object} options the options for the interpolation\n * @param {[number, number]|[number, number, number]|[number, number, number, number]} [options.size=null] output spatial size.\n * @param {\"bilinear\"|\"bicubic\"} [options.mode='bilinear'] algorithm used for upsampling\n * @returns {Promise} The interpolated tensor.\n */\nexport async function interpolate_4d(input, {\n size = null,\n mode = 'bilinear',\n} = {}) {\n\n // Error checking\n if (input.dims.length !== 4) {\n throw new Error('`interpolate_4d` currently only supports 4D input.');\n }\n if (!size) {\n // TODO: support scale_factor\n throw new Error('`interpolate_4d` requires a `size` argument.');\n }\n\n // Fill in missing dimensions\n let targetDims;\n if (size.length === 2) {\n targetDims = [...input.dims.slice(0, 2), ...size];\n } else if (size.length === 3) {\n targetDims = [input.dims[0], ...size];\n } else if (size.length === 4) {\n targetDims = size;\n } else {\n throw new Error('`size` must be of length 2, 3, or 4.');\n }\n\n let op;\n if (mode === 'bilinear') {\n op = await TensorOpRegistry.bilinear_interpolate_4d;\n } else if (mode === 'bicubic') {\n op = await TensorOpRegistry.bicubic_interpolate_4d;\n } else {\n throw new Error(`Unsupported mode: ${mode}`);\n }\n\n const sizeTensor = new Tensor('int64', new BigInt64Array(targetDims.map(BigInt)), [targetDims.length]);\n return await op({ x: input, s: sizeTensor });\n}\n\n/**\n * Matrix product of two tensors.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.matmul.html\n * @param {Tensor} a the first tensor to be multiplied\n * @param {Tensor} b the second tensor to be multiplied\n * @returns {Promise} The matrix product of the two tensors.\n */\nexport async function matmul(a, b) {\n const op = await TensorOpRegistry.matmul;\n return await op({ a, b });\n}\n\n/**\n * Computes the one dimensional Fourier transform of real-valued input.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.fft.rfft.html\n * @param {Tensor} x the real input tensor\n * @param {Tensor} a The dimension along which to take the one dimensional real FFT.\n * @returns {Promise} the output tensor.\n */\nexport async function rfft(x, a) {\n const op = await TensorOpRegistry.rfft;\n return await op({ x, a });\n}\n\n\n/**\n * Returns the k largest elements of the given input tensor.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.topk.html\n * @param {Tensor} x the input tensor\n * @param {number} k the k in \"top-k\"\n * @returns {Promise<[Tensor, Tensor]>} the output tuple of (Tensor, LongTensor) of top-k elements and their indices.\n */\nexport async function topk(x, k) {\n const op = await TensorOpRegistry.top_k;\n\n if (k === null) {\n k = x.dims.at(-1);\n } else {\n k = Math.min(k, x.dims.at(-1));\n }\n return await op({\n x,\n k: new Tensor(\n 'int64',\n [BigInt(k)],\n [1]\n )\n });\n}\n\n/**\n * Perform mean pooling of the last hidden state followed by a normalization step.\n * @param {Tensor} last_hidden_state Tensor of shape [batchSize, seqLength, embedDim]\n * @param {Tensor} attention_mask Tensor of shape [batchSize, seqLength]\n * @returns {Tensor} Returns a new Tensor of shape [batchSize, embedDim].\n */\nexport function mean_pooling(last_hidden_state, attention_mask) {\n // last_hidden_state: [batchSize, seqLength, embedDim]\n // attention_mask: [batchSize, seqLength]\n const lastHiddenStateData = last_hidden_state.data;\n const attentionMaskData = attention_mask.data;\n\n const shape = [last_hidden_state.dims[0], last_hidden_state.dims[2]];\n\n // @ts-ignore\n const returnedData = new lastHiddenStateData.constructor(shape[0] * shape[1]);\n const [batchSize, seqLength, embedDim] = last_hidden_state.dims;\n\n let outIndex = 0;\n for (let i = 0; i < batchSize; ++i) {\n const offset = i * embedDim * seqLength;\n\n for (let k = 0; k < embedDim; ++k) {\n let sum = 0;\n let count = 0;\n\n const attnMaskOffset = i * seqLength;\n const offset2 = offset + k;\n // Pool over all words in sequence\n for (let j = 0; j < seqLength; ++j) {\n // index into attention mask\n const attn = Number(attentionMaskData[attnMaskOffset + j]);\n\n count += attn;\n sum += lastHiddenStateData[offset2 + j * embedDim] * attn;\n }\n\n const avg = sum / count;\n returnedData[outIndex++] = avg;\n }\n }\n\n return new Tensor(\n last_hidden_state.type,\n returnedData,\n shape\n )\n}\n\n/**\n * Apply Layer Normalization for last certain number of dimensions.\n * @param {Tensor} input The input tensor\n * @param {number[]} normalized_shape input shape from an expected input of size\n * @param {Object} options The options for the layer normalization\n * @param {number} [options.eps=1e-5] A value added to the denominator for numerical stability.\n * @returns {Tensor} The normalized tensor.\n */\nexport function layer_norm(input, normalized_shape, {\n eps = 1e-5,\n} = {}) {\n if (input.dims.length !== 2) {\n throw new Error('`layer_norm` currently only supports 2D input.');\n }\n\n const [batchSize, featureDim] = input.dims;\n\n if (normalized_shape.length !== 1 && normalized_shape[0] !== featureDim) {\n throw new Error('`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.');\n }\n\n const [std, mean] = std_mean(input, 1, 0, true);\n const stdData = /** @type {Float32Array} */(std.data);\n const meanData = /** @type {Float32Array} */(mean.data);\n\n const inputData = /** @type {Float32Array} */(input.data);\n\n // @ts-ignore\n const returnedData = new inputData.constructor(inputData.length);\n\n for (let i = 0; i < batchSize; ++i) {\n const offset = i * featureDim;\n for (let j = 0; j < featureDim; ++j) {\n const offset2 = offset + j;\n returnedData[offset2] = (inputData[offset2] - meanData[i]) / (stdData[i] + eps);\n }\n }\n return new Tensor(input.type, returnedData, input.dims);\n}\n\n/**\n * Helper function to calculate new dimensions when performing a squeeze operation.\n * @param {number[]} dims The dimensions of the tensor.\n * @param {number|number[]|null} dim The dimension(s) to squeeze.\n * @returns {number[]} The new dimensions.\n * @private\n */\nfunction calc_squeeze_dims(dims, dim) {\n dims = dims.slice();\n if (dim === null) {\n dims = dims.filter((d) => d !== 1);\n } else if (typeof dim === 'number') {\n if (dims[dim] === 1) {\n dims.splice(dim, 1);\n }\n } else if (Array.isArray(dim)) {\n dims = dims.filter((x, i) => {\n return x !== 1 || !dim.includes(i);\n });\n }\n return dims;\n}\n\n/**\n * Helper function to calculate new dimensions when performing an unsqueeze operation.\n * @param {number[]} dims The dimensions of the tensor.\n * @param {number} dim The dimension to unsqueeze.\n * @returns {number[]} The new dimensions.\n * @private\n */\nfunction calc_unsqueeze_dims(dims, dim) {\n // Dimension out of range (e.g., \"expected to be in range of [-4, 3], but got 4\")\n // + 1 since we allow inserting at the end (i.e. dim = -1)\n dim = safeIndex(dim, dims.length + 1);\n dims = dims.slice();\n // Insert 1 into specified dimension\n dims.splice(dim, 0, 1);\n return dims;\n}\n\n/**\n * Safely calculate the index for an array of a given size, allowing negative indexing.\n * @param {number} index The index that will be used.\n * @param {number} size The size of the array.\n * @param {number} [dimension=null] The dimension that the index is for (optional).\n * @returns {number} The index, guaranteed to be non-negative and less than `arrayLength`.\n *\n * @throws {Error} If the index is out of range.\n * @private\n */\nfunction safeIndex(index, size, dimension = null, boundsCheck = true) {\n if (boundsCheck && (index < -size || index >= size)) {\n throw new Error(`IndexError: index ${index} is out of bounds for dimension${dimension === null ? '' : ' ' + dimension} with size ${size}`);\n }\n\n if (index < 0) {\n // Negative indexing, ensuring positive index\n index = ((index % size) + size) % size;\n }\n return index;\n}\n\n/**\n * Concatenates an array of tensors along a specified dimension.\n * @param {Tensor[]} tensors The array of tensors to concatenate.\n * @param {number} dim The dimension to concatenate along.\n * @returns {Tensor} The concatenated tensor.\n */\nexport function cat(tensors, dim = 0) {\n dim = safeIndex(dim, tensors[0].dims.length);\n\n // TODO do validation of shapes\n\n const resultDims = tensors[0].dims.slice();\n resultDims[dim] = tensors.reduce((a, b) => a + b.dims[dim], 0);\n\n // Create a new array to store the accumulated values\n const resultSize = resultDims.reduce((a, b) => a * b, 1);\n // @ts-ignore\n const result = new tensors[0].data.constructor(resultSize);\n\n // Create output tensor of same type as first\n const resultType = tensors[0].type;\n\n if (dim === 0) {\n // Handle special case for performance reasons\n\n let offset = 0;\n for (const tensor of tensors) {\n const tensorData = tensor.data;\n result.set(tensorData, offset);\n offset += tensorData.length;\n }\n\n } else {\n\n let currentDim = 0;\n\n for (let t = 0; t < tensors.length; ++t) {\n const { data, dims } = tensors[t];\n\n // Iterate over the data array\n for (let i = 0; i < data.length; ++i) {\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = dims[j];\n let index = num % size;\n if (j === dim) {\n index += currentDim;\n }\n resultIndex += index * resultMultiplier;\n resultMultiplier *= resultDims[j];\n num = Math.floor(num / size);\n }\n // Accumulate the value at the current index\n result[resultIndex] = data[i];\n }\n\n currentDim += dims[dim];\n }\n }\n return new Tensor(resultType, result, resultDims);\n}\n\n/**\n * Stack an array of tensors along a specified dimension.\n * @param {Tensor[]} tensors The array of tensors to stack.\n * @param {number} dim The dimension to stack along.\n * @returns {Tensor} The stacked tensor.\n */\nexport function stack(tensors, dim = 0) {\n // TODO do validation of shapes\n // NOTE: stack expects each tensor to be equal size\n return cat(tensors.map(t => t.unsqueeze(dim)), dim);\n}\n\n\n/**\n * Calculates the standard deviation and mean over the dimensions specified by dim. dim can be a single dimension or `null` to reduce over all dimensions.\n * @param {Tensor} input the input tenso\n * @param {number|null} dim the dimension to reduce. If None, all dimensions are reduced.\n * @param {number} correction difference between the sample size and sample degrees of freedom. Defaults to Bessel's correction, correction=1.\n * @param {boolean} keepdim whether the output tensor has dim retained or not.\n * @returns {Tensor[]} A tuple of (std, mean) tensors.\n */\nexport function std_mean(input, dim = null, correction = 1, keepdim = false) {\n const inputData = /** @type {Float32Array} */(input.data);\n const inputDims = input.dims;\n\n if (dim === null) {\n // None to reduce over all dimensions.\n const sum = inputData.reduce((a, b) => a + b, 0);\n const mean = sum / inputData.length;\n const std = Math.sqrt(inputData.reduce((a, b) => a + (b - mean) ** 2, 0) / (inputData.length - correction));\n\n const meanTensor = new Tensor(input.type, [mean], [/* scalar */]);\n const stdTensor = new Tensor(input.type, [std], [/* scalar */]);\n\n return [stdTensor, meanTensor];\n }\n\n // Negative indexing\n dim = safeIndex(dim, inputDims.length);\n\n const meanTensor = mean(input, dim, keepdim);\n const meanTensorData = meanTensor.data;\n\n // Calculate the shape of the resulting array after summation\n const resultDims = inputDims.slice(); // Copy the original dimensions\n resultDims[dim] = 1; // Remove the specified axis\n\n // Create a new array to store the accumulated values\n // @ts-ignore\n const result = new inputData.constructor(inputData.length / inputDims[dim]);\n\n // Iterate over the data array\n for (let i = 0; i < inputData.length; ++i) {\n\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = inputDims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = inputDims[j];\n if (j !== dim) {\n const index = num % size;\n resultIndex += index * resultMultiplier;\n resultMultiplier *= resultDims[j];\n }\n num = Math.floor(num / size);\n }\n\n // Accumulate the value at the current index\n result[resultIndex] += (inputData[i] - meanTensorData[resultIndex]) ** 2;\n }\n\n for (let i = 0; i < result.length; ++i) {\n result[i] = Math.sqrt(result[i] / (inputDims[dim] - correction));\n }\n\n if (!keepdim) {\n resultDims.splice(dim, 1);\n }\n\n const stdTensor = new Tensor(input.type, result, resultDims);\n\n return [stdTensor, meanTensor];\n}\n\n\n/**\n * Returns the mean value of each row of the input tensor in the given dimension dim.\n * @param {Tensor} input the input tensor.\n * @param {number|null} dim the dimension to reduce.\n * @param {boolean} keepdim whether the output tensor has dim retained or not.\n * @returns {Tensor} A new tensor with means taken along the specified dimension.\n */\nexport function mean(input, dim = null, keepdim = false) {\n const inputData = /** @type {Float32Array} */(input.data);\n\n if (dim === null) {\n // None to reduce over all dimensions.\n // @ts-ignore\n const val = inputData.reduce((a, b) => a + b, 0);\n return new Tensor(input.type, [val / inputData.length], [/* scalar */]);\n }\n const inputDims = input.dims;\n\n // Negative indexing\n dim = safeIndex(dim, inputDims.length);\n\n // Calculate the shape of the resulting array after summation\n const resultDims = inputDims.slice(); // Copy the original dimensions\n resultDims[dim] = 1; // Remove the specified axis\n\n // Create a new array to store the accumulated values\n // @ts-ignore\n const result = new inputData.constructor(inputData.length / inputDims[dim]);\n\n // Iterate over the data array\n for (let i = 0; i < inputData.length; ++i) {\n\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = inputDims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = inputDims[j];\n if (j !== dim) {\n const index = num % size;\n resultIndex += index * resultMultiplier;\n resultMultiplier *= resultDims[j];\n }\n num = Math.floor(num / size);\n }\n\n // Accumulate the value at the current index\n result[resultIndex] += inputData[i];\n }\n\n if (inputDims[dim] !== 1) {\n for (let i = 0; i < result.length; ++i) {\n result[i] = result[i] / inputDims[dim];\n }\n }\n\n if (!keepdim) {\n resultDims.splice(dim, 1);\n }\n\n return new Tensor(input.type, result, resultDims);\n}\n\n\nfunction dimsToStride(dims) {\n const stride = new Array(dims.length);\n for (let i = dims.length - 1, s2 = 1; i >= 0; --i) {\n stride[i] = s2;\n s2 *= dims[i];\n }\n return stride;\n}\n\nfunction fullHelper(size, fill_value, dtype, cls) {\n const numElements = size.reduce((a, b) => a * b, 1);\n return new Tensor(\n dtype,\n new cls(numElements).fill(fill_value),\n size\n )\n}\n\n/**\n * Creates a tensor of size size filled with fill_value. The tensor's dtype is inferred from fill_value.\n * @param {number[]} size A sequence of integers defining the shape of the output tensor.\n * @param {number|bigint} fill_value The value to fill the output tensor with.\n * @returns {Tensor} The filled tensor.\n */\nexport function full(size, fill_value) {\n let dtype;\n let typedArrayCls;\n if (typeof fill_value === 'number') {\n dtype = 'float32';\n typedArrayCls = Float32Array;\n } else if (typeof fill_value === 'bigint') {\n dtype = 'int64';\n typedArrayCls = BigInt64Array;\n } else {\n // TODO: support other dtypes\n throw new Error(`Unsupported data type: ${typeof fill_value}`);\n }\n return fullHelper(size, fill_value, dtype, typedArrayCls);\n}\n\nexport function full_like(tensor, fill_value) {\n return full(tensor.dims, fill_value);\n}\n\n/**\n * Returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size.\n * @param {number[]} size A sequence of integers defining the shape of the output tensor.\n * @returns {Tensor} The ones tensor.\n */\nexport function ones(size) {\n return fullHelper(size, 1n, 'int64', BigInt64Array);\n}\n\n/**\n * Returns a tensor filled with the scalar value 1, with the same size as input.\n * @param {Tensor} tensor The size of input will determine size of the output tensor.\n * @returns {Tensor} The ones tensor.\n */\nexport function ones_like(tensor) {\n return ones(tensor.dims);\n}\n\n/**\n * Returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size.\n * @param {number[]} size A sequence of integers defining the shape of the output tensor.\n * @returns {Tensor} The zeros tensor.\n */\nexport function zeros(size) {\n return fullHelper(size, 0n, 'int64', BigInt64Array);\n}\n\n/**\n * Returns a tensor filled with the scalar value 0, with the same size as input.\n * @param {Tensor} tensor The size of input will determine size of the output tensor.\n * @returns {Tensor} The zeros tensor.\n */\nexport function zeros_like(tensor) {\n return zeros(tensor.dims);\n}\n\n/**\n * Quantizes the embeddings tensor to binary or unsigned binary precision.\n * @param {Tensor} tensor The tensor to quantize.\n * @param {'binary'|'ubinary'} precision The precision to use for quantization.\n * @returns {Tensor} The quantized tensor.\n */\nexport function quantize_embeddings(tensor, precision) {\n if (tensor.dims.length !== 2) {\n throw new Error(\"The tensor must have 2 dimensions\");\n }\n if (tensor.dims.at(-1) % 8 !== 0) {\n throw new Error(\"The last dimension of the tensor must be a multiple of 8\");\n }\n if (!['binary', 'ubinary'].includes(precision)) {\n throw new Error(\"The precision must be either 'binary' or 'ubinary'\");\n }\n\n const signed = precision === 'binary';\n const dtype = signed ? 'int8' : 'uint8';\n\n // Create a typed array to store the packed bits\n const cls = signed ? Int8Array : Uint8Array;\n const inputData = tensor.data;\n const outputData = new cls(inputData.length / 8);\n\n // Iterate over each number in the array\n for (let i = 0; i < inputData.length; ++i) {\n // Determine if the number is greater than 0\n const bit = inputData[i] > 0 ? 1 : 0;\n\n // Calculate the index in the typed array and the position within the byte\n const arrayIndex = Math.floor(i / 8);\n const bitPosition = i % 8;\n\n // Pack the bit into the typed array\n outputData[arrayIndex] |= bit << (7 - bitPosition);\n if (signed && bitPosition === 0) {\n outputData[arrayIndex] -= 128;\n }\n };\n\n return new Tensor(dtype, outputData, [tensor.dims[0], tensor.dims[1] / 8]);\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","var scriptUrl;\nif (typeof import.meta.url === \"string\") scriptUrl = import.meta.url\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl;","__webpack_require__.b = new URL(\"./\", import.meta.url);\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t\"transformers\": 0\n};\n\n// no install chunk\n\n// no chunk on demand loading\n\n// no prefetching\n\n// no preloaded\n\n// no external install chunk\n\n// no on chunks loaded","/**\n * @file Entry point for the Transformers.js library. Only the exports from this file\n * are available to the end user, and are grouped as follows:\n * \n * 1. [Pipelines](./pipelines)\n * 2. [Environment variables](./env)\n * 3. [Models](./models)\n * 4. [Tokenizers](./tokenizers)\n * 5. [Processors](./processors)\n * \n * @module transformers\n */\n\nexport { env } from './env.js';\nexport * from './pipelines.js';\nexport * from './models.js';\nexport * from './tokenizers.js';\nexport * from './processors.js';\nexport * from './configs.js';\n\nexport * from './utils/audio.js';\nexport * from './utils/image.js';\nexport * from './utils/tensor.js';\nexport * from './utils/maths.js';\n\nexport * from './generation/streamers.js';\nexport * from './generation/stopping_criteria.js';\n\n"],"names":[],"sourceRoot":""} \ No newline at end of file diff --git a/assets/dist_transformers/1.21.0-dev.20241109/transformers.min.cjs b/assets/dist_transformers/1.21.0-dev.20241122/transformers.min.cjs similarity index 100% rename from assets/dist_transformers/1.21.0-dev.20241109/transformers.min.cjs rename to assets/dist_transformers/1.21.0-dev.20241122/transformers.min.cjs diff --git a/assets/dist_transformers/1.21.0-dev.20241109/transformers.min.cjs.map b/assets/dist_transformers/1.21.0-dev.20241122/transformers.min.cjs.map similarity index 100% rename from assets/dist_transformers/1.21.0-dev.20241109/transformers.min.cjs.map rename to assets/dist_transformers/1.21.0-dev.20241122/transformers.min.cjs.map diff --git a/assets/dist_transformers/1.21.0-dev.20241109/transformers.min.js b/assets/dist_transformers/1.21.0-dev.20241122/transformers.min.js similarity index 50% rename from assets/dist_transformers/1.21.0-dev.20241109/transformers.min.js rename to assets/dist_transformers/1.21.0-dev.20241122/transformers.min.js index a127df3..d5dd29a 100644 --- a/assets/dist_transformers/1.21.0-dev.20241109/transformers.min.js +++ b/assets/dist_transformers/1.21.0-dev.20241122/transformers.min.js @@ -25,7 +25,7 @@ var e,t,n={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm \*********************/()=>{},"./node_modules/@huggingface/jinja/dist/index.js": /*!*******************************************************!*\ !*** ./node_modules/@huggingface/jinja/dist/index.js ***! - \*******************************************************/(e,t,n)=>{n.r(t),n.d(t,{Environment:()=>Q,Interpreter:()=>Y,Template:()=>ee,parse:()=>O,tokenize:()=>d});var r=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),i=Object.freeze({set:r.Set,for:r.For,in:r.In,is:r.Is,if:r.If,else:r.Else,endif:r.EndIf,elif:r.ElseIf,endfor:r.EndFor,and:r.And,or:r.Or,not:r.Not,"not in":r.NotIn,macro:r.Macro,endmacro:r.EndMacro,true:r.BooleanLiteral,false:r.BooleanLiteral,True:r.BooleanLiteral,False:r.BooleanLiteral}),a=class{constructor(e,t){this.value=e,this.type=t}};function s(e){return/\w/.test(e)}function o(e){return/[0-9]/.test(e)}var l=[["{%",r.OpenStatement],["%}",r.CloseStatement],["{{",r.OpenExpression],["}}",r.CloseExpression],["(",r.OpenParen],[")",r.CloseParen],["{",r.OpenCurlyBracket],["}",r.CloseCurlyBracket],["[",r.OpenSquareBracket],["]",r.CloseSquareBracket],[",",r.Comma],[".",r.Dot],[":",r.Colon],["|",r.Pipe],["<=",r.ComparisonBinaryOperator],[">=",r.ComparisonBinaryOperator],["==",r.ComparisonBinaryOperator],["!=",r.ComparisonBinaryOperator],["<",r.ComparisonBinaryOperator],[">",r.ComparisonBinaryOperator],["+",r.AdditiveBinaryOperator],["-",r.AdditiveBinaryOperator],["*",r.MultiplicativeBinaryOperator],["/",r.MultiplicativeBinaryOperator],["%",r.MultiplicativeBinaryOperator],["=",r.Equals]],u=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function d(e,t={}){const n=[],d=function(e,t={}){return e.endsWith("\n")&&(e=e.slice(0,-1)),e=e.replace(/{#.*?#}/gs,"{##}"),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%])/gm,"$1")),t.trim_blocks&&(e=e.replace(/([#%]})\n/g,"$1")),e.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}(e,t);let c=0;const p=e=>{let t="";for(;e(d[c]);)if("\\"!==d[c]){if(t+=d[c++],c>=d.length)throw new SyntaxError("Unexpected end of input")}else{if(++c,c>=d.length)throw new SyntaxError("Unexpected end of input");const e=d[c++],n=u.get(e);if(void 0===n)throw new SyntaxError(`Unexpected escaped character: ${e}`);t+=n}return t};e:for(;c0){n.push(new a(e,r.Text));continue}}p((e=>/\s/.test(e)));const t=d[c];if("-"===t||"+"===t){const e=n.at(-1)?.type;if(e===r.Text||void 0===e)throw new SyntaxError(`Unexpected character: ${t}`);switch(e){case r.Identifier:case r.NumericLiteral:case r.BooleanLiteral:case r.StringLiteral:case r.CloseParen:case r.CloseSquareBracket:break;default:{++c;const e=p(o);n.push(new a(`${t}${e}`,e.length>0?r.NumericLiteral:r.UnaryOperator));continue}}}for(const[e,t]of l){if(d.slice(c,c+e.length)===e){n.push(new a(e,t)),c+=e.length;continue e}}if("'"!==t&&'"'!==t)if(o(t)){const e=p(o);n.push(new a(e,r.NumericLiteral))}else{if(!s(t))throw new SyntaxError(`Unexpected character: ${t}`);{const e=p(s),t=Object.hasOwn(i,e)?i[e]:r.Identifier;t===r.In&&n.at(-1)?.type===r.Not?(n.pop(),n.push(new a("not in",r.NotIn))):n.push(new a(e,t))}}else{++c;const e=p((e=>e!==t));n.push(new a(e,r.StringLiteral)),++c}}return n}var c=class{type="Statement"},p=class extends c{constructor(e){super(),this.body=e}type="Program"},h=class extends c{constructor(e,t,n){super(),this.test=e,this.body=t,this.alternate=n}type="If"},m=class extends c{constructor(e,t,n,r){super(),this.loopvar=e,this.iterable=t,this.body=n,this.defaultBlock=r}type="For"},f=class extends c{constructor(e,t){super(),this.assignee=e,this.value=t}type="Set"},g=class extends c{constructor(e,t,n){super(),this.name=e,this.args=t,this.body=n}type="Macro"},_=class extends c{type="Expression"},w=class extends _{constructor(e,t,n){super(),this.object=e,this.property=t,this.computed=n}type="MemberExpression"},b=class extends _{constructor(e,t){super(),this.callee=e,this.args=t}type="CallExpression"},y=class extends _{constructor(e){super(),this.value=e}type="Identifier"},x=class extends _{constructor(e){super(),this.value=e}type="Literal"},v=class extends x{type="NumericLiteral"},M=class extends x{type="StringLiteral"},T=class extends x{type="BooleanLiteral"},k=class extends x{type="ArrayLiteral"},$=class extends x{type="TupleLiteral"},C=class extends x{type="ObjectLiteral"},S=class extends _{constructor(e,t,n){super(),this.operator=e,this.left=t,this.right=n}type="BinaryExpression"},P=class extends _{constructor(e,t){super(),this.operand=e,this.filter=t}type="FilterExpression"},E=class extends _{constructor(e,t){super(),this.iterable=e,this.test=t}type="SelectExpression"},F=class extends _{constructor(e,t,n){super(),this.operand=e,this.negate=t,this.test=n}type="TestExpression"},A=class extends _{constructor(e,t){super(),this.operator=e,this.argument=t}type="UnaryExpression"},I=class extends _{constructor(e=void 0,t=void 0,n=void 0){super(),this.start=e,this.stop=t,this.step=n}type="SliceExpression"},z=class extends _{constructor(e,t){super(),this.key=e,this.value=t}type="KeywordArgumentExpression"};function O(e){const t=new p([]);let n=0;function i(t,r){const i=e[n++];if(!i||i.type!==t)throw new Error(`Parser Error: ${r}. ${i.type} !== ${t}.`);return i}function a(){switch(e[n].type){case r.Text:return new M(i(r.Text,"Expected text token").value);case r.OpenStatement:return function(){let t;switch(i(r.OpenStatement,"Expected opening statement token"),e[n].type){case r.Set:++n,t=l(),i(r.CloseStatement,"Expected closing statement token");break;case r.If:++n,t=u(),i(r.OpenStatement,"Expected {% token"),i(r.EndIf,"Expected endif token"),i(r.CloseStatement,"Expected %} token");break;case r.Macro:++n,t=function(){const e=q();if("Identifier"!==e.type)throw new SyntaxError("Expected identifier following macro statement");const t=D();i(r.CloseStatement,"Expected closing statement token");const n=[];for(;s(r.OpenStatement,r.EndMacro);)n.push(a());return new g(e,t,n)}(),i(r.OpenStatement,"Expected {% token"),i(r.EndMacro,"Expected endmacro token"),i(r.CloseStatement,"Expected %} token");break;case r.For:++n,t=function(){const e=d(!0);if(!(e instanceof y||e instanceof $))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${e.type} instead`);i(r.In,"Expected `in` keyword following loop variable");const t=c();i(r.CloseStatement,"Expected closing statement token");const l=[];for(;s(r.OpenStatement,r.EndFor)&&s(r.OpenStatement,r.Else);)l.push(a());const u=[];if(o(r.OpenStatement,r.Else))for(++n,++n,i(r.CloseStatement,"Expected closing statement token");s(r.OpenStatement,r.EndFor);)u.push(a());return new m(e,t,l,u)}(),i(r.OpenStatement,"Expected {% token"),i(r.EndFor,"Expected endfor token"),i(r.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${e[n].type}`)}return t}();case r.OpenExpression:return function(){i(r.OpenExpression,"Expected opening expression token");const e=c();return i(r.CloseExpression,"Expected closing expression token"),e}();default:throw new SyntaxError(`Unexpected token type: ${e[n].type}`)}}function s(...t){return n+t.length<=e.length&&t.some(((t,r)=>t!==e[n+r].type))}function o(...t){return n+t.length<=e.length&&t.every(((t,r)=>t===e[n+r].type))}function l(){const e=c();if(o(r.Equals)){++n;const t=l();return new f(e,t)}return e}function u(){const t=c();i(r.CloseStatement,"Expected closing statement token");const s=[],l=[];for(;e[n]?.type!==r.OpenStatement||e[n+1]?.type!==r.ElseIf&&e[n+1]?.type!==r.Else&&e[n+1]?.type!==r.EndIf;)s.push(a());if(e[n]?.type===r.OpenStatement&&e[n+1]?.type!==r.EndIf)if(++n,o(r.ElseIf))i(r.ElseIf,"Expected elseif token"),l.push(u());else for(i(r.Else,"Expected else token"),i(r.CloseStatement,"Expected closing statement token");e[n]?.type!==r.OpenStatement||e[n+1]?.type!==r.EndIf;)l.push(a());return new h(t,s,l)}function d(e=!1){const t=e?q:c,i=[t()],a=o(r.Comma);for(;a&&(++n,i.push(t()),o(r.Comma)););return a?new $(i):i[0]}function c(){return function(){const e=_();if(o(r.If)){++n;const t=_();if(o(r.Else)){++n;const r=_();return new h(t,[e],[r])}return new E(e,t)}return e}()}function _(){let t=x();for(;o(r.Or);){const r=e[n];++n;const i=x();t=new S(r,t,i)}return t}function x(){let t=O();for(;o(r.And);){const r=e[n];++n;const i=O();t=new S(r,t,i)}return t}function O(){let t;for(;o(r.Not);){const r=e[n];++n;const i=O();t=new A(r,i)}return t??function(){let t=B();for(;o(r.ComparisonBinaryOperator)||o(r.In)||o(r.NotIn);){const r=e[n];++n;const i=B();t=new S(r,t,i)}return t}()}function B(){let t=V();for(;o(r.AdditiveBinaryOperator);){const r=e[n];++n;const i=V();t=new S(r,t,i)}return t}function L(){const t=function(){let t=q();for(;o(r.Dot)||o(r.OpenSquareBracket);){const a=e[n];let s;++n;const o=a.type!==r.Dot;if(o)s=R(),i(r.CloseSquareBracket,"Expected closing square bracket");else if(s=q(),"Identifier"!==s.type)throw new SyntaxError("Expected identifier following dot operator");t=new w(t,s,o)}return t}();return o(r.OpenParen)?N(t):t}function N(e){let t=new b(e,D());return o(r.OpenParen)&&(t=N(t)),t}function D(){i(r.OpenParen,"Expected opening parenthesis for arguments list");const e=function(){const e=[];for(;!o(r.CloseParen);){let t=c();if(o(r.Equals)){if(++n,!(t instanceof y))throw new SyntaxError("Expected identifier for keyword argument");const e=c();t=new z(t,e)}e.push(t),o(r.Comma)&&++n}return e}();return i(r.CloseParen,"Expected closing parenthesis for arguments list"),e}function R(){const e=[];let t=!1;for(;!o(r.CloseSquareBracket);)o(r.Colon)?(e.push(void 0),++n,t=!0):(e.push(c()),o(r.Colon)&&(++n,t=!0));if(0===e.length)throw new SyntaxError("Expected at least one argument for member/slice expression");if(t){if(e.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new I(...e)}return e[0]}function V(){let t=j();for(;o(r.MultiplicativeBinaryOperator);){const r=e[n];++n;const i=j();t=new S(r,t,i)}return t}function j(){let e=function(){let e=L();for(;o(r.Pipe);){++n;let t=q();if(!(t instanceof y))throw new SyntaxError("Expected identifier for the filter");o(r.OpenParen)&&(t=N(t)),e=new P(e,t)}return e}();for(;o(r.Is);){++n;const t=o(r.Not);t&&++n;let i=q();if(i instanceof T&&(i=new y(i.value.toString())),!(i instanceof y))throw new SyntaxError("Expected identifier for the test");e=new F(e,t,i)}return e}function q(){const t=e[n];switch(t.type){case r.NumericLiteral:return++n,new v(Number(t.value));case r.StringLiteral:return++n,new M(t.value);case r.BooleanLiteral:return++n,new T("true"===t.value.toLowerCase());case r.Identifier:return++n,new y(t.value);case r.OpenParen:{++n;const t=d();if(e[n].type!==r.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${e[n].type} instead`);return++n,t}case r.OpenSquareBracket:{++n;const e=[];for(;!o(r.CloseSquareBracket);)e.push(c()),o(r.Comma)&&++n;return++n,new k(e)}case r.OpenCurlyBracket:{++n;const e=new Map;for(;!o(r.CloseCurlyBracket);){const t=c();i(r.Colon,"Expected colon between key and value in object literal");const a=c();e.set(t,a),o(r.Comma)&&++n}return++n,new C(e)}default:throw new SyntaxError(`Unexpected token: ${t.type}`)}}for(;n=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),n=(n??=e.length)<0?Math.max(e.length+n,0):Math.min(n,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),n=(n??=-1)<-1?Math.max(e.length+n,-1):Math.min(n,e.length-1));const a=[];for(let s=t;i*se.toUpperCase()))}var D=class{type="RuntimeValue";value;builtins=new Map;constructor(e=void 0){this.value=e}__bool__(){return new j(!!this.value)}},R=class extends D{type="NumericValue"},V=class extends D{type="StringValue";builtins=new Map([["upper",new H((()=>new V(this.value.toUpperCase())))],["lower",new H((()=>new V(this.value.toLowerCase())))],["strip",new H((()=>new V(this.value.trim())))],["title",new H((()=>new V(N(this.value))))],["length",new R(this.value.length)]])},j=class extends D{type="BooleanValue"},q=class extends D{type="ObjectValue";__bool__(){return new j(this.value.size>0)}builtins=new Map([["get",new H((([e,t])=>{if(!(e instanceof V))throw new Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new X}))],["items",new H((()=>new W(Array.from(this.value.entries()).map((([e,t])=>new W([new V(e),t]))))))]])},G=class extends q{type="KeywordArgumentsValue"},W=class extends D{type="ArrayValue";builtins=new Map([["length",new R(this.value.length)]]);__bool__(){return new j(this.value.length>0)}},U=class extends W{type="TupleValue"},H=class extends D{type="FunctionValue"},X=class extends D{type="NullValue"},K=class extends D{type="UndefinedValue"},Q=class{constructor(e){this.parent=e}variables=new Map([["namespace",new H((e=>{if(0===e.length)return new q(new Map);if(1!==e.length||!(e[0]instanceof q))throw new Error("`namespace` expects either zero arguments or a single object argument");return e[0]}))]]);tests=new Map([["boolean",e=>"BooleanValue"===e.type],["callable",e=>e instanceof H],["odd",e=>{if("NumericValue"!==e.type)throw new Error(`Cannot apply test "odd" to type: ${e.type}`);return e.value%2!=0}],["even",e=>{if("NumericValue"!==e.type)throw new Error(`Cannot apply test "even" to type: ${e.type}`);return e.value%2==0}],["false",e=>"BooleanValue"===e.type&&!e.value],["true",e=>"BooleanValue"===e.type&&e.value],["string",e=>"StringValue"===e.type],["number",e=>"NumericValue"===e.type],["integer",e=>"NumericValue"===e.type&&Number.isInteger(e.value)],["iterable",e=>e instanceof W||e instanceof V],["lower",e=>{const t=e.value;return"StringValue"===e.type&&t===t.toLowerCase()}],["upper",e=>{const t=e.value;return"StringValue"===e.type&&t===t.toUpperCase()}],["none",e=>"NullValue"===e.type],["defined",e=>"UndefinedValue"!==e.type],["undefined",e=>"UndefinedValue"===e.type],["equalto",(e,t)=>e.value===t.value],["eq",(e,t)=>e.value===t.value]]);set(e,t){return this.declareVariable(e,Z(t))}declareVariable(e,t){if(this.variables.has(e))throw new SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw new Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new K}catch{return new K}}},Y=class{global;constructor(e){this.global=e??new Q}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){const n=this.evaluate(e.left,t);switch(e.operator.value){case"and":return n.__bool__().value?this.evaluate(e.right,t):n;case"or":return n.__bool__().value?n:this.evaluate(e.right,t)}const r=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new j(n.value==r.value);case"!=":return new j(n.value!=r.value)}if(n instanceof K||r instanceof K)throw new Error("Cannot perform operation on undefined values");if(n instanceof X||r instanceof X)throw new Error("Cannot perform operation on null values");if(n instanceof R&&r instanceof R)switch(e.operator.value){case"+":return new R(n.value+r.value);case"-":return new R(n.value-r.value);case"*":return new R(n.value*r.value);case"/":return new R(n.value/r.value);case"%":return new R(n.value%r.value);case"<":return new j(n.value":return new j(n.value>r.value);case">=":return new j(n.value>=r.value);case"<=":return new j(n.value<=r.value)}else if(n instanceof W&&r instanceof W){if("+"===e.operator.value)return new W(n.value.concat(r.value))}else if(r instanceof W){const t=void 0!==r.value.find((e=>e.value===n.value));switch(e.operator.value){case"in":return new j(t);case"not in":return new j(!t)}}if((n instanceof V||r instanceof V)&&"+"===e.operator.value)return new V(n.value.toString()+r.value.toString());if(n instanceof V&&r instanceof V)switch(e.operator.value){case"in":return new j(r.value.includes(n.value));case"not in":return new j(!r.value.includes(n.value))}if(n instanceof V&&r instanceof q)switch(e.operator.value){case"in":return new j(r.value.has(n.value));case"not in":return new j(!r.value.has(n.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${n.type} and ${r.type}`)}evaluateArguments(e,t){const n=[],r=new Map;for(const i of e)if("KeywordArgumentExpression"===i.type){const e=i;r.set(e.key.value,this.evaluate(e.value,t))}else{if(r.size>0)throw new Error("Positional arguments must come before keyword arguments");n.push(this.evaluate(i,t))}return[n,r]}evaluateFilterExpression(e,t){const n=this.evaluate(e.operand,t);if("Identifier"===e.filter.type){const t=e.filter;if("tojson"===t.value)return new V(J(n));if(n instanceof W)switch(t.value){case"list":return n;case"first":return n.value[0];case"last":return n.value[n.value.length-1];case"length":return new R(n.value.length);case"reverse":return new W(n.value.reverse());case"sort":return new W(n.value.sort(((e,t)=>{if(e.type!==t.type)throw new Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case"NumericValue":return e.value-t.value;case"StringValue":return e.value.localeCompare(t.value);default:throw new Error(`Cannot compare type: ${e.type}`)}})));default:throw new Error(`Unknown ArrayValue filter: ${t.value}`)}else if(n instanceof V)switch(t.value){case"length":return new R(n.value.length);case"upper":return new V(n.value.toUpperCase());case"lower":return new V(n.value.toLowerCase());case"title":return new V(N(n.value));case"capitalize":return new V(n.value.charAt(0).toUpperCase()+n.value.slice(1));case"trim":return new V(n.value.trim());case"indent":return new V(n.value.split("\n").map(((e,t)=>0===t||0===e.length?e:" "+e)).join("\n"));case"string":return n;default:throw new Error(`Unknown StringValue filter: ${t.value}`)}else{if(n instanceof R){if("abs"===t.value)return new R(Math.abs(n.value));throw new Error(`Unknown NumericValue filter: ${t.value}`)}if(n instanceof q)switch(t.value){case"items":return new W(Array.from(n.value.entries()).map((([e,t])=>new W([new V(e),t]))));case"length":return new R(n.value.size);default:throw new Error(`Unknown ObjectValue filter: ${t.value}`)}}throw new Error(`Cannot apply filter "${t.value}" to type: ${n.type}`)}if("CallExpression"===e.filter.type){const r=e.filter;if("Identifier"!==r.callee.type)throw new Error(`Unknown filter: ${r.callee.type}`);const i=r.callee.value;if("tojson"===i){const[,e]=this.evaluateArguments(r.args,t),i=e.get("indent")??new X;if(!(i instanceof R||i instanceof X))throw new Error("If set, indent must be a number");return new V(J(n,i.value))}if(n instanceof W){switch(i){case"selectattr":{if(n.value.some((e=>!(e instanceof q))))throw new Error("`selectattr` can only be applied to array of objects");if(r.args.some((e=>"StringLiteral"!==e.type)))throw new Error("arguments of `selectattr` must be strings");const[e,i,a]=r.args.map((e=>this.evaluate(e,t)));let s;if(i){const e=t.tests.get(i.value);if(!e)throw new Error(`Unknown test: ${i.value}`);s=e}else s=(...e)=>e[0].__bool__().value;const o=n.value.filter((t=>{const n=t.value.get(e.value);return!!n&&s(n,a)}));return new W(o)}case"map":{const[,e]=this.evaluateArguments(r.args,t);if(e.has("attribute")){const t=e.get("attribute");if(!(t instanceof V))throw new Error("attribute must be a string");const r=e.get("default"),i=n.value.map((e=>{if(!(e instanceof q))throw new Error("items in map must be an object");return e.value.get(t.value)??r??new K}));return new W(i)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${i}`)}if(n instanceof V){if("indent"===i){const[e,i]=this.evaluateArguments(r.args,t),a=e.at(0)??i.get("width")??new R(4);if(!(a instanceof R))throw new Error("width must be a number");const s=e.at(1)??i.get("first")??new j(!1),o=e.at(2)??i.get("blank")??new j(!1),l=n.value.split("\n"),u=" ".repeat(a.value),d=l.map(((e,t)=>!s.value&&0===t||!o.value&&0===e.length?e:u+e));return new V(d.join("\n"))}throw new Error(`Unknown StringValue filter: ${i}`)}throw new Error(`Cannot apply filter "${i}" to type: ${n.type}`)}throw new Error(`Unknown filter: ${e.filter.type}`)}evaluateTestExpression(e,t){const n=this.evaluate(e.operand,t),r=t.tests.get(e.test.value);if(!r)throw new Error(`Unknown test: ${e.test.value}`);const i=r(n);return new j(e.negate?!i:i)}evaluateUnaryExpression(e,t){const n=this.evaluate(e.argument,t);if("not"===e.operator.value)return new j(!n.value);throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let n="";for(const r of e){const e=this.evaluate(r,t);"NullValue"!==e.type&&"UndefinedValue"!==e.type&&(n+=e.value)}return new V(n)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){const[n,r]=this.evaluateArguments(e.args,t);r.size>0&&n.push(new G(r));const i=this.evaluate(e.callee,t);if("FunctionValue"!==i.type)throw new Error(`Cannot call something that is not a function: got ${i.type}`);return i.value(n,t)}evaluateSliceExpression(e,t,n){if(!(e instanceof W||e instanceof V))throw new Error("Slice object must be an array or string");const r=this.evaluate(t.start,n),i=this.evaluate(t.stop,n),a=this.evaluate(t.step,n);if(!(r instanceof R||r instanceof K))throw new Error("Slice start must be numeric or undefined");if(!(i instanceof R||i instanceof K))throw new Error("Slice stop must be numeric or undefined");if(!(a instanceof R||a instanceof K))throw new Error("Slice step must be numeric or undefined");return e instanceof W?new W(L(e.value,r.value,i.value,a.value)):new V(L(Array.from(e.value),r.value,i.value,a.value).join(""))}evaluateMemberExpression(e,t){const n=this.evaluate(e.object,t);let r,i;if(e.computed){if("SliceExpression"===e.property.type)return this.evaluateSliceExpression(n,e.property,t);r=this.evaluate(e.property,t)}else r=new V(e.property.value);if(n instanceof q){if(!(r instanceof V))throw new Error(`Cannot access property with non-string: got ${r.type}`);i=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof W||n instanceof V)if(r instanceof R)i=n.value.at(r.value),n instanceof V&&(i=new V(n.value.at(r.value)));else{if(!(r instanceof V))throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);i=n.builtins.get(r.value)}else{if(!(r instanceof V))throw new Error(`Cannot access property with non-string: got ${r.type}`);i=n.builtins.get(r.value)}return i instanceof D?i:new K}evaluateSet(e,t){const n=this.evaluate(e.value,t);if("Identifier"===e.assignee.type){const r=e.assignee.value;t.setVariable(r,n)}else{if("MemberExpression"!==e.assignee.type)throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);{const r=e.assignee,i=this.evaluate(r.object,t);if(!(i instanceof q))throw new Error("Cannot assign to member of non-object");if("Identifier"!==r.property.type)throw new Error("Cannot assign to member with non-identifier property");i.value.set(r.property.value,n)}}return new X}evaluateIf(e,t){const n=this.evaluate(e.test,t);return this.evaluateBlock(n.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){const n=new Q(t);let r,i;if("SelectExpression"===e.iterable.type){const t=e.iterable;i=this.evaluate(t.iterable,n),r=t.test}else i=this.evaluate(e.iterable,n);if(!(i instanceof W))throw new Error(`Expected iterable type in for loop: got ${i.type}`);const a=[],s=[];for(let t=0;tt.setVariable(e.loopvar.value,l);else{if("TupleLiteral"!==e.loopvar.type)throw new Error(`Invalid loop variable(s): ${e.loopvar.type}`);{const t=e.loopvar;if("ArrayValue"!==l.type)throw new Error(`Cannot unpack non-iterable type: ${l.type}`);const n=l;if(t.value.length!==n.value.length)throw new Error(`Too ${t.value.length>n.value.length?"few":"many"} items to unpack`);u=e=>{for(let r=0;r0?a[t-1]:new K],["nextitem",t{const r=new Q(n);let i;t=t.slice(),"KeywordArgumentsValue"===t.at(-1)?.type&&(i=t.pop());for(let n=0;nthis.evaluate(e,t))));case"TupleLiteral":return new U(e.value.map((e=>this.evaluate(e,t))));case"ObjectLiteral":{const n=new Map;for(const[r,i]of e.value){const e=this.evaluate(r,t);if(!(e instanceof V))throw new Error(`Object keys must be strings: got ${e.type}`);n.set(e.value,this.evaluate(i,t))}return new q(n)}case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);case"TestExpression":return this.evaluateTestExpression(e,t);default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function Z(e){switch(typeof e){case"number":return new R(e);case"string":return new V(e);case"boolean":return new j(e);case"undefined":return new K;case"object":return null===e?new X:Array.isArray(e)?new W(e.map(Z)):new q(new Map(Object.entries(e).map((([e,t])=>[e,Z(t)]))));case"function":return new H(((t,n)=>Z(e(...t.map((e=>e.value)))??null)));default:throw new Error(`Cannot convert to runtime value: ${e}`)}}function J(e,t,n){const r=n??0;switch(e.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(e.value);case"ArrayValue":case"ObjectValue":{const n=t?" ".repeat(t):"",i="\n"+n.repeat(r),a=i+n;if("ArrayValue"===e.type){const n=e.value.map((e=>J(e,t,r+1)));return t?`[${a}${n.join(`,${a}`)}${i}]`:`[${n.join(", ")}]`}{const n=Array.from(e.value.entries()).map((([e,n])=>{const i=`"${e}": ${J(n,t,r+1)}`;return t?`${a}${i}`:i}));return t?`{${n.join(",")}${i}}`:`{${n.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}var ee=class{parsed;constructor(e){const t=d(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=O(t)}render(e){const t=new Q;t.set("false",!1),t.set("true",!0),t.set("raise_exception",(e=>{throw new Error(e)})),t.set("range",B);for(const[n,r]of Object.entries(e))t.set(n,r);return new Y(t).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js": + \*******************************************************/(e,t,n)=>{n.r(t),n.d(t,{Environment:()=>Q,Interpreter:()=>Y,Template:()=>ee,parse:()=>O,tokenize:()=>d});var r=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),i=Object.freeze({set:r.Set,for:r.For,in:r.In,is:r.Is,if:r.If,else:r.Else,endif:r.EndIf,elif:r.ElseIf,endfor:r.EndFor,and:r.And,or:r.Or,not:r.Not,"not in":r.NotIn,macro:r.Macro,endmacro:r.EndMacro,true:r.BooleanLiteral,false:r.BooleanLiteral,True:r.BooleanLiteral,False:r.BooleanLiteral}),a=class{constructor(e,t){this.value=e,this.type=t}};function s(e){return/\w/.test(e)}function o(e){return/[0-9]/.test(e)}var l=[["{%",r.OpenStatement],["%}",r.CloseStatement],["{{",r.OpenExpression],["}}",r.CloseExpression],["(",r.OpenParen],[")",r.CloseParen],["{",r.OpenCurlyBracket],["}",r.CloseCurlyBracket],["[",r.OpenSquareBracket],["]",r.CloseSquareBracket],[",",r.Comma],[".",r.Dot],[":",r.Colon],["|",r.Pipe],["<=",r.ComparisonBinaryOperator],[">=",r.ComparisonBinaryOperator],["==",r.ComparisonBinaryOperator],["!=",r.ComparisonBinaryOperator],["<",r.ComparisonBinaryOperator],[">",r.ComparisonBinaryOperator],["+",r.AdditiveBinaryOperator],["-",r.AdditiveBinaryOperator],["*",r.MultiplicativeBinaryOperator],["/",r.MultiplicativeBinaryOperator],["%",r.MultiplicativeBinaryOperator],["=",r.Equals]],u=new Map([["n","\n"],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function d(e,t={}){const n=[],d=function(e,t={}){return e.endsWith("\n")&&(e=e.slice(0,-1)),e=e.replace(/{#.*?#}/gs,"{##}"),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%])/gm,"$1")),t.trim_blocks&&(e=e.replace(/([#%]})\n/g,"$1")),e.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}(e,t);let c=0;const p=e=>{let t="";for(;e(d[c]);)if("\\"!==d[c]){if(t+=d[c++],c>=d.length)throw new SyntaxError("Unexpected end of input")}else{if(++c,c>=d.length)throw new SyntaxError("Unexpected end of input");const e=d[c++],n=u.get(e);if(void 0===n)throw new SyntaxError(`Unexpected escaped character: ${e}`);t+=n}return t};e:for(;c0){n.push(new a(e,r.Text));continue}}p((e=>/\s/.test(e)));const t=d[c];if("-"===t||"+"===t){const e=n.at(-1)?.type;if(e===r.Text||void 0===e)throw new SyntaxError(`Unexpected character: ${t}`);switch(e){case r.Identifier:case r.NumericLiteral:case r.BooleanLiteral:case r.StringLiteral:case r.CloseParen:case r.CloseSquareBracket:break;default:{++c;const e=p(o);n.push(new a(`${t}${e}`,e.length>0?r.NumericLiteral:r.UnaryOperator));continue}}}for(const[e,t]of l){if(d.slice(c,c+e.length)===e){n.push(new a(e,t)),c+=e.length;continue e}}if("'"!==t&&'"'!==t)if(o(t)){const e=p(o);n.push(new a(e,r.NumericLiteral))}else{if(!s(t))throw new SyntaxError(`Unexpected character: ${t}`);{const e=p(s),t=Object.hasOwn(i,e)?i[e]:r.Identifier;t===r.In&&n.at(-1)?.type===r.Not?(n.pop(),n.push(new a("not in",r.NotIn))):n.push(new a(e,t))}}else{++c;const e=p((e=>e!==t));n.push(new a(e,r.StringLiteral)),++c}}return n}var c=class{type="Statement"},p=class extends c{constructor(e){super(),this.body=e}type="Program"},h=class extends c{constructor(e,t,n){super(),this.test=e,this.body=t,this.alternate=n}type="If"},m=class extends c{constructor(e,t,n,r){super(),this.loopvar=e,this.iterable=t,this.body=n,this.defaultBlock=r}type="For"},f=class extends c{constructor(e,t){super(),this.assignee=e,this.value=t}type="Set"},g=class extends c{constructor(e,t,n){super(),this.name=e,this.args=t,this.body=n}type="Macro"},_=class extends c{type="Expression"},w=class extends _{constructor(e,t,n){super(),this.object=e,this.property=t,this.computed=n}type="MemberExpression"},b=class extends _{constructor(e,t){super(),this.callee=e,this.args=t}type="CallExpression"},y=class extends _{constructor(e){super(),this.value=e}type="Identifier"},x=class extends _{constructor(e){super(),this.value=e}type="Literal"},v=class extends x{type="NumericLiteral"},M=class extends x{type="StringLiteral"},T=class extends x{type="BooleanLiteral"},k=class extends x{type="ArrayLiteral"},$=class extends x{type="TupleLiteral"},S=class extends x{type="ObjectLiteral"},C=class extends _{constructor(e,t,n){super(),this.operator=e,this.left=t,this.right=n}type="BinaryExpression"},E=class extends _{constructor(e,t){super(),this.operand=e,this.filter=t}type="FilterExpression"},P=class extends _{constructor(e,t){super(),this.iterable=e,this.test=t}type="SelectExpression"},F=class extends _{constructor(e,t,n){super(),this.operand=e,this.negate=t,this.test=n}type="TestExpression"},A=class extends _{constructor(e,t){super(),this.operator=e,this.argument=t}type="UnaryExpression"},I=class extends _{constructor(e=void 0,t=void 0,n=void 0){super(),this.start=e,this.stop=t,this.step=n}type="SliceExpression"},z=class extends _{constructor(e,t){super(),this.key=e,this.value=t}type="KeywordArgumentExpression"};function O(e){const t=new p([]);let n=0;function i(t,r){const i=e[n++];if(!i||i.type!==t)throw new Error(`Parser Error: ${r}. ${i.type} !== ${t}.`);return i}function a(){switch(e[n].type){case r.Text:return new M(i(r.Text,"Expected text token").value);case r.OpenStatement:return function(){let t;switch(i(r.OpenStatement,"Expected opening statement token"),e[n].type){case r.Set:++n,t=l(),i(r.CloseStatement,"Expected closing statement token");break;case r.If:++n,t=u(),i(r.OpenStatement,"Expected {% token"),i(r.EndIf,"Expected endif token"),i(r.CloseStatement,"Expected %} token");break;case r.Macro:++n,t=function(){const e=q();if("Identifier"!==e.type)throw new SyntaxError("Expected identifier following macro statement");const t=D();i(r.CloseStatement,"Expected closing statement token");const n=[];for(;s(r.OpenStatement,r.EndMacro);)n.push(a());return new g(e,t,n)}(),i(r.OpenStatement,"Expected {% token"),i(r.EndMacro,"Expected endmacro token"),i(r.CloseStatement,"Expected %} token");break;case r.For:++n,t=function(){const e=d(!0);if(!(e instanceof y||e instanceof $))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${e.type} instead`);i(r.In,"Expected `in` keyword following loop variable");const t=c();i(r.CloseStatement,"Expected closing statement token");const l=[];for(;s(r.OpenStatement,r.EndFor)&&s(r.OpenStatement,r.Else);)l.push(a());const u=[];if(o(r.OpenStatement,r.Else))for(++n,++n,i(r.CloseStatement,"Expected closing statement token");s(r.OpenStatement,r.EndFor);)u.push(a());return new m(e,t,l,u)}(),i(r.OpenStatement,"Expected {% token"),i(r.EndFor,"Expected endfor token"),i(r.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${e[n].type}`)}return t}();case r.OpenExpression:return function(){i(r.OpenExpression,"Expected opening expression token");const e=c();return i(r.CloseExpression,"Expected closing expression token"),e}();default:throw new SyntaxError(`Unexpected token type: ${e[n].type}`)}}function s(...t){return n+t.length<=e.length&&t.some(((t,r)=>t!==e[n+r].type))}function o(...t){return n+t.length<=e.length&&t.every(((t,r)=>t===e[n+r].type))}function l(){const e=c();if(o(r.Equals)){++n;const t=l();return new f(e,t)}return e}function u(){const t=c();i(r.CloseStatement,"Expected closing statement token");const s=[],l=[];for(;e[n]?.type!==r.OpenStatement||e[n+1]?.type!==r.ElseIf&&e[n+1]?.type!==r.Else&&e[n+1]?.type!==r.EndIf;)s.push(a());if(e[n]?.type===r.OpenStatement&&e[n+1]?.type!==r.EndIf)if(++n,o(r.ElseIf))i(r.ElseIf,"Expected elseif token"),l.push(u());else for(i(r.Else,"Expected else token"),i(r.CloseStatement,"Expected closing statement token");e[n]?.type!==r.OpenStatement||e[n+1]?.type!==r.EndIf;)l.push(a());return new h(t,s,l)}function d(e=!1){const t=e?q:c,i=[t()],a=o(r.Comma);for(;a&&(++n,i.push(t()),o(r.Comma)););return a?new $(i):i[0]}function c(){return function(){const e=_();if(o(r.If)){++n;const t=_();if(o(r.Else)){++n;const r=_();return new h(t,[e],[r])}return new P(e,t)}return e}()}function _(){let t=x();for(;o(r.Or);){const r=e[n];++n;const i=x();t=new C(r,t,i)}return t}function x(){let t=O();for(;o(r.And);){const r=e[n];++n;const i=O();t=new C(r,t,i)}return t}function O(){let t;for(;o(r.Not);){const r=e[n];++n;const i=O();t=new A(r,i)}return t??function(){let t=B();for(;o(r.ComparisonBinaryOperator)||o(r.In)||o(r.NotIn);){const r=e[n];++n;const i=B();t=new C(r,t,i)}return t}()}function B(){let t=V();for(;o(r.AdditiveBinaryOperator);){const r=e[n];++n;const i=V();t=new C(r,t,i)}return t}function L(){const t=function(){let t=q();for(;o(r.Dot)||o(r.OpenSquareBracket);){const a=e[n];let s;++n;const o=a.type!==r.Dot;if(o)s=R(),i(r.CloseSquareBracket,"Expected closing square bracket");else if(s=q(),"Identifier"!==s.type)throw new SyntaxError("Expected identifier following dot operator");t=new w(t,s,o)}return t}();return o(r.OpenParen)?N(t):t}function N(e){let t=new b(e,D());return o(r.OpenParen)&&(t=N(t)),t}function D(){i(r.OpenParen,"Expected opening parenthesis for arguments list");const e=function(){const e=[];for(;!o(r.CloseParen);){let t=c();if(o(r.Equals)){if(++n,!(t instanceof y))throw new SyntaxError("Expected identifier for keyword argument");const e=c();t=new z(t,e)}e.push(t),o(r.Comma)&&++n}return e}();return i(r.CloseParen,"Expected closing parenthesis for arguments list"),e}function R(){const e=[];let t=!1;for(;!o(r.CloseSquareBracket);)o(r.Colon)?(e.push(void 0),++n,t=!0):(e.push(c()),o(r.Colon)&&(++n,t=!0));if(0===e.length)throw new SyntaxError("Expected at least one argument for member/slice expression");if(t){if(e.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new I(...e)}return e[0]}function V(){let t=j();for(;o(r.MultiplicativeBinaryOperator);){const r=e[n];++n;const i=j();t=new C(r,t,i)}return t}function j(){let e=function(){let e=L();for(;o(r.Pipe);){++n;let t=q();if(!(t instanceof y))throw new SyntaxError("Expected identifier for the filter");o(r.OpenParen)&&(t=N(t)),e=new E(e,t)}return e}();for(;o(r.Is);){++n;const t=o(r.Not);t&&++n;let i=q();if(i instanceof T&&(i=new y(i.value.toString())),!(i instanceof y))throw new SyntaxError("Expected identifier for the test");e=new F(e,t,i)}return e}function q(){const t=e[n];switch(t.type){case r.NumericLiteral:return++n,new v(Number(t.value));case r.StringLiteral:return++n,new M(t.value);case r.BooleanLiteral:return++n,new T("true"===t.value.toLowerCase());case r.Identifier:return++n,new y(t.value);case r.OpenParen:{++n;const t=d();if(e[n].type!==r.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${e[n].type} instead`);return++n,t}case r.OpenSquareBracket:{++n;const e=[];for(;!o(r.CloseSquareBracket);)e.push(c()),o(r.Comma)&&++n;return++n,new k(e)}case r.OpenCurlyBracket:{++n;const e=new Map;for(;!o(r.CloseCurlyBracket);){const t=c();i(r.Colon,"Expected colon between key and value in object literal");const a=c();e.set(t,a),o(r.Comma)&&++n}return++n,new S(e)}default:throw new SyntaxError(`Unexpected token: ${t.type}`)}}for(;n=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),n=(n??=e.length)<0?Math.max(e.length+n,0):Math.min(n,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),n=(n??=-1)<-1?Math.max(e.length+n,-1):Math.min(n,e.length-1));const a=[];for(let s=t;i*se.toUpperCase()))}var D=class{type="RuntimeValue";value;builtins=new Map;constructor(e=void 0){this.value=e}__bool__(){return new j(!!this.value)}},R=class extends D{type="NumericValue"},V=class extends D{type="StringValue";builtins=new Map([["upper",new H((()=>new V(this.value.toUpperCase())))],["lower",new H((()=>new V(this.value.toLowerCase())))],["strip",new H((()=>new V(this.value.trim())))],["title",new H((()=>new V(N(this.value))))],["length",new R(this.value.length)]])},j=class extends D{type="BooleanValue"},q=class extends D{type="ObjectValue";__bool__(){return new j(this.value.size>0)}builtins=new Map([["get",new H((([e,t])=>{if(!(e instanceof V))throw new Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new K}))],["items",new H((()=>new U(Array.from(this.value.entries()).map((([e,t])=>new U([new V(e),t]))))))]])},G=class extends q{type="KeywordArgumentsValue"},U=class extends D{type="ArrayValue";builtins=new Map([["length",new R(this.value.length)]]);__bool__(){return new j(this.value.length>0)}},W=class extends U{type="TupleValue"},H=class extends D{type="FunctionValue"},K=class extends D{type="NullValue"},X=class extends D{type="UndefinedValue"},Q=class{constructor(e){this.parent=e}variables=new Map([["namespace",new H((e=>{if(0===e.length)return new q(new Map);if(1!==e.length||!(e[0]instanceof q))throw new Error("`namespace` expects either zero arguments or a single object argument");return e[0]}))]]);tests=new Map([["boolean",e=>"BooleanValue"===e.type],["callable",e=>e instanceof H],["odd",e=>{if("NumericValue"!==e.type)throw new Error(`Cannot apply test "odd" to type: ${e.type}`);return e.value%2!=0}],["even",e=>{if("NumericValue"!==e.type)throw new Error(`Cannot apply test "even" to type: ${e.type}`);return e.value%2==0}],["false",e=>"BooleanValue"===e.type&&!e.value],["true",e=>"BooleanValue"===e.type&&e.value],["string",e=>"StringValue"===e.type],["number",e=>"NumericValue"===e.type],["integer",e=>"NumericValue"===e.type&&Number.isInteger(e.value)],["iterable",e=>e instanceof U||e instanceof V],["lower",e=>{const t=e.value;return"StringValue"===e.type&&t===t.toLowerCase()}],["upper",e=>{const t=e.value;return"StringValue"===e.type&&t===t.toUpperCase()}],["none",e=>"NullValue"===e.type],["defined",e=>"UndefinedValue"!==e.type],["undefined",e=>"UndefinedValue"===e.type],["equalto",(e,t)=>e.value===t.value],["eq",(e,t)=>e.value===t.value]]);set(e,t){return this.declareVariable(e,Z(t))}declareVariable(e,t){if(this.variables.has(e))throw new SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw new Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new X}catch{return new X}}},Y=class{global;constructor(e){this.global=e??new Q}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){const n=this.evaluate(e.left,t);switch(e.operator.value){case"and":return n.__bool__().value?this.evaluate(e.right,t):n;case"or":return n.__bool__().value?n:this.evaluate(e.right,t)}const r=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new j(n.value==r.value);case"!=":return new j(n.value!=r.value)}if(n instanceof X||r instanceof X)throw new Error("Cannot perform operation on undefined values");if(n instanceof K||r instanceof K)throw new Error("Cannot perform operation on null values");if(n instanceof R&&r instanceof R)switch(e.operator.value){case"+":return new R(n.value+r.value);case"-":return new R(n.value-r.value);case"*":return new R(n.value*r.value);case"/":return new R(n.value/r.value);case"%":return new R(n.value%r.value);case"<":return new j(n.value":return new j(n.value>r.value);case">=":return new j(n.value>=r.value);case"<=":return new j(n.value<=r.value)}else if(n instanceof U&&r instanceof U){if("+"===e.operator.value)return new U(n.value.concat(r.value))}else if(r instanceof U){const t=void 0!==r.value.find((e=>e.value===n.value));switch(e.operator.value){case"in":return new j(t);case"not in":return new j(!t)}}if((n instanceof V||r instanceof V)&&"+"===e.operator.value)return new V(n.value.toString()+r.value.toString());if(n instanceof V&&r instanceof V)switch(e.operator.value){case"in":return new j(r.value.includes(n.value));case"not in":return new j(!r.value.includes(n.value))}if(n instanceof V&&r instanceof q)switch(e.operator.value){case"in":return new j(r.value.has(n.value));case"not in":return new j(!r.value.has(n.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${n.type} and ${r.type}`)}evaluateArguments(e,t){const n=[],r=new Map;for(const i of e)if("KeywordArgumentExpression"===i.type){const e=i;r.set(e.key.value,this.evaluate(e.value,t))}else{if(r.size>0)throw new Error("Positional arguments must come before keyword arguments");n.push(this.evaluate(i,t))}return[n,r]}evaluateFilterExpression(e,t){const n=this.evaluate(e.operand,t);if("Identifier"===e.filter.type){const t=e.filter;if("tojson"===t.value)return new V(J(n));if(n instanceof U)switch(t.value){case"list":return n;case"first":return n.value[0];case"last":return n.value[n.value.length-1];case"length":return new R(n.value.length);case"reverse":return new U(n.value.reverse());case"sort":return new U(n.value.sort(((e,t)=>{if(e.type!==t.type)throw new Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case"NumericValue":return e.value-t.value;case"StringValue":return e.value.localeCompare(t.value);default:throw new Error(`Cannot compare type: ${e.type}`)}})));default:throw new Error(`Unknown ArrayValue filter: ${t.value}`)}else if(n instanceof V)switch(t.value){case"length":return new R(n.value.length);case"upper":return new V(n.value.toUpperCase());case"lower":return new V(n.value.toLowerCase());case"title":return new V(N(n.value));case"capitalize":return new V(n.value.charAt(0).toUpperCase()+n.value.slice(1));case"trim":return new V(n.value.trim());case"indent":return new V(n.value.split("\n").map(((e,t)=>0===t||0===e.length?e:" "+e)).join("\n"));case"string":return n;default:throw new Error(`Unknown StringValue filter: ${t.value}`)}else{if(n instanceof R){if("abs"===t.value)return new R(Math.abs(n.value));throw new Error(`Unknown NumericValue filter: ${t.value}`)}if(n instanceof q)switch(t.value){case"items":return new U(Array.from(n.value.entries()).map((([e,t])=>new U([new V(e),t]))));case"length":return new R(n.value.size);default:throw new Error(`Unknown ObjectValue filter: ${t.value}`)}}throw new Error(`Cannot apply filter "${t.value}" to type: ${n.type}`)}if("CallExpression"===e.filter.type){const r=e.filter;if("Identifier"!==r.callee.type)throw new Error(`Unknown filter: ${r.callee.type}`);const i=r.callee.value;if("tojson"===i){const[,e]=this.evaluateArguments(r.args,t),i=e.get("indent")??new K;if(!(i instanceof R||i instanceof K))throw new Error("If set, indent must be a number");return new V(J(n,i.value))}if(n instanceof U){switch(i){case"selectattr":{if(n.value.some((e=>!(e instanceof q))))throw new Error("`selectattr` can only be applied to array of objects");if(r.args.some((e=>"StringLiteral"!==e.type)))throw new Error("arguments of `selectattr` must be strings");const[e,i,a]=r.args.map((e=>this.evaluate(e,t)));let s;if(i){const e=t.tests.get(i.value);if(!e)throw new Error(`Unknown test: ${i.value}`);s=e}else s=(...e)=>e[0].__bool__().value;const o=n.value.filter((t=>{const n=t.value.get(e.value);return!!n&&s(n,a)}));return new U(o)}case"map":{const[,e]=this.evaluateArguments(r.args,t);if(e.has("attribute")){const t=e.get("attribute");if(!(t instanceof V))throw new Error("attribute must be a string");const r=e.get("default"),i=n.value.map((e=>{if(!(e instanceof q))throw new Error("items in map must be an object");return e.value.get(t.value)??r??new X}));return new U(i)}throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${i}`)}if(n instanceof V){if("indent"===i){const[e,i]=this.evaluateArguments(r.args,t),a=e.at(0)??i.get("width")??new R(4);if(!(a instanceof R))throw new Error("width must be a number");const s=e.at(1)??i.get("first")??new j(!1),o=e.at(2)??i.get("blank")??new j(!1),l=n.value.split("\n"),u=" ".repeat(a.value),d=l.map(((e,t)=>!s.value&&0===t||!o.value&&0===e.length?e:u+e));return new V(d.join("\n"))}throw new Error(`Unknown StringValue filter: ${i}`)}throw new Error(`Cannot apply filter "${i}" to type: ${n.type}`)}throw new Error(`Unknown filter: ${e.filter.type}`)}evaluateTestExpression(e,t){const n=this.evaluate(e.operand,t),r=t.tests.get(e.test.value);if(!r)throw new Error(`Unknown test: ${e.test.value}`);const i=r(n);return new j(e.negate?!i:i)}evaluateUnaryExpression(e,t){const n=this.evaluate(e.argument,t);if("not"===e.operator.value)return new j(!n.value);throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let n="";for(const r of e){const e=this.evaluate(r,t);"NullValue"!==e.type&&"UndefinedValue"!==e.type&&(n+=e.value)}return new V(n)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){const[n,r]=this.evaluateArguments(e.args,t);r.size>0&&n.push(new G(r));const i=this.evaluate(e.callee,t);if("FunctionValue"!==i.type)throw new Error(`Cannot call something that is not a function: got ${i.type}`);return i.value(n,t)}evaluateSliceExpression(e,t,n){if(!(e instanceof U||e instanceof V))throw new Error("Slice object must be an array or string");const r=this.evaluate(t.start,n),i=this.evaluate(t.stop,n),a=this.evaluate(t.step,n);if(!(r instanceof R||r instanceof X))throw new Error("Slice start must be numeric or undefined");if(!(i instanceof R||i instanceof X))throw new Error("Slice stop must be numeric or undefined");if(!(a instanceof R||a instanceof X))throw new Error("Slice step must be numeric or undefined");return e instanceof U?new U(L(e.value,r.value,i.value,a.value)):new V(L(Array.from(e.value),r.value,i.value,a.value).join(""))}evaluateMemberExpression(e,t){const n=this.evaluate(e.object,t);let r,i;if(e.computed){if("SliceExpression"===e.property.type)return this.evaluateSliceExpression(n,e.property,t);r=this.evaluate(e.property,t)}else r=new V(e.property.value);if(n instanceof q){if(!(r instanceof V))throw new Error(`Cannot access property with non-string: got ${r.type}`);i=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof U||n instanceof V)if(r instanceof R)i=n.value.at(r.value),n instanceof V&&(i=new V(n.value.at(r.value)));else{if(!(r instanceof V))throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);i=n.builtins.get(r.value)}else{if(!(r instanceof V))throw new Error(`Cannot access property with non-string: got ${r.type}`);i=n.builtins.get(r.value)}return i instanceof D?i:new X}evaluateSet(e,t){const n=this.evaluate(e.value,t);if("Identifier"===e.assignee.type){const r=e.assignee.value;t.setVariable(r,n)}else{if("MemberExpression"!==e.assignee.type)throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);{const r=e.assignee,i=this.evaluate(r.object,t);if(!(i instanceof q))throw new Error("Cannot assign to member of non-object");if("Identifier"!==r.property.type)throw new Error("Cannot assign to member with non-identifier property");i.value.set(r.property.value,n)}}return new K}evaluateIf(e,t){const n=this.evaluate(e.test,t);return this.evaluateBlock(n.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){const n=new Q(t);let r,i;if("SelectExpression"===e.iterable.type){const t=e.iterable;i=this.evaluate(t.iterable,n),r=t.test}else i=this.evaluate(e.iterable,n);if(!(i instanceof U))throw new Error(`Expected iterable type in for loop: got ${i.type}`);const a=[],s=[];for(let t=0;tt.setVariable(e.loopvar.value,l);else{if("TupleLiteral"!==e.loopvar.type)throw new Error(`Invalid loop variable(s): ${e.loopvar.type}`);{const t=e.loopvar;if("ArrayValue"!==l.type)throw new Error(`Cannot unpack non-iterable type: ${l.type}`);const n=l;if(t.value.length!==n.value.length)throw new Error(`Too ${t.value.length>n.value.length?"few":"many"} items to unpack`);u=e=>{for(let r=0;r0?a[t-1]:new X],["nextitem",t{const r=new Q(n);let i;t=t.slice(),"KeywordArgumentsValue"===t.at(-1)?.type&&(i=t.pop());for(let n=0;nthis.evaluate(e,t))));case"TupleLiteral":return new W(e.value.map((e=>this.evaluate(e,t))));case"ObjectLiteral":{const n=new Map;for(const[r,i]of e.value){const e=this.evaluate(r,t);if(!(e instanceof V))throw new Error(`Object keys must be strings: got ${e.type}`);n.set(e.value,this.evaluate(i,t))}return new q(n)}case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);case"TestExpression":return this.evaluateTestExpression(e,t);default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function Z(e){switch(typeof e){case"number":return new R(e);case"string":return new V(e);case"boolean":return new j(e);case"undefined":return new X;case"object":return null===e?new K:Array.isArray(e)?new U(e.map(Z)):new q(new Map(Object.entries(e).map((([e,t])=>[e,Z(t)]))));case"function":return new H(((t,n)=>Z(e(...t.map((e=>e.value)))??null)));default:throw new Error(`Cannot convert to runtime value: ${e}`)}}function J(e,t,n){const r=n??0;switch(e.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(e.value);case"ArrayValue":case"ObjectValue":{const n=t?" ".repeat(t):"",i="\n"+n.repeat(r),a=i+n;if("ArrayValue"===e.type){const n=e.value.map((e=>J(e,t,r+1)));return t?`[${a}${n.join(`,${a}`)}${i}]`:`[${n.join(", ")}]`}{const n=Array.from(e.value.entries()).map((([e,n])=>{const i=`"${e}": ${J(n,t,r+1)}`;return t?`${a}${i}`:i}));return t?`{${n.join(",")}${i}}`:`{${n.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}var ee=class{parsed;constructor(e){const t=d(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=O(t)}render(e){const t=new Q;t.set("false",!1),t.set("true",!0),t.set("raise_exception",(e=>{throw new Error(e)})),t.set("range",B);for(const[n,r]of Object.entries(e))t.set(n,r);return new Y(t).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js": /*!******************************************************************!*\ !*** ./node_modules/onnxruntime-common/dist/esm/backend-impl.js ***! \******************************************************************/(e,t,n)=>{n.r(t),n.d(t,{registerBackend:()=>a,resolveBackendAndExecutionProviders:()=>o});const r=new Map,i=[],a=(e,t,n)=>{if(!t||"function"!=typeof t.init||"function"!=typeof t.createInferenceSessionHandler)throw new TypeError("not a valid backend");{const a=r.get(e);if(void 0===a)r.set(e,{backend:t,priority:n});else{if(a.priority>n)return;if(a.priority===n&&a.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){const t=i.indexOf(e);-1!==t&&i.splice(t,1);for(let t=0;t{const t=r.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{const n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},o=async e=>{const t=e.executionProviders||[],n=t.map((e=>"string"==typeof e?e:e.name)),r=0===n.length?i:n;let a;const o=[],l=new Set;for(const e of r){const t=await s(e);"string"==typeof t?o.push({name:e,err:t}):(a||(a=t),a===t&&l.add(e))}if(!a)throw new Error(`no available backend found. ERR: ${o.map((e=>`[${e.name}] ${e.err}`)).join(", ")}`);for(const{name:e,err:t}of o)n.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);const u=t.filter((e=>l.has("string"==typeof e?e:e.name)));return[a,new Proxy(e,{get:(e,t)=>"executionProviders"===t?u:Reflect.get(e,t)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js": @@ -91,13 +91,13 @@ var e,t,n={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm \*************************************************************/(e,t,n)=>{n.r(t),n.d(t,{version:()=>r});const r="1.19.2"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs": /*!*********************************************************************!*\ !*** ./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs ***! - \*********************************************************************/(e,t,n)=>{n.r(t),n.d(t,{InferenceSession:()=>z,TRACE:()=>P,TRACE_FUNC_BEGIN:()=>F,TRACE_FUNC_END:()=>A,Tensor:()=>S,TrainingSession:()=>B,default:()=>tc,env:()=>p,registerBackend:()=>s}); + \*********************************************************************/(e,t,n)=>{n.r(t),n.d(t,{InferenceSession:()=>z,TRACE:()=>E,TRACE_FUNC_BEGIN:()=>F,TRACE_FUNC_END:()=>A,Tensor:()=>C,TrainingSession:()=>B,default:()=>rc,env:()=>p,registerBackend:()=>s}); /*! - * ONNX Runtime Web v1.21.0-dev.20241109-d3ad76b2cf + * ONNX Runtime Web v1.21.0-dev.20241122-a2ba3cb547 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ -var r,i,a,s,o,l,u,d,c,p,h,m,f,g,_,w,b,y,x,v,M,T,k,$,C,S,P,E,F,A,I,z,O,B,L=Object.defineProperty,N=Object.getOwnPropertyDescriptor,D=Object.getOwnPropertyNames,R=Object.prototype.hasOwnProperty,V=(r=function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')},typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r),j=(e,t)=>()=>(e&&(t=e(e=0)),t),q=(e,t)=>{for(var n in t)L(e,n,{get:t[n],enumerable:!0})},G=e=>((e,t,n,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of D(t))!R.call(e,i)&&i!==n&&L(e,i,{get:()=>t[i],enumerable:!(r=N(t,i))||r.enumerable});return e})(L({},"__esModule",{value:!0}),e),W=j((()=>{i=new Map,a=[],s=(e,t,n)=>{if(!t||"function"!=typeof t.init||"function"!=typeof t.createInferenceSessionHandler)throw new TypeError("not a valid backend");{let r=i.get(e);if(void 0===r)i.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let t=a.indexOf(e);-1!==t&&a.splice(t,1);for(let t=0;t{let t=i.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},l=async e=>{let t,n=e.executionProviders||[],r=n.map((e=>"string"==typeof e?e:e.name)),i=0===r.length?a:r,s=[],l=new Set;for(let e of i){let n=await o(e);"string"==typeof n?s.push({name:e,err:n}):(t||(t=n),t===n&&l.add(e))}if(!t)throw new Error(`no available backend found. ERR: ${s.map((e=>`[${e.name}] ${e.err}`)).join(", ")}`);for(let{name:e,err:t}of s)r.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let u=n.filter((e=>l.has("string"==typeof e?e:e.name)));return[t,new Proxy(e,{get:(e,t)=>"executionProviders"===t?u:Reflect.get(e,t)})]}})),U=j((()=>{W()})),H=j((()=>{u="1.21.0-dev.20241026-05fbb43b34"})),X=j((()=>{H(),d="warning",c={wasm:{},webgl:{},webgpu:{},versions:{common:u},set logLevel(e){if(void 0!==e){if("string"!=typeof e||-1===["verbose","info","warning","error","fatal"].indexOf(e))throw new Error(`Unsupported logging level: ${e}`);d=e}},get logLevel(){return d}},Object.defineProperty(c,"logLevel",{enumerable:!0})})),K=j((()=>{X(),p=c})),Q=j((()=>{h=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext("2d");if(null!=r){let i,a;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let s,o,l=void 0!==t?.format?t.format:"RGB",u=t?.norm;void 0===u||void 0===u.mean?s=[255,255,255,255]:"number"==typeof u.mean?s=[u.mean,u.mean,u.mean,u.mean]:(s=[u.mean[0],u.mean[1],u.mean[2],0],void 0!==u.mean[3]&&(s[3]=u.mean[3])),void 0===u||void 0===u.bias?o=[0,0,0,0]:"number"==typeof u.bias?o=[u.bias,u.bias,u.bias,u.bias]:(o=[u.bias[0],u.bias[1],u.bias[2],0],void 0!==u.bias[3]&&(o[3]=u.bias[3]));let d=a*i,c=0,p=d,h=2*d,m=-1;"RGBA"===l?(c=0,p=d,h=2*d,m=3*d):"RGB"===l?(c=0,p=d,h=2*d):"RBG"===l&&(c=0,h=d,p=2*d);for(let t=0;t{let n,r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");if(null==r)throw new Error("Can not access image data");{let i,a,s;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(i=e.dims[2],a=e.dims[1],s=e.dims[3]):(i=e.dims[3],a=e.dims[2],s=e.dims[1]);let o,l,u=void 0!==t&&void 0!==t.format?t.format:"RGB",d=t?.norm;void 0===d||void 0===d.mean?o=[255,255,255,255]:"number"==typeof d.mean?o=[d.mean,d.mean,d.mean,d.mean]:(o=[d.mean[0],d.mean[1],d.mean[2],255],void 0!==d.mean[3]&&(o[3]=d.mean[3])),void 0===d||void 0===d.bias?l=[0,0,0,0]:"number"==typeof d.bias?l=[d.bias,d.bias,d.bias,d.bias]:(l=[d.bias[0],d.bias[1],d.bias[2],0],void 0!==d.bias[3]&&(l[3]=d.bias[3]));let c=a*i;if(void 0!==t&&(void 0!==t.format&&4===s&&"RGBA"!==t.format||3===s&&"RGB"!==t.format&&"BGR"!==t.format))throw new Error("Tensor format doesn't match input tensor dims");let p=4,h=0,m=1,f=2,g=3,_=0,w=c,b=2*c,y=-1;"RGBA"===u?(_=0,w=c,b=2*c,y=3*c):"RGB"===u?(_=0,w=c,b=2*c):"RBG"===u&&(_=0,b=c,w=2*c),n=r.createImageData(i,a);for(let t=0;t{ee(),f=(e,t)=>{if(void 0===e)throw new Error("Image buffer must be defined");if(void 0===t.height||void 0===t.width)throw new Error("Image height and width must be defined");if("NHWC"===t.tensorLayout)throw new Error("NHWC Tensor layout is not supported yet");let n,r,{height:i,width:a}=t,s=t.norm??{mean:255,bias:0};n="number"==typeof s.mean?[s.mean,s.mean,s.mean,s.mean]:[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],r="number"==typeof s.bias?[s.bias,s.bias,s.bias,s.bias]:[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let o=void 0!==t.format?t.format:"RGBA",l=void 0!==t.tensorFormat&&void 0!==t.tensorFormat?t.tensorFormat:"RGB",u=i*a,d="RGBA"===l?new Float32Array(4*u):new Float32Array(3*u),c=4,p=0,h=1,m=2,f=3,g=0,_=u,w=2*u,b=-1;"RGB"===o&&(c=3,p=0,h=1,m=2,f=-1),"RGBA"===l?b=3*u:"RBG"===l?(g=0,w=u,_=2*u):"BGR"===l&&(w=0,_=u,g=2*u);for(let t=0;t{let n,r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,i=typeof ImageData<"u"&&e instanceof ImageData,a=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,s="string"==typeof e,o=t??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},u=e=>typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext("2d"):null;if(r){let r=l();r.width=e.width,r.height=e.height;let i=u(r);if(null==i)throw new Error("Can not access image data");{let r=e.height,a=e.width;if(void 0!==t&&void 0!==t.resizedHeight&&void 0!==t.resizedWidth&&(r=t.resizedHeight,a=t.resizedWidth),void 0!==t){if(o=t,void 0!==t.tensorFormat)throw new Error("Image input config format must be RGBA for HTMLImageElement");o.tensorFormat="RGBA",o.height=r,o.width=a}else o.tensorFormat="RGBA",o.height=r,o.width=a;i.drawImage(e,0,0),n=i.getImageData(0,0,a,r).data}}else{if(!i){if(a){if(void 0===t)throw new Error("Please provide image config with format for Imagebitmap");let r=l();r.width=e.width,r.height=e.height;let i=u(r);if(null!=i){let t=e.height,r=e.width;return i.drawImage(e,0,0,r,t),n=i.getImageData(0,0,r,t).data,o.height=t,o.width=r,f(n,o)}throw new Error("Can not access image data")}if(s)return new Promise(((t,n)=>{let r=l(),i=u(r);if(!e||!i)return n();let a=new Image;a.crossOrigin="Anonymous",a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);o.height=r.height,o.width=r.width,t(f(e.data,o))}}));throw new Error("Input data provided is not supported - aborted tensor creation")}{let r,i;if(void 0!==t&&void 0!==t.resizedWidth&&void 0!==t.resizedHeight?(r=t.resizedHeight,i=t.resizedWidth):(r=e.height,i=e.width),void 0!==t&&(o=t),o.format="RGBA",o.height=r,o.width=i,void 0!==t){let t=l();t.width=i,t.height=r;let a=u(t);if(null==a)throw new Error("Can not access image data");a.putImageData(e,0,0),n=a.getImageData(0,0,i,r).data}else n=e.data}}if(void 0!==n)return f(n,o);throw new Error("Input data provided is not supported - aborted tensor creation")},_=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new C({location:"texture",type:"float32",texture:e,dims:[1,r,n,4],download:i,dispose:a})},w=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new C({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:r,download:i,dispose:a})},b=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new C({location:"ml-tensor",type:n??"float32",mlTensor:e,dims:r,download:i,dispose:a})},y=(e,t,n)=>new C({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]})})),Z=j((()=>{x=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),v=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),M=!1,T=()=>{if(!M){M=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,n=typeof Float16Array<"u"&&Float16Array.from;e&&(x.set("int64",BigInt64Array),v.set(BigInt64Array,"int64")),t&&(x.set("uint64",BigUint64Array),v.set(BigUint64Array,"uint64")),n?(x.set("float16",Float16Array),v.set(Float16Array,"float16")):x.set("float16",Uint16Array)}}})),J=j((()=>{ee(),k=e=>{let t=1;for(let n=0;n{switch(e.location){case"cpu":return new C(e.type,e.data,t);case"cpu-pinned":return new C({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new C({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new C({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new C({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}})),ee=j((()=>{Q(),Y(),Z(),J(),C=class{constructor(e,t,n){let r,i;if(T(),"object"==typeof e&&"location"in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case"cpu-pinned":{let t=x.get(r);if(!t)throw new TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw new TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case"texture":if("float32"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case"gpu-buffer":if("float32"!==r&&"float16"!==r&&"int32"!==r&&"int64"!==r&&"uint32"!==r&&"uint8"!==r&&"bool"!==r&&"uint4"!==r&&"int4"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case"ml-tensor":if("float32"!==r&&"float16"!==r&&"int32"!==r&&"int64"!==r&&"uint32"!==r&&"uint64"!==r&&"int8"!==r&&"uint8"!==r&&"bool"!==r&&"uint4"!==r&&"int4"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,s;if("string"==typeof e)if(r=e,s=n,"string"===e){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");a=t}else{let n=x.get(e);if(void 0===n)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if("float16"===e&&n===Uint16Array||"uint4"===e||"int4"===e)throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a="uint64"===e||"int64"===e?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else{if(!(t instanceof Uint8ClampedArray))throw new TypeError(`A ${r} tensor's data must be type of ${n}`);if("uint8"!==e)throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");a=Uint8Array.from(t)}}else if(s=t,Array.isArray(e)){if(0===e.length)throw new TypeError("Tensor type cannot be inferred from an empty array.");let t=typeof e[0];if("string"===t)r="string",a=e;else{if("boolean"!==t)throw new TypeError(`Invalid element type of data array: ${t}.`);r="bool",a=Uint8Array.from(e)}}else if(e instanceof Uint8ClampedArray)r="uint8",a=Uint8Array.from(e);else{let t=v.get(e.constructor);if(void 0===t)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(void 0===s)s=[a.length];else if(!Array.isArray(s))throw new TypeError("A tensor's dims must be a number array");i=s,this.cpuData=a,this.dataLocation="cpu"}let a=k(i);if(this.cpuData&&a!==this.cpuData.length&&("uint4"!==r&&"int4"!==r||Math.ceil(a/2)!==this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return g(e,t)}static fromTexture(e,t){return _(e,t)}static fromGpuBuffer(e,t){return w(e,t)}static fromMLTensor(e,t){return b(e,t)}static fromPinnedBuffer(e,t,n){return y(e,t,n)}toDataURL(e){return h(this,e)}toImageData(e){return m(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if("none"===this.dataLocation)throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return $(this,e)}}})),te=j((()=>{ee(),S=C})),ne=j((()=>{X(),P=(e,t)=>{(typeof c.trace>"u"?!c.wasm.trace:!c.trace)||console.timeStamp(`${e}::ORT::${t}`)},E=(e,t)=>{let n=(new Error).stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i{(typeof c.trace>"u"?!c.wasm.trace:!c.trace)||E("BEGIN",e)},A=e=>{(typeof c.trace>"u"?!c.wasm.trace:!c.trace)||E("END",e)}})),re=j((()=>{W(),te(),ne(),I=class e{constructor(e){this.handler=e}async run(e,t,n){F();let r={},i={};if("object"!=typeof e||null===e||e instanceof S||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if("object"==typeof t){if(null===t)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof S)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(0===t.length)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let e of t){if("string"!=typeof e)throw new TypeError("'fetches' must be a string array or an object.");if(-1===this.outputNames.indexOf(e))throw new RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if("object"==typeof n&&null!==n)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let e=!1,s=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(-1!==s.indexOf(n)){let i=t[n];(null===i||i instanceof S)&&(e=!0,a=!1,r[n]=i)}if(e){if("object"==typeof n&&null!==n)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else i=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let t of this.inputNames)if(typeof e[t]>"u")throw new Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let s=await this.handler.run(e,r,i),o={};for(let e in s)if(Object.hasOwnProperty.call(s,e)){let t=s[e];o[e]=t instanceof S?t:new S(t.type,t.data,t.dims)}return A(),o}async release(){return this.handler.dispose()}static async create(t,n,r,i){F();let a,s={};if("string"==typeof t){if(a=t,"object"==typeof n&&null!==n)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,"object"==typeof n&&null!==n)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{if(!(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer))throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");{let e=t,o=0,l=t.byteLength;if("object"==typeof n&&null!==n)s=n;else if("number"==typeof n){if(o=n,!Number.isSafeInteger(o))throw new RangeError("'byteOffset' must be an integer.");if(o<0||o>=e.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(l=t.byteLength-o,"number"==typeof r){if(l=r,!Number.isSafeInteger(l))throw new RangeError("'byteLength' must be an integer.");if(l<=0||o+l>e.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${e.byteLength-o}].`);if("object"==typeof i&&null!==i)s=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof r<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof n<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(e,o,l)}}let[o,u]=await l(s),d=await o.createInferenceSessionHandler(a,u);return A(),new e(d)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}})),ie=j((()=>{re(),z=I})),ae=j((()=>{})),se=j((()=>{})),oe=j((()=>{})),le=j((()=>{})),ue=j((()=>{W(),te(),O=class e{constructor(e,t,n){this.handler=e,this.hasOptimizerModel=t,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(t,n){let r=t.evalModel||"",i=t.optimizerModel||"",a=n||{},[s,o]=await l(a);if(s.createTrainingSessionHandler){let n=await s.createTrainingSessionHandler(t.checkpointState,t.trainModel,r,i,o);return new e(n,!!t.optimizerModel,!!t.evalModel)}throw new Error("Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.")}typeNarrowingForRunStep(e,t,n,r,i){let a={},s={};if("object"!=typeof n||null===n||n instanceof S||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if("object"==typeof r){if(null===r)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof S)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(0===r.length)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(let e of r){if("string"!=typeof e)throw new TypeError("'fetches' must be a string array or an object.");if(-1===t.indexOf(e))throw new RangeError(`'fetches' contains invalid output name: ${e}.`);a[e]=null}if("object"==typeof i&&null!==i)s=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let e=!1,n=Object.getOwnPropertyNames(r);for(let i of t)if(-1!==n.indexOf(i)){let t=r[i];(null===t||t instanceof S)&&(e=!0,o=!1,a[i]=t)}if(e){if("object"==typeof i&&null!==i)s=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else s=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let t of e)if(typeof n[t]>"u")throw new Error(`input '${t}' is missing in 'feeds'.`);if(o)for(let e of t)a[e]=null;return[a,s]}convertHandlerReturnTypeToMapOfTensors(e){let t={};for(let n in e)if(Object.hasOwnProperty.call(e,n)){let r=e[n];t[n]=r instanceof S?r:new S(r.type,r.data,r.dims)}return t}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(e,t,n){let[r,i]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,e,t,n),a=await this.handler.runTrainStep(e,r,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}async runOptimizerStep(e){if(!this.hasOptimizerModel)throw new Error("This TrainingSession has no OptimizerModel loaded.");await this.handler.runOptimizerStep(e||{})}async runEvalStep(e,t,n){if(this.hasEvalModel){let[r,i]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,e,t,n),a=await this.handler.runEvalStep(e,r,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(e=!0){return this.handler.getParametersSize(e)}async loadParametersBuffer(e,t=!0){let n=await this.getParametersSize(t);if(e.length!==4*n)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(e,t)}async getContiguousParameters(e=!0){return this.handler.getContiguousParameters(e)}async release(){return this.handler.dispose()}}})),de=j((()=>{ue(),B=O})),ce={};q(ce,{InferenceSession:()=>z,TRACE:()=>P,TRACE_FUNC_BEGIN:()=>F,TRACE_FUNC_END:()=>A,Tensor:()=>S,TrainingSession:()=>B,env:()=>p,registerBackend:()=>s});var pe=j((()=>{U(),K(),ie(),te(),ae(),se(),ne(),oe(),le(),de()})),he=j((()=>{})),me={};q(me,{default:()=>_e});var fe,ge,_e,we=j((()=>{Hd(),Xl(),Hl(),fe="ort-wasm-proxy-worker",(ge=globalThis.self?.name===fe)&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case"init-wasm":Le(n.wasm).then((()=>{md(n).then((()=>{postMessage({type:t})}),(e=>{postMessage({type:t,err:e})}))}),(e=>{postMessage({type:t,err:e})}));break;case"init-ep":{let{epName:e,env:r}=n;fd(r,e).then((()=>{postMessage({type:t})}),(e=>{postMessage({type:t,err:e})}));break}case"copy-from":{let{buffer:e}=n,r=wd(e);postMessage({type:t,out:r});break}case"create":{let{model:e,options:r}=n;bd(e,r).then((e=>{postMessage({type:t,out:e})}),(e=>{postMessage({type:t,err:e})}));break}case"release":yd(n),postMessage({type:t});break;case"run":{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:s}=n;vd(e,r,i,a,new Array(a.length).fill(null),s).then((e=>{e.some((e=>"cpu"!==e[3]))?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:e},Td([...i,...e]))}),(e=>{postMessage({type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,Ea,Fa,Aa,Ia,za,Oa,Ba,La,Na,Da,Ra,Va,ja,qa,Ga,Wa,Ua,Ha,Xa,Ka,Qa,Ya,Za,Ja,es,ts,ns,rs,is,as,ss,os,ls,us,ds,cs,ps,hs,ms,fs,gs,_s,ws,bs,ys,xs,vs,Ms,Ts,ks,$s,Cs,Ss,Ps,Es,Fs,As,Is,zs,Os,Bs,Ls,Ns,Ds,Rs,Vs,js,qs,Gs,Ws,Us,Hs,Xs,Ks,Qs,Ys,Zs,Js,eo,to,no,ro,io,ao,so,oo,lo,uo,co,po,ho,mo,fo,go,_o,wo,bo,yo,xo,vo,Mo,To,ko,$o,Co,So,Po,Eo,Fo,Ao,Io,zo,Oo,Bo,Lo,No,Do,Ro,Vo,jo,qo,Go,Wo,Uo,Ho,Xo,Ko,Qo,Yo,Zo,Jo,el,tl,nl,rl,il,al,sl,ol,ll,ul,dl,cl,pl,hl,ml,fl,gl,_l,wl,bl,yl,xl,vl,Ml,Tl,kl,$l,Cl,Sl,Pl,El,Fl,Al,Il,zl,Ol,Bl,Ll,Nl,Dl,Rl,Vl,jl,ql,Gl,Wl,Ul=j((()=>{ye=import.meta.url,xe=async function(e={}){function t(){return F.buffer!=z.buffer&&W(),z}function r(){return F.buffer!=z.buffer&&W(),O}function i(){return F.buffer!=z.buffer&&W(),B}function a(){return F.buffer!=z.buffer&&W(),L}function s(){return F.buffer!=z.buffer&&W(),N}function o(){return F.buffer!=z.buffer&&W(),D}function l(){return F.buffer!=z.buffer&&W(),R}function u(){return F.buffer!=z.buffer&&W(),q}var d,c,p=Object.assign({},e),h=new Promise(((e,t)=>{d=e,c=t})),m="object"==typeof window,f="function"==typeof importScripts,g=f&&"em-pthread"==self.name;p.mountExternalData=(e,t)=>{e.startsWith("./")&&(e=e.substring(2)),(p.Eb||(p.Eb=new Map)).set(e,t)},p.unmountExternalData=()=>{delete p.Eb};var _=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let w=()=>{let e=(e,t,n)=>(...r)=>{let i=Ht,a=t?.();r=e(...r);let s=t?.();return a!==s&&(e=s,n(a),t=n=null),Ht!=i?new Promise(((e,t)=>{Jt={resolve:e,reject:t}})):r},t=e=>async(...t)=>{try{if(p.Fb)throw Error("Session already started");let n=p.Fb={fc:t[0],errors:[]},r=await e(...t);if(p.Fb!==n)throw Error("Session mismatch");p.Gb?.flush();let i=n.errors;if(0e)),0p._OrtCreateSession),(e=>p._OrtCreateSession=e)),p._OrtRun=t(e(p._OrtRun,(()=>p._OrtRun),(e=>p._OrtRun=e))),p._OrtRunWithBinding=t(e(p._OrtRunWithBinding,(()=>p._OrtRunWithBinding),(e=>p._OrtRunWithBinding=e))),p._OrtBindInput=e(p._OrtBindInput,(()=>p._OrtBindInput),(e=>p._OrtBindInput=e)),w=void 0};p.jsepInit=(e,t)=>{if(w?.(),"webgpu"===e){[p.Gb,p.Ub,p.Yb,p.Nb,p.Xb,p.jb,p.Zb,p.bc,p.Vb,p.Wb,p.$b]=t;let e=p.Gb;p.jsepRegisterBuffer=(t,n,r,i)=>e.registerBuffer(t,n,r,i),p.jsepGetBuffer=t=>e.getBuffer(t),p.jsepCreateDownloader=(t,n,r)=>e.createDownloader(t,n,r),p.jsepOnCreateSession=t=>{e.onCreateSession(t)},p.jsepOnReleaseSession=t=>{e.onReleaseSession(t)},p.jsepOnRunStart=t=>e.onRunStart(t),p.cc=(t,n)=>{e.upload(t,n)}}else if("webnn"===e){[p.Gb,p.ac,p.Ob,p.jsepEnsureTensor,p.dc,p.jsepDownloadTensor]=t,p.jsepReleaseTensorId=p.Ob;let e=p.Gb;p.jsepOnRunStart=t=>e.onRunStart(t),p.jsepRegisterMLContext=(t,n)=>{e.registerMLContext(t,n)},p.jsepOnReleaseSession=t=>{e.onReleaseSession(t)},p.jsepCreateMLTensorDownloader=(t,n)=>e.createMLTensorDownloader(t,n),p.jsepRegisterMLTensor=(t,n,r)=>e.registerMLTensor(t,n,r),p.jsepCreateMLContext=t=>e.createMLContext(t),p.qc=(t,n,r,i,a)=>e.registerMLConstant(t,n,r,i,a,p.Eb)}};var b,y,x=Object.assign({},p),v=(e,t)=>{throw t},M="";(m||f)&&(f?M=self.location.href:typeof document<"u"&&document.currentScript&&(M=document.currentScript.src),ye&&(M=ye),M=M.startsWith("blob:")?"":M.substr(0,M.replace(/[?#].*/,"").lastIndexOf("/")+1),f&&(y=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),b=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)});var T,k=console.log.bind(console),$=console.error.bind(console),C=k,S=$;if(Object.assign(p,x),x=null,g){let e=function(t){try{var n=t.data,r=n.cmd;if("load"===r){let t=[];self.onmessage=e=>t.push(e),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let n of t)e(n);self.onmessage=e};for(let e of n.handlers)p[e]&&!p[e].proxy||(p[e]=(...t)=>{postMessage({Mb:"callHandler",oc:e,args:t})},"print"==e&&(C=p[e]),"printErr"==e&&(S=p[e]));F=n.wasmMemory,W(),P(n.wasmModule)}else if("run"===r){Mr(n.pthread_ptr,0,0,1,0,0),Ot(n.pthread_ptr),Ce(),Me(),E||(wr(),E=!0);try{Se(n.start_routine,n.arg)}catch(e){if("unwind"!=e)throw e}}else"cancel"===r?yr()&&Cr(-1):"setimmediate"!==n.target&&("checkMailbox"===r?E&&Bt():r&&(S(`worker: received unknown command ${r}`),S(n)))}catch(e){throw Tr(),e}};var P,E=!1;S=function(...e){e=e.join(" "),console.error(e)},self.alert=function(...e){postMessage({Mb:"alert",text:e.join(" "),rc:yr()})},p.instantiateWasm=(e,t)=>new Promise((e=>{P=n=>{n=new WebAssembly.Instance(n,ae()),t(n),e()}})),self.onunhandledrejection=e=>{throw e.reason||e},self.onmessage=e}p.wasmBinary&&(T=p.wasmBinary);var F,A,I,z,O,B,L,N,D,R,V,j,q,G=!1;function W(){var e=F.buffer;p.HEAP8=z=new Int8Array(e),p.HEAP16=B=new Int16Array(e),p.HEAPU8=O=new Uint8Array(e),p.HEAPU16=L=new Uint16Array(e),p.HEAP32=N=new Int32Array(e),p.HEAPU32=D=new Uint32Array(e),p.HEAPF32=R=new Float32Array(e),p.HEAPF64=q=new Float64Array(e),p.HEAP64=V=new BigInt64Array(e),p.HEAPU64=j=new BigUint64Array(e)}if(!g){if(!((F=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof _))throw S("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),Error("bad memory");W()}var U=[],H=[],X=[],K=0,Q=null,Y=null;function Z(){if(0==--K&&(null!==Q&&(clearInterval(Q),Q=null),Y)){var e=Y;Y=null,e()}}function J(e){throw S(e="Aborted("+e+")"),G=!0,I=1,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),c(e),e}var ee,te=e=>e.startsWith("data:application/octet-stream;base64,"),ne=e=>e.startsWith("file://");function re(e){if(e==ee&&T)return new Uint8Array(T);if(y)return y(e);throw"both async and sync fetching of the wasm failed"}function ie(e,t,n){return function(e){if(!T&&(m||f)){if("function"==typeof fetch&&!ne(e))return fetch(e,{credentials:"same-origin"}).then((t=>{if(!t.ok)throw`failed to load wasm binary file at '${e}'`;return t.arrayBuffer()})).catch((()=>re(e)));if(b)return new Promise(((t,n)=>{b(e,(e=>t(new Uint8Array(e))),n)}))}return Promise.resolve().then((()=>re(e)))}(e).then((e=>WebAssembly.instantiate(e,t))).then(n,(e=>{S(`failed to asynchronously prepare wasm: ${e}`),J(e)}))}function ae(){return{a:{O:le,Aa:oe,b:Ee,aa:Ae,B:Be,qa:Le,Y:Ve,_:je,ra:qe,oa:Ge,ha:We,na:Ue,L:He,Z:Xe,W:Ke,pa:Qe,X:Ye,wa:et,F:ot,Q:ut,P:_t,E:bt,u:yt,q:xt,G:vt,A:Et,R:Ft,ua:At,ka:It,U:Lt,ba:Dt,H:Rt,ja:Ot,ta:Vt,t:Gt,x:nn,o:an,l:ln,c:pt,n:dn,j:mn,w:fn,p:gn,g:_n,s:wn,m:bn,e:yn,k:xn,i:vn,h:Mn,d:Tn,ea:kn,fa:Pn,ga:En,ca:Fn,da:An,T:In,f:Bn,D:Ln,I:Nn,M:Dn,y:Rn,sa:jn,V:qn,v:Vn,z:Gn,N:Wn,S:Un,za:Qn,ya:Yn,la:tr,ma:nr,$:ge,C:rr,K:ir,ia:ar,J:or,a:F,xa:me,va:cr,r:pr}}}var se={874964:(e,t,n,i,a)=>{if(void 0===p||!p.Eb)return 1;if((e=Oe(Number(e>>>0))).startsWith("./")&&(e=e.substring(2)),!(e=p.Eb.get(e)))return 2;if(t=Number(t>>>0),n=Number(n>>>0),i=Number(i>>>0),t+n>e.byteLength)return 3;try{let s=e.subarray(t,t+n);switch(a){case 0:r().set(s,i>>>0);break;case 1:p.cc(i,s);break;default:return 4}return 0}catch{return 4}},875679:(e,t,n)=>{p.dc(e,r().subarray(t>>>0,t+n>>>0))},875742:()=>p.ac(),875783:e=>{p.Ob(e)},875819:()=>{p.Vb()},875850:()=>{p.Wb()},875879:()=>{p.$b()},875904:e=>p.Ub(e),875937:e=>p.Yb(e),875969:(e,t,n)=>{p.Nb(Number(e),Number(t),Number(n),!0)},876032:(e,t,n)=>{p.Nb(Number(e),Number(t),Number(n))},876089:()=>typeof wasmOffsetConverter<"u",876146:e=>{p.jb("Abs",e,void 0)},876197:e=>{p.jb("Neg",e,void 0)},876248:e=>{p.jb("Floor",e,void 0)},876301:e=>{p.jb("Ceil",e,void 0)},876353:e=>{p.jb("Reciprocal",e,void 0)},876411:e=>{p.jb("Sqrt",e,void 0)},876463:e=>{p.jb("Exp",e,void 0)},876514:e=>{p.jb("Erf",e,void 0)},876565:e=>{p.jb("Sigmoid",e,void 0)},876620:(e,t,n)=>{p.jb("HardSigmoid",e,{alpha:t,beta:n})},876699:e=>{p.jb("Log",e,void 0)},876750:e=>{p.jb("Sin",e,void 0)},876801:e=>{p.jb("Cos",e,void 0)},876852:e=>{p.jb("Tan",e,void 0)},876903:e=>{p.jb("Asin",e,void 0)},876955:e=>{p.jb("Acos",e,void 0)},877007:e=>{p.jb("Atan",e,void 0)},877059:e=>{p.jb("Sinh",e,void 0)},877111:e=>{p.jb("Cosh",e,void 0)},877163:e=>{p.jb("Asinh",e,void 0)},877216:e=>{p.jb("Acosh",e,void 0)},877269:e=>{p.jb("Atanh",e,void 0)},877322:e=>{p.jb("Tanh",e,void 0)},877374:e=>{p.jb("Not",e,void 0)},877425:(e,t,n)=>{p.jb("Clip",e,{min:t,max:n})},877494:e=>{p.jb("Clip",e,void 0)},877546:(e,t)=>{p.jb("Elu",e,{alpha:t})},877604:e=>{p.jb("Gelu",e,void 0)},877656:e=>{p.jb("Relu",e,void 0)},877708:(e,t)=>{p.jb("LeakyRelu",e,{alpha:t})},877772:(e,t)=>{p.jb("ThresholdedRelu",e,{alpha:t})},877842:(e,t)=>{p.jb("Cast",e,{to:t})},877900:e=>{p.jb("Add",e,void 0)},877951:e=>{p.jb("Sub",e,void 0)},878002:e=>{p.jb("Mul",e,void 0)},878053:e=>{p.jb("Div",e,void 0)},878104:e=>{p.jb("Pow",e,void 0)},878155:e=>{p.jb("Equal",e,void 0)},878208:e=>{p.jb("Greater",e,void 0)},878263:e=>{p.jb("GreaterOrEqual",e,void 0)},878325:e=>{p.jb("Less",e,void 0)},878377:e=>{p.jb("LessOrEqual",e,void 0)},878436:(e,t,n,r,i)=>{p.jb("ReduceMean",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},878611:(e,t,n,r,i)=>{p.jb("ReduceMax",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},878785:(e,t,n,r,i)=>{p.jb("ReduceMin",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},878959:(e,t,n,r,i)=>{p.jb("ReduceProd",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},879134:(e,t,n,r,i)=>{p.jb("ReduceSum",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},879308:(e,t,n,r,i)=>{p.jb("ReduceL1",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},879481:(e,t,n,r,i)=>{p.jb("ReduceL2",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},879654:(e,t,n,r,i)=>{p.jb("ReduceLogSum",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},879831:(e,t,n,r,i)=>{p.jb("ReduceSumSquare",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},880011:(e,t,n,r,i)=>{p.jb("ReduceLogSumExp",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},880191:e=>{p.jb("Where",e,void 0)},880244:(e,t,n)=>{p.jb("Transpose",e,{perm:t?Array.from(s().subarray(Number(t)>>>0,Number(n)>>>0)):[]})},880368:(e,t,n,r)=>{p.jb("DepthToSpace",e,{blocksize:t,mode:Oe(n),format:r?"NHWC":"NCHW"})},880501:(e,t,n,r)=>{p.jb("DepthToSpace",e,{blocksize:t,mode:Oe(n),format:r?"NHWC":"NCHW"})},880634:(e,n,r,i,a,o,l,u,d,c,h,m,f,g,_)=>{p.jb("ConvTranspose",e,{format:d?"NHWC":"NCHW",autoPad:n,dilations:[r],group:i,kernelShape:[a],pads:[o,l],strides:[u],wIsConst:()=>!!t()[c>>>0],outputPadding:h?Array.from(s().subarray(Number(h)>>>0,Number(m)>>>0)):[],outputShape:f?Array.from(s().subarray(Number(f)>>>0,Number(g)>>>0)):[],activation:Oe(_)})},881067:(e,n,r,i,a,o,l,u,d,c,h,m,f,g)=>{p.jb("ConvTranspose",e,{format:u?"NHWC":"NCHW",autoPad:n,dilations:Array.from(s().subarray(Number(r)>>>0,2+(Number(r)>>>0)>>>0)),group:i,kernelShape:Array.from(s().subarray(Number(a)>>>0,2+(Number(a)>>>0)>>>0)),pads:Array.from(s().subarray(Number(o)>>>0,4+(Number(o)>>>0)>>>0)),strides:Array.from(s().subarray(Number(l)>>>0,2+(Number(l)>>>0)>>>0)),wIsConst:()=>!!t()[d>>>0],outputPadding:c?Array.from(s().subarray(Number(c)>>>0,Number(h)>>>0)):[],outputShape:m?Array.from(s().subarray(Number(m)>>>0,Number(f)>>>0)):[],activation:Oe(g)})},881728:(e,n,r,i,a,o,l,u,d,c,h,m,f,g,_)=>{p.jb("ConvTranspose",e,{format:d?"NHWC":"NCHW",autoPad:n,dilations:[r],group:i,kernelShape:[a],pads:[o,l],strides:[u],wIsConst:()=>!!t()[c>>>0],outputPadding:h?Array.from(s().subarray(Number(h)>>>0,Number(m)>>>0)):[],outputShape:f?Array.from(s().subarray(Number(f)>>>0,Number(g)>>>0)):[],activation:Oe(_)})},882161:(e,n,r,i,a,o,l,u,d,c,h,m,f,g)=>{p.jb("ConvTranspose",e,{format:u?"NHWC":"NCHW",autoPad:n,dilations:Array.from(s().subarray(Number(r)>>>0,2+(Number(r)>>>0)>>>0)),group:i,kernelShape:Array.from(s().subarray(Number(a)>>>0,2+(Number(a)>>>0)>>>0)),pads:Array.from(s().subarray(Number(o)>>>0,4+(Number(o)>>>0)>>>0)),strides:Array.from(s().subarray(Number(l)>>>0,2+(Number(l)>>>0)>>>0)),wIsConst:()=>!!t()[d>>>0],outputPadding:c?Array.from(s().subarray(Number(c)>>>0,Number(h)>>>0)):[],outputShape:m?Array.from(s().subarray(Number(m)>>>0,Number(f)>>>0)):[],activation:Oe(g)})},882822:(e,t)=>{p.jb("GlobalAveragePool",e,{format:t?"NHWC":"NCHW"})},882913:(e,t,n,r,i,a,o,l,u,d,c,h,m,f)=>{p.jb("AveragePool",e,{format:f?"NHWC":"NCHW",auto_pad:t,ceil_mode:n,count_include_pad:r,storage_order:i,dilations:a?Array.from(s().subarray(Number(a)>>>0,Number(o)>>>0)):[],kernel_shape:l?Array.from(s().subarray(Number(l)>>>0,Number(u)>>>0)):[],pads:d?Array.from(s().subarray(Number(d)>>>0,Number(c)>>>0)):[],strides:h?Array.from(s().subarray(Number(h)>>>0,Number(m)>>>0)):[]})},883392:(e,t)=>{p.jb("GlobalAveragePool",e,{format:t?"NHWC":"NCHW"})},883483:(e,t,n,r,i,a,o,l,u,d,c,h,m,f)=>{p.jb("AveragePool",e,{format:f?"NHWC":"NCHW",auto_pad:t,ceil_mode:n,count_include_pad:r,storage_order:i,dilations:a?Array.from(s().subarray(Number(a)>>>0,Number(o)>>>0)):[],kernel_shape:l?Array.from(s().subarray(Number(l)>>>0,Number(u)>>>0)):[],pads:d?Array.from(s().subarray(Number(d)>>>0,Number(c)>>>0)):[],strides:h?Array.from(s().subarray(Number(h)>>>0,Number(m)>>>0)):[]})},883962:(e,t)=>{p.jb("GlobalMaxPool",e,{format:t?"NHWC":"NCHW"})},884049:(e,t,n,r,i,a,o,l,u,d,c,h,m,f)=>{p.jb("MaxPool",e,{format:f?"NHWC":"NCHW",auto_pad:t,ceil_mode:n,count_include_pad:r,storage_order:i,dilations:a?Array.from(s().subarray(Number(a)>>>0,Number(o)>>>0)):[],kernel_shape:l?Array.from(s().subarray(Number(l)>>>0,Number(u)>>>0)):[],pads:d?Array.from(s().subarray(Number(d)>>>0,Number(c)>>>0)):[],strides:h?Array.from(s().subarray(Number(h)>>>0,Number(m)>>>0)):[]})},884524:(e,t)=>{p.jb("GlobalMaxPool",e,{format:t?"NHWC":"NCHW"})},884611:(e,t,n,r,i,a,o,l,u,d,c,h,m,f)=>{p.jb("MaxPool",e,{format:f?"NHWC":"NCHW",auto_pad:t,ceil_mode:n,count_include_pad:r,storage_order:i,dilations:a?Array.from(s().subarray(Number(a)>>>0,Number(o)>>>0)):[],kernel_shape:l?Array.from(s().subarray(Number(l)>>>0,Number(u)>>>0)):[],pads:d?Array.from(s().subarray(Number(d)>>>0,Number(c)>>>0)):[],strides:h?Array.from(s().subarray(Number(h)>>>0,Number(m)>>>0)):[]})},885086:(e,t,n,r,i)=>{p.jb("Gemm",e,{alpha:t,beta:n,transA:r,transB:i})},885190:e=>{p.jb("MatMul",e,void 0)},885244:(e,t,n,r)=>{p.jb("ArgMax",e,{keepDims:!!t,selectLastIndex:!!n,axis:r})},885352:(e,t,n,r)=>{p.jb("ArgMin",e,{keepDims:!!t,selectLastIndex:!!n,axis:r})},885460:(e,t)=>{p.jb("Softmax",e,{axis:t})},885523:(e,t)=>{p.jb("Concat",e,{axis:t})},885583:(e,t,n,r,i)=>{p.jb("Split",e,{axis:t,numOutputs:n,splitSizes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},885739:e=>{p.jb("Expand",e,void 0)},885793:(e,t)=>{p.jb("Gather",e,{axis:Number(t)})},885864:(e,t)=>{p.jb("GatherElements",e,{axis:Number(t)})},885943:(e,t,n,r,i,a,o,l,u,d,c)=>{p.jb("Resize",e,{antialias:t,axes:n?Array.from(s().subarray(Number(n)>>>0,Number(r)>>>0)):[],coordinateTransformMode:Oe(i),cubicCoeffA:a,excludeOutside:o,extrapolationValue:l,keepAspectRatioPolicy:Oe(u),mode:Oe(d),nearestMode:Oe(c)})},886305:(e,t,n,r,i,a,o)=>{p.jb("Slice",e,{starts:t?Array.from(s().subarray(Number(t)>>>0,Number(n)>>>0)):[],ends:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[],axes:a?Array.from(s().subarray(Number(a)>>>0,Number(o)>>>0)):[]})},886569:e=>{p.jb("Tile",e,void 0)},886621:(e,t,n)=>{p.jb("InstanceNormalization",e,{epsilon:t,format:n?"NHWC":"NCHW"})},886735:(e,t,n)=>{p.jb("InstanceNormalization",e,{epsilon:t,format:n?"NHWC":"NCHW"})},886849:e=>{p.jb("Range",e,void 0)},886902:(e,t)=>{p.jb("Einsum",e,{equation:Oe(t)})},886983:(e,t,n,r,i)=>{p.jb("Pad",e,{mode:t,value:n,pads:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},887126:(e,t,n,r,i,a)=>{p.jb("BatchNormalization",e,{epsilon:t,momentum:n,spatial:!!i,trainingMode:!!r,format:a?"NHWC":"NCHW"})},887295:(e,t,n,r,i,a)=>{p.jb("BatchNormalization",e,{epsilon:t,momentum:n,spatial:!!i,trainingMode:!!r,format:a?"NHWC":"NCHW"})},887464:(e,t,n)=>{p.jb("CumSum",e,{exclusive:Number(t),reverse:Number(n)})},887561:(e,t,n)=>{p.jb("DequantizeLinear",e,{axis:t,blockSize:n})},887651:(e,t,n,r,i)=>{p.jb("GridSample",e,{align_corners:t,mode:Oe(n),padding_mode:Oe(r),format:i?"NHWC":"NCHW"})},887821:(e,t,n,r,i)=>{p.jb("GridSample",e,{align_corners:t,mode:Oe(n),padding_mode:Oe(r),format:i?"NHWC":"NCHW"})},887991:(e,t,n,r,i,a,o,l,u)=>{p.jb("Attention",e,{numHeads:t,isUnidirectional:n,maskFilterValue:r,scale:i,doRotary:a,qkvHiddenSizes:o?Array.from(s().subarray(Number(l)>>>0,Number(l)+o>>>0)):[],pastPresentShareBuffer:!!u})},888263:e=>{p.jb("BiasAdd",e,void 0)},888318:e=>{p.jb("BiasSplitGelu",e,void 0)},888379:e=>{p.jb("FastGelu",e,void 0)},888435:(e,n,r,i,a,o,u,d,c,h,m,f,g,_,w,b)=>{p.jb("Conv",e,{format:f?"NHWC":"NCHW",auto_pad:n,dilations:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[],group:a,kernel_shape:o?Array.from(s().subarray(Number(o)>>>0,Number(u)>>>0)):[],pads:d?Array.from(s().subarray(Number(d)>>>0,Number(c)>>>0)):[],strides:h?Array.from(s().subarray(Number(h)>>>0,Number(m)>>>0)):[],w_is_const:()=>!!t()[Number(g)>>>0],activation:Oe(_),activation_params:w?Array.from(l().subarray(Number(w)>>>0,Number(b)>>>0)):[]})},889019:e=>{p.jb("Gelu",e,void 0)},889071:(e,t,n,r,i,a,s,o,l)=>{p.jb("GroupQueryAttention",e,{numHeads:t,kvNumHeads:n,scale:r,softcap:i,doRotary:a,rotaryInterleaved:s,smoothSoftmax:o,localWindowSize:l})},889288:(e,t,n,r)=>{p.jb("LayerNormalization",e,{axis:t,epsilon:n,simplified:!!r})},889399:(e,t,n,r)=>{p.jb("LayerNormalization",e,{axis:t,epsilon:n,simplified:!!r})},889510:(e,t,n,r,i,a)=>{p.jb("MatMulNBits",e,{k:t,n,accuracyLevel:r,bits:i,blockSize:a})},889637:(e,t,n,r,i,a)=>{p.jb("MultiHeadAttention",e,{numHeads:t,isUnidirectional:n,maskFilterValue:r,scale:i,doRotary:a})},889796:(e,t)=>{p.jb("QuickGelu",e,{alpha:t})},889860:(e,t,n,r,i)=>{p.jb("RotaryEmbedding",e,{interleaved:!!t,numHeads:n,rotaryEmbeddingDim:r,scale:i})},889999:(e,t,n)=>{p.jb("SkipLayerNormalization",e,{epsilon:t,simplified:!!n})},890101:(e,t,n)=>{p.jb("SkipLayerNormalization",e,{epsilon:t,simplified:!!n})},890203:(e,t,n,r)=>{p.jb("GatherBlockQuantized",e,{gatherAxis:t,quantizeAxis:n,blockSize:r})},890324:e=>{p.Zb(e)},890358:(e,t)=>p.bc(Number(e),Number(t),p.Fb.fc,p.Fb.errors)};function oe(e,t,n){return tn((async()=>{await p.Xb(Number(e),Number(t),Number(n))}))}function le(){return typeof wasmOffsetConverter<"u"}function ue(e){this.name="ExitStatus",this.message=`Program terminated with exit(${e})`,this.status=e}var de=e=>{e.terminate(),e.onmessage=()=>{}},ce=e=>{0==_e.length&&(ke(),Te(_e[0]));var t=_e.pop();if(!t)return 6;we.push(t),xe[e.Ab]=t,t.Ab=e.Ab;var n={cmd:"run",start_routine:e.hc,arg:e.Qb,pthread_ptr:e.Ab};return t.postMessage(n,e.mc),0},pe=0,he=(e,t,...n)=>{for(var r=2*n.length,i=Ar(),a=Fr(8*r),s=a>>>3,o=0;o>>0]=l)}return e=kr(e,0,r,a,t),Er(i),e};function me(e){if(g)return he(0,1,e);if(I=e,!(0{if(I=e,g)throw fe(e),"unwind";me(e)},_e=[],we=[],be=[],xe={},ve=e=>{var t=e.Ab;delete xe[t],_e.push(e),we.splice(we.indexOf(e),1),e.Ab=0,$r(t)};function Me(){be.forEach((e=>e()))}var Te=e=>new Promise((t=>{e.onmessage=n=>{var r=(n=n.data).cmd;if(n.targetThread&&n.targetThread!=yr()){var i=xe[n.targetThread];i?i.postMessage(n,n.transferList):S(`Internal error! Worker sent a message "${r}" to target pthread ${n.targetThread}, but that thread no longer exists!`)}else"checkMailbox"===r?Bt():"spawnThread"===r?ce(n):"cleanupThread"===r?ve(xe[n.thread]):"killThread"===r?(n=n.thread,r=xe[n],delete xe[n],de(r),$r(n),we.splice(we.indexOf(r),1),r.Ab=0):"cancelThread"===r?xe[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(e.loaded=!0,t(e)):"alert"===r?alert(`Thread ${n.threadId}: ${n.text}`):"setimmediate"===n.target?e.postMessage(n):"callHandler"===r?p[n.handler](...n.args):r&&S(`worker sent an unknown command ${r}`)},e.onerror=e=>{throw S(`worker sent an error! ${e.filename}:${e.lineno}: ${e.message}`),e};var n,r=[];for(n of[])p.hasOwnProperty(n)&&r.push(n);e.postMessage({cmd:"load",handlers:r,wasmMemory:F,wasmModule:A})}));function ke(){var e=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});_e.push(e)}var $e=e=>{for(;0{var e=yr(),t=o()[e+52>>>2>>>0];e=o()[e+56>>>2>>>0],Pr(t,t-e),Er(t)},Se=(e,t)=>{pe=0,e=Ir(e,t),0>>=0);throw t>>>=0,n>>>=0,o()[r.Jb+16>>>2>>>0]=0,o()[r.Jb+4>>>2>>>0]=t,o()[r.Jb+8>>>2>>>0]=n,e}function Fe(e,t,n,r){return g?he(2,1,e,t,n,r):Ae(e,t,n,r)}function Ae(e,t,n,r){if(e>>>=0,t>>>=0,n>>>=0,r>>>=0,void 0===_)return S("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var i=[];return g&&0===i.length?Fe(e,t,n,r):(e={hc:n,Ab:e,Qb:r,mc:i},g?(e.Mb="spawnThread",postMessage(e,i),0):ce(e))}var Ie=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,ze=(e,t,n)=>{var r=(t>>>=0)+n;for(n=t;e[n]&&!(n>=r);)++n;if(16(i=224==(240&i)?(15&i)<<12|a<<6|s:(7&i)<<18|a<<12|s<<6|63&e[t++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r},Oe=(e,t)=>(e>>>=0)?ze(r(),e,t):"";function Be(e,t,n){return g?he(3,1,e,t,n):0}function Le(e,t){if(g)return he(4,1,e,t)}var Ne=e=>{for(var t=0,n=0;n=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t},De=(e,t,n,r)=>{if(!(0>>=0;r=n+r-1;for(var a=0;a=s&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++a)),127>=s){if(n>=r)break;t[n++>>>0]=s}else{if(2047>=s){if(n+1>=r)break;t[n++>>>0]=192|s>>6}else{if(65535>=s){if(n+2>=r)break;t[n++>>>0]=224|s>>12}else{if(n+3>=r)break;t[n++>>>0]=240|s>>18,t[n++>>>0]=128|s>>12&63}t[n++>>>0]=128|s>>6&63}t[n++>>>0]=128|63&s}}return t[n>>>0]=0,n-i},Re=(e,t,n)=>De(e,r(),t,n);function Ve(e,t){if(g)return he(5,1,e,t)}function je(e,t,n){if(g)return he(6,1,e,t,n)}function qe(e,t,n){return g?he(7,1,e,t,n):0}function Ge(e,t){if(g)return he(8,1,e,t)}function We(e,t,n){if(g)return he(9,1,e,t,n)}function Ue(e,t,n,r){if(g)return he(10,1,e,t,n,r)}function He(e,t,n,r){if(g)return he(11,1,e,t,n,r)}function Xe(e,t,n,r){if(g)return he(12,1,e,t,n,r)}function Ke(e){if(g)return he(13,1,e)}function Qe(e,t){if(g)return he(14,1,e,t)}function Ye(e,t,n){if(g)return he(15,1,e,t,n)}var Ze,Je,et=()=>{J("")},tt=e=>{for(var t="";r()[e>>>0];)t+=Ze[r()[e++>>>0]];return t},nt={},rt={},it={};function at(e,t,n={}){if(!("argPackAdvance"in t))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(e,t,n={}){var r=t.name;if(!e)throw new Je(`type "${r}" must have a positive integer typeid pointer`);if(rt.hasOwnProperty(e)){if(n.Sb)return;throw new Je(`Cannot register type '${r}' twice`)}rt[e]=t,delete it[e],nt.hasOwnProperty(e)&&(t=nt[e],delete nt[e],t.forEach((e=>e())))}(e,t,n)}var st=(e,n,l)=>{switch(n){case 1:return l?e=>t()[e>>>0]:e=>r()[e>>>0];case 2:return l?e=>i()[e>>>1>>>0]:e=>a()[e>>>1>>>0];case 4:return l?e=>s()[e>>>2>>>0]:e=>o()[e>>>2>>>0];case 8:return l?e=>V[e>>>3]:e=>j[e>>>3];default:throw new TypeError(`invalid integer width (${n}): ${e}`)}};function ot(e,t,n){n>>>=0,at(e>>>=0,{name:t=tt(t>>>0),fromWireType:e=>e,toWireType:function(e,t){if("bigint"!=typeof t&&"number"!=typeof t)throw t=null===t?"null":"object"==(e=typeof t)||"array"===e||"function"===e?t.toString():""+t,new TypeError(`Cannot convert "${t}" to ${this.name}`);return"number"==typeof t&&(t=BigInt(t)),t},argPackAdvance:lt,readValueFromPointer:st(t,n,-1==t.indexOf("u")),Db:null})}var lt=8;function ut(e,t,n,i){at(e>>>=0,{name:t=tt(t>>>0),fromWireType:function(e){return!!e},toWireType:function(e,t){return t?n:i},argPackAdvance:lt,readValueFromPointer:function(e){return this.fromWireType(r()[e>>>0])},Db:null})}var dt=[],ct=[];function pt(e){9<(e>>>=0)&&0==--ct[e+1]&&(ct[e]=void 0,dt.push(e))}var ht=e=>{if(!e)throw new Je("Cannot use deleted val. handle = "+e);return ct[e]},mt=e=>{switch(e){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let t=dt.pop()||ct.length;return ct[t]=e,ct[t+1]=1,t}};function ft(e){return this.fromWireType(o()[e>>>2>>>0])}var gt={name:"emscripten::val",fromWireType:e=>{var t=ht(e);return pt(e),t},toWireType:(e,t)=>mt(t),argPackAdvance:lt,readValueFromPointer:ft,Db:null};function _t(e){return at(e>>>0,gt)}var wt=(e,t)=>{switch(t){case 4:return function(e){return this.fromWireType(l()[e>>>2>>>0])};case 8:return function(e){return this.fromWireType(u()[e>>>3>>>0])};default:throw new TypeError(`invalid float width (${t}): ${e}`)}};function bt(e,t,n){n>>>=0,at(e>>>=0,{name:t=tt(t>>>0),fromWireType:e=>e,toWireType:(e,t)=>t,argPackAdvance:lt,readValueFromPointer:wt(t,n),Db:null})}function yt(e,t,n,r,i){if(e>>>=0,n>>>=0,t=tt(t>>>0),-1===i&&(i=4294967295),i=e=>e,0===r){var a=32-8*n;i=e=>e<>>a}var s=t.includes("unsigned")?function(e,t){return t>>>0}:function(e,t){return t};at(e,{name:t,fromWireType:i,toWireType:s,argPackAdvance:lt,readValueFromPointer:st(t,n,0!==r),Db:null})}function xt(e,n,r){function i(e){var n=o()[e>>>2>>>0];return e=o()[e+4>>>2>>>0],new a(t().buffer,e,n)}var a=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][n];at(e>>>=0,{name:r=tt(r>>>0),fromWireType:i,argPackAdvance:lt,readValueFromPointer:i},{Sb:!0})}function vt(e,t){e>>>=0;var n="std::string"===(t=tt(t>>>0));at(e,{name:t,fromWireType:function(e){var t=o()[e>>>2>>>0],i=e+4;if(n)for(var a=i,s=0;s<=t;++s){var l=i+s;if(s==t||0==r()[l>>>0]){if(a=Oe(a,l-a),void 0===u)var u=a;else u+=String.fromCharCode(0),u+=a;a=l+1}}else{for(u=Array(t),s=0;s>>0]);u=u.join("")}return xr(e),u},toWireType:function(e,t){t instanceof ArrayBuffer&&(t=new Uint8Array(t));var i="string"==typeof t;if(!(i||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int8Array))throw new Je("Cannot pass non-string to std::string");var a=n&&i?Ne(t):t.length,s=vr(4+a+1),l=s+4;if(o()[s>>>2>>>0]=a,n&&i)Re(t,l,a+1);else if(i)for(i=0;i>>0]=u}else for(i=0;i>>0]=t[i];return null!==e&&e.push(xr,s),s},argPackAdvance:lt,readValueFromPointer:ft,Db(e){xr(e)}})}var Mt=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Tt=(e,t)=>{for(var n=e>>1,s=n+t/2;!(n>=s)&&a()[n>>>0];)++n;if(32<(n<<=1)-e&&Mt)return Mt.decode(r().slice(e,n));for(n="",s=0;!(s>=t/2);++s){var o=i()[e+2*s>>>1>>>0];if(0==o)break;n+=String.fromCharCode(o)}return n},kt=(e,t,n)=>{if(n??=2147483647,2>n)return 0;var r=t;n=(n-=2)<2*e.length?n/2:e.length;for(var a=0;a>>1>>>0]=s,t+=2}return i()[t>>>1>>>0]=0,t-r},$t=e=>2*e.length,Ct=(e,t)=>{for(var n=0,r="";!(n>=t/4);){var i=s()[e+4*n>>>2>>>0];if(0==i)break;++n,65536<=i?(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i)):r+=String.fromCharCode(i)}return r},St=(e,t,n)=>{if(t>>>=0,n??=2147483647,4>n)return 0;var r=t;n=r+n-4;for(var i=0;i=a&&(a=65536+((1023&a)<<10)|1023&e.charCodeAt(++i)),s()[t>>>2>>>0]=a,(t+=4)+4>n)break}return s()[t>>>2>>>0]=0,t-r},Pt=e=>{for(var t=0,n=0;n=r&&++n,t+=4}return t};function Et(e,t,n){if(e>>>=0,t>>>=0,n=tt(n>>>=0),2===t)var r=Tt,i=kt,s=$t,l=e=>a()[e>>>1>>>0];else 4===t&&(r=Ct,i=St,s=Pt,l=e=>o()[e>>>2>>>0]);at(e,{name:n,fromWireType:e=>{for(var n,i=o()[e>>>2>>>0],a=e+4,s=0;s<=i;++s){var u=e+4+s*t;s!=i&&0!=l(u)||(a=r(a,u-a),void 0===n?n=a:(n+=String.fromCharCode(0),n+=a),a=u+t)}return xr(e),n},toWireType:(e,r)=>{if("string"!=typeof r)throw new Je(`Cannot pass non-string to C++ string type ${n}`);var a=s(r),l=vr(4+a+t);return o()[l>>>2>>>0]=a/t,i(r,l+4,a+t),null!==e&&e.push(xr,l),l},argPackAdvance:lt,readValueFromPointer:ft,Db(e){xr(e)}})}function Ft(e,t){at(e>>>=0,{Tb:!0,name:t=tt(t>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var At=()=>1;function It(e){Mr(e>>>0,!f,1,!m,131072,!1),Me()}var zt=e=>{if(!G)try{if(e(),!(0>>=0,"function"==typeof Atomics.nc&&(Atomics.nc(s(),e>>>2,e).value.then(Bt),e+=128,Atomics.store(s(),e>>>2,1))}var Bt=()=>{var e=yr();e&&(Ot(e),zt(Sr))};function Lt(e,t){(e>>>=0)==t>>>0?setTimeout(Bt):g?postMessage({targetThread:e,cmd:"checkMailbox"}):(e=xe[e])&&e.postMessage({cmd:"checkMailbox"})}var Nt=[];function Dt(e,t,n,r,i){for(t>>>=0,r/=2,Nt.length=r,n=i>>>0>>>3,i=0;i>>0];return(t?se[t]:fr[e])(...Nt)}function Rt(e){e>>>=0,g?postMessage({cmd:"cleanupThread",thread:e}):ve(xe[e])}function Vt(e){}var jt=(e,t)=>{var n=rt[e];if(void 0===n)throw e=_r(e),n=tt(e),xr(e),new Je(`${t} has unknown type ${n}`);return n},qt=(e,t,n)=>{var r=[];return e=e.toWireType(r,n),r.length&&(o()[t>>>2>>>0]=mt(r)),e};function Gt(e,t,n){return t>>>=0,n>>>=0,e=ht(e>>>0),t=jt(t,"emval::as"),qt(t,n,e)}var Wt=e=>{try{e()}catch(e){J(e)}},Ut=0,Ht=null,Xt=0,Kt=[],Qt={},Yt={},Zt=0,Jt=null,en=[];function tn(e){return function(){if(!G){if(0===Ut){var t=!1,n=!1;(t=>{e().then(t)})(((e=0)=>{if(!G&&(Xt=e,t=!0,n)){Ut=2,Wt((()=>Br(Ht))),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.resume(),e=!1;try{var r=(o=s()[Ht+8>>>2>>>0],o=gr[Yt[o]],--pe,o())}catch(o){r=o,e=!0}var i=!1;if(!Ht){var a=Jt;a&&(Jt=null,(e?a.reject:a.resolve)(r),i=!0)}if(e&&!i)throw r}var o})),n=!0,t||(Ut=1,Ht=function(){var e=vr(65548),t=e+12;o()[e>>>2>>>0]=t,o()[e+4>>>2>>>0]=t+65536,t=Kt[0];var n=Qt[t];return void 0===n&&(n=Zt++,Qt[t]=n,Yt[n]=t),t=n,s()[e+8>>>2>>>0]=t,e}(),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.pause(),Wt((()=>zr(Ht))))}else 2===Ut?(Ut=0,Wt(Lr),xr(Ht),Ht=null,en.forEach(zt)):J(`invalid state: ${Ut}`);return Xt}}()}function nn(e){return e>>>=0,tn((()=>(e=ht(e)).then(mt)))}var rn=[];function an(e,t,n,r){return n>>>=0,r>>>=0,(e=rn[e>>>0])(null,t=ht(t>>>0),n,r)}var sn={},on=e=>{var t=sn[e];return void 0===t?tt(e):t};function ln(e,t,n,r,i){return n>>>=0,r>>>=0,i>>>=0,(e=rn[e>>>0])(t=ht(t>>>0),t[n=on(n)],r,i)}var un=()=>"object"==typeof globalThis?globalThis:Function("return this")();function dn(e){return 0==(e>>>=0)?mt(un()):(e=on(e),mt(un()[e]))}var cn=e=>{var t=rn.length;return rn.push(e),t},pn=(e,t)=>{for(var n=Array(e),r=0;r>>2>>>0],"parameter "+r);return n},hn=(e,t)=>Object.defineProperty(t,"name",{value:e});function mn(e,t,n){var r=(t=pn(e,t>>>0)).shift();e--;var i="return function (obj, func, destructorsRef, args) {\n",a=0,s=[];0===n&&s.push("obj");for(var o=["retType"],l=[r],u=0;ue.name)).join(", ")}) => ${r.name}>`,cn(hn(n,e))}function fn(e){return e=on(e>>>0),mt(p[e])}function gn(e,t){return t>>>=0,e=ht(e>>>0),t=ht(t),mt(e[t])}function _n(e){9<(e>>>=0)&&(ct[e+1]+=1)}function wn(){return mt([])}function bn(e){e=ht(e>>>0);for(var t=Array(e.length),n=0;n>>0))}function xn(){return mt({})}function vn(e){for(var t=ht(e>>>=0);t.length;){var n=t.pop();t.pop()(n)}pt(e)}function Mn(e,t,n){t>>>=0,n>>>=0,e=ht(e>>>0),t=ht(t),n=ht(n),e[t]=n}function Tn(e,t){return t>>>=0,e=(e=jt(e>>>0,"_emval_take_value")).readValueFromPointer(t),mt(e)}function kn(e,t){e=-9007199254740992>e||9007199254740992>>=0,e=new Date(1e3*e),s()[t>>>2>>>0]=e.getUTCSeconds(),s()[t+4>>>2>>>0]=e.getUTCMinutes(),s()[t+8>>>2>>>0]=e.getUTCHours(),s()[t+12>>>2>>>0]=e.getUTCDate(),s()[t+16>>>2>>>0]=e.getUTCMonth(),s()[t+20>>>2>>>0]=e.getUTCFullYear()-1900,s()[t+24>>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,s()[t+28>>>2>>>0]=e}var $n=e=>e%4==0&&(e%100!=0||e%400==0),Cn=[0,31,60,91,121,152,182,213,244,274,305,335],Sn=[0,31,59,90,120,151,181,212,243,273,304,334];function Pn(e,t){e=-9007199254740992>e||9007199254740992>>=0,e=new Date(1e3*e),s()[t>>>2>>>0]=e.getSeconds(),s()[t+4>>>2>>>0]=e.getMinutes(),s()[t+8>>>2>>>0]=e.getHours(),s()[t+12>>>2>>>0]=e.getDate(),s()[t+16>>>2>>>0]=e.getMonth(),s()[t+20>>>2>>>0]=e.getFullYear()-1900,s()[t+24>>>2>>>0]=e.getDay();var n=($n(e.getFullYear())?Cn:Sn)[e.getMonth()]+e.getDate()-1|0;s()[t+28>>>2>>>0]=n,s()[t+36>>>2>>>0]=-60*e.getTimezoneOffset(),n=new Date(e.getFullYear(),6,1).getTimezoneOffset();var r=new Date(e.getFullYear(),0,1).getTimezoneOffset();e=0|(n!=r&&e.getTimezoneOffset()==Math.min(r,n)),s()[t+32>>>2>>>0]=e}function En(e){e>>>=0;var t=new Date(s()[e+20>>>2>>>0]+1900,s()[e+16>>>2>>>0],s()[e+12>>>2>>>0],s()[e+8>>>2>>>0],s()[e+4>>>2>>>0],s()[e>>>2>>>0],0),n=s()[e+32>>>2>>>0],r=t.getTimezoneOffset(),i=new Date(t.getFullYear(),6,1).getTimezoneOffset(),a=new Date(t.getFullYear(),0,1).getTimezoneOffset(),o=Math.min(a,i);return 0>n?s()[e+32>>>2>>>0]=+(i!=a&&o==r):0>>2>>>0]=t.getDay(),n=($n(t.getFullYear())?Cn:Sn)[t.getMonth()]+t.getDate()-1|0,s()[e+28>>>2>>>0]=n,s()[e>>>2>>>0]=t.getSeconds(),s()[e+4>>>2>>>0]=t.getMinutes(),s()[e+8>>>2>>>0]=t.getHours(),s()[e+12>>>2>>>0]=t.getDate(),s()[e+16>>>2>>>0]=t.getMonth(),s()[e+20>>>2>>>0]=t.getYear(),e=t.getTime(),BigInt(isNaN(e)?-1:e/1e3)}function Fn(e,t,n,r,i,a,s){return g?he(16,1,e,t,n,r,i,a,s):-52}function An(e,t,n,r,i,a){if(g)return he(17,1,e,t,n,r,i,a)}function In(e,t,n,r){e>>>=0,t>>>=0,n>>>=0,r>>>=0;var i=(new Date).getFullYear(),a=new Date(i,0,1),l=new Date(i,6,1);i=a.getTimezoneOffset();var u=l.getTimezoneOffset(),d=Math.max(i,u);o()[e>>>2>>>0]=60*d,s()[t>>>2>>>0]=+(i!=u),a=(e=e=>e.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(a),l=e(l),u{zn.length=0;for(var n;n=r()[e++>>>0];){var i=105!=n;t+=(i&=112!=n)&&t%8?4:0,zn.push(112==n?o()[t>>>2>>>0]:106==n?V[t>>>3]:105==n?s()[t>>>2>>>0]:u()[t>>>3>>>0]),t+=i?8:4}return zn};function Bn(e,t,n){return e>>>=0,t=On(t>>>0,n>>>0),se[e](...t)}function Ln(e,t,n){return e>>>=0,t=On(t>>>0,n>>>0),se[e](...t)}var Nn=()=>{},Dn=()=>Date.now();function Rn(e,t){return S(Oe(e>>>0,t>>>0))}var Vn,jn=()=>{throw pe+=1,"unwind"};function qn(){return 4294901760}Vn=()=>performance.timeOrigin+performance.now();var Gn=()=>navigator.hardwareConcurrency;function Wn(){return J("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Un(e){e>>>=0;var t=r().length;if(e<=t||4294901760=n;n*=2){var i=t*(1+.2/n);i=Math.min(i,e+100663296);var a=Math;i=Math.max(e,i);e:{a=(a.min.call(a,4294901760,i+(65536-i%65536)%65536)-F.buffer.byteLength+65535)/65536;try{F.grow(a),W();var s=1;break e}catch{}s=void 0}if(s)return!0}return!1}var Hn=()=>(J("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Xn={},Kn=e=>{e.forEach((e=>{var t=Hn();t&&(Xn[t]=e)}))};function Qn(){var e=Error().stack.toString().split("\n");return"Error"==e[0]&&e.shift(),Kn(e),Xn.Pb=Hn(),Xn.ec=e,Xn.Pb}function Yn(e,t,n){if(e>>>=0,t>>>=0,Xn.Pb==e)var r=Xn.ec;else"Error"==(r=Error().stack.toString().split("\n"))[0]&&r.shift(),Kn(r);for(var i=3;r[i]&&Hn()!=e;)++i;for(e=0;e>>2>>>0]=Hn();return e}var Zn,Jn={},er=()=>{if(!Zn){var e,t={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:"./this.program"};for(e in Jn)void 0===Jn[e]?delete t[e]:t[e]=Jn[e];var n=[];for(e in t)n.push(`${e}=${t[e]}`);Zn=n}return Zn};function tr(e,n){if(g)return he(18,1,e,n);e>>>=0,n>>>=0;var r=0;return er().forEach(((i,a)=>{var s=n+r;for(a=o()[e+4*a>>>2>>>0]=s,s=0;s>>0]=i.charCodeAt(s);t()[a>>>0]=0,r+=i.length+1})),0}function nr(e,t){if(g)return he(19,1,e,t);e>>>=0,t>>>=0;var n=er();o()[e>>>2>>>0]=n.length;var r=0;return n.forEach((e=>r+=e.length+1)),o()[t>>>2>>>0]=r,0}function rr(e){return g?he(20,1,e):52}function ir(e,t,n,r){return g?he(21,1,e,t,n,r):52}function ar(e,t,n,r){return g?he(22,1,e,t,n,r):70}var sr=[null,[],[]];function or(e,t,n,i){if(g)return he(23,1,e,t,n,i);t>>>=0,n>>>=0,i>>>=0;for(var a=0,s=0;s>>2>>>0],u=o()[t+4>>>2>>>0];t+=8;for(var d=0;d>>0],p=sr[e];0===c||10===c?((1===e?C:S)(ze(p,0)),p.length=0):p.push(c)}a+=u}return o()[i>>>2>>>0]=a,0}var lr=[31,29,31,30,31,30,31,31,30,31,30,31],ur=[31,28,31,30,31,30,31,31,30,31,30,31],dr=(e,n)=>{t().set(e,n>>>0)};function cr(e,t,n,r){function i(e,t,n){for(e="number"==typeof e?e.toString():e||"";e.lengthe?-1:0r-e.getDate())){e.setDate(e.getDate()+t);break}t-=r-e.getDate()+1,e.setDate(1),11>n?e.setMonth(n+1):(e.setMonth(0),e.setFullYear(e.getFullYear()+1))}return n=new Date(e.getFullYear()+1,0,4),t=u(new Date(e.getFullYear(),0,4)),n=u(n),0>=l(t,e)?0>=l(n,e)?e.getFullYear()+1:e.getFullYear():e.getFullYear()-1}e>>>=0,t>>>=0,n>>>=0,r>>>=0;var c=o()[r+40>>>2>>>0];for(var p in r={kc:s()[r>>>2>>>0],jc:s()[r+4>>>2>>>0],Hb:s()[r+8>>>2>>>0],Lb:s()[r+12>>>2>>>0],Ib:s()[r+16>>>2>>>0],Cb:s()[r+20>>>2>>>0],ub:s()[r+24>>>2>>>0],Bb:s()[r+28>>>2>>>0],sc:s()[r+32>>>2>>>0],ic:s()[r+36>>>2>>>0],lc:c?Oe(c):""},n=Oe(n),c={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(p,"g"),c[p]);var h,m,f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),g="January February March April May June July August September October November December".split(" ");for(p in c={"%a":e=>f[e.ub].substring(0,3),"%A":e=>f[e.ub],"%b":e=>g[e.Ib].substring(0,3),"%B":e=>g[e.Ib],"%C":e=>a((e.Cb+1900)/100|0,2),"%d":e=>a(e.Lb,2),"%e":e=>i(e.Lb,2," "),"%g":e=>d(e).toString().substring(2),"%G":d,"%H":e=>a(e.Hb,2),"%I":e=>(0==(e=e.Hb)?e=12:12{for(var t=0,n=0;n<=e.Ib-1;t+=($n(e.Cb+1900)?lr:ur)[n++]);return a(e.Lb+t,3)},"%m":e=>a(e.Ib+1,2),"%M":e=>a(e.jc,2),"%n":()=>"\n","%p":e=>0<=e.Hb&&12>e.Hb?"AM":"PM","%S":e=>a(e.kc,2),"%t":()=>"\t","%u":e=>e.ub||7,"%U":e=>a(Math.floor((e.Bb+7-e.ub)/7),2),"%V":e=>{var t=Math.floor((e.Bb+7-(e.ub+6)%7)/7);if(2>=(e.ub+371-e.Bb-2)%7&&t++,t)53==t&&(4==(n=(e.ub+371-e.Bb)%7)||3==n&&$n(e.Cb)||(t=1));else{t=52;var n=(e.ub+7-e.Bb-1)%7;(4==n||5==n&&$n(e.Cb%400-1))&&t++}return a(t,2)},"%w":e=>e.ub,"%W":e=>a(Math.floor((e.Bb+7-(e.ub+6)%7)/7),2),"%y":e=>(e.Cb+1900).toString().substring(2),"%Y":e=>e.Cb+1900,"%z":e=>(0<=(e=e.ic)?"+":"-")+("0000"+((e=Math.abs(e)/60)/60*100+e%60)).slice(-4),"%Z":e=>e.lc,"%%":()=>"%"},n=n.replace(/%%/g,"\0\0"),c)n.includes(p)&&(n=n.replace(new RegExp(p,"g"),c[p](r)));return h=n=n.replace(/\0\0/g,"%"),m=Array(Ne(h)+1),De(h,m,0,m.length),(p=m).length>t?0:(dr(p,e),p.length-1)}function pr(e,t,n,r){return cr(e>>>0,t>>>0,n>>>0,r>>>0)}g||function(){for(var e=p.numThreads-1;e--;)ke();U.unshift((()=>{var e;K++,e=()=>Z(),g?e():Promise.all(_e.map(Te)).then(e)}))}();for(var hr=Array(256),mr=0;256>mr;++mr)hr[mr]=String.fromCharCode(mr);Ze=hr,Je=p.BindingError=class extends Error{constructor(e){super(e),this.name="BindingError"}},p.InternalError=class extends Error{constructor(e){super(e),this.name="InternalError"}},ct.push(0,1,void 0,1,null,1,!0,1,!1,1),p.count_emval_handles=()=>ct.length/2-5-dt.length;var fr=[me,fe,Fe,Be,Le,Ve,je,qe,Ge,We,Ue,He,Xe,Ke,Qe,Ye,Fn,An,tr,nr,rr,ir,ar,or],gr=function(){function e(e,t){return gr=e.exports,gr=function(){var e=gr,t={};for(let[n,r]of Object.entries(e))t[n]="function"==typeof r?(...e)=>{Kt.push(n);try{return r(...e)}finally{G||(Kt.pop(),Ht&&1===Ut&&0===Kt.length&&(Ut=0,pe+=1,Wt(Or),typeof Fibers<"u"&&Fibers.tc()))}}:r;return t}(),n=gr,r=e=>t=>e(t)>>>0,i=e=>()=>e()>>>0,(n=Object.assign({},n)).Ca=r(n.Ca),n.fb=i(n.fb),n.hb=r(n.hb),n.emscripten_main_runtime_thread_id=i(n.emscripten_main_runtime_thread_id),n.sb=r(n.sb),n.tb=i(n.tb),gr=n,be.push(gr.ib),H.unshift(gr.Ba),A=t,Z(),gr;var n,r,i}var t,r,i,a=ae();if(K++,p.instantiateWasm)try{return p.instantiateWasm(a,e)}catch(t){S(`Module.instantiateWasm callback failed with error: ${t}`),c(t)}return ee||=p.locateFile?te("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":p.locateFile?p.locateFile("ort-wasm-simd-threaded.jsep.wasm",M):M+"ort-wasm-simd-threaded.jsep.wasm":new URL(n(/*! ort-wasm-simd-threaded.jsep.wasm */"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),n.b).href,(t=a,r=function(t){e(t.instance,t.module)},i=ee,T||"function"!=typeof WebAssembly.instantiateStreaming||te(i)||ne(i)||"function"!=typeof fetch?ie(i,t,r):fetch(i,{credentials:"same-origin"}).then((e=>WebAssembly.instantiateStreaming(e,t).then(r,(function(e){return S(`wasm streaming compile failed: ${e}`),S("falling back to ArrayBuffer instantiation"),ie(i,t,r)}))))).catch(c),{}}(),_r=e=>(_r=gr.Ca)(e),wr=()=>(wr=gr.Da)();p._OrtInit=(e,t)=>(p._OrtInit=gr.Ea)(e,t),p._OrtGetLastError=(e,t)=>(p._OrtGetLastError=gr.Fa)(e,t),p._OrtCreateSessionOptions=(e,t,n,r,i,a,s,o,l,u)=>(p._OrtCreateSessionOptions=gr.Ga)(e,t,n,r,i,a,s,o,l,u),p._OrtAppendExecutionProvider=(e,t)=>(p._OrtAppendExecutionProvider=gr.Ha)(e,t),p._OrtAddFreeDimensionOverride=(e,t,n)=>(p._OrtAddFreeDimensionOverride=gr.Ia)(e,t,n),p._OrtAddSessionConfigEntry=(e,t,n)=>(p._OrtAddSessionConfigEntry=gr.Ja)(e,t,n),p._OrtReleaseSessionOptions=e=>(p._OrtReleaseSessionOptions=gr.Ka)(e),p._OrtCreateSession=(e,t,n)=>(p._OrtCreateSession=gr.La)(e,t,n),p._OrtReleaseSession=e=>(p._OrtReleaseSession=gr.Ma)(e),p._OrtGetInputOutputCount=(e,t,n)=>(p._OrtGetInputOutputCount=gr.Na)(e,t,n),p._OrtGetInputName=(e,t)=>(p._OrtGetInputName=gr.Oa)(e,t),p._OrtGetOutputName=(e,t)=>(p._OrtGetOutputName=gr.Pa)(e,t),p._OrtFree=e=>(p._OrtFree=gr.Qa)(e),p._OrtCreateTensor=(e,t,n,r,i,a)=>(p._OrtCreateTensor=gr.Ra)(e,t,n,r,i,a),p._OrtGetTensorData=(e,t,n,r,i)=>(p._OrtGetTensorData=gr.Sa)(e,t,n,r,i),p._OrtReleaseTensor=e=>(p._OrtReleaseTensor=gr.Ta)(e),p._OrtCreateRunOptions=(e,t,n,r)=>(p._OrtCreateRunOptions=gr.Ua)(e,t,n,r),p._OrtAddRunConfigEntry=(e,t,n)=>(p._OrtAddRunConfigEntry=gr.Va)(e,t,n),p._OrtReleaseRunOptions=e=>(p._OrtReleaseRunOptions=gr.Wa)(e),p._OrtCreateBinding=e=>(p._OrtCreateBinding=gr.Xa)(e),p._OrtBindInput=(e,t,n)=>(p._OrtBindInput=gr.Ya)(e,t,n),p._OrtBindOutput=(e,t,n,r)=>(p._OrtBindOutput=gr.Za)(e,t,n,r),p._OrtClearBoundOutputs=e=>(p._OrtClearBoundOutputs=gr._a)(e),p._OrtReleaseBinding=e=>(p._OrtReleaseBinding=gr.$a)(e),p._OrtRunWithBinding=(e,t,n,r,i)=>(p._OrtRunWithBinding=gr.ab)(e,t,n,r,i),p._OrtRun=(e,t,n,r,i,a,s,o)=>(p._OrtRun=gr.bb)(e,t,n,r,i,a,s,o),p._OrtEndProfiling=e=>(p._OrtEndProfiling=gr.cb)(e),p._JsepOutput=(e,t,n)=>(p._JsepOutput=gr.db)(e,t,n),p._JsepGetNodeName=e=>(p._JsepGetNodeName=gr.eb)(e);var br,yr=()=>(yr=gr.fb)(),xr=p._free=e=>(xr=p._free=gr.gb)(e),vr=p._malloc=e=>(vr=p._malloc=gr.hb)(e),Mr=(e,t,n,r,i,a)=>(Mr=gr.kb)(e,t,n,r,i,a),Tr=()=>(Tr=gr.lb)(),kr=(e,t,n,r,i)=>(kr=gr.mb)(e,t,n,r,i),$r=e=>($r=gr.nb)(e),Cr=e=>(Cr=gr.ob)(e),Sr=()=>(Sr=gr.pb)(),Pr=(e,t)=>(Pr=gr.qb)(e,t),Er=e=>(Er=gr.rb)(e),Fr=e=>(Fr=gr.sb)(e),Ar=()=>(Ar=gr.tb)(),Ir=p.dynCall_ii=(e,t)=>(Ir=p.dynCall_ii=gr.vb)(e,t),zr=e=>(zr=gr.wb)(e),Or=()=>(Or=gr.xb)(),Br=e=>(Br=gr.yb)(e),Lr=()=>(Lr=gr.zb)();function Nr(){0Ar(),p.stackRestore=e=>Er(e),p.stackAlloc=e=>Fr(e),p.setValue=function(e,n,r="i8"){switch(r.endsWith("*")&&(r="*"),r){case"i1":case"i8":t()[e>>>0]=n;break;case"i16":i()[e>>>1>>>0]=n;break;case"i32":s()[e>>>2>>>0]=n;break;case"i64":V[e>>>3]=BigInt(n);break;case"float":l()[e>>>2>>>0]=n;break;case"double":u()[e>>>3>>>0]=n;break;case"*":o()[e>>>2>>>0]=n;break;default:J(`invalid type for setValue: ${r}`)}},p.getValue=function(e,n="i8"){switch(n.endsWith("*")&&(n="*"),n){case"i1":case"i8":return t()[e>>>0];case"i16":return i()[e>>>1>>>0];case"i32":return s()[e>>>2>>>0];case"i64":return V[e>>>3];case"float":return l()[e>>>2>>>0];case"double":return u()[e>>>3>>>0];case"*":return o()[e>>>2>>>0];default:J(`invalid type for getValue: ${n}`)}},p.UTF8ToString=Oe,p.stringToUTF8=Re,p.lengthBytesUTF8=Ne,Y=function e(){br||Nr(),br||(Y=e)},Nr(),p.PTR_SIZE=4,h},ve=xe,"em-pthread"===globalThis.self?.name&&xe()})),Hl=j((()=>{he(),Me=import.meta.url??(typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0),Te=typeof location>"u"?void 0:location.origin,ke=(e,t)=>{try{let n=t??Me;return(n?new URL(e,n):new URL(e)).origin===Te}catch{return!1}},$e=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Ce=(we(),G(me)).default,Se=async()=>{if(!Me)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(ke(Me))return[void 0,Ce()];let e=await $e(Me);return[e,Ce(e)]},Pe=(Ul(),G(be)).default,Ee=async(e,t,n)=>[void 0,Pe]})),Xl=j((()=>{Hl(),Ae=!1,Ie=!1,ze=!1,Oe=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Be=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Le=async e=>{if(Ae)return Promise.resolve();if(Ie)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(ze)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ie=!0;let t=e.initTimeout,n=e.numThreads;if(!Be())throw new Error("WebAssembly SIMD is not supported in the current environment.");let r=Oe();n>1&&!r&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+n+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=n=1);let i=e.wasmPaths,a="string"==typeof i?i:void 0,s=i?.mjs,o=s?.href??s,l=i?.wasm,u=l?.href??l,d=e.wasmBinary,[c,p]=await Ee(o,a,n>1),h=!1,m=[];if(t>0&&m.push(new Promise((e=>{setTimeout((()=>{h=!0,e()}),t)}))),m.push(new Promise(((e,t)=>{let r={numThreads:n};d?r.wasmBinary=d:(u||a)&&(r.locateFile=(e,t)=>u??(a??t)+e),p(r).then((t=>{Ie=!1,Ae=!0,Fe=t,e(),c&&URL.revokeObjectURL(c)}),(e=>{Ie=!1,ze=!0,t(e)}))}))),await Promise.race(m),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ne=()=>{if(Ae&&Fe)return Fe;throw new Error("WebAssembly is not initialized yet.")}})),Kl=j((()=>{Xl(),De=(e,t)=>{let n=Ne(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},Re=(e,t,n,r)=>{if("object"==typeof e&&null!==e){if(n.has(e))throw new Error("Circular reference in options");n.add(e)}Object.entries(e).forEach((([e,i])=>{let a=t?t+e:e;if("object"==typeof i)Re(i,a+".",n,r);else if("string"==typeof i||"number"==typeof i)r(a,i.toString());else{if("boolean"!=typeof i)throw new Error("Can't handle extra config type: "+typeof i);r(a,i?"1":"0")}}))},Ve=e=>{let t=Ne(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,4===n?"i32":"i64")),a=t.getValue(r+n,"*"),s=a?t.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${s}`)}finally{t.stackRestore(n)}}})),Ql=j((()=>{Xl(),Kl(),je=e=>{let t=Ne(),n=0,r=[],i=e||{};try{if(void 0===e?.logSeverityLevel)i.logSeverityLevel=2;else if("number"!=typeof e.logSeverityLevel||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(void 0===e?.logVerbosityLevel)i.logVerbosityLevel=0;else if("number"!=typeof e.logVerbosityLevel||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);void 0===e?.terminate&&(i.terminate=!1);let a=0;return void 0!==e?.tag&&(a=De(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),0===n&&Ve("Can't create run options."),void 0!==e?.extra&&Re(e.extra,"",new WeakSet,((e,i)=>{let a=De(e,r),s=De(i,r);0!==t._OrtAddRunConfigEntry(n,a,s)&&Ve(`Can't set a run config entry: ${e} - ${i}.`)})),[n,r]}catch(e){throw 0!==n&&t._OrtReleaseRunOptions(n),r.forEach((e=>t._free(e))),e}}})),Yl=j((()=>{Xl(),Kl(),qe=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},Ge=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},We=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some((e=>"webgpu"===("string"==typeof e?e:e.name)))&&(e.enableMemPattern=!1)},Ue=(e,t,n)=>{for(let r of t){let t="string"==typeof r?r:r.name;switch(t){case"webnn":if(t="WEBNN","string"!=typeof r){let t=r?.deviceType;if(t){let r=De("deviceType",n),i=De(t,n);0!==Ne()._OrtAddSessionConfigEntry(e,r,i)&&Ve(`Can't set a session config entry: 'deviceType' - ${t}.`)}}break;case"webgpu":if(t="JS","string"!=typeof r){let t=r;if(t?.preferredLayout){if("NCHW"!==t.preferredLayout&&"NHWC"!==t.preferredLayout)throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${t.preferredLayout}`);let r=De("preferredLayout",n),i=De(t.preferredLayout,n);0!==Ne()._OrtAddSessionConfigEntry(e,r,i)&&Ve(`Can't set a session config entry: 'preferredLayout' - ${t.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${t}`)}let i=De(t,n);0!==Ne()._OrtAppendExecutionProvider(e,i)&&Ve(`Can't append execution provider: ${t}.`)}},He=e=>{let t=Ne(),n=0,r=[],i=e||{};We(i);try{let e=qe(i.graphOptimizationLevel??"all"),a=Ge(i.executionMode??"sequential"),s="string"==typeof i.logId?De(i.logId,r):0,o=i.logSeverityLevel??2;if(!Number.isInteger(o)||o<0||o>4)throw new Error(`log serverity level is not valid: ${o}`);let l=i.logVerbosityLevel??0;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log verbosity level is not valid: ${l}`);let u="string"==typeof i.optimizedModelFilePath?De(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,s,o,l,u),0===n&&Ve("Can't create session options."),i.executionProviders&&Ue(n,i.executionProviders,r),void 0!==i.enableGraphCapture){if("boolean"!=typeof i.enableGraphCapture)throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let e=De("enableGraphCapture",r),a=De(i.enableGraphCapture.toString(),r);0!==t._OrtAddSessionConfigEntry(n,e,a)&&Ve(`Can't set a session config entry: 'enableGraphCapture' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if("string"!=typeof e)throw new Error(`free dimension override name must be a string: ${e}`);if("number"!=typeof a||!Number.isInteger(a)||a<0)throw new Error(`free dimension override value must be a non-negative integer: ${a}`);let i=De(e,r);0!==t._OrtAddFreeDimensionOverride(n,i,a)&&Ve(`Can't set a free dimension override: ${e} - ${a}.`)}return void 0!==i.extra&&Re(i.extra,"",new WeakSet,((e,i)=>{let a=De(e,r),s=De(i,r);0!==t._OrtAddSessionConfigEntry(n,a,s)&&Ve(`Can't set a session config entry: ${e} - ${i}.`)})),[n,r]}catch(e){throw 0!==n&&0!==t._OrtReleaseSessionOptions(n)&&Ve("Can't release session options."),r.forEach((e=>t._free(e))),e}}})),Zl=j((()=>{Xe=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},Ke=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},Qe=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r="number"==typeof t?t:t.reduce(((e,t)=>e*t),1);return n>0?Math.ceil(r*n):void 0},Ye=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Ze=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},Je=e=>"float32"===e||"float16"===e||"int32"===e||"int64"===e||"uint32"===e||"uint8"===e||"bool"===e||"uint4"===e||"int4"===e,et=e=>"float32"===e||"float16"===e||"int32"===e||"int64"===e||"uint32"===e||"uint64"===e||"int8"===e||"uint8"===e||"bool"===e||"uint4"===e||"int4"===e,tt=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}})),Jl=j((()=>{he(),nt=async e=>{if("string"==typeof e){{let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let n=t.headers.get("Content-Length"),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n,i=t.body.getReader();try{n=new ArrayBuffer(r)}catch(e){if(!(e instanceof RangeError))throw e;{let e=Math.ceil(r/65536);n=new WebAssembly.Memory({initial:e,maximum:e}).buffer}}let a=0;for(;;){let{done:e,value:t}=await i.read();if(e)break;let r=t.byteLength;new Uint8Array(n,a,r).set(t),a+=r}return new Uint8Array(n,0,r)}}}return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}})),eu=j((()=>{Zl(),rt=["V","I","W","E","F"],it=(e,t)=>{console.log(`[${rt[e]},${(new Date).toISOString()}]${t}`)},ot=(e,t)=>{at=e,st=t},lt=(e,t)=>{let n=Ze(e);n>=Ze(at)&&it(n,"function"==typeof t?t():t)},ut=(...e)=>{st&<(...e)}})),tu=j((()=>{Zl(),dt=(e,t)=>new(Ye(t))(e)})),nu=j((()=>{})),ru=j((()=>{eu(),nu(),ct=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),pt=[],ht=e=>16*Math.ceil(Number(e)/16),mt=e=>{for(let t=0;tft++,_t=async(e,t,n,r)=>{let i=ht(n),a=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let s=e.getCommandEncoder();e.endComputePass(),s.copyBufferToBuffer(t,0,a,0,i),e.flush(),await a.mapAsync(GPUMapMode.READ);let o=a.getMappedRange();if(r){let e=r();return e.set(new Uint8Array(o,0,n)),e}return new Uint8Array(o.slice(0,n))}finally{a.destroy()}},wt=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[e]of ct)pt.push(e),this.freeBuffers.set(e,[]),this.freeUniformBuffers.set(e,[]);this.sessionCount=0}upload(e,t){let n=t.buffer,r=t.byteOffset,i=t.byteLength,a=ht(i),s=this.storageCache.get(e);if(!s)throw new Error("gpu data for uploading does not exist");if(Number(s.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${s.originalSize}, data size=${i}`);let o=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=o.getMappedRange();new Uint8Array(l).set(new Uint8Array(n,r,i)),o.unmap();let u=this.backend.device.createCommandEncoder();u.copyBufferToBuffer(o,0,s.gpuData.buffer,0,a),this.backend.device.queue.submit([u.finish()]),o.destroy(),ut("verbose",(()=>`[WebGPU] GpuDataManager.upload(id=${e})`))}memcpy(e,t){let n=this.storageCache.get(e);if(!n)throw new Error("source gpu data for memcpy does not exist");let r=this.storageCache.get(t);if(!r)throw new Error("destination gpu data for memcpy does not exist");if(n.originalSize!==r.originalSize)throw new Error("inconsistent source and destination gpu data size");let i=ht(n.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(n.gpuData.buffer,0,r.gpuData.buffer,0,i)}registerExternalBuffer(e,t,n){let r;if(n){if(r=n[0],e===n[1])return ut("verbose",(()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${r}, buffer is the same, skip.`)),r;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error("Registering a different external buffer under graph capture mode is not supported yet.\n Please use the previous external buffer!")}else r=gt();return this.storageCache.set(r,{gpuData:{id:r,type:0,buffer:e},originalSize:t}),ut("verbose",(()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${r}, registered.`)),r}unregisterExternalBuffer(e){void 0!==e&&(this.storageCache.delete(e),ut("verbose",(()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`)))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n,r=mt(e),i=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let e=(i?this.freeBuffers:this.freeUniformBuffers).get(r);n=e&&e.length>0?e.pop():this.backend.device.createBuffer({size:r,usage:t})}else n=this.backend.device.createBuffer({size:r,usage:t});let s={id:gt(),type:0,buffer:n};return this.storageCache.set(s.id,{gpuData:s,originalSize:Number(e)}),ut("verbose",(()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${s.id}`)),s}get(e){return this.storageCache.get(e)?.gpuData}release(e){let t="bigint"==typeof e?Number(e):e,n=this.storageCache.get(t);if(!n){if(0===this.storageCache.size)return 0;throw new Error("releasing data does not exist")}return ut("verbose",(()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${n.gpuData.id}`)),this.storageCache.delete(t),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(e,t){let n=this.storageCache.get(Number(e));if(!n)throw new Error("data does not exist");await _t(this.backend,n.gpuData.buffer,n.originalSize,t)}refreshPendingBuffers(){if(0!==this.buffersPending.length)if("default"===this.backend.sessionStatus){for(let e of this.buffersPending){let t=ct.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(e.size)||[];void 0===t||n.length>=t?e.destroy():n.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(e.size)||[];void 0===t||n.length>=t?e.destroy():n.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach((e=>{e.forEach((e=>{e.destroy()}))})),this.freeUniformBuffers.forEach((e=>{e.forEach((e=>{e.destroy()}))})),this.storageCache.forEach((e=>{e.gpuData.buffer.destroy()})),this.capturedPendingBuffers.forEach((e=>{e.forEach((e=>{e.destroy()}))})),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach((e=>{e.destroy()})),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,0===this.sessionCount&&(ut("warning",(()=>"[WebGPU] Clearing webgpu buffer cache")),this.storageCache.forEach((e=>{e.gpuData.buffer.destroy()})),this.storageCache=new Map)}},bt=(...e)=>new wt(...e)})),iu=j((()=>{yt=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map((e=>`${this[e]}`)).join(";")),this.key}},xt=e=>new yt(e)})),au=j((()=>{vt=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Mt=class{static calcShape(e,t,n=!1){let r=e.length,i=t.length;if(0===r)return t;if(0===i)return e;let a=Math.max(e.length,t.length),s=new Array(a);if(n){if(r<2||i<2)return;let n=vt.calcMatMulShape([e[r-2],e[r-1]],[t[i-2],t[i-1]]);if(void 0===n)return;[s[a-2],s[a-1]]=n}for(let o=n?3:1;o<=a;o++){let n=r-o<0?1:e[r-o],l=i-o<0?1:t[i-o];if(n!==l&&n>1&&l>1)return;let u=Math.max(n,l);if(n&&l)s[a-o]=Math.max(n,l);else{if(u>1)return;s[a-o]=0}}return s}static isValidBroadcast(e,t){let n=e.length,r=t.length;if(n>r)return!1;for(let i=1;i<=n;i++)if(1!==e[n-i]&&e[n-i]!==t[r-i])return!1;return!0}},Tt=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(e,t=4){let n=e.length;if(0===n)return[];let r=new Array(n),i=n-1;for(;i>=0;){if(e[i]%t==0){r[i]=e[i]/t;break}if(t%e[i]!=0)throw new Error("cannot convert shape");r[i]=1,t/=e[i],i--}for(i--;i>=0;i--)r[i]=e[i];return r}static sizeFromDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(e,t,n){let r=1;for(let i=t;i=0;--r)n[r]=n[r+1]*e[r+1];return n}static normalizeAxis(e,t){if(e<-t&&e>=t)throw new Error("unsupported axis for this operation.");return e<0?e+t:e}static normalizeAxes(e,t){return e.map((n=>this.normalizeAxis(n,t??e.length)))}static sortBasedOnPerm(e,t){return t?t.map((t=>e[t])):e.slice().reverse()}static padShape(e,t){let n=e.length;return e.map(((e,r)=>e+t[r]+t[r+n]))}static areEqual(e,t){return e.length===t.length&&e.every(((e,n)=>e===t[n]))}},kt=class e{static adjustPoolAttributes(e,t,n,r,i,a){if(!e&&n.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(e)for(let e=0;e=n.length?n.push(t[e+2]):n[e]=t[e+2];for(let e=0;e=n[e]||a[e+n.length]>=n[e])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,n,r,i,a,s,o){if(o){if(a.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(i.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{Zl(),au(),Pt=64,Et=(e,t)=>{if(3===t)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(4!==t)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},Ft=(e,t=1)=>{let n=Et(e,t);return"string"==typeof n?n:n[0]},At=(e,t=1)=>{let n=Et(e,t);return"string"==typeof n?n:n[1]},It=(...e)=>{let t=[];return e.forEach((e=>{0!==e.length&&t.push({type:12,data:e},{type:12,data:Tt.computeStrides(e)})})),t},zt=e=>e%4==0?4:e%2==0?2:1,Ot=(e="f32",t,n="0")=>t&&1!==t?`vec${t}<${e}>(${n})`:`${e}(${n})`,Bt=(e,t,n)=>"f32"===e?n:1===t?`f32(${n})`:`vec${t}(${n})`,Lt=(e,t)=>4===t?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:2===t?`(${e}.x + ${e}.y)`:3===t?`(${e}.x + ${e}.y + ${e}.z)`:e,Nt=(e,t,n,r)=>e.startsWith("uniforms.")&&n>4?"string"==typeof t?"f16"===r?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:"f16"===r?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:n>1?`${e}[${t}]`:e,Dt=(e,t,n,r,i)=>{let a="number"==typeof n,s=a?n:n.length,o=[...new Array(s).keys()],l=s<2?"u32":s<=4?`vec${s}`:`array`,u=Et(t,i),d="string"==typeof u?u:u[1],c="string"==typeof u?u:u[0],p={indices:l,value:d,storage:c,tensor:t},h=e=>"string"==typeof e?e:`${e}u`,m={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},f=a?"uniforms.":"",g=`${f}${e}_shape`,_=`${f}${e}_strides`,w="";for(let e=0;e ${p.indices} {\n var indices: ${p.indices};\n var current = offset;\n ${w}\n return indices;\n }`,y=[];if(s>=2)for(let e=s-1;e>=0;e--)y.push(`${Nt(_,e,s)} * (indices[${e}])`);let x=s<2?"":`\n fn i2o_${e}(indices: ${p.indices}) -> u32 {\n return ${y.join("+")};\n }`,v=(...e)=>0===s?"0u":`${p.indices}(${e.map(h).join(",")})`,M=(e,t)=>s<2?`${e}`:`${Nt(e,t,s)}`,T={},k=(t,n)=>(()=>{if(p.storage===p.value)return`${e}[${t}]=${n};`;if("vec2"===p.storage&&"i32"===p.value)return`${e}[${t}]=vec2(u32(${n}), select(0u, 0xFFFFFFFFu, ${n} < 0));`;if("vec2"===p.storage&&"u32"===p.value)return`${e}[${t}]=vec2(u32(${n}), 0u);`;if("u32"===p.storage&&"vec4"===p.value)return`${e}[${t}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${n}));`;throw new Error(`not supported combination of storage type ${p.storage} and value type ${p.value} yet`)})(),$=t=>(()=>{if(p.storage===p.value)return`${e}[${t}]`;if("vec2"===p.storage&&"i32"===p.value)return`i32(${e}[${t}].x)`;if("vec2"===p.storage&&"u32"===p.value)return`u32(${e}[${t}].x)`;if("u32"===p.storage&&"vec4"===p.value)return`vec4(bool(${e}[${t}] & 0xFFu), bool(${e}[${t}] & 0xFF00u), bool(${e}[${t}] & 0xFF0000u), bool(${e}[${t}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${p.storage} and value type ${p.value} yet`)})(),C=s<2?"":`\n fn get_${e}ByIndices(indices: ${p.indices}) -> ${d} {\n return ${$(`i2o_${e}(indices)`)};\n }`,S=s<2?"":(()=>{let t=o.map((e=>`d${e}: u32`)).join(", "),n=o.map((e=>`d${e}`)).join(", ");return`\n fn get_${e}(${t}) -> ${d} {\n return get_${e}ByIndices(${v(n)});\n }`})(),P=s<2?"":`\n fn set_${e}ByIndices(indices: ${p.indices}, value: ${d}) {\n ${k(`i2o_${e}(indices)`,"value")}\n }`,E=s<2?"":(()=>{let t=o.map((e=>`d${e}: u32`)).join(", "),n=o.map((e=>`d${e}`)).join(", ");return`\n fn set_${e}(${t}, value: ${d}) {\n set_${e}ByIndices(${v(n)}, value);\n }`})();return{impl:()=>{let e=[],t=!1;return m.offsetToIndices&&(e.push(b),t=!0),m.indicesToOffset&&(e.push(x),t=!0),m.broadcastedIndicesToOffset&&(Object.values(T).forEach((t=>e.push(t))),t=!0),m.set&&(e.push(E),t=!0),m.setByIndices&&(e.push(P),t=!0),m.get&&(e.push(S),t=!0),m.getByIndices&&(e.push(C),t=!0),!a&&t&&e.unshift(`const ${g} = ${p.indices}(${n.join(",")});`,`const ${_} = ${p.indices}(${Tt.computeStrides(n).join(",")});`),e.join("\n")},type:p,offsetToIndices:t=>(m.offsetToIndices=!0,s<2?t:`o2i_${e}(${t})`),indicesToOffset:t=>(m.indicesToOffset=!0,s<2?t:`i2o_${e}(${t})`),broadcastedIndicesToOffset:(t,n)=>{m.broadcastedIndicesToOffset=!0;let r=`${n.name}broadcastedIndicesTo${e}Offset`;if(r in T)return`${r}(${t})`;let i=[];for(let e=s-1;e>=0;e--){let t=n.indicesGet("outputIndices",e+n.rank-s);i.push(`${M(_,e)} * (${t} % ${M(g,e)})`)}return T[r]=`fn ${r}(outputIndices: ${n.type.indices}) -> u32 {\n return ${i.length>0?i.join("+"):"0u"};\n }`,`${r}(${t})`},indices:v,indicesGet:M,indicesSet:(e,t,n)=>s<2?`${e}=${n};`:`${Nt(e,t,s)}=${n};`,set:(...t)=>{if(t.length!==s+1)throw new Error(`indices length must be ${s}`);let n=t[s];if("string"!=typeof n)throw new Error("value must be string");let r=t.slice(0,s).map(h).join(",");return 0===s?k("0u",n):1===s?k(r[0],n):(m.set=!0,m.setByIndices=!0,m.indicesToOffset=!0,`set_${e}(${r}, ${n})`)},setByOffset:k,setByIndices:(t,n)=>s<2?k(t,n):(m.setByIndices=!0,m.indicesToOffset=!0,`set_${e}ByIndices(${t}, ${n});`),get:(...t)=>{if(t.length!==s)throw new Error(`indices length must be ${s}`);let n=t.map(h).join(",");return 0===s?$("0u"):1===s?$(n[0]):(m.get=!0,m.getByIndices=!0,m.indicesToOffset=!0,`get_${e}(${n})`)},getByOffset:$,getByIndices:t=>s<2?$(t):(m.getByIndices=!0,m.indicesToOffset=!0,`get_${e}ByIndices(${t})`),usage:r,name:e,strides:_,shape:g,rank:s}},Rt=(e,t,n,r=1)=>Dt(e,t,n,"input",r),Vt=(e,t,n,r=1)=>Dt(e,t,n,"output",r),jt=(e,t,n,r=1)=>Dt(e,t,n,"internal",r),qt=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${"number"==typeof e?`${e}u`:e}) { return; }`}mainStart(e=Pt){let t="number"==typeof e?e:e[0],n="number"==typeof e?1:e[1],r="number"==typeof e?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||r>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${n}, ${r}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*n*r>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${n}, ${r}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=1===this.normalizedDispatchGroup[1]&&1===this.normalizedDispatchGroup[2];return`@compute @workgroup_size(${t}, ${n}, ${r})\n fn main(${i?"@builtin(global_invocation_id) global_id : vec3,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(local_invocation_id) local_id : vec3":"@builtin(global_invocation_id) global_id : vec3,\n @builtin(local_invocation_id) local_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(num_workgroups) num_workgroups : vec3"}) {\n ${i?"let global_idx = global_id.x;\n let workgroup_index = workgroup_id.x;":`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] +\n workgroup_id.y * num_workgroups[0] + workgroup_id.x;\n let global_idx = workgroup_index * ${t*n*r}u + local_idx;`}\n `}appendVariableUniforms(e){0!==e.rank&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if("internal"===e.usage)throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let n="input"===e.usage?"read":"read_write",r=e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${r}>;`}declareVariables(...e){return e.map((e=>this.declareVariable(e,this.variableIndex++))).join("\n")}registerInternalVariable(e){if("internal"!==e.usage)throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach((e=>this.registerInternalVariable(e))),this}registerUniform(e,t,n=1){return this.uniforms.push({name:e,type:t,length:n}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(0===this.uniforms.length)return"";let e=[];for(let{name:t,type:n,length:r}of this.uniforms)if(r&&r>4)"f16"===n?e.push(`@align(16) ${t}:array, ${Math.ceil(r/8)}>`):e.push(`${t}:array, ${Math.ceil(r/4)}>`);else{let i=null==r||1===r?n:`vec${r}<${n}>`;e.push(`${t}:${i}`)}return`\n struct Uniforms { ${e.join(", ")} };\n @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map((e=>e.impl())).join("\n")+this.internalVariables.map((e=>e.impl())).join("\n")}get variablesInfo(){if(0===this.uniforms.length)return;let e=e=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(e)];return this.uniforms.map((t=>[e(t.type),t.length??1]))}},Gt=(e,t)=>new qt(e,t)})),ou=j((()=>{Zl(),au(),iu(),su(),Wt=e=>{if(!e||1!==e.length)throw new Error("Transpose requires 1 input.")},Ut=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,Ht=(e,t)=>Tt.sortBasedOnPerm(e,Ut(e.length,t)),Xt=(e,t,n,r)=>{let i=`fn perm(i: ${r.type.indices}) -> ${n.type.indices} {\n var a: ${n.type.indices};`;for(let r=0;r{let n=[],r=[];for(let i=0;i{let n=e.dataType,r=e.dims.length,i=Ut(r,t),a=Ht(e.dims,i),{newShape:s,newPerm:o}=Kt(e.dims,i),l=Tt.areEqual(o,[2,3,1]),u=Tt.areEqual(o,[3,1,2]),d=2===s.length&&o[0]>o[1]||l||u,c=d?s:e.dims,p=a;d&&(c=l?[s[0],s[1]*s[2]]:u?[s[0]*s[1],s[2]]:s,p=[c[1],c[0]]);let h,m=Rt("a",n,c.length),f=Vt("output",n,p.length),g=16;return h=d?e=>`\n ${e.registerUniform("output_size","u32").declareVariables(m,f)}\n var tile : array, 16>;\n ${e.mainStart([g,g,1])}\n let stride = (uniforms.output_shape[1] - 1) / 16 + 1;\n let workgroup_id_x = workgroup_index % stride;\n let workgroup_id_y = workgroup_index / stride;\n let input_col = workgroup_id_y * 16u + local_id.x;\n let input_row = workgroup_id_x * 16u + local_id.y;\n if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) {\n tile[local_id.y][local_id.x] = ${m.getByIndices(`${m.type.indices}(input_row, input_col)`)};\n }\n workgroupBarrier();\n\n let output_col = workgroup_id_x * 16u + local_id.x;\n let output_row = workgroup_id_y * 16u + local_id.y;\n if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) {\n ${f.setByIndices(`${f.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")}\n }\n }`:e=>`\n ${e.registerUniform("output_size","u32").declareVariables(m,f)}\n\n ${Xt(i,r,m,f)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${f.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${f.setByOffset("global_idx",m.getByIndices("aIndices"))}\n }`,{name:d?"TransposeShared":"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let t=Tt.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:d?{x:Math.ceil(p[1]/g),y:Math.ceil(p[0]/g)}:{x:Math.ceil(t/64)},programUniforms:[{type:12,data:t},...It(c,p)]}},getShaderSource:h}},Yt=(e,t)=>{Wt(e.inputs),e.compute(Qt(e.inputs[0],t.perm))},Zt=e=>xt({perm:e.perm})})),lu=j((()=>{Zl(),au(),su(),uu(),ou(),Jt={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},en={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},tn={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},nn={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},rn=(e,t)=>{let n=[];for(let r=t-e;r{let n=[],r=e.length;for(let i=0;ie[t]))]},sn=(e,t)=>{let n=e.length+t.length,r=[],i=0;for(let a=0;a{for(let n=0;n{let n=[];if(!on(e,t)){for(let r=0;rn.push(e)))}return n},un=(e,t,n,r,i,a,s)=>{let o=n[0].dims,l=Tt.size(a),u=Tt.size(s),d=Rt("_A",n[0].dataType,o),c=Vt("output",i,a),p=64;1===l&&(p=256);let h=`\n var aBestValues : array;\n `;return{name:e,shaderCache:{hint:`${t};${p}`,inputDependencies:["type"]},getShaderSource:e=>`\n ${e.registerUniform("reduceSize","u32").declareVariables(d,c)}\n ${h}\n fn DIV_CEIL(a : u32, b : u32) -> u32 {\n return ((a - 1u) / b + 1u);\n }\n ${e.mainStart(p)}\n\n let outputIndex = global_idx / ${p};\n let offset = outputIndex * uniforms.reduceSize;\n\n var bestValue = f32(${tn[r]});\n let Length = uniforms.reduceSize;\n for (var k = local_idx; k < Length; k = k + ${p}) {\n let candidate = f32(${d.getByOffset("offset + k")});\n bestValue = ${Jt[r]};\n }\n aBestValues[local_idx] = bestValue;\n workgroupBarrier();\n\n var reduceSize = min(Length, ${p}u);\n for (var currentSize = reduceSize / 2u; reduceSize > 1u;\n currentSize = reduceSize / 2u) {\n let interval = DIV_CEIL(reduceSize, 2u);\n if (local_idx < currentSize) {\n let candidate = aBestValues[local_idx + interval];\n bestValue = ${en[r]};\n aBestValues[local_idx] = bestValue;\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (local_idx == 0u) {\n ${c.setByOffset("outputIndex",""+("mean"===r?`${c.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${c.type.storage}(${nn[r]})`))};\n }\n }`,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:l},programUniforms:[{type:12,data:u}]})}},dn=(e,t,n,r)=>{let i=1===e.inputs.length?n:Tn(e.inputs,n),a=i.axes;0===a.length&&!i.noopWithEmptyAxes&&(a=e.inputs[0].dims.map(((e,t)=>t)));let s=Tt.normalizeAxes(a,e.inputs[0].dims.length),o=s,l=e.inputs[0],u=ln(o,e.inputs[0].dims.length);u.length>0&&(l=e.compute(Qt(e.inputs[0],u),{inputs:[0],outputs:[-1]})[0],o=rn(o.length,l.dims.length));let[d,c]=an(l.dims,o),p=d;i.keepDims&&(p=sn(d,s)),e.compute(un(t,i.cacheKey,[l],r,e.inputs[0].dataType,p,c),{inputs:[l]})},cn=(e,t)=>{dn(e,"ReduceMeanShared",t,"mean")},pn=(e,t)=>{dn(e,"ReduceL1Shared",t,"l1")},hn=(e,t)=>{dn(e,"ReduceL2Shared",t,"l2")},mn=(e,t)=>{dn(e,"ReduceLogSumExpShared",t,"logSumExp")},fn=(e,t)=>{dn(e,"ReduceMaxShared",t,"max")},gn=(e,t)=>{dn(e,"ReduceMinShared",t,"min")},_n=(e,t)=>{dn(e,"ReduceProdShared",t,"prod")},wn=(e,t)=>{dn(e,"ReduceSumShared",t,"sum")},bn=(e,t)=>{dn(e,"ReduceSumSquareShared",t,"sumSquare")},yn=(e,t)=>{dn(e,"ReduceLogSumShared",t,"logSum")}})),uu=j((()=>{Zl(),au(),iu(),su(),lu(),xn=e=>{if(!e||0===e.length||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(2===e.length&&1!==e[1].dims.length)throw new Error("Invalid axes input dims.")},vn=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Mn=(e,t,n,r,i,a,s=!1,o=!1)=>{let l=[],u=n[0].dims,d=u.length,c=Tt.normalizeAxes(i,d),p=!o&&0===c.length;u.forEach(((e,t)=>{p||c.indexOf(t)>=0?s&&l.push(1):l.push(e)}));let h=l.length,m=Tt.size(l);return{name:e,shaderCache:t,getShaderSource:e=>{let t=[],i=Rt("_A",n[0].dataType,d),o=Vt("output",a,h),l=r(i,o,c),m=l[2];for(let e=0,n=0;e=0?(s&&n++,m=`for(var j${e}: u32 = 0; j${e} < ${u[e]}; j${e}++) {\n ${l[2].includes("last_index")?`let last_index = j${e};`:""}\n ${i.indicesSet("input_indices",e,`j${e}`)}\n ${m}\n }`):(t.push(`${i.indicesSet("input_indices",e,o.indicesGet("output_indices",n))};`),n++);return`\n\n ${e.registerUniform("output_size","u32").declareVariables(i,o)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var input_indices: ${i.type.indices};\n let output_indices = ${o.offsetToIndices("global_idx")};\n\n ${t.join("\n")}\n ${l[0]} // init ops for reduce max/min\n ${l[1]}\n ${m}\n ${l[3]}\n ${4===l.length?o.setByOffset("global_idx","value"):l.slice(4).join("\n")}\n }`},getRunData:()=>({outputs:[{dims:l,dataType:a}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...It(u,l)]})}},Tn=(e,t)=>{let n=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach((e=>n.push(Number(e)))),xt({axes:n,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},kn=(e,t,n,r)=>{let i=e.inputs,a=1===i.length?n:Tn(i,n);e.compute(Mn(t,{hint:a.cacheKey,inputDependencies:["rank"]},[i[0]],a.noopWithEmptyAxes&&0===a.axes.length?vn:r,a.axes,i[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},$n=(e,t)=>{xn(e.inputs),kn(e,"ReduceLogSum",t,((e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += ${e.getByIndices("input_indices")};`,"value = log(value);"]))},Cn=(e,t)=>{xn(e.inputs),kn(e,"ReduceL1",t,((e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += abs(${e.getByIndices("input_indices")});`,""]))},Sn=(e,t)=>{xn(e.inputs),kn(e,"ReduceL2",t,((e,t)=>[`var t = ${t.type.value}(0); var value = ${t.type.value}(0);`,"",`t = ${e.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"]))},Pn=(e,t)=>{xn(e.inputs),kn(e,"ReduceLogSumExp",t,((e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += exp(${e.getByIndices("input_indices")});`,"value = log(value);"]))},En=(e,t)=>{xn(e.inputs),kn(e,"ReduceMax",t,((e,t,n)=>{let r=[];for(let t=0;t=0||0===n.length)&&r.push(e.indicesSet("input_indices",t,0));return[`${r.join("\n")}`,`var value = ${e.getByIndices("input_indices")};`,`value = max(value, ${e.getByIndices("input_indices")});`,""]}))},Fn=(e,t)=>{xn(e.inputs),kn(e,"ReduceMean",t,((t,n,r)=>{let i=1;for(let n=0;n=0||0===r.length)&&(i*=e.inputs[0].dims[n]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${i});`]}))},An=(e,t)=>{xn(e.inputs),kn(e,"ReduceMin",t,((e,t,n)=>{let r=[];for(let t=0;t=0||0===n.length)&&r.push(`input_indices[${t}] = 0;`);return[`${r.join("\n")}`,`var value = ${e.getByIndices("input_indices")};`,`value = min(value, ${e.getByIndices("input_indices")});`,""]}))},In=(e,t)=>{xn(e.inputs),kn(e,"ReduceProd",t,((e,t)=>[`var value = ${t.type.storage}(1);`,"",`value *= ${e.getByIndices("input_indices")};`,""]))},zn=(e,t)=>{xn(e.inputs),kn(e,"ReduceSum",t,((e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += ${e.getByIndices("input_indices")};`,""]))},On=(e,t)=>{xn(e.inputs),kn(e,"ReduceSumSquare",t,((e,t)=>[`var t = ${t.type.value}(0); var value = ${t.type.value}(0);`,"",`t = ${e.getByIndices("input_indices")}; value += t * t;`,""]))},Bn=(e,t,n)=>{if(0===t.length)return n;let r=1,i=1;for(let n=0;n1024},Ln=(e,t)=>{Bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Fn(e,t):cn(e,t)},Nn=(e,t)=>{Bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Cn(e,t):pn(e,t)},Dn=(e,t)=>{Bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Sn(e,t):hn(e,t)},Rn=(e,t)=>{Bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Pn(e,t):mn(e,t)},Vn=(e,t)=>{Bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?En(e,t):fn(e,t)},jn=(e,t)=>{Bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?An(e,t):gn(e,t)},qn=(e,t)=>{Bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?In(e,t):_n(e,t)},Gn=(e,t)=>{Bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?zn(e,t):wn(e,t)},Wn=(e,t)=>{Bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?On(e,t):bn(e,t)},Un=(e,t)=>{Bn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?$n(e,t):yn(e,t)}})),du=j((()=>{Zl(),iu(),uu(),Hn=e=>{if(!e||0===e.length||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(1!==e[0].dataType)throw new Error("Invalid input type.")},Xn=(e,t)=>{Hn(e.inputs);e.compute(Mn("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],((e,n,r)=>{let i=[];for(let t=0;t=0||0===r.length)&&i.push(`input_indices[${t}] = 0;`);return[`${i.join("\n")}`,`var value = ${e.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${e.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) {\n value = ${e.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",n.setByOffset("global_idx","best_index")]}),[t.axis],7,t.keepDims),{inputs:[0]})},Kn=(e,t)=>{Hn(e.inputs);e.compute(Mn("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],((e,n,r)=>{let i=[];for(let t=0;t=0||0===r.length)&&i.push(`input_indices[${t}] = 0;`);return[`${i.join("\n")}`,`var value = ${e.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${e.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) {\n value = ${e.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",n.setByOffset("global_idx","best_index")]}),[t.axis],7,t.keepDims),{inputs:[0]})},Qn=e=>xt(e)})),cu=j((()=>{Zl(),au(),nu(),su(),Yn=(e,t)=>{let n=e[0],r=e[1],i=e[2],a=e[3],s=e[4],o=e[5];if(s&&o)throw new Error("Attention cannot have both past and attention_bias");if(3!==n.dims.length)throw new Error('Input "input" must have 3 dimensions');let l=n.dims[0],u=n.dims[1],d=n.dims[2];if(1!==i.dims.length)throw new Error('Input "bias" is expected to have 1 dimensions');if(2!==r.dims.length)throw new Error('Input "weights" is expected to have 2 dimensions');if(r.dims[0]!==d)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==r.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let c=i.dims[0]/3,p=c,h=p;if(t.qkvHiddenSizes.length>0){if(3!==t.qkvHiddenSizes.length)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let e of t.qkvHiddenSizes)if(e%t.numHeads!=0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");c=t.qkvHiddenSizes[0],p=t.qkvHiddenSizes[1],h=t.qkvHiddenSizes[2]}let m=u;if(c!==p)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==c+p+h)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let f=0;if(s){if(p!==h)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(5!==s.dims.length)throw new Error('Input "past" must have 5 dimensions');if(2!==s.dims[0])throw new Error('Input "past" first dimension must be 2');if(s.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(s.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(s.dims[4]!==p/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(f=s.dims[3])}let g=m+f;if(a)throw new Error("Mask not supported");if(s)throw new Error("past is not supported");if(o){if(4!==o.dims.length)throw new Error('Input "attention_bias" must have 4 dimensions');if(o.dims[0]!==l||o.dims[1]!==t.numHeads||o.dims[2]!==u||o.dims[3]!==g)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:u,pastSequenceLength:f,kvSequenceLength:m,totalSequenceLength:g,maxSequenceLength:-1,inputHiddenSize:d,hiddenSize:c,vHiddenSize:h,headSize:Math.floor(c/t.numHeads),vHeadSize:Math.floor(h/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:0,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Zn=(e,t,n)=>t&&e?`\n let total_sequence_length_input = u32(${t.getByOffset("0")});\n let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);\n let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;\n let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input;\n total_sequence_length = u32(${e?.getByOffset("batchIdx")}) + 1;\n var past_sequence_length: u32 = 0;\n if (is_first_prompt == false) {\n past_sequence_length = total_sequence_length - sequence_length;\n }\n `:`\n ${n?"let past_sequence_length = uniforms.past_sequence_length":""};\n let present_sequence_length = total_sequence_length;\n `,Jn=(e,t,n,r,i,a,s,o)=>{let l=zt(s?1:a),u=64,d=a/l;d{let n=Vt("x",e.dataType,e.dims,l),r=[n],i=s?Rt("seq_lens",s.dataType,s.dims):void 0;i&&r.push(i);let a=o?Rt("total_sequence_length_input",o.dataType,o.dims):void 0;a&&r.push(a);let d=At(e.dataType);return`\n var thread_max: array;\n var thread_sum: array;\n ${t.registerUniforms([{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}]).declareVariables(...r)}\n ${t.mainStart([u,1,1])}\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let sequence_length = uniforms.sequence_length;\n var total_sequence_length = uniforms.total_sequence_length;\n ${Zn(i,a,!1)}\n let local_offset = local_idx * uniforms.elements_per_thread;\n let offset = (global_idx / ${u}) * uniforms.total_sequence_length + local_offset;\n let seq_causal_length = ${s?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"};\n var thread_max_vector = ${m}(-3.402823e+38f);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n thread_max_vector = max(${m}(x[offset + i]), thread_max_vector);\n }\n thread_max[local_idx] = ${(()=>{switch(l){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${l}`)}})()};\n workgroupBarrier();\n\n var max_value = f32(-3.402823e+38f);\n for (var i = 0u; i < ${u}; i++) {\n max_value = max(thread_max[i], max_value);\n }\n\n var sum_vector = ${m}(0);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n sum_vector += exp(${m}(x[offset + i]) - max_value);\n }\n thread_sum[local_idx] = ${(()=>{switch(l){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${l}`)}})()};\n workgroupBarrier();\n\n var sum: f32 = 0;\n for (var i = 0u; i < ${u}; i++) {\n sum += thread_sum[i];\n }\n\n if (sum == 0) {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n x[offset + i] = ${n.type.value}(${d}(1.0) / ${d}(seq_causal_length));\n }\n } else {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n var f32input = ${m}(x[offset + i]);\n x[offset + i] = ${n.type.value}(exp(f32input - max_value) / sum);\n }\n }\n ${s?`\n for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) {\n x[offset + total_seq_id] = ${n.type.value}(${d}(0));\n }`:""};\n }`},getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(a/u),y:i,z:t*n},programUniforms:p})}},er=(e,t,n,r,i,a,s,o,l)=>{let u=s+a.kvSequenceLength,d=[a.batchSize,a.numHeads,a.sequenceLength,u],c=e>1&&r,p=a.kvNumHeads?a.kvNumHeads:a.numHeads,h=c?[a.batchSize,p,u,a.headSize]:void 0,m=a.nReps?a.nReps:1,f=0===a.scale?1/Math.sqrt(a.headSize):a.scale,g=zt(a.headSize),_=a.headSize/g,w=12,b={x:Math.ceil(u/w),y:Math.ceil(a.sequenceLength/w),z:a.batchSize*a.numHeads},y=[{type:12,data:a.sequenceLength},{type:12,data:_},{type:12,data:u},{type:12,data:a.numHeads},{type:12,data:a.headSize},{type:1,data:f},{type:12,data:s},{type:12,data:a.kvSequenceLength},{type:12,data:m}],x=c&&r&&Tt.size(r.dims)>0,v=["type","type"];x&&v.push("type"),i&&v.push("type"),o&&v.push("type"),l&&v.push("type");let M=[{dims:d,dataType:t.dataType,gpuDataType:0}];c&&M.push({dims:h,dataType:t.dataType,gpuDataType:0});return{name:"AttentionProbs",shaderCache:{hint:`${g};${void 0!==i};${void 0!==r};${e}`,inputDependencies:v},getRunData:()=>({outputs:M,dispatchGroup:b,programUniforms:y}),getShaderSource:e=>{let a=Rt("q",t.dataType,t.dims,g),s=[a,Rt("key",n.dataType,n.dims,g)];if(x){let e=Rt("past_key",r.dataType,r.dims,g);s.push(e)}i&&s.push(Rt("attention_bias",i.dataType,i.dims));let u=o?Rt("seq_lens",o.dataType,o.dims):void 0;u&&s.push(u);let p=l?Rt("total_sequence_length_input",l.dataType,l.dims):void 0;p&&s.push(p);let f=Vt("output",t.dataType,d),_=[f];c&&_.push(Vt("present_key",t.dataType,h,g));let b=At(1,g);return`\n const TILE_SIZE = 12u;\n\n var tileQ: array<${a.type.storage}, 144>;\n var tileK: array<${a.type.storage}, 144>;\n ${e.registerUniforms([{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}]).declareVariables(...s,..._)}\n ${e.mainStart([w,w,1])}\n // x holds the N and y holds the M\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let kvHeadIdx = ${1===m?"headIdx":"headIdx / uniforms.n_reps"};\n let kv_num_heads = ${1===m?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let m = workgroup_id.y * TILE_SIZE;\n let n = workgroup_id.x * TILE_SIZE;\n let sequence_length = uniforms.M;\n var total_sequence_length = uniforms.N;\n ${Zn(u,p,!0)}\n let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx;\n let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;\n ${x&&c?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""};\n let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K;\n ${c?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""}\n var value = ${b}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {\n var idx = TILE_SIZE * local_id.y + local_id.x;\n ${x&&c?"\n if (n + local_id.y < past_sequence_length) {\n tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x];\n } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {\n tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x];\n }":"\n if (n + local_id.y < uniforms.kv_sequence_length) {\n tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x];\n }"}\n ${c?"if (n + local_id.y < present_sequence_length) {\n present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];\n }":""}\n }\n workgroupBarrier();\n\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {\n value += ${b}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);\n }\n\n workgroupBarrier();\n }\n\n if (global_id.y < uniforms.M && global_id.x < total_sequence_length) {\n let headOffset = workgroup_id.z * uniforms.M * uniforms.N;\n let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;\n var sum: f32 = ${(()=>{switch(g){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${g}`)}})()};\n output[outputIdx] = ${f.type.value} (sum * uniforms.alpha) + ${i?"attention_bias[outputIdx]":"0.0"};\n }\n }`}}},tr=(e,t,n,r,i,a,s=void 0,o=void 0)=>{let l=a+i.kvSequenceLength,u=i.nReps?i.nReps:1,d=i.vHiddenSize*u,c=e>1&&r,p=i.kvNumHeads?i.kvNumHeads:i.numHeads,h=c?[i.batchSize,p,l,i.headSize]:void 0,m=[i.batchSize,i.sequenceLength,d],f=12,g={x:Math.ceil(i.vHeadSize/f),y:Math.ceil(i.sequenceLength/f),z:i.batchSize*i.numHeads},_=[{type:12,data:i.sequenceLength},{type:12,data:l},{type:12,data:i.vHeadSize},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:d},{type:12,data:a},{type:12,data:i.kvSequenceLength},{type:12,data:u}],w=c&&r&&Tt.size(r.dims)>0,b=["type","type"];w&&b.push("type"),s&&b.push("type"),o&&b.push("type");let y=[{dims:m,dataType:t.dataType,gpuDataType:0}];c&&y.push({dims:h,dataType:t.dataType,gpuDataType:0});return{name:"AttentionScore",shaderCache:{hint:`${void 0!==r};${e}`,inputDependencies:b},getRunData:()=>({outputs:y,dispatchGroup:g,programUniforms:_}),getShaderSource:e=>{let i=Rt("probs",t.dataType,t.dims),a=[i,Rt("v",n.dataType,n.dims)];w&&a.push(Rt("past_value",r.dataType,r.dims));let l=s?Rt("seq_lens",s.dataType,s.dims):void 0;s&&a.push(l);let d=o?Rt("total_sequence_length_input",o.dataType,o.dims):void 0;o&&a.push(d);let p=[Vt("output",t.dataType,m)];c&&p.push(Vt("present_value",t.dataType,h));return`\n const TILE_SIZE = 12u;\n var tileQ: array<${i.type.value}, 144>;\n var tileV: array<${i.type.value}, 144>;\n ${e.registerUniforms([{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}]).declareVariables(...a,...p)}\n ${e.mainStart([f,f,1])}\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let kvHeadIdx = ${1===u?"headIdx":"headIdx / uniforms.n_reps"};\n let kv_num_heads = ${1===u?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};\n let m = global_id.y;\n let n = global_id.x;\n let sequence_length = uniforms.M;\n var total_sequence_length = uniforms.K;\n ${Zn(l,d,!0)}\n let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;\n let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch\n ${w&&c?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""};\n let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n;\n ${c?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""}\n var value = ${i.type.storage}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n var idx = TILE_SIZE * local_id.y + local_id.x;\n ${w&&c?"\n if (w + local_id.y < past_sequence_length) {\n tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N];\n } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {\n tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N];\n }\n ":"\n if (w + local_id.y < uniforms.kv_sequence_length) {\n tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N];\n }"}\n ${c?"\n if (w + local_id.y < present_sequence_length) {\n present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx];\n }":""}\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) {\n value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x];\n }\n workgroupBarrier();\n }\n\n // we need to transpose output from BNSH_v to BSND_v\n if (m < uniforms.M && n < uniforms.N) {\n let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size\n + headIdx * uniforms.N + n;\n output[outputIdx] = value;\n }\n }`}}},nr=(e,t,n,r,i,a,s,o,l,u,d=void 0,c=void 0)=>{let p=Math.min(e.outputCount,1+(s?1:0)+(o?1:0)),h=p>1?u.pastSequenceLength:0,m=h+u.kvSequenceLength,f=l&&Tt.size(l.dims)>0?l:void 0,g=[t,n];p>1&&s&&Tt.size(s.dims)>0&&g.push(s),f&&g.push(f),d&&g.push(d),c&&g.push(c);let _=e.compute(er(p,t,n,s,f,u,h,d,c),{inputs:g,outputs:p>1?[-1,1]:[-1]})[0];e.compute(Jn(_,u.batchSize,u.numHeads,h,u.sequenceLength,m,d,c),{inputs:d&&c?[_,d,c]:[_],outputs:[]});let w=[_,r];p>1&&o&&Tt.size(o.dims)>0&&w.push(o),d&&w.push(d),c&&w.push(c),e.compute(tr(p,_,r,o,u,h,d,c),{inputs:w,outputs:p>1?[0,2]:[0]})},rr=(e,t)=>{let n=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],r=t.sequenceLength,i=t.inputHiddenSize,a=t.headSize,s=12,o={x:Math.ceil(t.headSize/s),y:Math.ceil(t.sequenceLength/s),z:t.batchSize*t.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],u=[{type:12,data:r},{type:12,data:i},{type:12,data:a},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}];return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:o,programUniforms:u}),getShaderSource:e=>{let t=Vt("output_q",l[0].dataType,n),r=Vt("output_k",l[0].dataType,n),i=Vt("output_v",l[0].dataType,n),a=Rt("input",l[0].dataType,l[0].dims),o=Rt("weight",l[1].dataType,l[1].dims),u=Rt("bias",l[2].dataType,l[2].dims),d=a.type.storage;return`\n const TILE_SIZE = 12u;\n var tileInput: array<${d}, 144>;\n var tileWeightQ: array<${d}, 144>;\n var tileWeightK: array<${d}, 144>;\n var tileWeightV: array<${d}, 144>;\n ${e.registerUniforms([{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}]).declareVariables(a,o,u,t,r,i)}\n ${e.mainStart([s,s,1])}\n let batchIndex = workgroup_id.z / uniforms.num_heads;\n let headNumber = workgroup_id.z % uniforms.num_heads;\n let m = global_id.y;\n let n = global_id.x;\n\n let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;\n let biasOffsetQ = headNumber * uniforms.head_size;\n let biasOffsetK = uniforms.hidden_size + biasOffsetQ;\n let biasOffsetV = uniforms.hidden_size + biasOffsetK;\n\n var valueQ = ${d}(0);\n var valueK = ${d}(0);\n var valueV = ${d}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n let offset = n + (w + local_id.y) * uniforms.ldb;\n tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];\n tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];\n tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k{let n=Yn(e.inputs,t),[r,i,a]=rr(e,n);return nr(e,r,i,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],n)}})),pu=j((()=>{pe(),Zl(),au(),iu(),su(),ar=(e,t)=>{if(!e||5!==e.length)throw new Error("BatchNormalization requires 5 inputs");let n=(e,t,n)=>{let r=t.length;if(r!==e.length)throw new Error(`${n}: num dimensions != ${r}`);t.forEach(((t,r)=>{if(t!==e[r])throw new Error(`${n}: dim[${r}] do not match`)}))};if(e[0].dims.length>1){let r="NHWC"===t.format?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);n(e[1].dims,r,"Invalid input scale"),n(e[2].dims,r,"Invalid input B"),n(e[3].dims,r,"Invalid input mean"),n(e[4].dims,r,"Invalid input var")}else n(e[1].dims,[1],"Invalid input scale"),n(e[2].dims,[1],"Invalid input B"),n(e[3].dims,[1],"Invalid input mean"),n(e[4].dims,[1],"Invalid input var")},sr=(e,t)=>{let{epsilon:n,spatial:r,format:i}=t,a=e[0].dims,s=r?zt(a[a.length-1]):1,o="NHWC"===i&&a.length>1?s:1,l=Tt.size(a)/s,u=r,d=u?a.length:a,c=Rt("x",e[0].dataType,e[0].dims,s),p=Rt("scale",e[1].dataType,e[1].dims,o),h=Rt("bias",e[2].dataType,e[2].dims,o),m=Rt("inputMean",e[3].dataType,e[3].dims,o),f=Rt("inputVar",e[4].dataType,e[4].dims,o),g=Vt("y",e[0].dataType,d,s);return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${r}_${s}`,inputDependencies:u?["rank","type","type","type","type"]:void 0},getShaderSource:e=>`\n const epsilon = ${n};\n ${e.registerUniform("outputSize","u32").declareVariables(c,p,h,m,f,g)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${g.offsetToIndices(`global_idx * ${s}`)};\n ${(()=>{let e="";if(r)e=`let cOffset = ${1===a.length?"0u":"NHWC"===i?`outputIndices[${a.length-1}] / ${s}`:"outputIndices[1]"};`;else if("NCHW"===i)e=`\n ${g.indicesSet("outputIndices","0","0")}\n let cOffset = ${g.indicesToOffset("outputIndices")};`;else{e=`var cIndices = ${p.type.indices}(0);\n cIndices[0] = outputIndices[${a.length-1}];`;for(let t=1;t({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u?[{type:12,data:l},...It(a)]:[{type:12,data:l}]})}},or=e=>xt(e),lr=(e,t)=>{let{inputs:n,outputCount:r}=e,i=or({...t,outputCount:r});if(p.webgpu.validateInputContent&&ar(n,i),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(sr(n,i))}})),hu=j((()=>{au(),su(),ur=e=>{if(3!==e[0].dims.length)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(1!==e[1].dims.length)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},dr=e=>{let t=e[0].dims,n=e[0].dims[2],r=Tt.size(t)/4,i=e[0].dataType,a=Rt("input",i,t,4),s=Rt("bias",i,[n],4),o=Rt("residual",i,t,4),l=Vt("output",i,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(r/64)}}),getShaderSource:e=>`\n const channels = ${n}u / 4;\n ${e.declareVariables(a,s,o,l)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(r)}\n let value = ${a.getByOffset("global_idx")}\n + ${s.getByOffset("global_idx % channels")} + ${o.getByOffset("global_idx")};\n ${l.setByOffset("global_idx","value")}\n }`}},cr=e=>{ur(e.inputs),e.compute(dr(e.inputs))}})),mu=j((()=>{Zl(),au(),iu(),su(),pr=(e,t,n,r,i,a,s)=>{let o=Math.ceil(t/4),l="";l="string"==typeof i?`${i}(a)`:i("a");let u=Rt("inputData",n,[o],4),d=Vt("outputData",r,[o],4),c=[{name:"vec_size",type:"u32"}];return s&&c.push(...s),`\n ${e.registerUniforms(c).declareVariables(u,d)}\n\n ${a??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n\n let a = ${u.getByOffset("global_idx")};\n ${d.setByOffset("global_idx",l)}\n }`},hr=(e,t,n,r,i,a=e.dataType,s,o)=>{let l=[{type:12,data:Math.ceil(Tt.size(e.dims)/4)}];return s&&l.push(...s),{name:t,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:t=>pr(t,Tt.size(e.dims),e.dataType,a,n,r,o),getRunData:t=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(Tt.size(t[0].dims)/64/4)},programUniforms:l})}},mr=e=>{e.compute(hr(e.inputs[0],"Abs","abs"))},fr=e=>{e.compute(hr(e.inputs[0],"Acos","acos"))},gr=e=>{e.compute(hr(e.inputs[0],"Acosh","acosh"))},_r=e=>{e.compute(hr(e.inputs[0],"Asin","asin"))},wr=e=>{e.compute(hr(e.inputs[0],"Asinh","asinh"))},br=e=>{e.compute(hr(e.inputs[0],"Atan","atan"))},yr=e=>{e.compute(hr(e.inputs[0],"Atanh","atanh"))},xr=e=>xt(e),vr=(e,t)=>{let n;switch(t.to){case 10:n="vec4";break;case 1:n="vec4";break;case 12:n="vec4";break;case 6:n="vec4";break;case 9:n="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(hr(e.inputs[0],"Cast",n,void 0,t.cacheKey,t.to))},Mr=e=>{let t,n,r=e.length>=2&&0!==e[1].data,i=e.length>=3&&0!==e[2].data;switch(e[0].dataType){case 1:t=r?e[1].getFloat32Array()[0]:-34028234663852886e22,n=i?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=r?e[1].getUint16Array()[0]:64511,n=i?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return xt({min:t,max:n})},Tr=(e,t)=>{let n=t||Mr(e.inputs),r=At(e.inputs[0].dataType);e.compute(hr(e.inputs[0],"Clip",(e=>`clamp(${e}, vec4<${r}>(uniforms.min), vec4<${r}>(uniforms.max))`),void 0,n.cacheKey,void 0,[{type:e.inputs[0].dataType,data:n.min},{type:e.inputs[0].dataType,data:n.max}],[{name:"min",type:r},{name:"max",type:r}]),{inputs:[0]})},kr=e=>{e.compute(hr(e.inputs[0],"Ceil","ceil"))},$r=e=>{e.compute(hr(e.inputs[0],"Cos","cos"))},Cr=e=>{e.compute(hr(e.inputs[0],"Cosh","cosh"))},Sr=e=>xt(e),Pr=(e,t)=>{let n=At(e.inputs[0].dataType);e.compute(hr(e.inputs[0],"Elu",(e=>`elu_vf32(${e})`),`\n const elu_alpha_ = ${n}(${t.alpha});\n\n fn elu_f32(a: ${n}) -> ${n} {\n return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);\n }\n\n fn elu_vf32(v: vec4<${n}>) -> vec4<${n}> {\n return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));\n }`,t.cacheKey))},Er=(e="f32")=>`\nconst r0: ${e} = 0.3275911;\nconst r1: ${e} = 0.254829592;\nconst r2: ${e} = -0.284496736;\nconst r3: ${e} = 1.421413741;\nconst r4: ${e} = -1.453152027;\nconst r5: ${e} = 1.061405429;\n\nfn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {\n let absv = abs(v);\n let x = 1.0 / (1.0 + r0 * absv);\n return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));\n}`,Fr=e=>{let t=At(e.inputs[0].dataType);e.compute(hr(e.inputs[0],"Erf",(e=>`erf_vf32(${e})`),Er(t)))},Ar=e=>{e.compute(hr(e.inputs[0],"Exp","exp"))},Ir=e=>{e.compute(hr(e.inputs[0],"Floor","floor"))},zr=e=>{let t=At(e.inputs[0].dataType);e.compute(hr(e.inputs[0],"Gelu",(e=>`0.5 * ${e} * (1.0 + erf_vf32(${e} * 0.7071067811865475))`),Er(t)))},Or=(e,t)=>{let n=At(e.inputs[0].dataType);e.compute(hr(e.inputs[0],"LeakyRelu",(e=>`select(leaky_relu_alpha_ * ${e}, ${e}, ${e} >= vec4<${n}>(0.0))`),`const leaky_relu_alpha_ = ${n}(${t.alpha});`,t.cacheKey))},Br=e=>{e.compute(hr(e.inputs[0],"Not",(e=>`!${e}`)))},Lr=e=>{e.compute(hr(e.inputs[0],"Neg",(e=>`-${e}`)))},Nr=e=>{e.compute(hr(e.inputs[0],"Reciprocal",(e=>`1.0/${e}`)))},Dr=e=>{let t=At(e.inputs[0].dataType);e.compute(hr(e.inputs[0],"Relu",(e=>`select(vec4<${t}>(0.0), ${e}, ${e} > vec4<${t}>(0.0))`)))},Rr=e=>{e.compute(hr(e.inputs[0],"Sigmoid",(e=>`(1.0 / (1.0 + exp(-${e})))`)))},Vr=e=>xt(e),jr=(e,t)=>{let n=At(e.inputs[0].dataType);e.compute(hr(e.inputs[0],"HardSigmoid",(e=>`max(vec4<${n}>(0.0), min(vec4<${n}>(1.0), ${t.alpha} * ${e} + vec4<${n}>(${t.beta})))`),void 0,t.cacheKey))},qr=e=>{e.compute(hr(e.inputs[0],"Sin","sin"))},Gr=e=>{e.compute(hr(e.inputs[0],"Sinh","sinh"))},Wr=e=>{e.compute(hr(e.inputs[0],"Sqrt","sqrt"))},Ur=e=>{e.compute(hr(e.inputs[0],"Tan","tan"))},Hr=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Xr=e=>{e.compute(hr(e.inputs[0],"Tanh",Hr))},Kr=(e="f32")=>`\nconst fast_gelu_a: ${e} = 0.5;\nconst fast_gelu_b: ${e} = 0.7978845608028654;\nconst fast_gelu_c: ${e} = 0.035677408136300125;\n\nfn tanh_v(v: vec4<${e}>) -> vec4<${e}> {\n return ${Hr("v")};\n}\n`,Qr=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Yr=e=>{let t=At(e.inputs[0].dataType);e.compute(hr(e.inputs[0],"FastGelu",Qr,Kr(t),void 0,e.inputs[0].dataType))},Zr=(e,t)=>{let n=At(e.inputs[0].dataType);return e.compute(hr(e.inputs[0],"ThresholdedRelu",(e=>`select(vec4<${n}>(0.0), ${e}, ${e} > thresholded_relu_alpha_)`),`const thresholded_relu_alpha_ = vec4<${n}>(${t.alpha});`,t.cacheKey)),0},Jr=e=>{e.compute(hr(e.inputs[0],"Log","log"))},ei=(e,t)=>`\nconst alpha = vec4<${e}>(${t});\nconst one = ${e}(1.0);\nconst zero = ${e}(0.0);\n\nfn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {\n let v = x *alpha;\n var x1 : vec4<${e}>;\n for (var i = 0; i < 4; i = i + 1) {\n if (v[i] >= zero) {\n x1[i] = one / (one + exp(-v[i]));\n } else {\n x1[i] = one - one / (one + exp(v[i]));\n }\n }\n return x * x1;\n}\n`,ti=e=>`quick_gelu_impl(${e})`,ni=(e,t)=>{let n=At(e.inputs[0].dataType);e.compute(hr(e.inputs[0],"QuickGelu",ti,ei(n,t.alpha),t.cacheKey,e.inputs[0].dataType))}})),fu=j((()=>{au(),su(),mu(),ri=e=>{if(3!==e[0].dims.length)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(1!==e[1].dims.length)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},ii=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let n=Rt("input",e[0].dataType,e[0].dims,4),r=Rt("bias",e[0].dataType,[e[0].dims[2]],4),i=Vt("output",e[0].dataType,t,4),a=Tt.size(t)/4,s=Ft(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:t=>`\n const M_SQRT2 = sqrt(2.0);\n const halfChannels = ${e[0].dims[2]/4/2}u;\n\n ${t.declareVariables(n,r,i)}\n\n ${Er(s)}\n\n ${t.mainStart()}\n ${t.guardAgainstOutOfBoundsWorkgroupSizes(a)}\n let biasIdx = global_idx % halfChannels;\n let batchIndex = global_idx / halfChannels;\n let inputOffset = biasIdx + batchIndex * halfChannels * 2;\n let valueLeft = input[inputOffset] + bias[biasIdx];\n let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];\n let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);\n\n ${i.setByOffset("global_idx","valueLeft * geluRight")}\n }`}},ai=e=>{ri(e.inputs),e.compute(ii(e.inputs))}})),gu=j((()=>{Zl(),au(),su(),si=(e,t,n,r,i,a,s,o,l,u,d,c)=>{let p,h;"string"==typeof o?p=h=(e,t)=>`${o}((${e}),(${t}))`:"function"==typeof o?p=h=o:(p=o.scalar,h=o.vector);let m,f=Vt("outputData",d,r.length,4),g=Rt("aData",l,t.length,4),_=Rt("bData",u,n.length,4);if(i)if(a){let e=1===Tt.size(t),r=1===Tt.size(n),i=t.length>0&&t[t.length-1]%4==0,a=n.length>0&&n[n.length-1]%4==0;m=e||r?f.setByOffset("global_idx",h(e?`${g.type.value}(${g.getByOffset("0")}.x)`:g.getByOffset("global_idx"),r?`${_.type.value}(${_.getByOffset("0")}.x)`:_.getByOffset("global_idx"))):`\n let outputIndices = ${f.offsetToIndices("global_idx * 4u")};\n let offsetA = ${g.broadcastedIndicesToOffset("outputIndices",f)};\n let offsetB = ${_.broadcastedIndicesToOffset("outputIndices",f)};\n ${f.setByOffset("global_idx",h(s||i?g.getByOffset("offsetA / 4u"):`${g.type.value}(${g.getByOffset("offsetA / 4u")}[offsetA % 4u])`,s||a?_.getByOffset("offsetB / 4u"):`${_.type.value}(${_.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}\n `}else m=f.setByOffset("global_idx",h(g.getByOffset("global_idx"),_.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let e=(e,t,n="")=>{let r=`aData[indexA${t}][componentA${t}]`,i=`bData[indexB${t}][componentB${t}]`;return`\n let outputIndices${t} = ${f.offsetToIndices(`global_idx * 4u + ${t}u`)};\n let offsetA${t} = ${g.broadcastedIndicesToOffset(`outputIndices${t}`,f)};\n let offsetB${t} = ${_.broadcastedIndicesToOffset(`outputIndices${t}`,f)};\n let indexA${t} = offsetA${t} / 4u;\n let indexB${t} = offsetB${t} / 4u;\n let componentA${t} = offsetA${t} % 4u;\n let componentB${t} = offsetB${t} % 4u;\n ${e}[${t}] = ${n}(${p(r,i)});\n `};m=9===d?`\n var data = vec4(0);\n ${e("data",0,"u32")}\n ${e("data",1,"u32")}\n ${e("data",2,"u32")}\n ${e("data",3,"u32")}\n outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:`\n ${e("outputData[global_idx]",0)}\n ${e("outputData[global_idx]",1)}\n ${e("outputData[global_idx]",2)}\n ${e("outputData[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables(g,_,f)}\n\n ${c??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${m}\n }`},oi=(e,t,n,r,i,a,s=n.dataType)=>{let o=n.dims.map((e=>Number(e)??1)),l=r.dims.map((e=>Number(e)??1)),u=!Tt.areEqual(o,l),d=o,c=Tt.size(o),p=!1,h=!1,m=[u];if(u){let e=Mt.calcShape(o,l,!1);if(!e)throw new Error("Can't perform binary op on the given tensors");d=e.slice(),c=Tt.size(d);let t=1===Tt.size(o),n=1===Tt.size(l),r=o.length>0&&o[o.length-1]%4==0,i=l.length>0&&l[l.length-1]%4==0;m.push(t),m.push(n),m.push(r),m.push(i);let a=1;for(let e=1;ee.toString())).join("_"),inputDependencies:["rank","rank"]},getShaderSource:e=>si(e,o,l,d,p,u,h,i,n.dataType,r.dataType,s,a),getRunData:()=>({outputs:[{dims:d,dataType:s}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:Math.ceil(Tt.size(d)/4)},...It(o,l,d)]})}},li=(e,t,n,r,i,a)=>{e.compute(oi(t,i??"",e.inputs[0],e.inputs[1],n,r,a))},ui=e=>{li(e,"Add",((e,t)=>`${e}+${t}`))},di=e=>{li(e,"Div",((e,t)=>`${e}/${t}`))},ci=e=>{li(e,"Equal",{scalar:(e,t)=>`u32(${e}==${t})`,vector:(e,t)=>`vec4(${e}==${t})`},void 0,void 0,9)},pi=e=>{li(e,"Mul",((e,t)=>`${e}*${t}`))},hi=e=>{let t=Rt("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;li(e,"Pow",{scalar:(e,t)=>`pow_custom(${e},${t})`,vector:(e,t)=>`pow_vector_custom(${e},${t})`},`\n fn pow_custom(a : ${t}, b : ${t}) -> ${t} {\n if (b == ${t}(0.0)) {\n return ${t}(1.0);\n } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {\n return ${t}(pow(f32(a), f32(b))); // NaN\n }\n return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${"i32"===t?"round":""}(pow(f32(abs(a)), f32(b))));\n }\n fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {\n // TODO: implement vectorized pow\n return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));\n }\n `)},mi=e=>{li(e,"Sub",((e,t)=>`${e}-${t}`))},fi=e=>{li(e,"Greater",{scalar:(e,t)=>`u32(${e}>${t})`,vector:(e,t)=>`vec4(${e}>${t})`},void 0,void 0,9)},gi=e=>{li(e,"Less",{scalar:(e,t)=>`u32(${e}<${t})`,vector:(e,t)=>`vec4(${e}<${t})`},void 0,void 0,9)},_i=e=>{li(e,"GreaterOrEqual",{scalar:(e,t)=>`u32(${e}>=${t})`,vector:(e,t)=>`vec4(${e}>=${t})`},void 0,void 0,9)},wi=e=>{li(e,"LessOrEqual",{scalar:(e,t)=>`u32(${e}<=${t})`,vector:(e,t)=>`vec4(${e}<=${t})`},void 0,void 0,9)}})),_u=j((()=>{Zl(),au(),iu(),su(),bi=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let n=e[0],r=n.dataType,i=n.dims.length;e.forEach(((e,a)=>{if(0!==a){if(e.dataType!==r)throw new Error("input tensors should be one type");if(e.dims.length!==i)throw new Error("input tensors should have the same shape");e.dims.forEach(((e,r)=>{if(r!==t&&e!==n.dims[r])throw new Error("non concat dimensions must match")}))}}))},yi=(e,t)=>`\n fn calculateInputIndex(index: u32) -> u32 {\n let sizeInConcatAxis = array(${t});\n for (var i: u32 = 0u; i < ${e}; i += 1u ) {\n if (index < sizeInConcatAxis[i]) {\n return i;\n }\n }\n return ${e}u;\n }`,xi=(e,t)=>{let n=e.length,r=[];for(let i=0;i{let i=Tt.size(n),a=new Array(e.length),s=new Array(e.length),o=0,l=[],u=[],d=[{type:12,data:i}];for(let n=0;n`uniforms.sizeInConcatAxis${e}`)).join(",");return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:n,dataType:r}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:d}),getShaderSource:t=>`\n\n ${(()=>{t.registerUniform("outputSize","u32");for(let n=0;n(${h});\n ${p} -= sizeInConcatAxis[inputIndex - 1u];\n }\n\n ${xi(s,c)}\n }`}},Mi=(e,t)=>{let n=e.inputs,r=n[0].dims,i=Tt.normalizeAxis(t.axis,r.length);bi(n,i);let a=r.slice();a[i]=n.reduce(((e,t)=>e+(t.dims.length>i?t.dims[i]:0)),0);let s=n.filter((e=>Tt.size(e.dims)>0));e.compute(vi(s,i,a,n[0].dataType),{inputs:s})},Ti=e=>xt({axis:e.axis})})),wu=j((()=>{Zl(),au(),ki=(e,t,n="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${n}(uniforms.clip_min)), ${t}(${n}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${n}(uniforms.alpha) * value + ${n}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${n}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return"let e2x = exp(-2.0 * abs(value));\n value = sign(value) * (1.0 - e2x) / (1.0 + e2x);\n ";case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},$i=(e,t)=>{"Clip"===e.activation?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):"HardSigmoid"===e.activation?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):"LeakyRelu"===e.activation&&t.push({type:1,data:e.alpha})},Ci=(e,t)=>{"Clip"===e.activation?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):"HardSigmoid"===e.activation?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):"LeakyRelu"===e.activation&&t.push({name:"alpha",type:"f32"})},Si=e=>{let t=e?.activation||"";if("HardSigmoid"===t){let[n,r]=e?.activation_params||[.2,.5];return{activation:t,alpha:n,beta:r}}if("Clip"===t){let[n,r]=e?.activation_params||[Ct,St];return{activation:t,clipMax:r,clipMin:n}}if("LeakyRelu"===t){let[n]=e?.activation_params||[.01];return{activation:t,alpha:n}}return{activation:t}}})),bu=j((()=>{Pi=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},Ei=e=>`\n ${e?"value = value + getBiasByOutputCoords(coords);":""}\n `})),yu=j((()=>{Fi=e=>`\nfn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 {\n return dot(coords, vec4(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n}\nfn getOutputIndexFromCoords(coords : vec4) -> i32 {\n return dot(coords, vec4(\n i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));\n}\n`})),xu=j((()=>{Zl(),au(),su(),wu(),Ai=(e,t,n,r,i)=>{let a=r-n;return`\n ${Array.from({length:n}).map(((n,s)=>`\n if (${Nt(t.shape,s,t.rank)} != 1) {\n ${t.indicesSet(e,s,Nt(i,s+a,r))}\n } else {\n ${t.indicesSet(e,s,0)}\n }`)).join("")}\n`},Ii=(e,t,n,r,i=!1,a)=>{let s=e[0].dims,o=e[1].dims,l=s[s.length-2],u=o[o.length-1],d=s[s.length-1],c=zt(u),p=zt(d),h=zt(l),m=Tt.size(n)/c/h,f=e.length>2,g=r?r.slice(0,-2):n.slice(0,-2),_=[Tt.size(g),l,u],w=[{type:12,data:m},{type:12,data:l},{type:12,data:u},{type:12,data:d}];$i(t,w),w.push(...It(g,s,o)),f&&w.push(...It(e[2].dims)),w.push(...It(_));return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${c};${p};${h};${i}`,inputDependencies:f?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:a?a(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:w}),getShaderSource:r=>{let a=jt("batch_dims",e[0].dataType,g.length),l=Rt("a",e[0].dataType,s.length,p),u=Rt("b",e[1].dataType,o.length,c),d=Vt("output",e[0].dataType,_.length,c),m=Ft(d.type.tensor),w=ki(t,d.type.value,m),b=[l,u],y="";if(f){let t=i?c:1;b.push(Rt("bias",e[2].dataType,e[2].dims.length,t)),y=""+(i?`value += bias[col / ${t}];`:`value += ${d.type.value}(bias[row + i]);`)}let x=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Ci(t,x);return`\n ${r.registerUniforms(x).registerInternalVariables(a).declareVariables(...b,d)}\n ${r.mainStart()}\n ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let col = (global_idx % (uniforms.N / ${c})) * ${c};\n var index1 = global_idx / (uniforms.N / ${c});\n let stride1 = uniforms.M / ${h};\n let row = (index1 % stride1) * ${h};\n let batch = index1 / stride1;\n\n ${2===n.length?"":`let batch_indices = ${a.offsetToIndices("batch")};`}\n\n var a_indices: ${l.type.indices};\n ${Ai("a_indices",l,l.rank-2,a.rank,"batch_indices")}\n ${l.indicesSet("a_indices",l.rank-2,0)}\n ${l.indicesSet("a_indices",l.rank-1,0)}\n let a_offset = ${l.indicesToOffset("a_indices")};\n\n var b_indices: ${u.type.indices};\n ${Ai("b_indices",u,u.rank-2,a.rank,"batch_indices")}\n ${u.indicesSet("b_indices",u.rank-2,0)}\n ${u.indicesSet("b_indices",u.rank-1,0)}\n let b_offset = ${u.indicesToOffset("b_indices")};\n var values: array<${d.type.value}, ${h}>;\n for (var k: u32 = 0u; k < uniforms.K; k = k + ${p}) {\n ${(()=>{let e=`var a_data: ${l.type.value};`;for(let t=0;t{Zl(),au(),su(),wu(),xu(),bu(),zi=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart / innerElementSize + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRow + innerRow,\n kStart / innerElementSize + inputCol${t?", batchIndices":""});\n `,Oi=(e,t)=>e?`\n let ACached0 = mm_Asub[k * innerElementSize][localRow];\n let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];\n let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];\n ${3===t?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}\n for (var i = 0; i < rowPerThread; i = i + 1) {\n acc[i] = BCached0 * ACached0[i] + acc[i];\n acc[i] = BCached1 * ACached1[i] + acc[i];\n acc[i] = BCached2 * ACached2[i] + acc[i];\n ${3===t?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"}\n }`:`\n for (var i = 0; i < rowPerThread; i = i + 1) {\n let ACached = mm_Asub[tileRow + i][k];\n acc[i] = BCached0 * ACached.x + acc[i];\n acc[i] = BCached1 * ACached.y + acc[i];\n acc[i] = BCached2 * ACached.z + acc[i];\n ${3===t?"":"acc[i] = BCached3 * ACached.w + acc[i];"}\n }`,Bi=(e,t,n="f32",r,i=!1,a=32,s=!1,o=32)=>{let l=t[1]*e[1],u=t[0]*e[0],d=i?l:a,c=i?a:l,p=d/t[0],h=a/t[1];if((!i||4!==p||4!==e[1])&&(i||3!==p&&4!==p)||d%t[0]!=0||a%t[1]!=0||4!==e[0])throw new Error(`If transposeA ${i} is true, innerElementSize ${p} and workPerThread[1] ${e[1]} must be 4.\n Otherwise, innerElementSize ${p} must be 3 or 4.\n tileAWidth ${d} must be divisible by workgroupSize[0]${t[0]}. tileInner ${a} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`\nvar mm_Asub: array, ${d/p}>, ${c}>;\nvar mm_Bsub: array, ${u/e[0]}>, ${a}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${p};\nconst tileInner = ${a};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let localRow = i32(localId.y);\n let tileRow = localRow * rowPerThread;\n let tileCol = i32(localId.x);\n\n let globalRow =i32(globalId.y) * rowPerThread;\n let globalCol = i32(globalId.x);\n let batch = ${s?"0":"i32(globalId.z)"};\n ${r?`let batchIndices = ${r.offsetToIndices("u32(batch)")};`:""}\n let globalRowStart = i32(workgroupId.y) * ${l};\n\n let num_tiles = ${s?`${Math.ceil(o/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${s?`i32(globalId.z) * ${o}`:"0"};\n\n var acc: array, rowPerThread>;\n\n // Loop over shared dimension.\n let tileRowB = localRow * ${h};\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileCol;\n ${zi(i,r)}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${h}; innerRow = innerRow + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${r?", batchIndices":""});\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {\n let BCached0 = mm_Bsub[k * innerElementSize][tileCol];\n let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];\n let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];\n ${3===p?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}\n\n ${Oi(i,p)}\n }\n\n workgroupBarrier();\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);\n }\n}`},Li=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRowStart + inputRow,\n kStart + inputCol${t?", batchIndices":""});\n `,Ni=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Di=(e,t,n="f32",r,i=!1,a=32,s=!1,o=32,l=!1)=>{let u=e[1]*t[1],d=e[0]*t[0],c=i?u:a,p=i?a:u;if(p%t[1]!=0||c%t[0]!=0||a%t[1]!=0)throw new Error(`tileAHight ${p} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${c} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let h=p/t[1],m=c/t[0],f=a/t[1],g=l?`\n let localRow = i32(localId.y);\n let localCol = i32(localId.x);\n let globalRowStart = i32(workgroupId.y) * ${u};\n let globalColStart = i32(workgroupId.x) * ${d};\n\n // Loop over shared dimension.\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var inputRow = localRow; inputRow < ${p}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${c}; inputCol = inputCol + ${t[0]}) {\n ${Li(i,r)}\n }\n }\n // Load one tile of B into local memory.\n for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${t[0]}) {\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalColStart + inputCol${r?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${n}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let ACached = ${i?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] +\n ACached * BCached[innerCol];\n }\n }\n }\n workgroupBarrier();\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let gRow = globalRowStart + localRow + innerRow * ${t[1]};\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let gCol = globalColStart + localCol + innerCol * ${t[0]};\n mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);\n }\n }\n `:`\nlet tileRow = i32(localId.y) * rowPerThread;\nlet tileCol = i32(localId.x) * colPerThread;\n\nlet globalRow = i32(globalId.y) * rowPerThread;\nlet globalCol = i32(globalId.x) * colPerThread;\nlet globalRowStart = i32(workgroupId.y) * ${u};\n\nlet tileRowA = i32(localId.y) * ${h};\nlet tileColA = i32(localId.x) * ${m};\nlet tileRowB = i32(localId.y) * ${f};\n// Loop over shared dimension.\nfor (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${h}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${m}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${Li(i,r)}\n }\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${f}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol + innerCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalCol + innerCol${r?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${n}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][tileCol + inner];\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n ${Ni(i)}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];\n }\n }\n }\n\n workgroupBarrier();\n}\n\nfor (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n mm_write(batch, globalRow + innerRow, globalCol + innerCol,\n acc[innerRow][innerCol]);\n }\n}\n`;return`\n var mm_Asub : array, ${p}>;\n var mm_Bsub : array, ${a}>;\n const rowPerThread = ${e[1]};\n const colPerThread = ${e[0]};\n const tileInner = ${a};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let batch = ${s?"0":"i32(globalId.z)"};\n ${r?`let batchIndices = ${r.offsetToIndices("u32(batch)")};`:""}\n let num_tiles = ${s?`${Math.ceil(o/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${s?`i32(globalId.z) * ${o}`:"0"};\n\n var acc : array, rowPerThread>;\n ${g}\n }\n`},Ri=(e,t,n,r,i=!1)=>{let[a,s,o,l]=r,u=Ft(r[0].type.tensor);return`\n fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Pi(e,u)} {\n var value = ${Pi(e,u)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)\n {\n var aIndices: ${s.type.indices};\n ${Ai("aIndices",s,s.rank-2,a.rank,"batchIndices")}\n ${s.indicesSet("aIndices",s.rank-2,"u32(row)")}\n ${s.indicesSet("aIndices",s.rank-1,"u32(colIn)")}\n value = ${s.getByIndices("aIndices")};\n }\n return value;\n }\n\n fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Pi(e,u)} {\n var value = ${Pi(e,u)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)\n {\n var bIndices: ${o.type.indices};\n ${Ai("bIndices",o,o.rank-2,a.rank,"batchIndices")}\n ${o.indicesSet("bIndices",o.rank-2,"u32(row)")}\n ${o.indicesSet("bIndices",o.rank-1,"u32(colIn)")}\n value = ${o.getByIndices("bIndices")};\n }\n return value;\n }\n\n fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Pi(e,u)}) {\n let col = colIn * ${e};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueIn;\n let coords = vec3(batch, row, colIn);\n ${t?`value = value + ${i?"bias[colIn]":`${Pi(e,u)}(bias[row])`};`:""}\n ${n}\n ${l.setByIndices("vec3(coords)","value")}\n }\n }\n `},Vi=(e,t,n,r,i=!1,a)=>{let s=e[0].dims,o=e[1].dims,l=s.slice(0,-2),u=o.slice(0,-2),d=r?r.slice(0,-2):n.slice(0,-2),c=Tt.size(d),p=s[s.length-2],h=s[s.length-1],m=o[o.length-1],f=h%4==0&&m%4==0,g=p<=8?[4,1,1]:[4,4,1],_=[8,8,1],w=[Math.ceil(m/_[0]/g[0]),Math.ceil(p/_[1]/g[1]),Math.ceil(c/_[2]/g[2])],b=f?4:1,y=[...l,p,h/b],x=y.length,v=[...u,h,m/b],M=v.length,T=[c,p,m/b],k=[{type:6,data:p},{type:6,data:m},{type:6,data:h}];$i(t,k),k.push(...It(d,y,v));let $=["rank","rank"],C=e.length>2;C&&(k.push(...It(e[2].dims)),$.push("rank")),k.push(...It(T));return{name:"MatMul",shaderCache:{hint:`${g};${t.activation};${f};${i}`,inputDependencies:$},getRunData:()=>({outputs:[{dims:a?a(n):n,dataType:e[0].dataType}],dispatchGroup:{x:w[0],y:w[1],z:w[2]},programUniforms:k}),getShaderSource:n=>{let r=d.length,a=jt("batchDims",e[0].dataType,r,1),s=Ft(e[0].dataType),o=Rt("a",e[0].dataType,x,b),l=Rt("b",e[1].dataType,M,b),u=Vt("result",e[0].dataType,T.length,b),c=[o,l];if(C){let t=i?b:1;c.push(Rt("bias",e[2].dataType,e[2].dims.length,t))}let p=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Ci(t,p);let h=Ft(u.type.tensor),m=ki(t,u.type.value,h),w=Ri(b,C,m,[a,o,l,u],i);return`\n ${n.registerUniforms(p).registerInternalVariables(a).declareVariables(...c,u)}\n ${w}\n ${f?Bi(g,_,s,a):Di(g,_,s,a)}\n `}}}})),Mu=j((()=>{Zl(),eu(),su(),wu(),bu(),yu(),vu(),ji=(e,t,n,r,i=!1,a,s=4,o=4,l=4,u="f32")=>{let d=e?"\n let coord = vec4(batch, xRow, xCol, xCh);\n ":"\n let coord = vec4(batch, xCh, xRow, xCol);\n ",c=e?"\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n ":"\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n ",p=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",h=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",m=e?"row":"col",f=e?"col":"row",g=`\n let inChannels = i32(uniforms.w_shape[2]);\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${m} / outWidth;\n let outCol = ${m} % outWidth;\n\n let WRow = ${f} / (i32(uniforms.w_shape[1]) * inChannels);\n let WCol = ${f} / inChannels % i32(uniforms.w_shape[1]);\n let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];\n let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];\n let xCh = ${f} % inChannels;\n var resData = ${Pi(s,u)}(0.0);\n // The bounds checking is always needed since we use it to pad zero for\n // the 'same' padding type.\n if (xRow >= 0 && xRow < ${p} && xCol >= 0 && xCol < ${h}) {\n ${d}\n let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape));\n ${(e=>{switch(e){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${u}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${e} is not supported.`)}})(s)}\n }\n return resData;`,_=e?t&&r?`\n let col = colIn * ${s};\n ${g}`:`\n let col = colIn * ${s};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${g}\n }\n return ${Pi(s,u)}(0.0);`:r&&n?`\n let col = colIn * ${s};\n ${g}`:`\n let col = colIn * ${s};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${g}\n }\n return ${Pi(s,u)}(0.0);`,w=`${(e=>{switch(e){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${e} is not supported.`)}})(o)}`,b=Pi(l,u),y=Pi(e?s:o,u),x=Pi(e?o:s,u),v=ki(a,b,u);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${y} {\n ${e?_:w}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${x} {\n ${e?w:_}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${b}) {\n let col = colIn * ${l};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)\n {\n var value = valueIn;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${c}\n ${Ei(i)}\n ${v}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`},qi=(e,t,n,r,i,a,s,o,l)=>{let u="NHWC"===t.format,d=u?e[0].dims[3]:e[0].dims[1],c=n[0],p=u?n[2]:n[3],h=u?n[1]:n[2],m=u?n[3]:n[1],f=u&&(d%4==0||d%3==0)&&m%4==0,g=u?m:p*h,_=u?p*h:m,w=[8,8,1],b=r<=8?[4,1,1]:[4,4,1],y=[Math.ceil(g/w[0]/b[0]),Math.ceil(_/w[1]/b[1]),Math.ceil(c/w[2]/b[2])];ut("verbose",(()=>`[conv2d_mm_webgpu] dispatch = ${y}`));let x=f?u&&d%4!=0?3:4:1,v=w[1]*b[1],M=w[0]*b[0],T=Math.max(w[0]*x,w[1]),k=r%v==0,$=i%M==0,C=a%T==0,S=f?[x,4,4]:[1,1,1],P=[{type:6,data:r},{type:6,data:i},{type:6,data:a},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];$i(t,P),P.push(...It(e[0].dims,e[1].dims));let E=["rank","rank"];s&&(P.push(...It(e[2].dims)),E.push("rank")),P.push(...It(n));return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${x};${f};${k};${$};${C};${v};${M};${T}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:l?l(n):n,dataType:e[0].dataType}],dispatchGroup:{x:y[0],y:y[1],z:y[2]},programUniforms:P}),getShaderSource:r=>{let i=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];Ci(t,i);let a=f?4:1,l=Ft(e[0].dataType),d=`\n fn setOutputAtIndex(flatIndex : i32, value : ${f?`vec4<${l}>`:l}) {\n result[flatIndex] = ${f?`vec4<${l}>`:l}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${f?`vec4<${l}>`:l}) {\n let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${f?"/ 4":""}, value);\n }`,c=[Rt("x",e[0].dataType,e[0].dims.length,3===x?1:x),Rt("w",e[1].dataType,e[1].dims.length,a)],p=Vt("result",e[0].dataType,n.length,a);if(s){let t=Rt("bias",e[2].dataType,e[2].dims.length,a);c.push(t),d+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${f?`vec4<${l}>`:l} {\n return bias[coords.${u?"w":"y"}${f?"/ 4":""}];\n }`}return`\n ${Fi("uniforms.result_strides")}\n //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4,\n // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2,\n // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };\n ${r.registerUniforms(i).declareVariables(...c,p)}\n ${d}\n ${ji(u,k,$,C,s,t,S[0],S[1],S[2],l)}\n ${f?Bi(b,w,l,void 0,!u,T):Di(b,w,l,void 0,!u,T,!1,void 0,o)}`}}}})),Tu=j((()=>{Zl(),eu(),au(),su(),wu(),bu(),Gi=e=>{let t=1;for(let n=0;n"number"==typeof e?[e,e,e]:e,Ui=(e,t)=>t<=1?e:e+(e-1)*(t-1),Hi=(e,t,n,r=1)=>{let i=Ui(t,r);return Math.floor((e[0]*(n-1)-n+i)/2)},Xi=(e,t,n,r,i)=>{null==i&&(i=Hi(e,t[0],r[0]));let a=[0,0,0,n];for(let n=0;n<3;n++)e[n]+2*i>=t[n]&&(a[n]=Math.trunc((e[n]-t[n]+2*i)/r[n]+1));return a},Ki=(e,t,n,r,i,a,s,o,l,u)=>{let d,c,p,h;if("VALID"===e&&(e=0),"number"==typeof e){d={top:e,bottom:e,left:e,right:e,front:e,back:e};let m=Xi([t,n,r,1],[o,l,u],1,[i,a,s],e);c=m[0],p=m[1],h=m[2]}else if(Array.isArray(e)){if(!e.every(((e,t,n)=>e===n[0])))throw Error(`Unsupported padding parameter: ${e}`);d={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let m=Xi([t,n,r,1],[o,l,u],1,[i,a,s],e[0]);c=m[0],p=m[1],h=m[2]}else{if("SAME_UPPER"!==e)throw Error(`Unknown padding parameter: ${e}`);{c=Math.ceil(t/i),p=Math.ceil(n/a),h=Math.ceil(r/s);let e=(c-1)*i+o-t,m=(p-1)*a+l-n,f=(h-1)*s+u-r,g=Math.floor(e/2),_=e-g,w=Math.floor(m/2),b=m-w,y=Math.floor(f/2);d={top:w,bottom:b,left:y,right:f-y,front:g,back:_}}}return{padInfo:d,outDepth:c,outHeight:p,outWidth:h}},Qi=(e,t,n,r,i,a=!1,s="channelsLast")=>{let o,l,u,d,c;if("channelsLast"===s)[o,l,u,d,c]=e;else{if("channelsFirst"!==s)throw new Error(`Unknown dataFormat ${s}`);[o,c,l,u,d]=e}let[p,,h,m,f]=t,[g,_,w]=Wi(n),[b,y,x]=Wi(r),v=Ui(h,b),M=Ui(m,y),T=Ui(f,x),{padInfo:k,outDepth:$,outHeight:C,outWidth:S}=Ki(i,l,u,d,g,_,w,v,M,T),P=a?p*c:p,E=[0,0,0,0,0];return"channelsFirst"===s?E=[o,P,$,C,S]:"channelsLast"===s&&(E=[o,$,C,S,P]),{batchSize:o,dataFormat:s,inDepth:l,inHeight:u,inWidth:d,inChannels:c,outDepth:$,outHeight:C,outWidth:S,outChannels:P,padInfo:k,strideDepth:g,strideHeight:_,strideWidth:w,filterDepth:h,filterHeight:m,filterWidth:f,effectiveFilterDepth:v,effectiveFilterHeight:M,effectiveFilterWidth:T,dilationDepth:b,dilationHeight:y,dilationWidth:x,inShape:e,outShape:E,filterShape:t}},Yi=(e,t,n,r,i,a)=>{let s="channelsLast"===a,o=(s?e[0].dims[3]:e[0].dims[1],{x:n.map(((e,t)=>t))}),l=[Math.ceil(Gi(o.x.map((e=>n[e])))/64),1,1];ut("verbose",(()=>`[conv3d_naive_webgpu] dispatch = ${l}`));let u=[{type:12,data:Tt.size(n)},{type:12,data:r},{type:12,data:i},{type:12,data:t.strides},{type:12,data:t.dilations}];$i(t,u),u.push(...It(e[0].dims,e[1].dims));let d=["rank","rank"],c=3===e.length;c&&(u.push(...It(e[2].dims)),d.push("rank")),u.push(...It(n));return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${s};1;${c}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:l[0],y:l[1],z:l[2]},programUniforms:u}),getShaderSource:a=>{let o=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:r.length},{name:"pads",type:"u32",length:i.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Ci(t,o);let l=Ft(e[0].dataType),u=Rt("x",e[0].dataType,e[0].dims.length,1),d=Rt("W",e[1].dataType,e[1].dims.length,1),p=[u,d],h=Vt("result",e[0].dataType,n.length,1),m="";if(c){let t=Rt("bias",e[2].dataType,e[2].dims.length,1);p.push(t),m+=`\n fn getBiasByOutputCoords(coords : array) -> ${l} {\n return bias[${Nt("coords",s?4:1,5)}];\n }`}let f=Pi(1,l),g=ki(t,f,l);return`\n ${m}\n fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {\n let aIndices = array(d0, d1, d2, d3, d4);\n return ${u.getByIndices("aIndices")};\n }\n fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {\n let aIndices = array(d0, d1, d2, d3, d4);\n return ${d.getByIndices("aIndices")};\n }\n ${a.registerUniforms(o).declareVariables(...p,h)}\n ${a.mainStart()}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let coords = ${h.offsetToIndices("global_idx")};\n let batch = ${Nt("coords",0,u.rank)};\n let d2 = ${Nt("coords",s?u.rank-1:1,u.rank)};\n let xFRCCorner = vec3(${Nt("coords",s?1:2,u.rank)},\n ${Nt("coords",s?2:3,u.rank)},\n ${Nt("coords",s?3:4,u.rank)}) * uniforms.strides - uniforms.pads;\n let xFCorner = xFRCCorner.x;\n let xRCorner = xFRCCorner.y;\n let xCCorner = xFRCCorner.z;\n let xShapeY = ${Nt("uniforms.x_shape",s?1:2,u.rank)};\n let xShapeZ = ${Nt("uniforms.x_shape",s?2:3,u.rank)};\n let xShapeW = ${Nt("uniforms.x_shape",s?3:4,u.rank)};\n let xShapeU = ${Nt("uniforms.x_shape",s?4:1,u.rank)};\n let inputDepthNearestVec4 = (xShapeU / 4) * 4;\n let inputDepthVec4Remainder = xShapeU % 4;\n\n var value = 0.0;\n for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) {\n let xF = xFCorner + wF * uniforms.dilations[0];\n if (xF < 0 || xF >= xShapeY) {\n continue;\n }\n\n for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) {\n let xR = xRCorner + wR * uniforms.dilations[1];\n if (xR < 0 || xR >= xShapeZ) {\n continue;\n }\n\n for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) {\n let xC = xCCorner + wC * uniforms.dilations[2];\n if (xC < 0 || xC >= xShapeW) {\n continue;\n }\n\n for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) {\n ${s?"let 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 ":"let xValues = vec4(\n getX(batch, d1, xF, xR, xC),\n getX(batch, d1 + 1, xF, xR, xC),\n getX(batch, d1 + 2, xF, xR, xC),\n getX(batch, d1 + 3, xF, xR, xC));\n "}\n let wValues = vec4(\n getW(d2, d1, wF, wR, wC),\n getW(d2, d1 + 1, wF, wR, wC),\n getW(d2, d1 + 2, wF, wR, wC),\n getW(d2, d1 + 3, wF, wR, wC));\n value += dot(xValues, wValues);\n }\n if (inputDepthVec4Remainder == 1) {\n ${s?"value += getX(batch, xF, xR, xC, inputDepthNearestVec4)\n * getW(d2, inputDepthNearestVec4, wF, wR, wC);":"value += getX(batch, inputDepthNearestVec4, xF, xR, xC)\n * getW(d2, inputDepthNearestVec4, wF, wR, wC);"}\n } else if (inputDepthVec4Remainder == 2) {\n ${s?"let xValues = vec2(\n getX(batch, xF, xR, xC, inputDepthNearestVec4),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1));\n ":"let xValues = vec2(\n getX(batch, inputDepthNearestVec4, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC));\n "}\n let wValues = vec2(\n getW(d2, inputDepthNearestVec4, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC));\n value += dot(xValues, wValues);\n } else if (inputDepthVec4Remainder == 3) {\n ${s?"let xValues = vec3(\n getX(batch, xF, xR, xC, inputDepthNearestVec4),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2));\n ":"let xValues = vec3(\n getX(batch, inputDepthNearestVec4, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC));\n "}\n let wValues = vec3(\n getW(d2, inputDepthNearestVec4, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC));\n value += dot(xValues, wValues);\n }\n }\n }\n }\n ${c?"value = value + getBiasByOutputCoords(coords)":""};\n ${g}\n result[global_idx] = f32(value);\n }`}}}})),ku=j((()=>{Zl(),au(),su(),wu(),Zi=(e,t,n,r)=>{let i=e.length>2,a=i?"value += b[output_channel];":"",s=e[0].dims,o=e[1].dims,l="NHWC"===t.format,u=l?n[3]:n[1],d=u/t.group,c=l&&d>=4?zt(u):1,p=Tt.size(n)/c,h=[{type:12,data:p},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:d}];$i(t,h),h.push(...It(s,[o[0],o[1],o[2],o[3]/c]));let m=i?["rank","rank","rank"]:["rank","rank"];h.push(...It([n[0],n[1],n[2],n[3]/c]));return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${c}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:r?r(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:r=>{let u=Vt("output",e[0].dataType,n.length,c),d=Ft(u.type.tensor),p=ki(t,u.type.value,d),h=Rt("x",e[0].dataType,s.length),m=Rt("w",e[1].dataType,o.length,c),f=[h,m];i&&f.push(Rt("b",e[2].dataType,e[2].dims,c));let g=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];Ci(t,g);let _=l?`\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) {\n continue;\n }\n\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) {\n let input_channel = in_channel_offset + wInChannel;\n let xVal = ${h.get("batch","xHeight","xWidth","input_channel")};\n let wVal = ${m.get("wHeight","wWidth","wInChannel","output_channel")};\n value += xVal * wVal;\n }\n }\n }\n `:`\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {\n let input_channel = in_channel_offset + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) {\n continue;\n }\n\n let xVal = ${h.get("batch","input_channel","xHeight","xWidth")};\n let wVal = ${m.get("output_channel","wInChannel","wHeight","wWidth")};\n value += xVal * wVal;\n }\n }\n }\n `;return`\n ${r.registerUniforms(g).declareVariables(...f,u)}\n\n ${r.mainStart()}\n ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let outputIndices = ${u.offsetToIndices("global_idx")};\n let batch: u32 = outputIndices[0];\n let output_channel: u32 = outputIndices[${l?3:1}];\n let xRCCorner: vec2 = vec2(outputIndices[${l?1:2}], outputIndices[${l?2:3}]) * uniforms.strides - uniforms.pads;\n let group_id: u32 = output_channel * ${c} / uniforms.output_channels_per_group;\n var in_channel_offset = group_id * uniforms.w_shape[${l?2:1}];\n\n var value: ${u.type.value} = ${u.type.value}(0);\n ${_}\n ${a}\n ${p}\n ${u.setByOffset("global_idx","value")}\n }`}}},Ji=(e,t,n,r)=>{let i=e.length>2,a=zt(n[3]),s=zt(n[2]),o=Tt.size(n)/a/s,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],u=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],d=[n[0],n[1],n[2],n[3]/a],c=[{type:12,data:o},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];$i(t,c),c.push(...It(l,u,d));let p=(s-1)*t.strides[1]+u[1];return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${a};${s};${p};${u[0]};${u[1]}`,inputDependencies:i?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r?r(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:c}),getShaderSource:n=>{let r=Vt("output",e[0].dataType,d.length,a),o=Ft(r.type.tensor),c=ki(t,r.type.value,o),h=Rt("x",e[0].dataType,l.length,a),m=Rt("w",e[1].dataType,u.length,a),f=[h,m];i&&f.push(Rt("b",e[2].dataType,e[2].dims,a));let g=i?"value += b[output_channel];":"",_=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Ci(t,_),`\n ${n.registerUniforms(_).declareVariables(...f,r)}\n ${n.mainStart()}\n ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let width0 = uniforms.output_shape[3];\n let output_channel = global_idx % width0;\n var index1 = global_idx / width0;\n let width1 = uniforms.output_shape[2] / ${s}u;\n let col = (index1 % width1) * ${s}u;\n index1 = index1 / width1;\n let row = index1 % uniforms.output_shape[1];\n let batch = index1 / uniforms.output_shape[1];\n\n let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads;\n\n var x_vals: array<${h.type.value}, ${p}>;\n var values: array<${r.type.value}, ${s}>;\n let input_channel = output_channel;\n // Use constant instead of uniform can give better performance for w's height/width.\n for (var w_height: u32 = 0u; w_height < ${u[0]}; w_height++) {\n let x_height = x_corner.x + i32(w_height);\n if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {\n for (var i = 0; i < ${p}; i++) {\n let x_width = x_corner.y + i;\n if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {\n x_vals[i] = ${h.get("batch","u32(x_height)","u32(x_width)","input_channel")};\n } else {\n x_vals[i] = ${h.type.value}(0);\n }\n }\n for (var w_width: u32 = 0u; w_width < ${u[1]}; w_width++) {\n let w_val = ${m.get("w_height","w_width","0","output_channel")};\n for (var i = 0u; i < ${s}u; i++) {\n values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);\n }\n }\n }\n }\n\n for (var i = 0u; i < ${s}u; i++) {\n var value = values[i];\n ${g}\n ${c}\n ${r.set("batch","row","col + i","output_channel","value")};\n }\n }`}}}})),$u=j((()=>{au(),Mu(),Tu(),vu(),ku(),wu(),xu(),ou(),ea=(e,t,n,r,i,a)=>{let s=e[0],o=e.slice(a?1:2,a?3:4),l=o.length,u=t[0],d=t.slice(2).map(((e,t)=>e+(e-1)*(n[t]-1))),c=o.map(((e,t)=>e+r[t]+r[t+l])).map(((e,t)=>Math.floor((e-d[t]+i[t])/i[t])));return c.splice(0,0,s),c.splice(a?3:1,0,u),c},ta=[2,3,1,0],na=(e,t)=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");if(e[0].dims["NHWC"===t.format?e[0].dims.length-1:1]!==e[1].dims[1]*t.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(3===e.length&&(1!==e[2].dims.length||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let n=e[0].dims.length-2;if(t.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(t.strides.length!==n)throw new Error(`strides should be ${n}D`);if(t.pads.length!==2*n)throw new Error(`pads should be ${2*n}D`);if(0!==t.kernelShape.length&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},ra=(e,t)=>{let n=e.kernelShape.slice();n.length{let t=Si(e),n=e.format;return{autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],format:n,dilations:e.dilations,group:e.group,kernelShape:e.kernel_shape,pads:e.pads,strides:e.strides,wIsConst:e.w_is_const(),...t,cacheKey:`${e.format};${t.activation};`}},aa=(e,t,n,r)=>{let i="NHWC"===n.format,a=ea(t[0].dims,t[1].dims,n.dilations,n.pads,n.strides,i);if(1!==n.group){let s=[t[0]];if(i){let r=e.kernelCustomData.wT??e.compute(Qt(t[1],ta),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=r),s.push(r)}else s.push(t[1]);return 3===t.length&&s.push(t[2]),void(!e.adapterInfo.isArchitecture("ampere")&&i&&t[1].dims[0]===n.group&&1===t[1].dims[1]&&1===n.dilations[0]&&1===n.dilations[1]?e.compute(Ji(s,n,a,r),{inputs:s}):e.compute(Zi(s,n,a,r),{inputs:s}))}let s=3===t.length,o=t[0].dims[i?1:2],l=t[0].dims[i?2:3],u=t[0].dims[i?3:1],d=t[1].dims[2],c=t[1].dims[3],p=a[i?1:2],h=a[i?2:3],m=a[i?3:1],f=i&&d===o&&c===l&&0===n.pads[0]&&0===n.pads[1];if(f||1===d&&1===c&&1===n.dilations[0]&&1===n.dilations[1]&&1===n.strides[0]&&1===n.strides[1]&&0===n.pads[0]&&0===n.pads[1]){let d,c,g,_=a[0],w=[];if(i){let r=e.kernelCustomData.wT??e.compute(Qt(t[1],ta),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];if(n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=r),f){let e=o*l*u;d=t[0].reshape([1,_,e]),c=r.reshape([1,e,m]),g=[1,_,m]}else d=t[0].reshape([_,o*l,u]),c=r.reshape([1,u,m]),g=[_,p*h,m];w.push(d),w.push(c)}else d=t[0].reshape([_,u,o*l]),c=t[1].reshape([1,m,u]),g=[_,m,p*h],w.push(c),w.push(d);s&&w.push(t[2]);let b=g[2],y=w[0].dims[w[0].dims.length-1];return void(b<8&&y<8?e.compute(Ii(w,n,a,g,i,r),{inputs:w}):e.compute(Vi(w,n,a,g,i,r),{inputs:w}))}let g=e.kernelCustomData.wT??e.compute(Qt(t[1],ta),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=g);let _=[t[0],g];s&&_.push(t[2]);let w=i?p*h:m,b=i?m:p*h,y=d*c*u;e.compute(qi(_,n,a,w,b,y,s,!0,r),{inputs:_})},sa=(e,t)=>{let n="NHWC"===t.format,r=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];3===e.inputs.length&&r.push(e.inputs[2]);let i=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),s=[1].concat(t.dilations),o=[1].concat(t.kernelShape),l=ra({...t,pads:i,strides:a,dilations:s,kernelShape:o},r);aa(e,r,l,(e=>n?[e[0],e[2],e[3]]:[e[0],e[1],e[3]]))},oa=(e,t,n)=>{let r="NHWC"===n.format?"channelsLast":"channelsFirst",i=ra(n,t),a="NOTSET"===n.autoPad?n.pads:n.autoPad,s=Qi(t[0].dims,t[1].dims,n.strides,n.dilations,a,!1,r);e.compute(Yi(t,i,s.outShape,[s.filterDepth,s.filterHeight,s.filterWidth],[s.padInfo.front,s.padInfo.top,s.padInfo.left],r))},la=(e,t)=>{if(na(e.inputs,t),3===e.inputs[0].dims.length)sa(e,t);else if(5===e.inputs[0].dims.length)oa(e,e.inputs,t);else{let n=ra(t,e.inputs);aa(e,e.inputs,n)}}})),Cu=j((()=>{Zl(),eu(),su(),wu(),bu(),yu(),vu(),ua=(e,t=!1,n,r,i=4)=>{let a=e?"\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n ":"\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n ",s=e?"row":"col",o=e?"col":"row",l=`\n let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"};\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${s} / outWidth;\n let outCol = ${s} % outWidth;\n\n let WRow = ${o} / (uniforms.filter_dims[1] * inChannels);\n let WCol = ${o} / inChannels % uniforms.filter_dims[1];\n let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]);\n let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]);\n if (xR < 0.0 || xR >= f32(${e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])"}) || fract(xR) > 0.0) {\n return ${r}(0.0);\n }\n if (xC < 0.0 || xC >= f32(${e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])"}) || fract(xC) > 0.0) {\n return ${r}(0.0);\n }\n let iXR = i32(xR);\n let iXC = i32(xC);\n let xCh = ${o} % inChannels;\n ${e?"\n let coord = vec4(batch, iXR, iXC, xCh);\n ":"\n let coord = vec4(batch, xCh, iXR, iXC);\n "}\n return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${i}];`,u=e?`\n let col = colIn * ${i};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${l}\n }\n return ${r}(0.0);`:`\n let col = colIn * ${i};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${l}\n }\n return ${r}(0.0);`,d=`\n let col = colIn * ${i};\n let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"};\n let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels);\n let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1];\n if (${e?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) {\n let rowInner = row % inChannels;\n let coord = vec4(coordX, coordY, col, rowInner);\n ${(e=>{switch(e){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return`\n let coord1 = vec4(coordX, coordY, col + 1, rowInner);\n let coord2 = vec4(coordX, coordY, col + 2, rowInner);\n let coord3 = vec4(coordX, coordY, col + 3, rowInner);\n let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];\n let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))];\n let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))];\n let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))];\n return ${r}(v0, v1, v2, v3);\n `;default:throw new Error(`innerElementSize ${e} is not supported.`)}})(i)}\n }\n return ${r}(0.0);\n `,c=ki(n,r);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${r} {\n ${e?u:d}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${r} {\n ${e?d:u}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${r}) {\n let col = colIn * ${i};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueInput;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${a}\n ${Ei(t)}\n ${c}\n result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${i}] = value;\n }\n }`},da=(e,t,n,r,i,a,s,o)=>{let l="NHWC"===t.format,u=l?e[0].dims[3]:e[0].dims[1],d=n[0],c=l?n[2]:n[3],p=l?n[1]:n[2],h=l?n[3]:n[1],m=l&&u%4==0&&u%3&&h%4==0,f=l?h:c*p,g=l?c*p:h,_=[8,8,1],w=r<=8?[4,1,1]:[4,4,1],b=[Math.ceil(f/_[0]/w[0]),Math.ceil(g/_[1]/w[1]),Math.ceil(d/_[2]/w[2])];ut("verbose",(()=>`[conv_backprop_mm_webgpu] dispatch = ${b}`));let y=m?4:1,x=Math.max(_[0]*y,_[1]),v=m?4:1,M=[t.kernelShape[l?1:2],t.kernelShape[l?2:3]],T=[M[0]+(t.dilations[0]<=1?0:(M[0]-1)*(t.dilations[0]-1)),M[1]+(t.dilations[1]<=1?0:(M[1]-1)*(t.dilations[1]-1))],k=[T[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),T[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],$=[{type:6,data:r},{type:6,data:i},{type:6,data:a},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:M},{type:6,data:k}];$i(t,$),$.push(...It(e[0].dims,e[1].dims));let C=["rank","rank"];s&&($.push(...It(e[2].dims)),C.push("rank")),$.push(...It(n));return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${w};${_};${m}`,inputDependencies:C},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:b[0],y:b[1],z:b[2]},programUniforms:$}),getShaderSource:r=>{let i=Rt("x",e[0].dataType,e[0].dims.length,v),a=Rt("w",e[1].dataType,e[1].dims.length,1),u=Vt("result",e[0].dataType,n.length,v),d=[i,a],c="";if(s){let t=Rt("bias",e[2].dataType,e[2].dims.length,v);d.push(t),c+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${t.type.value} {\n return bias[coords.${l?"w":"y"}${m?"/ 4":""}];\n }`}let p=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:M.length},{name:"pads",type:"i32",length:k.length}];Ci(t,p);let h=Ft(e[0].dataType,1);if("f16"!==h&&"f32"!==h)throw new Error(`elemType ${h} is not supported.`);return`\n ${Fi("uniforms.result_strides")}\n ${r.registerUniforms(p).declareVariables(...d,u)};\n ${c}\n ${ua(l,s,t,i.type.value,y)}\n ${m?Bi(w,_,h,void 0,!l,x):Di(w,_,h,void 0,!l,x,!1,void 0,o)}`}}}})),Su=j((()=>{Zl(),eu(),au(),su(),ca=(e,t,n,r,i,a=!1,s,o,l=!1)=>{let u=l?1:2,d=l?2:3,c=l?3:1,p=a?2:1,h=`\n fn setOutputAtIndex(flatIndex : u32, value : ${a?`vec4<${s}>`:s}) {\n result[flatIndex] = ${a?`vec4<${s}>`:s}(value);\n }`;r&&(h+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${a?`vec4<${s}>`:s} {\n return bias[coords.${l?"w":"y"}${a?"/ 4":""}];\n }`);let m=a?4:1,f=Rt("W",t[1].dataType,t[1].dims.length,m),g=Rt("Dy",t[0].dataType,t[0].dims.length,m),_=[g,f];r&&_.push(Rt("bias",t[2].dataType,[n[c]].length,m));let w=Vt("result",t[0].dataType,n.length,m),b=`{\n let batch: u32 = ${i?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1];\n let r = ${i?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1];\n let c = ${i?"global_id.y":"workgroup_id.y"} * ${p};\n let d1: u32 = ${i?"global_id.x":"workgroup_id.x"} * 4;\n\n let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads);\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 var dotProd: array, ${p}>;\n for (var i = 0; i < ${p}; i++) {\n dotProd[i] = vec4<${s}>(0.0);\n }\n for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) {\n var dyR = (${s}(dyCorner.x) + ${s}(wR)) / ${s}(uniforms.strides.x);\n let wRPerm = uniforms.filter_dims[0] - 1 - wR;\n if (dyR < 0.0 || dyR >= ${s}(uniforms.Dy_shape[1]) ||\n fract(dyR) > 0.0 || wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) {\n let dyC = (${s}(dyCorner.y) + ${s}(wC)) / ${s}(uniforms.strides.y);\n let dyC2 = (${s}(dyCorner.y) + 1.0 + ${s}(wC)) / ${s}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims[1] - 1 - wC;\n if (wCPerm < 0) {\n continue;\n }\n var bDyCVal = true;\n var bDyCVal2 = true;\n if (dyC < 0.0 || dyC >= ${s}(uniforms.Dy_shape[2]) ||\n fract(dyC) > 0.0) {\n bDyCVal = false;\n }\n if (dyC2 < 0.0 || dyC2 >= ${s}(uniforms.Dy_shape[2]) ||\n fract(dyC2) > 0.0) {\n bDyCVal2 = false;\n }\n\n let idyC: u32 = u32(dyC);\n let idyC2: u32 = u32(dyC2);\n if (bDyCVal && bDyCVal2) {\n let d2Length = uniforms.Dy_shape[3];\n for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${f.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${f.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${f.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${f.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${g.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${s}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n\n xValue = ${g.get("batch","idyR","idyC2","d2")};\n\n dotProd[1] = dotProd[1] + vec4<${s}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n }\n } else if (bDyCVal) {\n let d2Length = uniforms.Dy_shape[${c}];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${f.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${f.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${f.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${f.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${g.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${s}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n }\n } else if (bDyCVal2) {\n let d2Length = uniforms.Dy_shape[3];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${f.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${f.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${f.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${f.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${g.get("batch","idyR","idyC2","d2")};\n let tmpval = vec4<${s}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[1] = dotProd[1] + tmpval;\n }\n }\n }\n }\n\n for (var i: u32 = 0; i < ${p}; i = i + 1) {\n let value = dotProd[i] + ${r?"bias[c+i]":`vec4<${s}>(0.0)`};\n ${w.set("batch","r","c + i","d1","value")};\n }\n }`,y=`\n let outputIndices = ${w.offsetToIndices("global_idx")};\n let batch = ${w.indicesGet("outputIndices",0)};\n let d1 = ${w.indicesGet("outputIndices",c)};\n let r = ${w.indicesGet("outputIndices",u)};\n let c = ${w.indicesGet("outputIndices",d)};\n let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads;\n let dyRCorner = dyCorner.x;\n let dyCCorner = dyCorner.y;\n let groupId = d1 / uniforms.output_channels_per_group;\n let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;\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 var dotProd = ${s}(0.0);\n for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {\n if (wR % uniforms.dilations.x != 0) {\n continue;\n }\n let dyR = (${s}(dyRCorner) + ${s}(wR)) / ${s}(uniforms.strides[0]);\n let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;\n if (dyR < 0.0 || dyR >= ${s}(uniforms.Dy_shape[${u}]) || fract(dyR) > 0.0 ||\n wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {\n if (wC % uniforms.dilations.y != 0) {\n continue;\n }\n let dyC = (${s}(dyCCorner) + ${s}(wC)) / ${s}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;\n if (dyC < 0.0 || dyC >= ${s}(uniforms.Dy_shape[${d}]) ||\n fract(dyC) > 0.0 || wCPerm < 0) {\n continue;\n }\n let idyC: u32 = u32(dyC);\n var inputChannel = groupId * uniforms.input_channels_per_group;\n for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) {\n let xValue = ${l?g.get("batch","idyR","idyC","inputChannel"):g.get("batch","inputChannel","idyR","idyC")};\n let wValue = ${f.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")};\n dotProd = dotProd + xValue * wValue;\n inputChannel = inputChannel + 1;\n }\n }\n }\n let value = dotProd + ${r?"bias[d1]":`${s}(0.0)`};\n ${w.setByOffset("global_idx","value")};\n `;return`\n ${e.registerUniforms(o).declareVariables(..._,w)}\n ${h}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};\n ${a?b:y}}`},pa=(e,t,n)=>{let r=e.length>2,i=t.outputShape,a=Tt.size(i),s=[Math.ceil(a/64),1,1];ut("verbose",(()=>`[conv2d_backprop_webgpu] dispatch = ${s}`));let o="NHWC"===t.format,l=["rank","rank"],u=[t.strides[0],t.strides[1]],d=[t.kernelShape[o?1:2],t.kernelShape[o?2:3]],c=[t.dilations[0],t.dilations[1]],p=[d[0]+(t.dilations[0]<=1?0:(t.kernelShape[o?1:2]-1)*(t.dilations[0]-1)),d[1]+(t.dilations[1]<=1?0:(t.kernelShape[o?2:3]-1)*(t.dilations[1]-1))],h=[p[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),p[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],m=t.group,f=e[1].dims,g=f[0]/m,_=f[1],w=[{type:12,data:a},{type:12,data:u},{type:12,data:d},{type:12,data:c},{type:12,data:p},{type:6,data:h},{type:12,data:g},{type:12,data:_},...It(e[0].dims,e[1].dims)];r&&(w.push(...It(e[2].dims)),l.push("rank")),w.push(...It(i));let b=1===s[1]&&1===s[2];return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:l},getRunData:()=>({dispatchGroup:{x:s[0],y:s[1],z:s[2]},outputs:[{dims:n?n(i):i,dataType:e[0].dataType}],programUniforms:w}),getShaderSource:t=>{let n=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:u.length},{name:"filter_dims",type:"u32",length:d.length},{name:"dilations",type:"u32",length:d.length},{name:"effective_filter_dims",type:"u32",length:p.length},{name:"pads",type:"i32",length:h.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],a=Ft(e[0].dataType);return`${ca(t,e,i,r,b,false,a,n,o)}`}}}})),Pu=j((()=>{Cu(),Su(),wu(),ou(),ha=(e,t,n,r,i,a)=>(e-1)*t+n+(r-1)*i+1-a,ma=(e,t,n,r,i)=>{let a=Math.floor(e/2);"SAME_UPPER"===t?(n[r]=a,n[i]=e-a):"SAME_LOWER"===t&&(n[r]=e-a,n[i]=a)},fa=(e,t,n,r,i,a,s,o,l,u)=>{let d=e.length-2,c=0===u.length;l.length{let n=e.kernelShape.slice();if(0===e.kernelShape.length||0===e.kernelShape.reduce(((e,t)=>e*t),1)){n.length=0;for(let e=2;ee+t),0)){let e=t[0].dims.length-2;l=new Array(e).fill(1)}let u=e.strides.slice();if(0===u.reduce(((e,t)=>e+t),0)){let e=t[0].dims.length-2;u=new Array(e).fill(1)}fa(o,n,l,e.autoPad,e.group,i,u,r,s,a);let d=Object.assign({},e);return Object.assign(d,{kernelShape:n,pads:i,outputPadding:s,outputShape:a,dilations:l,strides:u}),d},_a=e=>{let t=Si(e),n=e.format,r=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,a=e.group,s=e.kernelShape,o=e.pads,l=e.strides,u=e.wIsConst();return{autoPad:r,format:n,dilations:i,group:a,kernelShape:s,outputPadding:e.outputPadding,outputShape:e.outputShape,pads:o,strides:l,wIsConst:u,...t,cacheKey:`${e.format};${t.activation};`}},wa=(e,t)=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==e[0].dims.length&&3!==e[0].dims.length)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");if(e[0].dims["NHWC"===t.format?e[0].dims.length-1:1]!==e[1].dims[0])throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let n=e[1].dims[1]*t.group;if(3===e.length&&(1!==e[2].dims.length||e[2].dims[0]!==n))throw new Error("invalid bias");let r=e[0].dims.length-2;if(t.dilations.reduce(((e,t)=>e+t),0)>0&&t.dilations.length!==r)throw new Error(`dilations should be ${r}D`);if(t.strides.reduce(((e,t)=>e+t),0)>0&&t.strides.length!==r)throw new Error(`strides should be ${r}D`);if(t.pads.reduce(((e,t)=>e+t),0)>0&&t.pads.length!==2*r)throw new Error(`pads should be ${2*r}D`);if(t.outputPadding.length!==r&&0!==t.outputPadding.length)throw new Error(`output_padding should be ${r}D`);if(t.kernelShape.reduce(((e,t)=>e+t),0)>0&&0!==t.kernelShape.length&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(0!==t.outputShape.length&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},ba=[2,3,1,0],ya=(e,t,n)=>{let r=ga(n,t),i="NHWC"===n.format,a=r.outputShape,s=a[i?3:1],o=t[0].dims[i?3:1];if(1!==r.group||1===s&&1===o)return void e.compute(pa(t,r));let l=a[i?1:2],u=a[i?2:3],d=i?l*u:s,c=i?s:l*u,p=t[1].dims[2]*t[1].dims[3]*o,h=e.kernelCustomData.wT??e.compute(Qt(t[1],ba),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=h);let m=[t[0],h],f=3===t.length;f&&(i||1!==t[2].dims.length?m.push(t[2]):m.push(t[2].reshape([t[2].dims[0],1,1]))),e.compute(da(m,r,a,d,c,p,f,!0),{inputs:m})},xa=(e,t)=>{let n="NHWC"===t.format,r=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];3===e.inputs.length&&r.push(e.inputs[2]);let i=t.kernelShape;(0===i.length||0===i[0])&&(i=[e.inputs[1].dims[2]]);let a=t.dilations;(0===a.length||0===a[0])&&(a=[1]);let s=t.strides;(0===s.length||0===s[0])&&(s=[1]);let o=t.pads;0===o.length&&(o=[0,0]),o=[0,o[0],0,o[1]],s=[1].concat(s),a=[1].concat(a),i=[1].concat(i);let l=ga({...t,pads:o,strides:s,dilations:a,kernelShape:i},r);e.compute(pa(r,l,(e=>n?[e[0],e[2],e[3]]:[e[0],e[1],e[3]])))},va=(e,t)=>{wa(e.inputs,t),3===e.inputs[0].dims.length?xa(e,t):ya(e,e.inputs,t)}})),Eu=j((()=>{Zl(),au(),iu(),su(),Ma=(e,t,n,r)=>{let i=Tt.size(t),a=t.length,s=Rt("input",e,a),o=Vt("output",e,a),l=6===n.dataType?n.getInt32Array()[0]:Number(n.getBigInt64Array()[0]),u=Tt.normalizeAxis(l,a);return{name:"CumSum",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:u},...It(t,t)]}),getShaderSource:e=>{let t=` i32(${s.indicesGet("inputIndices","uniforms.axis")}) `,n=Nt("uniforms.input_shape","uniforms.axis",a),i=r.reverse?t+(r.exclusive?" + 1":""):"0",l=r.reverse?n:t+(r.exclusive?"":" + 1");return`\n ${e.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(s,o)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var inputIndices = ${o.offsetToIndices("global_idx")};\n var sum = ${o.type.value}(0);\n let first : i32 = ${i};\n let last : i32 = ${l};\n for (var i : i32 = first; i < last; i++) {\n ${s.indicesSet("inputIndices","uniforms.axis","u32(i)")};\n sum = sum + ${s.getByIndices("inputIndices")};\n }\n ${o.setByOffset("global_idx","sum")};\n }`}}},Ta=(e,t)=>{let n=e.inputs[0].dims,r=e.inputs[0].dataType,i=e.inputs[1];e.compute(Ma(r,n,i,t),{inputs:[0]})},ka=e=>{let t=1===e.exclusive,n=1===e.reverse;return xt({exclusive:t,reverse:n})}})),Fu=j((()=>{Zl(),au(),iu(),su(),$a=e=>{if(!e||1!==e.length)throw new Error("DepthToSpace requires 1 input.");if(4!==e[0].dims.length)throw new Error("DepthToSpace requires 4D input.")},Ca=(e,t,n,r)=>{let i=[];i.push(`fn perm(i: ${r.type.indices}) -> ${n.type.indices} {\n var a: ${n.type.indices};`);for(let r=0;r{let n,r,i,a,s,o,l="NHWC"===t.format,u=t.blocksize,d="DCR"===t.mode;l?([n,r,i,a]=e.dims,s=d?[n,r,i,u,u,a/u**2]:[n,r,i,a/u**2,u,u],o=d?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([n,r,i,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],s=d?[n,u,u,a/u**2,r,i]:[n,a/u**2,u,u,r,i],o=d?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let c=e.reshape(s),p=c.dims.length,h=e.dataType,m=Rt("a",h,p),f=Vt("output",h,p);return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:e=>{let t=l?[n,r*u,i*u,a/u**2]:[n,a/u**2,r*u,i*u],s=Tt.size(t),d=c.dims,p=Tt.sortBasedOnPerm(d,o);return{outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:[{type:12,data:s},...It(d,p)]}},getShaderSource:e=>`\n ${e.registerUniform("output_size","u32").declareVariables(m,f)}\n\n ${Ca(o,p,m,f)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${f.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${f.setByOffset("global_idx",m.getByIndices("aIndices"))}\n }`}},Pa=(e,t)=>{$a(e.inputs),e.compute(Sa(e.inputs[0],t))},Ea=e=>xt({blocksize:e.blocksize,mode:e.mode,format:e.format})})),Au=j((()=>{Zl(),au(),iu(),su(),Ia="^"+(Aa="("+(Fa="[a-zA-Z]|\\.\\.\\.")+")+")+"$",za="^"+("("+Aa+",)*"+Aa)+"$",Oa=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let n=this.symbolToIndices.get(e);void 0===n?n=[t]:n.push(t),this.symbolToIndices.set(e,n)}},Ba=class{constructor(e,t){this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[n,r]=t.includes("->")?t.split("->",2):[t,""];if(!n.match(RegExp(za)))throw new Error("Invalid LHS term");if(n.split(",").forEach(((t,n)=>{let r=e[n].dims.slice();if(!t.match(RegExp(Ia)))throw new Error("Invalid LHS term");let i=this.processTerm(t,!0,r,n);this.lhs.push(i)})),""===r)r+=[...this.symbolToInfo.entries()].filter((([e,t])=>1===t.count||"..."===e)).map((([e])=>e)).join("");else if(!r.match(RegExp(Aa)))throw new Error("Invalid RHS");r.match(RegExp(Fa,"g"))?.forEach((e=>{if("..."===e)this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let t=this.symbolToInfo.get(e);if(void 0===t)throw new Error("Invalid RHS symbol");this.outputDims.push(t.dimValue)}})),this.rhs=this.processTerm(r,!1,this.outputDims)}addSymbol(e,t,n){let r=this.symbolToInfo.get(e);if(void 0!==r){if(r.dimValue!==t&&1!==r.count)throw new Error("Dimension mismatch");r.count++,r.inputIndices.push(n)}else r={count:1,dimValue:t,inputIndices:[n]};this.symbolToInfo.set(e,r)}processTerm(e,t,n,r=-1){let i=n.length,a=!1,s=[],o=0;if(!e.match(RegExp(Ia))&&!t&&""!==e)throw new Error("Invalid LHS term");let l=e.match(RegExp(Fa,"g")),u=new Oa(r);return l?.forEach(((e,d)=>{if("..."===e){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let e=i-l.length+1;if(e<0)throw new Error("Ellipsis out of bounds");if(s=n.slice(o,o+e),this.hasEllipsis){if(this.ellipsisDims.length!==s.length||this.ellipsisDims.toString()!==s.toString())throw new Error("Ellipsis dimensions mismatch")}else{if(!t)throw new Error("Ellipsis must be specified in the LHS");this.hasEllipsis=!0,this.ellipsisDims=s}for(let e=0;ee+"_max",Na=(e,t,n,r)=>{let i=e.map((e=>e.length)).map(((e,n)=>Rt(`input${n}`,t,e))),a=Tt.size(r),s=Vt("output",t,r.length),o=[...n.symbolToInfo.keys()].filter((e=>!n.rhs.symbolToIndices.has(e)));return{name:"Einsum",shaderCache:{hint:n.equation,inputDependencies:e.map((()=>"rank"))},getRunData:()=>{let i=o.filter((e=>n.symbolToInfo.has(e))).map((e=>({type:12,data:n.symbolToInfo.get(e)?.dimValue||0})));i.push({type:12,data:a});let s=e.map(((e,t)=>[...It(e)])).reduce(((e,t)=>e.concat(t)),i);return s.push(...It(r)),{outputs:[{dims:r,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:s}},getShaderSource:e=>{let t=[],r=[],a=[],l=[],u=[],d=n.symbolToInfo.size===n.rhs.symbolToIndices.size;n.symbolToInfo.forEach(((e,o)=>{if(n.rhs.symbolToIndices.has(o)){let r=n.rhs.symbolToIndices.get(o)?.[0];void 0!==r&&n.lhs.forEach(((n,a)=>{if(e.inputIndices.includes(a)){let e=n.symbolToIndices.get(o);if(void 0===e)throw new Error("Invalid symbol error");e.forEach((e=>{t.push(`${i[a].indicesSet(`input${a}Indices`,e,s.indicesGet("outputIndices",r))}`)}))}}))}else n.lhs.forEach(((t,n)=>{if(e.inputIndices.includes(n)){let e=t.symbolToIndices.get(o);if(void 0===e)throw new Error("Invalid symbol error");e.forEach((e=>{r.push(`${i[n].indicesSet(`input${n}Indices`,e,`${o}`)}`)})),u.push(`prod *= ${i[n].getByIndices(`input${n}Indices`)};`)}})),a.push(`for(var ${o}: u32 = 0; ${o} < uniforms.${La(o)}; ${o}++) {`),l.push("}")}));let c=d?[...t,`let sum = ${i.map(((e,t)=>e.getByIndices(`input${t}Indices`))).join(" * ")};`]:[...t,"var sum = 0.0;",...a,...r,"var prod = 1.0;",...u,"sum += prod;",...l];return`\n ${e.registerUniforms(o.map((e=>({name:`${La(e)}`,type:"u32"})))).registerUniform("outputSize","u32").declareVariables(...i,s)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${s.offsetToIndices("global_idx")};\n ${i.map(((e,t)=>`var input${t}Indices: ${i[t].type.indices};`)).join("\n")}\n ${c.join("\n")};\n ${s.setByOffset("global_idx","sum")};\n }`}}},Da=(e,t)=>{let n=new Ba(e.inputs,t.equation),r=n.outputDims,i=e.inputs.map(((e,t)=>e.dims));e.compute(Na(i,e.inputs[0].dataType,n,r))},Ra=e=>{let t=e.equation.replace(/\s+/g,"");return xt({equation:t})}})),Iu=j((()=>{Zl(),au(),su(),Va=e=>{if(!e||2!==e.length)throw new Error("Expand requires 2 input.");let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),r=n.length{let n=e.length-t.length,r=[];for(let t=0;te.length>t.length?ja(e,t):ja(t,e),Ga=e=>{let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),r=qa(t,n),i=e[0].dataType,a=9===i?4:1,s=Math.ceil(Tt.size(r)/a),o=[{type:12,data:s},...It(t,r)];return{name:"Expand",shaderCache:{hint:`${r.length}`,inputDependencies:["rank"]},getShaderSource:e=>{let n,s=Rt("input",i,t.length,a),o=Vt("output",i,r.length,a);if(9===i){let e=(e,t,n="")=>`\n let outputIndices${t} = ${o.offsetToIndices(`outputOffset + ${t}u`)};\n let offset${t} = ${s.broadcastedIndicesToOffset(`outputIndices${t}`,o)};\n let index${t} = offset${t} / 4u;\n let component${t} = offset${t} % 4u;\n ${e}[${t}] = ${n}(${s.getByOffset(`index${t}`)}[component${t}]);\n `;n=`\n let outputOffset = global_idx * ${a};\n var data = vec4(0);\n ${e("data",0,"u32")}\n ${e("data",1,"u32")}\n ${e("data",2,"u32")}\n ${e("data",3,"u32")}\n ${o.setByOffset("global_idx","data")}\n }`}else n=`\n let outputIndices = ${o.offsetToIndices("global_idx")};\n let inputOffset = ${s.broadcastedIndicesToOffset("outputIndices",o)};\n ${o.setByOffset("global_idx",s.getByOffset("inputOffset"))}\n }`;return`\n ${e.registerUniform("vec_size","u32").declareVariables(s,o)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${n}`},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:o})}},Wa=e=>{Va(e.inputs),e.compute(Ga(e.inputs),{inputs:[0]})}})),zu=j((()=>{Zl(),au(),su(),mu(),Ua=e=>{let t=e[0].dataType,n=Tt.size(e[0].dims),r=Tt.size(e[1].dims),i=r%4==0;return{name:"FastGeluWithBias",shaderCache:{hint:`${i}`,inputDependencies:["type","type"]},getShaderSource:e=>{let n=Rt("x",t,[1],4),r=Rt("bias",t,[1],4),a=Vt("y",t,[1],4),s=e=>`\n let bias${e}_offset: u32 = (global_idx * 4 + ${e}) % uniforms.bias_size;\n let bias${e} = ${r.getByOffset(`bias${e}_offset / 4`)}[bias${e}_offset % 4];`,o=i?`\n let bias = ${r.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${s(0)}${s(1)}${s(2)}${s(3)}\n let bias = ${n.type.value}(bias0, bias1, bias2, bias3);`;return`${e.registerUniforms([{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}]).declareVariables(n,r,a)}\n\n ${Kr(At(t))}\n\n ${e.mainStart(Pt)}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}\n\n let x = ${n.getByOffset("global_idx")};\n ${o}\n let x_in = x + bias;\n ${a.setByOffset("global_idx",Qr("x_in"))}\n }`},getRunData:e=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],programUniforms:[{type:12,data:Math.ceil(n/4)},{type:12,data:r}],dispatchGroup:{x:Math.ceil(n/Pt/4)}})}},Ha=e=>{e.inputs.length<2||0===Tt.size(e.inputs[1].dims)?Yr(e):e.compute(Ua(e.inputs))}})),Ou=j((()=>{Zl(),au(),iu(),su(),Xa=e=>{if(!e||2!==e.length)throw new Error("Gather requires 2 inputs.")},Ka=(e,t)=>{let n=e[0].dims,r=e[1].dims,i=n.length,a=Tt.normalizeAxis(t.axis,i),s=n.slice(0);s.splice(a,1,...r);let o=n[a],l=9===e[0].dataType?4:1,u=Math.ceil(Tt.size(s)/l),d=[{type:12,data:u},{type:6,data:o},{type:12,data:a},...It(e[0].dims,e[1].dims,s)];return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:d}),getShaderSource:t=>{let n,o=Rt("data",e[0].dataType,e[0].dims.length,l),u=Rt("inputIndices",e[1].dataType,e[1].dims.length),d=Vt("output",e[0].dataType,s.length,l),c=e=>{let t=r.length,n=`var indicesIndices${e} = ${u.type.indices}(0);`;for(let r=0;r1?`indicesIndices${e}[${r}]`:`indicesIndices${e}`} = ${s.length>1?`outputIndices${e}[uniforms.axis + ${r}]`:`outputIndices${e}`};`;n+=`\n var idx${e} = ${u.getByIndices(`indicesIndices${e}`)};\n if (idx${e} < 0) {\n idx${e} = idx${e} + uniforms.axisDimLimit;\n }\n var dataIndices${e} : ${o.type.indices};\n `;for(let r=0,o=0;r1?`dataIndices${e}[${r}]`:`dataIndices${e}`} = u32(idx${e});`,o+=t):(n+=`${i>1?`dataIndices${e}[${r}]`:`dataIndices${e}`} = ${s.length>1?`outputIndices${e}[${o}]`:`outputIndices${e}`};`,o++);return n};if(9===e[0].dataType){let e=(e,t,n="")=>`\n let outputIndices${t} = ${d.offsetToIndices(`outputOffset + ${t}u`)};\n ${c(t)};\n let offset${t} = ${o.indicesToOffset(`dataIndices${t}`)};\n let index${t} = offset${t} / 4u;\n let component${t} = offset${t} % 4u;\n ${e}[${t}] = ${n}(${o.getByOffset(`index${t}`)}[component${t}]);\n `;n=`\n let outputOffset = global_idx * ${l};\n var value = vec4(0);\n ${e("value",0,"u32")}\n ${e("value",1,"u32")}\n ${e("value",2,"u32")}\n ${e("value",3,"u32")}\n ${d.setByOffset("global_idx","value")}\n `}else n=`\n let outputIndices = ${d.offsetToIndices("global_idx")};\n ${c("")};\n let value = ${o.getByIndices("dataIndices")};\n ${d.setByOffset("global_idx","value")};\n `;return`\n ${t.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(o,u,d)}\n ${t.mainStart()}\n ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n ${n}\n }`}}},Qa=e=>xt({axis:e.axis}),Ya=(e,t)=>{let n=e.inputs;Xa(n),e.compute(Ka(e.inputs,t))}})),Bu=j((()=>{Zl(),au(),iu(),su(),Za=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let n=Tt.normalizeAxis(t.quantizeAxis,e[0].dims.length),r=t.blockSize,i=e[0],a=e[2],s=4===e.length?e[3]:void 0;if(a.dims.length!==i.dims.length||!i.dims.map(((e,t)=>t===n?Math.ceil(e/r)===a.dims[t]:e===a.dims[t])).reduce(((e,t)=>e&&t),!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(s){if(s.dataType!==i.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(s.dims.length!==a.dims.length||!s.dims.map(((e,t)=>e===a.dims[t])).reduce(((e,t)=>e&&t),!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Ja=(e,t)=>{let n=e[0].dims,r=e[1].dims,i=n.length,a=Tt.normalizeAxis(t.gatherAxis,i),s=Tt.normalizeAxis(t.quantizeAxis,i),o=n.slice(0);o.splice(a,1,...r);let l=Tt.size(o),u=e[2].dataType,d=22===e[0].dataType,c=[{type:12,data:l},{type:12,data:s},{type:12,data:a},{type:12,data:t.blockSize},...It(...e.map(((e,t)=>e.dims)),o)];return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter(((e,t)=>1!==t)).map((e=>e.dims.join("_"))).join(";")}`,inputDependencies:Array.from({length:e.length},((e,t)=>"rank"))},getRunData:()=>({outputs:[{dims:o,dataType:u}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c}),getShaderSource:t=>{let i=Rt("data",e[0].dataType,e[0].dims.length),s=Rt("inputIndices",e[1].dataType,e[1].dims.length),l=Rt("scales",e[2].dataType,e[2].dims.length),c=e.length>3?Rt("zeroPoint",e[3].dataType,e[3].dims.length):void 0,p=Vt("output",u,o.length),h=[i,s,l];c&&h.push(c);return`\n ${t.registerUniforms([{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}]).declareVariables(...h,p)}\n ${t.mainStart()}\n let output_indices = ${p.offsetToIndices("global_idx")};\n var indices_indices = ${s.type.indices}(0);\n ${r.length>1?`\n for (var i: u32 = 0; i < ${r.length}; i++) {\n let index = ${p.indicesGet("output_indices","uniforms.gather_axis + i")};\n ${s.indicesSet("indices_indices","i","index")};\n }`:`indices_indices = ${p.indicesGet("output_indices","uniforms.gather_axis")};`};\n var data_indices = ${i.type.indices}(0);\n for (var i: u32 = 0; i < uniforms.gather_axis; i++) {\n let index = ${p.indicesGet("output_indices","i")};\n ${i.indicesSet("data_indices","i","index")};\n }\n var index_from_indices = ${s.getByIndices("indices_indices")};\n if (index_from_indices < 0) {\n index_from_indices += ${n[a]};\n }\n ${i.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")};\n for (var i = uniforms.gather_axis + 1; i < ${o.length}; i++) {\n let index = ${p.indicesGet("output_indices",`i + ${r.length} - 1`)};\n ${i.indicesSet("data_indices","i","index")};\n }\n let data_offset = ${i.indicesToOffset("data_indices")};\n let data_index = data_offset % 8;\n // Convert 4-bit packed data to 8-bit packed data.\n let packed_4bit_quantized_data = ${i.getByOffset("data_offset / 8")};\n let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f;\n let quantized_data_vec = ${d?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data));\n let quantized_data = quantized_data_vec[data_index / 2];\n var scale_indices = data_indices;\n let quantize_axis_index = ${l.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size;\n ${l.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")};\n var scale = ${l.getByIndices("scale_indices")};\n ${c?`\n let zero_point_indices = scale_indices;\n let zero_point_offset = ${c.indicesToOffset("zero_point_indices")};\n let zero_point_index = zero_point_offset % 8;\n let packed_4bit_zero_points = ${c.getByOffset("zero_point_offset / 8")};\n let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f;\n let zero_point_vec = ${d?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points));\n let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"};\n let dequantized_data = ${At(u)}(quantized_data - zero_point) * scale;\n ${p.setByOffset("global_idx","dequantized_data")};\n }`}}},es=(e,t)=>{let n=e.inputs;Za(n,t),e.compute(Ja(e.inputs,t))},ts=e=>xt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})})),Lu=j((()=>{Zl(),au(),iu(),su(),ns=e=>{if(!e||2!==e.length)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error("GatherElements requires that the data input and\n indices input tensors be of same rank.")},rs=(e,t)=>{let n=e[0].dims,r=e[0].dataType,i=n.length,a=e[1].dims,s=e[1].dataType,o=Tt.normalizeAxis(t.axis,i),l=n[o],u=a.slice(0),d=Tt.size(u),c=Rt("input",r,i),p=Rt("indicesInput",s,a.length),h=Vt("output",r,u.length),m=[{type:12,data:d},{type:6,data:l},{type:12,data:o}];return m.push(...It(n,a,u)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:m}),getShaderSource:e=>`\n ${e.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(c,p,h)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let outputIndices = ${h.offsetToIndices("global_idx")};\n\n var idx = ${p.getByOffset("global_idx")};\n if (idx < 0) {\n idx = idx + uniforms.axisDimLimit;\n }\n var inputIndices = ${c.type.indices}(outputIndices);\n ${c.indicesSet("inputIndices","uniforms.axis","u32(idx)")};\n let value = ${c.getByIndices("inputIndices")};\n\n ${h.setByOffset("global_idx","value")};\n }`}},is=e=>xt({axis:e.axis}),as=(e,t)=>{let n=e.inputs;ns(n),e.compute(rs(e.inputs,t))}})),Nu=j((()=>{Zl(),au(),su(),ss=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(3===e.length&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||3===e.length&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},os=(e,t)=>{let n=e[0].dims.slice(),r=e[1].dims.slice(),[i,a,s]=$t.getShapeOfGemmResult(n,t.transA,r,t.transB,3===e.length?e[2].dims:void 0),o=[i,a];if(!o)throw new Error("Can't use gemm on the given tensors");let l=16,u=Math.ceil(a/l),d=Math.ceil(i/l),c=(Tt.size(o),[{type:12,data:u},{type:12,data:i},{type:12,data:a},{type:12,data:s},{type:1,data:t.alpha},{type:1,data:t.beta}]),p=["type","type"];3===e.length&&(c.push(...It(e[2].dims)),p.push("rank")),c.push(...It(o));return{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:u*d},programUniforms:c}),getShaderSource:n=>{let r=Rt("a",e[0].dataType,e[0].dims),i=Rt("b",e[1].dataType,e[1].dims),a=null,s=[r,i];3===e.length&&(a=Rt("c",e[2].dataType,e[2].dims.length),s.push(a));let u=Vt("output",e[0].dataType,o.length);s.push(u);let d="",c="";t.transA&&t.transB?(c=`\n var col = tile_row_start + local_id.x;\n var row = k_start + local_id.y;\n if (col < uniforms.M && row < uniforms.K) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${r.type.value}(0);\n }\n\n col = k_start + local_id.x;\n row = tile_col_start + local_id.y;\n if (col < uniforms.K && row < uniforms.N) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${i.type.value}(0);\n }\n `,d="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(c=`\n var col = tile_row_start + local_id.x;\n var row = k_start + local_id.y;\n if (col < uniforms.M && row < uniforms.K) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${r.type.value}(0);\n }\n\n col = tile_col_start + local_id.x;\n row = k_start + local_id.y;\n if (col < uniforms.N && row < uniforms.K) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${i.type.value}(0);\n }\n `,d="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(c=`\n var col = k_start + local_id.x;\n var row = tile_row_start + local_id.y;\n if (col < uniforms.K && row < uniforms.M) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${r.type.value}(0);\n }\n\n col = k_start + local_id.x;\n row = tile_col_start + local_id.y;\n if (col < uniforms.K && row < uniforms.N) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${i.type.value}(0);\n }\n `,d="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(c=`\n var col = k_start + local_id.x;\n var row = tile_row_start + local_id.y;\n if (col < uniforms.K && row < uniforms.M) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${r.type.value}(0);\n }\n\n col = tile_col_start + local_id.x;\n row = k_start + local_id.y;\n if (col < uniforms.N && row < uniforms.K) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${i.type.value}(0);\n }\n `,d="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let p=1===t.alpha?"":"value *= uniforms.alpha;";return`\n ${n.registerUniforms([{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}]).declareVariables(...s)}\n var tile_a: array, 16>;\n var tile_b: array, 16>;\n ${n.mainStart([l,l,1])}\n let tile_col_start = (workgroup_index % uniforms.num_tile_n) * 16;\n let tile_row_start = (workgroup_index / uniforms.num_tile_n) * 16;\n let num_tiles = (uniforms.K - 1) / 16 + 1;\n var k_start = 0u;\n var value = ${u.type.value}(0);\n for (var t: u32 = 0u; t < num_tiles; t++) {\n ${c}\n k_start = k_start + 16;\n workgroupBarrier();\n\n for (var k: u32 = 0u; k < 16; k++) {\n ${d}\n }\n workgroupBarrier();\n }\n\n ${p}\n let m = tile_row_start + local_id.y;\n let n = tile_col_start + local_id.x;\n ${null!=a?`let cOffset = ${a.broadcastedIndicesToOffset("vec2(m, n)",u)}; value += ${u.type.value}(uniforms.beta) * ${a.getByOffset("cOffset")};`:""}\n if (m < uniforms.M && n < uniforms.N) {\n output[m * uniforms.N + n] = value;\n }\n }`}}},ls=e=>({transA:e.transA,transB:e.transB,alpha:e.alpha,beta:e.beta,cacheKey:`${e.transA};${e.transB};${1===e.alpha}`}),us=(e,t)=>{ss(e.inputs),e.compute(os(e.inputs,t))}})),Du=j((()=>{Zl(),au(),iu(),su(),[ds,cs,ps,hs]=[0,1,2,3],ms=e=>{if(4!==e[0].dims.length)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error("last dimension of grid must be equal to "+(e[0].dims.length-2));if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},fs=e=>`\n fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} {\n var v: vec4;\n var coeffs = gs_get_cubic_coeffs(x);\n for (var i = 0; i < 4; i++) {\n v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3];\n }\n coeffs = gs_get_cubic_coeffs(y);\n let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]);\n return pixel;\n }\n`,gs=e=>`\n fn gs_denormalize(n: f32, length: i32) -> f32 {\n ${0===e.alignCorners?"\n // alignCorners: false => [-1, 1] to [-0.5, length - 0.5]\n return ((n + 1.0) * f32(length) - 1.0) / 2.0;\n ":"\n // alignCorners: true => [-1, 1] to [0, length - 1]\n return (n + 1.0) / 2.0 * (f32(length - 1));\n "}\n }\n`,_s=e=>`\n ${"reflection"===e.paddingMode?"\n fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 {\n var dx = 0.0;\n var fx = f32(x);\n let range = x_max - x_min;\n if (fx < x_min) {\n dx = x_min - fx;\n let n = u32(dx / range);\n let r = dx - f32(n) * range;\n if (n % 2 == 0) {\n fx = x_min + r;\n } else {\n fx = x_max - r;\n }\n } else if (fx > x_max) {\n dx = fx - x_max;\n let n = u32(dx / range);\n let r = dx - f32(n) * range;\n if (n % 2 == 0) {\n fx = x_max - r;\n } else {\n fx = x_min + r;\n }\n }\n return u32(fx);\n }":""}\n`,ws=(e,t,n)=>`\n fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} {\n var pixel = ${t}(0);\n var indices = vec4(0);\n indices[${ds}] = batch;\n indices[${cs}] = channel;`+(()=>{switch(n.paddingMode){case"zeros":return`\n if (r >= 0 && r < H && c >=0 && c < W) {\n indices[${ps}] = u32(r);\n indices[${hs}] = u32(c);\n }\n `;case"border":return`\n indices[${ps}] = u32(clamp(r, 0, H - 1));\n indices[${hs}] = u32(clamp(c, 0, W - 1));\n `;case"reflection":return`\n indices[${ps}] = gs_reflect(r, border[1], border[3]);\n indices[${hs}] = gs_reflect(c, border[0], border[2]);\n `;default:throw new Error(`padding mode ${n.paddingMode} is not supported`)}})()+`\n return ${e.getByIndices("indices")};\n }\n`,bs=(e,t,n)=>(()=>{switch(n.mode){case"nearest":return`\n let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${ds}], indices[${cs}], border);\n `;case"bilinear":return`\n let x1 = i32(floor(x));\n let y1 = i32(floor(y));\n let x2 = x1 + 1;\n let y2 = y1 + 1;\n\n let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${ds}], indices[${cs}], border);\n let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${ds}], indices[${cs}], border);\n let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${ds}], indices[${cs}], border);\n let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${ds}], indices[${cs}], border);\n\n let dx2 = ${t}(f32(x2) - x);\n let dx1 = ${t}(x - f32(x1));\n let dy2 = ${t}(f32(y2) - y);\n let dy1 = ${t}(y - f32(y1));\n let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22);\n `;case"bicubic":return`\n let x0 = i32(floor(x)) - 1;\n let y0 = i32(floor(y)) - 1;\n var p: mat4x4<${t}>;\n for (var h = 0; h < 4; h++) {\n for (var w = 0; w < 4; w++) {\n p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${ds}], indices[${cs}], border);\n }\n }\n\n let dx = x - f32(x0 + 1);\n let dy = y - f32(y0 + 1);\n let result = gs_bicubic_interpolate(p, dx, dy);\n `;default:throw new Error(`mode ${n.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,ys=(e,t)=>{let n=Rt("x",e[0].dataType,e[0].dims.length),r=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],i=Rt("grid",e[1].dataType,r.length,2),a=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];"NHWC"===t.format&&(a=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[ds,cs,ps,hs]=[0,3,1,2]);let s=Vt("output",e[0].dataType,a.length),o=n.type.value,l=[{type:12,data:Tt.size(a)},...It(e[0].dims,r,a)];return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:e=>{let t=Tt.size(a);return{outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(t/64)},programUniforms:l}},getShaderSource:e=>`\n ${e.registerUniform("output_size","u32").declareVariables(n,i,s)}\n \n fn gs_get_cubic_coeffs(x: f32) -> vec4 {\n let cubic_alpha = -0.75f;\n let x_abs = abs(x);\n var coeffs: vec4;\n coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha);\n coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1);\n coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1);\n coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha);\n return coeffs;\n }\n\n ${fs(o)}\n ${gs(t)}\n ${_s(t)}\n ${ws(n,o,t)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let H_in = i32(uniforms.x_shape[${ps}]);\n let W_in = i32(uniforms.x_shape[${hs}]);\n\n ${0===t.alignCorners?"\n let x_min = -0.5;\n let x_max = f32(W_in) - 0.5;\n let y_min = -0.5;\n let y_max = f32(H_in) - 0.5;\n ":"\n let x_min = 0.0;\n let x_max = f32(W_in) - 1.0;\n let y_min = 0.0;\n let y_max = f32(H_in) - 1.0;\n "};\n let border = vec4(x_min, y_min, x_max, y_max);\n\n let indices = ${s.offsetToIndices("global_idx")};\n var grid_indices = vec3(indices[${ds}], indices[${ps}], indices[${hs}]);\n let nxy = ${i.getByIndices("grid_indices")};\n var x = gs_denormalize(f32(nxy[0]), W_in);\n var y = gs_denormalize(f32(nxy[1]), H_in);\n\n ${bs(s,o,t)}\n }`}},xs=(e,t)=>{ms(e.inputs),e.compute(ys(e.inputs,t))},vs=e=>xt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})})),Ru=j((()=>{Zl(),au(),iu(),nu(),cu(),su(),ou(),Ms=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,Ts=(e,t)=>{let n=e[0],r=Ms(e,1),i=Ms(e,2),a=Ms(e,3),s=Ms(e,4),o=Ms(e,5),l=Ms(e,6),u=Ms(e,7);if(3!==n.dims.length&&5!==n.dims.length)throw new Error("Input query is expected to have 3 or 5 dimensions");let d,c=n.dims[0],p=n.dims[1],h=3===n.dims.length?n.dims[2]:t.numHeads*n.dims[4],m=p,f=0,g=0,_=Math.floor(h/t.numHeads);if(l&&u&&Tt.size(l.dims)&&Tt.size(u.dims)){if(4!==l.dims.length)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims[0]!==c||l.dims[1]!==t.numHeads||l.dims[3]!==_)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(u.dims[0]!==c||u.dims[1]!==t.numHeads||u.dims[3]!==_)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==u.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(4!==u.dims.length)throw new Error('Input "past_value" is expected to have 4 dimensions');f=l.dims[2],g=l.dims[2]}else if(l&&Tt.size(l.dims)||u&&Tt.size(u.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');if(r&&Tt.size(r.dims)>0){if(3!==n.dims.length)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(r.dims.length<3||r.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(n.dims[0]!==r.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(3===r.dims.length){if(r.dims[2]!==n.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');d=2,m=r.dims[1]}else if(5===r.dims.length){if(r.dims[2]!==t.numHeads||2!==r.dims[3]||r.dims[4]!==_)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');d=5,m=r.dims[1]}else{if(r.dims[1]!==t.numHeads||r.dims[3]!==_)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');d=0,m=r.dims[2]}}else{if(5!==n.dims.length)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(n.dims[2]!==t.numHeads||3!==n.dims[3])throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');d=3}if(a&&Tt.size(a.dims)>0){if(1!==a.dims.length)throw new Error('Input "bias" is expected to have 1 dimension');if(r&&5===r.dims.length&&2===r.dims[3])throw new Error("bias is not allowed for packed kv.")}let w=f+m,b=0;if(s&&Tt.size(s.dims)>0){b=8;let e=s.dims;throw 1===e.length?e[0]===c?b=1:e[0]===3*c+2&&(b=3):2===e.length&&e[0]===c&&e[1]===w&&(b=5),8===b?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let y=!1,x=h;if(i&&Tt.size(i.dims)>0){if(3!==i.dims.length&&4!==i.dims.length)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(3===i.dims.length){if(m!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');x=i.dims[2]}else{if(m!==i.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');x=i.dims[1]*i.dims[3],y=!0}}if(s&&Tt.size(s.dims)>0)throw new Error("Key padding mask is not supported");if(o&&Tt.size(o.dims)>0){if(4!==o.dims.length)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(o.dims[0]!==c||o.dims[1]!==t.numHeads||o.dims[2]!==p||o.dims[3]!==w)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:c,sequenceLength:p,pastSequenceLength:f,kvSequenceLength:m,totalSequenceLength:w,maxSequenceLength:g,inputHiddenSize:0,hiddenSize:h,vHiddenSize:x,headSize:_,vHeadSize:Math.floor(x/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:b,scale:t.scale,broadcastResPosBias:!1,passPastInKv:y,qkvFormat:d}},ks=e=>xt({...e}),$s=xt({perm:[0,2,1,3]}),Cs=(e,t,n,r,i,a,s)=>{let o=[r,i,a],l=Tt.size(o),u=[{type:12,data:l},{type:12,data:s},{type:12,data:a}];return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:o,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:e=>{let r=Vt("qkv_with_bias",t.dataType,o),i=Rt("qkv",t.dataType,o),a=Rt("bias",n.dataType,o);return`\n ${e.registerUniforms([{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}]).declareVariables(i,a,r)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;\n\n qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];\n }`}},{inputs:[t,n],outputs:[-1]})[0]},Ss=(e,t,n,r,i,a,s,o)=>{let l=a;if(s&&Tt.size(s.dims)>0){if(1===r)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=Cs(e,a,s,t,r,n*i,o),l=l.reshape([t,r,n,i]),1===n||1===r?l:e.compute(Qt(l,$s.perm),{inputs:[l],outputs:[-1]})[0]}return 3===a.dims.length&&(l=a.reshape([t,r,n,i])),1===n||1===r?l:e.compute(Qt(l,$s.perm),{inputs:[l],outputs:[-1]})[0]},Ps=(e,t)=>{let n=Ts(e.inputs,t),r=e.inputs[0],i=Ms(e.inputs,1),a=Ms(e.inputs,2),s=Ms(e.inputs,3),o=Ms(e.inputs,4),l=Ms(e.inputs,5),u=Ms(e.inputs,6),d=Ms(e.inputs,7);if(5===r.dims.length)throw new Error("Packed QKV is not implemented");if(5===i?.dims.length)throw new Error("Packed KV is not implemented");let c=i&&a&&4===i.dims.length&&4===a.dims.length,p=Ss(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,r,s,0);if(c)return nr(e,p,i,a,o,void 0,u,d,l,n);if(!i||!a)throw new Error("key and value must be provided");let h=Ss(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.headSize,i,s,n.hiddenSize),m=Ss(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.vHeadSize,a,s,2*n.hiddenSize);nr(e,p,h,m,o,void 0,u,d,l,n)}})),Vu=j((()=>{Zl(),au(),iu(),su(),Es=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Fs=(e,t)=>{let n=[],r=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach((e=>n.push(Number(e)))),r=n.length),xt({numOutputs:r,axis:t.axis,splitSizes:n})},As=e=>`\nfn calculateOutputIndex(index: u32) -> u32 {\n for (var i: u32 = 0u; i < ${e}u; i += 1u ) {\n if (index < ${Nt("uniforms.size_in_split_axis","i",e)}) {\n return i;\n }\n }\n return ${e}u;\n}`,Is=e=>{let t=e.length,n=[];for(let r=0;r{let n=e[0].dims,r=Tt.size(n),i=e[0].dataType,a=Tt.normalizeAxis(t.axis,n.length),s=new Array(t.numOutputs),o=Rt("input",i,n.length),l=new Array(t.numOutputs),u=[],d=[],c=0,p=[{type:12,data:r}];for(let r=0;r`\n ${e.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(o,...s)}\n ${As(l.length)}\n ${Is(s)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}\n\n var indices = ${o.offsetToIndices("global_idx")};\n var index = ${o.indicesGet("indices",a)};\n let output_number = calculateOutputIndex(index);\n if (output_number != 0) {\n index -= ${Nt("uniforms.size_in_split_axis","output_number - 1u",l.length)};\n ${o.indicesSet("indices",a,"index")};\n }\n writeBufferData(output_number, indices, global_idx);\n }`,getRunData:()=>({outputs:u,dispatchGroup:{x:Math.ceil(r/64)},programUniforms:p})}},Os=(e,t)=>{Es(e.inputs);let n=1===e.inputs.length?t:Fs(e.inputs,t);e.compute(zs(e.inputs,n),{inputs:[0]})},Bs=e=>{let t=e.axis,n=e.splitSizes,r=e.numOutputs<0?n.length:e.numOutputs;if(r!==n.length)throw new Error("numOutputs and splitSizes lengh must be equal");return xt({axis:t,numOutputs:r,splitSizes:n})}})),ju=j((()=>{iu(),cu(),Ru(),Vu(),ou(),Ls=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let n=e[0],r=e[1],i=e[2],a=e[3],s=e[4];if(-1!==t.localWindowSize)throw new Error("Local attention is not supported");if(0!==t.softcap)throw new Error("Softcap is not supported");if(0!==t.rotaryInterleaved)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(3!==n.dims.length&&5!==n.dims.length)throw new Error("Input query is expected to have 3 or 5 dimensions");let o=n.dims[0],l=n.dims[1],u=3===n.dims.length?n.dims[2]:t.numHeads*n.dims[4],d=l,c=0,p=!r||0===r.dims.length,h=Math.floor(p?u/(t.numHeads+2*t.kvNumHeads):u/t.numHeads);p&&(u=h*t.numHeads);let m=a&&0!==a.dims.length,f=s&&0!==s.dims.length;if(m&&4===a.dims.length&&a.dims[0]===o&&a.dims[1]!==t.kvNumHeads&&a.dims[2]===t.kvNumHeads&&a.dims[3]===h)throw new Error("BSNH pastKey/pastValue is not supported");if(m&&f){if(4!==a.dims.length)throw new Error('Input "past_key" is expected to have 4 dimensions');if(4!==s.dims.length)throw new Error('Input "past_value" is expected to have 4 dimensions');c=a.dims[2]}else if(m||f)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let g=1;if(r&&r.dims.length>0){if(3!==n.dims.length)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(r.dims.length<3||r.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(n.dims[0]!==r.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(3===r.dims.length){if(n.dims[2]%r.dims[2]!=0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');d=r.dims[1]}else if(5===r.dims.length){if(r.dims[2]!==t.numHeads||2!==r.dims[3]||r.dims[4]!==h)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');d=r.dims[1]}else{if(r.dims[1]!==t.numHeads||r.dims[3]!==h)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');d=r.dims[2]}}else{if(3!==n.dims.length&&5!==n.dims.length)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(5===n.dims.length&&(n.dims[2]!==t.numHeads||3!==n.dims[3]))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');g=3}let _=!1,w=t.kvNumHeads?h*t.kvNumHeads:u;if(i&&i.dims.length>0){if(3!==i.dims.length&&4!==i.dims.length)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(3===i.dims.length){if(d!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');w=i.dims[2]}else{if(d!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');w=i.dims[1]*i.dims[3],_=!0}}let b=e.length>4?e[5]:void 0;if(b&&1!==b.dims.length&&b.dims[0]!==o)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:o,sequenceLength:l,pastSequenceLength:c,kvSequenceLength:d,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:u,vHiddenSize:w,headSize:h,vHeadSize:Math.floor(w/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:0,scale:t.scale,broadcastResPosBias:!1,passPastInKv:_,qkvFormat:g}},Ns=xt({perm:[0,2,1,3]}),Ds=(e,t,n)=>{let r=t,i=n.kvNumHeads;return 3===t.dims.length&&0!==n.kvSequenceLength&&(r=t.reshape([n.batchSize,n.kvSequenceLength,i,n.headSize]),r=e.compute(Qt(r,Ns.perm),{inputs:[r],outputs:[-1]})[0]),r},Rs=(e,t)=>{let n=Ls(e.inputs,t);if(5===e.inputs[0].dims.length)throw new Error("Packed QKV is not implemented");if(5===e.inputs[1]?.dims.length)throw new Error("Packed KV is not implemented");let r=e.inputs[0],i=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,a=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,s=e.inputs[3]&&0!==e.inputs[3].dims.length?e.inputs[3]:void 0,o=e.inputs[4]&&0!==e.inputs[4].dims.length?e.inputs[4]:void 0,l=e.inputs.length>4?e.inputs[5]:void 0,u=e.inputs.length>5?e.inputs[6]:void 0,d=n.kvNumHeads?n.kvNumHeads:n.numHeads,c=xt({axis:2,numOutputs:3,splitSizes:[n.numHeads*n.headSize,d*n.headSize,d*n.headSize]}),[p,h,m]=i||a?[r,i,a]:e.compute(zs([r],c),{inputs:[r],outputs:[-1,-1,-1]}),f=Ss(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,p,void 0,0);nr(e,f,Ds(e,h,n),Ds(e,m,n),void 0,void 0,s,o,void 0,n,l,u)}})),qu=j((()=>{Zl(),au(),ou(),su(),Vs=(e,t,n,r,i,a,s,o)=>{let l=zt(a),u=1===l?"f32":`vec${l}f`,d=1===l?"vec2f":`mat2x${l}f`,c=i*s,p=64;1===c&&(p=256);let h=[i,s,a/l],m=[i,s,2],f=[];f.push(...It(h,m));return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${o};${p}`,inputDependencies:["rank","type","type"]},getRunData:()=>({outputs:[{dims:m,dataType:1}],dispatchGroup:{x:c},programUniforms:f}),getShaderSource:e=>{let i=Rt("x",t.dataType,3,l),a=[i,Rt("scale",n.dataType,n.dims),Rt("bias",r.dataType,r.dims),Vt("output",1,3,2)];return`\n var workgroup_shared : array<${d}, ${p}>;\n const workgroup_size = ${p}u;\n ${e.declareVariables(...a)}\n ${e.mainStart(p)}\n let batch = workgroup_index / uniforms.x_shape[1];\n let channel = workgroup_index % uniforms.x_shape[1];\n let hight = uniforms.x_shape[2];\n // initialize workgroup memory\n var sum = ${u}(0);\n var squared_sum = ${u}(0);\n for (var h = local_idx; h < hight; h += workgroup_size) {\n let value = ${u}(${i.get("batch","channel","h")});\n sum += value;\n squared_sum += value * value;\n }\n workgroup_shared[local_idx] = ${d}(sum, squared_sum);\n workgroupBarrier();\n\n for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) {\n if (local_idx < currSize) {\n workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize];\n }\n workgroupBarrier();\n }\n if (local_idx == 0) {\n let sum_final = ${Lt("workgroup_shared[0][0]",l)} / f32(hight * ${l});\n let squared_sum_final = ${Lt("workgroup_shared[0][1]",l)} / f32(hight * ${l});\n\n let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${o}));\n let channel_scale = inv_std_dev * f32(scale[channel]);\n let channel_shift = f32(bias[channel]) - sum_final * channel_scale;\n output[workgroup_index] = vec2f(channel_scale, channel_shift);\n }\n }`}},{inputs:[t,n,r],outputs:[-1]})[0]},js=(e,t,n)=>{let r=t[0].dims,i=r,a=r[0],s=r[1],o=Tt.sizeFromDimension(r,2),l=zt(o),u=Tt.size(i)/l,d=Vs(e,t[0],t[1],t[2],a,o,s,n.epsilon),c=[a,s,o/l],p=[a,s];e.compute({name:"InstanceNormalization",shaderCache:{hint:`${l}`,inputDependencies:["type","none"]},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},...It(c,p,c)]}),getShaderSource:e=>{let n=Rt("x",t[0].dataType,c.length,l),r=Rt("scale_shift",1,p.length,2),i=Vt("output",t[0].dataType,c.length,l),a=[n,r,i];return`\n ${e.registerUniform("output_size","u32").declareVariables(...a)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let outputIndices = ${i.offsetToIndices("global_idx")};\n let batch = outputIndices[0];\n let channel = outputIndices[1];\n let scale_shift = ${r.getByIndices("vec2(batch, channel)")};\n let value = ${n.getByOffset("global_idx")} * ${i.type.value}(scale_shift.x) + ${i.type.value}(scale_shift.y);\n ${i.setByOffset("global_idx","value")};\n }`}},{inputs:[t[0],d]})},qs=(e,t,n)=>{let r=t[0].dims,i=r,a=r[0],s=r[r.length-1],o=Tt.sizeFromDimension(r,1)/s,l=zt(s),u=Tt.size(i)/l,d=[{type:12,data:o},{type:12,data:Math.floor(s/l)}],c=!1,p=[0,r.length-1];for(let e=0;er[p[t]]))),m=Vs(e,h,t[1],t[2],a,o,s,n.epsilon);e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:d}),getShaderSource:e=>{let n=Ft(t[0].dataType),r=1===l?"vec2f":`mat${l}x2f`,a=e=>{let t=0===e?"x":"y",r=1===l?"f32":`vec${l}f`;switch(l){case 1:return`${n}(${r}(scale.${t}))`;case 2:return`vec2<${n}>(${r}(scale[0].${t}, scale[1].${t}))`;case 4:return`vec4<${n}>(${r}(scale[0].${t}, scale[1].${t}, scale[2].${t}, scale[3].${t}))`;default:throw new Error(`Not supported compoents ${l}`)}},s=Rt("input",t[0].dataType,t[0].dims,l),o=Vt("output",t[0].dataType,i,l);return`\n @group(0) @binding(0) var input : array<${s.type.storage}>;\n @group(0) @binding(1) var scale_input : array<${r}>;\n @group(0) @binding(2) var output : array<${o.type.storage}>;\n struct Uniforms {H: u32, C : u32};\n @group(0) @binding(3) var uniforms: Uniforms;\n\n ${e.mainStart()}\n let current_image_number = global_idx / (uniforms.C * uniforms.H);\n let current_channel_number = global_idx % uniforms.C;\n\n let scale_offset = current_image_number * uniforms.C + current_channel_number;\n let scale = scale_input[scale_offset];\n output[global_idx] = fma(input[global_idx], ${a(0)}, ${a(1)});\n }`}},{inputs:[t[0],m]})},Gs=(e,t)=>{"NHWC"===t.format?qs(e,e.inputs,t):js(e,e.inputs,t)}})),Gu=j((()=>{Zl(),au(),su(),Ws=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Us=(e,t,n)=>{let r=t.simplified,i=e[0].dims,a=e[1],s=!r&&e[2],o=i,l=Tt.normalizeAxis(t.axis,i.length),u=Tt.sizeToDimension(i,l),d=Tt.sizeFromDimension(i,l),c=Tt.size(a.dims),p=s?Tt.size(s.dims):0;if(c!==d||s&&p!==d)throw new Error(`Size of X.shape()[axis:] == ${d}.\n Size of scale and bias (if provided) must match this.\n Got scale size of ${c} and bias size of ${p}`);let h=[];for(let e=0;e1,w=n>2,b=[{dims:o,dataType:e[0].dataType}];return _&&b.push({dims:h,dataType:1}),w&&b.push({dims:h,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${m};${n};${r}`,inputDependencies:f},getRunData:()=>({outputs:b,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:g}),getShaderSource:t=>{let n=Ft(e[0].dataType),i=[Rt("x",e[0].dataType,e[0].dims,m),Rt("scale",a.dataType,a.dims,m)];s&&i.push(Rt("bias",s.dataType,s.dims,m)),i.push(Vt("output",e[0].dataType,o,m)),_&&i.push(Vt("mean_data_output",1,h)),w&&i.push(Vt("inv_std_output",1,h));return`\n ${t.registerUniforms([{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}]).declareVariables(...i)}\n ${t.mainStart()}\n ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}\n let offset = global_idx * uniforms.norm_size_vectorized;\n var mean_vector = ${Ot("f32",m)};\n var mean_square_vector = ${Ot("f32",m)};\n\n for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {\n let value = ${Bt(n,m,"x[h + offset]")};\n mean_vector += value;\n mean_square_vector += value * value;\n }\n let mean = ${Lt("mean_vector",m)} / uniforms.norm_size;\n let inv_std_dev = inverseSqrt(${Lt("mean_square_vector",m)} / uniforms.norm_size ${r?"":"- mean * mean"} + uniforms.epsilon);\n\n for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {\n let f32input = ${Bt(n,m,"x[j + offset]")};\n let f32scale = ${Bt(n,m,"scale[j]")};\n output[j + offset] = ${i[0].type.value}((f32input ${r?"":"- mean"}) * inv_std_dev * f32scale\n ${s?`+ ${Bt(n,m,"bias[j]")}`:""}\n );\n }\n\n ${_?"mean_data_output[global_idx] = mean":""};\n ${w?"inv_std_output[global_idx] = inv_std_dev":""};\n }`}}},Hs=(e,t)=>{Ws(e.inputs),e.compute(Us(e.inputs,t,e.outputCount))}})),Wu=j((()=>{au(),xu(),vu(),Xs=e=>{if(!e||2!==e.length)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},Ks=e=>{Xs(e.inputs);let t=Mt.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let n=t[t.length-1],r=e.inputs[0].dims[e.inputs[0].dims.length-1];if(n<8&&r<8)e.compute(Ii(e.inputs,{activation:""},t));else{let i=t[t.length-2],a=Tt.size(e.inputs[0].dims.slice(0,-2)),s=Tt.size(e.inputs[1].dims.slice(0,-2));if(1!==a&&1===i&&1===s){let i=[1,a,n],s=[e.inputs[0].reshape([1,a,r]),e.inputs[1].reshape([1,r,n])];e.compute(Vi(s,{activation:""},t,i),{inputs:s})}else e.compute(Vi(e.inputs,{activation:""},t))}}})),Uu=j((()=>{Zl(),au(),iu(),su(),Qs=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let n=e[0],r=n.dims.length;if(n.dims[r-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let i=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,s=e[1];if(!Tt.areEqual(s.dims,[t.n,i,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let o=e[2].dims;if(Tt.size(o)!==t.n*i)throw new Error("scales input size error.");if(4===e.length){let n=e[3].dims,r=t.bits>4?t.n*i:t.n*Math.floor((i+1)/2);if(Tt.size(n)!==r)throw new Error("zeroPoints input size error.")}},Ys=(e,t)=>{let n=e[0].dims,r=n.length,i=n[r-2],a=t.k,s=t.n,o=n.slice(0,r-2),l=Tt.size(o),u=e[1].dims[2]/4,d=e[0].dataType,c=zt(t.k),p=zt(u),h=zt(s),m=o.concat([i,s]),f=i>1&&s/h%2==0?2:1,g=Tt.size(m)/h/f,_=64,w=[],b=[l,i,a/c],y=Tt.convertShape(e[1].dims).slice();y.splice(-1,1,u/p),w.push(...It(b)),w.push(...It(y)),w.push(...It(e[2].dims)),4===e.length&&w.push(...It(Tt.convertShape(e[3].dims)));let x=[l,i,s/h];w.push(...It(x));return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${c};${p};${h};${f};64`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:m,dataType:d}],dispatchGroup:{x:g},programUniforms:w}),getShaderSource:n=>{let r=b.length,i=Rt("a",e[0].dataType,r,c),a=Rt("b",12,y.length,p),s=Rt("scales",e[2].dataType,e[2].dims.length),o=[i,a,s],l=4===e.length?Rt("zero_points",12,e[3].dims.length):void 0;l&&o.push(l);let d=x.length,m=Vt("output",e[0].dataType,d,h),g=Ft(e[0].dataType),w=(()=>{switch(c){case 1:return`array<${g}, 8>`;case 2:return`mat4x2<${g}>`;case 4:return`mat2x4<${g}>`;default:throw new Error(`${c}-component is not supported.`)}})();return`\n var workgroup_shared: array<${m.type.value}, ${f*_}>;\n ${n.declareVariables(...o,m)}\n ${n.mainStart([_,1,1])}\n let output_indices = ${m.offsetToIndices(`(global_idx / 64) * ${f}`)};\n let col = output_indices[2];\n let row = output_indices[1];\n let batch = output_indices[0];\n let nBlocksPerCol = uniforms.b_shape[1];\n\n for (var block = local_id.x; block < nBlocksPerCol; block += 64) {\n //process one block\n var word_offset: u32 = block * ${t.blockSize/c};\n ${(()=>{let e=`\n var col_index = col * ${h};\n ${l?"\n let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2;\n var zero_point_byte_count: u32;\n var zero_point_word_index: u32;\n var zero_point_byte_offset: u32;\n let zero_point_nibble_offset: u32 = block & 0x1u;\n var zero_point_bits_offset: u32;\n var zero_point_word: u32;":`\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${g}(8);`}\n `;for(let t=0;t> 0x1u);\n zero_point_word_index = zero_point_byte_count >> 0x2u;\n zero_point_byte_offset = zero_point_byte_count & 0x3u;\n zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n zero_point_word = ${l.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;\n let zero_point${t} = ${g}((zero_point_word) & 0xFu);`:""}\n col_index += 1;`;return e})()}\n for (var word: u32 = 0; word < ${u}; word += ${p}) {\n ${(()=>{let e=`col_index = col * ${h};`;for(let t=0;t;\n var b_value_upper: vec4;\n var b_quantized_values: ${w};\n var b_dequantized_values: ${w};`,e})()}\n for (var i: u32 = 0; i < ${p}; i++) {\n ${(()=>{let e=`\n // reuse a data\n var input_offset = ${i.indicesToOffset(`${i.type.indices}(batch, row, word_offset)`)};\n var a_data: ${w};\n for (var j: u32 = 0; j < ${8/c}; j++) {\n a_data[j] = ${i.getByOffset("input_offset")};\n input_offset++;\n }\n `;for(let t=0;t> 4) & b_mask);\n b_quantized_values = ${w}(${Array.from({length:4},((e,t)=>`${g}(b_value_lower[${t}]), ${g}(b_value_upper[${t}])`)).join(", ")});\n b_dequantized_values = ${1===c?`${w}(${Array.from({length:8},((e,n)=>`(b_quantized_values[${n}] - ${l?`zero_point${t}`:"zero_point"}) * scale${t}`)).join(", ")});`:`(b_quantized_values - ${w}(${Array(8).fill(l?`zero_point${t}`:"zero_point").join(",")})) * scale${t};`};\n workgroup_shared[local_id.x * ${f} + ${Math.floor(t/h)}]${h>1?`[${t%h}]`:""} += ${Array.from({length:8/c},((e,t)=>""+(1===c?`a_data[${t}] * b_dequantized_values[${t}]`:`dot(a_data[${t}], b_dequantized_values[${t}])`))).join(" + ")};\n `;return e})()}\n word_offset += ${8/c};\n }\n }\n }\n workgroupBarrier();\n\n if (local_id.x < ${f}) {\n var output_value: ${m.type.value} = ${m.type.value}(0);\n var workgroup_shared_offset: u32 = local_id.x;\n for (var b: u32 = 0u; b < 64u; b++) {\n output_value += workgroup_shared[workgroup_shared_offset];\n workgroup_shared_offset += ${f};\n }\n ${m.setByIndices(`${m.type.indices}(batch, row, col + local_id.x)`,"output_value")};\n }\n }`}}},Zs=(e,t)=>{let n=e[0].dims,r=n.length,i=n[r-2],a=t.k,s=t.n,o=n.slice(0,r-2),l=Tt.size(o),u=e[1].dims[2]/4,d=e[0].dataType,c=zt(t.k),p=zt(u),h=o.concat([i,s]),m=s%8==0?8:s%4==0?4:1,f=128/m,g=f*p*8,_=g/c,w=g/t.blockSize,b=Tt.size(h)/m,y=[],x=[l,i,a/c],v=Tt.convertShape(e[1].dims).slice();v.splice(-1,1,u/p),y.push(...It(x)),y.push(...It(v)),y.push(...It(e[2].dims)),4===e.length&&y.push(...It(Tt.convertShape(e[3].dims)));let M=[l,i,s];y.push(...It(M));return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${c};${p};${f};${m}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:h,dataType:d}],dispatchGroup:{x:b},programUniforms:y}),getShaderSource:n=>{let r=x.length,i=Rt("a",e[0].dataType,r,c),a=Rt("b",12,v.length,p),s=Rt("scales",e[2].dataType,e[2].dims.length),o=[i,a,s],l=4===e.length?Rt("zero_points",12,e[3].dims.length):void 0;l&&o.push(l);let u=M.length,d=Vt("output",e[0].dataType,u),h=Ft(e[0].dataType);return`\n var sub_a: array<${i.type.value}, ${_}>;\n var inter_results: array, ${m}>;\n ${n.declareVariables(...o,d)}\n ${n.mainStart([f,m,1])}\n let output_indices = ${d.offsetToIndices(`workgroup_index * ${m}`)};\n let col = output_indices[2];\n let row = output_indices[1];\n let batch = output_indices[0];\n let n_blocks_per_col = uniforms.b_shape[1];\n let num_tiles = (n_blocks_per_col - 1) / ${w} + 1;\n\n // Loop over shared dimension.\n for (var tile: u32 = 0; tile < num_tiles; tile += 1) {\n let a_col_start = tile * ${_};\n // load one tile A data into shared memory.\n for (var a_offset = local_idx; a_offset < ${_}; a_offset += 128)\n {\n let a_col = a_col_start + a_offset;\n if (a_col < uniforms.a_shape[2])\n {\n sub_a[a_offset] = ${i.getByIndices(`${i.type.indices}(batch, row, a_col)`)};\n } else {\n sub_a[a_offset] = ${i.type.value}(0);\n }\n }\n workgroupBarrier();\n\n // each thread process one block\n let b_row = col + local_id.y;\n let block = tile * ${w} + local_id.x;\n ${l?`\n let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2;\n let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u);\n let zero_point_word_index = zero_point_byte_count >> 0x2u;\n let zero_point_byte_offset = zero_point_byte_count & 0x3u;\n let zero_point_nibble_offset: u32 = block & 0x1u;\n let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n let zero_point_word = ${l.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;\n let zero_point = ${h}((zero_point_word) & 0xFu);`:`\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${h}(8);`}\n let scale = ${s.getByOffset("b_row * n_blocks_per_col + block")};\n let b_data = ${a.getByIndices(`${a.type.indices}(b_row, block, 0)`)};\n var word_offset = local_id.x * ${t.blockSize/c};\n for (var i: u32 = 0; i < ${p}; i++) {\n ${(()=>{switch(c){case 1:return`\n let a_data0 = vec4<${h}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]);\n let a_data1 = vec4<${h}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return`\n let a_data0 = vec4<${h}>(sub_a[word_offset], sub_a[word_offset + 1]);\n let a_data1 = vec4<${h}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return"\n let a_data0 = sub_a[word_offset];\n let a_data1 = sub_a[word_offset + 1];";default:throw new Error(`${c}-component is not supported.`)}})()}\n let b_value = ${1===p?"b_data":"b_data[i]"};\n let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu);\n let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu);\n let b_quantized_values = mat2x4<${h}>(${Array.from({length:4},((e,t)=>`${h}(b_value_lower[${t}]), ${h}(b_value_upper[${t}])`)).join(", ")});\n let b_dequantized_values = (b_quantized_values - mat2x4<${h}>(${Array(8).fill("zero_point").join(",")})) * scale;\n inter_results[local_id.y][local_id.x] += ${Array.from({length:2},((e,t)=>`dot(a_data${t}, b_dequantized_values[${t}])`)).join(" + ")};\n word_offset += ${8/c};\n }\n workgroupBarrier();\n }\n\n if (local_idx < ${m}) {\n var output_value: ${d.type.value} = ${d.type.value}(0);\n for (var b = 0u; b < ${f}; b++) {\n output_value += inter_results[local_idx][b];\n }\n if (col + local_idx < uniforms.output_shape[2])\n {\n ${d.setByIndices(`${d.type.indices}(batch, row, col + local_idx)`,"output_value")}\n }\n }\n }`}}},Js=(e,t)=>{Qs(e.inputs,t),32===t.blockSize&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(Zs(e.inputs,t)):e.compute(Ys(e.inputs,t))},eo=e=>xt(e)})),Hu=j((()=>{Zl(),au(),su(),to=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(1!==e[0].dataType&&10!==e[0].dataType)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=2*e[0].dims.length===e[1].dims[0];if(4===e.length&&(t=2*e[3].dims[0]===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},no=(e,t,n)=>{let r="";for(let i=t-1;i>=0;--i)r+=`\n k = i32(${e.indicesGet("indices",i)}) - ${Nt("uniforms.pads",i,n)};\n if (k < 0) {\n break;\n }\n if (k >= i32(${Nt("uniforms.x_shape",i,t)})) {\n break;\n }\n offset += k * i32(${Nt("uniforms.x_strides",i,t)});\n `;return`\n value = ${e.type.value}(uniforms.constant_value);\n for (var i = 0; i < 1; i++) {\n var offset = 0;\n var k = 0;\n ${r}\n value = x[offset];\n }\n `},ro=(e,t,n)=>{let r="";for(let i=t-1;i>=0;--i)r+=`\n k = i32(${e.indicesGet("indices",i)}) - ${Nt("uniforms.pads",i,n)};\n if (k < 0) {\n k = -k;\n }\n {\n let _2n_1 = 2 * (i32(${Nt("uniforms.x_shape",i,t)}) - 1);\n k = k % _2n_1;\n if(k >= i32(${Nt("uniforms.x_shape",i,t)})) {\n k = _2n_1 - k;\n }\n }\n offset += k * i32(${Nt("uniforms.x_strides",i,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${r}\n value = x[offset];\n `},io=(e,t,n)=>{let r="";for(let i=t-1;i>=0;--i)r+=`\n k = i32(${e.indicesGet("indices",i)}) - ${Nt("uniforms.pads",i,n)};\n if (k < 0) {\n k = 0;\n }\n if (k >= i32(${Nt("uniforms.x_shape",i,t)})) {\n k = i32(${Nt("uniforms.x_shape",i,t)}) - 1;\n }\n offset += k * i32(${Nt("uniforms.x_strides",i,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${r}\n value = x[offset];\n `},ao=(e,t,n)=>{let r="";for(let i=t-1;i>=0;--i)r+=`\n k = i32(${e.indicesGet("indices",i)}) - ${Nt("uniforms.pads",i,n)};\n if (k < 0) {\n k += i32(${Nt("uniforms.x_shape",i,t)}]);\n }\n if (k >= i32(${Nt("uniforms.x_shape",i,t)})) {\n k -= i32(${Nt("uniforms.x_shape",i,t)});\n }\n offset += k * i32(${Nt("uniforms.x_strides",i,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${r}\n value = x[offset];\n `},so=(e,t,n)=>{switch(n.mode){case 0:return no(e,t,n.pads.length);case 1:return ro(e,t,n.pads.length);case 2:return io(e,t,n.pads.length);case 3:return ao(e,t,n.pads.length);default:throw new Error("Invalid mode")}},oo=(e,t)=>{let n=Tt.padShape(e[0].dims.slice(),t.pads),r=e[0].dims,i=[{type:12,data:Tt.size(n)},{type:6,data:t.pads}],a=e.length>=3&&e[2].data;0===t.mode&&i.push({type:a?e[2].dataType:1,data:t.value}),i.push(...It(e[0].dims,n));return{name:"Pad",shaderCache:{hint:`${t.mode}${a}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Tt.size(n)/64)},programUniforms:i}),getShaderSource:i=>{let s=Vt("output",e[0].dataType,n.length),o=Rt("x",e[0].dataType,r.length),l=o.type.value,u=so(s,r.length,t),d=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return 0===t.mode&&d.push({name:"constant_value",type:a?l:"f32"}),`\n ${i.registerUniforms(d).declareVariables(o,s)}\n ${i.mainStart()}\n ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${s.offsetToIndices("global_idx")};\n\n var value = ${l}(0);\n ${u}\n output[global_idx] = value;\n }`}}},lo=(e,t)=>{if(e.length>1){let n=e[1].getBigInt64Array(),r=e.length>=3&&e[2].data?10===e[2].dataType?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,i=e[0].dims.length,a=new Int32Array(2*i).fill(0);if(e.length>=4){let t=e[3].getBigInt64Array();for(let e=0;ea[Number(t)]=Number(e)));let s=[];return a.forEach((e=>s.push(e))),{mode:t.mode,value:r,pads:s}}return t},uo=(e,t)=>{to(e.inputs);let n=lo(e.inputs,t);e.compute(oo(e.inputs,n),{inputs:[0]})}})),Xu=j((()=>{pe(),Zl(),au(),su(),co=e=>{if(p.webgpu.validateInputContent&&(!e||1!==e.length))throw new Error("Pool ops requires 1 input.")},po=(e,t,n)=>{let r="NHWC"===t.format,i=e.dims.slice();r&&i.splice(1,0,i.pop());let a=Object.hasOwnProperty.call(t,"dilations"),s=t.kernelShape.slice(),o=t.strides.slice(),l=a?t.dilations.slice():[],u=t.pads.slice();kt.adjustPoolAttributes(n,i,s,o,l,u);let d=kt.computePoolOutputShape(n,i,o,l,s,u,t.autoPad),c=Object.assign({},t);a?Object.assign(c,{kernelShape:s,strides:o,pads:u,dilations:l,cacheKey:t.cacheKey}):Object.assign(c,{kernelShape:s,strides:o,pads:u,cacheKey:t.cacheKey});let p=d.slice();return p.push(p.splice(1,1)[0]),[c,r?p:d]},ho=(e,t)=>{let n="NHWC"===t.format,r=[{type:12,data:Tt.size(e)},{type:12,data:Tt.size(t.kernelShape)}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let e=t.kernelShape[t.kernelShape.length-1],n=t.strides[t.strides.length-1],a=t.pads[t.pads.length/2-1],s=t.pads[t.pads.length-1],o=!!(a+s);r.push({type:12,data:e},{type:12,data:n},{type:12,data:a},{type:12,data:s}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let l=!1;if(2===t.kernelShape.length){let e=t.kernelShape[t.kernelShape.length-2],n=t.strides[t.strides.length-2],a=t.pads[t.pads.length/2-2],s=t.pads[t.pads.length-2];l=!!(a+s),r.push({type:12,data:e},{type:12,data:n},{type:12,data:a},{type:12,data:s}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[r,i,!0,o,l]}{if(n)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let e=Tt.computeStrides(t.kernelShape);return r.push({type:12,data:e},{type:12,data:t.pads},{type:12,data:t.strides}),i.push({name:"kernelStrides",type:"u32",length:e.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length}),[r,i,!!t.pads.reduce(((e,t)=>e+t)),!1,!1]}},mo=(e,t,n,r,i,a,s,o,l,u,d,c)=>{let p="NHWC"===i.format,h=t.type.value,m=Vt("output",t.type.tensor,r);if(i.kernelShape.length<=2){let r="",u="",f="",g=n-(p?2:1);if(r=d?`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i;\n if (xIndices[${g}] < 0 || xIndices[${g}]\n >= uniforms.x_shape[${g}]) {\n pad++;\n continue;\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${a}\n }`:`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i;\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${a}\n }`,2===i.kernelShape.length){let e=n-(p?3:2);u=c?`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${e}] = indices[${e}] * uniforms.sh - uniforms.phStart + j;\n if (xIndices[${e}] < 0 || xIndices[${e}] >= uniforms.x_shape[${e}]) {\n pad += i32(uniforms.kw);\n continue;\n }\n `:`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${e}] = indices[${e}] * uniforms.sh - uniforms.phStart + j;\n `,f="\n }\n "}return`\n ${e.registerUniforms(l).declareVariables(t,m)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let indices = ${m.offsetToIndices("global_idx")};\n var xIndices = ${m.offsetToIndices("global_idx")};\n\n var value = ${h}(${o});\n var pad = 0;\n ${u}\n ${r}\n ${f}\n ${s}\n\n output[global_idx] = value;\n }`}{if(p)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let r=i.kernelShape.length,d=i.pads.length,c="";return c=u?`\n if (xIndices[j] >= uniforms.x_shape[j]) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${a}\n }`:`\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${a}\n `,`\n ${e.registerUniforms(l).declareVariables(t,m)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let indices = ${m.offsetToIndices("global_idx")};\n var xIndices = ${m.offsetToIndices("global_idx")};\n\n var offsets: array;\n\n var value = ${h}(${o});\n var pad = 0;\n var isPad = false;\n\n for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {\n var offset = i;\n for (var j = 0u; j < ${r-1}u; j++) {\n offsets[j] = offset / ${Nt("uniforms.kernelStrides","j",r)};\n offset -= offsets[j] * ${Nt("uniforms.kernelStrides","j",r)};\n }\n offsets[${r-1}] = offset;\n\n isPad = false;\n for (var j = ${n-r}u; j < ${n}u; j++) {\n xIndices[j] = indices[j] * ${Nt("uniforms.strides",`j - ${n-r}u`,r)}\n + offsets[j - ${n-r}u] - ${Nt("uniforms.pads","j - 2u",d)};\n ${c}\n }\n ${s}\n\n output[global_idx] = value;\n }`}},fo=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,go=e=>`${fo(e)};${e.countIncludePad}`,_o=e=>`${fo(e)};${e.storageOrder};${e.dilations}`,wo=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),bo=(e,t,n,r)=>{let[i,a]=po(t,r,n),s=Rt("x",t.dataType,t.dims.length),o=s.type.value,l="";i.countIncludePad?l+=`value /= ${o}(uniforms.kernelSize);`:l+=`value /= ${o}(i32(uniforms.kernelSize) - pad);`;let[u,d,c,p,h]=ho(a,i);u.push(...It(t.dims,a));return{name:e,shaderCache:{hint:`${r.cacheKey};${c};${p};${h}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Tt.size(a)/64)},programUniforms:u}),getShaderSource:e=>mo(e,s,t.dims.length,a.length,i,"value += x_val;",l,0,d,c,p,h)}},yo=e=>{let t=0!==e.count_include_pad,n=wo(e);if(0!==n.ceilMode)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let r={countIncludePad:t,...n,cacheKey:""};return{...r,cacheKey:go(r)}},xo=(e,t)=>{co(e.inputs),e.compute(bo("AveragePool",e.inputs[0],!1,t))},vo={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Mo=e=>{let t=e.format;return{format:t,...vo,cacheKey:t}},To=(e,t)=>{co(e.inputs),e.compute(bo("GlobalAveragePool",e.inputs[0],!0,t))},ko=(e,t,n,r)=>{let[i,a]=po(t,r,n),s=Rt("x",t.dataType,t.dims.length),[o,l,u,d,c]=ho(a,i);return o.push(...It(t.dims,a)),{name:e,shaderCache:{hint:`${r.cacheKey};${u};${d};${c}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Tt.size(a)/64)},programUniforms:o}),getShaderSource:e=>mo(e,s,t.dims.length,a.length,i,"\n value = max(x_val, value);\n ","",10===t.dataType?-65504:-1e5,l,u,d,c)}},$o=(e,t)=>{co(e.inputs),e.compute(ko("MaxPool",e.inputs[0],!1,t))},Co=e=>{let t=e.storage_order,n=e.dilations,r=wo(e);if(0!==t)throw new Error("column major storage order is not yet supported for MaxPool");if(0!==r.ceilMode)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let i={storageOrder:t,dilations:n,...r,cacheKey:""};return{...i,cacheKey:_o(i)}},So=e=>{let t=e.format;return{format:t,...vo,cacheKey:t}},Po=(e,t)=>{co(e.inputs),e.compute(ko("GlobalMaxPool",e.inputs[0],!0,t))}})),Ku=j((()=>{Zl(),au(),iu(),su(),Eo=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(3===e.length&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(3===e.length&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(6===e[0].dataType&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(0!==e[1].dims.length&&1!==e[1].dims.length&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map(((t,n)=>t===e[2].dims[n])).reduce(((e,t)=>e&&t),!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(0===e[1].dims.length||1===e[1].dims.length&&1===e[1].dims[0])throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map(((n,r)=>r===t.axis||n===e[0].dims[r])).reduce(((e,t)=>e&&t),!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let n=e[0].dims[t.axis],r=e[1].dims[t.axis];if(t.blockSizeMath.ceil(n/(r-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Fo=(e,t)=>{let n=Tt.normalizeAxis(t.axis,e[0].dims.length),r=e[0].dataType,i=3===r,a=e[0].dims,s=e[1].dataType,o=Tt.size(a),l=3===r||2===r,u=l?[Math.ceil(Tt.size(e[0].dims)/4)]:e[0].dims,d=e[1].dims,c=e.length>2?e[2]:void 0,p=c?l?[Math.ceil(Tt.size(c.dims)/4)]:c.dims:void 0,h=0===d.length||1===d.length&&1===d[0],m=!1===h&&1===d.length,f=zt(o),g=h&&(!l||4===f),_=g?f:1,w=g&&!l?f:1,b=Rt("input",l?12:r,u.length,w),y=Rt("scale",s,d.length),x=c?Rt("zero_point",l?12:r,p.length):void 0,v=Vt("output",s,a.length,_),M=[b,y];x&&M.push(x);let T=[u,d];c&&T.push(p);let k=[{type:12,data:o/_},{type:12,data:n},{type:12,data:t.blockSize},...It(...T,a)];return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:x?["rank","rank","rank"]:["rank","rank"]},getShaderSource:e=>`\n ${e.registerUniforms([{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}]).declareVariables(...M,v)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let output_indices = ${v.offsetToIndices("global_idx")};\n\n // Set input x\n ${l?`\n let input = ${b.getByOffset("global_idx / 4")};\n let x_vec = ${i?"unpack4xI8(input)":"unpack4xU8(input)"};\n let x_value = ${1===_?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${b.getByOffset("global_idx")};`};\n\n // Set scale input\n ${h?`let scale_value= ${y.getByOffset("0")}`:m?`\n let scale_index = ${v.indicesGet("output_indices","uniforms.axis")};\n let scale_value= ${y.getByOffset("scale_index")};`:`\n var scale_indices: ${y.type.indices} = output_indices;\n let index = ${y.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size;\n ${y.indicesSet("scale_indices","uniforms.axis","index")};\n let scale_value= ${y.getByIndices("scale_indices")};`};\n\n // Set zero-point input\n ${x?h?l?`\n let zero_point_input = ${x.getByOffset("0")};\n let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};\n let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${x.getByOffset("0")}`:m?l?`\n let zero_point_index = ${v.indicesGet("output_indices","uniforms.axis")};\n let zero_point_input = ${x.getByOffset("zero_point_index / 4")};\n let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};\n let zero_point_value = zero_point_vec[zero_point_index % 4]`:`\n let zero_point_index = ${v.indicesGet("output_indices","uniforms.axis")};\n let zero_point_value = ${x.getByOffset("zero_point_index")};`:l?`\n let zero_point_offset = ${y.indicesToOffset("scale_indices")};\n let zero_point_input = ${x.getByOffset("zero_point_offset / 4")};\n let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};\n let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${x.getByIndices("scale_indices")};`:`let zero_point_value = ${l?i?"i32":"u32":b.type.value}(0);`};\n // Compute and write output\n ${v.setByOffset("global_idx",`${v.type.value}(x_value - zero_point_value) * scale_value`)};\n }`,getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:Math.ceil(o/_/64),y:1,z:1},programUniforms:k})}},Ao=(e,t)=>{Eo(e.inputs,t),e.compute(Fo(e.inputs,t))},Io=e=>xt({axis:e.axis,blockSize:e.blockSize})})),Qu=j((()=>{pe(),Zl(),su(),zo=(e,t,n)=>{if(e===t||et&&n>0)throw new Error("Range these inputs' contents are invalid.")},Oo=(e,t,n,r)=>{let i=Math.abs(Math.ceil((t-e)/n)),a=[i],s=i,o=[{type:12,data:s},{type:r,data:e},{type:r,data:n},...It(a)];return{name:"Range",shaderCache:{hint:`${r}`},getShaderSource:e=>{let t=Vt("output",r,a.length),n=t.type.value,i=[{name:"outputSize",type:"u32"},{name:"start",type:n},{name:"delta",type:n}];return`\n ${e.registerUniforms(i).declareVariables(t)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n output[global_idx] = uniforms.start + ${n}(global_idx) * uniforms.delta;\n }`},getRunData:()=>({outputs:[{dims:a,dataType:r}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:o})}},Bo=e=>{let t=0,n=0,r=0;6===e.inputs[0].dataType?(t=e.inputs[0].getInt32Array()[0],n=e.inputs[1].getInt32Array()[0],r=e.inputs[2].getInt32Array()[0]):1===e.inputs[0].dataType&&(t=e.inputs[0].getFloat32Array()[0],n=e.inputs[1].getFloat32Array()[0],r=e.inputs[2].getFloat32Array()[0]),p.webgpu.validateInputContent&&zo(t,n,r),e.compute(Oo(t,n,r,e.inputs[0].dataType),{inputs:[]})}})),Yu=j((()=>{Zl(),au(),iu(),su(),Lo=(e,t)=>{if(e.every((e=>e>0||(()=>{throw new Error("Resize requires scales input values to be positive")}))),e.length>0)if("linear"===t.mode){if(!(2===e.length||3===e.length||4===e.length&&1===e[0]&&1===e[1]||4===e.length&&1===e[0]&&1===e[3]||5===e.length&&1===e[0]&&1===e[1]))throw new Error("For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and\n one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1")}else if("cubic"===t.mode&&!(2===e.length||4===e.length&&1===e[0]&&1===e[1]||4===e.length&&1===e[0]&&1===e[3]))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")},No=(e,t,n)=>{t.every((e=>e>=0&&e{throw new Error("Resize requires axes input values to be positive and less than rank")})));let r=new Array(n).fill(1);return t.forEach(((t,n)=>r[t]=e[n])),r},Do=(e,t,n,r,i,a)=>{let[s,o,l]=n>10?[1,2,3]:[-1,e.length>1?1:-1,-1],u=e[0].dims.length;if(s>0&&e.length>s&&e[s].dims.length>0)e[s].getFloat32Array().forEach((e=>a.push(e)));else if("tf_crop_and_resize"===t.coordinateTransformMode)throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(o>0&&e.length>o&&1===e[o].dims.length&&e[o].dims[0]>0){if(e[o].getFloat32Array().forEach((e=>r.push(e))),0!==r.length&&r.length!==u&&n>=18&&r.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Lo(r,t),t.axes.length>0&&No(r,t.axes,u).forEach(((e,t)=>r[t]=e))}if(l>0&&e.length>l&&1===e[l].dims.length&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach((e=>i.push(Number(e)))),0!==i.length&&i.length!==u&&n>=18&&i.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(0!==r.length&&r.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(0!==i.length&&i.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof r<"u"&&typeof i<"u"&&r.length>0&&i.length>u)throw new Error("Resize requires only of scales or sizes to be specified")},Ro=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,\n lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`return ${t}(xResized) / ${t}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) {\n return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;\n } else {\n return 0.0;\n }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) {\n return 0.0;\n } else {\n // The whole part and the fractional part are calculated separately due to inaccuracy of floating\n // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an\n // offset-by-one error later in floor().\n let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1));\n let fract =\n ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1);\n return whole + fract;\n }`;case"tf_crop_and_resize":return`if (lengthResized > 1) {\n return ${t}(roiStart) * ${t}(lengthOriginal - 1) +\n (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /\n ${t}(lengthResized - 1);\n } else {\n return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);\n }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized);\n const adjustment = ${t}(lengthResized) / outputWidth;\n const center = ${t}(lengthOriginal) / 2;\n const offset = center * (1 - adjustment);\n return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",Vo=(e,t,n)=>`fn getNearestPixelFromOriginal(xOriginal: ${n}, isDownSample: bool) -> ${n} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",jo=(e,t,n)=>{let r=new Array(n).fill(0).concat(new Array(n).fill(1)),i=0===e.length?r:e.slice();return t.length>0?(t.forEach(((e,a)=>{r[e]=i[a],r[a+n]=i[t.length+a]})),r):i},qo=(e,t,n,r)=>{let i=[];if(n.length>0)if(r.length>0){if(e.forEach((e=>i.push(e))),Math.max(...r)>e.length)throw new Error("axes is out of bound");r.forEach(((e,t)=>i[e]=n[t]))}else n.forEach((e=>i.push(e)));else{if(0===t.length)throw new Error("Resize requires either scales or sizes.");i=e.map(((e,n)=>Math.round(e*t[n])))}return i},Go=(e,t,n)=>{let r=(()=>{switch(n.keepAspectRatioPolicy){case"not_larger":return n.axes.length>0?Math.min(...n.axes.map((e=>t[e])),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return n.axes.length>0?Math.max(...n.axes.map((e=>t[e])),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${n.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let i=e.slice();return n.axes.length>0?(n.axes.forEach((e=>t[e]=r)),n.axes.forEach((n=>i[n]=Math.round(e[n]*t[n])))):(t.fill(r,0,t.length),i.forEach(((e,n)=>i[n]=Math.round(e*t[n])))),i},Wo=(e,t,n,r,i)=>`\n fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${n.length}> {\n var original_indices: array<${e.type.value}, ${n.length}>;\n for (var i:u32 = 0; i < ${n.length}; i++) {\n var output_index = ${e.indicesGet("output_indices","i")};\n var scale = ${Nt("uniforms.scales","i",r)};\n var roi_low = ${Nt("uniforms.roi","i",i)};\n var roi_hi = ${Nt("uniforms.roi",`i + ${t.length}`,i)};\n if (scale == 1.0) {\n original_indices[i] = ${e.type.value}(output_index);\n } else {\n var input_shape_i = ${Nt("uniforms.input_shape","i",t.length)};\n var output_shape_i = ${Nt("uniforms.output_shape","i",n.length)};\n original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n }\n }\n return original_indices;\n }`,Uo=(e,t,n,r,i,a,s)=>`\n fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n for (var i:u32 = 0; i < ${r.length}; i++) {\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index: u32;\n var scale = ${Nt("uniforms.scales","i",i)};\n if (scale == 1.0) {\n input_index = output_index;\n } else {\n var roi_low = ${Nt("uniforms.roi","i",a)};\n var roi_hi = ${Nt("uniforms.roi",`i + ${n.length}`,a)};\n var input_shape_i = ${Nt("uniforms.input_shape","i",n.length)};\n var output_shape_i = ${Nt("uniforms.output_shape","i",r.length)};\n var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n if (!${s} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {\n if (original_idx < 0) {\n input_index = 0;\n } else if (original_idx > ${t.type.value}(input_shape_i - 1)) {\n input_index = input_shape_i - 1;\n } else {\n input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));\n }\n } else {\n input_index = u32(original_idx);\n }\n }\n ${e.indicesSet("input_indices","i"," input_index")}\n }\n return input_indices;\n }`,Ho=(e,t)=>`\n fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {\n for (var i:u32 = 0; i < ${t.length}; i++) {\n var input_index = ${e.indicesGet("input_indices","i")};\n if (input_index < 0 || input_index >= ${Nt("uniforms.input_shape","i",t.length)}) {\n return false;\n }\n }\n return true;\n }`,Xo=(e,t,n,r)=>e.rank>r?`\n ${e.indicesSet("input_indices",t,"channel")};\n ${e.indicesSet("input_indices",n,"batch")};\n`:"",Ko=(e,t,n,r,i)=>{let[a,s,o,l]=2===n.length?[-1,0,1,-1]:[0,2,3,1],u=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${u} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",s,`max(0, min(row, ${n[s]} - 1))`)};\n ${e.indicesSet("input_indices",o,`max(0, min(col, ${n[o]} - 1))`)};\n ${Xo(e,l,a,2)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${u} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var row:${u} = originalIndices[${s}];\n var col:${u} = originalIndices[${o}];\n ${r?`if (row < 0 || row > (${n[s]} - 1) || col < 0 || col > (${n[o]} - 1)) {\n return ${i};\n }`:""};\n row = max(0, min(row, ${n[s]} - 1));\n col = max(0, min(col, ${n[o]} - 1));\n var row1: u32 = u32(row);\n var col1: u32 = u32(col);\n var row2: u32 = u32(row + 1);\n var col2: u32 = u32(col + 1);\n var channel: u32 = ${n.length>2?`u32(originalIndices[${l}])`:"0"};\n var batch: u32 = ${n.length>2?`u32(originalIndices[${a}])`:"0"};\n var x11: ${u} = getInputValue(batch, channel, row1, col1);\n var x12: ${u} = getInputValue(batch, channel, row1, col2);\n var x21: ${u} = getInputValue(batch, channel, row2, col1);\n var x22: ${u} = getInputValue(batch, channel, row2, col2);\n var dx1: ${u} = abs(row - ${u}(row1));\n var dx2: ${u} = abs(${u}(row2) - row);\n var dy1: ${u} = abs(col - ${u}(col1));\n var dy2: ${u} = abs(${u}(col2) - col);\n if (row1 == row2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (col1 == col2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);\n }`},Qo=(e,t,n,r,i,a,s,o,l,u)=>{let d=2===n.length,[c,p]=d?[0,1]:[2,3],h=e.type.value,m=s=>{let d=s===c?"row":"col";return`\n fn ${d}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${h} {\n var output_index = ${t.indicesGet("output_indices",s)};\n var originalIdx: ${h} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[s]},\n ${r[s]}, ${n[s]}, ${a[s]}, ${a[s]} + ${n.length});\n var fractOriginalIdx: ${h} = originalIdx - floor(originalIdx);\n var coefs = getCubicInterpolationCoefs(fractOriginalIdx);\n\n if (${o} && (originalIdx < 0 || originalIdx > (${n[s]} - 1))) {\n return ${l};\n }\n var data: array<${h}, 4> = array<${h}, 4>(0.0, 0.0, 0.0, 0.0);\n for (var i: i32 = -1; i < 3; i++) {\n var ${d}: ${h} = originalIdx + ${h}(i);\n if (${d} < 0 || ${d} >= ${n[s]}) {\n ${u?"coefs[i + 1] = 0.0;\n continue;":o?`return ${l};`:`${d} = max(0, min(${d}, ${n[s]} - 1));`};\n }\n var input_indices_copy: ${e.type.indices} = input_indices;\n ${e.indicesSet("input_indices_copy",s,`u32(${d})`)};\n data[i + 1] = ${s===c?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};\n }\n return cubicInterpolation1D(data, coefs);\n }`};return`\n ${m(c)};\n ${m(p)};\n fn getCubicInterpolationCoefs(s: ${h}) -> array<${h}, 4> {\n var absS = abs(s);\n var coeffs: array<${h}, 4> = array<${h}, 4>(0.0, 0.0, 0.0, 0.0);\n var oneMinusAbsS: ${h} = 1.0 - absS;\n var twoMinusAbsS: ${h} = 2.0 - absS;\n var onePlusAbsS: ${h} = 1.0 + absS;\n coeffs[0] = ((${s} * onePlusAbsS - 5 * ${s}) * onePlusAbsS + 8 * ${s}) * onePlusAbsS - 4 * ${s};\n coeffs[1] = ((${s} + 2) * absS - (${s} + 3)) * absS * absS + 1;\n coeffs[2] = ((${s} + 2) * oneMinusAbsS - (${s} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;\n coeffs[3] = ((${s} * twoMinusAbsS - 5 * ${s}) * twoMinusAbsS + 8 * ${s}) * twoMinusAbsS - 4 * ${s};\n return coeffs;\n }\n\n fn cubicInterpolation1D(x: array<${h}, 4>, coefs: array<${h}, 4>) -> ${h} {\n var coefsSum: ${h} = coefs[0] + coefs[1] + coefs[2] + coefs[3];\n return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;\n }\n\n fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${h} {\n var input_indices: ${e.type.indices} = output_indices;\n return colCubicInterpolation(input_indices, output_indices);\n }\n `},Yo=(e,t,n,r,i)=>{let[a,s,o,l,u]=3===n.length?[-1,0,1,2,-1]:[0,2,3,4,1],d=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${d} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",s,`max(0, min(depth, ${n[s]} - 1))`)};\n ${e.indicesSet("input_indices",o,`max(0, min(height, ${n[o]} - 1))`)};\n ${e.indicesSet("input_indices",l,`max(0, min(width, ${n[l]} - 1))`)};\n ${Xo(e,u,a,3)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${d} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var depth:${d} = originalIndices[${s}];\n var height:${d} = originalIndices[${o}];\n var width:${d} = originalIndices[${l}];\n ${r?`if (depth < 0 || depth > (${n[s]} - 1) || height < 0 || height > (${n[o]} - 1) || width < 0 || (width > ${n[l]} - 1)) {\n return ${i};\n }`:""};\n\n depth = max(0, min(depth, ${n[s]} - 1));\n height = max(0, min(height, ${n[o]} - 1));\n width = max(0, min(width, ${n[l]} - 1));\n var depth1: u32 = u32(depth);\n var height1: u32 = u32(height);\n var width1: u32 = u32(width);\n var depth2: u32 = u32(depth + 1);\n var height2: u32 = u32(height + 1);\n var width2: u32 = u32(width + 1);\n var channel: u32 = ${n.length>3?`u32(originalIndices[${u}])`:"0"};\n var batch: u32 = ${n.length>3?`u32(originalIndices[${a}])`:"0"};\n\n var x111: ${d} = getInputValue(batch, channel, depth1, height1, width1);\n var x112: ${d} = getInputValue(batch, channel, depth1, height1, width2);\n var x121: ${d} = getInputValue(batch, channel, depth1, height2, width1);\n var x122: ${d} = getInputValue(batch, channel, depth1, height2, width2);\n var x211: ${d} = getInputValue(batch, channel, depth2, height1, width1);\n var x212: ${d} = getInputValue(batch, channel, depth2, height1, width2);\n var x221: ${d} = getInputValue(batch, channel, depth2, height2, width1);\n var x222: ${d} = getInputValue(batch, channel, depth2, height2, width2);\n var dx1: ${d} = abs(depth - ${d}(depth1));\n var dx2: ${d} = abs(${d}(depth2) - depth);\n var dy1: ${d} = abs(height - ${d}(height1));\n var dy2: ${d} = abs(${d}(height2) - height);\n var dz1: ${d} = abs(width - ${d}(width1));\n var dz2: ${d} = abs(${d}(width2) - width);\n if (depth1 == depth2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (height1 == height2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n if (width1 == width2) {\n dz1 = 0.5;\n dz2 = 0.5;\n }\n return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +\n x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);\n }`},Zo=(e,t,n,r,i,a)=>{let s=e.dims,o=jo(a,t.axes,s.length),l=qo(s,r,i,t.axes),u=r.slice();0===r.length&&(u=s.map(((e,t)=>0===e?1:l[t]/e)),"stretch"!==t.keepAspectRatioPolicy&&(l=Go(s,u,t)));let d=Vt("output",e.dataType,l.length),c=Rt("input",e.dataType,s.length),p=Tt.size(l),h=s.length===l.length&&s.every(((e,t)=>e===l[t])),m="tf_crop_and_resize"===t.coordinateTransformMode,f=t.extrapolationValue,g=c.type.value;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${n}|${u.length>0?u:""}|${i.length>0?i:""}|${o.length>0?o:""}|${h}|${s}`,inputDependencies:["rank"]},getShaderSource:e=>`\n ${h?"":`\n ${Ro(t.coordinateTransformMode,g)};\n ${(()=>{switch(t.mode){case"nearest":return`\n ${Ho(c,s)};\n ${Vo(t.nearestMode,n,g)};\n ${Uo(c,d,s,l,u.length,o.length,m)};\n `;case"linear":return`\n ${Wo(d,s,l,u.length,o.length)};\n ${(()=>{if(2===s.length||4===s.length)return`${Ko(c,d,s,m,f)}`;if(3===s.length||5===s.length)return`${Yo(c,d,s,m,f)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};\n `;case"cubic":return`\n ${(()=>{if(2===s.length||4===s.length)return`${Qo(c,d,s,l,u,o,t.cubicCoeffA,m,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()};\n `;default:throw Error("Invalid resize mode")}})()};\n `}\n ${e.registerUniform("output_size","u32").registerUniform("scales","f32",u.length).registerUniform("roi","f32",o.length).declareVariables(c,d)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n ${h?"output[global_idx] = input[global_idx];":`\n let output_indices = ${d.offsetToIndices("global_idx")};\n var input_indices: ${c.type.indices};\n ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);\n if (checkInputIndices(input_indices)) {\n output[global_idx] = ${c.getByIndices("input_indices")};\n } else {\n output[global_idx] = ${t.extrapolationValue};\n }`;case"linear":return`output[global_idx] = ${2===s.length||4===s.length?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};\n`}\n }`,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},{type:1,data:u},{type:1,data:o},...It(s,l)]})}},Jo=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},el=(e,t)=>{let n=[],r=[],i=[],a=Jo(e);if(0!==t.antialias)throw Error("Only default value (0) for Antialias attribute is supported");Do(e.inputs,t,a,n,r,i),e.compute(Zo(e.inputs[0],t,a,n,r,i),{inputs:[0]})},tl=e=>{let t=e.antialias,n=e.axes,r=e.coordinateTransformMode,i=e.cubicCoeffA,a=0!==e.excludeOutside,s=e.extrapolationValue,o=e.keepAspectRatioPolicy,l=e.mode,u=""===e.nearestMode?"simple":e.nearestMode;return xt({antialias:t,axes:n,coordinateTransformMode:r,cubicCoeffA:i,excludeOutside:a,extrapolationValue:s,keepAspectRatioPolicy:o,mode:l,nearestMode:u})}})),Zu=j((()=>{Zl(),au(),iu(),su(),nl=(e,t)=>{let[n,r,i,a]=e,{numHeads:s,rotaryEmbeddingDim:o}=t;if(3!==n.dims.length&&4!==n.dims.length)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${n.dims.length}`);if(!Tt.areEqual(r.dims,[])&&!Tt.areEqual(r.dims,[1])&&2!==r.dims.length)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${r.dims.length}`);if(2!==i.dims.length)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(2!==a.dims.length)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!Tt.areEqual(i.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(o>0&&0===s)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=n.dims[0],u=n.dims[n.dims.length-2],d=i.dims[0],c=Tt.sizeFromDimension(n.dims,1)/u,p=0===o?2*i.dims[1]:c/s;if(o>p)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(2===r.dims.length){if(l!==r.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${r.dims[0]}`);if(u!==r.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${r.dims[1]}`)}if(p/2!==i.dims[1]&&o/2!==i.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(u>d)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},rl=(e,t)=>{let{interleaved:n,numHeads:r,rotaryEmbeddingDim:i,scale:a}=t,s=e[0].dims[0],o=Tt.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],u=o/l,d=e[2].dims[1],c=0===i?2*d:u/r,p=new Array(s,l,u/c,c-d),h=Tt.computeStrides(p),m=[{type:1,data:a},{type:12,data:p},{type:12,data:h},...3===e[0].dims.length?new Array({type:12,data:[o,u,c,1]}):[],...4===e[0].dims.length?new Array({type:12,data:[o,c,l*c,1]}):[],...It(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)];return{name:"RotaryEmbedding",shaderCache:{hint:xt({interleaved:n}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:t=>{let r=Rt("input",e[0].dataType,e[0].dims.length),i=Rt("position_ids",e[1].dataType,e[1].dims.length),a=Rt("cos_cache",e[2].dataType,e[2].dims.length),s=Rt("sin_cache",e[3].dataType,e[3].dims.length),o=Vt("output",e[0].dataType,e[0].dims.length);return t.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:p.length},{name:"global_strides",type:"u32",length:h.length},{name:"input_output_strides",type:"u32",length:h.length}]),`\n ${t.declareVariables(r,i,a,s,o)}\n\n ${t.mainStart(Pt)}\n let half_rotary_emb_dim = uniforms.${a.name}_shape[1];\n let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;\n let size = uniforms.global_shape[0] * uniforms.global_strides[0];\n ${t.guardAgainstOutOfBoundsWorkgroupSizes("size")}\n\n if (bsnh[3] < half_rotary_emb_dim) {\n let position_ids_idx =\n ${i.broadcastedIndicesToOffset("bsnh.xy",Vt("",i.type.tensor,2))};\n let position_id =\n u32(${i.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0);\n let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${n});\n let j = i + select(half_rotary_emb_dim, 1, ${n});\n let re = ${r.getByOffset("i")} * ${a.get("position_id","bsnh[3]")} -\n ${r.getByOffset("j")} * ${s.get("position_id","bsnh[3]")};\n ${o.setByOffset("i","re")}\n let im = ${r.getByOffset("i")} * ${s.get("position_id","bsnh[3]")} +\n ${r.getByOffset("j")} * ${a.get("position_id","bsnh[3]")};\n ${o.setByOffset("j","im")}\n } else {\n let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;\n ${o.setByOffset("k",r.getByOffset("k"))}\n }\n }`},getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Tt.size(p)/Pt)},programUniforms:m})}},il=(e,t)=>{nl(e.inputs,t),e.compute(rl(e.inputs,t))}})),Ju=j((()=>{Zl(),au(),su(),al=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],n=e[1],r=e[2];if(t.dataType!==n.dataType||t.dataType!==r.dataType)throw new Error("All inputs must have the same data type");if(3!==t.dims.length&&2!==t.dims.length)throw new Error("Input must be 2D or 3D");if(3!==n.dims.length&&2!==n.dims.length)throw new Error("Skip must be 2D or 3D");let i=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(n.dims[n.dims.length-1]!==i)throw new Error("Skip must have the same hidden size as input");if(n.dims[n.dims.length-2]!==a)throw new Error("Skip must have the same sequence length as input");if(1!==r.dims.length)throw new Error("Gamma must be 1D");if(r.dims[r.dims.length-1]!==i)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let t=e[3];if(1!==t.dims.length)throw new Error("Beta must be 1D");if(t.dims[t.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let t=e[4];if(1!==t.dims.length)throw new Error("Bias must be 1D");if(t.dims[t.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},sl=(e,t,n,r)=>{let i=t.simplified,a=e[0].dims,s=Tt.size(a),o=a,l=s,u=a.slice(-1)[0],d=r?a.slice(0,-1).concat(1):[],c=!i&&e.length>3,p=e.length>4,h=r&&n>1,m=r&&n>2,f=n>3,g=64,_=zt(u),w=[{type:12,data:l},{type:12,data:_},{type:12,data:u},{type:1,data:t.epsilon}],b=[{dims:o,dataType:e[0].dataType}];return n>1&&b.push({dims:d,dataType:1}),n>2&&b.push({dims:d,dataType:1}),n>3&&b.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${_};${h};${m};${f}`,inputDependencies:e.map(((e,t)=>"type"))},getShaderSource:t=>{let n=[Rt("x",e[0].dataType,e[0].dims,_),Rt("skip",e[1].dataType,e[1].dims,_),Rt("gamma",e[2].dataType,e[2].dims,_)];c&&n.push(Rt("beta",e[3].dataType,e[3].dims,_)),p&&n.push(Rt("bias",e[4].dataType,e[4].dims,_)),n.push(Vt("output",e[0].dataType,o,_)),h&&n.push(Vt("mean_output",1,d)),m&&n.push(Vt("inv_std_output",1,d)),f&&n.push(Vt("input_skip_bias_sum",e[0].dataType,o,_));let r=Ft(e[0].dataType),a=Ft(1,_);return`\n\n ${t.registerUniforms([{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}]).declareVariables(...n)}\n var sum_shared : array<${a}, 64>;\n var sum_squared_shared : array<${a}, 64>;\n\n ${t.mainStart([g,1,1])}\n let ix = local_id.x;\n let iy = global_id.x / 64;\n\n let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;\n var stride = hidden_size_vectorized / 64;\n let offset = ix * stride + iy * hidden_size_vectorized;\n let offset1d = stride * ix;\n if (ix == 63) {\n stride = hidden_size_vectorized - stride * ix;\n }\n for (var i: u32 = 0; i < stride; i++) {\n let skip_value = skip[offset + i];\n let bias_value = ${p?"bias[offset1d + i]":r+"(0.0)"};\n let input_value = x[offset + i];\n let value = input_value + skip_value + bias_value;\n ${f?"input_skip_bias_sum[offset + i] = value;":""}\n output[offset + i] = value;\n let f32_value = ${Bt(r,_,"value")};\n sum_shared[ix] += f32_value;\n sum_squared_shared[ix] += f32_value * f32_value;\n }\n workgroupBarrier();\n\n var reduce_size : u32 = 64;\n for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) {\n reduce_size = curr_size + (reduce_size & 1);\n if (ix < curr_size) {\n sum_shared[ix] += sum_shared[ix + reduce_size];\n sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size];\n }\n workgroupBarrier();\n }\n\n let sum = sum_shared[0];\n let square_sum = sum_squared_shared[0];\n let mean = ${Lt("sum",_)} / f32(uniforms.hidden_size);\n let inv_std_dev = inverseSqrt(${Lt("square_sum",_)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon);\n ${h?"mean_output[global_idx] = mean;":""}\n ${m?"inv_std_output[global_idx] = inv_std_dev;":""}\n\n for (var i: u32 = 0; i < stride; i++) {\n output[offset + i] = (output[offset + i] ${i?"":`- ${r}(mean)`}) *\n ${r}(inv_std_dev) * gamma[offset1d + i]\n ${c?"+ beta[offset1d + i]":""};\n }\n }`},getRunData:()=>({outputs:b,dispatchGroup:{x:Math.ceil(l/u)},programUniforms:w})}},ol=(e,t)=>{al(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(sl(e.inputs,t,e.outputCount,!1),{outputs:n})}})),ed=j((()=>{Zl(),au(),iu(),su(),ll=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(0!==t.axes.length){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach(((t,n)=>{if(6!==e[n+1].dataType&&7!==e[n+1].dataType)throw new Error(`Input ${n} must be an array of int32 or int64`)}))},ul=(e,t)=>{let n=[];if(e.length>t)if(7===e[t].dataType)e[t].getBigInt64Array().forEach((e=>n.push(Number(e))));else{if(6!==e[t].dataType)throw new Error(`Input ${t} must be an array of int32 or int64`);e[t].getInt32Array().forEach((e=>n.push(Number(e))))}return n},dl=(e,t)=>{if(e.length>1){let t=ul(e,1),n=ul(e,2),r=ul(e,3);return 0===r.length&&(r=[...Array(e[0].dims.length).keys()]),xt({starts:t,ends:n,axes:r})}return t},cl=(e,t,n,r,i)=>{let a=e;return e<0&&(a+=n[r[t]]),i[t]<0?Math.max(0,Math.min(a,n[r[t]]-1)):Math.max(0,Math.min(a,n[r[t]]))},pl=(e,t,n)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n var carry = 0u;\n for (var i = ${n.length}; i >= 0; i--) {\n let input_shape_i = ${Nt("uniforms.input_shape","i",n.length)};\n let steps_i = ${Nt("uniforms.steps","i",n.length)};\n let signs_i = ${Nt("uniforms.signs","i",n.length)};\n let starts_i = ${Nt("uniforms.starts","i",n.length)};\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index = output_index * steps_i + starts_i + carry;\n carry = input_index / input_shape_i;\n input_index = input_index % input_shape_i;\n if (signs_i < 0) {\n input_index = input_shape_i - input_index - 1u + starts_i;\n }\n ${e.indicesSet("input_indices","i","input_index")};\n }\n return input_indices;\n }`,hl=(e,t)=>{let n=e[0].dims,r=Tt.size(n),i=t.axes.length>0?Tt.normalizeAxes(t.axes,n.length):[...Array(n.length).keys()],a=ul(e,4);a.forEach((e=>0!==e||(()=>{throw new Error("step cannot be 0")}))),0===a.length&&(a=Array(i.length).fill(1));let s=t.starts.map(((e,t)=>cl(e,t,n,i,a))),o=t.ends.map(((e,t)=>cl(e,t,n,i,a)));if(i.length!==s.length||i.length!==o.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==n.length)for(let e=0;eMath.sign(e)));a.forEach(((e,t,n)=>{if(e<0){let r=(o[t]-s[t])/e,i=s[t],l=i+r*a[t];s[t]=l,o[t]=i,n[t]=-e}}));let u=n.slice(0);i.forEach(((e,t)=>{u[e]=Math.ceil((o[e]-s[e])/a[e])}));let d={dims:u,dataType:e[0].dataType},c=Vt("output",e[0].dataType,u.length),p=Rt("input",e[0].dataType,e[0].dims.length),h=Tt.size(u),m=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:s.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:a.length}],f=[{type:12,data:h},{type:12,data:s},{type:6,data:l},{type:12,data:a},...It(e[0].dims,u)];return{name:"Slice",shaderCache:{hint:`${l.length}_${s.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:e=>`\n ${e.registerUniforms(m).declareVariables(p,c)}\n ${pl(p,c,n)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let output_indices = ${c.offsetToIndices("global_idx")};\n let input_indices = calculateInputIndices(output_indices);\n ${c.setByOffset("global_idx",p.getByIndices("input_indices"))}\n }`,getRunData:()=>({outputs:[d],dispatchGroup:{x:Math.ceil(r/64)},programUniforms:f})}},ml=(e,t)=>{ll(e.inputs,t);let n=dl(e.inputs,t);e.compute(hl(e.inputs,n),{inputs:[0]})},fl=e=>{let t=e.starts,n=e.ends,r=e.axes;return xt({starts:t,ends:n,axes:r})}})),td=j((()=>{Zl(),au(),iu(),ou(),su(),gl=e=>{if(!e||1!==e.length)throw new Error("Softmax op requires 1 input.")},_l=(e,t)=>{let n,r=e.inputs[0],i=r.dims,a=Tt.size(i),s=i.length,o=Tt.normalizeAxis(t.axis,s),l=ot)),u[o]=s-1,u[s-1]=o,n=e.compute(Qt(r,u),{inputs:[r],outputs:[-1]})[0]):n=r;let d=n.dims,c=d[s-1],p=a/c,h=zt(c),m=c/h,f=64;1===p&&(f=256);let g=Rt("x",n.dataType,n.dims,h),_=Vt("result",n.dataType,n.dims,h),w=g.type.value,b="f32"===Ft(n.dataType)?`var threadMax = ${w}(-3.402823e+38f);`:`var threadMax = ${w}(-65504.0h);`,y=e.compute({name:"Softmax",shaderCache:{hint:`${h};${f}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:d,dataType:n.dataType}],dispatchGroup:{x:p},programUniforms:[{type:6,data:m}]}),getShaderSource:e=>`\n var rowMaxShared : ${w};\n var rowSumShared : ${w};\n var threadShared : array<${w}, ${f}>;\n\n fn getValue(row: i32, col: i32, row_stride: i32) -> ${w} {\n let index = row * row_stride + col;\n return x[index];\n }\n\n fn setValue(row: i32, col: i32, row_stride: i32, value: ${w}) {\n let index = row * row_stride + col;\n result[index] = value;\n }\n ${e.registerUniform("packedCols","i32").declareVariables(g,_)}\n ${e.mainStart(f)}\n let gindex = i32(global_idx);\n let lindex = i32(local_idx);\n const wg = ${f};\n let row = gindex / wg;\n let cols = uniforms.packedCols;\n let row_stride : i32 = uniforms.packedCols;\n\n // find the rows max\n ${b}\n for (var col = lindex; col < cols; col += wg) {\n let value = getValue(row, col, row_stride);\n threadMax = max(threadMax, value);\n }\n if (lindex < cols) {\n threadShared[lindex] = threadMax;\n }\n workgroupBarrier();\n\n var reduceSize = min(cols, wg);\n for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {\n reduceSize = currSize + (reduceSize & 1);\n if (lindex < currSize) {\n threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowMaxShared = ${w}(${((e,t)=>4===t?`max(max(${e}.x, ${e}.y), max(${e}.z, ${e}.w))`:2===t?`max(${e}.x, ${e}.y)`:3===t?`max(max(${e}.x, ${e}.y), ${e}.z)`:e)("threadShared[0]",h)});\n }\n workgroupBarrier();\n\n // find the rows sum\n var threadSum = ${w}(0.0);\n for (var col = lindex; col < cols; col += wg) {\n let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);\n threadSum += subExp;\n }\n threadShared[lindex] = threadSum;\n workgroupBarrier();\n\n for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {\n if (lindex < currSize) {\n threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowSumShared = ${w}(${Lt("threadShared[0]",h)});\n }\n workgroupBarrier();\n\n // calculate final value for each element in the row\n for (var col = lindex; col < cols; col += wg) {\n let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;\n setValue(row, col, row_stride, value);\n }\n }`},{inputs:[n],outputs:[l?-1:0]})[0];l&&e.compute(Qt(y,u),{inputs:[y]})},wl=(e,t)=>{gl(e.inputs),_l(e,t)},bl=e=>xt({axis:e.axis})})),nd=j((()=>{Zl(),au(),su(),yl=e=>Array.from(e.getBigInt64Array(),Number),xl=e=>{if(!e||2!==e.length)throw new Error("Tile requires 2 inputs.");if(1!==e[0].dataType&&10!==e[0].dataType&&6!==e[0].dataType&&12!==e[0].dataType)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(7!==e[1].dataType)throw new Error("Tile `repeats` input should be of int64 data type");if(1!==e[1].dims.length)throw new Error("Tile `repeats` input should be 1-D");if(yl(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},vl=(e,t)=>{let n=[];for(let r=0;r{let n=e[0].dims,r=t??yl(e[1]),i=vl(n,r),a=Tt.size(i),s=e[0].dataType,o=Rt("input",s,n.length),l=Vt("output",s,i.length);return{name:"Tile",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...It(e[0].dims,i)]}),getShaderSource:e=>`\n const inputShape = ${o.indices(...n)};\n ${e.registerUniform("output_size","u32").declareVariables(o,l)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let output_indices = ${l.offsetToIndices("global_idx")};\n var input_indices: ${o.type.indices};\n for (var i = 0; i < ${n.length}; i++) {\n let input_dim_i = ${o.indicesGet("uniforms.input_shape","i")};\n let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i;\n\n ${o.indicesSet("input_indices","i","input_dim_value")}\n }\n ${l.setByOffset("global_idx",o.getByIndices("input_indices"))}\n }`}},Tl=e=>{xl(e.inputs),e.compute(Ml(e.inputs),{inputs:[0]})}})),rd=j((()=>{Zl(),au(),su(),kl=(e,t,n,r,i)=>{let a,s=Vt("output_data",i,n.length,4),o=Rt("a_data",t[1].dataType,t[1].dims.length,4),l=Rt("b_data",t[2].dataType,t[2].dims.length,4),u=Rt("c_data",t[0].dataType,t[0].dims.length,4),d=(e,t,n)=>`select(${t}, ${e}, ${n})`;if(r){let e=(e,t,n="")=>{let r=`a_data[index_a${t}][component_a${t}]`,i=`b_data[index_b${t}][component_b${t}]`,a=`bool(c_data[index_c${t}] & (0xffu << (component_c${t} * 8)))`;return`\n let output_indices${t} = ${s.offsetToIndices(`global_idx * 4u + ${t}u`)};\n let offset_a${t} = ${o.broadcastedIndicesToOffset(`output_indices${t}`,s)};\n let offset_b${t} = ${l.broadcastedIndicesToOffset(`output_indices${t}`,s)};\n let offset_c${t} = ${u.broadcastedIndicesToOffset(`output_indices${t}`,s)};\n let index_a${t} = offset_a${t} / 4u;\n let index_b${t} = offset_b${t} / 4u;\n let index_c${t} = offset_c${t} / 4u;\n let component_a${t} = offset_a${t} % 4u;\n let component_b${t} = offset_b${t} % 4u;\n let component_c${t} = offset_c${t} % 4u;\n ${e}[${t}] = ${n}(${d(r,i,a)});\n `};a=9===i?`\n var data = vec4(0);\n ${e("data",0,"u32")}\n ${e("data",1,"u32")}\n ${e("data",2,"u32")}\n ${e("data",3,"u32")}\n output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:`\n ${e("output_data[global_idx]",0)}\n ${e("output_data[global_idx]",1)}\n ${e("output_data[global_idx]",2)}\n ${e("output_data[global_idx]",3)}\n `}else a=s.setByOffset("global_idx",d(o.getByOffset("global_idx"),l.getByOffset("global_idx"),u.getByOffset("global_idx")));return`\n ${e.registerUniform("vec_size","u32").declareVariables(u,o,l,s)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${a}\n }`},$l=e=>{let t=e[1].dims,n=e[2].dims,r=e[0].dims,i=e[1].dataType,a=!(Tt.areEqual(t,n)&&Tt.areEqual(n,r)),s=t,o=Tt.size(t);if(a){let e=Mt.calcShape(Mt.calcShape(t,n,!1),r,!1);if(!e)throw new Error("Can't perform where op on the given tensors");s=e,o=Tt.size(s)}let l=Math.ceil(o/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:t=>kl(t,e,s,a,i),getRunData:()=>({outputs:[{dims:s,dataType:i}],dispatchGroup:{x:Math.ceil(o/64/4)},programUniforms:[{type:12,data:l},...It(r,t,n,s)]})}},Cl=e=>{e.compute($l(e.inputs))}})),id=j((()=>{du(),cu(),pu(),hu(),fu(),gu(),_u(),$u(),Pu(),Eu(),Fu(),Au(),Iu(),zu(),Ou(),Bu(),Lu(),Nu(),Du(),ju(),qu(),Gu(),Wu(),Uu(),Ru(),Hu(),Xu(),Ku(),Qu(),uu(),Yu(),Zu(),Ju(),ed(),td(),Vu(),nd(),ou(),mu(),rd(),Sl=new Map([["Abs",[mr]],["Acos",[fr]],["Acosh",[gr]],["Add",[ui]],["ArgMax",[Kn,Qn]],["ArgMin",[Xn,Qn]],["Asin",[_r]],["Asinh",[wr]],["Atan",[br]],["Atanh",[yr]],["Attention",[ir]],["AveragePool",[xo,yo]],["BatchNormalization",[lr]],["BiasAdd",[cr]],["BiasSplitGelu",[ai]],["Cast",[vr,xr]],["Ceil",[kr]],["Clip",[Tr]],["Concat",[Mi,Ti]],["Conv",[la,ia]],["ConvTranspose",[va,_a]],["Cos",[$r]],["Cosh",[Cr]],["CumSum",[Ta,ka]],["DepthToSpace",[Pa,Ea]],["DequantizeLinear",[Ao,Io]],["Div",[di]],["Einsum",[Da,Ra]],["Elu",[Pr,Sr]],["Equal",[ci]],["Erf",[Fr]],["Exp",[Ar]],["Expand",[Wa]],["FastGelu",[Ha]],["Floor",[Ir]],["FusedConv",[la,ia]],["Gather",[Ya,Qa]],["GatherElements",[as,is]],["GatherBlockQuantized",[es,ts]],["Gelu",[zr]],["Gemm",[us,ls]],["GlobalAveragePool",[To,Mo]],["GlobalMaxPool",[Po,So]],["Greater",[fi]],["GreaterOrEqual",[_i]],["GridSample",[xs,vs]],["GroupQueryAttention",[Rs]],["HardSigmoid",[jr,Vr]],["InstanceNormalization",[Gs]],["LayerNormalization",[Hs]],["LeakyRelu",[Or,Sr]],["Less",[gi]],["LessOrEqual",[wi]],["Log",[Jr]],["MatMul",[Ks]],["MatMulNBits",[Js,eo]],["MaxPool",[$o,Co]],["Mul",[pi]],["MultiHeadAttention",[Ps,ks]],["Neg",[Lr]],["Not",[Br]],["Pad",[uo]],["Pow",[hi]],["QuickGelu",[ni,Sr]],["Range",[Bo]],["Reciprocal",[Nr]],["ReduceMin",[jn]],["ReduceMean",[Ln]],["ReduceMax",[Vn]],["ReduceSum",[Gn]],["ReduceProd",[qn]],["ReduceL1",[Nn]],["ReduceL2",[Dn]],["ReduceLogSum",[Un]],["ReduceLogSumExp",[Rn]],["ReduceSumSquare",[Wn]],["Relu",[Dr]],["Resize",[el,tl]],["RotaryEmbedding",[il]],["Sigmoid",[Rr]],["Sin",[qr]],["Sinh",[Gr]],["Slice",[ml,fl]],["SkipLayerNormalization",[ol]],["Split",[Os,Bs]],["Sqrt",[Wr]],["Softmax",[wl,bl]],["Sub",[mi]],["Tan",[Ur]],["Tanh",[Xr]],["ThresholdedRelu",[Zr,Sr]],["Tile",[Tl]],["Transpose",[Yt,Zt]],["Where",[Cl]]])})),ad=j((()=>{pe(),eu(),su(),Pl=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n,r,i){F(e.programInfo.name);let a=this.backend.device,s=this.backend.getComputePassEncoder();this.backend.writeTimestamp(2*this.backend.pendingDispatchNumber);let o=[];for(let e of t)o.push({binding:o.length,resource:{buffer:e.buffer}});for(let e of n)o.push({binding:o.length,resource:{buffer:e.buffer}});i&&o.push({binding:o.length,resource:i});let l=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:o,label:e.programInfo.name});if("capturing"===this.backend.sessionStatus){let t={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:r};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(t)}s.setPipeline(e.computePipeline),s.setBindGroup(0,l),s.dispatchWorkgroups(...r),this.backend.writeTimestamp(2*this.backend.pendingDispatchNumber+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||"at-passes"===this.backend.queryType)&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),A(e.programInfo.name)}dispose(){}build(e,t){F(e.name);let n=this.backend.device,r=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"},{feature:"subgroups-f16",extension:"subgroups_f16"}].forEach((e=>{n.features.has(e.feature)&&r.push(`enable ${e.extension};`)}));let i=Gt(t,this.backend.device.limits),a=e.getShaderSource(i),s=`${r.join("\n")}\n${i.additionalImplementations}\n${a}`,o=n.createShaderModule({code:s,label:e.name});ut("verbose",(()=>`[WebGPU] ${e.name} shader code: ${s}`));let l=n.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:e.name});return A(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(e){let t="number"==typeof e?e:e.x,n="number"==typeof e?1:e.y||1,r="number"==typeof e?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&n<=i&&r<=i)return[t,n,r];let a=t*n*r,s=Math.ceil(Math.sqrt(a));if(s>i){if(s=Math.ceil(Math.cbrt(a)),s>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[s,s,s]}return[s,s,1]}}})),sd=j((()=>{pe(),Zl(),eu(),tu(),ru(),id(),ad(),El=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let r=0;r{let r=e.name;return e.shaderCache?.hint&&(r+="["+e.shaderCache.hint+"]"),r+=":"+n+`:${El(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,r},Al=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Il=class{constructor(e){this.subgroupsSupported=e.features.has("subgroups"),this.subgroupsF16Supported=e.features.has("subgroups");let t=e.limits;this.subgroupsSupported&&t.minSubgroupSize&&t.maxSubgroupSize?this.subgroupSizeRange=[t.minSubgroupSize,t.maxSubgroupSize]:this.subgroupSizeRange=void 0}},zl=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(null===this.currentKernelId)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let n=[],r={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},i=e=>t.features.has(e)&&n.push(e)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups")&&i("subgroups-f16"),this.device=await t.requestDevice(r),this.deviceInfo=new Il(this.device),this.adapterInfo=new Al(t.info||await t.requestAdapterInfo()),this.gpuDataManager=bt(this),this.programManager=new Pl(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ot(e.logLevel,!!e.debug),this.device.onuncapturederror=e=>{e.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${e.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};"at-passes"===this.queryType&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:2*this.pendingDispatchNumber,endOfPassWriteIndex:2*this.pendingDispatchNumber+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;let e;F(),this.endComputePass(),"none"!==this.queryType&&(this.commandEncoder.resolveQuerySet(this.querySet,0,2*this.pendingDispatchNumber,this.queryResolveBuffer,0),e=this.device.createBuffer({size:2*this.pendingDispatchNumber*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,2*this.pendingDispatchNumber*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,"none"!==this.queryType&&e.mapAsync(GPUMapMode.READ).then((()=>{let t=new BigUint64Array(e.getMappedRange()),n=this.pendingQueries.get(e);for(let e=0;e"u"&&(this.queryTimeBase=c);let h=Number(c-this.queryTimeBase),m=Number(p-this.queryTimeBase);if(!Number.isSafeInteger(h)||!Number.isSafeInteger(m))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:u.map((e=>({dims:e.dims,dataType:Ke(e.dataType)}))),outputsMetadata:d.map((e=>({dims:e.dims,dataType:Ke(e.dataType)}))),kernelId:i,kernelType:s,kernelName:o,programName:l,startTime:h,endTime:m});else{let e="";u.forEach(((t,n)=>{e+=`input[${n}]: [${t.dims}] | ${Ke(t.dataType)}, `}));let t="";d.forEach(((e,n)=>{t+=`output[${n}]: [${e.dims}] | ${Ke(e.dataType)}, `})),console.log(`[profiling] kernel "${i}|${s}|${o}|${l}" ${e}${t}execution time: ${m-h} ns`)}P("GPU",`${l}::${c}::${p}`)}e.unmap(),this.pendingQueries.delete(e)})),A()}run(e,t,n,r,i,a){F(e.name);let s=[];for(let e=0;et)):n;if(d.length!==o.length)throw new Error(`Output size ${d.length} must be equal to ${o.length}.`);let c,p=[],h=[];for(let e=0;e=a)throw new Error(`Invalid output index: ${d[e]}`);if(-3===d[e])continue;let t=-1===d[e],n=-2===d[e],s=t||n?i(o[e].dataType,o[e].dims):r(d[e],o[e].dataType,o[e].dims);if(p.push(s),0===s.data)continue;let l=this.gpuDataManager.get(s.data);if(!l)throw new Error(`no GPU data for output: ${s.data}`);if(t&&this.temporaryData.push(l),n){let e=this.kernelPersistentData.get(this.currentKernelId);e||(e=[],this.kernelPersistentData.set(this.currentKernelId,e)),e.push(l)}h.push(l)}if(s.length!==t.length||h.length!==p.length){if(0===h.length)return A(e.name),p;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}if(u){let e=0,t=[];u.forEach((n=>{let r="number"==typeof n.data?[n.data]:n.data;if(0===r.length)return;let i,a,s=10===n.type?2:4;10===n.type?(a=r.length>4?16:r.length>2?8:r.length*s,i=r.length>4?16:s*r.length):(a=r.length<=2?r.length*s:16,i=16),e=Math.ceil(e/a)*a,t.push(e);let o=10===n.type?8:4;e+=r.length>4?Math.ceil(r.length/o)*i:r.length*s}));let n=16;e=Math.ceil(e/n)*n;let r=new ArrayBuffer(e);u.forEach(((e,n)=>{let i=t[n],a="number"==typeof e.data?[e.data]:e.data;if(6===e.type)new Int32Array(r,i,a.length).set(a);else if(12===e.type)new Uint32Array(r,i,a.length).set(a);else if(10===e.type)new Uint16Array(r,i,a.length).set(a);else{if(1!==e.type)throw new Error(`Unsupported uniform type: ${Ke(e.type)}`);new Float32Array(r,i,a.length).set(a)}}));let i=this.gpuDataManager.create(e,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(i.buffer,0,r,0,e),this.gpuDataManager.release(i.id),c={offset:0,size:e,buffer:i.buffer}}let m=this.programManager.normalizeDispatchGroupSize(l),f=1===m[1]&&1===m[2],g=Fl(e,t,f),_=this.programManager.getArtifact(g);if(_||(_=this.programManager.build(e,m),this.programManager.setArtifact(g,_),ut("info",(()=>`[artifact] key: ${g}, programName: ${e.name}`))),u&&_.uniformVariablesInfo){if(u.length!==_.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${_.uniformVariablesInfo.length}, got ${u.length} in program "${_.programInfo.name}".`);for(let e=0;e`[ProgramManager] run "${e.name}" (key=${g}) with ${m[0]}x${m[1]}x${m[2]}`)),"none"!==this.queryType||"capturing"===this.sessionStatus){let e={kernelId:this.currentKernelId,programName:_.programInfo.name,inputTensorViews:t,outputTensorViews:p};this.pendingKernels.push(e),"capturing"===this.sessionStatus&&this.capturedPendingKernels.get(this.currentSessionId).push(e)}return this.programManager.run(_,s,h,m,c),A(e.name),p}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,n,r){let i=Sl.get(e);if(!i)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:r,kernelEntry:i[0],attributes:[i[1],n]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let e of t)this.gpuDataManager.release(e.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let r=this.kernels.get(e);if(!r)throw new Error(`kernel not created: ${e}`);let i=r.kernelType,a=r.kernelName,s=r.kernelEntry,o=r.attributes;if(null!==this.currentKernelId)throw new Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,o[0]&&(o[1]=o[0](o[1]),o[0]=void 0),ut("info",(()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`));let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),s(t,o[1]),0}catch(e){return n.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${e}`)),1}finally{l&&n.push(this.device.popErrorScope().then((e=>e?`GPU validation error for kernel "[${i}] ${a}": ${e.message}`:null)));for(let e of this.temporaryData)this.gpuDataManager.release(e.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,r){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let a=i.get(t),s=this.gpuDataManager.registerExternalBuffer(n,r,a);return i.set(t,[s,n]),s}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach((e=>this.gpuDataManager.unregisterExternalBuffer(e[0]))),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,n){return async()=>{let r=await _t(this,e,t);return dt(r.buffer,n)}}writeTimestamp(e){"inside-passes"===this.queryType&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType="none",("default"===this.env.webgpu.profiling?.mode||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),"none"!==this.queryType&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:2*this.maxDispatchNumber}),this.queryResolveBuffer=this.device.createBuffer({size:2*this.maxDispatchNumber*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){ut("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){ut("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){ut("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),n=e.length;this.pendingKernels=[];for(let r=0;r=this.maxDispatchNumber||"at-passes"===this.queryType)&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}})),od=j((()=>{eu(),Ol=1,Bl=()=>Ol++,Ll=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Nl=(e,t)=>{let n=Ll.get(e);if(!n)throw new Error("Unsupported data type.");return Math.ceil(t.reduce(((e,t)=>e*t))*n/8)},Dl=class{constructor(e){this.sessionId=e.sessionId,this.mlContext=e.context,this.mlTensor=e.tensor,this.dataType=e.dataType,this.tensorShape=e.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Nl(this.dataType,this.tensorShape)}destroy(){ut("verbose",(()=>"[WebNN] TensorWrapper.destroy")),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}sameTypeAndShape(e,t){return this.dataType===e&&this.tensorShape.length===t.length&&this.tensorShape.every(((e,n)=>e===t[n]))}},Rl=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n){if(this.wrapper){if(this.wrapper.sameTypeAndShape(e,t))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==Nl(e,t))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let r=MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,r,!0,!0),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper){if(e.byteLength===this.wrapper.byteLength)return void this.wrapper.write(e);ut("verbose",(()=>"Data size does not match tensor size. Releasing tensor.")),this.releaseTensor()}this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(e){if(this.activeUpload)return e?void(e instanceof ArrayBuffer?new Uint8Array(e).set(this.activeUpload):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(this.activeUpload)):this.activeUpload.buffer;if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Vl=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}reserveTensorId(){let e=Bl();return this.tensorTrackersById.set(e,new Rl(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,r){ut("verbose",(()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${n}, copyOld: ${r}}`));let i=this.tensorTrackersById.get(e);if(!i)throw new Error("Tensor not found.");return i.ensureTensor(t,n,r)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");n.upload(t)}async download(e,t){ut("verbose",(()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`));let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter((t=>t.sessionId!==e))}registerTensor(e,t,n,r){let i=Bl(),a=new Dl({sessionId:this.backend.currentSessionId,context:e,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(i,new Rl(this,a)),this.externalTensors.add(a),i}async getCachedTensor(e,t,n,r,i){let a=this.backend.currentSessionId;for(let[n,r]of this.freeTensors.entries())if(r.sameTypeAndShape(e,t)){ut("verbose",(()=>`[WebNN] Reusing tensor {dataType: ${e}, shape: ${t}}`));let r=this.freeTensors.splice(n,1)[0];return r.sessionId=a,r}let s=this.backend.currentContext;ut("verbose",(()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`));let o=await s.createTensor({dataType:e,shape:t,dimensions:t,usage:n,writable:r,readable:i});return new Dl({sessionId:a,context:s,tensor:o,dataType:e,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},jl=(...e)=>new Vl(...e)})),ld=j((()=>{Zl(),Xl(),tu(),od(),eu(),ql=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Gl=(e,t)=>{if(e===t)return!0;if(void 0===e||void 0===t)return!1;let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every(((n,i)=>n===r[i]&&e[n]===t[n]))},Wl=class{constructor(e){this.tensorManager=jl(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],ot(e.logLevel,!!e.debug)}get currentSessionId(){if(void 0===this.activeSessionId)throw new Error("No active session");return this.activeSessionId}onRunStart(e){this.activeSessionId=e}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex((t=>t.gpuDevice===e));if(-1!==t)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:t}),t}}if(void 0===e){let e=this.mlContextCache.findIndex((e=>void 0===e.options&&void 0===e.gpuDevice));if(-1!==e)return this.mlContextCache[e].mlContext;{let e=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:e}),e}}let t=this.mlContextCache.findIndex((t=>Gl(t.options,e)));if(-1!==t)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}get currentContext(){let e=this.getMLContext(this.currentSessionId);if(!e)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return e}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e)}onReleaseSession(e){let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),0===n.size){this.sessionIdsByMLContext.delete(t);let e=this.mlContextCache.findIndex((e=>e.mlContext===t));-1!==e&&this.mlContextCache.splice(e,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){ut("verbose",(()=>`[WebNN] releaseTensorId {tensorId: ${e}}`)),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r){let i=ql.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,i,n,r)}uploadTensor(e,t){if(!Ne().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");ut("verbose",(()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`)),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return dt(n,t)}}registerMLTensor(e,t,n){let r=ql.get(t);if(!r)throw new Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.registerTensor(this.currentContext,e,r,n);return ut("verbose",(()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${r}, dimensions: ${n}} -> {tensorId: ${i}}`)),i}registerMLConstant(e,t,n,r,i,a){if(!a)throw new Error("External mounted files are not available.");let s=e;e.startsWith("./")&&(s=e.substring(2));let o=a.get(s);if(!o)throw new Error(`File with name ${s} not found in preloaded files.`);if(t+n>o.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let l,u=o.slice(t,t+n).buffer;switch(i.dataType){case"float32":l=new Float32Array(u);break;case"float16":l=new Uint16Array(u);break;case"int32":l=new Int32Array(u);break;case"uint32":l=new Uint32Array(u);break;case"int64":l=new BigInt64Array(u);break;case"uint64":l=new BigUint64Array(u);break;case"int8":l=new Int8Array(u);break;case"int4":case"uint4":case"uint8":l=new Uint8Array(u);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return ut("verbose",(()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`)),r.constant(i,l)}flush(){}}})),ud={};q(ud,{init:()=>pd});var dd,cd,pd,hd,md,fd,gd,_d,wd,bd,yd,xd,vd,Md,Td,kd,$d,Cd,Sd,Pd,Ed,Fd,Ad,Id,zd,Od,Bd,Ld,Nd,Dd,Rd,Vd,jd,qd,Gd,Wd,Ud=j((()=>{Zl(),sd(),eu(),au(),ld(),dd=class e{constructor(e,t,n,r){this.module=e,this.dataType=t,this.data=n,this.dims=r}getFloat32Array(){if(1!==this.dataType)throw new Error("Invalid data type");let e=Tt.size(this.dims);return 0===e?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(7!==this.dataType)throw new Error("Invalid data type");let e=Tt.size(this.dims);return 0===e?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(6!==this.dataType)throw new Error("Invalid data type");let e=Tt.size(this.dims);return 0===e?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}getUint16Array(){if(10!==this.dataType&&4!==this.dataType)throw new Error("Invalid data type");let e=Tt.size(this.dims);return 0===e?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(t){if(Tt.size(t)!==Tt.size(this.dims))throw new Error("Invalid new shape");return new e(this.module,this.dataType,this.data,t)}},cd=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo,this.deviceInfo=t.deviceInfo;let r=e.PTR_SIZE,i=n/e.PTR_SIZE,a=4===r?"i32":"i64";this.opKernelContext=Number(e.getValue(r*i++,a));let s=Number(e.getValue(r*i++,a));this.outputCount=Number(e.getValue(r*i++,a)),this.customDataOffset=Number(e.getValue(r*i++,"*")),this.customDataSize=Number(e.getValue(r*i++,a));let o=[];for(let t=0;t"number"==typeof e?this.inputs[e]:e))??this.inputs,r=t?.outputs??[];return this.backend.run(e,n,r,((e,t,n)=>new dd(this.module,t,this.output(e,n),n)),((e,t)=>{let n=Qe(e,t);if(!n)throw new Error(`Unsupported data type: ${e}`);let r=n>0?this.backend.gpuDataManager.create(n).id:0;return new dd(this.module,e,r,t)}),this.outputCount)}output(e,t){let n=this.module.stackSave();try{let n=this.module.PTR_SIZE,r=4===n?"i32":"i64",i=this.module.stackAlloc((1+t.length)*n);this.module.setValue(i,t.length,r);for(let e=0;e{let i=t.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if("webgpu"===e){let e=new zl;await e.initialize(n,r),i("webgpu",[e,t=>e.alloc(Number(t)),t=>e.free(t),(n,r,i,a=!1)=>{if(a)ut("verbose",(()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(n)}, dst=${Number(r)}, size=${Number(i)}`)),e.memcpy(Number(n),Number(r));else{ut("verbose",(()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(n)}, gpuDataId=${Number(r)}, size=${Number(i)}`));let a=t.HEAPU8.subarray(Number(n>>>0),Number(n>>>0)+Number(i));e.upload(Number(r),a)}},async(n,r,i)=>{ut("verbose",(()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${n}, dataOffset=${r}, size=${i}`)),await e.download(Number(n),(()=>t.HEAPU8.subarray(Number(r)>>>0,Number(r+i)>>>0)))},(n,r,i)=>e.createKernel(n,Number(r),i,t.UTF8ToString(t._JsepGetNodeName(Number(r)))),t=>e.releaseKernel(t),(n,r,i,a)=>{ut("verbose",(()=>`[WebGPU] jsepRun: sessionHandle=${i}, kernel=${n}, contextDataOffset=${r}`));let s=new cd(t,e,Number(r));return e.computeKernel(Number(n),s,a)},()=>e.captureBegin(),()=>e.captureEnd(),()=>e.replay()])}else{let e=new Wl(n);i("webnn",[e,()=>e.reserveTensorId(),t=>e.releaseTensorId(t),async(t,n,r,i)=>e.ensureTensor(t,n,r,i),(t,n)=>{e.uploadTensor(t,n)},async(t,n)=>e.downloadTensor(t,n)])}}})),Hd=j((()=>{Ql(),Yl(),Zl(),Xl(),Kl(),Jl(),hd=(e,t)=>{0!==Ne()._OrtInit(e,t)&&Ve("Can't initialize onnxruntime.")},md=async e=>{hd(e.wasm.numThreads,Ze(e.logLevel))},fd=async(e,t)=>{{let n=(Ud(),G(ud)).init;if("webgpu"===t){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let t=e.webgpu.adapter;if(t){if("object"!=typeof t.limits||"object"!=typeof t.features||"function"!=typeof t.requestDevice)throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let n=e.webgpu.powerPreference;if(void 0!==n&&"low-power"!==n&&"high-performance"!==n)throw new Error(`Invalid powerPreference setting: "${n}"`);let r=e.webgpu.forceFallbackAdapter;if(void 0!==r&&"boolean"!=typeof r)throw new Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(t=await navigator.gpu.requestAdapter({powerPreference:n,forceFallbackAdapter:r}),!t)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await n("webgpu",Ne(),e,t)}if("webnn"===t){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await n("webnn",Ne(),e)}}},gd=new Map,_d=e=>{let t=Ne(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);0!==t._OrtGetInputOutputCount(e,r,r+n)&&Ve("Can't get session input/output count.");let i=4===n?"i32":"i64";return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},wd=e=>{let t=Ne(),n=t._malloc(e.byteLength);if(0===n)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},bd=async(e,t)=>{let n,r,i=Ne();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=wd(e);let a=0,s=0,o=0,l=[],u=[],d=[];try{if([s,l]=He(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t="string"==typeof n?n:n.path;e.push(nt("string"==typeof n?n:n.data).then((e=>{i.mountExternalData(t,e)})))}await Promise.all(e)}for(let e of t?.executionProviders??[])if("webnn"===("string"==typeof e?e:e.name)){if(i.shouldTransferToMLTensor=!1,i.currentContext)throw new Error("WebNN execution provider is already set.");if("string"!=typeof e){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,s=t?.powerPreference;i.currentContext=n||(r?await i.jsepCreateMLContext(r):await i.jsepCreateMLContext({deviceType:a,powerPreference:s}))}else i.currentContext=await i.jsepCreateMLContext();break}a=await i._OrtCreateSession(n,r,s),0===a&&Ve("Can't create a session."),i.jsepOnCreateSession?.(),i.currentContext&&(i.jsepRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,c]=_d(a),p=!!t?.enableGraphCapture,h=[],m=[],f=[];for(let t=0;t"gpu-buffer"===e||"ml-tensor"===e))&&(o=i._OrtCreateBinding(a),0===o&&Ve("Can't create IO binding."),g={handle:o,outputPreferredLocations:f,outputPreferredLocationsEncoded:f.map((e=>tt(e)))}),gd.set(a,[a,u,d,g,p,!1]),[a,h,m]}catch(e){throw u.forEach((e=>i._OrtFree(e))),d.forEach((e=>i._OrtFree(e))),0!==o&&0!==i._OrtReleaseBinding(o)&&Ve("Can't release IO binding."),0!==a&&0!==i._OrtReleaseSession(a)&&Ve("Can't release session."),e}finally{i._free(n),0!==s&&0!==i._OrtReleaseSessionOptions(s)&&Ve("Can't release session options."),l.forEach((e=>i._free(e))),i.unmountExternalData?.()}},yd=e=>{let t=Ne(),n=gd.get(e);if(!n)throw new Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,s,o]=n;s&&(o&&0!==t._OrtClearBoundOutputs(s.handle)&&Ve("Can't clear bound outputs."),0!==t._OrtReleaseBinding(s.handle)&&Ve("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),i.forEach((e=>t._OrtFree(e))),a.forEach((e=>t._OrtFree(e))),0!==t._OrtReleaseSession(r)&&Ve("Can't release session."),gd.delete(e)},xd=(e,t,n,r,i,a=!1)=>{if(!e)return void t.push(0);let s,o,l=Ne(),u=l.PTR_SIZE,d=e[0],c=e[1],p=e[3];if("string"===d&&("gpu-buffer"===p||"ml-tensor"===p))throw new Error("String tensor is not supported on GPU.");if(a&&"gpu-buffer"!==p)throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if("gpu-buffer"===p){let t=e[2].gpuBuffer;o=Qe(Xe(d),c);let n=l.jsepRegisterBuffer;if(!n)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');s=n(r,i,t,o)}else if("ml-tensor"===p){let t=e[2].mlTensor;o=Qe(Xe(d),c);let n=l.jsepRegisterMLTensor;if(!n)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');s=n(t,Xe(d),c)}else{let t=e[2];if(Array.isArray(t)){o=u*t.length,s=l._malloc(o),n.push(s);for(let e=0;el.setValue(m+t*u,e,4===u?"i32":"i64")));let e=l._OrtCreateTensor(Xe(d),s,o,m,c.length,tt(p));0===e&&Ve(`Can't create tensor for input/output. session=${r}, index=${i}.`),t.push(e)}finally{l.stackRestore(h)}},vd=async(e,t,n,r,i,a)=>{let s=Ne(),o=s.PTR_SIZE,l=gd.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let u=l[0],d=l[1],c=l[2],p=l[3],h=l[4],m=l[5],f=t.length,g=r.length,_=0,w=[],b=[],y=[],x=[],v=s.stackSave(),M=s.stackAlloc(f*o),T=s.stackAlloc(f*o),k=s.stackAlloc(g*o),$=s.stackAlloc(g*o);try{s.jsepOnRunStart?.(u),[_,w]=je(a);for(let r=0;re*t),1);n=Ke(a);let g=p?.outputPreferredLocations[r[e]];if("string"===n){if("gpu-buffer"===g||"ml-tensor"===g)throw new Error("String tensor is not supported on GPU.");let e=[];for(let t=0;t0){let e=s.jsepGetBuffer;if(!e)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let r=e(d),i=Qe(a,f);if(void 0===i||!Je(n))throw new Error(`Unsupported data type: ${n}`);u=!0,v.push([n,m,{gpuBuffer:r,download:s.jsepCreateDownloader(r,i,n),dispose:()=>{0!==s._OrtReleaseTensor(t)&&Ve("Can't release tensor.")}},"gpu-buffer"])}else if("ml-tensor"===g&&f>0){let e=s.jsepEnsureTensor;if(!e)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(void 0===Qe(a,f)||!et(n))throw new Error(`Unsupported data type: ${n}`);let r=await e(d,a,m,!1);u=!0,v.push([n,m,{mlTensor:r,download:s.jsepCreateMLTensorDownloader(d,n),dispose:()=>{s.jsepReleaseTensorId(d),s._OrtReleaseTensor(t)}},"ml-tensor"])}else{let e=new(Ye(n))(f);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(s.HEAPU8.subarray(d,d+e.byteLength)),v.push([n,m,e,"cpu"])}}finally{s.stackRestore(a),"string"===n&&d&&s._free(d),u||s._OrtReleaseTensor(t)}}return p&&!h&&(0!==s._OrtClearBoundOutputs(p.handle)&&Ve("Can't clear bound outputs."),gd.set(e,[u,d,c,p,h,!1])),v}finally{s.stackRestore(v),b.forEach((e=>s._OrtReleaseTensor(e))),y.forEach((e=>s._OrtReleaseTensor(e))),x.forEach((e=>s._free(e))),0!==_&&s._OrtReleaseRunOptions(_),w.forEach((e=>s._free(e)))}},Md=e=>{let t=Ne(),n=gd.get(e);if(!n)throw new Error("invalid session id");let r=n[0],i=t._OrtEndProfiling(r);0===i&&Ve("Can't get an profile file name."),t._OrtFree(i)},Td=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&"buffer"in e&&t.push(e.buffer)}return t}})),Xd=j((()=>{pe(),Hd(),Xl(),Hl(),kd=()=>!!p.wasm.proxy&&typeof document<"u",Cd=!1,Sd=!1,Pd=!1,Ad=new Map,Id=(e,t)=>{let n=Ad.get(e);n?n.push(t):Ad.set(e,[t])},zd=()=>{if(Cd||!Sd||Pd||!$d)throw new Error("worker not ready")},Od=e=>{switch(e.data.type){case"init-wasm":Cd=!1,e.data.err?(Pd=!0,Fd[1](e.data.err)):(Sd=!0,Fd[0]()),Ed&&(URL.revokeObjectURL(Ed),Ed=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Ad.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Bd=async()=>{if(!Sd){if(Cd)throw new Error("multiple calls to 'initWasm()' detected.");if(Pd)throw new Error("previous call to 'initWasm()' failed.");if(Cd=!0,kd())return new Promise(((e,t)=>{$d?.terminate(),Se().then((([n,r])=>{try{($d=r).onerror=e=>t(e),$d.onmessage=Od,Fd=[e,t];let i={type:"init-wasm",in:p};$d.postMessage(i),Ed=n}catch(e){t(e)}}),t)}));try{await Le(p.wasm),await md(p),Sd=!0}catch(e){throw Pd=!0,e}finally{Cd=!1}}},Ld=async e=>{if(kd())return zd(),new Promise(((t,n)=>{Id("init-ep",[t,n]);let r={type:"init-ep",in:{epName:e,env:p}};$d.postMessage(r)}));await fd(p,e)},Nd=async e=>kd()?(zd(),new Promise(((t,n)=>{Id("copy-from",[t,n]);let r={type:"copy-from",in:{buffer:e}};$d.postMessage(r,[e.buffer])}))):wd(e),Dd=async(e,t)=>{if(kd()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return zd(),new Promise(((n,r)=>{Id("create",[n,r]);let i={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),$d.postMessage(i,a)}))}return bd(e,t)},Rd=async e=>{if(kd())return zd(),new Promise(((t,n)=>{Id("release",[t,n]);let r={type:"release",in:e};$d.postMessage(r)}));yd(e)},Vd=async(e,t,n,r,i,a)=>{if(kd()){if(n.some((e=>"cpu"!==e[3])))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some((e=>e)))throw new Error("pre-allocated output tensor is not supported for proxy.");return zd(),new Promise(((i,s)=>{Id("run",[i,s]);let o=n,l={type:"run",in:{sessionId:e,inputIndices:t,inputs:o,outputIndices:r,options:a}};$d.postMessage(l,Td(o))}))}return vd(e,t,n,r,i,a)},jd=async e=>{if(kd())return zd(),new Promise(((t,n)=>{Id("end-profiling",[t,n]);let r={type:"end-profiling",in:e};$d.postMessage(r)}));Md(e)}})),Kd=j((()=>{pe(),Xd(),Zl(),he(),Jl(),qd=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},Gd=e=>{switch(e[3]){case"cpu":return new S(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Je(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return S.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case"ml-tensor":{let t=e[0];if(!et(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return S.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw new Error(`invalid data location: ${e[3]}`)}},Wd=class{async fetchModelAndCopyToWasmMemory(e){return Nd(await nt(e))}async loadModel(e,t){let n;F(),n="string"==typeof e?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames]=await Dd(n,t),A()}async dispose(){return Rd(this.sessionId)}async run(e,t,n){F();let r=[],i=[];Object.entries(e).forEach((e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(-1===a)throw new Error(`invalid input '${t}'`);r.push(n),i.push(a)}));let a=[],s=[];Object.entries(t).forEach((e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(-1===r)throw new Error(`invalid output '${t}'`);a.push(n),s.push(r)}));let o=r.map(((e,t)=>qd(e,(()=>`input "${this.inputNames[i[t]]}"`)))),l=a.map(((e,t)=>e?qd(e,(()=>`output "${this.outputNames[s[t]]}"`)):null)),u=await Vd(this.sessionId,i,o,s,l,n),d={};for(let e=0;eZd,initializeFlags:()=>Yd,wasmBackend:()=>Jd});var Yd,Zd,Jd,ec=j((()=>{pe(),Xd(),Kd(),Hl(),Yd=()=>{if(("number"!=typeof p.wasm.initTimeout||p.wasm.initTimeout<0)&&(p.wasm.initTimeout=0),!1===p.wasm.simd&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),"boolean"!=typeof p.wasm.proxy&&(p.wasm.proxy=!1),"boolean"!=typeof p.wasm.trace&&(p.wasm.trace=!1),"number"!=typeof p.wasm.numThreads||!Number.isInteger(p.wasm.numThreads)||p.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)p.wasm.numThreads=1;else{let e=typeof navigator>"u"?V("node:os").cpus().length:navigator.hardwareConcurrency;p.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Jd=new(Zd=class{async init(e){Yd(),await Bd(),await Ld(e)}async createInferenceSessionHandler(e,t){let n=new Wd;return await n.loadModel(e,t),Promise.resolve(n)}})}));pe(),pe(),pe();var tc=ce;{let e=(ec(),G(Qd)).wasmBackend;s("webgpu",e,5),s("webnn",e,5),s("cpu",e,10),s("wasm",e,10)}Object.defineProperty(p.versions,"web",{value:"1.21.0-dev.20241109-d3ad76b2cf",enumerable:!0})} +var r,i,a,s,o,l,u,d,c,p,h,m,f,g,_,w,b,y,x,v,M,T,k,$,S,C,E,P,F,A,I,z,O,B,L=Object.defineProperty,N=Object.getOwnPropertyDescriptor,D=Object.getOwnPropertyNames,R=Object.prototype.hasOwnProperty,V=(r=function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')},typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r),j=(e,t)=>()=>(e&&(t=e(e=0)),t),q=(e,t)=>{for(var n in t)L(e,n,{get:t[n],enumerable:!0})},G=e=>((e,t,n,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of D(t))!R.call(e,i)&&i!==n&&L(e,i,{get:()=>t[i],enumerable:!(r=N(t,i))||r.enumerable});return e})(L({},"__esModule",{value:!0}),e),U=j((()=>{i=new Map,a=[],s=(e,t,n)=>{if(!t||"function"!=typeof t.init||"function"!=typeof t.createInferenceSessionHandler)throw new TypeError("not a valid backend");{let r=i.get(e);if(void 0===r)i.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let t=a.indexOf(e);-1!==t&&a.splice(t,1);for(let t=0;t{let t=i.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},l=async e=>{let t,n=e.executionProviders||[],r=n.map((e=>"string"==typeof e?e:e.name)),i=0===r.length?a:r,s=[],l=new Set;for(let e of i){let n=await o(e);"string"==typeof n?s.push({name:e,err:n}):(t||(t=n),t===n&&l.add(e))}if(!t)throw new Error(`no available backend found. ERR: ${s.map((e=>`[${e.name}] ${e.err}`)).join(", ")}`);for(let{name:e,err:t}of s)r.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let u=n.filter((e=>l.has("string"==typeof e?e:e.name)));return[t,new Proxy(e,{get:(e,t)=>"executionProviders"===t?u:Reflect.get(e,t)})]}})),W=j((()=>{U()})),H=j((()=>{u="1.21.0-dev.20241026-05fbb43b34"})),K=j((()=>{H(),d="warning",c={wasm:{},webgl:{},webgpu:{},versions:{common:u},set logLevel(e){if(void 0!==e){if("string"!=typeof e||-1===["verbose","info","warning","error","fatal"].indexOf(e))throw new Error(`Unsupported logging level: ${e}`);d=e}},get logLevel(){return d}},Object.defineProperty(c,"logLevel",{enumerable:!0})})),X=j((()=>{K(),p=c})),Q=j((()=>{h=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext("2d");if(null!=r){let i,a;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let s,o,l=void 0!==t?.format?t.format:"RGB",u=t?.norm;void 0===u||void 0===u.mean?s=[255,255,255,255]:"number"==typeof u.mean?s=[u.mean,u.mean,u.mean,u.mean]:(s=[u.mean[0],u.mean[1],u.mean[2],0],void 0!==u.mean[3]&&(s[3]=u.mean[3])),void 0===u||void 0===u.bias?o=[0,0,0,0]:"number"==typeof u.bias?o=[u.bias,u.bias,u.bias,u.bias]:(o=[u.bias[0],u.bias[1],u.bias[2],0],void 0!==u.bias[3]&&(o[3]=u.bias[3]));let d=a*i,c=0,p=d,h=2*d,m=-1;"RGBA"===l?(c=0,p=d,h=2*d,m=3*d):"RGB"===l?(c=0,p=d,h=2*d):"RBG"===l&&(c=0,h=d,p=2*d);for(let t=0;t{let n,r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");if(null==r)throw new Error("Can not access image data");{let i,a,s;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(i=e.dims[2],a=e.dims[1],s=e.dims[3]):(i=e.dims[3],a=e.dims[2],s=e.dims[1]);let o,l,u=void 0!==t&&void 0!==t.format?t.format:"RGB",d=t?.norm;void 0===d||void 0===d.mean?o=[255,255,255,255]:"number"==typeof d.mean?o=[d.mean,d.mean,d.mean,d.mean]:(o=[d.mean[0],d.mean[1],d.mean[2],255],void 0!==d.mean[3]&&(o[3]=d.mean[3])),void 0===d||void 0===d.bias?l=[0,0,0,0]:"number"==typeof d.bias?l=[d.bias,d.bias,d.bias,d.bias]:(l=[d.bias[0],d.bias[1],d.bias[2],0],void 0!==d.bias[3]&&(l[3]=d.bias[3]));let c=a*i;if(void 0!==t&&(void 0!==t.format&&4===s&&"RGBA"!==t.format||3===s&&"RGB"!==t.format&&"BGR"!==t.format))throw new Error("Tensor format doesn't match input tensor dims");let p=4,h=0,m=1,f=2,g=3,_=0,w=c,b=2*c,y=-1;"RGBA"===u?(_=0,w=c,b=2*c,y=3*c):"RGB"===u?(_=0,w=c,b=2*c):"RBG"===u&&(_=0,b=c,w=2*c),n=r.createImageData(i,a);for(let t=0;t{ee(),f=(e,t)=>{if(void 0===e)throw new Error("Image buffer must be defined");if(void 0===t.height||void 0===t.width)throw new Error("Image height and width must be defined");if("NHWC"===t.tensorLayout)throw new Error("NHWC Tensor layout is not supported yet");let n,r,{height:i,width:a}=t,s=t.norm??{mean:255,bias:0};n="number"==typeof s.mean?[s.mean,s.mean,s.mean,s.mean]:[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],r="number"==typeof s.bias?[s.bias,s.bias,s.bias,s.bias]:[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let o=void 0!==t.format?t.format:"RGBA",l=void 0!==t.tensorFormat&&void 0!==t.tensorFormat?t.tensorFormat:"RGB",u=i*a,d="RGBA"===l?new Float32Array(4*u):new Float32Array(3*u),c=4,p=0,h=1,m=2,f=3,g=0,_=u,w=2*u,b=-1;"RGB"===o&&(c=3,p=0,h=1,m=2,f=-1),"RGBA"===l?b=3*u:"RBG"===l?(g=0,w=u,_=2*u):"BGR"===l&&(w=0,_=u,g=2*u);for(let t=0;t{let n,r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,i=typeof ImageData<"u"&&e instanceof ImageData,a=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,s="string"==typeof e,o=t??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},u=e=>typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext("2d"):null;if(r){let r=l();r.width=e.width,r.height=e.height;let i=u(r);if(null==i)throw new Error("Can not access image data");{let r=e.height,a=e.width;if(void 0!==t&&void 0!==t.resizedHeight&&void 0!==t.resizedWidth&&(r=t.resizedHeight,a=t.resizedWidth),void 0!==t){if(o=t,void 0!==t.tensorFormat)throw new Error("Image input config format must be RGBA for HTMLImageElement");o.tensorFormat="RGBA",o.height=r,o.width=a}else o.tensorFormat="RGBA",o.height=r,o.width=a;i.drawImage(e,0,0),n=i.getImageData(0,0,a,r).data}}else{if(!i){if(a){if(void 0===t)throw new Error("Please provide image config with format for Imagebitmap");let r=l();r.width=e.width,r.height=e.height;let i=u(r);if(null!=i){let t=e.height,r=e.width;return i.drawImage(e,0,0,r,t),n=i.getImageData(0,0,r,t).data,o.height=t,o.width=r,f(n,o)}throw new Error("Can not access image data")}if(s)return new Promise(((t,n)=>{let r=l(),i=u(r);if(!e||!i)return n();let a=new Image;a.crossOrigin="Anonymous",a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);o.height=r.height,o.width=r.width,t(f(e.data,o))}}));throw new Error("Input data provided is not supported - aborted tensor creation")}{let r,i;if(void 0!==t&&void 0!==t.resizedWidth&&void 0!==t.resizedHeight?(r=t.resizedHeight,i=t.resizedWidth):(r=e.height,i=e.width),void 0!==t&&(o=t),o.format="RGBA",o.height=r,o.width=i,void 0!==t){let t=l();t.width=i,t.height=r;let a=u(t);if(null==a)throw new Error("Can not access image data");a.putImageData(e,0,0),n=a.getImageData(0,0,i,r).data}else n=e.data}}if(void 0!==n)return f(n,o);throw new Error("Input data provided is not supported - aborted tensor creation")},_=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new S({location:"texture",type:"float32",texture:e,dims:[1,r,n,4],download:i,dispose:a})},w=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new S({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:r,download:i,dispose:a})},b=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new S({location:"ml-tensor",type:n??"float32",mlTensor:e,dims:r,download:i,dispose:a})},y=(e,t,n)=>new S({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]})})),Z=j((()=>{x=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),v=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),M=!1,T=()=>{if(!M){M=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,n=typeof Float16Array<"u"&&Float16Array.from;e&&(x.set("int64",BigInt64Array),v.set(BigInt64Array,"int64")),t&&(x.set("uint64",BigUint64Array),v.set(BigUint64Array,"uint64")),n?(x.set("float16",Float16Array),v.set(Float16Array,"float16")):x.set("float16",Uint16Array)}}})),J=j((()=>{ee(),k=e=>{let t=1;for(let n=0;n{switch(e.location){case"cpu":return new S(e.type,e.data,t);case"cpu-pinned":return new S({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new S({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new S({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new S({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}})),ee=j((()=>{Q(),Y(),Z(),J(),S=class{constructor(e,t,n){let r,i;if(T(),"object"==typeof e&&"location"in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case"cpu-pinned":{let t=x.get(r);if(!t)throw new TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw new TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case"texture":if("float32"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case"gpu-buffer":if("float32"!==r&&"float16"!==r&&"int32"!==r&&"int64"!==r&&"uint32"!==r&&"uint8"!==r&&"bool"!==r&&"uint4"!==r&&"int4"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case"ml-tensor":if("float32"!==r&&"float16"!==r&&"int32"!==r&&"int64"!==r&&"uint32"!==r&&"uint64"!==r&&"int8"!==r&&"uint8"!==r&&"bool"!==r&&"uint4"!==r&&"int4"!==r)throw new TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,s;if("string"==typeof e)if(r=e,s=n,"string"===e){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");a=t}else{let n=x.get(e);if(void 0===n)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if("float16"===e&&n===Uint16Array||"uint4"===e||"int4"===e)throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a="uint64"===e||"int64"===e?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else{if(!(t instanceof Uint8ClampedArray))throw new TypeError(`A ${r} tensor's data must be type of ${n}`);if("uint8"!==e)throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");a=Uint8Array.from(t)}}else if(s=t,Array.isArray(e)){if(0===e.length)throw new TypeError("Tensor type cannot be inferred from an empty array.");let t=typeof e[0];if("string"===t)r="string",a=e;else{if("boolean"!==t)throw new TypeError(`Invalid element type of data array: ${t}.`);r="bool",a=Uint8Array.from(e)}}else if(e instanceof Uint8ClampedArray)r="uint8",a=Uint8Array.from(e);else{let t=v.get(e.constructor);if(void 0===t)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(void 0===s)s=[a.length];else if(!Array.isArray(s))throw new TypeError("A tensor's dims must be a number array");i=s,this.cpuData=a,this.dataLocation="cpu"}let a=k(i);if(this.cpuData&&a!==this.cpuData.length&&("uint4"!==r&&"int4"!==r||Math.ceil(a/2)!==this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return g(e,t)}static fromTexture(e,t){return _(e,t)}static fromGpuBuffer(e,t){return w(e,t)}static fromMLTensor(e,t){return b(e,t)}static fromPinnedBuffer(e,t,n){return y(e,t,n)}toDataURL(e){return h(this,e)}toImageData(e){return m(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if("none"===this.dataLocation)throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return $(this,e)}}})),te=j((()=>{ee(),C=S})),ne=j((()=>{K(),E=(e,t)=>{(typeof c.trace>"u"?!c.wasm.trace:!c.trace)||console.timeStamp(`${e}::ORT::${t}`)},P=(e,t)=>{let n=(new Error).stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i{(typeof c.trace>"u"?!c.wasm.trace:!c.trace)||P("BEGIN",e)},A=e=>{(typeof c.trace>"u"?!c.wasm.trace:!c.trace)||P("END",e)}})),re=j((()=>{U(),te(),ne(),I=class e{constructor(e){this.handler=e}async run(e,t,n){F();let r={},i={};if("object"!=typeof e||null===e||e instanceof C||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if("object"==typeof t){if(null===t)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof C)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(0===t.length)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let e of t){if("string"!=typeof e)throw new TypeError("'fetches' must be a string array or an object.");if(-1===this.outputNames.indexOf(e))throw new RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if("object"==typeof n&&null!==n)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let e=!1,s=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(-1!==s.indexOf(n)){let i=t[n];(null===i||i instanceof C)&&(e=!0,a=!1,r[n]=i)}if(e){if("object"==typeof n&&null!==n)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else i=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let t of this.inputNames)if(typeof e[t]>"u")throw new Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let s=await this.handler.run(e,r,i),o={};for(let e in s)if(Object.hasOwnProperty.call(s,e)){let t=s[e];o[e]=t instanceof C?t:new C(t.type,t.data,t.dims)}return A(),o}async release(){return this.handler.dispose()}static async create(t,n,r,i){F();let a,s={};if("string"==typeof t){if(a=t,"object"==typeof n&&null!==n)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,"object"==typeof n&&null!==n)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{if(!(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer))throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");{let e=t,o=0,l=t.byteLength;if("object"==typeof n&&null!==n)s=n;else if("number"==typeof n){if(o=n,!Number.isSafeInteger(o))throw new RangeError("'byteOffset' must be an integer.");if(o<0||o>=e.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(l=t.byteLength-o,"number"==typeof r){if(l=r,!Number.isSafeInteger(l))throw new RangeError("'byteLength' must be an integer.");if(l<=0||o+l>e.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${e.byteLength-o}].`);if("object"==typeof i&&null!==i)s=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof r<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof n<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(e,o,l)}}let[o,u]=await l(s),d=await o.createInferenceSessionHandler(a,u);return A(),new e(d)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}})),ie=j((()=>{re(),z=I})),ae=j((()=>{})),se=j((()=>{})),oe=j((()=>{})),le=j((()=>{})),ue=j((()=>{U(),te(),O=class e{constructor(e,t,n){this.handler=e,this.hasOptimizerModel=t,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(t,n){let r=t.evalModel||"",i=t.optimizerModel||"",a=n||{},[s,o]=await l(a);if(s.createTrainingSessionHandler){let n=await s.createTrainingSessionHandler(t.checkpointState,t.trainModel,r,i,o);return new e(n,!!t.optimizerModel,!!t.evalModel)}throw new Error("Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.")}typeNarrowingForRunStep(e,t,n,r,i){let a={},s={};if("object"!=typeof n||null===n||n instanceof C||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if("object"==typeof r){if(null===r)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof C)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(0===r.length)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(let e of r){if("string"!=typeof e)throw new TypeError("'fetches' must be a string array or an object.");if(-1===t.indexOf(e))throw new RangeError(`'fetches' contains invalid output name: ${e}.`);a[e]=null}if("object"==typeof i&&null!==i)s=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let e=!1,n=Object.getOwnPropertyNames(r);for(let i of t)if(-1!==n.indexOf(i)){let t=r[i];(null===t||t instanceof C)&&(e=!0,o=!1,a[i]=t)}if(e){if("object"==typeof i&&null!==i)s=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else s=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let t of e)if(typeof n[t]>"u")throw new Error(`input '${t}' is missing in 'feeds'.`);if(o)for(let e of t)a[e]=null;return[a,s]}convertHandlerReturnTypeToMapOfTensors(e){let t={};for(let n in e)if(Object.hasOwnProperty.call(e,n)){let r=e[n];t[n]=r instanceof C?r:new C(r.type,r.data,r.dims)}return t}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(e,t,n){let[r,i]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,e,t,n),a=await this.handler.runTrainStep(e,r,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}async runOptimizerStep(e){if(!this.hasOptimizerModel)throw new Error("This TrainingSession has no OptimizerModel loaded.");await this.handler.runOptimizerStep(e||{})}async runEvalStep(e,t,n){if(this.hasEvalModel){let[r,i]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,e,t,n),a=await this.handler.runEvalStep(e,r,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(e=!0){return this.handler.getParametersSize(e)}async loadParametersBuffer(e,t=!0){let n=await this.getParametersSize(t);if(e.length!==4*n)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(e,t)}async getContiguousParameters(e=!0){return this.handler.getContiguousParameters(e)}async release(){return this.handler.dispose()}}})),de=j((()=>{ue(),B=O})),ce={};q(ce,{InferenceSession:()=>z,TRACE:()=>E,TRACE_FUNC_BEGIN:()=>F,TRACE_FUNC_END:()=>A,Tensor:()=>C,TrainingSession:()=>B,env:()=>p,registerBackend:()=>s});var pe=j((()=>{W(),X(),ie(),te(),ae(),se(),ne(),oe(),le(),de()})),he=j((()=>{})),me={};q(me,{default:()=>_e});var fe,ge,_e,we=j((()=>{Xd(),Ql(),Xl(),fe="ort-wasm-proxy-worker",(ge=globalThis.self?.name===fe)&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case"init-wasm":Le(n.wasm).then((()=>{gd(n).then((()=>{postMessage({type:t})}),(e=>{postMessage({type:t,err:e})}))}),(e=>{postMessage({type:t,err:e})}));break;case"init-ep":{let{epName:e,env:r}=n;_d(r,e).then((()=>{postMessage({type:t})}),(e=>{postMessage({type:t,err:e})}));break}case"copy-from":{let{buffer:e}=n,r=yd(e);postMessage({type:t,out:r});break}case"create":{let{model:e,options:r}=n;xd(e,r).then((e=>{postMessage({type:t,out:e})}),(e=>{postMessage({type:t,err:e})}));break}case"release":vd(n),postMessage({type:t});break;case"run":{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:s}=n;Td(e,r,i,a,new Array(a.length).fill(null),s).then((e=>{e.some((e=>"cpu"!==e[3]))?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:e},$d([...i,...e]))}),(e=>{postMessage({type:t,err:e})}));break}case"end-profiling":kd(n),postMessage({type:t})}}catch(e){postMessage({type:t,err:e})}}),_e=ge?null:e=>new Worker(e??Me,{type:"module",name:fe})})),be={};q(be,{default:()=>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,os,ls,us,ds,cs,ps,hs,ms,fs,gs,_s,ws,bs,ys,xs,vs,Ms,Ts,ks,$s,Ss,Cs,Es,Ps,Fs,As,Is,zs,Os,Bs,Ls,Ns,Ds,Rs,Vs,js,qs,Gs,Us,Ws,Hs,Ks,Xs,Qs,Ys,Zs,Js,eo,to,no,ro,io,ao,so,oo,lo,uo,co,po,ho,mo,fo,go,_o,wo,bo,yo,xo,vo,Mo,To,ko,$o,So,Co,Eo,Po,Fo,Ao,Io,zo,Oo,Bo,Lo,No,Do,Ro,Vo,jo,qo,Go,Uo,Wo,Ho,Ko,Xo,Qo,Yo,Zo,Jo,el,tl,nl,rl,il,al,sl,ol,ll,ul,dl,cl,pl,hl,ml,fl,gl,_l,wl,bl,yl,xl,vl,Ml,Tl,kl,$l,Sl,Cl,El,Pl,Fl,Al,Il,zl,Ol,Bl,Ll,Nl,Dl,Rl,Vl,jl,ql,Gl,Ul,Wl,Hl,Kl=j((()=>{ye=import.meta.url,xe=async function(e={}){function t(){return F.buffer!=z.buffer&&U(),z}function r(){return F.buffer!=z.buffer&&U(),O}function i(){return F.buffer!=z.buffer&&U(),B}function a(){return F.buffer!=z.buffer&&U(),L}function s(){return F.buffer!=z.buffer&&U(),N}function o(){return F.buffer!=z.buffer&&U(),D}function l(){return F.buffer!=z.buffer&&U(),R}function u(){return F.buffer!=z.buffer&&U(),q}var d,c,p=Object.assign({},e),h=new Promise(((e,t)=>{d=e,c=t})),m="object"==typeof window,f="function"==typeof importScripts,g=f&&"em-pthread"==self.name;p.mountExternalData=(e,t)=>{e.startsWith("./")&&(e=e.substring(2)),(p.Eb||(p.Eb=new Map)).set(e,t)},p.unmountExternalData=()=>{delete p.Eb};var _=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let w=()=>{let e=(e,t,n)=>(...r)=>{let i=Ht,a=t?.();r=e(...r);let s=t?.();return a!==s&&(e=s,n(a),t=n=null),Ht!=i?new Promise(((e,t)=>{Jt={resolve:e,reject:t}})):r},t=e=>async(...t)=>{try{if(p.Fb)throw Error("Session already started");let n=p.Fb={fc:t[0],errors:[]},r=await e(...t);if(p.Fb!==n)throw Error("Session mismatch");p.Gb?.flush();let i=n.errors;if(0e)),0p._OrtCreateSession),(e=>p._OrtCreateSession=e)),p._OrtRun=t(e(p._OrtRun,(()=>p._OrtRun),(e=>p._OrtRun=e))),p._OrtRunWithBinding=t(e(p._OrtRunWithBinding,(()=>p._OrtRunWithBinding),(e=>p._OrtRunWithBinding=e))),p._OrtBindInput=e(p._OrtBindInput,(()=>p._OrtBindInput),(e=>p._OrtBindInput=e)),w=void 0};p.jsepInit=(e,t)=>{if(w?.(),"webgpu"===e){[p.Gb,p.Ub,p.Yb,p.Nb,p.Xb,p.jb,p.Zb,p.bc,p.Vb,p.Wb,p.$b]=t;let e=p.Gb;p.jsepRegisterBuffer=(t,n,r,i)=>e.registerBuffer(t,n,r,i),p.jsepGetBuffer=t=>e.getBuffer(t),p.jsepCreateDownloader=(t,n,r)=>e.createDownloader(t,n,r),p.jsepOnCreateSession=t=>{e.onCreateSession(t)},p.jsepOnReleaseSession=t=>{e.onReleaseSession(t)},p.jsepOnRunStart=t=>e.onRunStart(t),p.cc=(t,n)=>{e.upload(t,n)}}else if("webnn"===e){[p.Gb,p.ac,p.Ob,p.jsepEnsureTensor,p.dc,p.jsepDownloadTensor]=t,p.jsepReleaseTensorId=p.Ob;let e=p.Gb;p.jsepOnRunStart=t=>e.onRunStart(t),p.jsepRegisterMLContext=(t,n)=>{e.registerMLContext(t,n)},p.jsepOnReleaseSession=t=>{e.onReleaseSession(t)},p.jsepCreateMLTensorDownloader=(t,n)=>e.createMLTensorDownloader(t,n),p.jsepRegisterMLTensor=(t,n,r)=>e.registerMLTensor(t,n,r),p.jsepCreateMLContext=t=>e.createMLContext(t),p.jsepRegisterMLConstant=(t,n,r,i,a)=>e.registerMLConstant(t,n,r,i,a,p.Eb)}};var b,y,x=Object.assign({},p),v=(e,t)=>{throw t},M="";(m||f)&&(f?M=self.location.href:typeof document<"u"&&document.currentScript&&(M=document.currentScript.src),ye&&(M=ye),M=M.startsWith("blob:")?"":M.substr(0,M.replace(/[?#].*/,"").lastIndexOf("/")+1),f&&(y=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),b=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)});var T,k=console.log.bind(console),$=console.error.bind(console),S=k,C=$;if(Object.assign(p,x),x=null,g){let e=function(t){try{var n=t.data,r=n.cmd;if("load"===r){let t=[];self.onmessage=e=>t.push(e),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let n of t)e(n);self.onmessage=e};for(let e of n.handlers)p[e]&&!p[e].proxy||(p[e]=(...t)=>{postMessage({Mb:"callHandler",oc:e,args:t})},"print"==e&&(S=p[e]),"printErr"==e&&(C=p[e]));F=n.wasmMemory,U(),E(n.wasmModule)}else if("run"===r){Mr(n.pthread_ptr,0,0,1,0,0),Ot(n.pthread_ptr),Se(),Me(),P||(wr(),P=!0);try{Ce(n.start_routine,n.arg)}catch(e){if("unwind"!=e)throw e}}else"cancel"===r?yr()&&Sr(-1):"setimmediate"!==n.target&&("checkMailbox"===r?P&&Bt():r&&(C(`worker: received unknown command ${r}`),C(n)))}catch(e){throw Tr(),e}};var E,P=!1;C=function(...e){e=e.join(" "),console.error(e)},self.alert=function(...e){postMessage({Mb:"alert",text:e.join(" "),qc:yr()})},p.instantiateWasm=(e,t)=>new Promise((e=>{E=n=>{n=new WebAssembly.Instance(n,ae()),t(n),e()}})),self.onunhandledrejection=e=>{throw e.reason||e},self.onmessage=e}p.wasmBinary&&(T=p.wasmBinary);var F,A,I,z,O,B,L,N,D,R,V,j,q,G=!1;function U(){var e=F.buffer;p.HEAP8=z=new Int8Array(e),p.HEAP16=B=new Int16Array(e),p.HEAPU8=O=new Uint8Array(e),p.HEAPU16=L=new Uint16Array(e),p.HEAP32=N=new Int32Array(e),p.HEAPU32=D=new Uint32Array(e),p.HEAPF32=R=new Float32Array(e),p.HEAPF64=q=new Float64Array(e),p.HEAP64=V=new BigInt64Array(e),p.HEAPU64=j=new BigUint64Array(e)}if(!g){if(!((F=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof _))throw C("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),Error("bad memory");U()}var W=[],H=[],K=[],X=0,Q=null,Y=null;function Z(){if(0==--X&&(null!==Q&&(clearInterval(Q),Q=null),Y)){var e=Y;Y=null,e()}}function J(e){throw C(e="Aborted("+e+")"),G=!0,I=1,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),c(e),e}var ee,te=e=>e.startsWith("data:application/octet-stream;base64,"),ne=e=>e.startsWith("file://");function re(e){if(e==ee&&T)return new Uint8Array(T);if(y)return y(e);throw"both async and sync fetching of the wasm failed"}function ie(e,t,n){return function(e){if(!T&&(m||f)){if("function"==typeof fetch&&!ne(e))return fetch(e,{credentials:"same-origin"}).then((t=>{if(!t.ok)throw`failed to load wasm binary file at '${e}'`;return t.arrayBuffer()})).catch((()=>re(e)));if(b)return new Promise(((t,n)=>{b(e,(e=>t(new Uint8Array(e))),n)}))}return Promise.resolve().then((()=>re(e)))}(e).then((e=>WebAssembly.instantiate(e,t))).then(n,(e=>{C(`failed to asynchronously prepare wasm: ${e}`),J(e)}))}function ae(){return{a:{O:le,Aa:oe,b:Pe,aa:Ae,B:Be,qa:Le,Y:Ve,_:je,ra:qe,oa:Ge,ha:Ue,na:We,L:He,Z:Ke,W:Xe,pa:Qe,X:Ye,wa:et,F:ot,Q:ut,P:_t,E:bt,u:yt,q:xt,G:vt,A:Pt,R:Ft,ua:At,ka:It,U:Lt,ba:Dt,H:Rt,ja:Ot,ta:Vt,t:Gt,x:nn,o:an,m:ln,c:pt,n:dn,k:mn,w:fn,p:gn,f:_n,s:wn,l:bn,e:yn,j:xn,i:vn,h:Mn,d:Tn,ea:kn,fa:En,ga:Pn,ca:Fn,da:An,T:In,g:Bn,D:Ln,I:Nn,M:Dn,y:Rn,sa:jn,V:qn,v:Vn,z:Gn,N:Un,S:Wn,za:Qn,ya:Yn,la:tr,ma:nr,$:ge,C:rr,K:ir,ia:ar,J:or,a:F,xa:me,va:cr,r:pr}}}var se={873844:(e,t,n,i,a)=>{if(void 0===p||!p.Eb)return 1;if((e=Oe(Number(e>>>0))).startsWith("./")&&(e=e.substring(2)),!(e=p.Eb.get(e)))return 2;if(t=Number(t>>>0),n=Number(n>>>0),i=Number(i>>>0),t+n>e.byteLength)return 3;try{let s=e.subarray(t,t+n);switch(a){case 0:r().set(s,i>>>0);break;case 1:p.cc(i,s);break;default:return 4}return 0}catch{return 4}},874559:(e,t,n)=>{p.dc(e,r().subarray(t>>>0,t+n>>>0))},874622:()=>p.ac(),874663:e=>{p.Ob(e)},874699:()=>{p.Vb()},874730:()=>{p.Wb()},874759:()=>{p.$b()},874784:e=>p.Ub(e),874817:e=>p.Yb(e),874849:(e,t,n)=>{p.Nb(Number(e),Number(t),Number(n),!0)},874912:(e,t,n)=>{p.Nb(Number(e),Number(t),Number(n))},874969:()=>typeof wasmOffsetConverter<"u",875026:e=>{p.jb("Abs",e,void 0)},875077:e=>{p.jb("Neg",e,void 0)},875128:e=>{p.jb("Floor",e,void 0)},875181:e=>{p.jb("Ceil",e,void 0)},875233:e=>{p.jb("Reciprocal",e,void 0)},875291:e=>{p.jb("Sqrt",e,void 0)},875343:e=>{p.jb("Exp",e,void 0)},875394:e=>{p.jb("Erf",e,void 0)},875445:e=>{p.jb("Sigmoid",e,void 0)},875500:(e,t,n)=>{p.jb("HardSigmoid",e,{alpha:t,beta:n})},875579:e=>{p.jb("Log",e,void 0)},875630:e=>{p.jb("Sin",e,void 0)},875681:e=>{p.jb("Cos",e,void 0)},875732:e=>{p.jb("Tan",e,void 0)},875783:e=>{p.jb("Asin",e,void 0)},875835:e=>{p.jb("Acos",e,void 0)},875887:e=>{p.jb("Atan",e,void 0)},875939:e=>{p.jb("Sinh",e,void 0)},875991:e=>{p.jb("Cosh",e,void 0)},876043:e=>{p.jb("Asinh",e,void 0)},876096:e=>{p.jb("Acosh",e,void 0)},876149:e=>{p.jb("Atanh",e,void 0)},876202:e=>{p.jb("Tanh",e,void 0)},876254:e=>{p.jb("Not",e,void 0)},876305:(e,t,n)=>{p.jb("Clip",e,{min:t,max:n})},876374:e=>{p.jb("Clip",e,void 0)},876426:(e,t)=>{p.jb("Elu",e,{alpha:t})},876484:e=>{p.jb("Gelu",e,void 0)},876536:e=>{p.jb("Relu",e,void 0)},876588:(e,t)=>{p.jb("LeakyRelu",e,{alpha:t})},876652:(e,t)=>{p.jb("ThresholdedRelu",e,{alpha:t})},876722:(e,t)=>{p.jb("Cast",e,{to:t})},876780:e=>{p.jb("Add",e,void 0)},876831:e=>{p.jb("Sub",e,void 0)},876882:e=>{p.jb("Mul",e,void 0)},876933:e=>{p.jb("Div",e,void 0)},876984:e=>{p.jb("Pow",e,void 0)},877035:e=>{p.jb("Equal",e,void 0)},877088:e=>{p.jb("Greater",e,void 0)},877143:e=>{p.jb("GreaterOrEqual",e,void 0)},877205:e=>{p.jb("Less",e,void 0)},877257:e=>{p.jb("LessOrEqual",e,void 0)},877316:(e,t,n,r,i)=>{p.jb("ReduceMean",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},877491:(e,t,n,r,i)=>{p.jb("ReduceMax",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},877665:(e,t,n,r,i)=>{p.jb("ReduceMin",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},877839:(e,t,n,r,i)=>{p.jb("ReduceProd",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},878014:(e,t,n,r,i)=>{p.jb("ReduceSum",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},878188:(e,t,n,r,i)=>{p.jb("ReduceL1",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},878361:(e,t,n,r,i)=>{p.jb("ReduceL2",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},878534:(e,t,n,r,i)=>{p.jb("ReduceLogSum",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},878711:(e,t,n,r,i)=>{p.jb("ReduceSumSquare",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},878891:(e,t,n,r,i)=>{p.jb("ReduceLogSumExp",e,{keepDims:!!t,noopWithEmptyAxes:!!n,axes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},879071:e=>{p.jb("Where",e,void 0)},879124:(e,t,n)=>{p.jb("Transpose",e,{perm:t?Array.from(s().subarray(Number(t)>>>0,Number(n)>>>0)):[]})},879248:(e,t,n,r)=>{p.jb("DepthToSpace",e,{blocksize:t,mode:Oe(n),format:r?"NHWC":"NCHW"})},879381:(e,t,n,r)=>{p.jb("DepthToSpace",e,{blocksize:t,mode:Oe(n),format:r?"NHWC":"NCHW"})},879514:(e,n,r,i,a,o,l,u,d,c,h,m,f,g,_)=>{p.jb("ConvTranspose",e,{format:d?"NHWC":"NCHW",autoPad:n,dilations:[r],group:i,kernelShape:[a],pads:[o,l],strides:[u],wIsConst:()=>!!t()[c>>>0],outputPadding:h?Array.from(s().subarray(Number(h)>>>0,Number(m)>>>0)):[],outputShape:f?Array.from(s().subarray(Number(f)>>>0,Number(g)>>>0)):[],activation:Oe(_)})},879947:(e,n,r,i,a,o,l,u,d,c,h,m,f,g)=>{p.jb("ConvTranspose",e,{format:u?"NHWC":"NCHW",autoPad:n,dilations:Array.from(s().subarray(Number(r)>>>0,2+(Number(r)>>>0)>>>0)),group:i,kernelShape:Array.from(s().subarray(Number(a)>>>0,2+(Number(a)>>>0)>>>0)),pads:Array.from(s().subarray(Number(o)>>>0,4+(Number(o)>>>0)>>>0)),strides:Array.from(s().subarray(Number(l)>>>0,2+(Number(l)>>>0)>>>0)),wIsConst:()=>!!t()[d>>>0],outputPadding:c?Array.from(s().subarray(Number(c)>>>0,Number(h)>>>0)):[],outputShape:m?Array.from(s().subarray(Number(m)>>>0,Number(f)>>>0)):[],activation:Oe(g)})},880608:(e,n,r,i,a,o,l,u,d,c,h,m,f,g,_)=>{p.jb("ConvTranspose",e,{format:d?"NHWC":"NCHW",autoPad:n,dilations:[r],group:i,kernelShape:[a],pads:[o,l],strides:[u],wIsConst:()=>!!t()[c>>>0],outputPadding:h?Array.from(s().subarray(Number(h)>>>0,Number(m)>>>0)):[],outputShape:f?Array.from(s().subarray(Number(f)>>>0,Number(g)>>>0)):[],activation:Oe(_)})},881041:(e,n,r,i,a,o,l,u,d,c,h,m,f,g)=>{p.jb("ConvTranspose",e,{format:u?"NHWC":"NCHW",autoPad:n,dilations:Array.from(s().subarray(Number(r)>>>0,2+(Number(r)>>>0)>>>0)),group:i,kernelShape:Array.from(s().subarray(Number(a)>>>0,2+(Number(a)>>>0)>>>0)),pads:Array.from(s().subarray(Number(o)>>>0,4+(Number(o)>>>0)>>>0)),strides:Array.from(s().subarray(Number(l)>>>0,2+(Number(l)>>>0)>>>0)),wIsConst:()=>!!t()[d>>>0],outputPadding:c?Array.from(s().subarray(Number(c)>>>0,Number(h)>>>0)):[],outputShape:m?Array.from(s().subarray(Number(m)>>>0,Number(f)>>>0)):[],activation:Oe(g)})},881702:(e,t)=>{p.jb("GlobalAveragePool",e,{format:t?"NHWC":"NCHW"})},881793:(e,t,n,r,i,a,o,l,u,d,c,h,m,f)=>{p.jb("AveragePool",e,{format:f?"NHWC":"NCHW",auto_pad:t,ceil_mode:n,count_include_pad:r,storage_order:i,dilations:a?Array.from(s().subarray(Number(a)>>>0,Number(o)>>>0)):[],kernel_shape:l?Array.from(s().subarray(Number(l)>>>0,Number(u)>>>0)):[],pads:d?Array.from(s().subarray(Number(d)>>>0,Number(c)>>>0)):[],strides:h?Array.from(s().subarray(Number(h)>>>0,Number(m)>>>0)):[]})},882272:(e,t)=>{p.jb("GlobalAveragePool",e,{format:t?"NHWC":"NCHW"})},882363:(e,t,n,r,i,a,o,l,u,d,c,h,m,f)=>{p.jb("AveragePool",e,{format:f?"NHWC":"NCHW",auto_pad:t,ceil_mode:n,count_include_pad:r,storage_order:i,dilations:a?Array.from(s().subarray(Number(a)>>>0,Number(o)>>>0)):[],kernel_shape:l?Array.from(s().subarray(Number(l)>>>0,Number(u)>>>0)):[],pads:d?Array.from(s().subarray(Number(d)>>>0,Number(c)>>>0)):[],strides:h?Array.from(s().subarray(Number(h)>>>0,Number(m)>>>0)):[]})},882842:(e,t)=>{p.jb("GlobalMaxPool",e,{format:t?"NHWC":"NCHW"})},882929:(e,t,n,r,i,a,o,l,u,d,c,h,m,f)=>{p.jb("MaxPool",e,{format:f?"NHWC":"NCHW",auto_pad:t,ceil_mode:n,count_include_pad:r,storage_order:i,dilations:a?Array.from(s().subarray(Number(a)>>>0,Number(o)>>>0)):[],kernel_shape:l?Array.from(s().subarray(Number(l)>>>0,Number(u)>>>0)):[],pads:d?Array.from(s().subarray(Number(d)>>>0,Number(c)>>>0)):[],strides:h?Array.from(s().subarray(Number(h)>>>0,Number(m)>>>0)):[]})},883404:(e,t)=>{p.jb("GlobalMaxPool",e,{format:t?"NHWC":"NCHW"})},883491:(e,t,n,r,i,a,o,l,u,d,c,h,m,f)=>{p.jb("MaxPool",e,{format:f?"NHWC":"NCHW",auto_pad:t,ceil_mode:n,count_include_pad:r,storage_order:i,dilations:a?Array.from(s().subarray(Number(a)>>>0,Number(o)>>>0)):[],kernel_shape:l?Array.from(s().subarray(Number(l)>>>0,Number(u)>>>0)):[],pads:d?Array.from(s().subarray(Number(d)>>>0,Number(c)>>>0)):[],strides:h?Array.from(s().subarray(Number(h)>>>0,Number(m)>>>0)):[]})},883966:(e,t,n,r,i)=>{p.jb("Gemm",e,{alpha:t,beta:n,transA:r,transB:i})},884070:e=>{p.jb("MatMul",e,void 0)},884124:(e,t,n,r)=>{p.jb("ArgMax",e,{keepDims:!!t,selectLastIndex:!!n,axis:r})},884232:(e,t,n,r)=>{p.jb("ArgMin",e,{keepDims:!!t,selectLastIndex:!!n,axis:r})},884340:(e,t)=>{p.jb("Softmax",e,{axis:t})},884403:(e,t)=>{p.jb("Concat",e,{axis:t})},884463:(e,t,n,r,i)=>{p.jb("Split",e,{axis:t,numOutputs:n,splitSizes:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},884619:e=>{p.jb("Expand",e,void 0)},884673:(e,t)=>{p.jb("Gather",e,{axis:Number(t)})},884744:(e,t)=>{p.jb("GatherElements",e,{axis:Number(t)})},884823:(e,t,n,r,i,a,o,l,u,d,c)=>{p.jb("Resize",e,{antialias:t,axes:n?Array.from(s().subarray(Number(n)>>>0,Number(r)>>>0)):[],coordinateTransformMode:Oe(i),cubicCoeffA:a,excludeOutside:o,extrapolationValue:l,keepAspectRatioPolicy:Oe(u),mode:Oe(d),nearestMode:Oe(c)})},885185:(e,t,n,r,i,a,o)=>{p.jb("Slice",e,{starts:t?Array.from(s().subarray(Number(t)>>>0,Number(n)>>>0)):[],ends:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[],axes:a?Array.from(s().subarray(Number(a)>>>0,Number(o)>>>0)):[]})},885449:e=>{p.jb("Tile",e,void 0)},885501:(e,t,n)=>{p.jb("InstanceNormalization",e,{epsilon:t,format:n?"NHWC":"NCHW"})},885615:(e,t,n)=>{p.jb("InstanceNormalization",e,{epsilon:t,format:n?"NHWC":"NCHW"})},885729:e=>{p.jb("Range",e,void 0)},885782:(e,t)=>{p.jb("Einsum",e,{equation:Oe(t)})},885863:(e,t,n,r,i)=>{p.jb("Pad",e,{mode:t,value:n,pads:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[]})},886006:(e,t,n,r,i,a)=>{p.jb("BatchNormalization",e,{epsilon:t,momentum:n,spatial:!!i,trainingMode:!!r,format:a?"NHWC":"NCHW"})},886175:(e,t,n,r,i,a)=>{p.jb("BatchNormalization",e,{epsilon:t,momentum:n,spatial:!!i,trainingMode:!!r,format:a?"NHWC":"NCHW"})},886344:(e,t,n)=>{p.jb("CumSum",e,{exclusive:Number(t),reverse:Number(n)})},886441:(e,t,n)=>{p.jb("DequantizeLinear",e,{axis:t,blockSize:n})},886531:(e,t,n,r,i)=>{p.jb("GridSample",e,{align_corners:t,mode:Oe(n),padding_mode:Oe(r),format:i?"NHWC":"NCHW"})},886701:(e,t,n,r,i)=>{p.jb("GridSample",e,{align_corners:t,mode:Oe(n),padding_mode:Oe(r),format:i?"NHWC":"NCHW"})},886871:(e,t)=>{p.jb("ScatterND",e,{reduction:Oe(t)})},886956:(e,t,n,r,i,a,o,l,u)=>{p.jb("Attention",e,{numHeads:t,isUnidirectional:n,maskFilterValue:r,scale:i,doRotary:a,qkvHiddenSizes:o?Array.from(s().subarray(Number(l)>>>0,Number(l)+o>>>0)):[],pastPresentShareBuffer:!!u})},887228:e=>{p.jb("BiasAdd",e,void 0)},887283:e=>{p.jb("BiasSplitGelu",e,void 0)},887344:e=>{p.jb("FastGelu",e,void 0)},887400:(e,n,r,i,a,o,u,d,c,h,m,f,g,_,w,b)=>{p.jb("Conv",e,{format:f?"NHWC":"NCHW",auto_pad:n,dilations:r?Array.from(s().subarray(Number(r)>>>0,Number(i)>>>0)):[],group:a,kernel_shape:o?Array.from(s().subarray(Number(o)>>>0,Number(u)>>>0)):[],pads:d?Array.from(s().subarray(Number(d)>>>0,Number(c)>>>0)):[],strides:h?Array.from(s().subarray(Number(h)>>>0,Number(m)>>>0)):[],w_is_const:()=>!!t()[Number(g)>>>0],activation:Oe(_),activation_params:w?Array.from(l().subarray(Number(w)>>>0,Number(b)>>>0)):[]})},887984:e=>{p.jb("Gelu",e,void 0)},888036:(e,t,n,r,i,a,s,o,l)=>{p.jb("GroupQueryAttention",e,{numHeads:t,kvNumHeads:n,scale:r,softcap:i,doRotary:a,rotaryInterleaved:s,smoothSoftmax:o,localWindowSize:l})},888253:(e,t,n,r)=>{p.jb("LayerNormalization",e,{axis:t,epsilon:n,simplified:!!r})},888364:(e,t,n,r)=>{p.jb("LayerNormalization",e,{axis:t,epsilon:n,simplified:!!r})},888475:(e,t,n,r,i,a)=>{p.jb("MatMulNBits",e,{k:t,n,accuracyLevel:r,bits:i,blockSize:a})},888602:(e,t,n,r,i,a)=>{p.jb("MultiHeadAttention",e,{numHeads:t,isUnidirectional:n,maskFilterValue:r,scale:i,doRotary:a})},888761:(e,t)=>{p.jb("QuickGelu",e,{alpha:t})},888825:(e,t,n,r,i)=>{p.jb("RotaryEmbedding",e,{interleaved:!!t,numHeads:n,rotaryEmbeddingDim:r,scale:i})},888964:(e,t,n)=>{p.jb("SkipLayerNormalization",e,{epsilon:t,simplified:!!n})},889066:(e,t,n)=>{p.jb("SkipLayerNormalization",e,{epsilon:t,simplified:!!n})},889168:(e,t,n,r)=>{p.jb("GatherBlockQuantized",e,{gatherAxis:t,quantizeAxis:n,blockSize:r})},889289:e=>{p.Zb(e)},889323:(e,t)=>p.bc(Number(e),Number(t),p.Fb.fc,p.Fb.errors)};function oe(e,t,n){return tn((async()=>{await p.Xb(Number(e),Number(t),Number(n))}))}function le(){return typeof wasmOffsetConverter<"u"}function ue(e){this.name="ExitStatus",this.message=`Program terminated with exit(${e})`,this.status=e}var de=e=>{e.terminate(),e.onmessage=()=>{}},ce=e=>{0==_e.length&&(ke(),Te(_e[0]));var t=_e.pop();if(!t)return 6;we.push(t),xe[e.Ab]=t,t.Ab=e.Ab;var n={cmd:"run",start_routine:e.hc,arg:e.Qb,pthread_ptr:e.Ab};return t.postMessage(n,e.mc),0},pe=0,he=(e,t,...n)=>{for(var r=2*n.length,i=Ar(),a=Fr(8*r),s=a>>>3,o=0;o>>0]=l)}return e=kr(e,0,r,a,t),Pr(i),e};function me(e){if(g)return he(0,1,e);if(I=e,!(0{if(I=e,g)throw fe(e),"unwind";me(e)},_e=[],we=[],be=[],xe={},ve=e=>{var t=e.Ab;delete xe[t],_e.push(e),we.splice(we.indexOf(e),1),e.Ab=0,$r(t)};function Me(){be.forEach((e=>e()))}var Te=e=>new Promise((t=>{e.onmessage=n=>{var r=(n=n.data).cmd;if(n.targetThread&&n.targetThread!=yr()){var i=xe[n.targetThread];i?i.postMessage(n,n.transferList):C(`Internal error! Worker sent a message "${r}" to target pthread ${n.targetThread}, but that thread no longer exists!`)}else"checkMailbox"===r?Bt():"spawnThread"===r?ce(n):"cleanupThread"===r?ve(xe[n.thread]):"killThread"===r?(n=n.thread,r=xe[n],delete xe[n],de(r),$r(n),we.splice(we.indexOf(r),1),r.Ab=0):"cancelThread"===r?xe[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(e.loaded=!0,t(e)):"alert"===r?alert(`Thread ${n.threadId}: ${n.text}`):"setimmediate"===n.target?e.postMessage(n):"callHandler"===r?p[n.handler](...n.args):r&&C(`worker sent an unknown command ${r}`)},e.onerror=e=>{throw C(`worker sent an error! ${e.filename}:${e.lineno}: ${e.message}`),e};var n,r=[];for(n of[])p.hasOwnProperty(n)&&r.push(n);e.postMessage({cmd:"load",handlers:r,wasmMemory:F,wasmModule:A})}));function ke(){var e=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});_e.push(e)}var $e=e=>{for(;0{var e=yr(),t=o()[e+52>>>2>>>0];e=o()[e+56>>>2>>>0],Er(t,t-e),Pr(t)},Ce=(e,t)=>{pe=0,e=Ir(e,t),0>>=0);throw t>>>=0,n>>>=0,o()[r.Jb+16>>>2>>>0]=0,o()[r.Jb+4>>>2>>>0]=t,o()[r.Jb+8>>>2>>>0]=n,e}function Fe(e,t,n,r){return g?he(2,1,e,t,n,r):Ae(e,t,n,r)}function Ae(e,t,n,r){if(e>>>=0,t>>>=0,n>>>=0,r>>>=0,void 0===_)return C("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var i=[];return g&&0===i.length?Fe(e,t,n,r):(e={hc:n,Ab:e,Qb:r,mc:i},g?(e.Mb="spawnThread",postMessage(e,i),0):ce(e))}var Ie=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,ze=(e,t,n)=>{var r=(t>>>=0)+n;for(n=t;e[n]&&!(n>=r);)++n;if(16(i=224==(240&i)?(15&i)<<12|a<<6|s:(7&i)<<18|a<<12|s<<6|63&e[t++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r},Oe=(e,t)=>(e>>>=0)?ze(r(),e,t):"";function Be(e,t,n){return g?he(3,1,e,t,n):0}function Le(e,t){if(g)return he(4,1,e,t)}var Ne=e=>{for(var t=0,n=0;n=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t},De=(e,t,n,r)=>{if(!(0>>=0;r=n+r-1;for(var a=0;a=s&&(s=65536+((1023&s)<<10)|1023&e.charCodeAt(++a)),127>=s){if(n>=r)break;t[n++>>>0]=s}else{if(2047>=s){if(n+1>=r)break;t[n++>>>0]=192|s>>6}else{if(65535>=s){if(n+2>=r)break;t[n++>>>0]=224|s>>12}else{if(n+3>=r)break;t[n++>>>0]=240|s>>18,t[n++>>>0]=128|s>>12&63}t[n++>>>0]=128|s>>6&63}t[n++>>>0]=128|63&s}}return t[n>>>0]=0,n-i},Re=(e,t,n)=>De(e,r(),t,n);function Ve(e,t){if(g)return he(5,1,e,t)}function je(e,t,n){if(g)return he(6,1,e,t,n)}function qe(e,t,n){return g?he(7,1,e,t,n):0}function Ge(e,t){if(g)return he(8,1,e,t)}function Ue(e,t,n){if(g)return he(9,1,e,t,n)}function We(e,t,n,r){if(g)return he(10,1,e,t,n,r)}function He(e,t,n,r){if(g)return he(11,1,e,t,n,r)}function Ke(e,t,n,r){if(g)return he(12,1,e,t,n,r)}function Xe(e){if(g)return he(13,1,e)}function Qe(e,t){if(g)return he(14,1,e,t)}function Ye(e,t,n){if(g)return he(15,1,e,t,n)}var Ze,Je,et=()=>{J("")},tt=e=>{for(var t="";r()[e>>>0];)t+=Ze[r()[e++>>>0]];return t},nt={},rt={},it={};function at(e,t,n={}){if(!("argPackAdvance"in t))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(e,t,n={}){var r=t.name;if(!e)throw new Je(`type "${r}" must have a positive integer typeid pointer`);if(rt.hasOwnProperty(e)){if(n.Sb)return;throw new Je(`Cannot register type '${r}' twice`)}rt[e]=t,delete it[e],nt.hasOwnProperty(e)&&(t=nt[e],delete nt[e],t.forEach((e=>e())))}(e,t,n)}var st=(e,n,l)=>{switch(n){case 1:return l?e=>t()[e>>>0]:e=>r()[e>>>0];case 2:return l?e=>i()[e>>>1>>>0]:e=>a()[e>>>1>>>0];case 4:return l?e=>s()[e>>>2>>>0]:e=>o()[e>>>2>>>0];case 8:return l?e=>V[e>>>3]:e=>j[e>>>3];default:throw new TypeError(`invalid integer width (${n}): ${e}`)}};function ot(e,t,n){n>>>=0,at(e>>>=0,{name:t=tt(t>>>0),fromWireType:e=>e,toWireType:function(e,t){if("bigint"!=typeof t&&"number"!=typeof t)throw t=null===t?"null":"object"==(e=typeof t)||"array"===e||"function"===e?t.toString():""+t,new TypeError(`Cannot convert "${t}" to ${this.name}`);return"number"==typeof t&&(t=BigInt(t)),t},argPackAdvance:lt,readValueFromPointer:st(t,n,-1==t.indexOf("u")),Db:null})}var lt=8;function ut(e,t,n,i){at(e>>>=0,{name:t=tt(t>>>0),fromWireType:function(e){return!!e},toWireType:function(e,t){return t?n:i},argPackAdvance:lt,readValueFromPointer:function(e){return this.fromWireType(r()[e>>>0])},Db:null})}var dt=[],ct=[];function pt(e){9<(e>>>=0)&&0==--ct[e+1]&&(ct[e]=void 0,dt.push(e))}var ht=e=>{if(!e)throw new Je("Cannot use deleted val. handle = "+e);return ct[e]},mt=e=>{switch(e){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let t=dt.pop()||ct.length;return ct[t]=e,ct[t+1]=1,t}};function ft(e){return this.fromWireType(o()[e>>>2>>>0])}var gt={name:"emscripten::val",fromWireType:e=>{var t=ht(e);return pt(e),t},toWireType:(e,t)=>mt(t),argPackAdvance:lt,readValueFromPointer:ft,Db:null};function _t(e){return at(e>>>0,gt)}var wt=(e,t)=>{switch(t){case 4:return function(e){return this.fromWireType(l()[e>>>2>>>0])};case 8:return function(e){return this.fromWireType(u()[e>>>3>>>0])};default:throw new TypeError(`invalid float width (${t}): ${e}`)}};function bt(e,t,n){n>>>=0,at(e>>>=0,{name:t=tt(t>>>0),fromWireType:e=>e,toWireType:(e,t)=>t,argPackAdvance:lt,readValueFromPointer:wt(t,n),Db:null})}function yt(e,t,n,r,i){if(e>>>=0,n>>>=0,t=tt(t>>>0),-1===i&&(i=4294967295),i=e=>e,0===r){var a=32-8*n;i=e=>e<>>a}var s=t.includes("unsigned")?function(e,t){return t>>>0}:function(e,t){return t};at(e,{name:t,fromWireType:i,toWireType:s,argPackAdvance:lt,readValueFromPointer:st(t,n,0!==r),Db:null})}function xt(e,n,r){function i(e){var n=o()[e>>>2>>>0];return e=o()[e+4>>>2>>>0],new a(t().buffer,e,n)}var a=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][n];at(e>>>=0,{name:r=tt(r>>>0),fromWireType:i,argPackAdvance:lt,readValueFromPointer:i},{Sb:!0})}function vt(e,t){e>>>=0;var n="std::string"===(t=tt(t>>>0));at(e,{name:t,fromWireType:function(e){var t=o()[e>>>2>>>0],i=e+4;if(n)for(var a=i,s=0;s<=t;++s){var l=i+s;if(s==t||0==r()[l>>>0]){if(a=Oe(a,l-a),void 0===u)var u=a;else u+=String.fromCharCode(0),u+=a;a=l+1}}else{for(u=Array(t),s=0;s>>0]);u=u.join("")}return xr(e),u},toWireType:function(e,t){t instanceof ArrayBuffer&&(t=new Uint8Array(t));var i="string"==typeof t;if(!(i||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int8Array))throw new Je("Cannot pass non-string to std::string");var a=n&&i?Ne(t):t.length,s=vr(4+a+1),l=s+4;if(o()[s>>>2>>>0]=a,n&&i)Re(t,l,a+1);else if(i)for(i=0;i>>0]=u}else for(i=0;i>>0]=t[i];return null!==e&&e.push(xr,s),s},argPackAdvance:lt,readValueFromPointer:ft,Db(e){xr(e)}})}var Mt=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Tt=(e,t)=>{for(var n=e>>1,s=n+t/2;!(n>=s)&&a()[n>>>0];)++n;if(32<(n<<=1)-e&&Mt)return Mt.decode(r().slice(e,n));for(n="",s=0;!(s>=t/2);++s){var o=i()[e+2*s>>>1>>>0];if(0==o)break;n+=String.fromCharCode(o)}return n},kt=(e,t,n)=>{if(n??=2147483647,2>n)return 0;var r=t;n=(n-=2)<2*e.length?n/2:e.length;for(var a=0;a>>1>>>0]=s,t+=2}return i()[t>>>1>>>0]=0,t-r},$t=e=>2*e.length,St=(e,t)=>{for(var n=0,r="";!(n>=t/4);){var i=s()[e+4*n>>>2>>>0];if(0==i)break;++n,65536<=i?(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i)):r+=String.fromCharCode(i)}return r},Ct=(e,t,n)=>{if(t>>>=0,n??=2147483647,4>n)return 0;var r=t;n=r+n-4;for(var i=0;i=a&&(a=65536+((1023&a)<<10)|1023&e.charCodeAt(++i)),s()[t>>>2>>>0]=a,(t+=4)+4>n)break}return s()[t>>>2>>>0]=0,t-r},Et=e=>{for(var t=0,n=0;n=r&&++n,t+=4}return t};function Pt(e,t,n){if(e>>>=0,t>>>=0,n=tt(n>>>=0),2===t)var r=Tt,i=kt,s=$t,l=e=>a()[e>>>1>>>0];else 4===t&&(r=St,i=Ct,s=Et,l=e=>o()[e>>>2>>>0]);at(e,{name:n,fromWireType:e=>{for(var n,i=o()[e>>>2>>>0],a=e+4,s=0;s<=i;++s){var u=e+4+s*t;s!=i&&0!=l(u)||(a=r(a,u-a),void 0===n?n=a:(n+=String.fromCharCode(0),n+=a),a=u+t)}return xr(e),n},toWireType:(e,r)=>{if("string"!=typeof r)throw new Je(`Cannot pass non-string to C++ string type ${n}`);var a=s(r),l=vr(4+a+t);return o()[l>>>2>>>0]=a/t,i(r,l+4,a+t),null!==e&&e.push(xr,l),l},argPackAdvance:lt,readValueFromPointer:ft,Db(e){xr(e)}})}function Ft(e,t){at(e>>>=0,{Tb:!0,name:t=tt(t>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var At=()=>1;function It(e){Mr(e>>>0,!f,1,!m,131072,!1),Me()}var zt=e=>{if(!G)try{if(e(),!(0>>=0,"function"==typeof Atomics.nc&&(Atomics.nc(s(),e>>>2,e).value.then(Bt),e+=128,Atomics.store(s(),e>>>2,1))}var Bt=()=>{var e=yr();e&&(Ot(e),zt(Cr))};function Lt(e,t){(e>>>=0)==t>>>0?setTimeout(Bt):g?postMessage({targetThread:e,cmd:"checkMailbox"}):(e=xe[e])&&e.postMessage({cmd:"checkMailbox"})}var Nt=[];function Dt(e,t,n,r,i){for(t>>>=0,r/=2,Nt.length=r,n=i>>>0>>>3,i=0;i>>0];return(t?se[t]:fr[e])(...Nt)}function Rt(e){e>>>=0,g?postMessage({cmd:"cleanupThread",thread:e}):ve(xe[e])}function Vt(e){}var jt=(e,t)=>{var n=rt[e];if(void 0===n)throw e=_r(e),n=tt(e),xr(e),new Je(`${t} has unknown type ${n}`);return n},qt=(e,t,n)=>{var r=[];return e=e.toWireType(r,n),r.length&&(o()[t>>>2>>>0]=mt(r)),e};function Gt(e,t,n){return t>>>=0,n>>>=0,e=ht(e>>>0),t=jt(t,"emval::as"),qt(t,n,e)}var Ut=e=>{try{e()}catch(e){J(e)}},Wt=0,Ht=null,Kt=0,Xt=[],Qt={},Yt={},Zt=0,Jt=null,en=[];function tn(e){return function(){if(!G){if(0===Wt){var t=!1,n=!1;(t=>{e().then(t)})(((e=0)=>{if(!G&&(Kt=e,t=!0,n)){Wt=2,Ut((()=>Br(Ht))),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.resume(),e=!1;try{var r=(o=s()[Ht+8>>>2>>>0],o=gr[Yt[o]],--pe,o())}catch(o){r=o,e=!0}var i=!1;if(!Ht){var a=Jt;a&&(Jt=null,(e?a.reject:a.resolve)(r),i=!0)}if(e&&!i)throw r}var o})),n=!0,t||(Wt=1,Ht=function(){var e=vr(65548),t=e+12;o()[e>>>2>>>0]=t,o()[e+4>>>2>>>0]=t+65536,t=Xt[0];var n=Qt[t];return void 0===n&&(n=Zt++,Qt[t]=n,Yt[n]=t),t=n,s()[e+8>>>2>>>0]=t,e}(),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.pause(),Ut((()=>zr(Ht))))}else 2===Wt?(Wt=0,Ut(Lr),xr(Ht),Ht=null,en.forEach(zt)):J(`invalid state: ${Wt}`);return Kt}}()}function nn(e){return e>>>=0,tn((()=>(e=ht(e)).then(mt)))}var rn=[];function an(e,t,n,r){return n>>>=0,r>>>=0,(e=rn[e>>>0])(null,t=ht(t>>>0),n,r)}var sn={},on=e=>{var t=sn[e];return void 0===t?tt(e):t};function ln(e,t,n,r,i){return n>>>=0,r>>>=0,i>>>=0,(e=rn[e>>>0])(t=ht(t>>>0),t[n=on(n)],r,i)}var un=()=>"object"==typeof globalThis?globalThis:Function("return this")();function dn(e){return 0==(e>>>=0)?mt(un()):(e=on(e),mt(un()[e]))}var cn=e=>{var t=rn.length;return rn.push(e),t},pn=(e,t)=>{for(var n=Array(e),r=0;r>>2>>>0],"parameter "+r);return n},hn=(e,t)=>Object.defineProperty(t,"name",{value:e});function mn(e,t,n){var r=(t=pn(e,t>>>0)).shift();e--;var i="return function (obj, func, destructorsRef, args) {\n",a=0,s=[];0===n&&s.push("obj");for(var o=["retType"],l=[r],u=0;ue.name)).join(", ")}) => ${r.name}>`,cn(hn(n,e))}function fn(e){return e=on(e>>>0),mt(p[e])}function gn(e,t){return t>>>=0,e=ht(e>>>0),t=ht(t),mt(e[t])}function _n(e){9<(e>>>=0)&&(ct[e+1]+=1)}function wn(){return mt([])}function bn(e){e=ht(e>>>0);for(var t=Array(e.length),n=0;n>>0))}function xn(){return mt({})}function vn(e){for(var t=ht(e>>>=0);t.length;){var n=t.pop();t.pop()(n)}pt(e)}function Mn(e,t,n){t>>>=0,n>>>=0,e=ht(e>>>0),t=ht(t),n=ht(n),e[t]=n}function Tn(e,t){return t>>>=0,e=(e=jt(e>>>0,"_emval_take_value")).readValueFromPointer(t),mt(e)}function kn(e,t){e=-9007199254740992>e||9007199254740992>>=0,e=new Date(1e3*e),s()[t>>>2>>>0]=e.getUTCSeconds(),s()[t+4>>>2>>>0]=e.getUTCMinutes(),s()[t+8>>>2>>>0]=e.getUTCHours(),s()[t+12>>>2>>>0]=e.getUTCDate(),s()[t+16>>>2>>>0]=e.getUTCMonth(),s()[t+20>>>2>>>0]=e.getUTCFullYear()-1900,s()[t+24>>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,s()[t+28>>>2>>>0]=e}var $n=e=>e%4==0&&(e%100!=0||e%400==0),Sn=[0,31,60,91,121,152,182,213,244,274,305,335],Cn=[0,31,59,90,120,151,181,212,243,273,304,334];function En(e,t){e=-9007199254740992>e||9007199254740992>>=0,e=new Date(1e3*e),s()[t>>>2>>>0]=e.getSeconds(),s()[t+4>>>2>>>0]=e.getMinutes(),s()[t+8>>>2>>>0]=e.getHours(),s()[t+12>>>2>>>0]=e.getDate(),s()[t+16>>>2>>>0]=e.getMonth(),s()[t+20>>>2>>>0]=e.getFullYear()-1900,s()[t+24>>>2>>>0]=e.getDay();var n=($n(e.getFullYear())?Sn:Cn)[e.getMonth()]+e.getDate()-1|0;s()[t+28>>>2>>>0]=n,s()[t+36>>>2>>>0]=-60*e.getTimezoneOffset(),n=new Date(e.getFullYear(),6,1).getTimezoneOffset();var r=new Date(e.getFullYear(),0,1).getTimezoneOffset();e=0|(n!=r&&e.getTimezoneOffset()==Math.min(r,n)),s()[t+32>>>2>>>0]=e}function Pn(e){e>>>=0;var t=new Date(s()[e+20>>>2>>>0]+1900,s()[e+16>>>2>>>0],s()[e+12>>>2>>>0],s()[e+8>>>2>>>0],s()[e+4>>>2>>>0],s()[e>>>2>>>0],0),n=s()[e+32>>>2>>>0],r=t.getTimezoneOffset(),i=new Date(t.getFullYear(),6,1).getTimezoneOffset(),a=new Date(t.getFullYear(),0,1).getTimezoneOffset(),o=Math.min(a,i);return 0>n?s()[e+32>>>2>>>0]=+(i!=a&&o==r):0>>2>>>0]=t.getDay(),n=($n(t.getFullYear())?Sn:Cn)[t.getMonth()]+t.getDate()-1|0,s()[e+28>>>2>>>0]=n,s()[e>>>2>>>0]=t.getSeconds(),s()[e+4>>>2>>>0]=t.getMinutes(),s()[e+8>>>2>>>0]=t.getHours(),s()[e+12>>>2>>>0]=t.getDate(),s()[e+16>>>2>>>0]=t.getMonth(),s()[e+20>>>2>>>0]=t.getYear(),e=t.getTime(),BigInt(isNaN(e)?-1:e/1e3)}function Fn(e,t,n,r,i,a,s){return g?he(16,1,e,t,n,r,i,a,s):-52}function An(e,t,n,r,i,a){if(g)return he(17,1,e,t,n,r,i,a)}function In(e,t,n,r){e>>>=0,t>>>=0,n>>>=0,r>>>=0;var i=(new Date).getFullYear(),a=new Date(i,0,1),l=new Date(i,6,1);i=a.getTimezoneOffset();var u=l.getTimezoneOffset(),d=Math.max(i,u);o()[e>>>2>>>0]=60*d,s()[t>>>2>>>0]=+(i!=u),a=(e=e=>e.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(a),l=e(l),u{zn.length=0;for(var n;n=r()[e++>>>0];){var i=105!=n;t+=(i&=112!=n)&&t%8?4:0,zn.push(112==n?o()[t>>>2>>>0]:106==n?V[t>>>3]:105==n?s()[t>>>2>>>0]:u()[t>>>3>>>0]),t+=i?8:4}return zn};function Bn(e,t,n){return e>>>=0,t=On(t>>>0,n>>>0),se[e](...t)}function Ln(e,t,n){return e>>>=0,t=On(t>>>0,n>>>0),se[e](...t)}var Nn=()=>{},Dn=()=>Date.now();function Rn(e,t){return C(Oe(e>>>0,t>>>0))}var Vn,jn=()=>{throw pe+=1,"unwind"};function qn(){return 4294901760}Vn=()=>performance.timeOrigin+performance.now();var Gn=()=>navigator.hardwareConcurrency;function Un(){return J("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Wn(e){e>>>=0;var t=r().length;if(e<=t||4294901760=n;n*=2){var i=t*(1+.2/n);i=Math.min(i,e+100663296);var a=Math;i=Math.max(e,i);e:{a=(a.min.call(a,4294901760,i+(65536-i%65536)%65536)-F.buffer.byteLength+65535)/65536;try{F.grow(a),U();var s=1;break e}catch{}s=void 0}if(s)return!0}return!1}var Hn=()=>(J("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Kn={},Xn=e=>{e.forEach((e=>{var t=Hn();t&&(Kn[t]=e)}))};function Qn(){var e=Error().stack.toString().split("\n");return"Error"==e[0]&&e.shift(),Xn(e),Kn.Pb=Hn(),Kn.ec=e,Kn.Pb}function Yn(e,t,n){if(e>>>=0,t>>>=0,Kn.Pb==e)var r=Kn.ec;else"Error"==(r=Error().stack.toString().split("\n"))[0]&&r.shift(),Xn(r);for(var i=3;r[i]&&Hn()!=e;)++i;for(e=0;e>>2>>>0]=Hn();return e}var Zn,Jn={},er=()=>{if(!Zn){var e,t={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:"./this.program"};for(e in Jn)void 0===Jn[e]?delete t[e]:t[e]=Jn[e];var n=[];for(e in t)n.push(`${e}=${t[e]}`);Zn=n}return Zn};function tr(e,n){if(g)return he(18,1,e,n);e>>>=0,n>>>=0;var r=0;return er().forEach(((i,a)=>{var s=n+r;for(a=o()[e+4*a>>>2>>>0]=s,s=0;s>>0]=i.charCodeAt(s);t()[a>>>0]=0,r+=i.length+1})),0}function nr(e,t){if(g)return he(19,1,e,t);e>>>=0,t>>>=0;var n=er();o()[e>>>2>>>0]=n.length;var r=0;return n.forEach((e=>r+=e.length+1)),o()[t>>>2>>>0]=r,0}function rr(e){return g?he(20,1,e):52}function ir(e,t,n,r){return g?he(21,1,e,t,n,r):52}function ar(e,t,n,r){return g?he(22,1,e,t,n,r):70}var sr=[null,[],[]];function or(e,t,n,i){if(g)return he(23,1,e,t,n,i);t>>>=0,n>>>=0,i>>>=0;for(var a=0,s=0;s>>2>>>0],u=o()[t+4>>>2>>>0];t+=8;for(var d=0;d>>0],p=sr[e];0===c||10===c?((1===e?S:C)(ze(p,0)),p.length=0):p.push(c)}a+=u}return o()[i>>>2>>>0]=a,0}var lr=[31,29,31,30,31,30,31,31,30,31,30,31],ur=[31,28,31,30,31,30,31,31,30,31,30,31],dr=(e,n)=>{t().set(e,n>>>0)};function cr(e,t,n,r){function i(e,t,n){for(e="number"==typeof e?e.toString():e||"";e.lengthe?-1:0r-e.getDate())){e.setDate(e.getDate()+t);break}t-=r-e.getDate()+1,e.setDate(1),11>n?e.setMonth(n+1):(e.setMonth(0),e.setFullYear(e.getFullYear()+1))}return n=new Date(e.getFullYear()+1,0,4),t=u(new Date(e.getFullYear(),0,4)),n=u(n),0>=l(t,e)?0>=l(n,e)?e.getFullYear()+1:e.getFullYear():e.getFullYear()-1}e>>>=0,t>>>=0,n>>>=0,r>>>=0;var c=o()[r+40>>>2>>>0];for(var p in r={kc:s()[r>>>2>>>0],jc:s()[r+4>>>2>>>0],Hb:s()[r+8>>>2>>>0],Lb:s()[r+12>>>2>>>0],Ib:s()[r+16>>>2>>>0],Cb:s()[r+20>>>2>>>0],ub:s()[r+24>>>2>>>0],Bb:s()[r+28>>>2>>>0],rc:s()[r+32>>>2>>>0],ic:s()[r+36>>>2>>>0],lc:c?Oe(c):""},n=Oe(n),c={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(p,"g"),c[p]);var h,m,f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),g="January February March April May June July August September October November December".split(" ");for(p in c={"%a":e=>f[e.ub].substring(0,3),"%A":e=>f[e.ub],"%b":e=>g[e.Ib].substring(0,3),"%B":e=>g[e.Ib],"%C":e=>a((e.Cb+1900)/100|0,2),"%d":e=>a(e.Lb,2),"%e":e=>i(e.Lb,2," "),"%g":e=>d(e).toString().substring(2),"%G":d,"%H":e=>a(e.Hb,2),"%I":e=>(0==(e=e.Hb)?e=12:12{for(var t=0,n=0;n<=e.Ib-1;t+=($n(e.Cb+1900)?lr:ur)[n++]);return a(e.Lb+t,3)},"%m":e=>a(e.Ib+1,2),"%M":e=>a(e.jc,2),"%n":()=>"\n","%p":e=>0<=e.Hb&&12>e.Hb?"AM":"PM","%S":e=>a(e.kc,2),"%t":()=>"\t","%u":e=>e.ub||7,"%U":e=>a(Math.floor((e.Bb+7-e.ub)/7),2),"%V":e=>{var t=Math.floor((e.Bb+7-(e.ub+6)%7)/7);if(2>=(e.ub+371-e.Bb-2)%7&&t++,t)53==t&&(4==(n=(e.ub+371-e.Bb)%7)||3==n&&$n(e.Cb)||(t=1));else{t=52;var n=(e.ub+7-e.Bb-1)%7;(4==n||5==n&&$n(e.Cb%400-1))&&t++}return a(t,2)},"%w":e=>e.ub,"%W":e=>a(Math.floor((e.Bb+7-(e.ub+6)%7)/7),2),"%y":e=>(e.Cb+1900).toString().substring(2),"%Y":e=>e.Cb+1900,"%z":e=>(0<=(e=e.ic)?"+":"-")+("0000"+((e=Math.abs(e)/60)/60*100+e%60)).slice(-4),"%Z":e=>e.lc,"%%":()=>"%"},n=n.replace(/%%/g,"\0\0"),c)n.includes(p)&&(n=n.replace(new RegExp(p,"g"),c[p](r)));return h=n=n.replace(/\0\0/g,"%"),m=Array(Ne(h)+1),De(h,m,0,m.length),(p=m).length>t?0:(dr(p,e),p.length-1)}function pr(e,t,n,r){return cr(e>>>0,t>>>0,n>>>0,r>>>0)}g||function(){for(var e=p.numThreads-1;e--;)ke();W.unshift((()=>{var e;X++,e=()=>Z(),g?e():Promise.all(_e.map(Te)).then(e)}))}();for(var hr=Array(256),mr=0;256>mr;++mr)hr[mr]=String.fromCharCode(mr);Ze=hr,Je=p.BindingError=class extends Error{constructor(e){super(e),this.name="BindingError"}},p.InternalError=class extends Error{constructor(e){super(e),this.name="InternalError"}},ct.push(0,1,void 0,1,null,1,!0,1,!1,1),p.count_emval_handles=()=>ct.length/2-5-dt.length;var fr=[me,fe,Fe,Be,Le,Ve,je,qe,Ge,Ue,We,He,Ke,Xe,Qe,Ye,Fn,An,tr,nr,rr,ir,ar,or],gr=function(){function e(e,t){return gr=e.exports,gr=function(){var e=gr,t={};for(let[n,r]of Object.entries(e))t[n]="function"==typeof r?(...e)=>{Xt.push(n);try{return r(...e)}finally{G||(Xt.pop(),Ht&&1===Wt&&0===Xt.length&&(Wt=0,pe+=1,Ut(Or),typeof Fibers<"u"&&Fibers.sc()))}}:r;return t}(),n=gr,r=e=>t=>e(t)>>>0,i=e=>()=>e()>>>0,(n=Object.assign({},n)).Ca=r(n.Ca),n.fb=i(n.fb),n.hb=r(n.hb),n.emscripten_main_runtime_thread_id=i(n.emscripten_main_runtime_thread_id),n.sb=r(n.sb),n.tb=i(n.tb),gr=n,be.push(gr.ib),H.unshift(gr.Ba),A=t,Z(),gr;var n,r,i}var t,r,i,a=ae();if(X++,p.instantiateWasm)try{return p.instantiateWasm(a,e)}catch(t){C(`Module.instantiateWasm callback failed with error: ${t}`),c(t)}return ee||=p.locateFile?te("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":p.locateFile?p.locateFile("ort-wasm-simd-threaded.jsep.wasm",M):M+"ort-wasm-simd-threaded.jsep.wasm":new URL(n(/*! ort-wasm-simd-threaded.jsep.wasm */"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),n.b).href,(t=a,r=function(t){e(t.instance,t.module)},i=ee,T||"function"!=typeof WebAssembly.instantiateStreaming||te(i)||ne(i)||"function"!=typeof fetch?ie(i,t,r):fetch(i,{credentials:"same-origin"}).then((e=>WebAssembly.instantiateStreaming(e,t).then(r,(function(e){return C(`wasm streaming compile failed: ${e}`),C("falling back to ArrayBuffer instantiation"),ie(i,t,r)}))))).catch(c),{}}(),_r=e=>(_r=gr.Ca)(e),wr=()=>(wr=gr.Da)();p._OrtInit=(e,t)=>(p._OrtInit=gr.Ea)(e,t),p._OrtGetLastError=(e,t)=>(p._OrtGetLastError=gr.Fa)(e,t),p._OrtCreateSessionOptions=(e,t,n,r,i,a,s,o,l,u)=>(p._OrtCreateSessionOptions=gr.Ga)(e,t,n,r,i,a,s,o,l,u),p._OrtAppendExecutionProvider=(e,t)=>(p._OrtAppendExecutionProvider=gr.Ha)(e,t),p._OrtAddFreeDimensionOverride=(e,t,n)=>(p._OrtAddFreeDimensionOverride=gr.Ia)(e,t,n),p._OrtAddSessionConfigEntry=(e,t,n)=>(p._OrtAddSessionConfigEntry=gr.Ja)(e,t,n),p._OrtReleaseSessionOptions=e=>(p._OrtReleaseSessionOptions=gr.Ka)(e),p._OrtCreateSession=(e,t,n)=>(p._OrtCreateSession=gr.La)(e,t,n),p._OrtReleaseSession=e=>(p._OrtReleaseSession=gr.Ma)(e),p._OrtGetInputOutputCount=(e,t,n)=>(p._OrtGetInputOutputCount=gr.Na)(e,t,n),p._OrtGetInputName=(e,t)=>(p._OrtGetInputName=gr.Oa)(e,t),p._OrtGetOutputName=(e,t)=>(p._OrtGetOutputName=gr.Pa)(e,t),p._OrtFree=e=>(p._OrtFree=gr.Qa)(e),p._OrtCreateTensor=(e,t,n,r,i,a)=>(p._OrtCreateTensor=gr.Ra)(e,t,n,r,i,a),p._OrtGetTensorData=(e,t,n,r,i)=>(p._OrtGetTensorData=gr.Sa)(e,t,n,r,i),p._OrtReleaseTensor=e=>(p._OrtReleaseTensor=gr.Ta)(e),p._OrtCreateRunOptions=(e,t,n,r)=>(p._OrtCreateRunOptions=gr.Ua)(e,t,n,r),p._OrtAddRunConfigEntry=(e,t,n)=>(p._OrtAddRunConfigEntry=gr.Va)(e,t,n),p._OrtReleaseRunOptions=e=>(p._OrtReleaseRunOptions=gr.Wa)(e),p._OrtCreateBinding=e=>(p._OrtCreateBinding=gr.Xa)(e),p._OrtBindInput=(e,t,n)=>(p._OrtBindInput=gr.Ya)(e,t,n),p._OrtBindOutput=(e,t,n,r)=>(p._OrtBindOutput=gr.Za)(e,t,n,r),p._OrtClearBoundOutputs=e=>(p._OrtClearBoundOutputs=gr._a)(e),p._OrtReleaseBinding=e=>(p._OrtReleaseBinding=gr.$a)(e),p._OrtRunWithBinding=(e,t,n,r,i)=>(p._OrtRunWithBinding=gr.ab)(e,t,n,r,i),p._OrtRun=(e,t,n,r,i,a,s,o)=>(p._OrtRun=gr.bb)(e,t,n,r,i,a,s,o),p._OrtEndProfiling=e=>(p._OrtEndProfiling=gr.cb)(e),p._JsepOutput=(e,t,n)=>(p._JsepOutput=gr.db)(e,t,n),p._JsepGetNodeName=e=>(p._JsepGetNodeName=gr.eb)(e);var br,yr=()=>(yr=gr.fb)(),xr=p._free=e=>(xr=p._free=gr.gb)(e),vr=p._malloc=e=>(vr=p._malloc=gr.hb)(e),Mr=(e,t,n,r,i,a)=>(Mr=gr.kb)(e,t,n,r,i,a),Tr=()=>(Tr=gr.lb)(),kr=(e,t,n,r,i)=>(kr=gr.mb)(e,t,n,r,i),$r=e=>($r=gr.nb)(e),Sr=e=>(Sr=gr.ob)(e),Cr=()=>(Cr=gr.pb)(),Er=(e,t)=>(Er=gr.qb)(e,t),Pr=e=>(Pr=gr.rb)(e),Fr=e=>(Fr=gr.sb)(e),Ar=()=>(Ar=gr.tb)(),Ir=p.dynCall_ii=(e,t)=>(Ir=p.dynCall_ii=gr.vb)(e,t),zr=e=>(zr=gr.wb)(e),Or=()=>(Or=gr.xb)(),Br=e=>(Br=gr.yb)(e),Lr=()=>(Lr=gr.zb)();function Nr(){0Ar(),p.stackRestore=e=>Pr(e),p.stackAlloc=e=>Fr(e),p.setValue=function(e,n,r="i8"){switch(r.endsWith("*")&&(r="*"),r){case"i1":case"i8":t()[e>>>0]=n;break;case"i16":i()[e>>>1>>>0]=n;break;case"i32":s()[e>>>2>>>0]=n;break;case"i64":V[e>>>3]=BigInt(n);break;case"float":l()[e>>>2>>>0]=n;break;case"double":u()[e>>>3>>>0]=n;break;case"*":o()[e>>>2>>>0]=n;break;default:J(`invalid type for setValue: ${r}`)}},p.getValue=function(e,n="i8"){switch(n.endsWith("*")&&(n="*"),n){case"i1":case"i8":return t()[e>>>0];case"i16":return i()[e>>>1>>>0];case"i32":return s()[e>>>2>>>0];case"i64":return V[e>>>3];case"float":return l()[e>>>2>>>0];case"double":return u()[e>>>3>>>0];case"*":return o()[e>>>2>>>0];default:J(`invalid type for getValue: ${n}`)}},p.UTF8ToString=Oe,p.stringToUTF8=Re,p.lengthBytesUTF8=Ne,Y=function e(){br||Nr(),br||(Y=e)},Nr(),p.PTR_SIZE=4,h},ve=xe,"em-pthread"===globalThis.self?.name&&xe()})),Xl=j((()=>{he(),Me=import.meta.url??(typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0),Te=typeof location>"u"?void 0:location.origin,ke=(e,t)=>{try{let n=t??Me;return(n?new URL(e,n):new URL(e)).origin===Te}catch{return!1}},$e=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Se=(we(),G(me)).default,Ce=async()=>{if(!Me)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(ke(Me))return[void 0,Se()];let e=await $e(Me);return[e,Se(e)]},Ee=(Kl(),G(be)).default,Pe=async(e,t,n)=>[void 0,Ee]})),Ql=j((()=>{Xl(),Ae=!1,Ie=!1,ze=!1,Oe=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Be=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Le=async e=>{if(Ae)return Promise.resolve();if(Ie)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(ze)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ie=!0;let t=e.initTimeout,n=e.numThreads;if(!Be())throw new Error("WebAssembly SIMD is not supported in the current environment.");let r=Oe();n>1&&!r&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+n+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=n=1);let i=e.wasmPaths,a="string"==typeof i?i:void 0,s=i?.mjs,o=s?.href??s,l=i?.wasm,u=l?.href??l,d=e.wasmBinary,[c,p]=await Pe(o,a,n>1),h=!1,m=[];if(t>0&&m.push(new Promise((e=>{setTimeout((()=>{h=!0,e()}),t)}))),m.push(new Promise(((e,t)=>{let r={numThreads:n};d?r.wasmBinary=d:(u||a)&&(r.locateFile=(e,t)=>u??(a??t)+e),p(r).then((t=>{Ie=!1,Ae=!0,Fe=t,e(),c&&URL.revokeObjectURL(c)}),(e=>{Ie=!1,ze=!0,t(e)}))}))),await Promise.race(m),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ne=()=>{if(Ae&&Fe)return Fe;throw new Error("WebAssembly is not initialized yet.")}})),Yl=j((()=>{Ql(),De=(e,t)=>{let n=Ne(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},Re=(e,t,n,r)=>{if("object"==typeof e&&null!==e){if(n.has(e))throw new Error("Circular reference in options");n.add(e)}Object.entries(e).forEach((([e,i])=>{let a=t?t+e:e;if("object"==typeof i)Re(i,a+".",n,r);else if("string"==typeof i||"number"==typeof i)r(a,i.toString());else{if("boolean"!=typeof i)throw new Error("Can't handle extra config type: "+typeof i);r(a,i?"1":"0")}}))},Ve=e=>{let t=Ne(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,4===n?"i32":"i64")),a=t.getValue(r+n,"*"),s=a?t.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${s}`)}finally{t.stackRestore(n)}}})),Zl=j((()=>{Ql(),Yl(),je=e=>{let t=Ne(),n=0,r=[],i=e||{};try{if(void 0===e?.logSeverityLevel)i.logSeverityLevel=2;else if("number"!=typeof e.logSeverityLevel||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(void 0===e?.logVerbosityLevel)i.logVerbosityLevel=0;else if("number"!=typeof e.logVerbosityLevel||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);void 0===e?.terminate&&(i.terminate=!1);let a=0;return void 0!==e?.tag&&(a=De(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),0===n&&Ve("Can't create run options."),void 0!==e?.extra&&Re(e.extra,"",new WeakSet,((e,i)=>{let a=De(e,r),s=De(i,r);0!==t._OrtAddRunConfigEntry(n,a,s)&&Ve(`Can't set a run config entry: ${e} - ${i}.`)})),[n,r]}catch(e){throw 0!==n&&t._OrtReleaseRunOptions(n),r.forEach((e=>t._free(e))),e}}})),Jl=j((()=>{Ql(),Yl(),qe=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},Ge=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Ue=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some((e=>"webgpu"===("string"==typeof e?e:e.name)))&&(e.enableMemPattern=!1)},We=(e,t,n)=>{for(let r of t){let t="string"==typeof r?r:r.name;switch(t){case"webnn":if(t="WEBNN","string"!=typeof r){let t=r?.deviceType;if(t){let r=De("deviceType",n),i=De(t,n);0!==Ne()._OrtAddSessionConfigEntry(e,r,i)&&Ve(`Can't set a session config entry: 'deviceType' - ${t}.`)}}break;case"webgpu":if(t="JS","string"!=typeof r){let t=r;if(t?.preferredLayout){if("NCHW"!==t.preferredLayout&&"NHWC"!==t.preferredLayout)throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${t.preferredLayout}`);let r=De("preferredLayout",n),i=De(t.preferredLayout,n);0!==Ne()._OrtAddSessionConfigEntry(e,r,i)&&Ve(`Can't set a session config entry: 'preferredLayout' - ${t.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${t}`)}let i=De(t,n);0!==Ne()._OrtAppendExecutionProvider(e,i)&&Ve(`Can't append execution provider: ${t}.`)}},He=e=>{let t=Ne(),n=0,r=[],i=e||{};Ue(i);try{let e=qe(i.graphOptimizationLevel??"all"),a=Ge(i.executionMode??"sequential"),s="string"==typeof i.logId?De(i.logId,r):0,o=i.logSeverityLevel??2;if(!Number.isInteger(o)||o<0||o>4)throw new Error(`log serverity level is not valid: ${o}`);let l=i.logVerbosityLevel??0;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log verbosity level is not valid: ${l}`);let u="string"==typeof i.optimizedModelFilePath?De(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,s,o,l,u),0===n&&Ve("Can't create session options."),i.executionProviders&&We(n,i.executionProviders,r),void 0!==i.enableGraphCapture){if("boolean"!=typeof i.enableGraphCapture)throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let e=De("enableGraphCapture",r),a=De(i.enableGraphCapture.toString(),r);0!==t._OrtAddSessionConfigEntry(n,e,a)&&Ve(`Can't set a session config entry: 'enableGraphCapture' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if("string"!=typeof e)throw new Error(`free dimension override name must be a string: ${e}`);if("number"!=typeof a||!Number.isInteger(a)||a<0)throw new Error(`free dimension override value must be a non-negative integer: ${a}`);let i=De(e,r);0!==t._OrtAddFreeDimensionOverride(n,i,a)&&Ve(`Can't set a free dimension override: ${e} - ${a}.`)}return void 0!==i.extra&&Re(i.extra,"",new WeakSet,((e,i)=>{let a=De(e,r),s=De(i,r);0!==t._OrtAddSessionConfigEntry(n,a,s)&&Ve(`Can't set a session config entry: ${e} - ${i}.`)})),[n,r]}catch(e){throw 0!==n&&0!==t._OrtReleaseSessionOptions(n)&&Ve("Can't release session options."),r.forEach((e=>t._free(e))),e}}})),eu=j((()=>{Ke=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},Xe=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},Qe=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r="number"==typeof t?t:t.reduce(((e,t)=>e*t),1);return n>0?Math.ceil(r*n):void 0},Ye=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Ze=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},Je=e=>"float32"===e||"float16"===e||"int32"===e||"int64"===e||"uint32"===e||"uint8"===e||"bool"===e||"uint4"===e||"int4"===e,et=e=>"float32"===e||"float16"===e||"int32"===e||"int64"===e||"uint32"===e||"uint64"===e||"int8"===e||"uint8"===e||"bool"===e||"uint4"===e||"int4"===e,tt=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}})),tu=j((()=>{he(),nt=async e=>{if("string"==typeof e){{let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let n=t.headers.get("Content-Length"),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n,i=t.body.getReader();try{n=new ArrayBuffer(r)}catch(e){if(!(e instanceof RangeError))throw e;{let e=Math.ceil(r/65536);n=new WebAssembly.Memory({initial:e,maximum:e}).buffer}}let a=0;for(;;){let{done:e,value:t}=await i.read();if(e)break;let r=t.byteLength;new Uint8Array(n,a,r).set(t),a+=r}return new Uint8Array(n,0,r)}}}return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}})),nu=j((()=>{eu(),rt=["V","I","W","E","F"],it=(e,t)=>{console.log(`[${rt[e]},${(new Date).toISOString()}]${t}`)},ot=(e,t)=>{at=e,st=t},lt=(e,t)=>{let n=Ze(e);n>=Ze(at)&&it(n,"function"==typeof t?t():t)},ut=(...e)=>{st&<(...e)}})),ru=j((()=>{eu(),dt=(e,t)=>new(Ye(t))(e)})),iu=j((()=>{})),au=j((()=>{nu(),iu(),ct=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),pt=[],ht=e=>16*Math.ceil(Number(e)/16),mt=e=>{for(let t=0;tft++,_t=async(e,t,n,r)=>{let i=ht(n),a=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let s=e.getCommandEncoder();e.endComputePass(),s.copyBufferToBuffer(t,0,a,0,i),e.flush(),await a.mapAsync(GPUMapMode.READ);let o=a.getMappedRange();if(r){let e=r();return e.set(new Uint8Array(o,0,n)),e}return new Uint8Array(o.slice(0,n))}finally{a.destroy()}},wt=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[e]of ct)pt.push(e),this.freeBuffers.set(e,[]),this.freeUniformBuffers.set(e,[]);this.sessionCount=0}upload(e,t){let n=t.buffer,r=t.byteOffset,i=t.byteLength,a=ht(i),s=this.storageCache.get(e);if(!s)throw new Error("gpu data for uploading does not exist");if(Number(s.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${s.originalSize}, data size=${i}`);let o=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=o.getMappedRange();new Uint8Array(l).set(new Uint8Array(n,r,i)),o.unmap();let u=this.backend.device.createCommandEncoder();u.copyBufferToBuffer(o,0,s.gpuData.buffer,0,a),this.backend.device.queue.submit([u.finish()]),o.destroy(),ut("verbose",(()=>`[WebGPU] GpuDataManager.upload(id=${e})`))}memcpy(e,t){let n=this.storageCache.get(e);if(!n)throw new Error("source gpu data for memcpy does not exist");let r=this.storageCache.get(t);if(!r)throw new Error("destination gpu data for memcpy does not exist");if(n.originalSize!==r.originalSize)throw new Error("inconsistent source and destination gpu data size");let i=ht(n.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(n.gpuData.buffer,0,r.gpuData.buffer,0,i)}registerExternalBuffer(e,t,n){let r;if(n){if(r=n[0],e===n[1])return ut("verbose",(()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${r}, buffer is the same, skip.`)),r;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error("Registering a different external buffer under graph capture mode is not supported yet.\n Please use the previous external buffer!")}else r=gt();return this.storageCache.set(r,{gpuData:{id:r,type:0,buffer:e},originalSize:t}),ut("verbose",(()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${r}, registered.`)),r}unregisterExternalBuffer(e){void 0!==e&&(this.storageCache.delete(e),ut("verbose",(()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`)))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n,r=mt(e),i=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let e=(i?this.freeBuffers:this.freeUniformBuffers).get(r);n=e&&e.length>0?e.pop():this.backend.device.createBuffer({size:r,usage:t})}else n=this.backend.device.createBuffer({size:r,usage:t});let s={id:gt(),type:0,buffer:n};return this.storageCache.set(s.id,{gpuData:s,originalSize:Number(e)}),ut("verbose",(()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${s.id}`)),s}get(e){return this.storageCache.get(e)?.gpuData}release(e){let t="bigint"==typeof e?Number(e):e,n=this.storageCache.get(t);if(!n){if(0===this.storageCache.size)return 0;throw new Error("releasing data does not exist")}return ut("verbose",(()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${n.gpuData.id}`)),this.storageCache.delete(t),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(e,t){let n=this.storageCache.get(Number(e));if(!n)throw new Error("data does not exist");await _t(this.backend,n.gpuData.buffer,n.originalSize,t)}refreshPendingBuffers(){if(0!==this.buffersPending.length)if("default"===this.backend.sessionStatus){for(let e of this.buffersPending){let t=ct.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(e.size)||[];void 0===t||n.length>=t?e.destroy():n.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(e.size)||[];void 0===t||n.length>=t?e.destroy():n.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach((e=>{e.forEach((e=>{e.destroy()}))})),this.freeUniformBuffers.forEach((e=>{e.forEach((e=>{e.destroy()}))})),this.storageCache.forEach((e=>{e.gpuData.buffer.destroy()})),this.capturedPendingBuffers.forEach((e=>{e.forEach((e=>{e.destroy()}))})),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach((e=>{e.destroy()})),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,0===this.sessionCount&&(ut("warning",(()=>"[WebGPU] Clearing webgpu buffer cache")),this.storageCache.forEach((e=>{e.gpuData.buffer.destroy()})),this.storageCache=new Map)}},bt=(...e)=>new wt(...e)})),su=j((()=>{yt=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map((e=>`${this[e]}`)).join(";")),this.key}},xt=e=>new yt(e)})),ou=j((()=>{vt=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Mt=class{static calcShape(e,t,n=!1){let r=e.length,i=t.length;if(0===r)return t;if(0===i)return e;let a=Math.max(e.length,t.length),s=new Array(a);if(n){if(r<2||i<2)return;let n=vt.calcMatMulShape([e[r-2],e[r-1]],[t[i-2],t[i-1]]);if(void 0===n)return;[s[a-2],s[a-1]]=n}for(let o=n?3:1;o<=a;o++){let n=r-o<0?1:e[r-o],l=i-o<0?1:t[i-o];if(n!==l&&n>1&&l>1)return;let u=Math.max(n,l);if(n&&l)s[a-o]=Math.max(n,l);else{if(u>1)return;s[a-o]=0}}return s}static isValidBroadcast(e,t){let n=e.length,r=t.length;if(n>r)return!1;for(let i=1;i<=n;i++)if(1!==e[n-i]&&e[n-i]!==t[r-i])return!1;return!0}},Tt=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(e,t=4){let n=e.length;if(0===n)return[];let r=new Array(n),i=n-1;for(;i>=0;){if(e[i]%t==0){r[i]=e[i]/t;break}if(t%e[i]!=0)throw new Error("cannot convert shape");r[i]=1,t/=e[i],i--}for(i--;i>=0;i--)r[i]=e[i];return r}static sizeFromDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(e,t,n){let r=1;for(let i=t;i=0;--r)n[r]=n[r+1]*e[r+1];return n}static normalizeAxis(e,t){if(e<-t&&e>=t)throw new Error("unsupported axis for this operation.");return e<0?e+t:e}static normalizeAxes(e,t){return e.map((n=>this.normalizeAxis(n,t??e.length)))}static sortBasedOnPerm(e,t){return t?t.map((t=>e[t])):e.slice().reverse()}static padShape(e,t){let n=e.length;return e.map(((e,r)=>e+t[r]+t[r+n]))}static areEqual(e,t){return e.length===t.length&&e.every(((e,n)=>e===t[n]))}},kt=class e{static adjustPoolAttributes(e,t,n,r,i,a){if(!e&&n.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(e)for(let e=0;e=n.length?n.push(t[e+2]):n[e]=t[e+2];for(let e=0;e=n[e]||a[e+n.length]>=n[e])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,n,r,i,a,s,o){if(o){if(a.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(i.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{eu(),ou(),Et=64,Pt=(e,t)=>{if(3===t)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(4!==t)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},Ft=(e,t=1)=>{let n=Pt(e,t);return"string"==typeof n?n:n[0]},At=(e,t=1)=>{let n=Pt(e,t);return"string"==typeof n?n:n[1]},It=(...e)=>{let t=[];return e.forEach((e=>{0!==e.length&&t.push({type:12,data:e},{type:12,data:Tt.computeStrides(e)})})),t},zt=e=>e%4==0?4:e%2==0?2:1,Ot=(e="f32",t,n="0")=>t&&1!==t?`vec${t}<${e}>(${n})`:`${e}(${n})`,Bt=(e,t,n)=>"f32"===e?n:1===t?`f32(${n})`:`vec${t}(${n})`,Lt=(e,t)=>4===t?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:2===t?`(${e}.x + ${e}.y)`:3===t?`(${e}.x + ${e}.y + ${e}.z)`:e,Nt=(e,t,n,r)=>e.startsWith("uniforms.")&&n>4?"string"==typeof t?"f16"===r?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:"f16"===r?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:n>1?`${e}[${t}]`:e,Dt=(e,t,n,r,i)=>{let a="number"==typeof n,s=a?n:n.length,o=[...new Array(s).keys()],l=s<2?"u32":s<=4?`vec${s}`:`array`,u=Pt(t,i),d="string"==typeof u?u:u[1],c="string"==typeof u?u:u[0],p={indices:l,value:d,storage:c,tensor:t},h=e=>"string"==typeof e?e:`${e}u`,m={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},f=a?"uniforms.":"",g=`${f}${e}_shape`,_=`${f}${e}_strides`,w="";for(let e=0;e ${p.indices} {\n var indices: ${p.indices};\n var current = offset;\n ${w}\n return indices;\n }`,y=[];if(s>=2)for(let e=s-1;e>=0;e--)y.push(`${Nt(_,e,s)} * (indices[${e}])`);let x=s<2?"":`\n fn i2o_${e}(indices: ${p.indices}) -> u32 {\n return ${y.join("+")};\n }`,v=(...e)=>0===s?"0u":`${p.indices}(${e.map(h).join(",")})`,M=(e,t)=>s<2?`${e}`:`${Nt(e,t,s)}`,T={},k=(t,n)=>(()=>{if(p.storage===p.value)return`${e}[${t}]=${n};`;if("vec2"===p.storage&&"i32"===p.value)return`${e}[${t}]=vec2(u32(${n}), select(0u, 0xFFFFFFFFu, ${n} < 0));`;if("vec2"===p.storage&&"u32"===p.value)return`${e}[${t}]=vec2(u32(${n}), 0u);`;if("u32"===p.storage&&"vec4"===p.value)return`${e}[${t}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${n}));`;throw new Error(`not supported combination of storage type ${p.storage} and value type ${p.value} yet`)})(),$=t=>(()=>{if(p.storage===p.value)return`${e}[${t}]`;if("vec2"===p.storage&&"i32"===p.value)return`i32(${e}[${t}].x)`;if("vec2"===p.storage&&"u32"===p.value)return`u32(${e}[${t}].x)`;if("u32"===p.storage&&"vec4"===p.value)return`vec4(bool(${e}[${t}] & 0xFFu), bool(${e}[${t}] & 0xFF00u), bool(${e}[${t}] & 0xFF0000u), bool(${e}[${t}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${p.storage} and value type ${p.value} yet`)})(),S=s<2?"":`\n fn get_${e}ByIndices(indices: ${p.indices}) -> ${d} {\n return ${$(`i2o_${e}(indices)`)};\n }`,C=s<2?"":(()=>{let t=o.map((e=>`d${e}: u32`)).join(", "),n=o.map((e=>`d${e}`)).join(", ");return`\n fn get_${e}(${t}) -> ${d} {\n return get_${e}ByIndices(${v(n)});\n }`})(),E=s<2?"":`\n fn set_${e}ByIndices(indices: ${p.indices}, value: ${d}) {\n ${k(`i2o_${e}(indices)`,"value")}\n }`,P=s<2?"":(()=>{let t=o.map((e=>`d${e}: u32`)).join(", "),n=o.map((e=>`d${e}`)).join(", ");return`\n fn set_${e}(${t}, value: ${d}) {\n set_${e}ByIndices(${v(n)}, value);\n }`})();return{impl:()=>{let e=[],t=!1;return m.offsetToIndices&&(e.push(b),t=!0),m.indicesToOffset&&(e.push(x),t=!0),m.broadcastedIndicesToOffset&&(Object.values(T).forEach((t=>e.push(t))),t=!0),m.set&&(e.push(P),t=!0),m.setByIndices&&(e.push(E),t=!0),m.get&&(e.push(C),t=!0),m.getByIndices&&(e.push(S),t=!0),!a&&t&&e.unshift(`const ${g} = ${p.indices}(${n.join(",")});`,`const ${_} = ${p.indices}(${Tt.computeStrides(n).join(",")});`),e.join("\n")},type:p,offsetToIndices:t=>(m.offsetToIndices=!0,s<2?t:`o2i_${e}(${t})`),indicesToOffset:t=>(m.indicesToOffset=!0,s<2?t:`i2o_${e}(${t})`),broadcastedIndicesToOffset:(t,n)=>{m.broadcastedIndicesToOffset=!0;let r=`${n.name}broadcastedIndicesTo${e}Offset`;if(r in T)return`${r}(${t})`;let i=[];for(let e=s-1;e>=0;e--){let t=n.indicesGet("outputIndices",e+n.rank-s);i.push(`${M(_,e)} * (${t} % ${M(g,e)})`)}return T[r]=`fn ${r}(outputIndices: ${n.type.indices}) -> u32 {\n return ${i.length>0?i.join("+"):"0u"};\n }`,`${r}(${t})`},indices:v,indicesGet:M,indicesSet:(e,t,n)=>s<2?`${e}=${n};`:`${Nt(e,t,s)}=${n};`,set:(...t)=>{if(t.length!==s+1)throw new Error(`indices length must be ${s}`);let n=t[s];if("string"!=typeof n)throw new Error("value must be string");let r=t.slice(0,s).map(h).join(",");return 0===s?k("0u",n):1===s?k(r[0],n):(m.set=!0,m.setByIndices=!0,m.indicesToOffset=!0,`set_${e}(${r}, ${n})`)},setByOffset:k,setByIndices:(t,n)=>s<2?k(t,n):(m.setByIndices=!0,m.indicesToOffset=!0,`set_${e}ByIndices(${t}, ${n});`),get:(...t)=>{if(t.length!==s)throw new Error(`indices length must be ${s}`);let n=t.map(h).join(",");return 0===s?$("0u"):1===s?$(n[0]):(m.get=!0,m.getByIndices=!0,m.indicesToOffset=!0,`get_${e}(${n})`)},getByOffset:$,getByIndices:t=>s<2?$(t):(m.getByIndices=!0,m.indicesToOffset=!0,`get_${e}ByIndices(${t})`),usage:r,name:e,strides:_,shape:g,rank:s}},Rt=(e,t,n,r=1)=>Dt(e,t,n,"input",r),Vt=(e,t,n,r=1)=>Dt(e,t,n,"output",r),jt=(e,t,n)=>Dt(e,t,n,"atomicOutput",1),qt=(e,t,n,r=1)=>Dt(e,t,n,"internal",r),Gt=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${"number"==typeof e?`${e}u`:e}) { return; }`}mainStart(e=Et){let t="number"==typeof e?e:e[0],n="number"==typeof e?1:e[1],r="number"==typeof e?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||r>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${n}, ${r}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*n*r>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${n}, ${r}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=1===this.normalizedDispatchGroup[1]&&1===this.normalizedDispatchGroup[2];return`@compute @workgroup_size(${t}, ${n}, ${r})\n fn main(${i?"@builtin(global_invocation_id) global_id : vec3,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(local_invocation_id) local_id : vec3":"@builtin(global_invocation_id) global_id : vec3,\n @builtin(local_invocation_id) local_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(num_workgroups) num_workgroups : vec3"}) {\n ${i?"let global_idx = global_id.x;\n let workgroup_index = workgroup_id.x;":`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] +\n workgroup_id.y * num_workgroups[0] + workgroup_id.x;\n let global_idx = workgroup_index * ${t*n*r}u + local_idx;`}\n `}appendVariableUniforms(e){0!==e.rank&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if("internal"===e.usage)throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let n="input"===e.usage?"read":"read_write",r="atomicOutput"===e.usage?"atomic":e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${r}>;`}declareVariables(...e){return e.map((e=>this.declareVariable(e,this.variableIndex++))).join("\n")}registerInternalVariable(e){if("internal"!==e.usage)throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach((e=>this.registerInternalVariable(e))),this}registerUniform(e,t,n=1){return this.uniforms.push({name:e,type:t,length:n}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(0===this.uniforms.length)return"";let e=[];for(let{name:t,type:n,length:r}of this.uniforms)if(r&&r>4)"f16"===n?e.push(`@align(16) ${t}:array, ${Math.ceil(r/8)}>`):e.push(`${t}:array, ${Math.ceil(r/4)}>`);else{let i=null==r||1===r?n:`vec${r}<${n}>`;e.push(`${t}:${i}`)}return`\n struct Uniforms { ${e.join(", ")} };\n @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map((e=>e.impl())).join("\n")+this.internalVariables.map((e=>e.impl())).join("\n")}get variablesInfo(){if(0===this.uniforms.length)return;let e=e=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(e)];return this.uniforms.map((t=>[e(t.type),t.length??1]))}},Ut=(e,t)=>new Gt(e,t)})),uu=j((()=>{eu(),ou(),su(),lu(),Wt=e=>{if(!e||1!==e.length)throw new Error("Transpose requires 1 input.")},Ht=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,Kt=(e,t)=>Tt.sortBasedOnPerm(e,Ht(e.length,t)),Xt=(e,t,n,r)=>{let i=`fn perm(i: ${r.type.indices}) -> ${n.type.indices} {\n var a: ${n.type.indices};`;for(let r=0;r{let n=[],r=[];for(let i=0;i{let n=0;for(let r=0;r{let n,r=e.dataType,i=e.dims.length,a=Ht(i,t),s=Kt(e.dims,a),o=e.dims,l=s;if(Yt(a,e.dims))return n=e=>{let t=Rt("input",r,o,4),n=Vt("output",r,l,4);return`\n ${e.registerUniform("output_size","u32").declareVariables(t,n)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n output[global_idx] = input[global_idx];\n }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let t=Tt.size(s);return{outputs:[{dims:s,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(t/64/4)},programUniforms:[{type:12,data:Math.ceil(t/4)}]}},getShaderSource:n};let{newShape:u,newPerm:d}=Qt(e.dims,a),c=Tt.areEqual(d,[2,3,1]),p=Tt.areEqual(d,[3,1,2]);if(2===u.length||c||p){o=c?[u[0],u[1]*u[2]]:p?[u[0]*u[1],u[2]]:u,l=[o[1],o[0]];let t=16;return n=e=>{let n=Rt("a",r,o.length),i=Vt("output",r,l.length);return`\n ${e.registerUniform("output_size","u32").declareVariables(n,i)}\n var tile : array, ${t}>;\n ${e.mainStart([t,t,1])}\n let stride = (uniforms.output_shape[1] - 1) / ${t} + 1;\n let workgroup_id_x = workgroup_index % stride;\n let workgroup_id_y = workgroup_index / stride;\n let input_col = workgroup_id_y * ${t}u + local_id.x;\n let input_row = workgroup_id_x * ${t}u + local_id.y;\n if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) {\n tile[local_id.y][local_id.x] = ${n.getByIndices(`${n.type.indices}(input_row, input_col)`)};\n }\n workgroupBarrier();\n\n let output_col = workgroup_id_x * ${t}u + local_id.x;\n let output_row = workgroup_id_y * ${t}u + local_id.y;\n if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) {\n ${i.setByIndices(`${i.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")}\n }\n }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let n=Tt.size(s);return{outputs:[{dims:s,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(l[1]/t),y:Math.ceil(l[0]/t)},programUniforms:[{type:12,data:n},...It(o,l)]}},getShaderSource:n}}return n=e=>{let t=Rt("a",r,o.length),n=Vt("output",r,l.length);return`\n ${e.registerUniform("output_size","u32").declareVariables(t,n)}\n\n ${Xt(a,i,t,n)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${n.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${n.setByOffset("global_idx",t.getByIndices("aIndices"))}\n }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let t=Tt.size(s);return{outputs:[{dims:s,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(t/64)},programUniforms:[{type:12,data:t},...It(o,l)]}},getShaderSource:n}},Jt=(e,t)=>{Wt(e.inputs),e.compute(Zt(e.inputs[0],t.perm))},en=e=>xt({perm:e.perm})})),du=j((()=>{eu(),ou(),lu(),cu(),uu(),tn={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},nn={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},rn={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},an={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},sn=(e,t)=>{let n=[];for(let r=t-e;r{let n=[],r=e.length;for(let i=0;ie[t]))]},ln=(e,t)=>{let n=e.length+t.length,r=[],i=0;for(let a=0;a{for(let n=0;n{let n=[];if(!un(e,t)){for(let r=0;rn.push(e)))}return n},cn=(e,t,n,r,i,a,s)=>{let o=n[0].dims,l=Tt.size(a),u=Tt.size(s),d=Rt("_A",n[0].dataType,o),c=Vt("output",i,a),p=64;1===l&&(p=256);let h=`\n var aBestValues : array;\n `;return{name:e,shaderCache:{hint:`${t};${p}`,inputDependencies:["type"]},getShaderSource:e=>`\n ${e.registerUniform("reduceSize","u32").declareVariables(d,c)}\n ${h}\n fn DIV_CEIL(a : u32, b : u32) -> u32 {\n return ((a - 1u) / b + 1u);\n }\n ${e.mainStart(p)}\n\n let outputIndex = global_idx / ${p};\n let offset = outputIndex * uniforms.reduceSize;\n\n var bestValue = f32(${rn[r]});\n let Length = uniforms.reduceSize;\n for (var k = local_idx; k < Length; k = k + ${p}) {\n let candidate = f32(${d.getByOffset("offset + k")});\n bestValue = ${tn[r]};\n }\n aBestValues[local_idx] = bestValue;\n workgroupBarrier();\n\n var reduceSize = min(Length, ${p}u);\n for (var currentSize = reduceSize / 2u; reduceSize > 1u;\n currentSize = reduceSize / 2u) {\n let interval = DIV_CEIL(reduceSize, 2u);\n if (local_idx < currentSize) {\n let candidate = aBestValues[local_idx + interval];\n bestValue = ${nn[r]};\n aBestValues[local_idx] = bestValue;\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (local_idx == 0u) {\n ${c.setByOffset("outputIndex",""+("mean"===r?`${c.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${c.type.storage}(${an[r]})`))};\n }\n }`,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:l},programUniforms:[{type:12,data:u}]})}},pn=(e,t,n,r)=>{let i=1===e.inputs.length?n:$n(e.inputs,n),a=i.axes;0===a.length&&!i.noopWithEmptyAxes&&(a=e.inputs[0].dims.map(((e,t)=>t)));let s=Tt.normalizeAxes(a,e.inputs[0].dims.length),o=s,l=e.inputs[0],u=dn(o,e.inputs[0].dims.length);u.length>0&&(l=e.compute(Zt(e.inputs[0],u),{inputs:[0],outputs:[-1]})[0],o=sn(o.length,l.dims.length));let[d,c]=on(l.dims,o),p=d;i.keepDims&&(p=ln(d,s)),e.compute(cn(t,i.cacheKey,[l],r,e.inputs[0].dataType,p,c),{inputs:[l]})},hn=(e,t)=>{pn(e,"ReduceMeanShared",t,"mean")},mn=(e,t)=>{pn(e,"ReduceL1Shared",t,"l1")},fn=(e,t)=>{pn(e,"ReduceL2Shared",t,"l2")},gn=(e,t)=>{pn(e,"ReduceLogSumExpShared",t,"logSumExp")},_n=(e,t)=>{pn(e,"ReduceMaxShared",t,"max")},wn=(e,t)=>{pn(e,"ReduceMinShared",t,"min")},bn=(e,t)=>{pn(e,"ReduceProdShared",t,"prod")},yn=(e,t)=>{pn(e,"ReduceSumShared",t,"sum")},xn=(e,t)=>{pn(e,"ReduceSumSquareShared",t,"sumSquare")},vn=(e,t)=>{pn(e,"ReduceLogSumShared",t,"logSum")}})),cu=j((()=>{eu(),ou(),su(),lu(),du(),Mn=e=>{if(!e||0===e.length||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(2===e.length&&1!==e[1].dims.length)throw new Error("Invalid axes input dims.")},Tn=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],kn=(e,t,n,r,i,a,s=!1,o=!1)=>{let l=[],u=n[0].dims,d=u.length,c=Tt.normalizeAxes(i,d),p=!o&&0===c.length;u.forEach(((e,t)=>{p||c.indexOf(t)>=0?s&&l.push(1):l.push(e)}));let h=l.length,m=Tt.size(l);return{name:e,shaderCache:t,getShaderSource:e=>{let t=[],i=Rt("_A",n[0].dataType,d),o=Vt("output",a,h),l=r(i,o,c),m=l[2];for(let e=0,n=0;e=0?(s&&n++,m=`for(var j${e}: u32 = 0; j${e} < ${u[e]}; j${e}++) {\n ${l[2].includes("last_index")?`let last_index = j${e};`:""}\n ${i.indicesSet("input_indices",e,`j${e}`)}\n ${m}\n }`):(t.push(`${i.indicesSet("input_indices",e,o.indicesGet("output_indices",n))};`),n++);return`\n\n ${e.registerUniform("output_size","u32").declareVariables(i,o)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var input_indices: ${i.type.indices};\n let output_indices = ${o.offsetToIndices("global_idx")};\n\n ${t.join("\n")}\n ${l[0]} // init ops for reduce max/min\n ${l[1]}\n ${m}\n ${l[3]}\n ${4===l.length?o.setByOffset("global_idx","value"):l.slice(4).join("\n")}\n }`},getRunData:()=>({outputs:[{dims:l,dataType:a}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...It(u,l)]})}},$n=(e,t)=>{let n=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach((e=>n.push(Number(e)))),xt({axes:n,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},Sn=(e,t,n,r)=>{let i=e.inputs,a=1===i.length?n:$n(i,n);e.compute(kn(t,{hint:a.cacheKey,inputDependencies:["rank"]},[i[0]],a.noopWithEmptyAxes&&0===a.axes.length?Tn:r,a.axes,i[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},Cn=(e,t)=>{Mn(e.inputs),Sn(e,"ReduceLogSum",t,((e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += ${e.getByIndices("input_indices")};`,"value = log(value);"]))},En=(e,t)=>{Mn(e.inputs),Sn(e,"ReduceL1",t,((e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += abs(${e.getByIndices("input_indices")});`,""]))},Pn=(e,t)=>{Mn(e.inputs),Sn(e,"ReduceL2",t,((e,t)=>[`var t = ${t.type.value}(0); var value = ${t.type.value}(0);`,"",`t = ${e.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"]))},Fn=(e,t)=>{Mn(e.inputs),Sn(e,"ReduceLogSumExp",t,((e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += exp(${e.getByIndices("input_indices")});`,"value = log(value);"]))},An=(e,t)=>{Mn(e.inputs),Sn(e,"ReduceMax",t,((e,t,n)=>{let r=[];for(let t=0;t=0||0===n.length)&&r.push(e.indicesSet("input_indices",t,0));return[`${r.join("\n")}`,`var value = ${e.getByIndices("input_indices")};`,`value = max(value, ${e.getByIndices("input_indices")});`,""]}))},In=(e,t)=>{Mn(e.inputs),Sn(e,"ReduceMean",t,((t,n,r)=>{let i=1;for(let n=0;n=0||0===r.length)&&(i*=e.inputs[0].dims[n]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${i});`]}))},zn=(e,t)=>{Mn(e.inputs),Sn(e,"ReduceMin",t,((e,t,n)=>{let r=[];for(let t=0;t=0||0===n.length)&&r.push(`input_indices[${t}] = 0;`);return[`${r.join("\n")}`,`var value = ${e.getByIndices("input_indices")};`,`value = min(value, ${e.getByIndices("input_indices")});`,""]}))},On=(e,t)=>{Mn(e.inputs),Sn(e,"ReduceProd",t,((e,t)=>[`var value = ${t.type.storage}(1);`,"",`value *= ${e.getByIndices("input_indices")};`,""]))},Bn=(e,t)=>{Mn(e.inputs),Sn(e,"ReduceSum",t,((e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += ${e.getByIndices("input_indices")};`,""]))},Ln=(e,t)=>{Mn(e.inputs),Sn(e,"ReduceSumSquare",t,((e,t)=>[`var t = ${t.type.value}(0); var value = ${t.type.value}(0);`,"",`t = ${e.getByIndices("input_indices")}; value += t * t;`,""]))},Nn=(e,t,n)=>{if(0===t.length)return n;let r=1,i=1;for(let n=0;n1024},Dn=(e,t)=>{Nn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?In(e,t):hn(e,t)},Rn=(e,t)=>{Nn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?En(e,t):mn(e,t)},Vn=(e,t)=>{Nn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Pn(e,t):fn(e,t)},jn=(e,t)=>{Nn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Fn(e,t):gn(e,t)},qn=(e,t)=>{Nn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?An(e,t):_n(e,t)},Gn=(e,t)=>{Nn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?zn(e,t):wn(e,t)},Un=(e,t)=>{Nn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?On(e,t):bn(e,t)},Wn=(e,t)=>{Nn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Bn(e,t):yn(e,t)},Hn=(e,t)=>{Nn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ln(e,t):xn(e,t)},Kn=(e,t)=>{Nn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Cn(e,t):vn(e,t)}})),pu=j((()=>{eu(),su(),cu(),Xn=e=>{if(!e||0===e.length||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(1!==e[0].dataType)throw new Error("Invalid input type.")},Qn=(e,t)=>{Xn(e.inputs);e.compute(kn("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],((e,n,r)=>{let i=[];for(let t=0;t=0||0===r.length)&&i.push(`input_indices[${t}] = 0;`);return[`${i.join("\n")}`,`var value = ${e.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${e.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) {\n value = ${e.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",n.setByOffset("global_idx","best_index")]}),[t.axis],7,t.keepDims),{inputs:[0]})},Yn=(e,t)=>{Xn(e.inputs);e.compute(kn("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],((e,n,r)=>{let i=[];for(let t=0;t=0||0===r.length)&&i.push(`input_indices[${t}] = 0;`);return[`${i.join("\n")}`,`var value = ${e.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${e.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) {\n value = ${e.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",n.setByOffset("global_idx","best_index")]}),[t.axis],7,t.keepDims),{inputs:[0]})},Zn=e=>xt(e)})),hu=j((()=>{eu(),ou(),iu(),lu(),Jn=(e,t)=>{let n=e[0],r=e[1],i=e[2],a=e[3],s=e[4],o=e[5];if(s&&o)throw new Error("Attention cannot have both past and attention_bias");if(3!==n.dims.length)throw new Error('Input "input" must have 3 dimensions');let l=n.dims[0],u=n.dims[1],d=n.dims[2];if(1!==i.dims.length)throw new Error('Input "bias" is expected to have 1 dimensions');if(2!==r.dims.length)throw new Error('Input "weights" is expected to have 2 dimensions');if(r.dims[0]!==d)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==r.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let c=i.dims[0]/3,p=c,h=p;if(t.qkvHiddenSizes.length>0){if(3!==t.qkvHiddenSizes.length)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let e of t.qkvHiddenSizes)if(e%t.numHeads!=0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");c=t.qkvHiddenSizes[0],p=t.qkvHiddenSizes[1],h=t.qkvHiddenSizes[2]}let m=u;if(c!==p)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==c+p+h)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let f=0;if(s){if(p!==h)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(5!==s.dims.length)throw new Error('Input "past" must have 5 dimensions');if(2!==s.dims[0])throw new Error('Input "past" first dimension must be 2');if(s.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(s.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(s.dims[4]!==p/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(f=s.dims[3])}let g=m+f;if(a)throw new Error("Mask not supported");if(s)throw new Error("past is not supported");if(o){if(4!==o.dims.length)throw new Error('Input "attention_bias" must have 4 dimensions');if(o.dims[0]!==l||o.dims[1]!==t.numHeads||o.dims[2]!==u||o.dims[3]!==g)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:u,pastSequenceLength:f,kvSequenceLength:m,totalSequenceLength:g,maxSequenceLength:-1,inputHiddenSize:d,hiddenSize:c,vHiddenSize:h,headSize:Math.floor(c/t.numHeads),vHeadSize:Math.floor(h/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:0,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},er=(e,t,n)=>t&&e?`\n let total_sequence_length_input = u32(${t.getByOffset("0")});\n let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);\n let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;\n let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input;\n total_sequence_length = u32(${e?.getByOffset("batchIdx")}) + 1;\n var past_sequence_length: u32 = 0;\n if (is_first_prompt == false) {\n past_sequence_length = total_sequence_length - sequence_length;\n }\n `:`\n ${n?"let past_sequence_length = uniforms.past_sequence_length":""};\n let present_sequence_length = total_sequence_length;\n `,tr=(e,t,n,r,i,a,s,o)=>{let l=zt(s?1:a),u=64,d=a/l;d{let n=Vt("x",e.dataType,e.dims,l),r=[n],i=s?Rt("seq_lens",s.dataType,s.dims):void 0;i&&r.push(i);let a=o?Rt("total_sequence_length_input",o.dataType,o.dims):void 0;a&&r.push(a);let d=At(e.dataType);return`\n var thread_max: array;\n var thread_sum: array;\n ${t.registerUniforms([{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}]).declareVariables(...r)}\n ${t.mainStart([u,1,1])}\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let sequence_length = uniforms.sequence_length;\n var total_sequence_length = uniforms.total_sequence_length;\n ${er(i,a,!1)}\n let local_offset = local_idx * uniforms.elements_per_thread;\n let offset = (global_idx / ${u}) * uniforms.total_sequence_length + local_offset;\n let seq_causal_length = ${s?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"};\n var thread_max_vector = ${m}(-3.402823e+38f);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n thread_max_vector = max(${m}(x[offset + i]), thread_max_vector);\n }\n thread_max[local_idx] = ${(()=>{switch(l){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${l}`)}})()};\n workgroupBarrier();\n\n var max_value = f32(-3.402823e+38f);\n for (var i = 0u; i < ${u}; i++) {\n max_value = max(thread_max[i], max_value);\n }\n\n var sum_vector = ${m}(0);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n sum_vector += exp(${m}(x[offset + i]) - max_value);\n }\n thread_sum[local_idx] = ${(()=>{switch(l){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${l}`)}})()};\n workgroupBarrier();\n\n var sum: f32 = 0;\n for (var i = 0u; i < ${u}; i++) {\n sum += thread_sum[i];\n }\n\n if (sum == 0) {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n x[offset + i] = ${n.type.value}(${d}(1.0) / ${d}(seq_causal_length));\n }\n } else {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n var f32input = ${m}(x[offset + i]);\n x[offset + i] = ${n.type.value}(exp(f32input - max_value) / sum);\n }\n }\n ${s?`\n for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) {\n x[offset + total_seq_id] = ${n.type.value}(${d}(0));\n }`:""};\n }`},getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(a/u),y:i,z:t*n},programUniforms:p})}},nr=(e,t,n,r,i,a,s,o,l)=>{let u=s+a.kvSequenceLength,d=[a.batchSize,a.numHeads,a.sequenceLength,u],c=e>1&&r,p=a.kvNumHeads?a.kvNumHeads:a.numHeads,h=c?[a.batchSize,p,u,a.headSize]:void 0,m=a.nReps?a.nReps:1,f=0===a.scale?1/Math.sqrt(a.headSize):a.scale,g=zt(a.headSize),_=a.headSize/g,w=12,b={x:Math.ceil(u/w),y:Math.ceil(a.sequenceLength/w),z:a.batchSize*a.numHeads},y=[{type:12,data:a.sequenceLength},{type:12,data:_},{type:12,data:u},{type:12,data:a.numHeads},{type:12,data:a.headSize},{type:1,data:f},{type:12,data:s},{type:12,data:a.kvSequenceLength},{type:12,data:m}],x=c&&r&&Tt.size(r.dims)>0,v=["type","type"];x&&v.push("type"),i&&v.push("type"),o&&v.push("type"),l&&v.push("type");let M=[{dims:d,dataType:t.dataType,gpuDataType:0}];c&&M.push({dims:h,dataType:t.dataType,gpuDataType:0});return{name:"AttentionProbs",shaderCache:{hint:`${g};${void 0!==i};${void 0!==r};${e}`,inputDependencies:v},getRunData:()=>({outputs:M,dispatchGroup:b,programUniforms:y}),getShaderSource:e=>{let a=Rt("q",t.dataType,t.dims,g),s=[a,Rt("key",n.dataType,n.dims,g)];if(x){let e=Rt("past_key",r.dataType,r.dims,g);s.push(e)}i&&s.push(Rt("attention_bias",i.dataType,i.dims));let u=o?Rt("seq_lens",o.dataType,o.dims):void 0;u&&s.push(u);let p=l?Rt("total_sequence_length_input",l.dataType,l.dims):void 0;p&&s.push(p);let f=Vt("output",t.dataType,d),_=[f];c&&_.push(Vt("present_key",t.dataType,h,g));let b=At(1,g);return`\n const TILE_SIZE = 12u;\n\n var tileQ: array<${a.type.storage}, 144>;\n var tileK: array<${a.type.storage}, 144>;\n ${e.registerUniforms([{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}]).declareVariables(...s,..._)}\n ${e.mainStart([w,w,1])}\n // x holds the N and y holds the M\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let kvHeadIdx = ${1===m?"headIdx":"headIdx / uniforms.n_reps"};\n let kv_num_heads = ${1===m?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let m = workgroup_id.y * TILE_SIZE;\n let n = workgroup_id.x * TILE_SIZE;\n let sequence_length = uniforms.M;\n var total_sequence_length = uniforms.N;\n ${er(u,p,!0)}\n let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx;\n let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;\n ${x&&c?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""};\n let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K;\n ${c?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""}\n var value = ${b}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {\n var idx = TILE_SIZE * local_id.y + local_id.x;\n ${x&&c?"\n if (n + local_id.y < past_sequence_length) {\n tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x];\n } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {\n tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x];\n }":"\n if (n + local_id.y < uniforms.kv_sequence_length) {\n tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x];\n }"}\n ${c?"if (n + local_id.y < present_sequence_length) {\n present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];\n }":""}\n }\n workgroupBarrier();\n\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {\n value += ${b}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);\n }\n\n workgroupBarrier();\n }\n\n if (global_id.y < uniforms.M && global_id.x < total_sequence_length) {\n let headOffset = workgroup_id.z * uniforms.M * uniforms.N;\n let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;\n var sum: f32 = ${(()=>{switch(g){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${g}`)}})()};\n output[outputIdx] = ${f.type.value} (sum * uniforms.alpha) + ${i?"attention_bias[outputIdx]":"0.0"};\n }\n }`}}},rr=(e,t,n,r,i,a,s=void 0,o=void 0)=>{let l=a+i.kvSequenceLength,u=i.nReps?i.nReps:1,d=i.vHiddenSize*u,c=e>1&&r,p=i.kvNumHeads?i.kvNumHeads:i.numHeads,h=c?[i.batchSize,p,l,i.headSize]:void 0,m=[i.batchSize,i.sequenceLength,d],f=12,g={x:Math.ceil(i.vHeadSize/f),y:Math.ceil(i.sequenceLength/f),z:i.batchSize*i.numHeads},_=[{type:12,data:i.sequenceLength},{type:12,data:l},{type:12,data:i.vHeadSize},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:d},{type:12,data:a},{type:12,data:i.kvSequenceLength},{type:12,data:u}],w=c&&r&&Tt.size(r.dims)>0,b=["type","type"];w&&b.push("type"),s&&b.push("type"),o&&b.push("type");let y=[{dims:m,dataType:t.dataType,gpuDataType:0}];c&&y.push({dims:h,dataType:t.dataType,gpuDataType:0});return{name:"AttentionScore",shaderCache:{hint:`${void 0!==r};${e}`,inputDependencies:b},getRunData:()=>({outputs:y,dispatchGroup:g,programUniforms:_}),getShaderSource:e=>{let i=Rt("probs",t.dataType,t.dims),a=[i,Rt("v",n.dataType,n.dims)];w&&a.push(Rt("past_value",r.dataType,r.dims));let l=s?Rt("seq_lens",s.dataType,s.dims):void 0;s&&a.push(l);let d=o?Rt("total_sequence_length_input",o.dataType,o.dims):void 0;o&&a.push(d);let p=[Vt("output",t.dataType,m)];c&&p.push(Vt("present_value",t.dataType,h));return`\n const TILE_SIZE = 12u;\n var tileQ: array<${i.type.value}, 144>;\n var tileV: array<${i.type.value}, 144>;\n ${e.registerUniforms([{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}]).declareVariables(...a,...p)}\n ${e.mainStart([f,f,1])}\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let kvHeadIdx = ${1===u?"headIdx":"headIdx / uniforms.n_reps"};\n let kv_num_heads = ${1===u?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};\n let m = global_id.y;\n let n = global_id.x;\n let sequence_length = uniforms.M;\n var total_sequence_length = uniforms.K;\n ${er(l,d,!0)}\n let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;\n let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch\n ${w&&c?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""};\n let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n;\n ${c?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""}\n var value = ${i.type.storage}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n var idx = TILE_SIZE * local_id.y + local_id.x;\n ${w&&c?"\n if (w + local_id.y < past_sequence_length) {\n tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N];\n } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {\n tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N];\n }\n ":"\n if (w + local_id.y < uniforms.kv_sequence_length) {\n tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N];\n }"}\n ${c?"\n if (w + local_id.y < present_sequence_length) {\n present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx];\n }":""}\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) {\n value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x];\n }\n workgroupBarrier();\n }\n\n // we need to transpose output from BNSH_v to BSND_v\n if (m < uniforms.M && n < uniforms.N) {\n let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size\n + headIdx * uniforms.N + n;\n output[outputIdx] = value;\n }\n }`}}},ir=(e,t,n,r,i,a,s,o,l,u,d=void 0,c=void 0)=>{let p=Math.min(e.outputCount,1+(s?1:0)+(o?1:0)),h=p>1?u.pastSequenceLength:0,m=h+u.kvSequenceLength,f=l&&Tt.size(l.dims)>0?l:void 0,g=[t,n];p>1&&s&&Tt.size(s.dims)>0&&g.push(s),f&&g.push(f),d&&g.push(d),c&&g.push(c);let _=e.compute(nr(p,t,n,s,f,u,h,d,c),{inputs:g,outputs:p>1?[-1,1]:[-1]})[0];e.compute(tr(_,u.batchSize,u.numHeads,h,u.sequenceLength,m,d,c),{inputs:d&&c?[_,d,c]:[_],outputs:[]});let w=[_,r];p>1&&o&&Tt.size(o.dims)>0&&w.push(o),d&&w.push(d),c&&w.push(c),e.compute(rr(p,_,r,o,u,h,d,c),{inputs:w,outputs:p>1?[0,2]:[0]})},ar=(e,t)=>{let n=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],r=t.sequenceLength,i=t.inputHiddenSize,a=t.headSize,s=12,o={x:Math.ceil(t.headSize/s),y:Math.ceil(t.sequenceLength/s),z:t.batchSize*t.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],u=[{type:12,data:r},{type:12,data:i},{type:12,data:a},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}];return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:o,programUniforms:u}),getShaderSource:e=>{let t=Vt("output_q",l[0].dataType,n),r=Vt("output_k",l[0].dataType,n),i=Vt("output_v",l[0].dataType,n),a=Rt("input",l[0].dataType,l[0].dims),o=Rt("weight",l[1].dataType,l[1].dims),u=Rt("bias",l[2].dataType,l[2].dims),d=a.type.storage;return`\n const TILE_SIZE = 12u;\n var tileInput: array<${d}, 144>;\n var tileWeightQ: array<${d}, 144>;\n var tileWeightK: array<${d}, 144>;\n var tileWeightV: array<${d}, 144>;\n ${e.registerUniforms([{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}]).declareVariables(a,o,u,t,r,i)}\n ${e.mainStart([s,s,1])}\n let batchIndex = workgroup_id.z / uniforms.num_heads;\n let headNumber = workgroup_id.z % uniforms.num_heads;\n let m = global_id.y;\n let n = global_id.x;\n\n let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;\n let biasOffsetQ = headNumber * uniforms.head_size;\n let biasOffsetK = uniforms.hidden_size + biasOffsetQ;\n let biasOffsetV = uniforms.hidden_size + biasOffsetK;\n\n var valueQ = ${d}(0);\n var valueK = ${d}(0);\n var valueV = ${d}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n let offset = n + (w + local_id.y) * uniforms.ldb;\n tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];\n tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];\n tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k{let n=Jn(e.inputs,t),[r,i,a]=ar(e,n);return ir(e,r,i,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],n)}})),mu=j((()=>{pe(),eu(),ou(),su(),lu(),or=(e,t)=>{if(!e||5!==e.length)throw new Error("BatchNormalization requires 5 inputs");let n=(e,t,n)=>{let r=t.length;if(r!==e.length)throw new Error(`${n}: num dimensions != ${r}`);t.forEach(((t,r)=>{if(t!==e[r])throw new Error(`${n}: dim[${r}] do not match`)}))};if(e[0].dims.length>1){let r="NHWC"===t.format?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);n(e[1].dims,r,"Invalid input scale"),n(e[2].dims,r,"Invalid input B"),n(e[3].dims,r,"Invalid input mean"),n(e[4].dims,r,"Invalid input var")}else n(e[1].dims,[1],"Invalid input scale"),n(e[2].dims,[1],"Invalid input B"),n(e[3].dims,[1],"Invalid input mean"),n(e[4].dims,[1],"Invalid input var")},lr=(e,t)=>{let{epsilon:n,spatial:r,format:i}=t,a=e[0].dims,s=r?zt(a[a.length-1]):1,o="NHWC"===i&&a.length>1?s:1,l=Tt.size(a)/s,u=r,d=u?a.length:a,c=Rt("x",e[0].dataType,e[0].dims,s),p=Rt("scale",e[1].dataType,e[1].dims,o),h=Rt("bias",e[2].dataType,e[2].dims,o),m=Rt("inputMean",e[3].dataType,e[3].dims,o),f=Rt("inputVar",e[4].dataType,e[4].dims,o),g=Vt("y",e[0].dataType,d,s);return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${r}_${s}`,inputDependencies:u?["rank","type","type","type","type"]:void 0},getShaderSource:e=>`\n const epsilon = ${n};\n ${e.registerUniform("outputSize","u32").declareVariables(c,p,h,m,f,g)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${g.offsetToIndices(`global_idx * ${s}`)};\n ${(()=>{let e="";if(r)e=`let cOffset = ${1===a.length?"0u":"NHWC"===i?`outputIndices[${a.length-1}] / ${s}`:"outputIndices[1]"};`;else if("NCHW"===i)e=`\n ${g.indicesSet("outputIndices","0","0")}\n let cOffset = ${g.indicesToOffset("outputIndices")};`;else{e=`var cIndices = ${p.type.indices}(0);\n cIndices[0] = outputIndices[${a.length-1}];`;for(let t=1;t({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u?[{type:12,data:l},...It(a)]:[{type:12,data:l}]})}},ur=e=>xt(e),dr=(e,t)=>{let{inputs:n,outputCount:r}=e,i=ur({...t,outputCount:r});if(p.webgpu.validateInputContent&&or(n,i),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(lr(n,i))}})),fu=j((()=>{ou(),lu(),cr=e=>{if(3!==e[0].dims.length)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(1!==e[1].dims.length)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},pr=e=>{let t=e[0].dims,n=e[0].dims[2],r=Tt.size(t)/4,i=e[0].dataType,a=Rt("input",i,t,4),s=Rt("bias",i,[n],4),o=Rt("residual",i,t,4),l=Vt("output",i,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(r/64)}}),getShaderSource:e=>`\n const channels = ${n}u / 4;\n ${e.declareVariables(a,s,o,l)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(r)}\n let value = ${a.getByOffset("global_idx")}\n + ${s.getByOffset("global_idx % channels")} + ${o.getByOffset("global_idx")};\n ${l.setByOffset("global_idx","value")}\n }`}},hr=e=>{cr(e.inputs),e.compute(pr(e.inputs))}})),gu=j((()=>{eu(),ou(),su(),lu(),mr=(e,t,n,r,i,a,s)=>{let o=Math.ceil(t/4),l="";l="string"==typeof i?`${i}(a)`:i("a");let u=Rt("inputData",n,[o],4),d=Vt("outputData",r,[o],4),c=[{name:"vec_size",type:"u32"}];return s&&c.push(...s),`\n ${e.registerUniforms(c).declareVariables(u,d)}\n\n ${a??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n\n let a = ${u.getByOffset("global_idx")};\n ${d.setByOffset("global_idx",l)}\n }`},fr=(e,t,n,r,i,a=e.dataType,s,o)=>{let l=[{type:12,data:Math.ceil(Tt.size(e.dims)/4)}];return s&&l.push(...s),{name:t,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:t=>mr(t,Tt.size(e.dims),e.dataType,a,n,r,o),getRunData:t=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(Tt.size(t[0].dims)/64/4)},programUniforms:l})}},gr=e=>{e.compute(fr(e.inputs[0],"Abs","abs"))},_r=e=>{e.compute(fr(e.inputs[0],"Acos","acos"))},wr=e=>{e.compute(fr(e.inputs[0],"Acosh","acosh"))},br=e=>{e.compute(fr(e.inputs[0],"Asin","asin"))},yr=e=>{e.compute(fr(e.inputs[0],"Asinh","asinh"))},xr=e=>{e.compute(fr(e.inputs[0],"Atan","atan"))},vr=e=>{e.compute(fr(e.inputs[0],"Atanh","atanh"))},Mr=e=>xt(e),Tr=(e,t)=>{let n;switch(t.to){case 10:n="vec4";break;case 1:n="vec4";break;case 12:n="vec4";break;case 6:n="vec4";break;case 9:n="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(fr(e.inputs[0],"Cast",n,void 0,t.cacheKey,t.to))},kr=e=>{let t,n,r=e.length>=2&&0!==e[1].data,i=e.length>=3&&0!==e[2].data;switch(e[0].dataType){case 1:t=r?e[1].getFloat32Array()[0]:-34028234663852886e22,n=i?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=r?e[1].getUint16Array()[0]:64511,n=i?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return xt({min:t,max:n})},$r=(e,t)=>{let n=t||kr(e.inputs),r=At(e.inputs[0].dataType);e.compute(fr(e.inputs[0],"Clip",(e=>`clamp(${e}, vec4<${r}>(uniforms.min), vec4<${r}>(uniforms.max))`),void 0,n.cacheKey,void 0,[{type:e.inputs[0].dataType,data:n.min},{type:e.inputs[0].dataType,data:n.max}],[{name:"min",type:r},{name:"max",type:r}]),{inputs:[0]})},Sr=e=>{e.compute(fr(e.inputs[0],"Ceil","ceil"))},Cr=e=>{e.compute(fr(e.inputs[0],"Cos","cos"))},Er=e=>{e.compute(fr(e.inputs[0],"Cosh","cosh"))},Pr=e=>xt(e),Fr=(e,t)=>{let n=At(e.inputs[0].dataType);e.compute(fr(e.inputs[0],"Elu",(e=>`elu_vf32(${e})`),`\n const elu_alpha_ = ${n}(${t.alpha});\n\n fn elu_f32(a: ${n}) -> ${n} {\n return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);\n }\n\n fn elu_vf32(v: vec4<${n}>) -> vec4<${n}> {\n return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));\n }`,t.cacheKey))},Ar=(e="f32")=>`\nconst r0: ${e} = 0.3275911;\nconst r1: ${e} = 0.254829592;\nconst r2: ${e} = -0.284496736;\nconst r3: ${e} = 1.421413741;\nconst r4: ${e} = -1.453152027;\nconst r5: ${e} = 1.061405429;\n\nfn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {\n let absv = abs(v);\n let x = 1.0 / (1.0 + r0 * absv);\n return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));\n}`,Ir=e=>{let t=At(e.inputs[0].dataType);e.compute(fr(e.inputs[0],"Erf",(e=>`erf_vf32(${e})`),Ar(t)))},zr=e=>{e.compute(fr(e.inputs[0],"Exp","exp"))},Or=e=>{e.compute(fr(e.inputs[0],"Floor","floor"))},Br=e=>{let t=At(e.inputs[0].dataType);e.compute(fr(e.inputs[0],"Gelu",(e=>`0.5 * ${e} * (1.0 + erf_vf32(${e} * 0.7071067811865475))`),Ar(t)))},Lr=(e,t)=>{let n=At(e.inputs[0].dataType);e.compute(fr(e.inputs[0],"LeakyRelu",(e=>`select(leaky_relu_alpha_ * ${e}, ${e}, ${e} >= vec4<${n}>(0.0))`),`const leaky_relu_alpha_ = ${n}(${t.alpha});`,t.cacheKey))},Nr=e=>{e.compute(fr(e.inputs[0],"Not",(e=>`!${e}`)))},Dr=e=>{e.compute(fr(e.inputs[0],"Neg",(e=>`-${e}`)))},Rr=e=>{e.compute(fr(e.inputs[0],"Reciprocal",(e=>`1.0/${e}`)))},Vr=e=>{let t=At(e.inputs[0].dataType);e.compute(fr(e.inputs[0],"Relu",(e=>`select(vec4<${t}>(0.0), ${e}, ${e} > vec4<${t}>(0.0))`)))},jr=e=>{e.compute(fr(e.inputs[0],"Sigmoid",(e=>`(1.0 / (1.0 + exp(-${e})))`)))},qr=e=>xt(e),Gr=(e,t)=>{let n=At(e.inputs[0].dataType);e.compute(fr(e.inputs[0],"HardSigmoid",(e=>`max(vec4<${n}>(0.0), min(vec4<${n}>(1.0), ${t.alpha} * ${e} + vec4<${n}>(${t.beta})))`),void 0,t.cacheKey))},Ur=e=>{e.compute(fr(e.inputs[0],"Sin","sin"))},Wr=e=>{e.compute(fr(e.inputs[0],"Sinh","sinh"))},Hr=e=>{e.compute(fr(e.inputs[0],"Sqrt","sqrt"))},Kr=e=>{e.compute(fr(e.inputs[0],"Tan","tan"))},Xr=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Qr=e=>{e.compute(fr(e.inputs[0],"Tanh",Xr))},Yr=(e="f32")=>`\nconst fast_gelu_a: ${e} = 0.5;\nconst fast_gelu_b: ${e} = 0.7978845608028654;\nconst fast_gelu_c: ${e} = 0.035677408136300125;\n\nfn tanh_v(v: vec4<${e}>) -> vec4<${e}> {\n return ${Xr("v")};\n}\n`,Zr=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Jr=e=>{let t=At(e.inputs[0].dataType);e.compute(fr(e.inputs[0],"FastGelu",Zr,Yr(t),void 0,e.inputs[0].dataType))},ei=(e,t)=>{let n=At(e.inputs[0].dataType);return e.compute(fr(e.inputs[0],"ThresholdedRelu",(e=>`select(vec4<${n}>(0.0), ${e}, ${e} > thresholded_relu_alpha_)`),`const thresholded_relu_alpha_ = vec4<${n}>(${t.alpha});`,t.cacheKey)),0},ti=e=>{e.compute(fr(e.inputs[0],"Log","log"))},ni=(e,t)=>`\nconst alpha = vec4<${e}>(${t});\nconst one = ${e}(1.0);\nconst zero = ${e}(0.0);\n\nfn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {\n let v = x *alpha;\n var x1 : vec4<${e}>;\n for (var i = 0; i < 4; i = i + 1) {\n if (v[i] >= zero) {\n x1[i] = one / (one + exp(-v[i]));\n } else {\n x1[i] = one - one / (one + exp(v[i]));\n }\n }\n return x * x1;\n}\n`,ri=e=>`quick_gelu_impl(${e})`,ii=(e,t)=>{let n=At(e.inputs[0].dataType);e.compute(fr(e.inputs[0],"QuickGelu",ri,ni(n,t.alpha),t.cacheKey,e.inputs[0].dataType))}})),_u=j((()=>{ou(),lu(),gu(),ai=e=>{if(3!==e[0].dims.length)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(1!==e[1].dims.length)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},si=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let n=Rt("input",e[0].dataType,e[0].dims,4),r=Rt("bias",e[0].dataType,[e[0].dims[2]],4),i=Vt("output",e[0].dataType,t,4),a=Tt.size(t)/4,s=Ft(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:t=>`\n const M_SQRT2 = sqrt(2.0);\n const halfChannels = ${e[0].dims[2]/4/2}u;\n\n ${t.declareVariables(n,r,i)}\n\n ${Ar(s)}\n\n ${t.mainStart()}\n ${t.guardAgainstOutOfBoundsWorkgroupSizes(a)}\n let biasIdx = global_idx % halfChannels;\n let batchIndex = global_idx / halfChannels;\n let inputOffset = biasIdx + batchIndex * halfChannels * 2;\n let valueLeft = input[inputOffset] + bias[biasIdx];\n let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];\n let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);\n\n ${i.setByOffset("global_idx","valueLeft * geluRight")}\n }`}},oi=e=>{ai(e.inputs),e.compute(si(e.inputs))}})),wu=j((()=>{eu(),ou(),lu(),li=(e,t,n,r,i,a,s,o,l,u,d,c)=>{let p,h;"string"==typeof o?p=h=(e,t)=>`${o}((${e}),(${t}))`:"function"==typeof o?p=h=o:(p=o.scalar,h=o.vector);let m,f=Vt("outputData",d,r.length,4),g=Rt("aData",l,t.length,4),_=Rt("bData",u,n.length,4);if(i)if(a){let e=1===Tt.size(t),r=1===Tt.size(n),i=t.length>0&&t[t.length-1]%4==0,a=n.length>0&&n[n.length-1]%4==0;m=e||r?f.setByOffset("global_idx",h(e?`${g.type.value}(${g.getByOffset("0")}.x)`:g.getByOffset("global_idx"),r?`${_.type.value}(${_.getByOffset("0")}.x)`:_.getByOffset("global_idx"))):`\n let outputIndices = ${f.offsetToIndices("global_idx * 4u")};\n let offsetA = ${g.broadcastedIndicesToOffset("outputIndices",f)};\n let offsetB = ${_.broadcastedIndicesToOffset("outputIndices",f)};\n ${f.setByOffset("global_idx",h(s||i?g.getByOffset("offsetA / 4u"):`${g.type.value}(${g.getByOffset("offsetA / 4u")}[offsetA % 4u])`,s||a?_.getByOffset("offsetB / 4u"):`${_.type.value}(${_.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}\n `}else m=f.setByOffset("global_idx",h(g.getByOffset("global_idx"),_.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let e=(e,t,n="")=>{let r=`aData[indexA${t}][componentA${t}]`,i=`bData[indexB${t}][componentB${t}]`;return`\n let outputIndices${t} = ${f.offsetToIndices(`global_idx * 4u + ${t}u`)};\n let offsetA${t} = ${g.broadcastedIndicesToOffset(`outputIndices${t}`,f)};\n let offsetB${t} = ${_.broadcastedIndicesToOffset(`outputIndices${t}`,f)};\n let indexA${t} = offsetA${t} / 4u;\n let indexB${t} = offsetB${t} / 4u;\n let componentA${t} = offsetA${t} % 4u;\n let componentB${t} = offsetB${t} % 4u;\n ${e}[${t}] = ${n}(${p(r,i)});\n `};m=9===d?`\n var data = vec4(0);\n ${e("data",0,"u32")}\n ${e("data",1,"u32")}\n ${e("data",2,"u32")}\n ${e("data",3,"u32")}\n outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:`\n ${e("outputData[global_idx]",0)}\n ${e("outputData[global_idx]",1)}\n ${e("outputData[global_idx]",2)}\n ${e("outputData[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables(g,_,f)}\n\n ${c??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${m}\n }`},ui=(e,t,n,r,i,a,s=n.dataType)=>{let o=n.dims.map((e=>Number(e)??1)),l=r.dims.map((e=>Number(e)??1)),u=!Tt.areEqual(o,l),d=o,c=Tt.size(o),p=!1,h=!1,m=[u];if(u){let e=Mt.calcShape(o,l,!1);if(!e)throw new Error("Can't perform binary op on the given tensors");d=e.slice(),c=Tt.size(d);let t=1===Tt.size(o),n=1===Tt.size(l),r=o.length>0&&o[o.length-1]%4==0,i=l.length>0&&l[l.length-1]%4==0;m.push(t),m.push(n),m.push(r),m.push(i);let a=1;for(let e=1;ee.toString())).join("_"),inputDependencies:["rank","rank"]},getShaderSource:e=>li(e,o,l,d,p,u,h,i,n.dataType,r.dataType,s,a),getRunData:()=>({outputs:[{dims:d,dataType:s}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:Math.ceil(Tt.size(d)/4)},...It(o,l,d)]})}},di=(e,t,n,r,i,a)=>{e.compute(ui(t,i??"",e.inputs[0],e.inputs[1],n,r,a))},ci=e=>{di(e,"Add",((e,t)=>`${e}+${t}`))},pi=e=>{di(e,"Div",((e,t)=>`${e}/${t}`))},hi=e=>{di(e,"Equal",{scalar:(e,t)=>`u32(${e}==${t})`,vector:(e,t)=>`vec4(${e}==${t})`},void 0,void 0,9)},mi=e=>{di(e,"Mul",((e,t)=>`${e}*${t}`))},fi=e=>{let t=Rt("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;di(e,"Pow",{scalar:(e,t)=>`pow_custom(${e},${t})`,vector:(e,t)=>`pow_vector_custom(${e},${t})`},`\n fn pow_custom(a : ${t}, b : ${t}) -> ${t} {\n if (b == ${t}(0.0)) {\n return ${t}(1.0);\n } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {\n return ${t}(pow(f32(a), f32(b))); // NaN\n }\n return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${"i32"===t?"round":""}(pow(f32(abs(a)), f32(b))));\n }\n fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {\n // TODO: implement vectorized pow\n return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));\n }\n `)},gi=e=>{di(e,"Sub",((e,t)=>`${e}-${t}`))},_i=e=>{di(e,"Greater",{scalar:(e,t)=>`u32(${e}>${t})`,vector:(e,t)=>`vec4(${e}>${t})`},void 0,void 0,9)},wi=e=>{di(e,"Less",{scalar:(e,t)=>`u32(${e}<${t})`,vector:(e,t)=>`vec4(${e}<${t})`},void 0,void 0,9)},bi=e=>{di(e,"GreaterOrEqual",{scalar:(e,t)=>`u32(${e}>=${t})`,vector:(e,t)=>`vec4(${e}>=${t})`},void 0,void 0,9)},yi=e=>{di(e,"LessOrEqual",{scalar:(e,t)=>`u32(${e}<=${t})`,vector:(e,t)=>`vec4(${e}<=${t})`},void 0,void 0,9)}})),bu=j((()=>{eu(),ou(),su(),lu(),xi=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let n=e[0],r=n.dataType,i=n.dims.length;e.forEach(((e,a)=>{if(0!==a){if(e.dataType!==r)throw new Error("input tensors should be one type");if(e.dims.length!==i)throw new Error("input tensors should have the same shape");e.dims.forEach(((e,r)=>{if(r!==t&&e!==n.dims[r])throw new Error("non concat dimensions must match")}))}}))},vi=(e,t)=>`\n fn calculateInputIndex(index: u32) -> u32 {\n let sizeInConcatAxis = array(${t});\n for (var i: u32 = 0u; i < ${e}; i += 1u ) {\n if (index < sizeInConcatAxis[i]) {\n return i;\n }\n }\n return ${e}u;\n }`,Mi=(e,t)=>{let n=e.length,r=[];for(let i=0;i{let i=Tt.size(n),a=new Array(e.length),s=new Array(e.length),o=0,l=[],u=[],d=[{type:12,data:i}];for(let n=0;n`uniforms.sizeInConcatAxis${e}`)).join(",");return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:n,dataType:r}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:d}),getShaderSource:t=>`\n\n ${(()=>{t.registerUniform("outputSize","u32");for(let n=0;n(${h});\n ${p} -= sizeInConcatAxis[inputIndex - 1u];\n }\n\n ${Mi(s,c)}\n }`}},ki=(e,t)=>{let n=e.inputs,r=n[0].dims,i=Tt.normalizeAxis(t.axis,r.length);xi(n,i);let a=r.slice();a[i]=n.reduce(((e,t)=>e+(t.dims.length>i?t.dims[i]:0)),0);let s=n.filter((e=>Tt.size(e.dims)>0));e.compute(Ti(s,i,a,n[0].dataType),{inputs:s})},$i=e=>xt({axis:e.axis})})),yu=j((()=>{eu(),ou(),Si=(e,t,n="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${n}(uniforms.clip_min)), ${t}(${n}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${n}(uniforms.alpha) * value + ${n}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${n}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return"let e2x = exp(-2.0 * abs(value));\n value = sign(value) * (1.0 - e2x) / (1.0 + e2x);\n ";case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},Ci=(e,t)=>{"Clip"===e.activation?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):"HardSigmoid"===e.activation?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):"LeakyRelu"===e.activation&&t.push({type:1,data:e.alpha})},Ei=(e,t)=>{"Clip"===e.activation?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):"HardSigmoid"===e.activation?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):"LeakyRelu"===e.activation&&t.push({name:"alpha",type:"f32"})},Pi=e=>{let t=e?.activation||"";if("HardSigmoid"===t){let[n,r]=e?.activation_params||[.2,.5];return{activation:t,alpha:n,beta:r}}if("Clip"===t){let[n,r]=e?.activation_params||[St,Ct];return{activation:t,clipMax:r,clipMin:n}}if("LeakyRelu"===t){let[n]=e?.activation_params||[.01];return{activation:t,alpha:n}}return{activation:t}}})),xu=j((()=>{Fi=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},Ai=e=>`\n ${e?"value = value + getBiasByOutputCoords(coords);":""}\n `})),vu=j((()=>{Ii=e=>`\nfn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 {\n return dot(coords, vec4(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n}\nfn getOutputIndexFromCoords(coords : vec4) -> i32 {\n return dot(coords, vec4(\n i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));\n}\n`})),Mu=j((()=>{eu(),ou(),lu(),yu(),zi=(e,t,n,r,i)=>{let a=r-n;return`\n ${Array.from({length:n}).map(((n,s)=>`\n if (${Nt(t.shape,s,t.rank)} != 1) {\n ${t.indicesSet(e,s,Nt(i,s+a,r))}\n } else {\n ${t.indicesSet(e,s,0)}\n }`)).join("")}\n`},Oi=(e,t,n,r,i=!1,a)=>{let s=e[0].dims,o=e[1].dims,l=s[s.length-2],u=o[o.length-1],d=s[s.length-1],c=zt(u),p=zt(d),h=zt(l),m=Tt.size(n)/c/h,f=e.length>2,g=r?r.slice(0,-2):n.slice(0,-2),_=[Tt.size(g),l,u],w=[{type:12,data:m},{type:12,data:l},{type:12,data:u},{type:12,data:d}];Ci(t,w),w.push(...It(g,s,o)),f&&w.push(...It(e[2].dims)),w.push(...It(_));return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${c};${p};${h};${i}`,inputDependencies:f?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:a?a(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:w}),getShaderSource:r=>{let a=qt("batch_dims",e[0].dataType,g.length),l=Rt("a",e[0].dataType,s.length,p),u=Rt("b",e[1].dataType,o.length,c),d=Vt("output",e[0].dataType,_.length,c),m=Ft(d.type.tensor),w=Si(t,d.type.value,m),b=[l,u],y="";if(f){let t=i?c:1;b.push(Rt("bias",e[2].dataType,e[2].dims.length,t)),y=""+(i?`value += bias[col / ${t}];`:`value += ${d.type.value}(bias[row + i]);`)}let x=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Ei(t,x);return`\n ${r.registerUniforms(x).registerInternalVariables(a).declareVariables(...b,d)}\n ${r.mainStart()}\n ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let col = (global_idx % (uniforms.N / ${c})) * ${c};\n var index1 = global_idx / (uniforms.N / ${c});\n let stride1 = uniforms.M / ${h};\n let row = (index1 % stride1) * ${h};\n let batch = index1 / stride1;\n\n ${2===n.length?"":`let batch_indices = ${a.offsetToIndices("batch")};`}\n\n var a_indices: ${l.type.indices};\n ${zi("a_indices",l,l.rank-2,a.rank,"batch_indices")}\n ${l.indicesSet("a_indices",l.rank-2,0)}\n ${l.indicesSet("a_indices",l.rank-1,0)}\n let a_offset = ${l.indicesToOffset("a_indices")};\n\n var b_indices: ${u.type.indices};\n ${zi("b_indices",u,u.rank-2,a.rank,"batch_indices")}\n ${u.indicesSet("b_indices",u.rank-2,0)}\n ${u.indicesSet("b_indices",u.rank-1,0)}\n let b_offset = ${u.indicesToOffset("b_indices")};\n var values: array<${d.type.value}, ${h}>;\n for (var k: u32 = 0u; k < uniforms.K; k = k + ${p}) {\n ${(()=>{let e=`var a_data: ${l.type.value};`;for(let t=0;t{eu(),ou(),lu(),yu(),Mu(),xu(),Bi=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart / innerElementSize + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRow + innerRow,\n kStart / innerElementSize + inputCol${t?", batchIndices":""});\n `,Li=(e,t)=>e?`\n let ACached0 = mm_Asub[k * innerElementSize][localRow];\n let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];\n let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];\n ${3===t?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}\n for (var i = 0; i < rowPerThread; i = i + 1) {\n acc[i] = BCached0 * ACached0[i] + acc[i];\n acc[i] = BCached1 * ACached1[i] + acc[i];\n acc[i] = BCached2 * ACached2[i] + acc[i];\n ${3===t?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"}\n }`:`\n for (var i = 0; i < rowPerThread; i = i + 1) {\n let ACached = mm_Asub[tileRow + i][k];\n acc[i] = BCached0 * ACached.x + acc[i];\n acc[i] = BCached1 * ACached.y + acc[i];\n acc[i] = BCached2 * ACached.z + acc[i];\n ${3===t?"":"acc[i] = BCached3 * ACached.w + acc[i];"}\n }`,Ni=(e,t,n="f32",r,i=!1,a=32,s=!1,o=32)=>{let l=t[1]*e[1],u=t[0]*e[0],d=i?l:a,c=i?a:l,p=d/t[0],h=a/t[1];if((!i||4!==p||4!==e[1])&&(i||3!==p&&4!==p)||d%t[0]!=0||a%t[1]!=0||4!==e[0])throw new Error(`If transposeA ${i} is true, innerElementSize ${p} and workPerThread[1] ${e[1]} must be 4.\n Otherwise, innerElementSize ${p} must be 3 or 4.\n tileAWidth ${d} must be divisible by workgroupSize[0]${t[0]}. tileInner ${a} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`\nvar mm_Asub: array, ${d/p}>, ${c}>;\nvar mm_Bsub: array, ${u/e[0]}>, ${a}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${p};\nconst tileInner = ${a};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let localRow = i32(localId.y);\n let tileRow = localRow * rowPerThread;\n let tileCol = i32(localId.x);\n\n let globalRow =i32(globalId.y) * rowPerThread;\n let globalCol = i32(globalId.x);\n let batch = ${s?"0":"i32(globalId.z)"};\n ${r?`let batchIndices = ${r.offsetToIndices("u32(batch)")};`:""}\n let globalRowStart = i32(workgroupId.y) * ${l};\n\n let num_tiles = ${s?`${Math.ceil(o/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${s?`i32(globalId.z) * ${o}`:"0"};\n\n var acc: array, rowPerThread>;\n\n // Loop over shared dimension.\n let tileRowB = localRow * ${h};\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileCol;\n ${Bi(i,r)}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${h}; innerRow = innerRow + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${r?", batchIndices":""});\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {\n let BCached0 = mm_Bsub[k * innerElementSize][tileCol];\n let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];\n let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];\n ${3===p?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}\n\n ${Li(i,p)}\n }\n\n workgroupBarrier();\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);\n }\n}`},Di=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRowStart + inputRow,\n kStart + inputCol${t?", batchIndices":""});\n `,Ri=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Vi=(e,t,n="f32",r,i=!1,a=32,s=!1,o=32,l=!1)=>{let u=e[1]*t[1],d=e[0]*t[0],c=i?u:a,p=i?a:u;if(p%t[1]!=0||c%t[0]!=0||a%t[1]!=0)throw new Error(`tileAHight ${p} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${c} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let h=p/t[1],m=c/t[0],f=a/t[1],g=l?`\n let localRow = i32(localId.y);\n let localCol = i32(localId.x);\n let globalRowStart = i32(workgroupId.y) * ${u};\n let globalColStart = i32(workgroupId.x) * ${d};\n\n // Loop over shared dimension.\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var inputRow = localRow; inputRow < ${p}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${c}; inputCol = inputCol + ${t[0]}) {\n ${Di(i,r)}\n }\n }\n // Load one tile of B into local memory.\n for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${t[0]}) {\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalColStart + inputCol${r?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${n}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let ACached = ${i?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] +\n ACached * BCached[innerCol];\n }\n }\n }\n workgroupBarrier();\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let gRow = globalRowStart + localRow + innerRow * ${t[1]};\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let gCol = globalColStart + localCol + innerCol * ${t[0]};\n mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);\n }\n }\n `:`\nlet tileRow = i32(localId.y) * rowPerThread;\nlet tileCol = i32(localId.x) * colPerThread;\n\nlet globalRow = i32(globalId.y) * rowPerThread;\nlet globalCol = i32(globalId.x) * colPerThread;\nlet globalRowStart = i32(workgroupId.y) * ${u};\n\nlet tileRowA = i32(localId.y) * ${h};\nlet tileColA = i32(localId.x) * ${m};\nlet tileRowB = i32(localId.y) * ${f};\n// Loop over shared dimension.\nfor (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${h}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${m}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${Di(i,r)}\n }\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${f}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol + innerCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalCol + innerCol${r?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${n}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][tileCol + inner];\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n ${Ri(i)}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];\n }\n }\n }\n\n workgroupBarrier();\n}\n\nfor (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n mm_write(batch, globalRow + innerRow, globalCol + innerCol,\n acc[innerRow][innerCol]);\n }\n}\n`;return`\n var mm_Asub : array, ${p}>;\n var mm_Bsub : array, ${a}>;\n const rowPerThread = ${e[1]};\n const colPerThread = ${e[0]};\n const tileInner = ${a};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let batch = ${s?"0":"i32(globalId.z)"};\n ${r?`let batchIndices = ${r.offsetToIndices("u32(batch)")};`:""}\n let num_tiles = ${s?`${Math.ceil(o/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${s?`i32(globalId.z) * ${o}`:"0"};\n\n var acc : array, rowPerThread>;\n ${g}\n }\n`},ji=(e,t,n,r,i=!1)=>{let[a,s,o,l]=r,u=Ft(r[0].type.tensor);return`\n fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Fi(e,u)} {\n var value = ${Fi(e,u)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)\n {\n var aIndices: ${s.type.indices};\n ${zi("aIndices",s,s.rank-2,a.rank,"batchIndices")}\n ${s.indicesSet("aIndices",s.rank-2,"u32(row)")}\n ${s.indicesSet("aIndices",s.rank-1,"u32(colIn)")}\n value = ${s.getByIndices("aIndices")};\n }\n return value;\n }\n\n fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Fi(e,u)} {\n var value = ${Fi(e,u)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)\n {\n var bIndices: ${o.type.indices};\n ${zi("bIndices",o,o.rank-2,a.rank,"batchIndices")}\n ${o.indicesSet("bIndices",o.rank-2,"u32(row)")}\n ${o.indicesSet("bIndices",o.rank-1,"u32(colIn)")}\n value = ${o.getByIndices("bIndices")};\n }\n return value;\n }\n\n fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Fi(e,u)}) {\n let col = colIn * ${e};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueIn;\n let coords = vec3(batch, row, colIn);\n ${t?`value = value + ${i?"bias[colIn]":`${Fi(e,u)}(bias[row])`};`:""}\n ${n}\n ${l.setByIndices("vec3(coords)","value")}\n }\n }\n `},qi=(e,t,n,r,i=!1,a)=>{let s=e[0].dims,o=e[1].dims,l=s.slice(0,-2),u=o.slice(0,-2),d=r?r.slice(0,-2):n.slice(0,-2),c=Tt.size(d),p=s[s.length-2],h=s[s.length-1],m=o[o.length-1],f=h%4==0&&m%4==0,g=p<=8?[4,1,1]:[4,4,1],_=[8,8,1],w=[Math.ceil(m/_[0]/g[0]),Math.ceil(p/_[1]/g[1]),Math.ceil(c/_[2]/g[2])],b=f?4:1,y=[...l,p,h/b],x=y.length,v=[...u,h,m/b],M=v.length,T=[c,p,m/b],k=[{type:6,data:p},{type:6,data:m},{type:6,data:h}];Ci(t,k),k.push(...It(d,y,v));let $=["rank","rank"],S=e.length>2;S&&(k.push(...It(e[2].dims)),$.push("rank")),k.push(...It(T));return{name:"MatMul",shaderCache:{hint:`${g};${t.activation};${f};${i}`,inputDependencies:$},getRunData:()=>({outputs:[{dims:a?a(n):n,dataType:e[0].dataType}],dispatchGroup:{x:w[0],y:w[1],z:w[2]},programUniforms:k}),getShaderSource:n=>{let r=d.length,a=qt("batchDims",e[0].dataType,r,1),s=Ft(e[0].dataType),o=Rt("a",e[0].dataType,x,b),l=Rt("b",e[1].dataType,M,b),u=Vt("result",e[0].dataType,T.length,b),c=[o,l];if(S){let t=i?b:1;c.push(Rt("bias",e[2].dataType,e[2].dims.length,t))}let p=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Ei(t,p);let h=Ft(u.type.tensor),m=Si(t,u.type.value,h),w=ji(b,S,m,[a,o,l,u],i);return`\n ${n.registerUniforms(p).registerInternalVariables(a).declareVariables(...c,u)}\n ${w}\n ${f?Ni(g,_,s,a):Vi(g,_,s,a)}\n `}}}})),ku=j((()=>{eu(),nu(),lu(),yu(),xu(),vu(),Tu(),Gi=(e,t,n,r,i=!1,a,s=4,o=4,l=4,u="f32")=>{let d=e?"\n let coord = vec4(batch, xRow, xCol, xCh);\n ":"\n let coord = vec4(batch, xCh, xRow, xCol);\n ",c=e?"\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n ":"\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n ",p=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",h=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",m=e?"row":"col",f=e?"col":"row",g=`\n let inChannels = i32(uniforms.w_shape[2]);\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${m} / outWidth;\n let outCol = ${m} % outWidth;\n\n let WRow = ${f} / (i32(uniforms.w_shape[1]) * inChannels);\n let WCol = ${f} / inChannels % i32(uniforms.w_shape[1]);\n let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];\n let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];\n let xCh = ${f} % inChannels;\n var resData = ${Fi(s,u)}(0.0);\n // The bounds checking is always needed since we use it to pad zero for\n // the 'same' padding type.\n if (xRow >= 0 && xRow < ${p} && xCol >= 0 && xCol < ${h}) {\n ${d}\n let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape));\n ${(e=>{switch(e){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${u}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${e} is not supported.`)}})(s)}\n }\n return resData;`,_=e?t&&r?`\n let col = colIn * ${s};\n ${g}`:`\n let col = colIn * ${s};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${g}\n }\n return ${Fi(s,u)}(0.0);`:r&&n?`\n let col = colIn * ${s};\n ${g}`:`\n let col = colIn * ${s};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${g}\n }\n return ${Fi(s,u)}(0.0);`,w=`${(e=>{switch(e){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${e} is not supported.`)}})(o)}`,b=Fi(l,u),y=Fi(e?s:o,u),x=Fi(e?o:s,u),v=Si(a,b,u);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${y} {\n ${e?_:w}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${x} {\n ${e?w:_}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${b}) {\n let col = colIn * ${l};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)\n {\n var value = valueIn;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${c}\n ${Ai(i)}\n ${v}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`},Ui=(e,t,n,r,i,a,s,o,l)=>{let u="NHWC"===t.format,d=u?e[0].dims[3]:e[0].dims[1],c=n[0],p=u?n[2]:n[3],h=u?n[1]:n[2],m=u?n[3]:n[1],f=u&&(d%4==0||d%3==0)&&m%4==0,g=u?m:p*h,_=u?p*h:m,w=[8,8,1],b=r<=8?[4,1,1]:[4,4,1],y=[Math.ceil(g/w[0]/b[0]),Math.ceil(_/w[1]/b[1]),Math.ceil(c/w[2]/b[2])];ut("verbose",(()=>`[conv2d_mm_webgpu] dispatch = ${y}`));let x=f?u&&d%4!=0?3:4:1,v=w[1]*b[1],M=w[0]*b[0],T=Math.max(w[0]*x,w[1]),k=r%v==0,$=i%M==0,S=a%T==0,C=f?[x,4,4]:[1,1,1],E=[{type:6,data:r},{type:6,data:i},{type:6,data:a},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Ci(t,E),E.push(...It(e[0].dims,e[1].dims));let P=["rank","rank"];s&&(E.push(...It(e[2].dims)),P.push("rank")),E.push(...It(n));return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${x};${f};${k};${$};${S};${v};${M};${T}`,inputDependencies:P},getRunData:()=>({outputs:[{dims:l?l(n):n,dataType:e[0].dataType}],dispatchGroup:{x:y[0],y:y[1],z:y[2]},programUniforms:E}),getShaderSource:r=>{let i=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];Ei(t,i);let a=f?4:1,l=Ft(e[0].dataType),d=`\n fn setOutputAtIndex(flatIndex : i32, value : ${f?`vec4<${l}>`:l}) {\n result[flatIndex] = ${f?`vec4<${l}>`:l}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${f?`vec4<${l}>`:l}) {\n let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${f?"/ 4":""}, value);\n }`,c=[Rt("x",e[0].dataType,e[0].dims.length,3===x?1:x),Rt("w",e[1].dataType,e[1].dims.length,a)],p=Vt("result",e[0].dataType,n.length,a);if(s){let t=Rt("bias",e[2].dataType,e[2].dims.length,a);c.push(t),d+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${f?`vec4<${l}>`:l} {\n return bias[coords.${u?"w":"y"}${f?"/ 4":""}];\n }`}return`\n ${Ii("uniforms.result_strides")}\n //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4,\n // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2,\n // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };\n ${r.registerUniforms(i).declareVariables(...c,p)}\n ${d}\n ${Gi(u,k,$,S,s,t,C[0],C[1],C[2],l)}\n ${f?Ni(b,w,l,void 0,!u,T):Vi(b,w,l,void 0,!u,T,!1,void 0,o)}`}}}})),$u=j((()=>{eu(),nu(),ou(),lu(),yu(),xu(),Wi=e=>{let t=1;for(let n=0;n"number"==typeof e?[e,e,e]:e,Ki=(e,t)=>t<=1?e:e+(e-1)*(t-1),Xi=(e,t,n,r=1)=>{let i=Ki(t,r);return Math.floor((e[0]*(n-1)-n+i)/2)},Qi=(e,t,n,r,i)=>{null==i&&(i=Xi(e,t[0],r[0]));let a=[0,0,0,n];for(let n=0;n<3;n++)e[n]+2*i>=t[n]&&(a[n]=Math.trunc((e[n]-t[n]+2*i)/r[n]+1));return a},Yi=(e,t,n,r,i,a,s,o,l,u)=>{let d,c,p,h;if("VALID"===e&&(e=0),"number"==typeof e){d={top:e,bottom:e,left:e,right:e,front:e,back:e};let m=Qi([t,n,r,1],[o,l,u],1,[i,a,s],e);c=m[0],p=m[1],h=m[2]}else if(Array.isArray(e)){if(!e.every(((e,t,n)=>e===n[0])))throw Error(`Unsupported padding parameter: ${e}`);d={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let m=Qi([t,n,r,1],[o,l,u],1,[i,a,s],e[0]);c=m[0],p=m[1],h=m[2]}else{if("SAME_UPPER"!==e)throw Error(`Unknown padding parameter: ${e}`);{c=Math.ceil(t/i),p=Math.ceil(n/a),h=Math.ceil(r/s);let e=(c-1)*i+o-t,m=(p-1)*a+l-n,f=(h-1)*s+u-r,g=Math.floor(e/2),_=e-g,w=Math.floor(m/2),b=m-w,y=Math.floor(f/2);d={top:w,bottom:b,left:y,right:f-y,front:g,back:_}}}return{padInfo:d,outDepth:c,outHeight:p,outWidth:h}},Zi=(e,t,n,r,i,a=!1,s="channelsLast")=>{let o,l,u,d,c;if("channelsLast"===s)[o,l,u,d,c]=e;else{if("channelsFirst"!==s)throw new Error(`Unknown dataFormat ${s}`);[o,c,l,u,d]=e}let[p,,h,m,f]=t,[g,_,w]=Hi(n),[b,y,x]=Hi(r),v=Ki(h,b),M=Ki(m,y),T=Ki(f,x),{padInfo:k,outDepth:$,outHeight:S,outWidth:C}=Yi(i,l,u,d,g,_,w,v,M,T),E=a?p*c:p,P=[0,0,0,0,0];return"channelsFirst"===s?P=[o,E,$,S,C]:"channelsLast"===s&&(P=[o,$,S,C,E]),{batchSize:o,dataFormat:s,inDepth:l,inHeight:u,inWidth:d,inChannels:c,outDepth:$,outHeight:S,outWidth:C,outChannels:E,padInfo:k,strideDepth:g,strideHeight:_,strideWidth:w,filterDepth:h,filterHeight:m,filterWidth:f,effectiveFilterDepth:v,effectiveFilterHeight:M,effectiveFilterWidth:T,dilationDepth:b,dilationHeight:y,dilationWidth:x,inShape:e,outShape:P,filterShape:t}},Ji=(e,t,n,r,i,a)=>{let s="channelsLast"===a,o=(s?e[0].dims[3]:e[0].dims[1],{x:n.map(((e,t)=>t))}),l=[Math.ceil(Wi(o.x.map((e=>n[e])))/64),1,1];ut("verbose",(()=>`[conv3d_naive_webgpu] dispatch = ${l}`));let u=[{type:12,data:Tt.size(n)},{type:12,data:r},{type:12,data:i},{type:12,data:t.strides},{type:12,data:t.dilations}];Ci(t,u),u.push(...It(e[0].dims,e[1].dims));let d=["rank","rank"],c=3===e.length;c&&(u.push(...It(e[2].dims)),d.push("rank")),u.push(...It(n));return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${s};1;${c}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:l[0],y:l[1],z:l[2]},programUniforms:u}),getShaderSource:a=>{let o=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:r.length},{name:"pads",type:"u32",length:i.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Ei(t,o);let l=Ft(e[0].dataType),u=Rt("x",e[0].dataType,e[0].dims.length,1),d=Rt("W",e[1].dataType,e[1].dims.length,1),p=[u,d],h=Vt("result",e[0].dataType,n.length,1),m="";if(c){let t=Rt("bias",e[2].dataType,e[2].dims.length,1);p.push(t),m+=`\n fn getBiasByOutputCoords(coords : array) -> ${l} {\n return bias[${Nt("coords",s?4:1,5)}];\n }`}let f=Fi(1,l),g=Si(t,f,l);return`\n ${m}\n fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {\n let aIndices = array(d0, d1, d2, d3, d4);\n return ${u.getByIndices("aIndices")};\n }\n fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {\n let aIndices = array(d0, d1, d2, d3, d4);\n return ${d.getByIndices("aIndices")};\n }\n ${a.registerUniforms(o).declareVariables(...p,h)}\n ${a.mainStart()}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let coords = ${h.offsetToIndices("global_idx")};\n let batch = ${Nt("coords",0,u.rank)};\n let d2 = ${Nt("coords",s?u.rank-1:1,u.rank)};\n let xFRCCorner = vec3(${Nt("coords",s?1:2,u.rank)},\n ${Nt("coords",s?2:3,u.rank)},\n ${Nt("coords",s?3:4,u.rank)}) * uniforms.strides - uniforms.pads;\n let xFCorner = xFRCCorner.x;\n let xRCorner = xFRCCorner.y;\n let xCCorner = xFRCCorner.z;\n let xShapeY = ${Nt("uniforms.x_shape",s?1:2,u.rank)};\n let xShapeZ = ${Nt("uniforms.x_shape",s?2:3,u.rank)};\n let xShapeW = ${Nt("uniforms.x_shape",s?3:4,u.rank)};\n let xShapeU = ${Nt("uniforms.x_shape",s?4:1,u.rank)};\n let inputDepthNearestVec4 = (xShapeU / 4) * 4;\n let inputDepthVec4Remainder = xShapeU % 4;\n\n var value = 0.0;\n for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) {\n let xF = xFCorner + wF * uniforms.dilations[0];\n if (xF < 0 || xF >= xShapeY) {\n continue;\n }\n\n for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) {\n let xR = xRCorner + wR * uniforms.dilations[1];\n if (xR < 0 || xR >= xShapeZ) {\n continue;\n }\n\n for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) {\n let xC = xCCorner + wC * uniforms.dilations[2];\n if (xC < 0 || xC >= xShapeW) {\n continue;\n }\n\n for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) {\n ${s?"let 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 ":"let xValues = vec4(\n getX(batch, d1, xF, xR, xC),\n getX(batch, d1 + 1, xF, xR, xC),\n getX(batch, d1 + 2, xF, xR, xC),\n getX(batch, d1 + 3, xF, xR, xC));\n "}\n let wValues = vec4(\n getW(d2, d1, wF, wR, wC),\n getW(d2, d1 + 1, wF, wR, wC),\n getW(d2, d1 + 2, wF, wR, wC),\n getW(d2, d1 + 3, wF, wR, wC));\n value += dot(xValues, wValues);\n }\n if (inputDepthVec4Remainder == 1) {\n ${s?"value += getX(batch, xF, xR, xC, inputDepthNearestVec4)\n * getW(d2, inputDepthNearestVec4, wF, wR, wC);":"value += getX(batch, inputDepthNearestVec4, xF, xR, xC)\n * getW(d2, inputDepthNearestVec4, wF, wR, wC);"}\n } else if (inputDepthVec4Remainder == 2) {\n ${s?"let xValues = vec2(\n getX(batch, xF, xR, xC, inputDepthNearestVec4),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1));\n ":"let xValues = vec2(\n getX(batch, inputDepthNearestVec4, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC));\n "}\n let wValues = vec2(\n getW(d2, inputDepthNearestVec4, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC));\n value += dot(xValues, wValues);\n } else if (inputDepthVec4Remainder == 3) {\n ${s?"let xValues = vec3(\n getX(batch, xF, xR, xC, inputDepthNearestVec4),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2));\n ":"let xValues = vec3(\n getX(batch, inputDepthNearestVec4, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC));\n "}\n let wValues = vec3(\n getW(d2, inputDepthNearestVec4, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC));\n value += dot(xValues, wValues);\n }\n }\n }\n }\n ${c?"value = value + getBiasByOutputCoords(coords)":""};\n ${g}\n result[global_idx] = f32(value);\n }`}}}})),Su=j((()=>{eu(),ou(),lu(),yu(),ea=(e,t,n,r)=>{let i=e.length>2,a=i?"value += b[output_channel];":"",s=e[0].dims,o=e[1].dims,l="NHWC"===t.format,u=l?n[3]:n[1],d=u/t.group,c=l&&d>=4?zt(u):1,p=Tt.size(n)/c,h=[{type:12,data:p},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:d}];Ci(t,h),h.push(...It(s,[o[0],o[1],o[2],o[3]/c]));let m=i?["rank","rank","rank"]:["rank","rank"];h.push(...It([n[0],n[1],n[2],n[3]/c]));return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${c}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:r?r(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:r=>{let u=Vt("output",e[0].dataType,n.length,c),d=Ft(u.type.tensor),p=Si(t,u.type.value,d),h=Rt("x",e[0].dataType,s.length),m=Rt("w",e[1].dataType,o.length,c),f=[h,m];i&&f.push(Rt("b",e[2].dataType,e[2].dims,c));let g=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];Ei(t,g);let _=l?`\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) {\n continue;\n }\n\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) {\n let input_channel = in_channel_offset + wInChannel;\n let xVal = ${h.get("batch","xHeight","xWidth","input_channel")};\n let wVal = ${m.get("wHeight","wWidth","wInChannel","output_channel")};\n value += xVal * wVal;\n }\n }\n }\n `:`\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {\n let input_channel = in_channel_offset + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) {\n continue;\n }\n\n let xVal = ${h.get("batch","input_channel","xHeight","xWidth")};\n let wVal = ${m.get("output_channel","wInChannel","wHeight","wWidth")};\n value += xVal * wVal;\n }\n }\n }\n `;return`\n ${r.registerUniforms(g).declareVariables(...f,u)}\n\n ${r.mainStart()}\n ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let outputIndices = ${u.offsetToIndices("global_idx")};\n let batch: u32 = outputIndices[0];\n let output_channel: u32 = outputIndices[${l?3:1}];\n let xRCCorner: vec2 = vec2(outputIndices[${l?1:2}], outputIndices[${l?2:3}]) * uniforms.strides - uniforms.pads;\n let group_id: u32 = output_channel * ${c} / uniforms.output_channels_per_group;\n var in_channel_offset = group_id * uniforms.w_shape[${l?2:1}];\n\n var value: ${u.type.value} = ${u.type.value}(0);\n ${_}\n ${a}\n ${p}\n ${u.setByOffset("global_idx","value")}\n }`}}},ta=(e,t,n,r)=>{let i=e.length>2,a=zt(n[3]),s=zt(n[2]),o=Tt.size(n)/a/s,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],u=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],d=[n[0],n[1],n[2],n[3]/a],c=[{type:12,data:o},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Ci(t,c),c.push(...It(l,u,d));let p=(s-1)*t.strides[1]+u[1];return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${a};${s};${p};${u[0]};${u[1]}`,inputDependencies:i?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r?r(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:c}),getShaderSource:n=>{let r=Vt("output",e[0].dataType,d.length,a),o=Ft(r.type.tensor),c=Si(t,r.type.value,o),h=Rt("x",e[0].dataType,l.length,a),m=Rt("w",e[1].dataType,u.length,a),f=[h,m];i&&f.push(Rt("b",e[2].dataType,e[2].dims,a));let g=i?"value += b[output_channel];":"",_=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Ei(t,_),`\n ${n.registerUniforms(_).declareVariables(...f,r)}\n ${n.mainStart()}\n ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let width0 = uniforms.output_shape[3];\n let output_channel = global_idx % width0;\n var index1 = global_idx / width0;\n let width1 = uniforms.output_shape[2] / ${s}u;\n let col = (index1 % width1) * ${s}u;\n index1 = index1 / width1;\n let row = index1 % uniforms.output_shape[1];\n let batch = index1 / uniforms.output_shape[1];\n\n let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads;\n\n var x_vals: array<${h.type.value}, ${p}>;\n var values: array<${r.type.value}, ${s}>;\n let input_channel = output_channel;\n // Use constant instead of uniform can give better performance for w's height/width.\n for (var w_height: u32 = 0u; w_height < ${u[0]}; w_height++) {\n let x_height = x_corner.x + i32(w_height);\n if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {\n for (var i = 0; i < ${p}; i++) {\n let x_width = x_corner.y + i;\n if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {\n x_vals[i] = ${h.get("batch","u32(x_height)","u32(x_width)","input_channel")};\n } else {\n x_vals[i] = ${h.type.value}(0);\n }\n }\n for (var w_width: u32 = 0u; w_width < ${u[1]}; w_width++) {\n let w_val = ${m.get("w_height","w_width","0","output_channel")};\n for (var i = 0u; i < ${s}u; i++) {\n values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);\n }\n }\n }\n }\n\n for (var i = 0u; i < ${s}u; i++) {\n var value = values[i];\n ${g}\n ${c}\n ${r.set("batch","row","col + i","output_channel","value")};\n }\n }`}}}})),Cu=j((()=>{ou(),ku(),$u(),Tu(),Su(),yu(),Mu(),uu(),na=(e,t,n,r,i,a)=>{let s=e[0],o=e.slice(a?1:2,a?3:4),l=o.length,u=t[0],d=t.slice(2).map(((e,t)=>e+(e-1)*(n[t]-1))),c=o.map(((e,t)=>e+r[t]+r[t+l])).map(((e,t)=>Math.floor((e-d[t]+i[t])/i[t])));return c.splice(0,0,s),c.splice(a?3:1,0,u),c},ra=[2,3,1,0],ia=(e,t)=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");if(e[0].dims["NHWC"===t.format?e[0].dims.length-1:1]!==e[1].dims[1]*t.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(3===e.length&&(1!==e[2].dims.length||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let n=e[0].dims.length-2;if(t.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(t.strides.length!==n)throw new Error(`strides should be ${n}D`);if(t.pads.length!==2*n)throw new Error(`pads should be ${2*n}D`);if(0!==t.kernelShape.length&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},aa=(e,t)=>{let n=e.kernelShape.slice();n.length{let t=Pi(e),n=e.format;return{autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],format:n,dilations:e.dilations,group:e.group,kernelShape:e.kernel_shape,pads:e.pads,strides:e.strides,wIsConst:e.w_is_const(),...t,cacheKey:`${e.format};${t.activation};`}},oa=(e,t,n,r)=>{let i="NHWC"===n.format,a=na(t[0].dims,t[1].dims,n.dilations,n.pads,n.strides,i);if(1!==n.group){let s=[t[0]];if(i){let r=e.kernelCustomData.wT??e.compute(Zt(t[1],ra),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=r),s.push(r)}else s.push(t[1]);return 3===t.length&&s.push(t[2]),void(!e.adapterInfo.isArchitecture("ampere")&&i&&t[1].dims[0]===n.group&&1===t[1].dims[1]&&1===n.dilations[0]&&1===n.dilations[1]?e.compute(ta(s,n,a,r),{inputs:s}):e.compute(ea(s,n,a,r),{inputs:s}))}let s=3===t.length,o=t[0].dims[i?1:2],l=t[0].dims[i?2:3],u=t[0].dims[i?3:1],d=t[1].dims[2],c=t[1].dims[3],p=a[i?1:2],h=a[i?2:3],m=a[i?3:1],f=i&&d===o&&c===l&&0===n.pads[0]&&0===n.pads[1];if(f||1===d&&1===c&&1===n.dilations[0]&&1===n.dilations[1]&&1===n.strides[0]&&1===n.strides[1]&&0===n.pads[0]&&0===n.pads[1]){let d,c,g,_=a[0],w=[];if(i){let r=e.kernelCustomData.wT??e.compute(Zt(t[1],ra),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];if(n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=r),f){let e=o*l*u;d=t[0].reshape([1,_,e]),c=r.reshape([1,e,m]),g=[1,_,m]}else d=t[0].reshape([_,o*l,u]),c=r.reshape([1,u,m]),g=[_,p*h,m];w.push(d),w.push(c)}else d=t[0].reshape([_,u,o*l]),c=t[1].reshape([1,m,u]),g=[_,m,p*h],w.push(c),w.push(d);s&&w.push(t[2]);let b=g[2],y=w[0].dims[w[0].dims.length-1];return void(b<8&&y<8?e.compute(Oi(w,n,a,g,i,r),{inputs:w}):e.compute(qi(w,n,a,g,i,r),{inputs:w}))}let g=e.kernelCustomData.wT??e.compute(Zt(t[1],ra),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=g);let _=[t[0],g];s&&_.push(t[2]);let w=i?p*h:m,b=i?m:p*h,y=d*c*u;e.compute(Ui(_,n,a,w,b,y,s,!0,r),{inputs:_})},la=(e,t)=>{let n="NHWC"===t.format,r=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];3===e.inputs.length&&r.push(e.inputs[2]);let i=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),s=[1].concat(t.dilations),o=[1].concat(t.kernelShape),l=aa({...t,pads:i,strides:a,dilations:s,kernelShape:o},r);oa(e,r,l,(e=>n?[e[0],e[2],e[3]]:[e[0],e[1],e[3]]))},ua=(e,t,n)=>{let r="NHWC"===n.format?"channelsLast":"channelsFirst",i=aa(n,t),a="NOTSET"===n.autoPad?n.pads:n.autoPad,s=Zi(t[0].dims,t[1].dims,n.strides,n.dilations,a,!1,r);e.compute(Ji(t,i,s.outShape,[s.filterDepth,s.filterHeight,s.filterWidth],[s.padInfo.front,s.padInfo.top,s.padInfo.left],r))},da=(e,t)=>{if(ia(e.inputs,t),3===e.inputs[0].dims.length)la(e,t);else if(5===e.inputs[0].dims.length)ua(e,e.inputs,t);else{let n=aa(t,e.inputs);oa(e,e.inputs,n)}}})),Eu=j((()=>{eu(),nu(),ou(),lu(),ca=(e,t,n)=>{let r=e.length>2,i=t.outputShape,a="NHWC"===t.format,s=t.group,o=e[1].dims,l=o[2]/s,u=o[3],d=a?zt(u):1,c=Tt.size(i)/d,p=[Math.ceil(c/64),1,1];ut("verbose",(()=>`[conv2d_backprop_webgpu] dispatch = ${p}`));let h=["rank","rank"],m=[t.strides[0],t.strides[1]],f=[t.kernelShape[a?1:2],t.kernelShape[a?2:3]],g=[t.dilations[0],t.dilations[1]],_=[f[0]+(t.dilations[0]<=1?0:(t.kernelShape[a?1:2]-1)*(t.dilations[0]-1)),f[1]+(t.dilations[1]<=1?0:(t.kernelShape[a?2:3]-1)*(t.dilations[1]-1))],w=[_[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),_[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],b=[{type:12,data:c},{type:12,data:m},{type:12,data:f},{type:12,data:g},{type:12,data:_},{type:6,data:w},{type:12,data:l},{type:12,data:u},...It(e[0].dims,e[1].dims)];r&&(b.push(...It(e[2].dims)),h.push("rank")),b.push(...It(i));return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${d}`,inputDependencies:h},getRunData:()=>({dispatchGroup:{x:p[0],y:p[1],z:p[2]},outputs:[{dims:n?n(i):i,dataType:e[0].dataType}],programUniforms:b}),getShaderSource:t=>{let n=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:m.length},{name:"filter_dims",type:"u32",length:f.length},{name:"dilations",type:"u32",length:f.length},{name:"effective_filter_dims",type:"u32",length:_.length},{name:"pads",type:"i32",length:w.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],s=Ft(e[0].dataType),o=a?1:2,l=a?2:3,u=a?3:1,c=Rt("W",e[1].dataType,e[1].dims.length,d),p=Rt("Dy",e[0].dataType,e[0].dims.length),h=[p,c];r&&h.push(Rt("bias",e[2].dataType,[i[u]].length,d));let g=Vt("result",e[0].dataType,i.length,d),b=`\n let outputIndices = ${g.offsetToIndices(`global_idx * ${d}`)};\n let batch = ${g.indicesGet("outputIndices",0)};\n let d1 = ${g.indicesGet("outputIndices",u)};\n let r = ${g.indicesGet("outputIndices",o)};\n let c = ${g.indicesGet("outputIndices",l)};\n let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads;\n let dyRCorner = dyCorner.x;\n let dyCCorner = dyCorner.y;\n let groupId = d1 / uniforms.output_channels_per_group;\n let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;\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 var dotProd = ${g.type.value}(0.0);\n for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {\n if (wR % uniforms.dilations.x != 0) {\n continue;\n }\n let dyR = (${s}(dyRCorner) + ${s}(wR)) / ${s}(uniforms.strides[0]);\n let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;\n if (dyR < 0.0 || dyR >= ${s}(uniforms.Dy_shape[${o}]) || fract(dyR) > 0.0 ||\n wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {\n if (wC % uniforms.dilations.y != 0) {\n continue;\n }\n let dyC = (${s}(dyCCorner) + ${s}(wC)) / ${s}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;\n if (dyC < 0.0 || dyC >= ${s}(uniforms.Dy_shape[${l}]) ||\n fract(dyC) > 0.0 || wCPerm < 0) {\n continue;\n }\n let idyC: u32 = u32(dyC);\n var inputChannel = groupId * uniforms.input_channels_per_group;\n for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) {\n let xValue = ${a?p.get("batch","idyR","idyC","inputChannel"):p.get("batch","inputChannel","idyR","idyC")};\n let w_offset = ${c.indicesToOffset(`${c.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)};\n let wValue = ${c.getByOffset(`w_offset / ${d}`)};\n dotProd = dotProd + xValue * wValue;\n inputChannel = inputChannel + 1;\n }\n }\n }\n let value = dotProd${r?` + bias[d1 / ${d}]`:""};\n ${g.setByOffset("global_idx","value")};\n `;return`\n ${t.registerUniforms(n).declareVariables(...h,g)}\n ${t.mainStart()}\n ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};\n ${b}}`}}}})),Pu=j((()=>{Eu(),yu(),uu(),pa=(e,t,n,r,i,a)=>(e-1)*t+n+(r-1)*i+1-a,ha=(e,t,n,r,i)=>{let a=Math.floor(e/2);"SAME_UPPER"===t?(n[r]=a,n[i]=e-a):"SAME_LOWER"===t&&(n[r]=e-a,n[i]=a)},ma=(e,t,n,r,i,a,s,o,l,u)=>{let d=e.length-2,c=0===u.length;l.length{let n=e.kernelShape.slice();if(0===e.kernelShape.length||0===e.kernelShape.reduce(((e,t)=>e*t),1)){n.length=0;for(let e=2;ee+t),0)){let e=t[0].dims.length-2;l=new Array(e).fill(1)}let u=e.strides.slice();if(0===u.reduce(((e,t)=>e+t),0)){let e=t[0].dims.length-2;u=new Array(e).fill(1)}ma(o,n,l,e.autoPad,e.group,i,u,r,s,a);let d=Object.assign({},e);return Object.assign(d,{kernelShape:n,pads:i,outputPadding:s,outputShape:a,dilations:l,strides:u}),d},ga=e=>{let t=Pi(e),n=e.format,r=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,a=e.group,s=e.kernelShape,o=e.pads,l=e.strides,u=e.wIsConst();return{autoPad:r,format:n,dilations:i,group:a,kernelShape:s,outputPadding:e.outputPadding,outputShape:e.outputShape,pads:o,strides:l,wIsConst:u,...t,cacheKey:`${e.format};${t.activation};`}},_a=(e,t)=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==e[0].dims.length&&3!==e[0].dims.length)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");if(e[0].dims["NHWC"===t.format?e[0].dims.length-1:1]!==e[1].dims[0])throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let n=e[1].dims[1]*t.group;if(3===e.length&&(1!==e[2].dims.length||e[2].dims[0]!==n))throw new Error("invalid bias");let r=e[0].dims.length-2;if(t.dilations.reduce(((e,t)=>e+t),0)>0&&t.dilations.length!==r)throw new Error(`dilations should be ${r}D`);if(t.strides.reduce(((e,t)=>e+t),0)>0&&t.strides.length!==r)throw new Error(`strides should be ${r}D`);if(t.pads.reduce(((e,t)=>e+t),0)>0&&t.pads.length!==2*r)throw new Error(`pads should be ${2*r}D`);if(t.outputPadding.length!==r&&0!==t.outputPadding.length)throw new Error(`output_padding should be ${r}D`);if(t.kernelShape.reduce(((e,t)=>e+t),0)>0&&0!==t.kernelShape.length&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(0!==t.outputShape.length&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},wa=(e,t,n,r)=>{let i=e.kernelCustomData.wT??e.compute(Zt(t[1],[2,3,0,1]),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=i);let a=[t[0],i];3===t.length&&a.push(t[2]),e.compute(ca(a,n,r),{inputs:a})},ba=(e,t)=>{let n="NHWC"===t.format,r=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];3===e.inputs.length&&r.push(e.inputs[2]);let i=t.kernelShape;(0===i.length||0===i[0])&&(i=[e.inputs[1].dims[2]]);let a=t.dilations;(0===a.length||0===a[0])&&(a=[1]);let s=t.strides;(0===s.length||0===s[0])&&(s=[1]);let o=t.pads;0===o.length&&(o=[0,0]),o=[0,o[0],0,o[1]],s=[1].concat(s),a=[1].concat(a),i=[1].concat(i);let l=fa({...t,pads:o,strides:s,dilations:a,kernelShape:i},r);wa(e,r,l,(e=>n?[e[0],e[2],e[3]]:[e[0],e[1],e[3]]))},ya=(e,t)=>{if(_a(e.inputs,t),3===e.inputs[0].dims.length)ba(e,t);else{let n=fa(t,e.inputs);wa(e,e.inputs,n)}}})),Fu=j((()=>{eu(),ou(),su(),lu(),xa=(e,t,n,r)=>{let i=Tt.size(t),a=t.length,s=Rt("input",e,a),o=Vt("output",e,a),l=6===n.dataType?n.getInt32Array()[0]:Number(n.getBigInt64Array()[0]),u=Tt.normalizeAxis(l,a);return{name:"CumSum",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:u},...It(t,t)]}),getShaderSource:e=>{let t=` i32(${s.indicesGet("inputIndices","uniforms.axis")}) `,n=Nt("uniforms.input_shape","uniforms.axis",a),i=r.reverse?t+(r.exclusive?" + 1":""):"0",l=r.reverse?n:t+(r.exclusive?"":" + 1");return`\n ${e.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(s,o)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var inputIndices = ${o.offsetToIndices("global_idx")};\n var sum = ${o.type.value}(0);\n let first : i32 = ${i};\n let last : i32 = ${l};\n for (var i : i32 = first; i < last; i++) {\n ${s.indicesSet("inputIndices","uniforms.axis","u32(i)")};\n sum = sum + ${s.getByIndices("inputIndices")};\n }\n ${o.setByOffset("global_idx","sum")};\n }`}}},va=(e,t)=>{let n=e.inputs[0].dims,r=e.inputs[0].dataType,i=e.inputs[1];e.compute(xa(r,n,i,t),{inputs:[0]})},Ma=e=>{let t=1===e.exclusive,n=1===e.reverse;return xt({exclusive:t,reverse:n})}})),Au=j((()=>{eu(),ou(),su(),lu(),Ta=e=>{if(!e||1!==e.length)throw new Error("DepthToSpace requires 1 input.");if(4!==e[0].dims.length)throw new Error("DepthToSpace requires 4D input.")},ka=(e,t,n,r)=>{let i=[];i.push(`fn perm(i: ${r.type.indices}) -> ${n.type.indices} {\n var a: ${n.type.indices};`);for(let r=0;r{let n,r,i,a,s,o,l="NHWC"===t.format,u=t.blocksize,d="DCR"===t.mode;l?([n,r,i,a]=e.dims,s=d?[n,r,i,u,u,a/u**2]:[n,r,i,a/u**2,u,u],o=d?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([n,r,i,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],s=d?[n,u,u,a/u**2,r,i]:[n,a/u**2,u,u,r,i],o=d?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let c=e.reshape(s),p=c.dims.length,h=e.dataType,m=Rt("a",h,p),f=Vt("output",h,p);return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:e=>{let t=l?[n,r*u,i*u,a/u**2]:[n,a/u**2,r*u,i*u],s=Tt.size(t),d=c.dims,p=Tt.sortBasedOnPerm(d,o);return{outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:[{type:12,data:s},...It(d,p)]}},getShaderSource:e=>`\n ${e.registerUniform("output_size","u32").declareVariables(m,f)}\n\n ${ka(o,p,m,f)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${f.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${f.setByOffset("global_idx",m.getByIndices("aIndices"))}\n }`}},Sa=(e,t)=>{Ta(e.inputs),e.compute($a(e.inputs[0],t))},Ca=e=>xt({blocksize:e.blocksize,mode:e.mode,format:e.format})})),Iu=j((()=>{eu(),ou(),su(),lu(),Fa="^"+(Pa="("+(Ea="[a-zA-Z]|\\.\\.\\.")+")+")+"$",Aa="^"+("("+Pa+",)*"+Pa)+"$",Ia=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let n=this.symbolToIndices.get(e);void 0===n?n=[t]:n.push(t),this.symbolToIndices.set(e,n)}},za=class{constructor(e,t){this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[n,r]=t.includes("->")?t.split("->",2):[t,""];if(!n.match(RegExp(Aa)))throw new Error("Invalid LHS term");if(n.split(",").forEach(((t,n)=>{let r=e[n].dims.slice();if(!t.match(RegExp(Fa)))throw new Error("Invalid LHS term");let i=this.processTerm(t,!0,r,n);this.lhs.push(i)})),""===r)r+=[...this.symbolToInfo.entries()].filter((([e,t])=>1===t.count||"..."===e)).map((([e])=>e)).join("");else if(!r.match(RegExp(Pa)))throw new Error("Invalid RHS");r.match(RegExp(Ea,"g"))?.forEach((e=>{if("..."===e)this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let t=this.symbolToInfo.get(e);if(void 0===t)throw new Error("Invalid RHS symbol");this.outputDims.push(t.dimValue)}})),this.rhs=this.processTerm(r,!1,this.outputDims)}addSymbol(e,t,n){let r=this.symbolToInfo.get(e);if(void 0!==r){if(r.dimValue!==t&&1!==r.count)throw new Error("Dimension mismatch");r.count++,r.inputIndices.push(n)}else r={count:1,dimValue:t,inputIndices:[n]};this.symbolToInfo.set(e,r)}processTerm(e,t,n,r=-1){let i=n.length,a=!1,s=[],o=0;if(!e.match(RegExp(Fa))&&!t&&""!==e)throw new Error("Invalid LHS term");let l=e.match(RegExp(Ea,"g")),u=new Ia(r);return l?.forEach(((e,d)=>{if("..."===e){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let e=i-l.length+1;if(e<0)throw new Error("Ellipsis out of bounds");if(s=n.slice(o,o+e),this.hasEllipsis){if(this.ellipsisDims.length!==s.length||this.ellipsisDims.toString()!==s.toString())throw new Error("Ellipsis dimensions mismatch")}else{if(!t)throw new Error("Ellipsis must be specified in the LHS");this.hasEllipsis=!0,this.ellipsisDims=s}for(let e=0;ee+"_max",Ba=(e,t,n,r)=>{let i=e.map((e=>e.length)).map(((e,n)=>Rt(`input${n}`,t,e))),a=Tt.size(r),s=Vt("output",t,r.length),o=[...n.symbolToInfo.keys()].filter((e=>!n.rhs.symbolToIndices.has(e)));return{name:"Einsum",shaderCache:{hint:n.equation,inputDependencies:e.map((()=>"rank"))},getRunData:()=>{let i=o.filter((e=>n.symbolToInfo.has(e))).map((e=>({type:12,data:n.symbolToInfo.get(e)?.dimValue||0})));i.push({type:12,data:a});let s=e.map(((e,t)=>[...It(e)])).reduce(((e,t)=>e.concat(t)),i);return s.push(...It(r)),{outputs:[{dims:r,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:s}},getShaderSource:e=>{let t=[],r=[],a=[],l=[],u=[],d=n.symbolToInfo.size===n.rhs.symbolToIndices.size;n.symbolToInfo.forEach(((e,o)=>{if(n.rhs.symbolToIndices.has(o)){let r=n.rhs.symbolToIndices.get(o)?.[0];void 0!==r&&n.lhs.forEach(((n,a)=>{if(e.inputIndices.includes(a)){let e=n.symbolToIndices.get(o);if(void 0===e)throw new Error("Invalid symbol error");e.forEach((e=>{t.push(`${i[a].indicesSet(`input${a}Indices`,e,s.indicesGet("outputIndices",r))}`)}))}}))}else n.lhs.forEach(((t,n)=>{if(e.inputIndices.includes(n)){let e=t.symbolToIndices.get(o);if(void 0===e)throw new Error("Invalid symbol error");e.forEach((e=>{r.push(`${i[n].indicesSet(`input${n}Indices`,e,`${o}`)}`)})),u.push(`prod *= ${i[n].getByIndices(`input${n}Indices`)};`)}})),a.push(`for(var ${o}: u32 = 0; ${o} < uniforms.${Oa(o)}; ${o}++) {`),l.push("}")}));let c=d?[...t,`let sum = ${i.map(((e,t)=>e.getByIndices(`input${t}Indices`))).join(" * ")};`]:[...t,"var sum = 0.0;",...a,...r,"var prod = 1.0;",...u,"sum += prod;",...l];return`\n ${e.registerUniforms(o.map((e=>({name:`${Oa(e)}`,type:"u32"})))).registerUniform("outputSize","u32").declareVariables(...i,s)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${s.offsetToIndices("global_idx")};\n ${i.map(((e,t)=>`var input${t}Indices: ${i[t].type.indices};`)).join("\n")}\n ${c.join("\n")};\n ${s.setByOffset("global_idx","sum")};\n }`}}},La=(e,t)=>{let n=new za(e.inputs,t.equation),r=n.outputDims,i=e.inputs.map(((e,t)=>e.dims));e.compute(Ba(i,e.inputs[0].dataType,n,r))},Na=e=>{let t=e.equation.replace(/\s+/g,"");return xt({equation:t})}})),zu=j((()=>{eu(),ou(),lu(),Da=e=>{if(!e||2!==e.length)throw new Error("Expand requires 2 input.");let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),r=n.length{let n=e.length-t.length,r=[];for(let t=0;te.length>t.length?Ra(e,t):Ra(t,e),ja=e=>{let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),r=Va(t,n),i=e[0].dataType,a=9===i||1===Tt.size(t),s=9===i||t.length>0&&t[t.length-1]%4==0?4:1,o=a||r.length>0&&r[r.length-1]%4==0?4:1,l=Math.ceil(Tt.size(r)/o),u=[{type:12,data:l},...It(t,r)];return{name:"Expand",shaderCache:{hint:`${r.length};${s}${o}`,inputDependencies:["rank"]},getShaderSource:e=>{let n,a=Rt("input",i,t.length,s),l=Vt("output",i,r.length,o);if(9===i){let e=(e,t,n="")=>`\n let outputIndices${t} = ${l.offsetToIndices(`outputOffset + ${t}u`)};\n let offset${t} = ${a.broadcastedIndicesToOffset(`outputIndices${t}`,l)};\n let index${t} = offset${t} / 4u;\n let component${t} = offset${t} % 4u;\n ${e}[${t}] = ${n}(${a.getByOffset(`index${t}`)}[component${t}]);\n `;n=`\n let outputOffset = global_idx * ${o};\n var data = vec4(0);\n ${e("data",0,"u32")}\n ${e("data",1,"u32")}\n ${e("data",2,"u32")}\n ${e("data",3,"u32")}\n ${l.setByOffset("global_idx","data")}\n }`}else n=`\n let outputIndices = ${l.offsetToIndices(`global_idx * ${o}`)};\n let inputOffset = ${a.broadcastedIndicesToOffset("outputIndices",l)};\n let data = ${l.type.value}(${a.getByOffset(`inputOffset / ${s}`)});\n ${l.setByOffset("global_idx","data")}\n }`;return`\n ${e.registerUniform("vec_size","u32").declareVariables(a,l)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${n}`},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u})}},qa=e=>{Da(e.inputs),e.compute(ja(e.inputs),{inputs:[0]})}})),Ou=j((()=>{eu(),ou(),lu(),gu(),Ga=e=>{let t=e[0].dataType,n=Tt.size(e[0].dims),r=Tt.size(e[1].dims),i=r%4==0;return{name:"FastGeluWithBias",shaderCache:{hint:`${i}`,inputDependencies:["type","type"]},getShaderSource:e=>{let n=Rt("x",t,[1],4),r=Rt("bias",t,[1],4),a=Vt("y",t,[1],4),s=e=>`\n let bias${e}_offset: u32 = (global_idx * 4 + ${e}) % uniforms.bias_size;\n let bias${e} = ${r.getByOffset(`bias${e}_offset / 4`)}[bias${e}_offset % 4];`,o=i?`\n let bias = ${r.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${s(0)}${s(1)}${s(2)}${s(3)}\n let bias = ${n.type.value}(bias0, bias1, bias2, bias3);`;return`${e.registerUniforms([{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}]).declareVariables(n,r,a)}\n\n ${Yr(At(t))}\n\n ${e.mainStart(Et)}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}\n\n let x = ${n.getByOffset("global_idx")};\n ${o}\n let x_in = x + bias;\n ${a.setByOffset("global_idx",Zr("x_in"))}\n }`},getRunData:e=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],programUniforms:[{type:12,data:Math.ceil(n/4)},{type:12,data:r}],dispatchGroup:{x:Math.ceil(n/Et/4)}})}},Ua=e=>{e.inputs.length<2||0===Tt.size(e.inputs[1].dims)?Jr(e):e.compute(Ga(e.inputs))}})),Bu=j((()=>{eu(),ou(),su(),lu(),Wa=e=>{if(!e||2!==e.length)throw new Error("Gather requires 2 inputs.")},Ha=(e,t)=>{let n=e[0].dims,r=e[1].dims,i=n.length,a=Tt.normalizeAxis(t.axis,i),s=n.slice(0);s.splice(a,1,...r);let o=n[a],l=9===e[0].dataType?4:1,u=Math.ceil(Tt.size(s)/l),d=[{type:12,data:u},{type:6,data:o},{type:12,data:a},...It(e[0].dims,e[1].dims,s)];return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:d}),getShaderSource:t=>{let n,o=Rt("data",e[0].dataType,e[0].dims.length,l),u=Rt("inputIndices",e[1].dataType,e[1].dims.length),d=Vt("output",e[0].dataType,s.length,l),c=e=>{let t=r.length,n=`var indicesIndices${e} = ${u.type.indices}(0);`;for(let r=0;r1?`indicesIndices${e}[${r}]`:`indicesIndices${e}`} = ${s.length>1?`outputIndices${e}[uniforms.axis + ${r}]`:`outputIndices${e}`};`;n+=`\n var idx${e} = ${u.getByIndices(`indicesIndices${e}`)};\n if (idx${e} < 0) {\n idx${e} = idx${e} + uniforms.axisDimLimit;\n }\n var dataIndices${e} : ${o.type.indices};\n `;for(let r=0,o=0;r1?`dataIndices${e}[${r}]`:`dataIndices${e}`} = u32(idx${e});`,o+=t):(n+=`${i>1?`dataIndices${e}[${r}]`:`dataIndices${e}`} = ${s.length>1?`outputIndices${e}[${o}]`:`outputIndices${e}`};`,o++);return n};if(9===e[0].dataType){let e=(e,t,n="")=>`\n let outputIndices${t} = ${d.offsetToIndices(`outputOffset + ${t}u`)};\n ${c(t)};\n let offset${t} = ${o.indicesToOffset(`dataIndices${t}`)};\n let index${t} = offset${t} / 4u;\n let component${t} = offset${t} % 4u;\n ${e}[${t}] = ${n}(${o.getByOffset(`index${t}`)}[component${t}]);\n `;n=`\n let outputOffset = global_idx * ${l};\n var value = vec4(0);\n ${e("value",0,"u32")}\n ${e("value",1,"u32")}\n ${e("value",2,"u32")}\n ${e("value",3,"u32")}\n ${d.setByOffset("global_idx","value")}\n `}else n=`\n let outputIndices = ${d.offsetToIndices("global_idx")};\n ${c("")};\n let value = ${o.getByIndices("dataIndices")};\n ${d.setByOffset("global_idx","value")};\n `;return`\n ${t.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(o,u,d)}\n ${t.mainStart()}\n ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n ${n}\n }`}}},Ka=e=>xt({axis:e.axis}),Xa=(e,t)=>{let n=e.inputs;Wa(n),e.compute(Ha(e.inputs,t))}})),Lu=j((()=>{eu(),ou(),su(),lu(),Qa=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let n=Tt.normalizeAxis(t.quantizeAxis,e[0].dims.length),r=t.blockSize,i=e[0],a=e[2],s=4===e.length?e[3]:void 0;if(a.dims.length!==i.dims.length||!i.dims.map(((e,t)=>t===n?Math.ceil(e/r)===a.dims[t]:e===a.dims[t])).reduce(((e,t)=>e&&t),!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(s){if(s.dataType!==i.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(s.dims.length!==a.dims.length||!s.dims.map(((e,t)=>e===a.dims[t])).reduce(((e,t)=>e&&t),!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Ya=(e,t)=>{let n=e[0].dims,r=e[1].dims,i=n.length,a=Tt.normalizeAxis(t.gatherAxis,i),s=Tt.normalizeAxis(t.quantizeAxis,i),o=n.slice(0);o.splice(a,1,...r);let l=Tt.size(o),u=e[2].dataType,d=22===e[0].dataType,c=[{type:12,data:l},{type:12,data:s},{type:12,data:a},{type:12,data:t.blockSize},...It(...e.map(((e,t)=>e.dims)),o)];return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter(((e,t)=>1!==t)).map((e=>e.dims.join("_"))).join(";")}`,inputDependencies:Array.from({length:e.length},((e,t)=>"rank"))},getRunData:()=>({outputs:[{dims:o,dataType:u}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c}),getShaderSource:t=>{let i=Rt("data",e[0].dataType,e[0].dims.length),s=Rt("inputIndices",e[1].dataType,e[1].dims.length),l=Rt("scales",e[2].dataType,e[2].dims.length),c=e.length>3?Rt("zeroPoint",e[3].dataType,e[3].dims.length):void 0,p=Vt("output",u,o.length),h=[i,s,l];c&&h.push(c);return`\n ${t.registerUniforms([{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}]).declareVariables(...h,p)}\n ${t.mainStart()}\n let output_indices = ${p.offsetToIndices("global_idx")};\n var indices_indices = ${s.type.indices}(0);\n ${r.length>1?`\n for (var i: u32 = 0; i < ${r.length}; i++) {\n let index = ${p.indicesGet("output_indices","uniforms.gather_axis + i")};\n ${s.indicesSet("indices_indices","i","index")};\n }`:`indices_indices = ${p.indicesGet("output_indices","uniforms.gather_axis")};`};\n var data_indices = ${i.type.indices}(0);\n for (var i: u32 = 0; i < uniforms.gather_axis; i++) {\n let index = ${p.indicesGet("output_indices","i")};\n ${i.indicesSet("data_indices","i","index")};\n }\n var index_from_indices = ${s.getByIndices("indices_indices")};\n if (index_from_indices < 0) {\n index_from_indices += ${n[a]};\n }\n ${i.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")};\n for (var i = uniforms.gather_axis + 1; i < ${o.length}; i++) {\n let index = ${p.indicesGet("output_indices",`i + ${r.length} - 1`)};\n ${i.indicesSet("data_indices","i","index")};\n }\n let data_offset = ${i.indicesToOffset("data_indices")};\n let data_index = data_offset % 8;\n // Convert 4-bit packed data to 8-bit packed data.\n let packed_4bit_quantized_data = ${i.getByOffset("data_offset / 8")};\n let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f;\n let quantized_data_vec = ${d?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data));\n let quantized_data = quantized_data_vec[data_index / 2];\n var scale_indices = data_indices;\n let quantize_axis_index = ${l.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size;\n ${l.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")};\n var scale = ${l.getByIndices("scale_indices")};\n ${c?`\n let zero_point_indices = scale_indices;\n let zero_point_offset = ${c.indicesToOffset("zero_point_indices")};\n let zero_point_index = zero_point_offset % 8;\n let packed_4bit_zero_points = ${c.getByOffset("zero_point_offset / 8")};\n let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f;\n let zero_point_vec = ${d?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points));\n let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"};\n let dequantized_data = ${At(u)}(quantized_data - zero_point) * scale;\n ${p.setByOffset("global_idx","dequantized_data")};\n }`}}},Za=(e,t)=>{let n=e.inputs;Qa(n,t),e.compute(Ya(e.inputs,t))},Ja=e=>xt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})})),Nu=j((()=>{eu(),ou(),su(),lu(),es=e=>{if(!e||2!==e.length)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error("GatherElements requires that the data input and\n indices input tensors be of same rank.")},ts=(e,t)=>{let n=e[0].dims,r=e[0].dataType,i=n.length,a=e[1].dims,s=e[1].dataType,o=Tt.normalizeAxis(t.axis,i),l=n[o],u=a.slice(0),d=Tt.size(u),c=Rt("input",r,i),p=Rt("indicesInput",s,a.length),h=Vt("output",r,u.length),m=[{type:12,data:d},{type:6,data:l},{type:12,data:o}];return m.push(...It(n,a,u)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:m}),getShaderSource:e=>`\n ${e.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(c,p,h)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let outputIndices = ${h.offsetToIndices("global_idx")};\n\n var idx = ${p.getByOffset("global_idx")};\n if (idx < 0) {\n idx = idx + uniforms.axisDimLimit;\n }\n var inputIndices = ${c.type.indices}(outputIndices);\n ${c.indicesSet("inputIndices","uniforms.axis","u32(idx)")};\n let value = ${c.getByIndices("inputIndices")};\n\n ${h.setByOffset("global_idx","value")};\n }`}},ns=e=>xt({axis:e.axis}),rs=(e,t)=>{let n=e.inputs;es(n),e.compute(ts(e.inputs,t))}})),Du=j((()=>{eu(),ou(),lu(),is=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(3===e.length&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||3===e.length&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},as=(e,t)=>{let n=e[0].dims.slice(),r=e[1].dims.slice(),[i,a,s]=$t.getShapeOfGemmResult(n,t.transA,r,t.transB,3===e.length?e[2].dims:void 0),o=[i,a];if(!o)throw new Error("Can't use gemm on the given tensors");let l=16,u=Math.ceil(a/l),d=Math.ceil(i/l),c=(Tt.size(o),[{type:12,data:u},{type:12,data:i},{type:12,data:a},{type:12,data:s},{type:1,data:t.alpha},{type:1,data:t.beta}]),p=["type","type"];3===e.length&&(c.push(...It(e[2].dims)),p.push("rank")),c.push(...It(o));return{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:u*d},programUniforms:c}),getShaderSource:n=>{let r=Rt("a",e[0].dataType,e[0].dims),i=Rt("b",e[1].dataType,e[1].dims),a=null,s=[r,i];3===e.length&&(a=Rt("c",e[2].dataType,e[2].dims.length),s.push(a));let u=Vt("output",e[0].dataType,o.length);s.push(u);let d="",c="";t.transA&&t.transB?(c=`\n var col = tile_row_start + local_id.x;\n var row = k_start + local_id.y;\n if (col < uniforms.M && row < uniforms.K) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${r.type.value}(0);\n }\n\n col = k_start + local_id.x;\n row = tile_col_start + local_id.y;\n if (col < uniforms.K && row < uniforms.N) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${i.type.value}(0);\n }\n `,d="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(c=`\n var col = tile_row_start + local_id.x;\n var row = k_start + local_id.y;\n if (col < uniforms.M && row < uniforms.K) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${r.type.value}(0);\n }\n\n col = tile_col_start + local_id.x;\n row = k_start + local_id.y;\n if (col < uniforms.N && row < uniforms.K) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${i.type.value}(0);\n }\n `,d="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(c=`\n var col = k_start + local_id.x;\n var row = tile_row_start + local_id.y;\n if (col < uniforms.K && row < uniforms.M) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${r.type.value}(0);\n }\n\n col = k_start + local_id.x;\n row = tile_col_start + local_id.y;\n if (col < uniforms.K && row < uniforms.N) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${i.type.value}(0);\n }\n `,d="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(c=`\n var col = k_start + local_id.x;\n var row = tile_row_start + local_id.y;\n if (col < uniforms.K && row < uniforms.M) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${r.type.value}(0);\n }\n\n col = tile_col_start + local_id.x;\n row = k_start + local_id.y;\n if (col < uniforms.N && row < uniforms.K) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${i.type.value}(0);\n }\n `,d="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let p=1===t.alpha?"":"value *= uniforms.alpha;";return`\n ${n.registerUniforms([{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}]).declareVariables(...s)}\n var tile_a: array, 16>;\n var tile_b: array, 16>;\n ${n.mainStart([l,l,1])}\n let tile_col_start = (workgroup_index % uniforms.num_tile_n) * 16;\n let tile_row_start = (workgroup_index / uniforms.num_tile_n) * 16;\n let num_tiles = (uniforms.K - 1) / 16 + 1;\n var k_start = 0u;\n var value = ${u.type.value}(0);\n for (var t: u32 = 0u; t < num_tiles; t++) {\n ${c}\n k_start = k_start + 16;\n workgroupBarrier();\n\n for (var k: u32 = 0u; k < 16; k++) {\n ${d}\n }\n workgroupBarrier();\n }\n\n ${p}\n let m = tile_row_start + local_id.y;\n let n = tile_col_start + local_id.x;\n ${null!=a?`let cOffset = ${a.broadcastedIndicesToOffset("vec2(m, n)",u)}; value += ${u.type.value}(uniforms.beta) * ${a.getByOffset("cOffset")};`:""}\n if (m < uniforms.M && n < uniforms.N) {\n output[m * uniforms.N + n] = value;\n }\n }`}}},ss=e=>({transA:e.transA,transB:e.transB,alpha:e.alpha,beta:e.beta,cacheKey:`${e.transA};${e.transB};${1===e.alpha}`}),os=(e,t)=>{is(e.inputs),e.compute(as(e.inputs,t))}})),Ru=j((()=>{eu(),ou(),su(),lu(),[ls,us,ds,cs]=[0,1,2,3],ps=e=>{if(4!==e[0].dims.length)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error("last dimension of grid must be equal to "+(e[0].dims.length-2));if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},hs=e=>`\n fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} {\n var v: vec4;\n var coeffs = gs_get_cubic_coeffs(x);\n for (var i = 0; i < 4; i++) {\n v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3];\n }\n coeffs = gs_get_cubic_coeffs(y);\n let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]);\n return pixel;\n }\n`,ms=e=>`\n fn gs_denormalize(n: f32, length: i32) -> f32 {\n ${0===e.alignCorners?"\n // alignCorners: false => [-1, 1] to [-0.5, length - 0.5]\n return ((n + 1.0) * f32(length) - 1.0) / 2.0;\n ":"\n // alignCorners: true => [-1, 1] to [0, length - 1]\n return (n + 1.0) / 2.0 * (f32(length - 1));\n "}\n }\n`,fs=e=>`\n ${"reflection"===e.paddingMode?"\n fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 {\n var dx = 0.0;\n var fx = f32(x);\n let range = x_max - x_min;\n if (fx < x_min) {\n dx = x_min - fx;\n let n = u32(dx / range);\n let r = dx - f32(n) * range;\n if (n % 2 == 0) {\n fx = x_min + r;\n } else {\n fx = x_max - r;\n }\n } else if (fx > x_max) {\n dx = fx - x_max;\n let n = u32(dx / range);\n let r = dx - f32(n) * range;\n if (n % 2 == 0) {\n fx = x_max - r;\n } else {\n fx = x_min + r;\n }\n }\n return u32(fx);\n }":""}\n`,gs=(e,t,n)=>`\n fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} {\n var pixel = ${t}(0);\n var indices = vec4(0);\n indices[${ls}] = batch;\n indices[${us}] = channel;`+(()=>{switch(n.paddingMode){case"zeros":return`\n if (r >= 0 && r < H && c >=0 && c < W) {\n indices[${ds}] = u32(r);\n indices[${cs}] = u32(c);\n }\n `;case"border":return`\n indices[${ds}] = u32(clamp(r, 0, H - 1));\n indices[${cs}] = u32(clamp(c, 0, W - 1));\n `;case"reflection":return`\n indices[${ds}] = gs_reflect(r, border[1], border[3]);\n indices[${cs}] = gs_reflect(c, border[0], border[2]);\n `;default:throw new Error(`padding mode ${n.paddingMode} is not supported`)}})()+`\n return ${e.getByIndices("indices")};\n }\n`,_s=(e,t,n)=>(()=>{switch(n.mode){case"nearest":return`\n let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${ls}], indices[${us}], border);\n `;case"bilinear":return`\n let x1 = i32(floor(x));\n let y1 = i32(floor(y));\n let x2 = x1 + 1;\n let y2 = y1 + 1;\n\n let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${ls}], indices[${us}], border);\n let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${ls}], indices[${us}], border);\n let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${ls}], indices[${us}], border);\n let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${ls}], indices[${us}], border);\n\n let dx2 = ${t}(f32(x2) - x);\n let dx1 = ${t}(x - f32(x1));\n let dy2 = ${t}(f32(y2) - y);\n let dy1 = ${t}(y - f32(y1));\n let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22);\n `;case"bicubic":return`\n let x0 = i32(floor(x)) - 1;\n let y0 = i32(floor(y)) - 1;\n var p: mat4x4<${t}>;\n for (var h = 0; h < 4; h++) {\n for (var w = 0; w < 4; w++) {\n p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${ls}], indices[${us}], border);\n }\n }\n\n let dx = x - f32(x0 + 1);\n let dy = y - f32(y0 + 1);\n let result = gs_bicubic_interpolate(p, dx, dy);\n `;default:throw new Error(`mode ${n.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,ws=(e,t)=>{let n=Rt("x",e[0].dataType,e[0].dims.length),r=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],i=Rt("grid",e[1].dataType,r.length,2),a=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];"NHWC"===t.format&&(a=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[ls,us,ds,cs]=[0,3,1,2]);let s=Vt("output",e[0].dataType,a.length),o=n.type.value,l=[{type:12,data:Tt.size(a)},...It(e[0].dims,r,a)];return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:e=>{let t=Tt.size(a);return{outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(t/64)},programUniforms:l}},getShaderSource:e=>`\n ${e.registerUniform("output_size","u32").declareVariables(n,i,s)}\n \n fn gs_get_cubic_coeffs(x: f32) -> vec4 {\n let cubic_alpha = -0.75f;\n let x_abs = abs(x);\n var coeffs: vec4;\n coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha);\n coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1);\n coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1);\n coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha);\n return coeffs;\n }\n\n ${hs(o)}\n ${ms(t)}\n ${fs(t)}\n ${gs(n,o,t)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let H_in = i32(uniforms.x_shape[${ds}]);\n let W_in = i32(uniforms.x_shape[${cs}]);\n\n ${0===t.alignCorners?"\n let x_min = -0.5;\n let x_max = f32(W_in) - 0.5;\n let y_min = -0.5;\n let y_max = f32(H_in) - 0.5;\n ":"\n let x_min = 0.0;\n let x_max = f32(W_in) - 1.0;\n let y_min = 0.0;\n let y_max = f32(H_in) - 1.0;\n "};\n let border = vec4(x_min, y_min, x_max, y_max);\n\n let indices = ${s.offsetToIndices("global_idx")};\n var grid_indices = vec3(indices[${ls}], indices[${ds}], indices[${cs}]);\n let nxy = ${i.getByIndices("grid_indices")};\n var x = gs_denormalize(f32(nxy[0]), W_in);\n var y = gs_denormalize(f32(nxy[1]), H_in);\n\n ${_s(s,o,t)}\n }`}},bs=(e,t)=>{ps(e.inputs),e.compute(ws(e.inputs,t))},ys=e=>xt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})})),Vu=j((()=>{eu(),ou(),su(),iu(),hu(),lu(),uu(),xs=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,vs=(e,t)=>{let n=e[0],r=xs(e,1),i=xs(e,2),a=xs(e,3),s=xs(e,4),o=xs(e,5),l=xs(e,6),u=xs(e,7);if(3!==n.dims.length&&5!==n.dims.length)throw new Error("Input query is expected to have 3 or 5 dimensions");let d,c=n.dims[0],p=n.dims[1],h=3===n.dims.length?n.dims[2]:t.numHeads*n.dims[4],m=p,f=0,g=0,_=Math.floor(h/t.numHeads);if(l&&u&&Tt.size(l.dims)&&Tt.size(u.dims)){if(4!==l.dims.length)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims[0]!==c||l.dims[1]!==t.numHeads||l.dims[3]!==_)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(u.dims[0]!==c||u.dims[1]!==t.numHeads||u.dims[3]!==_)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==u.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(4!==u.dims.length)throw new Error('Input "past_value" is expected to have 4 dimensions');f=l.dims[2],g=l.dims[2]}else if(l&&Tt.size(l.dims)||u&&Tt.size(u.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');if(r&&Tt.size(r.dims)>0){if(3!==n.dims.length)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(r.dims.length<3||r.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(n.dims[0]!==r.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(3===r.dims.length){if(r.dims[2]!==n.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');d=2,m=r.dims[1]}else if(5===r.dims.length){if(r.dims[2]!==t.numHeads||2!==r.dims[3]||r.dims[4]!==_)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');d=5,m=r.dims[1]}else{if(r.dims[1]!==t.numHeads||r.dims[3]!==_)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');d=0,m=r.dims[2]}}else{if(5!==n.dims.length)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(n.dims[2]!==t.numHeads||3!==n.dims[3])throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');d=3}if(a&&Tt.size(a.dims)>0){if(1!==a.dims.length)throw new Error('Input "bias" is expected to have 1 dimension');if(r&&5===r.dims.length&&2===r.dims[3])throw new Error("bias is not allowed for packed kv.")}let w=f+m,b=0;if(s&&Tt.size(s.dims)>0){b=8;let e=s.dims;throw 1===e.length?e[0]===c?b=1:e[0]===3*c+2&&(b=3):2===e.length&&e[0]===c&&e[1]===w&&(b=5),8===b?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let y=!1,x=h;if(i&&Tt.size(i.dims)>0){if(3!==i.dims.length&&4!==i.dims.length)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(3===i.dims.length){if(m!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');x=i.dims[2]}else{if(m!==i.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');x=i.dims[1]*i.dims[3],y=!0}}if(s&&Tt.size(s.dims)>0)throw new Error("Key padding mask is not supported");if(o&&Tt.size(o.dims)>0){if(4!==o.dims.length)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(o.dims[0]!==c||o.dims[1]!==t.numHeads||o.dims[2]!==p||o.dims[3]!==w)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:c,sequenceLength:p,pastSequenceLength:f,kvSequenceLength:m,totalSequenceLength:w,maxSequenceLength:g,inputHiddenSize:0,hiddenSize:h,vHiddenSize:x,headSize:_,vHeadSize:Math.floor(x/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:b,scale:t.scale,broadcastResPosBias:!1,passPastInKv:y,qkvFormat:d}},Ms=e=>xt({...e}),Ts=xt({perm:[0,2,1,3]}),ks=(e,t,n,r,i,a,s)=>{let o=[r,i,a],l=Tt.size(o),u=[{type:12,data:l},{type:12,data:s},{type:12,data:a}];return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:o,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:e=>{let r=Vt("qkv_with_bias",t.dataType,o),i=Rt("qkv",t.dataType,o),a=Rt("bias",n.dataType,o);return`\n ${e.registerUniforms([{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}]).declareVariables(i,a,r)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;\n\n qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];\n }`}},{inputs:[t,n],outputs:[-1]})[0]},$s=(e,t,n,r,i,a,s,o)=>{let l=a;if(s&&Tt.size(s.dims)>0){if(1===r)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=ks(e,a,s,t,r,n*i,o),l=l.reshape([t,r,n,i]),1===n||1===r?l:e.compute(Zt(l,Ts.perm),{inputs:[l],outputs:[-1]})[0]}return 3===a.dims.length&&(l=a.reshape([t,r,n,i])),1===n||1===r?l:e.compute(Zt(l,Ts.perm),{inputs:[l],outputs:[-1]})[0]},Ss=(e,t)=>{let n=vs(e.inputs,t),r=e.inputs[0],i=xs(e.inputs,1),a=xs(e.inputs,2),s=xs(e.inputs,3),o=xs(e.inputs,4),l=xs(e.inputs,5),u=xs(e.inputs,6),d=xs(e.inputs,7);if(5===r.dims.length)throw new Error("Packed QKV is not implemented");if(5===i?.dims.length)throw new Error("Packed KV is not implemented");let c=i&&a&&4===i.dims.length&&4===a.dims.length,p=$s(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,r,s,0);if(c)return ir(e,p,i,a,o,void 0,u,d,l,n);if(!i||!a)throw new Error("key and value must be provided");let h=$s(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.headSize,i,s,n.hiddenSize),m=$s(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.vHeadSize,a,s,2*n.hiddenSize);ir(e,p,h,m,o,void 0,u,d,l,n)}})),ju=j((()=>{eu(),ou(),su(),lu(),Cs=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Es=(e,t)=>{let n=[],r=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach((e=>n.push(Number(e)))),r=n.length),xt({numOutputs:r,axis:t.axis,splitSizes:n})},Ps=e=>`\nfn calculateOutputIndex(index: u32) -> u32 {\n for (var i: u32 = 0u; i < ${e}u; i += 1u ) {\n if (index < ${Nt("uniforms.size_in_split_axis","i",e)}) {\n return i;\n }\n }\n return ${e}u;\n}`,Fs=e=>{let t=e.length,n=[];for(let r=0;r{let n=e[0].dims,r=Tt.size(n),i=e[0].dataType,a=Tt.normalizeAxis(t.axis,n.length),s=new Array(t.numOutputs),o=Rt("input",i,n.length),l=new Array(t.numOutputs),u=[],d=[],c=0,p=[{type:12,data:r}];for(let r=0;r`\n ${e.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(o,...s)}\n ${Ps(l.length)}\n ${Fs(s)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}\n\n var indices = ${o.offsetToIndices("global_idx")};\n var index = ${o.indicesGet("indices",a)};\n let output_number = calculateOutputIndex(index);\n if (output_number != 0) {\n index -= ${Nt("uniforms.size_in_split_axis","output_number - 1u",l.length)};\n ${o.indicesSet("indices",a,"index")};\n }\n writeBufferData(output_number, indices, global_idx);\n }`,getRunData:()=>({outputs:u,dispatchGroup:{x:Math.ceil(r/64)},programUniforms:p})}},Is=(e,t)=>{Cs(e.inputs);let n=1===e.inputs.length?t:Es(e.inputs,t);e.compute(As(e.inputs,n),{inputs:[0]})},zs=e=>{let t=e.axis,n=e.splitSizes,r=e.numOutputs<0?n.length:e.numOutputs;if(r!==n.length)throw new Error("numOutputs and splitSizes lengh must be equal");return xt({axis:t,numOutputs:r,splitSizes:n})}})),qu=j((()=>{su(),hu(),Vu(),ju(),uu(),Os=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let n=e[0],r=e[1],i=e[2],a=e[3],s=e[4];if(-1!==t.localWindowSize)throw new Error("Local attention is not supported");if(0!==t.softcap)throw new Error("Softcap is not supported");if(0!==t.rotaryInterleaved)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(3!==n.dims.length&&5!==n.dims.length)throw new Error("Input query is expected to have 3 or 5 dimensions");let o=n.dims[0],l=n.dims[1],u=3===n.dims.length?n.dims[2]:t.numHeads*n.dims[4],d=l,c=0,p=!r||0===r.dims.length,h=Math.floor(p?u/(t.numHeads+2*t.kvNumHeads):u/t.numHeads);p&&(u=h*t.numHeads);let m=a&&0!==a.dims.length,f=s&&0!==s.dims.length;if(m&&4===a.dims.length&&a.dims[0]===o&&a.dims[1]!==t.kvNumHeads&&a.dims[2]===t.kvNumHeads&&a.dims[3]===h)throw new Error("BSNH pastKey/pastValue is not supported");if(m&&f){if(4!==a.dims.length)throw new Error('Input "past_key" is expected to have 4 dimensions');if(4!==s.dims.length)throw new Error('Input "past_value" is expected to have 4 dimensions');c=a.dims[2]}else if(m||f)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let g=1;if(r&&r.dims.length>0){if(3!==n.dims.length)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(r.dims.length<3||r.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(n.dims[0]!==r.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(3===r.dims.length){if(n.dims[2]%r.dims[2]!=0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');d=r.dims[1]}else if(5===r.dims.length){if(r.dims[2]!==t.numHeads||2!==r.dims[3]||r.dims[4]!==h)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');d=r.dims[1]}else{if(r.dims[1]!==t.numHeads||r.dims[3]!==h)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');d=r.dims[2]}}else{if(3!==n.dims.length&&5!==n.dims.length)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(5===n.dims.length&&(n.dims[2]!==t.numHeads||3!==n.dims[3]))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');g=3}let _=!1,w=t.kvNumHeads?h*t.kvNumHeads:u;if(i&&i.dims.length>0){if(3!==i.dims.length&&4!==i.dims.length)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(3===i.dims.length){if(d!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');w=i.dims[2]}else{if(d!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');w=i.dims[1]*i.dims[3],_=!0}}let b=e.length>4?e[5]:void 0;if(b&&1!==b.dims.length&&b.dims[0]!==o)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:o,sequenceLength:l,pastSequenceLength:c,kvSequenceLength:d,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:u,vHiddenSize:w,headSize:h,vHeadSize:Math.floor(w/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:0,scale:t.scale,broadcastResPosBias:!1,passPastInKv:_,qkvFormat:g}},Bs=xt({perm:[0,2,1,3]}),Ls=(e,t,n)=>{let r=t,i=n.kvNumHeads;return 3===t.dims.length&&0!==n.kvSequenceLength&&(r=t.reshape([n.batchSize,n.kvSequenceLength,i,n.headSize]),r=e.compute(Zt(r,Bs.perm),{inputs:[r],outputs:[-1]})[0]),r},Ns=(e,t)=>{let n=Os(e.inputs,t);if(5===e.inputs[0].dims.length)throw new Error("Packed QKV is not implemented");if(5===e.inputs[1]?.dims.length)throw new Error("Packed KV is not implemented");let r=e.inputs[0],i=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,a=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,s=e.inputs[3]&&0!==e.inputs[3].dims.length?e.inputs[3]:void 0,o=e.inputs[4]&&0!==e.inputs[4].dims.length?e.inputs[4]:void 0,l=e.inputs.length>4?e.inputs[5]:void 0,u=e.inputs.length>5?e.inputs[6]:void 0,d=n.kvNumHeads?n.kvNumHeads:n.numHeads,c=xt({axis:2,numOutputs:3,splitSizes:[n.numHeads*n.headSize,d*n.headSize,d*n.headSize]}),[p,h,m]=i||a?[r,i,a]:e.compute(As([r],c),{inputs:[r],outputs:[-1,-1,-1]}),f=$s(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,p,void 0,0);ir(e,f,Ls(e,h,n),Ls(e,m,n),void 0,void 0,s,o,void 0,n,l,u)}})),Gu=j((()=>{eu(),ou(),uu(),lu(),Ds=(e,t,n,r,i,a,s,o)=>{let l=zt(a),u=1===l?"f32":`vec${l}f`,d=1===l?"vec2f":`mat2x${l}f`,c=i*s,p=64;1===c&&(p=256);let h=[i,s,a/l],m=[i,s,2],f=[];f.push(...It(h,m));return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${o};${p}`,inputDependencies:["rank","type","type"]},getRunData:()=>({outputs:[{dims:m,dataType:1}],dispatchGroup:{x:c},programUniforms:f}),getShaderSource:e=>{let i=Rt("x",t.dataType,3,l),a=[i,Rt("scale",n.dataType,n.dims),Rt("bias",r.dataType,r.dims),Vt("output",1,3,2)];return`\n var workgroup_shared : array<${d}, ${p}>;\n const workgroup_size = ${p}u;\n ${e.declareVariables(...a)}\n ${e.mainStart(p)}\n let batch = workgroup_index / uniforms.x_shape[1];\n let channel = workgroup_index % uniforms.x_shape[1];\n let hight = uniforms.x_shape[2];\n // initialize workgroup memory\n var sum = ${u}(0);\n var squared_sum = ${u}(0);\n for (var h = local_idx; h < hight; h += workgroup_size) {\n let value = ${u}(${i.get("batch","channel","h")});\n sum += value;\n squared_sum += value * value;\n }\n workgroup_shared[local_idx] = ${d}(sum, squared_sum);\n workgroupBarrier();\n\n for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) {\n if (local_idx < currSize) {\n workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize];\n }\n workgroupBarrier();\n }\n if (local_idx == 0) {\n let sum_final = ${Lt("workgroup_shared[0][0]",l)} / f32(hight * ${l});\n let squared_sum_final = ${Lt("workgroup_shared[0][1]",l)} / f32(hight * ${l});\n\n let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${o}));\n let channel_scale = inv_std_dev * f32(scale[channel]);\n let channel_shift = f32(bias[channel]) - sum_final * channel_scale;\n output[workgroup_index] = vec2f(channel_scale, channel_shift);\n }\n }`}},{inputs:[t,n,r],outputs:[-1]})[0]},Rs=(e,t,n)=>{let r=t[0].dims,i=r,a=r[0],s=r[1],o=Tt.sizeFromDimension(r,2),l=zt(o),u=Tt.size(i)/l,d=Ds(e,t[0],t[1],t[2],a,o,s,n.epsilon),c=[a,s,o/l],p=[a,s];e.compute({name:"InstanceNormalization",shaderCache:{hint:`${l}`,inputDependencies:["type","none"]},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},...It(c,p,c)]}),getShaderSource:e=>{let n=Rt("x",t[0].dataType,c.length,l),r=Rt("scale_shift",1,p.length,2),i=Vt("output",t[0].dataType,c.length,l),a=[n,r,i];return`\n ${e.registerUniform("output_size","u32").declareVariables(...a)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let outputIndices = ${i.offsetToIndices("global_idx")};\n let batch = outputIndices[0];\n let channel = outputIndices[1];\n let scale_shift = ${r.getByIndices("vec2(batch, channel)")};\n let value = ${n.getByOffset("global_idx")} * ${i.type.value}(scale_shift.x) + ${i.type.value}(scale_shift.y);\n ${i.setByOffset("global_idx","value")};\n }`}},{inputs:[t[0],d]})},Vs=(e,t,n)=>{let r=t[0].dims,i=r,a=r[0],s=r[r.length-1],o=Tt.sizeFromDimension(r,1)/s,l=zt(s),u=Tt.size(i)/l,d=[{type:12,data:o},{type:12,data:Math.floor(s/l)}],c=!1,p=[0,r.length-1];for(let e=0;er[p[t]]))),m=Ds(e,h,t[1],t[2],a,o,s,n.epsilon);e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:d}),getShaderSource:e=>{let n=Ft(t[0].dataType),r=1===l?"vec2f":`mat${l}x2f`,a=e=>{let t=0===e?"x":"y",r=1===l?"f32":`vec${l}f`;switch(l){case 1:return`${n}(${r}(scale.${t}))`;case 2:return`vec2<${n}>(${r}(scale[0].${t}, scale[1].${t}))`;case 4:return`vec4<${n}>(${r}(scale[0].${t}, scale[1].${t}, scale[2].${t}, scale[3].${t}))`;default:throw new Error(`Not supported compoents ${l}`)}},s=Rt("input",t[0].dataType,t[0].dims,l),o=Vt("output",t[0].dataType,i,l);return`\n @group(0) @binding(0) var input : array<${s.type.storage}>;\n @group(0) @binding(1) var scale_input : array<${r}>;\n @group(0) @binding(2) var output : array<${o.type.storage}>;\n struct Uniforms {H: u32, C : u32};\n @group(0) @binding(3) var uniforms: Uniforms;\n\n ${e.mainStart()}\n let current_image_number = global_idx / (uniforms.C * uniforms.H);\n let current_channel_number = global_idx % uniforms.C;\n\n let scale_offset = current_image_number * uniforms.C + current_channel_number;\n let scale = scale_input[scale_offset];\n output[global_idx] = fma(input[global_idx], ${a(0)}, ${a(1)});\n }`}},{inputs:[t[0],m]})},js=(e,t)=>{"NHWC"===t.format?Vs(e,e.inputs,t):Rs(e,e.inputs,t)}})),Uu=j((()=>{eu(),ou(),lu(),qs=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Gs=(e,t,n)=>{let r=t.simplified,i=e[0].dims,a=e[1],s=!r&&e[2],o=i,l=Tt.normalizeAxis(t.axis,i.length),u=Tt.sizeToDimension(i,l),d=Tt.sizeFromDimension(i,l),c=Tt.size(a.dims),p=s?Tt.size(s.dims):0;if(c!==d||s&&p!==d)throw new Error(`Size of X.shape()[axis:] == ${d}.\n Size of scale and bias (if provided) must match this.\n Got scale size of ${c} and bias size of ${p}`);let h=[];for(let e=0;e1,w=n>2,b=[{dims:o,dataType:e[0].dataType}];return _&&b.push({dims:h,dataType:1}),w&&b.push({dims:h,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${m};${n};${r}`,inputDependencies:f},getRunData:()=>({outputs:b,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:g}),getShaderSource:t=>{let n=Ft(e[0].dataType),i=[Rt("x",e[0].dataType,e[0].dims,m),Rt("scale",a.dataType,a.dims,m)];s&&i.push(Rt("bias",s.dataType,s.dims,m)),i.push(Vt("output",e[0].dataType,o,m)),_&&i.push(Vt("mean_data_output",1,h)),w&&i.push(Vt("inv_std_output",1,h));return`\n ${t.registerUniforms([{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}]).declareVariables(...i)}\n ${t.mainStart()}\n ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}\n let offset = global_idx * uniforms.norm_size_vectorized;\n var mean_vector = ${Ot("f32",m)};\n var mean_square_vector = ${Ot("f32",m)};\n\n for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {\n let value = ${Bt(n,m,"x[h + offset]")};\n mean_vector += value;\n mean_square_vector += value * value;\n }\n let mean = ${Lt("mean_vector",m)} / uniforms.norm_size;\n let inv_std_dev = inverseSqrt(${Lt("mean_square_vector",m)} / uniforms.norm_size ${r?"":"- mean * mean"} + uniforms.epsilon);\n\n for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {\n let f32input = ${Bt(n,m,"x[j + offset]")};\n let f32scale = ${Bt(n,m,"scale[j]")};\n output[j + offset] = ${i[0].type.value}((f32input ${r?"":"- mean"}) * inv_std_dev * f32scale\n ${s?`+ ${Bt(n,m,"bias[j]")}`:""}\n );\n }\n\n ${_?"mean_data_output[global_idx] = mean":""};\n ${w?"inv_std_output[global_idx] = inv_std_dev":""};\n }`}}},Us=(e,t)=>{qs(e.inputs),e.compute(Gs(e.inputs,t,e.outputCount))}})),Wu=j((()=>{ou(),Mu(),Tu(),Ws=e=>{if(!e||2!==e.length)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},Hs=e=>{Ws(e.inputs);let t=Mt.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let n=t[t.length-1],r=e.inputs[0].dims[e.inputs[0].dims.length-1];if(n<8&&r<8)e.compute(Oi(e.inputs,{activation:""},t));else{let i=t[t.length-2],a=Tt.size(e.inputs[0].dims.slice(0,-2)),s=Tt.size(e.inputs[1].dims.slice(0,-2));if(1!==a&&1===i&&1===s){let i=[1,a,n],s=[e.inputs[0].reshape([1,a,r]),e.inputs[1].reshape([1,r,n])];e.compute(qi(s,{activation:""},t,i),{inputs:s})}else e.compute(qi(e.inputs,{activation:""},t))}}})),Hu=j((()=>{eu(),ou(),su(),lu(),Ks=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let n=e[0],r=n.dims.length;if(n.dims[r-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let i=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,s=e[1];if(!Tt.areEqual(s.dims,[t.n,i,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let o=e[2].dims;if(Tt.size(o)!==t.n*i)throw new Error("scales input size error.");if(4===e.length){let n=e[3].dims,r=t.bits>4?t.n*i:t.n*Math.floor((i+1)/2);if(Tt.size(n)!==r)throw new Error("zeroPoints input size error.")}},Xs=(e,t)=>{let n=e[0].dims,r=n.length,i=n[r-2],a=t.k,s=t.n,o=n.slice(0,r-2),l=Tt.size(o),u=e[1].dims[2]/4,d=e[0].dataType,c=zt(t.k),p=zt(u),h=zt(s),m=o.concat([i,s]),f=i>1&&s/h%2==0?2:1,g=Tt.size(m)/h/f,_=64,w=[],b=[l,i,a/c],y=Tt.convertShape(e[1].dims).slice();y.splice(-1,1,u/p),w.push(...It(b)),w.push(...It(y)),w.push(...It(e[2].dims)),4===e.length&&w.push(...It(Tt.convertShape(e[3].dims)));let x=[l,i,s/h];w.push(...It(x));return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${c};${p};${h};${f};64`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:m,dataType:d}],dispatchGroup:{x:g},programUniforms:w}),getShaderSource:n=>{let r=b.length,i=Rt("a",e[0].dataType,r,c),a=Rt("b",12,y.length,p),s=Rt("scales",e[2].dataType,e[2].dims.length),o=[i,a,s],l=4===e.length?Rt("zero_points",12,e[3].dims.length):void 0;l&&o.push(l);let d=x.length,m=Vt("output",e[0].dataType,d,h),g=Ft(e[0].dataType),w=(()=>{switch(c){case 1:return`array<${g}, 8>`;case 2:return`mat4x2<${g}>`;case 4:return`mat2x4<${g}>`;default:throw new Error(`${c}-component is not supported.`)}})();return`\n var workgroup_shared: array<${m.type.value}, ${f*_}>;\n ${n.declareVariables(...o,m)}\n ${n.mainStart([_,1,1])}\n let output_indices = ${m.offsetToIndices(`(global_idx / 64) * ${f}`)};\n let col = output_indices[2];\n let row = output_indices[1];\n let batch = output_indices[0];\n let nBlocksPerCol = uniforms.b_shape[1];\n\n for (var block = local_id.x; block < nBlocksPerCol; block += 64) {\n //process one block\n var word_offset: u32 = block * ${t.blockSize/c};\n ${(()=>{let e=`\n var col_index = col * ${h};\n ${l?"\n let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2;\n var zero_point_byte_count: u32;\n var zero_point_word_index: u32;\n var zero_point_byte_offset: u32;\n let zero_point_nibble_offset: u32 = block & 0x1u;\n var zero_point_bits_offset: u32;\n var zero_point_word: u32;":`\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${g}(8);`}\n `;for(let t=0;t> 0x1u);\n zero_point_word_index = zero_point_byte_count >> 0x2u;\n zero_point_byte_offset = zero_point_byte_count & 0x3u;\n zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n zero_point_word = ${l.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;\n let zero_point${t} = ${g}((zero_point_word) & 0xFu);`:""}\n col_index += 1;`;return e})()}\n for (var word: u32 = 0; word < ${u}; word += ${p}) {\n ${(()=>{let e=`col_index = col * ${h};`;for(let t=0;t;\n var b_value_upper: vec4;\n var b_quantized_values: ${w};\n var b_dequantized_values: ${w};`,e})()}\n for (var i: u32 = 0; i < ${p}; i++) {\n ${(()=>{let e=`\n // reuse a data\n var input_offset = ${i.indicesToOffset(`${i.type.indices}(batch, row, word_offset)`)};\n var a_data: ${w};\n for (var j: u32 = 0; j < ${8/c}; j++) {\n a_data[j] = ${i.getByOffset("input_offset")};\n input_offset++;\n }\n `;for(let t=0;t> 4) & b_mask);\n b_quantized_values = ${w}(${Array.from({length:4},((e,t)=>`${g}(b_value_lower[${t}]), ${g}(b_value_upper[${t}])`)).join(", ")});\n b_dequantized_values = ${1===c?`${w}(${Array.from({length:8},((e,n)=>`(b_quantized_values[${n}] - ${l?`zero_point${t}`:"zero_point"}) * scale${t}`)).join(", ")});`:`(b_quantized_values - ${w}(${Array(8).fill(l?`zero_point${t}`:"zero_point").join(",")})) * scale${t};`};\n workgroup_shared[local_id.x * ${f} + ${Math.floor(t/h)}]${h>1?`[${t%h}]`:""} += ${Array.from({length:8/c},((e,t)=>""+(1===c?`a_data[${t}] * b_dequantized_values[${t}]`:`dot(a_data[${t}], b_dequantized_values[${t}])`))).join(" + ")};\n `;return e})()}\n word_offset += ${8/c};\n }\n }\n }\n workgroupBarrier();\n\n if (local_id.x < ${f}) {\n var output_value: ${m.type.value} = ${m.type.value}(0);\n var workgroup_shared_offset: u32 = local_id.x;\n for (var b: u32 = 0u; b < 64u; b++) {\n output_value += workgroup_shared[workgroup_shared_offset];\n workgroup_shared_offset += ${f};\n }\n ${m.setByIndices(`${m.type.indices}(batch, row, col + local_id.x)`,"output_value")};\n }\n }`}}},Qs=(e,t)=>{let n=e[0].dims,r=n.length,i=n[r-2],a=t.k,s=t.n,o=n.slice(0,r-2),l=Tt.size(o),u=e[1].dims[2]/4,d=e[0].dataType,c=zt(t.k),p=zt(u),h=o.concat([i,s]),m=s%8==0?8:s%4==0?4:1,f=128/m,g=f*p*8,_=g/c,w=g/t.blockSize,b=Tt.size(h)/m,y=[],x=[l,i,a/c],v=Tt.convertShape(e[1].dims).slice();v.splice(-1,1,u/p),y.push(...It(x)),y.push(...It(v)),y.push(...It(e[2].dims)),4===e.length&&y.push(...It(Tt.convertShape(e[3].dims)));let M=[l,i,s];y.push(...It(M));return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${c};${p};${f};${m}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:h,dataType:d}],dispatchGroup:{x:b},programUniforms:y}),getShaderSource:n=>{let r=x.length,i=Rt("a",e[0].dataType,r,c),a=Rt("b",12,v.length,p),s=Rt("scales",e[2].dataType,e[2].dims.length),o=[i,a,s],l=4===e.length?Rt("zero_points",12,e[3].dims.length):void 0;l&&o.push(l);let u=M.length,d=Vt("output",e[0].dataType,u),h=Ft(e[0].dataType);return`\n var sub_a: array<${i.type.value}, ${_}>;\n var inter_results: array, ${m}>;\n ${n.declareVariables(...o,d)}\n ${n.mainStart([f,m,1])}\n let output_indices = ${d.offsetToIndices(`workgroup_index * ${m}`)};\n let col = output_indices[2];\n let row = output_indices[1];\n let batch = output_indices[0];\n let n_blocks_per_col = uniforms.b_shape[1];\n let num_tiles = (n_blocks_per_col - 1) / ${w} + 1;\n\n // Loop over shared dimension.\n for (var tile: u32 = 0; tile < num_tiles; tile += 1) {\n let a_col_start = tile * ${_};\n // load one tile A data into shared memory.\n for (var a_offset = local_idx; a_offset < ${_}; a_offset += 128)\n {\n let a_col = a_col_start + a_offset;\n if (a_col < uniforms.a_shape[2])\n {\n sub_a[a_offset] = ${i.getByIndices(`${i.type.indices}(batch, row, a_col)`)};\n } else {\n sub_a[a_offset] = ${i.type.value}(0);\n }\n }\n workgroupBarrier();\n\n // each thread process one block\n let b_row = col + local_id.y;\n let block = tile * ${w} + local_id.x;\n ${l?`\n let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2;\n let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u);\n let zero_point_word_index = zero_point_byte_count >> 0x2u;\n let zero_point_byte_offset = zero_point_byte_count & 0x3u;\n let zero_point_nibble_offset: u32 = block & 0x1u;\n let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n let zero_point_word = ${l.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;\n let zero_point = ${h}((zero_point_word) & 0xFu);`:`\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${h}(8);`}\n let scale = ${s.getByOffset("b_row * n_blocks_per_col + block")};\n let b_data = ${a.getByIndices(`${a.type.indices}(b_row, block, 0)`)};\n var word_offset = local_id.x * ${t.blockSize/c};\n for (var i: u32 = 0; i < ${p}; i++) {\n ${(()=>{switch(c){case 1:return`\n let a_data0 = vec4<${h}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]);\n let a_data1 = vec4<${h}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return`\n let a_data0 = vec4<${h}>(sub_a[word_offset], sub_a[word_offset + 1]);\n let a_data1 = vec4<${h}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return"\n let a_data0 = sub_a[word_offset];\n let a_data1 = sub_a[word_offset + 1];";default:throw new Error(`${c}-component is not supported.`)}})()}\n let b_value = ${1===p?"b_data":"b_data[i]"};\n let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu);\n let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu);\n let b_quantized_values = mat2x4<${h}>(${Array.from({length:4},((e,t)=>`${h}(b_value_lower[${t}]), ${h}(b_value_upper[${t}])`)).join(", ")});\n let b_dequantized_values = (b_quantized_values - mat2x4<${h}>(${Array(8).fill("zero_point").join(",")})) * scale;\n inter_results[local_id.y][local_id.x] += ${Array.from({length:2},((e,t)=>`dot(a_data${t}, b_dequantized_values[${t}])`)).join(" + ")};\n word_offset += ${8/c};\n }\n workgroupBarrier();\n }\n\n if (local_idx < ${m}) {\n var output_value: ${d.type.value} = ${d.type.value}(0);\n for (var b = 0u; b < ${f}; b++) {\n output_value += inter_results[local_idx][b];\n }\n if (col + local_idx < uniforms.output_shape[2])\n {\n ${d.setByIndices(`${d.type.indices}(batch, row, col + local_idx)`,"output_value")}\n }\n }\n }`}}},Ys=(e,t)=>{Ks(e.inputs,t),32===t.blockSize&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(Qs(e.inputs,t)):e.compute(Xs(e.inputs,t))},Zs=e=>xt(e)})),Ku=j((()=>{eu(),ou(),lu(),Js=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(1!==e[0].dataType&&10!==e[0].dataType)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=2*e[0].dims.length===e[1].dims[0];if(4===e.length&&(t=2*e[3].dims[0]===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},eo=(e,t,n)=>{let r="";for(let i=t-1;i>=0;--i)r+=`\n k = i32(${e.indicesGet("indices",i)}) - ${Nt("uniforms.pads",i,n)};\n if (k < 0) {\n break;\n }\n if (k >= i32(${Nt("uniforms.x_shape",i,t)})) {\n break;\n }\n offset += k * i32(${Nt("uniforms.x_strides",i,t)});\n `;return`\n value = ${e.type.value}(uniforms.constant_value);\n for (var i = 0; i < 1; i++) {\n var offset = 0;\n var k = 0;\n ${r}\n value = x[offset];\n }\n `},to=(e,t,n)=>{let r="";for(let i=t-1;i>=0;--i)r+=`\n k = i32(${e.indicesGet("indices",i)}) - ${Nt("uniforms.pads",i,n)};\n if (k < 0) {\n k = -k;\n }\n {\n let _2n_1 = 2 * (i32(${Nt("uniforms.x_shape",i,t)}) - 1);\n k = k % _2n_1;\n if(k >= i32(${Nt("uniforms.x_shape",i,t)})) {\n k = _2n_1 - k;\n }\n }\n offset += k * i32(${Nt("uniforms.x_strides",i,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${r}\n value = x[offset];\n `},no=(e,t,n)=>{let r="";for(let i=t-1;i>=0;--i)r+=`\n k = i32(${e.indicesGet("indices",i)}) - ${Nt("uniforms.pads",i,n)};\n if (k < 0) {\n k = 0;\n }\n if (k >= i32(${Nt("uniforms.x_shape",i,t)})) {\n k = i32(${Nt("uniforms.x_shape",i,t)}) - 1;\n }\n offset += k * i32(${Nt("uniforms.x_strides",i,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${r}\n value = x[offset];\n `},ro=(e,t,n)=>{let r="";for(let i=t-1;i>=0;--i)r+=`\n k = i32(${e.indicesGet("indices",i)}) - ${Nt("uniforms.pads",i,n)};\n if (k < 0) {\n k += i32(${Nt("uniforms.x_shape",i,t)}]);\n }\n if (k >= i32(${Nt("uniforms.x_shape",i,t)})) {\n k -= i32(${Nt("uniforms.x_shape",i,t)});\n }\n offset += k * i32(${Nt("uniforms.x_strides",i,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${r}\n value = x[offset];\n `},io=(e,t,n)=>{switch(n.mode){case 0:return eo(e,t,n.pads.length);case 1:return to(e,t,n.pads.length);case 2:return no(e,t,n.pads.length);case 3:return ro(e,t,n.pads.length);default:throw new Error("Invalid mode")}},ao=(e,t)=>{let n=Tt.padShape(e[0].dims.slice(),t.pads),r=e[0].dims,i=[{type:12,data:Tt.size(n)},{type:6,data:t.pads}],a=e.length>=3&&e[2].data;0===t.mode&&i.push({type:a?e[2].dataType:1,data:t.value}),i.push(...It(e[0].dims,n));return{name:"Pad",shaderCache:{hint:`${t.mode}${a}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Tt.size(n)/64)},programUniforms:i}),getShaderSource:i=>{let s=Vt("output",e[0].dataType,n.length),o=Rt("x",e[0].dataType,r.length),l=o.type.value,u=io(s,r.length,t),d=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return 0===t.mode&&d.push({name:"constant_value",type:a?l:"f32"}),`\n ${i.registerUniforms(d).declareVariables(o,s)}\n ${i.mainStart()}\n ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${s.offsetToIndices("global_idx")};\n\n var value = ${l}(0);\n ${u}\n output[global_idx] = value;\n }`}}},so=(e,t)=>{if(e.length>1){let n=e[1].getBigInt64Array(),r=e.length>=3&&e[2].data?10===e[2].dataType?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,i=e[0].dims.length,a=new Int32Array(2*i).fill(0);if(e.length>=4){let t=e[3].getBigInt64Array();for(let e=0;ea[Number(t)]=Number(e)));let s=[];return a.forEach((e=>s.push(e))),{mode:t.mode,value:r,pads:s}}return t},oo=(e,t)=>{Js(e.inputs);let n=so(e.inputs,t);e.compute(ao(e.inputs,n),{inputs:[0]})}})),Xu=j((()=>{pe(),eu(),ou(),lu(),lo=e=>{if(p.webgpu.validateInputContent&&(!e||1!==e.length))throw new Error("Pool ops requires 1 input.")},uo=(e,t,n)=>{let r="NHWC"===t.format,i=e.dims.slice();r&&i.splice(1,0,i.pop());let a=Object.hasOwnProperty.call(t,"dilations"),s=t.kernelShape.slice(),o=t.strides.slice(),l=a?t.dilations.slice():[],u=t.pads.slice();kt.adjustPoolAttributes(n,i,s,o,l,u);let d=kt.computePoolOutputShape(n,i,o,l,s,u,t.autoPad),c=Object.assign({},t);a?Object.assign(c,{kernelShape:s,strides:o,pads:u,dilations:l,cacheKey:t.cacheKey}):Object.assign(c,{kernelShape:s,strides:o,pads:u,cacheKey:t.cacheKey});let p=d.slice();return p.push(p.splice(1,1)[0]),[c,r?p:d]},co=(e,t)=>{let n="NHWC"===t.format,r=[{type:12,data:Tt.size(e)},{type:12,data:Tt.size(t.kernelShape)}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let e=t.kernelShape[t.kernelShape.length-1],n=t.strides[t.strides.length-1],a=t.pads[t.pads.length/2-1],s=t.pads[t.pads.length-1],o=!!(a+s);r.push({type:12,data:e},{type:12,data:n},{type:12,data:a},{type:12,data:s}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let l=!1;if(2===t.kernelShape.length){let e=t.kernelShape[t.kernelShape.length-2],n=t.strides[t.strides.length-2],a=t.pads[t.pads.length/2-2],s=t.pads[t.pads.length-2];l=!!(a+s),r.push({type:12,data:e},{type:12,data:n},{type:12,data:a},{type:12,data:s}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[r,i,!0,o,l]}{if(n)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let e=Tt.computeStrides(t.kernelShape);return r.push({type:12,data:e},{type:12,data:t.pads},{type:12,data:t.strides}),i.push({name:"kernelStrides",type:"u32",length:e.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length}),[r,i,!!t.pads.reduce(((e,t)=>e+t)),!1,!1]}},po=(e,t,n,r,i,a,s,o,l,u,d,c)=>{let p="NHWC"===i.format,h=t.type.value,m=Vt("output",t.type.tensor,r);if(i.kernelShape.length<=2){let r="",u="",f="",g=n-(p?2:1);if(r=d?`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i;\n if (xIndices[${g}] < 0 || xIndices[${g}]\n >= uniforms.x_shape[${g}]) {\n pad++;\n continue;\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${a}\n }`:`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i;\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${a}\n }`,2===i.kernelShape.length){let e=n-(p?3:2);u=c?`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${e}] = indices[${e}] * uniforms.sh - uniforms.phStart + j;\n if (xIndices[${e}] < 0 || xIndices[${e}] >= uniforms.x_shape[${e}]) {\n pad += i32(uniforms.kw);\n continue;\n }\n `:`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${e}] = indices[${e}] * uniforms.sh - uniforms.phStart + j;\n `,f="\n }\n "}return`\n ${e.registerUniforms(l).declareVariables(t,m)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let indices = ${m.offsetToIndices("global_idx")};\n var xIndices = ${m.offsetToIndices("global_idx")};\n\n var value = ${h}(${o});\n var pad = 0;\n ${u}\n ${r}\n ${f}\n ${s}\n\n output[global_idx] = value;\n }`}{if(p)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let r=i.kernelShape.length,d=i.pads.length,c="";return c=u?`\n if (xIndices[j] >= uniforms.x_shape[j]) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${a}\n }`:`\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${a}\n `,`\n ${e.registerUniforms(l).declareVariables(t,m)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let indices = ${m.offsetToIndices("global_idx")};\n var xIndices = ${m.offsetToIndices("global_idx")};\n\n var offsets: array;\n\n var value = ${h}(${o});\n var pad = 0;\n var isPad = false;\n\n for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {\n var offset = i;\n for (var j = 0u; j < ${r-1}u; j++) {\n offsets[j] = offset / ${Nt("uniforms.kernelStrides","j",r)};\n offset -= offsets[j] * ${Nt("uniforms.kernelStrides","j",r)};\n }\n offsets[${r-1}] = offset;\n\n isPad = false;\n for (var j = ${n-r}u; j < ${n}u; j++) {\n xIndices[j] = indices[j] * ${Nt("uniforms.strides",`j - ${n-r}u`,r)}\n + offsets[j - ${n-r}u] - ${Nt("uniforms.pads","j - 2u",d)};\n ${c}\n }\n ${s}\n\n output[global_idx] = value;\n }`}},ho=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,mo=e=>`${ho(e)};${e.countIncludePad}`,fo=e=>`${ho(e)};${e.storageOrder};${e.dilations}`,go=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),_o=(e,t,n,r)=>{let[i,a]=uo(t,r,n),s=Rt("x",t.dataType,t.dims.length),o=s.type.value,l="";i.countIncludePad?l+=`value /= ${o}(uniforms.kernelSize);`:l+=`value /= ${o}(i32(uniforms.kernelSize) - pad);`;let[u,d,c,p,h]=co(a,i);u.push(...It(t.dims,a));return{name:e,shaderCache:{hint:`${r.cacheKey};${c};${p};${h}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Tt.size(a)/64)},programUniforms:u}),getShaderSource:e=>po(e,s,t.dims.length,a.length,i,"value += x_val;",l,0,d,c,p,h)}},wo=e=>{let t=0!==e.count_include_pad,n=go(e);if(0!==n.ceilMode)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let r={countIncludePad:t,...n,cacheKey:""};return{...r,cacheKey:mo(r)}},bo=(e,t)=>{lo(e.inputs),e.compute(_o("AveragePool",e.inputs[0],!1,t))},yo={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},xo=e=>{let t=e.format;return{format:t,...yo,cacheKey:t}},vo=(e,t)=>{lo(e.inputs),e.compute(_o("GlobalAveragePool",e.inputs[0],!0,t))},Mo=(e,t,n,r)=>{let[i,a]=uo(t,r,n),s=Rt("x",t.dataType,t.dims.length),[o,l,u,d,c]=co(a,i);return o.push(...It(t.dims,a)),{name:e,shaderCache:{hint:`${r.cacheKey};${u};${d};${c}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Tt.size(a)/64)},programUniforms:o}),getShaderSource:e=>po(e,s,t.dims.length,a.length,i,"\n value = max(x_val, value);\n ","",10===t.dataType?-65504:-1e5,l,u,d,c)}},To=(e,t)=>{lo(e.inputs),e.compute(Mo("MaxPool",e.inputs[0],!1,t))},ko=e=>{let t=e.storage_order,n=e.dilations,r=go(e);if(0!==t)throw new Error("column major storage order is not yet supported for MaxPool");if(0!==r.ceilMode)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let i={storageOrder:t,dilations:n,...r,cacheKey:""};return{...i,cacheKey:fo(i)}},$o=e=>{let t=e.format;return{format:t,...yo,cacheKey:t}},So=(e,t)=>{lo(e.inputs),e.compute(Mo("GlobalMaxPool",e.inputs[0],!0,t))}})),Qu=j((()=>{eu(),ou(),su(),lu(),Co=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(3===e.length&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(3===e.length&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(6===e[0].dataType&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(0!==e[1].dims.length&&1!==e[1].dims.length&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map(((t,n)=>t===e[2].dims[n])).reduce(((e,t)=>e&&t),!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(0===e[1].dims.length||1===e[1].dims.length&&1===e[1].dims[0])throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map(((n,r)=>r===t.axis||n===e[0].dims[r])).reduce(((e,t)=>e&&t),!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let n=e[0].dims[t.axis],r=e[1].dims[t.axis];if(t.blockSizeMath.ceil(n/(r-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Eo=(e,t)=>{let n=Tt.normalizeAxis(t.axis,e[0].dims.length),r=e[0].dataType,i=3===r,a=e[0].dims,s=e[1].dataType,o=Tt.size(a),l=3===r||2===r,u=l?[Math.ceil(Tt.size(e[0].dims)/4)]:e[0].dims,d=e[1].dims,c=e.length>2?e[2]:void 0,p=c?l?[Math.ceil(Tt.size(c.dims)/4)]:c.dims:void 0,h=0===d.length||1===d.length&&1===d[0],m=!1===h&&1===d.length,f=zt(o),g=h&&(!l||4===f),_=g?f:1,w=g&&!l?f:1,b=Rt("input",l?12:r,u.length,w),y=Rt("scale",s,d.length),x=c?Rt("zero_point",l?12:r,p.length):void 0,v=Vt("output",s,a.length,_),M=[b,y];x&&M.push(x);let T=[u,d];c&&T.push(p);let k=[{type:12,data:o/_},{type:12,data:n},{type:12,data:t.blockSize},...It(...T,a)];return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:x?["rank","rank","rank"]:["rank","rank"]},getShaderSource:e=>`\n ${e.registerUniforms([{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}]).declareVariables(...M,v)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let output_indices = ${v.offsetToIndices("global_idx")};\n\n // Set input x\n ${l?`\n let input = ${b.getByOffset("global_idx / 4")};\n let x_vec = ${i?"unpack4xI8(input)":"unpack4xU8(input)"};\n let x_value = ${1===_?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${b.getByOffset("global_idx")};`};\n\n // Set scale input\n ${h?`let scale_value= ${y.getByOffset("0")}`:m?`\n let scale_index = ${v.indicesGet("output_indices","uniforms.axis")};\n let scale_value= ${y.getByOffset("scale_index")};`:`\n var scale_indices: ${y.type.indices} = output_indices;\n let index = ${y.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size;\n ${y.indicesSet("scale_indices","uniforms.axis","index")};\n let scale_value= ${y.getByIndices("scale_indices")};`};\n\n // Set zero-point input\n ${x?h?l?`\n let zero_point_input = ${x.getByOffset("0")};\n let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};\n let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${x.getByOffset("0")}`:m?l?`\n let zero_point_index = ${v.indicesGet("output_indices","uniforms.axis")};\n let zero_point_input = ${x.getByOffset("zero_point_index / 4")};\n let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};\n let zero_point_value = zero_point_vec[zero_point_index % 4]`:`\n let zero_point_index = ${v.indicesGet("output_indices","uniforms.axis")};\n let zero_point_value = ${x.getByOffset("zero_point_index")};`:l?`\n let zero_point_offset = ${y.indicesToOffset("scale_indices")};\n let zero_point_input = ${x.getByOffset("zero_point_offset / 4")};\n let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};\n let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${x.getByIndices("scale_indices")};`:`let zero_point_value = ${l?i?"i32":"u32":b.type.value}(0);`};\n // Compute and write output\n ${v.setByOffset("global_idx",`${v.type.value}(x_value - zero_point_value) * scale_value`)};\n }`,getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:Math.ceil(o/_/64),y:1,z:1},programUniforms:k})}},Po=(e,t)=>{Co(e.inputs,t),e.compute(Eo(e.inputs,t))},Fo=e=>xt({axis:e.axis,blockSize:e.blockSize})})),Yu=j((()=>{pe(),eu(),lu(),Ao=(e,t,n)=>{if(e===t||et&&n>0)throw new Error("Range these inputs' contents are invalid.")},Io=(e,t,n,r)=>{let i=Math.abs(Math.ceil((t-e)/n)),a=[i],s=i,o=[{type:12,data:s},{type:r,data:e},{type:r,data:n},...It(a)];return{name:"Range",shaderCache:{hint:`${r}`},getShaderSource:e=>{let t=Vt("output",r,a.length),n=t.type.value,i=[{name:"outputSize",type:"u32"},{name:"start",type:n},{name:"delta",type:n}];return`\n ${e.registerUniforms(i).declareVariables(t)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n output[global_idx] = uniforms.start + ${n}(global_idx) * uniforms.delta;\n }`},getRunData:()=>({outputs:[{dims:a,dataType:r}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:o})}},zo=e=>{let t=0,n=0,r=0;6===e.inputs[0].dataType?(t=e.inputs[0].getInt32Array()[0],n=e.inputs[1].getInt32Array()[0],r=e.inputs[2].getInt32Array()[0]):1===e.inputs[0].dataType&&(t=e.inputs[0].getFloat32Array()[0],n=e.inputs[1].getFloat32Array()[0],r=e.inputs[2].getFloat32Array()[0]),p.webgpu.validateInputContent&&Ao(t,n,r),e.compute(Io(t,n,r,e.inputs[0].dataType),{inputs:[]})}})),Zu=j((()=>{eu(),ou(),su(),lu(),Oo=(e,t,n,r)=>{if("none"!==e&&"i32"!==r&&"u32"!==r&&"f32"!==r)throw new Error(`Input ${r} is not supported with reduction ${e}.`);let i="{\n var oldValue = 0;\n loop {\n let newValueF32 =",a=`;\n let newValue = bitcast(newValueF32);\n let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue);\n if res.exchanged {\n break;\n }\n oldValue = res.old_value;\n }\n }`;switch(e){case"none":return`${t}=${n};`;case"add":return"i32"===r||"u32"===r?`atomicAdd(&${t}, bitcast<${r}>(${n}));`:`\n ${i}bitcast<${r}>(oldValue) + (${n})${a}`;case"max":return"i32"===r||"u32"===r?`atomicMax(&${t}, bitcast<${r}>(${n}));`:`\n ${i}max(bitcast(oldValue), (${n}))${a}`;case"min":return"i32"===r||"u32"===r?`atomicMin(&${t}, bitcast<${r}>(${n}));`:`${i}min(bitcast<${r}>(oldValue), (${n}))${a}`;case"mul":return`${i}(bitcast<${r}>(oldValue) * (${n}))${a}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Bo=(e,t)=>{let n=e[0].dims,r=e[1].dims,i=n,a=Math.ceil(Tt.size(r)/1),s=r[r.length-1],o=Tt.sizeFromDimension(n,s),l=[{type:12,data:a},{type:12,data:s},{type:12,data:o},...It(e[1].dims,e[2].dims,i)];return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l}),getShaderSource:n=>{let r=Rt("indices",e[1].dataType,e[1].dims.length),a=Rt("updates",e[2].dataType,e[2].dims.length,1),s="none"!==t.reduction&&""!==t.reduction?jt("output",e[0].dataType,i.length):Vt("output",e[0].dataType,i.length,1);return`\n ${n.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(r,a,s)}\n ${n.mainStart()}\n ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var data_offset = 0u;\n let indices_start = uniforms.last_index_dimension * global_idx;\n let indices_end = indices_start + uniforms.last_index_dimension;\n for (var i = indices_start; i < indices_end; i++) {\n var index = i32(indices[i].x);\n ${1===e[0].dims.length?"\n let element_count_dim = uniforms.output_strides;\n let dim_value = uniforms.output_shape;":"\n let element_count_dim = uniforms.output_strides[i - indices_start];\n let dim_value = uniforms.output_shape[i - indices_start + uniforms.last_index_dimension];"}\n if (index >= 0) {\n if (index >= i32(dim_value)) {\n index = i32(dim_value - 1);\n }\n } else {\n if (index < -i32(dim_value)) {\n index = 0;\n } else {\n index += i32(dim_value);\n }\n }\n data_offset += u32((u32(index) * element_count_dim));\n }\n\n for (var i = 0u; i < uniforms.num_updates_elements; i++) {\n let value = updates[uniforms.num_updates_elements * global_idx + i];\n ${Oo(t.reduction,"output[data_offset + i]","value",s.type.value)}\n }\n\n }`}}},Lo=e=>xt({reduction:e.reduction}),No=(e,t)=>{e.compute(Bo(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}})),Ju=j((()=>{eu(),ou(),su(),lu(),Do=(e,t)=>{if(e.every((e=>e>0||(()=>{throw new Error("Resize requires scales input values to be positive")}))),e.length>0)if("linear"===t.mode){if(!(2===e.length||3===e.length||4===e.length&&1===e[0]&&1===e[1]||4===e.length&&1===e[0]&&1===e[3]||5===e.length&&1===e[0]&&1===e[1]))throw new Error("For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and\n one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1")}else if("cubic"===t.mode&&!(2===e.length||4===e.length&&1===e[0]&&1===e[1]||4===e.length&&1===e[0]&&1===e[3]))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")},Ro=(e,t,n)=>{t.every((e=>e>=0&&e{throw new Error("Resize requires axes input values to be positive and less than rank")})));let r=new Array(n).fill(1);return t.forEach(((t,n)=>r[t]=e[n])),r},Vo=(e,t,n,r,i,a)=>{let[s,o,l]=n>10?[1,2,3]:[-1,e.length>1?1:-1,-1],u=e[0].dims.length;if(s>0&&e.length>s&&e[s].dims.length>0)e[s].getFloat32Array().forEach((e=>a.push(e)));else if("tf_crop_and_resize"===t.coordinateTransformMode)throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(o>0&&e.length>o&&1===e[o].dims.length&&e[o].dims[0]>0){if(e[o].getFloat32Array().forEach((e=>r.push(e))),0!==r.length&&r.length!==u&&n>=18&&r.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Do(r,t),t.axes.length>0&&Ro(r,t.axes,u).forEach(((e,t)=>r[t]=e))}if(l>0&&e.length>l&&1===e[l].dims.length&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach((e=>i.push(Number(e)))),0!==i.length&&i.length!==u&&n>=18&&i.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(0!==r.length&&r.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(0!==i.length&&i.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof r<"u"&&typeof i<"u"&&r.length>0&&i.length>u)throw new Error("Resize requires only of scales or sizes to be specified")},jo=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,\n lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`return ${t}(xResized) / ${t}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) {\n return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;\n } else {\n return 0.0;\n }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) {\n return 0.0;\n } else {\n // The whole part and the fractional part are calculated separately due to inaccuracy of floating\n // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an\n // offset-by-one error later in floor().\n let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1));\n let fract =\n ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1);\n return whole + fract;\n }`;case"tf_crop_and_resize":return`if (lengthResized > 1) {\n return ${t}(roiStart) * ${t}(lengthOriginal - 1) +\n (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /\n ${t}(lengthResized - 1);\n } else {\n return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);\n }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized);\n const adjustment = ${t}(lengthResized) / outputWidth;\n const center = ${t}(lengthOriginal) / 2;\n const offset = center * (1 - adjustment);\n return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",qo=(e,t,n)=>`fn getNearestPixelFromOriginal(xOriginal: ${n}, isDownSample: bool) -> ${n} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",Go=(e,t,n)=>{let r=new Array(n).fill(0).concat(new Array(n).fill(1)),i=0===e.length?r:e.slice();return t.length>0?(t.forEach(((e,a)=>{r[e]=i[a],r[a+n]=i[t.length+a]})),r):i},Uo=(e,t,n,r)=>{let i=[];if(n.length>0)if(r.length>0){if(e.forEach((e=>i.push(e))),Math.max(...r)>e.length)throw new Error("axes is out of bound");r.forEach(((e,t)=>i[e]=n[t]))}else n.forEach((e=>i.push(e)));else{if(0===t.length)throw new Error("Resize requires either scales or sizes.");i=e.map(((e,n)=>Math.round(e*t[n])))}return i},Wo=(e,t,n)=>{let r=(()=>{switch(n.keepAspectRatioPolicy){case"not_larger":return n.axes.length>0?Math.min(...n.axes.map((e=>t[e])),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return n.axes.length>0?Math.max(...n.axes.map((e=>t[e])),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${n.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let i=e.slice();return n.axes.length>0?(n.axes.forEach((e=>t[e]=r)),n.axes.forEach((n=>i[n]=Math.round(e[n]*t[n])))):(t.fill(r,0,t.length),i.forEach(((e,n)=>i[n]=Math.round(e*t[n])))),i},Ho=(e,t,n,r,i)=>`\n fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${n.length}> {\n var original_indices: array<${e.type.value}, ${n.length}>;\n for (var i:u32 = 0; i < ${n.length}; i++) {\n var output_index = ${e.indicesGet("output_indices","i")};\n var scale = ${Nt("uniforms.scales","i",r)};\n var roi_low = ${Nt("uniforms.roi","i",i)};\n var roi_hi = ${Nt("uniforms.roi",`i + ${t.length}`,i)};\n if (scale == 1.0) {\n original_indices[i] = ${e.type.value}(output_index);\n } else {\n var input_shape_i = ${Nt("uniforms.input_shape","i",t.length)};\n var output_shape_i = ${Nt("uniforms.output_shape","i",n.length)};\n original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n }\n }\n return original_indices;\n }`,Ko=(e,t,n,r,i,a,s)=>`\n fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n for (var i:u32 = 0; i < ${r.length}; i++) {\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index: u32;\n var scale = ${Nt("uniforms.scales","i",i)};\n if (scale == 1.0) {\n input_index = output_index;\n } else {\n var roi_low = ${Nt("uniforms.roi","i",a)};\n var roi_hi = ${Nt("uniforms.roi",`i + ${n.length}`,a)};\n var input_shape_i = ${Nt("uniforms.input_shape","i",n.length)};\n var output_shape_i = ${Nt("uniforms.output_shape","i",r.length)};\n var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n if (!${s} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {\n if (original_idx < 0) {\n input_index = 0;\n } else if (original_idx > ${t.type.value}(input_shape_i - 1)) {\n input_index = input_shape_i - 1;\n } else {\n input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));\n }\n } else {\n input_index = u32(original_idx);\n }\n }\n ${e.indicesSet("input_indices","i"," input_index")}\n }\n return input_indices;\n }`,Xo=(e,t)=>`\n fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {\n for (var i:u32 = 0; i < ${t.length}; i++) {\n var input_index = ${e.indicesGet("input_indices","i")};\n if (input_index < 0 || input_index >= ${Nt("uniforms.input_shape","i",t.length)}) {\n return false;\n }\n }\n return true;\n }`,Qo=(e,t,n,r)=>e.rank>r?`\n ${e.indicesSet("input_indices",t,"channel")};\n ${e.indicesSet("input_indices",n,"batch")};\n`:"",Yo=(e,t,n,r,i)=>{let[a,s,o,l]=2===n.length?[-1,0,1,-1]:[0,2,3,1],u=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${u} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",s,`max(0, min(row, ${n[s]} - 1))`)};\n ${e.indicesSet("input_indices",o,`max(0, min(col, ${n[o]} - 1))`)};\n ${Qo(e,l,a,2)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${u} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var row:${u} = originalIndices[${s}];\n var col:${u} = originalIndices[${o}];\n ${r?`if (row < 0 || row > (${n[s]} - 1) || col < 0 || col > (${n[o]} - 1)) {\n return ${i};\n }`:""};\n row = max(0, min(row, ${n[s]} - 1));\n col = max(0, min(col, ${n[o]} - 1));\n var row1: u32 = u32(row);\n var col1: u32 = u32(col);\n var row2: u32 = u32(row + 1);\n var col2: u32 = u32(col + 1);\n var channel: u32 = ${n.length>2?`u32(originalIndices[${l}])`:"0"};\n var batch: u32 = ${n.length>2?`u32(originalIndices[${a}])`:"0"};\n var x11: ${u} = getInputValue(batch, channel, row1, col1);\n var x12: ${u} = getInputValue(batch, channel, row1, col2);\n var x21: ${u} = getInputValue(batch, channel, row2, col1);\n var x22: ${u} = getInputValue(batch, channel, row2, col2);\n var dx1: ${u} = abs(row - ${u}(row1));\n var dx2: ${u} = abs(${u}(row2) - row);\n var dy1: ${u} = abs(col - ${u}(col1));\n var dy2: ${u} = abs(${u}(col2) - col);\n if (row1 == row2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (col1 == col2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);\n }`},Zo=(e,t,n,r,i,a,s,o,l,u)=>{let d=2===n.length,[c,p]=d?[0,1]:[2,3],h=e.type.value,m=s=>{let d=s===c?"row":"col";return`\n fn ${d}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${h} {\n var output_index = ${t.indicesGet("output_indices",s)};\n var originalIdx: ${h} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[s]},\n ${r[s]}, ${n[s]}, ${a[s]}, ${a[s]} + ${n.length});\n var fractOriginalIdx: ${h} = originalIdx - floor(originalIdx);\n var coefs = getCubicInterpolationCoefs(fractOriginalIdx);\n\n if (${o} && (originalIdx < 0 || originalIdx > (${n[s]} - 1))) {\n return ${l};\n }\n var data: array<${h}, 4> = array<${h}, 4>(0.0, 0.0, 0.0, 0.0);\n for (var i: i32 = -1; i < 3; i++) {\n var ${d}: ${h} = originalIdx + ${h}(i);\n if (${d} < 0 || ${d} >= ${n[s]}) {\n ${u?"coefs[i + 1] = 0.0;\n continue;":o?`return ${l};`:`${d} = max(0, min(${d}, ${n[s]} - 1));`};\n }\n var input_indices_copy: ${e.type.indices} = input_indices;\n ${e.indicesSet("input_indices_copy",s,`u32(${d})`)};\n data[i + 1] = ${s===c?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};\n }\n return cubicInterpolation1D(data, coefs);\n }`};return`\n ${m(c)};\n ${m(p)};\n fn getCubicInterpolationCoefs(s: ${h}) -> array<${h}, 4> {\n var absS = abs(s);\n var coeffs: array<${h}, 4> = array<${h}, 4>(0.0, 0.0, 0.0, 0.0);\n var oneMinusAbsS: ${h} = 1.0 - absS;\n var twoMinusAbsS: ${h} = 2.0 - absS;\n var onePlusAbsS: ${h} = 1.0 + absS;\n coeffs[0] = ((${s} * onePlusAbsS - 5 * ${s}) * onePlusAbsS + 8 * ${s}) * onePlusAbsS - 4 * ${s};\n coeffs[1] = ((${s} + 2) * absS - (${s} + 3)) * absS * absS + 1;\n coeffs[2] = ((${s} + 2) * oneMinusAbsS - (${s} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;\n coeffs[3] = ((${s} * twoMinusAbsS - 5 * ${s}) * twoMinusAbsS + 8 * ${s}) * twoMinusAbsS - 4 * ${s};\n return coeffs;\n }\n\n fn cubicInterpolation1D(x: array<${h}, 4>, coefs: array<${h}, 4>) -> ${h} {\n var coefsSum: ${h} = coefs[0] + coefs[1] + coefs[2] + coefs[3];\n return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;\n }\n\n fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${h} {\n var input_indices: ${e.type.indices} = output_indices;\n return colCubicInterpolation(input_indices, output_indices);\n }\n `},Jo=(e,t,n,r,i)=>{let[a,s,o,l,u]=3===n.length?[-1,0,1,2,-1]:[0,2,3,4,1],d=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${d} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",s,`max(0, min(depth, ${n[s]} - 1))`)};\n ${e.indicesSet("input_indices",o,`max(0, min(height, ${n[o]} - 1))`)};\n ${e.indicesSet("input_indices",l,`max(0, min(width, ${n[l]} - 1))`)};\n ${Qo(e,u,a,3)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${d} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var depth:${d} = originalIndices[${s}];\n var height:${d} = originalIndices[${o}];\n var width:${d} = originalIndices[${l}];\n ${r?`if (depth < 0 || depth > (${n[s]} - 1) || height < 0 || height > (${n[o]} - 1) || width < 0 || (width > ${n[l]} - 1)) {\n return ${i};\n }`:""};\n\n depth = max(0, min(depth, ${n[s]} - 1));\n height = max(0, min(height, ${n[o]} - 1));\n width = max(0, min(width, ${n[l]} - 1));\n var depth1: u32 = u32(depth);\n var height1: u32 = u32(height);\n var width1: u32 = u32(width);\n var depth2: u32 = u32(depth + 1);\n var height2: u32 = u32(height + 1);\n var width2: u32 = u32(width + 1);\n var channel: u32 = ${n.length>3?`u32(originalIndices[${u}])`:"0"};\n var batch: u32 = ${n.length>3?`u32(originalIndices[${a}])`:"0"};\n\n var x111: ${d} = getInputValue(batch, channel, depth1, height1, width1);\n var x112: ${d} = getInputValue(batch, channel, depth1, height1, width2);\n var x121: ${d} = getInputValue(batch, channel, depth1, height2, width1);\n var x122: ${d} = getInputValue(batch, channel, depth1, height2, width2);\n var x211: ${d} = getInputValue(batch, channel, depth2, height1, width1);\n var x212: ${d} = getInputValue(batch, channel, depth2, height1, width2);\n var x221: ${d} = getInputValue(batch, channel, depth2, height2, width1);\n var x222: ${d} = getInputValue(batch, channel, depth2, height2, width2);\n var dx1: ${d} = abs(depth - ${d}(depth1));\n var dx2: ${d} = abs(${d}(depth2) - depth);\n var dy1: ${d} = abs(height - ${d}(height1));\n var dy2: ${d} = abs(${d}(height2) - height);\n var dz1: ${d} = abs(width - ${d}(width1));\n var dz2: ${d} = abs(${d}(width2) - width);\n if (depth1 == depth2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (height1 == height2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n if (width1 == width2) {\n dz1 = 0.5;\n dz2 = 0.5;\n }\n return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +\n x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);\n }`},el=(e,t,n,r,i,a)=>{let s=e.dims,o=Go(a,t.axes,s.length),l=Uo(s,r,i,t.axes),u=r.slice();0===r.length&&(u=s.map(((e,t)=>0===e?1:l[t]/e)),"stretch"!==t.keepAspectRatioPolicy&&(l=Wo(s,u,t)));let d=Vt("output",e.dataType,l.length),c=Rt("input",e.dataType,s.length),p=Tt.size(l),h=s.length===l.length&&s.every(((e,t)=>e===l[t])),m="tf_crop_and_resize"===t.coordinateTransformMode,f=t.extrapolationValue,g=c.type.value;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${n}|${u.length>0?u:""}|${i.length>0?i:""}|${o.length>0?o:""}|${h}|${s}`,inputDependencies:["rank"]},getShaderSource:e=>`\n ${h?"":`\n ${jo(t.coordinateTransformMode,g)};\n ${(()=>{switch(t.mode){case"nearest":return`\n ${Xo(c,s)};\n ${qo(t.nearestMode,n,g)};\n ${Ko(c,d,s,l,u.length,o.length,m)};\n `;case"linear":return`\n ${Ho(d,s,l,u.length,o.length)};\n ${(()=>{if(2===s.length||4===s.length)return`${Yo(c,d,s,m,f)}`;if(3===s.length||5===s.length)return`${Jo(c,d,s,m,f)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};\n `;case"cubic":return`\n ${(()=>{if(2===s.length||4===s.length)return`${Zo(c,d,s,l,u,o,t.cubicCoeffA,m,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()};\n `;default:throw Error("Invalid resize mode")}})()};\n `}\n ${e.registerUniform("output_size","u32").registerUniform("scales","f32",u.length).registerUniform("roi","f32",o.length).declareVariables(c,d)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n ${h?"output[global_idx] = input[global_idx];":`\n let output_indices = ${d.offsetToIndices("global_idx")};\n var input_indices: ${c.type.indices};\n ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);\n if (checkInputIndices(input_indices)) {\n output[global_idx] = ${c.getByIndices("input_indices")};\n } else {\n output[global_idx] = ${t.extrapolationValue};\n }`;case"linear":return`output[global_idx] = ${2===s.length||4===s.length?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};\n`}\n }`,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},{type:1,data:u},{type:1,data:o},...It(s,l)]})}},tl=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},nl=(e,t)=>{let n=[],r=[],i=[],a=tl(e);if(0!==t.antialias)throw Error("Only default value (0) for Antialias attribute is supported");Vo(e.inputs,t,a,n,r,i),e.compute(el(e.inputs[0],t,a,n,r,i),{inputs:[0]})},rl=e=>{let t=e.antialias,n=e.axes,r=e.coordinateTransformMode,i=e.cubicCoeffA,a=0!==e.excludeOutside,s=e.extrapolationValue,o=e.keepAspectRatioPolicy,l=e.mode,u=""===e.nearestMode?"simple":e.nearestMode;return xt({antialias:t,axes:n,coordinateTransformMode:r,cubicCoeffA:i,excludeOutside:a,extrapolationValue:s,keepAspectRatioPolicy:o,mode:l,nearestMode:u})}})),ed=j((()=>{eu(),ou(),su(),lu(),il=(e,t)=>{let[n,r,i,a]=e,{numHeads:s,rotaryEmbeddingDim:o}=t;if(3!==n.dims.length&&4!==n.dims.length)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${n.dims.length}`);if(!Tt.areEqual(r.dims,[])&&!Tt.areEqual(r.dims,[1])&&2!==r.dims.length)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${r.dims.length}`);if(2!==i.dims.length)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(2!==a.dims.length)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!Tt.areEqual(i.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(o>0&&0===s)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=n.dims[0],u=n.dims[n.dims.length-2],d=i.dims[0],c=Tt.sizeFromDimension(n.dims,1)/u,p=0===o?2*i.dims[1]:c/s;if(o>p)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(2===r.dims.length){if(l!==r.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${r.dims[0]}`);if(u!==r.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${r.dims[1]}`)}if(p/2!==i.dims[1]&&o/2!==i.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(u>d)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},al=(e,t)=>{let{interleaved:n,numHeads:r,rotaryEmbeddingDim:i,scale:a}=t,s=e[0].dims[0],o=Tt.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],u=o/l,d=e[2].dims[1],c=0===i?2*d:u/r,p=new Array(s,l,u/c,c-d),h=Tt.computeStrides(p),m=[{type:1,data:a},{type:12,data:p},{type:12,data:h},...3===e[0].dims.length?new Array({type:12,data:[o,u,c,1]}):[],...4===e[0].dims.length?new Array({type:12,data:[o,c,l*c,1]}):[],...It(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)];return{name:"RotaryEmbedding",shaderCache:{hint:xt({interleaved:n}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:t=>{let r=Rt("input",e[0].dataType,e[0].dims.length),i=Rt("position_ids",e[1].dataType,e[1].dims.length),a=Rt("cos_cache",e[2].dataType,e[2].dims.length),s=Rt("sin_cache",e[3].dataType,e[3].dims.length),o=Vt("output",e[0].dataType,e[0].dims.length);return t.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:p.length},{name:"global_strides",type:"u32",length:h.length},{name:"input_output_strides",type:"u32",length:h.length}]),`\n ${t.declareVariables(r,i,a,s,o)}\n\n ${t.mainStart(Et)}\n let half_rotary_emb_dim = uniforms.${a.name}_shape[1];\n let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;\n let size = uniforms.global_shape[0] * uniforms.global_strides[0];\n ${t.guardAgainstOutOfBoundsWorkgroupSizes("size")}\n\n if (bsnh[3] < half_rotary_emb_dim) {\n let position_ids_idx =\n ${i.broadcastedIndicesToOffset("bsnh.xy",Vt("",i.type.tensor,2))};\n let position_id =\n u32(${i.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0);\n let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${n});\n let j = i + select(half_rotary_emb_dim, 1, ${n});\n let re = ${r.getByOffset("i")} * ${a.get("position_id","bsnh[3]")} -\n ${r.getByOffset("j")} * ${s.get("position_id","bsnh[3]")};\n ${o.setByOffset("i","re")}\n let im = ${r.getByOffset("i")} * ${s.get("position_id","bsnh[3]")} +\n ${r.getByOffset("j")} * ${a.get("position_id","bsnh[3]")};\n ${o.setByOffset("j","im")}\n } else {\n let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;\n ${o.setByOffset("k",r.getByOffset("k"))}\n }\n }`},getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Tt.size(p)/Et)},programUniforms:m})}},sl=(e,t)=>{il(e.inputs,t),e.compute(al(e.inputs,t))}})),td=j((()=>{eu(),ou(),lu(),ol=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],n=e[1],r=e[2];if(t.dataType!==n.dataType||t.dataType!==r.dataType)throw new Error("All inputs must have the same data type");if(3!==t.dims.length&&2!==t.dims.length)throw new Error("Input must be 2D or 3D");if(3!==n.dims.length&&2!==n.dims.length)throw new Error("Skip must be 2D or 3D");let i=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(n.dims[n.dims.length-1]!==i)throw new Error("Skip must have the same hidden size as input");if(n.dims[n.dims.length-2]!==a)throw new Error("Skip must have the same sequence length as input");if(1!==r.dims.length)throw new Error("Gamma must be 1D");if(r.dims[r.dims.length-1]!==i)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let t=e[3];if(1!==t.dims.length)throw new Error("Beta must be 1D");if(t.dims[t.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let t=e[4];if(1!==t.dims.length)throw new Error("Bias must be 1D");if(t.dims[t.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},ll=(e,t,n,r)=>{let i=t.simplified,a=e[0].dims,s=Tt.size(a),o=a,l=s,u=a.slice(-1)[0],d=r?a.slice(0,-1).concat(1):[],c=!i&&e.length>3,p=e.length>4,h=r&&n>1,m=r&&n>2,f=n>3,g=64,_=zt(u),w=[{type:12,data:l},{type:12,data:_},{type:12,data:u},{type:1,data:t.epsilon}],b=[{dims:o,dataType:e[0].dataType}];return n>1&&b.push({dims:d,dataType:1}),n>2&&b.push({dims:d,dataType:1}),n>3&&b.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${_};${h};${m};${f}`,inputDependencies:e.map(((e,t)=>"type"))},getShaderSource:t=>{let n=[Rt("x",e[0].dataType,e[0].dims,_),Rt("skip",e[1].dataType,e[1].dims,_),Rt("gamma",e[2].dataType,e[2].dims,_)];c&&n.push(Rt("beta",e[3].dataType,e[3].dims,_)),p&&n.push(Rt("bias",e[4].dataType,e[4].dims,_)),n.push(Vt("output",e[0].dataType,o,_)),h&&n.push(Vt("mean_output",1,d)),m&&n.push(Vt("inv_std_output",1,d)),f&&n.push(Vt("input_skip_bias_sum",e[0].dataType,o,_));let r=Ft(e[0].dataType),a=Ft(1,_);return`\n\n ${t.registerUniforms([{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}]).declareVariables(...n)}\n var sum_shared : array<${a}, 64>;\n var sum_squared_shared : array<${a}, 64>;\n\n ${t.mainStart([g,1,1])}\n let ix = local_id.x;\n let iy = global_id.x / 64;\n\n let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;\n var stride = hidden_size_vectorized / 64;\n let offset = ix * stride + iy * hidden_size_vectorized;\n let offset1d = stride * ix;\n if (ix == 63) {\n stride = hidden_size_vectorized - stride * ix;\n }\n for (var i: u32 = 0; i < stride; i++) {\n let skip_value = skip[offset + i];\n let bias_value = ${p?"bias[offset1d + i]":r+"(0.0)"};\n let input_value = x[offset + i];\n let value = input_value + skip_value + bias_value;\n ${f?"input_skip_bias_sum[offset + i] = value;":""}\n output[offset + i] = value;\n let f32_value = ${Bt(r,_,"value")};\n sum_shared[ix] += f32_value;\n sum_squared_shared[ix] += f32_value * f32_value;\n }\n workgroupBarrier();\n\n var reduce_size : u32 = 64;\n for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) {\n reduce_size = curr_size + (reduce_size & 1);\n if (ix < curr_size) {\n sum_shared[ix] += sum_shared[ix + reduce_size];\n sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size];\n }\n workgroupBarrier();\n }\n\n let sum = sum_shared[0];\n let square_sum = sum_squared_shared[0];\n let mean = ${Lt("sum",_)} / f32(uniforms.hidden_size);\n let inv_std_dev = inverseSqrt(${Lt("square_sum",_)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon);\n ${h?"mean_output[global_idx] = mean;":""}\n ${m?"inv_std_output[global_idx] = inv_std_dev;":""}\n\n for (var i: u32 = 0; i < stride; i++) {\n output[offset + i] = (output[offset + i] ${i?"":`- ${r}(mean)`}) *\n ${r}(inv_std_dev) * gamma[offset1d + i]\n ${c?"+ beta[offset1d + i]":""};\n }\n }`},getRunData:()=>({outputs:b,dispatchGroup:{x:Math.ceil(l/u)},programUniforms:w})}},ul=(e,t)=>{ol(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(ll(e.inputs,t,e.outputCount,!1),{outputs:n})}})),nd=j((()=>{eu(),ou(),su(),lu(),dl=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(0!==t.axes.length){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach(((t,n)=>{if(6!==e[n+1].dataType&&7!==e[n+1].dataType)throw new Error(`Input ${n} must be an array of int32 or int64`)}))},cl=(e,t)=>{let n=[];if(e.length>t)if(7===e[t].dataType)e[t].getBigInt64Array().forEach((e=>n.push(Number(e))));else{if(6!==e[t].dataType)throw new Error(`Input ${t} must be an array of int32 or int64`);e[t].getInt32Array().forEach((e=>n.push(Number(e))))}return n},pl=(e,t)=>{if(e.length>1){let t=cl(e,1),n=cl(e,2),r=cl(e,3);return 0===r.length&&(r=[...Array(e[0].dims.length).keys()]),xt({starts:t,ends:n,axes:r})}return t},hl=(e,t,n,r,i)=>{let a=e;return e<0&&(a+=n[r[t]]),i[t]<0?Math.max(0,Math.min(a,n[r[t]]-1)):Math.max(0,Math.min(a,n[r[t]]))},ml=(e,t,n)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n var carry = 0u;\n for (var i = ${n.length}; i >= 0; i--) {\n let input_shape_i = ${Nt("uniforms.input_shape","i",n.length)};\n let steps_i = ${Nt("uniforms.steps","i",n.length)};\n let signs_i = ${Nt("uniforms.signs","i",n.length)};\n let starts_i = ${Nt("uniforms.starts","i",n.length)};\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index = output_index * steps_i + starts_i + carry;\n carry = input_index / input_shape_i;\n input_index = input_index % input_shape_i;\n if (signs_i < 0) {\n input_index = input_shape_i - input_index - 1u + starts_i;\n }\n ${e.indicesSet("input_indices","i","input_index")};\n }\n return input_indices;\n }`,fl=(e,t)=>{let n=e[0].dims,r=Tt.size(n),i=t.axes.length>0?Tt.normalizeAxes(t.axes,n.length):[...Array(n.length).keys()],a=cl(e,4);a.forEach((e=>0!==e||(()=>{throw new Error("step cannot be 0")}))),0===a.length&&(a=Array(i.length).fill(1));let s=t.starts.map(((e,t)=>hl(e,t,n,i,a))),o=t.ends.map(((e,t)=>hl(e,t,n,i,a)));if(i.length!==s.length||i.length!==o.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==n.length)for(let e=0;eMath.sign(e)));a.forEach(((e,t,n)=>{if(e<0){let r=(o[t]-s[t])/e,i=s[t],l=i+r*a[t];s[t]=l,o[t]=i,n[t]=-e}}));let u=n.slice(0);i.forEach(((e,t)=>{u[e]=Math.ceil((o[e]-s[e])/a[e])}));let d={dims:u,dataType:e[0].dataType},c=Vt("output",e[0].dataType,u.length),p=Rt("input",e[0].dataType,e[0].dims.length),h=Tt.size(u),m=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:s.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:a.length}],f=[{type:12,data:h},{type:12,data:s},{type:6,data:l},{type:12,data:a},...It(e[0].dims,u)];return{name:"Slice",shaderCache:{hint:`${l.length}_${s.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:e=>`\n ${e.registerUniforms(m).declareVariables(p,c)}\n ${ml(p,c,n)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let output_indices = ${c.offsetToIndices("global_idx")};\n let input_indices = calculateInputIndices(output_indices);\n ${c.setByOffset("global_idx",p.getByIndices("input_indices"))}\n }`,getRunData:()=>({outputs:[d],dispatchGroup:{x:Math.ceil(r/64)},programUniforms:f})}},gl=(e,t)=>{dl(e.inputs,t);let n=pl(e.inputs,t);e.compute(fl(e.inputs,n),{inputs:[0]})},_l=e=>{let t=e.starts,n=e.ends,r=e.axes;return xt({starts:t,ends:n,axes:r})}})),rd=j((()=>{eu(),ou(),su(),uu(),lu(),wl=e=>{if(!e||1!==e.length)throw new Error("Softmax op requires 1 input.")},bl=(e,t)=>{let n,r=e.inputs[0],i=r.dims,a=Tt.size(i),s=i.length,o=Tt.normalizeAxis(t.axis,s),l=ot)),u[o]=s-1,u[s-1]=o,n=e.compute(Zt(r,u),{inputs:[r],outputs:[-1]})[0]):n=r;let d=n.dims,c=d[s-1],p=a/c,h=zt(c),m=c/h,f=64;1===p&&(f=256);let g=Rt("x",n.dataType,n.dims,h),_=Vt("result",n.dataType,n.dims,h),w=g.type.value,b="f32"===Ft(n.dataType)?`var threadMax = ${w}(-3.402823e+38f);`:`var threadMax = ${w}(-65504.0h);`,y=e.compute({name:"Softmax",shaderCache:{hint:`${h};${f}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:d,dataType:n.dataType}],dispatchGroup:{x:p},programUniforms:[{type:6,data:m}]}),getShaderSource:e=>`\n var rowMaxShared : ${w};\n var rowSumShared : ${w};\n var threadShared : array<${w}, ${f}>;\n\n fn getValue(row: i32, col: i32, row_stride: i32) -> ${w} {\n let index = row * row_stride + col;\n return x[index];\n }\n\n fn setValue(row: i32, col: i32, row_stride: i32, value: ${w}) {\n let index = row * row_stride + col;\n result[index] = value;\n }\n ${e.registerUniform("packedCols","i32").declareVariables(g,_)}\n ${e.mainStart(f)}\n let gindex = i32(global_idx);\n let lindex = i32(local_idx);\n const wg = ${f};\n let row = gindex / wg;\n let cols = uniforms.packedCols;\n let row_stride : i32 = uniforms.packedCols;\n\n // find the rows max\n ${b}\n for (var col = lindex; col < cols; col += wg) {\n let value = getValue(row, col, row_stride);\n threadMax = max(threadMax, value);\n }\n if (lindex < cols) {\n threadShared[lindex] = threadMax;\n }\n workgroupBarrier();\n\n var reduceSize = min(cols, wg);\n for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {\n reduceSize = currSize + (reduceSize & 1);\n if (lindex < currSize) {\n threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowMaxShared = ${w}(${((e,t)=>4===t?`max(max(${e}.x, ${e}.y), max(${e}.z, ${e}.w))`:2===t?`max(${e}.x, ${e}.y)`:3===t?`max(max(${e}.x, ${e}.y), ${e}.z)`:e)("threadShared[0]",h)});\n }\n workgroupBarrier();\n\n // find the rows sum\n var threadSum = ${w}(0.0);\n for (var col = lindex; col < cols; col += wg) {\n let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);\n threadSum += subExp;\n }\n threadShared[lindex] = threadSum;\n workgroupBarrier();\n\n for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {\n if (lindex < currSize) {\n threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowSumShared = ${w}(${Lt("threadShared[0]",h)});\n }\n workgroupBarrier();\n\n // calculate final value for each element in the row\n for (var col = lindex; col < cols; col += wg) {\n let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;\n setValue(row, col, row_stride, value);\n }\n }`},{inputs:[n],outputs:[l?-1:0]})[0];l&&e.compute(Zt(y,u),{inputs:[y]})},yl=(e,t)=>{wl(e.inputs),bl(e,t)},xl=e=>xt({axis:e.axis})})),id=j((()=>{eu(),ou(),lu(),vl=e=>Array.from(e.getBigInt64Array(),Number),Ml=e=>{if(!e||2!==e.length)throw new Error("Tile requires 2 inputs.");if(1!==e[0].dataType&&10!==e[0].dataType&&6!==e[0].dataType&&12!==e[0].dataType)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(7!==e[1].dataType)throw new Error("Tile `repeats` input should be of int64 data type");if(1!==e[1].dims.length)throw new Error("Tile `repeats` input should be 1-D");if(vl(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Tl=(e,t)=>{let n=[];for(let r=0;r{let n=e[0].dims,r=t??vl(e[1]),i=Tl(n,r),a=Tt.size(i),s=e[0].dataType,o=Rt("input",s,n.length),l=Vt("output",s,i.length);return{name:"Tile",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...It(e[0].dims,i)]}),getShaderSource:e=>`\n const inputShape = ${o.indices(...n)};\n ${e.registerUniform("output_size","u32").declareVariables(o,l)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let output_indices = ${l.offsetToIndices("global_idx")};\n var input_indices: ${o.type.indices};\n for (var i = 0; i < ${n.length}; i++) {\n let input_dim_i = ${o.indicesGet("uniforms.input_shape","i")};\n let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i;\n\n ${o.indicesSet("input_indices","i","input_dim_value")}\n }\n ${l.setByOffset("global_idx",o.getByIndices("input_indices"))}\n }`}},$l=e=>{Ml(e.inputs),e.compute(kl(e.inputs),{inputs:[0]})}})),ad=j((()=>{eu(),ou(),lu(),Sl=(e,t,n,r,i)=>{let a,s=Vt("output_data",i,n.length,4),o=Rt("a_data",t[1].dataType,t[1].dims.length,4),l=Rt("b_data",t[2].dataType,t[2].dims.length,4),u=Rt("c_data",t[0].dataType,t[0].dims.length,4),d=(e,t,n)=>`select(${t}, ${e}, ${n})`;if(r){let e=(e,t,n="")=>{let r=`a_data[index_a${t}][component_a${t}]`,i=`b_data[index_b${t}][component_b${t}]`,a=`bool(c_data[index_c${t}] & (0xffu << (component_c${t} * 8)))`;return`\n let output_indices${t} = ${s.offsetToIndices(`global_idx * 4u + ${t}u`)};\n let offset_a${t} = ${o.broadcastedIndicesToOffset(`output_indices${t}`,s)};\n let offset_b${t} = ${l.broadcastedIndicesToOffset(`output_indices${t}`,s)};\n let offset_c${t} = ${u.broadcastedIndicesToOffset(`output_indices${t}`,s)};\n let index_a${t} = offset_a${t} / 4u;\n let index_b${t} = offset_b${t} / 4u;\n let index_c${t} = offset_c${t} / 4u;\n let component_a${t} = offset_a${t} % 4u;\n let component_b${t} = offset_b${t} % 4u;\n let component_c${t} = offset_c${t} % 4u;\n ${e}[${t}] = ${n}(${d(r,i,a)});\n `};a=9===i?`\n var data = vec4(0);\n ${e("data",0,"u32")}\n ${e("data",1,"u32")}\n ${e("data",2,"u32")}\n ${e("data",3,"u32")}\n output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:`\n ${e("output_data[global_idx]",0)}\n ${e("output_data[global_idx]",1)}\n ${e("output_data[global_idx]",2)}\n ${e("output_data[global_idx]",3)}\n `}else a=s.setByOffset("global_idx",d(o.getByOffset("global_idx"),l.getByOffset("global_idx"),u.getByOffset("global_idx")));return`\n ${e.registerUniform("vec_size","u32").declareVariables(u,o,l,s)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${a}\n }`},Cl=e=>{let t=e[1].dims,n=e[2].dims,r=e[0].dims,i=e[1].dataType,a=!(Tt.areEqual(t,n)&&Tt.areEqual(n,r)),s=t,o=Tt.size(t);if(a){let e=Mt.calcShape(Mt.calcShape(t,n,!1),r,!1);if(!e)throw new Error("Can't perform where op on the given tensors");s=e,o=Tt.size(s)}let l=Math.ceil(o/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:t=>Sl(t,e,s,a,i),getRunData:()=>({outputs:[{dims:s,dataType:i}],dispatchGroup:{x:Math.ceil(o/64/4)},programUniforms:[{type:12,data:l},...It(r,t,n,s)]})}},El=e=>{e.compute(Cl(e.inputs))}})),sd=j((()=>{pu(),hu(),mu(),fu(),_u(),wu(),bu(),Cu(),Pu(),Fu(),Au(),Iu(),zu(),Ou(),Bu(),Lu(),Nu(),Du(),Ru(),qu(),Gu(),Uu(),Wu(),Hu(),Vu(),Ku(),Xu(),Qu(),Yu(),Zu(),cu(),Ju(),ed(),td(),nd(),rd(),ju(),id(),uu(),gu(),ad(),Pl=new Map([["Abs",[gr]],["Acos",[_r]],["Acosh",[wr]],["Add",[ci]],["ArgMax",[Yn,Zn]],["ArgMin",[Qn,Zn]],["Asin",[br]],["Asinh",[yr]],["Atan",[xr]],["Atanh",[vr]],["Attention",[sr]],["AveragePool",[bo,wo]],["BatchNormalization",[dr]],["BiasAdd",[hr]],["BiasSplitGelu",[oi]],["Cast",[Tr,Mr]],["Ceil",[Sr]],["Clip",[$r]],["Concat",[ki,$i]],["Conv",[da,sa]],["ConvTranspose",[ya,ga]],["Cos",[Cr]],["Cosh",[Er]],["CumSum",[va,Ma]],["DepthToSpace",[Sa,Ca]],["DequantizeLinear",[Po,Fo]],["Div",[pi]],["Einsum",[La,Na]],["Elu",[Fr,Pr]],["Equal",[hi]],["Erf",[Ir]],["Exp",[zr]],["Expand",[qa]],["FastGelu",[Ua]],["Floor",[Or]],["FusedConv",[da,sa]],["Gather",[Xa,Ka]],["GatherElements",[rs,ns]],["GatherBlockQuantized",[Za,Ja]],["Gelu",[Br]],["Gemm",[os,ss]],["GlobalAveragePool",[vo,xo]],["GlobalMaxPool",[So,$o]],["Greater",[_i]],["GreaterOrEqual",[bi]],["GridSample",[bs,ys]],["GroupQueryAttention",[Ns]],["HardSigmoid",[Gr,qr]],["InstanceNormalization",[js]],["LayerNormalization",[Us]],["LeakyRelu",[Lr,Pr]],["Less",[wi]],["LessOrEqual",[yi]],["Log",[ti]],["MatMul",[Hs]],["MatMulNBits",[Ys,Zs]],["MaxPool",[To,ko]],["Mul",[mi]],["MultiHeadAttention",[Ss,Ms]],["Neg",[Dr]],["Not",[Nr]],["Pad",[oo]],["Pow",[fi]],["QuickGelu",[ii,Pr]],["Range",[zo]],["Reciprocal",[Rr]],["ReduceMin",[Gn]],["ReduceMean",[Dn]],["ReduceMax",[qn]],["ReduceSum",[Wn]],["ReduceProd",[Un]],["ReduceL1",[Rn]],["ReduceL2",[Vn]],["ReduceLogSum",[Kn]],["ReduceLogSumExp",[jn]],["ReduceSumSquare",[Hn]],["Relu",[Vr]],["Resize",[nl,rl]],["RotaryEmbedding",[sl]],["ScatterND",[No,Lo]],["Sigmoid",[jr]],["Sin",[Ur]],["Sinh",[Wr]],["Slice",[gl,_l]],["SkipLayerNormalization",[ul]],["Split",[Is,zs]],["Sqrt",[Hr]],["Softmax",[yl,xl]],["Sub",[gi]],["Tan",[Kr]],["Tanh",[Qr]],["ThresholdedRelu",[ei,Pr]],["Tile",[$l]],["Transpose",[Jt,en]],["Where",[El]]])})),od=j((()=>{pe(),nu(),lu(),Fl=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n,r,i){F(e.programInfo.name);let a=this.backend.device,s=this.backend.getComputePassEncoder();this.backend.writeTimestamp(2*this.backend.pendingDispatchNumber);let o=[];for(let e of t)o.push({binding:o.length,resource:{buffer:e.buffer}});for(let e of n)o.push({binding:o.length,resource:{buffer:e.buffer}});i&&o.push({binding:o.length,resource:i});let l=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:o,label:e.programInfo.name});if("capturing"===this.backend.sessionStatus){let t={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:r};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(t)}s.setPipeline(e.computePipeline),s.setBindGroup(0,l),s.dispatchWorkgroups(...r),this.backend.writeTimestamp(2*this.backend.pendingDispatchNumber+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||"at-passes"===this.backend.queryType)&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),A(e.programInfo.name)}dispose(){}build(e,t){F(e.name);let n=this.backend.device,r=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"},{feature:"subgroups-f16",extension:"subgroups_f16"}].forEach((e=>{n.features.has(e.feature)&&r.push(`enable ${e.extension};`)}));let i=Ut(t,this.backend.device.limits),a=e.getShaderSource(i),s=`${r.join("\n")}\n${i.additionalImplementations}\n${a}`,o=n.createShaderModule({code:s,label:e.name});ut("verbose",(()=>`[WebGPU] ${e.name} shader code: ${s}`));let l=n.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:e.name});return A(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(e){let t="number"==typeof e?e:e.x,n="number"==typeof e?1:e.y||1,r="number"==typeof e?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&n<=i&&r<=i)return[t,n,r];let a=t*n*r,s=Math.ceil(Math.sqrt(a));if(s>i){if(s=Math.ceil(Math.cbrt(a)),s>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[s,s,s]}return[s,s,1]}}})),ld=j((()=>{pe(),eu(),nu(),ru(),au(),sd(),od(),Al=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let r=0;r{let r=e.name;return e.shaderCache?.hint&&(r+="["+e.shaderCache.hint+"]"),r+=":"+n+`:${Al(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,r},zl=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Ol=class{constructor(e){this.subgroupsSupported=e.features.has("subgroups"),this.subgroupsF16Supported=e.features.has("subgroups");let t=e.limits;this.subgroupsSupported&&t.minSubgroupSize&&t.maxSubgroupSize?this.subgroupSizeRange=[t.minSubgroupSize,t.maxSubgroupSize]:this.subgroupSizeRange=void 0}},Bl=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(null===this.currentKernelId)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let n=[],r={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},i=e=>t.features.has(e)&&n.push(e)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups")&&i("subgroups-f16"),this.device=await t.requestDevice(r),this.deviceInfo=new Ol(this.device),this.adapterInfo=new zl(t.info||await t.requestAdapterInfo()),this.gpuDataManager=bt(this),this.programManager=new Fl(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ot(e.logLevel,!!e.debug),this.device.onuncapturederror=e=>{e.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${e.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};"at-passes"===this.queryType&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:2*this.pendingDispatchNumber,endOfPassWriteIndex:2*this.pendingDispatchNumber+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;let e;F(),this.endComputePass(),"none"!==this.queryType&&(this.commandEncoder.resolveQuerySet(this.querySet,0,2*this.pendingDispatchNumber,this.queryResolveBuffer,0),e=this.device.createBuffer({size:2*this.pendingDispatchNumber*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,2*this.pendingDispatchNumber*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,"none"!==this.queryType&&e.mapAsync(GPUMapMode.READ).then((()=>{let t=new BigUint64Array(e.getMappedRange()),n=this.pendingQueries.get(e);for(let e=0;e"u"&&(this.queryTimeBase=c);let h=Number(c-this.queryTimeBase),m=Number(p-this.queryTimeBase);if(!Number.isSafeInteger(h)||!Number.isSafeInteger(m))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:u.map((e=>({dims:e.dims,dataType:Xe(e.dataType)}))),outputsMetadata:d.map((e=>({dims:e.dims,dataType:Xe(e.dataType)}))),kernelId:i,kernelType:s,kernelName:o,programName:l,startTime:h,endTime:m});else{let e="";u.forEach(((t,n)=>{e+=`input[${n}]: [${t.dims}] | ${Xe(t.dataType)}, `}));let t="";d.forEach(((e,n)=>{t+=`output[${n}]: [${e.dims}] | ${Xe(e.dataType)}, `})),console.log(`[profiling] kernel "${i}|${s}|${o}|${l}" ${e}${t}execution time: ${m-h} ns`)}E("GPU",`${l}::${c}::${p}`)}e.unmap(),this.pendingQueries.delete(e)})),A()}run(e,t,n,r,i,a){F(e.name);let s=[];for(let e=0;et)):n;if(d.length!==o.length)throw new Error(`Output size ${d.length} must be equal to ${o.length}.`);let c,p=[],h=[];for(let e=0;e=a)throw new Error(`Invalid output index: ${d[e]}`);if(-3===d[e])continue;let t=-1===d[e],n=-2===d[e],s=t||n?i(o[e].dataType,o[e].dims):r(d[e],o[e].dataType,o[e].dims);if(p.push(s),0===s.data)continue;let l=this.gpuDataManager.get(s.data);if(!l)throw new Error(`no GPU data for output: ${s.data}`);if(t&&this.temporaryData.push(l),n){let e=this.kernelPersistentData.get(this.currentKernelId);e||(e=[],this.kernelPersistentData.set(this.currentKernelId,e)),e.push(l)}h.push(l)}if(s.length!==t.length||h.length!==p.length){if(0===h.length)return A(e.name),p;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}if(u){let e=0,t=[];u.forEach((n=>{let r="number"==typeof n.data?[n.data]:n.data;if(0===r.length)return;let i,a,s=10===n.type?2:4;10===n.type?(a=r.length>4?16:r.length>2?8:r.length*s,i=r.length>4?16:s*r.length):(a=r.length<=2?r.length*s:16,i=16),e=Math.ceil(e/a)*a,t.push(e);let o=10===n.type?8:4;e+=r.length>4?Math.ceil(r.length/o)*i:r.length*s}));let n=16;e=Math.ceil(e/n)*n;let r=new ArrayBuffer(e);u.forEach(((e,n)=>{let i=t[n],a="number"==typeof e.data?[e.data]:e.data;if(6===e.type)new Int32Array(r,i,a.length).set(a);else if(12===e.type)new Uint32Array(r,i,a.length).set(a);else if(10===e.type)new Uint16Array(r,i,a.length).set(a);else{if(1!==e.type)throw new Error(`Unsupported uniform type: ${Xe(e.type)}`);new Float32Array(r,i,a.length).set(a)}}));let i=this.gpuDataManager.create(e,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(i.buffer,0,r,0,e),this.gpuDataManager.release(i.id),c={offset:0,size:e,buffer:i.buffer}}let m=this.programManager.normalizeDispatchGroupSize(l),f=1===m[1]&&1===m[2],g=Il(e,t,f),_=this.programManager.getArtifact(g);if(_||(_=this.programManager.build(e,m),this.programManager.setArtifact(g,_),ut("info",(()=>`[artifact] key: ${g}, programName: ${e.name}`))),u&&_.uniformVariablesInfo){if(u.length!==_.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${_.uniformVariablesInfo.length}, got ${u.length} in program "${_.programInfo.name}".`);for(let e=0;e`[ProgramManager] run "${e.name}" (key=${g}) with ${m[0]}x${m[1]}x${m[2]}`)),"none"!==this.queryType||"capturing"===this.sessionStatus){let e={kernelId:this.currentKernelId,programName:_.programInfo.name,inputTensorViews:t,outputTensorViews:p};this.pendingKernels.push(e),"capturing"===this.sessionStatus&&this.capturedPendingKernels.get(this.currentSessionId).push(e)}return this.programManager.run(_,s,h,m,c),A(e.name),p}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,n,r){let i=Pl.get(e);if(!i)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:r,kernelEntry:i[0],attributes:[i[1],n]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let e of t)this.gpuDataManager.release(e.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let r=this.kernels.get(e);if(!r)throw new Error(`kernel not created: ${e}`);let i=r.kernelType,a=r.kernelName,s=r.kernelEntry,o=r.attributes;if(null!==this.currentKernelId)throw new Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,o[0]&&(o[1]=o[0](o[1]),o[0]=void 0),ut("info",(()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`));let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),s(t,o[1]),0}catch(e){return n.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${e}`)),1}finally{l&&n.push(this.device.popErrorScope().then((e=>e?`GPU validation error for kernel "[${i}] ${a}": ${e.message}`:null)));for(let e of this.temporaryData)this.gpuDataManager.release(e.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,r){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let a=i.get(t),s=this.gpuDataManager.registerExternalBuffer(n,r,a);return i.set(t,[s,n]),s}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach((e=>this.gpuDataManager.unregisterExternalBuffer(e[0]))),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,n){return async()=>{let r=await _t(this,e,t);return dt(r.buffer,n)}}writeTimestamp(e){"inside-passes"===this.queryType&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType="none",("default"===this.env.webgpu.profiling?.mode||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),"none"!==this.queryType&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:2*this.maxDispatchNumber}),this.queryResolveBuffer=this.device.createBuffer({size:2*this.maxDispatchNumber*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){ut("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){ut("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){ut("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),n=e.length;this.pendingKernels=[];for(let r=0;r=this.maxDispatchNumber||"at-passes"===this.queryType)&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}})),ud=j((()=>{nu(),Ll=1,Nl=()=>Ll++,Dl=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Rl=(e,t)=>{let n=Dl.get(e);if(!n)throw new Error("Unsupported data type.");return Math.ceil(t.reduce(((e,t)=>e*t))*n/8)},Vl=class{constructor(e){this.sessionId=e.sessionId,this.mlContext=e.context,this.mlTensor=e.tensor,this.dataType=e.dataType,this.tensorShape=e.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Rl(this.dataType,this.tensorShape)}destroy(){ut("verbose",(()=>"[WebNN] TensorWrapper.destroy")),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}sameTypeAndShape(e,t){return this.dataType===e&&this.tensorShape.length===t.length&&this.tensorShape.every(((e,n)=>e===t[n]))}},jl=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n){if(this.wrapper){if(this.wrapper.sameTypeAndShape(e,t))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==Rl(e,t))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let r=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,r,!0,!0),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper){if(e.byteLength===this.wrapper.byteLength)return void this.wrapper.write(e);ut("verbose",(()=>"Data size does not match tensor size. Releasing tensor.")),this.releaseTensor()}this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(e){if(this.activeUpload)return e?void(e instanceof ArrayBuffer?new Uint8Array(e).set(this.activeUpload):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(this.activeUpload)):this.activeUpload.buffer;if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},ql=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}reserveTensorId(){let e=Nl();return this.tensorTrackersById.set(e,new jl(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,r){ut("verbose",(()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${n}, copyOld: ${r}}`));let i=this.tensorTrackersById.get(e);if(!i)throw new Error("Tensor not found.");return i.ensureTensor(t,n,r)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");n.upload(t)}async download(e,t){ut("verbose",(()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`));let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter((t=>t.sessionId!==e))}registerTensor(e,t,n,r){let i=Nl(),a=new Vl({sessionId:this.backend.currentSessionId,context:e,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(i,new jl(this,a)),this.externalTensors.add(a),i}async getCachedTensor(e,t,n,r,i){let a=this.backend.currentSessionId;for(let[n,r]of this.freeTensors.entries())if(r.sameTypeAndShape(e,t)){ut("verbose",(()=>`[WebNN] Reusing tensor {dataType: ${e}, shape: ${t}}`));let r=this.freeTensors.splice(n,1)[0];return r.sessionId=a,r}let s=this.backend.currentContext;ut("verbose",(()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`));let o=await s.createTensor({dataType:e,shape:t,dimensions:t,usage:n,writable:r,readable:i});return new Vl({sessionId:a,context:s,tensor:o,dataType:e,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Gl=(...e)=>new ql(...e)})),dd=j((()=>{eu(),Ql(),ru(),ud(),nu(),Ul=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Wl=(e,t)=>{if(e===t)return!0;if(void 0===e||void 0===t)return!1;let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every(((n,i)=>n===r[i]&&e[n]===t[n]))},Hl=class{constructor(e){this.tensorManager=Gl(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],ot(e.logLevel,!!e.debug)}get currentSessionId(){if(void 0===this.activeSessionId)throw new Error("No active session");return this.activeSessionId}onRunStart(e){this.activeSessionId=e}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex((t=>t.gpuDevice===e));if(-1!==t)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:t}),t}}if(void 0===e){let e=this.mlContextCache.findIndex((e=>void 0===e.options&&void 0===e.gpuDevice));if(-1!==e)return this.mlContextCache[e].mlContext;{let e=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:e}),e}}let t=this.mlContextCache.findIndex((t=>Wl(t.options,e)));if(-1!==t)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}get currentContext(){let e=this.getMLContext(this.currentSessionId);if(!e)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return e}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e)}onReleaseSession(e){let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),0===n.size){this.sessionIdsByMLContext.delete(t);let e=this.mlContextCache.findIndex((e=>e.mlContext===t));-1!==e&&this.mlContextCache.splice(e,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){ut("verbose",(()=>`[WebNN] releaseTensorId {tensorId: ${e}}`)),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r){let i=Ul.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,i,n,r)}uploadTensor(e,t){if(!Ne().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");ut("verbose",(()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`)),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return dt(n,t)}}registerMLTensor(e,t,n){let r=Ul.get(t);if(!r)throw new Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.registerTensor(this.currentContext,e,r,n);return ut("verbose",(()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${r}, dimensions: ${n}} -> {tensorId: ${i}}`)),i}registerMLConstant(e,t,n,r,i,a){if(!a)throw new Error("External mounted files are not available.");let s=e;e.startsWith("./")&&(s=e.substring(2));let o=a.get(s);if(!o)throw new Error(`File with name ${s} not found in preloaded files.`);if(t+n>o.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let l,u=o.slice(t,t+n).buffer;switch(i.dataType){case"float32":l=new Float32Array(u);break;case"float16":l=new Uint16Array(u);break;case"int32":l=new Int32Array(u);break;case"uint32":l=new Uint32Array(u);break;case"int64":l=new BigInt64Array(u);break;case"uint64":l=new BigUint64Array(u);break;case"int8":l=new Int8Array(u);break;case"int4":case"uint4":case"uint8":l=new Uint8Array(u);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return ut("verbose",(()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`)),r.constant(i,l)}flush(){}}})),cd={};q(cd,{init:()=>md});var pd,hd,md,fd,gd,_d,wd,bd,yd,xd,vd,Md,Td,kd,$d,Sd,Cd,Ed,Pd,Fd,Ad,Id,zd,Od,Bd,Ld,Nd,Dd,Rd,Vd,jd,qd,Gd,Ud,Wd,Hd,Kd=j((()=>{eu(),ld(),nu(),ou(),dd(),pd=class e{constructor(e,t,n,r){this.module=e,this.dataType=t,this.data=n,this.dims=r}getFloat32Array(){if(1!==this.dataType)throw new Error("Invalid data type");let e=Tt.size(this.dims);return 0===e?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(7!==this.dataType)throw new Error("Invalid data type");let e=Tt.size(this.dims);return 0===e?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(6!==this.dataType)throw new Error("Invalid data type");let e=Tt.size(this.dims);return 0===e?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}getUint16Array(){if(10!==this.dataType&&4!==this.dataType)throw new Error("Invalid data type");let e=Tt.size(this.dims);return 0===e?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(t){if(Tt.size(t)!==Tt.size(this.dims))throw new Error("Invalid new shape");return new e(this.module,this.dataType,this.data,t)}},hd=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo,this.deviceInfo=t.deviceInfo;let r=e.PTR_SIZE,i=n/e.PTR_SIZE,a=4===r?"i32":"i64";this.opKernelContext=Number(e.getValue(r*i++,a));let s=Number(e.getValue(r*i++,a));this.outputCount=Number(e.getValue(r*i++,a)),this.customDataOffset=Number(e.getValue(r*i++,"*")),this.customDataSize=Number(e.getValue(r*i++,a));let o=[];for(let t=0;t"number"==typeof e?this.inputs[e]:e))??this.inputs,r=t?.outputs??[];return this.backend.run(e,n,r,((e,t,n)=>new pd(this.module,t,this.output(e,n),n)),((e,t)=>{let n=Qe(e,t);if(!n)throw new Error(`Unsupported data type: ${e}`);let r=n>0?this.backend.gpuDataManager.create(n).id:0;return new pd(this.module,e,r,t)}),this.outputCount)}output(e,t){let n=this.module.stackSave();try{let n=this.module.PTR_SIZE,r=4===n?"i32":"i64",i=this.module.stackAlloc((1+t.length)*n);this.module.setValue(i,t.length,r);for(let e=0;e{let i=t.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if("webgpu"===e){let e=new Bl;await e.initialize(n,r),i("webgpu",[e,t=>e.alloc(Number(t)),t=>e.free(t),(n,r,i,a=!1)=>{if(a)ut("verbose",(()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(n)}, dst=${Number(r)}, size=${Number(i)}`)),e.memcpy(Number(n),Number(r));else{ut("verbose",(()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(n)}, gpuDataId=${Number(r)}, size=${Number(i)}`));let a=t.HEAPU8.subarray(Number(n>>>0),Number(n>>>0)+Number(i));e.upload(Number(r),a)}},async(n,r,i)=>{ut("verbose",(()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${n}, dataOffset=${r}, size=${i}`)),await e.download(Number(n),(()=>t.HEAPU8.subarray(Number(r)>>>0,Number(r+i)>>>0)))},(n,r,i)=>e.createKernel(n,Number(r),i,t.UTF8ToString(t._JsepGetNodeName(Number(r)))),t=>e.releaseKernel(t),(n,r,i,a)=>{ut("verbose",(()=>`[WebGPU] jsepRun: sessionHandle=${i}, kernel=${n}, contextDataOffset=${r}`));let s=new hd(t,e,Number(r));return e.computeKernel(Number(n),s,a)},()=>e.captureBegin(),()=>e.captureEnd(),()=>e.replay()])}else{let e=new Hl(n);i("webnn",[e,()=>e.reserveTensorId(),t=>e.releaseTensorId(t),async(t,n,r,i)=>e.ensureTensor(t,n,r,i),(t,n)=>{e.uploadTensor(t,n)},async(t,n)=>e.downloadTensor(t,n)])}}})),Xd=j((()=>{Zl(),Jl(),eu(),Ql(),Yl(),tu(),fd=(e,t)=>{0!==Ne()._OrtInit(e,t)&&Ve("Can't initialize onnxruntime.")},gd=async e=>{fd(e.wasm.numThreads,Ze(e.logLevel))},_d=async(e,t)=>{{let n=(Kd(),G(cd)).init;if("webgpu"===t){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let t=e.webgpu.adapter;if(t){if("object"!=typeof t.limits||"object"!=typeof t.features||"function"!=typeof t.requestDevice)throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let n=e.webgpu.powerPreference;if(void 0!==n&&"low-power"!==n&&"high-performance"!==n)throw new Error(`Invalid powerPreference setting: "${n}"`);let r=e.webgpu.forceFallbackAdapter;if(void 0!==r&&"boolean"!=typeof r)throw new Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(t=await navigator.gpu.requestAdapter({powerPreference:n,forceFallbackAdapter:r}),!t)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await n("webgpu",Ne(),e,t)}if("webnn"===t){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await n("webnn",Ne(),e)}}},wd=new Map,bd=e=>{let t=Ne(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);0!==t._OrtGetInputOutputCount(e,r,r+n)&&Ve("Can't get session input/output count.");let i=4===n?"i32":"i64";return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},yd=e=>{let t=Ne(),n=t._malloc(e.byteLength);if(0===n)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},xd=async(e,t)=>{let n,r,i=Ne();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=yd(e);let a=0,s=0,o=0,l=[],u=[],d=[];try{if([s,l]=He(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t="string"==typeof n?n:n.path;e.push(nt("string"==typeof n?n:n.data).then((e=>{i.mountExternalData(t,e)})))}await Promise.all(e)}for(let e of t?.executionProviders??[])if("webnn"===("string"==typeof e?e:e.name)){if(i.shouldTransferToMLTensor=!1,"string"!=typeof e){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,s=t?.powerPreference;i.currentContext=n||(r?await i.jsepCreateMLContext(r):await i.jsepCreateMLContext({deviceType:a,powerPreference:s}))}else i.currentContext=await i.jsepCreateMLContext();break}a=await i._OrtCreateSession(n,r,s),0===a&&Ve("Can't create a session."),i.jsepOnCreateSession?.(),i.currentContext&&(i.jsepRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,c]=bd(a),p=!!t?.enableGraphCapture,h=[],m=[],f=[];for(let t=0;t"gpu-buffer"===e||"ml-tensor"===e))&&(o=i._OrtCreateBinding(a),0===o&&Ve("Can't create IO binding."),g={handle:o,outputPreferredLocations:f,outputPreferredLocationsEncoded:f.map((e=>tt(e)))}),wd.set(a,[a,u,d,g,p,!1]),[a,h,m]}catch(e){throw u.forEach((e=>i._OrtFree(e))),d.forEach((e=>i._OrtFree(e))),0!==o&&0!==i._OrtReleaseBinding(o)&&Ve("Can't release IO binding."),0!==a&&0!==i._OrtReleaseSession(a)&&Ve("Can't release session."),e}finally{i._free(n),0!==s&&0!==i._OrtReleaseSessionOptions(s)&&Ve("Can't release session options."),l.forEach((e=>i._free(e))),i.unmountExternalData?.()}},vd=e=>{let t=Ne(),n=wd.get(e);if(!n)throw new Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,s,o]=n;s&&(o&&0!==t._OrtClearBoundOutputs(s.handle)&&Ve("Can't clear bound outputs."),0!==t._OrtReleaseBinding(s.handle)&&Ve("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),i.forEach((e=>t._OrtFree(e))),a.forEach((e=>t._OrtFree(e))),0!==t._OrtReleaseSession(r)&&Ve("Can't release session."),wd.delete(e)},Md=(e,t,n,r,i,a=!1)=>{if(!e)return void t.push(0);let s,o,l=Ne(),u=l.PTR_SIZE,d=e[0],c=e[1],p=e[3];if("string"===d&&("gpu-buffer"===p||"ml-tensor"===p))throw new Error("String tensor is not supported on GPU.");if(a&&"gpu-buffer"!==p)throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if("gpu-buffer"===p){let t=e[2].gpuBuffer;o=Qe(Ke(d),c);let n=l.jsepRegisterBuffer;if(!n)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');s=n(r,i,t,o)}else if("ml-tensor"===p){let t=e[2].mlTensor;o=Qe(Ke(d),c);let n=l.jsepRegisterMLTensor;if(!n)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');s=n(t,Ke(d),c)}else{let t=e[2];if(Array.isArray(t)){o=u*t.length,s=l._malloc(o),n.push(s);for(let e=0;el.setValue(m+t*u,e,4===u?"i32":"i64")));let e=l._OrtCreateTensor(Ke(d),s,o,m,c.length,tt(p));0===e&&Ve(`Can't create tensor for input/output. session=${r}, index=${i}.`),t.push(e)}finally{l.stackRestore(h)}},Td=async(e,t,n,r,i,a)=>{let s=Ne(),o=s.PTR_SIZE,l=wd.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let u=l[0],d=l[1],c=l[2],p=l[3],h=l[4],m=l[5],f=t.length,g=r.length,_=0,w=[],b=[],y=[],x=[],v=s.stackSave(),M=s.stackAlloc(f*o),T=s.stackAlloc(f*o),k=s.stackAlloc(g*o),$=s.stackAlloc(g*o);try{s.jsepOnRunStart?.(u),[_,w]=je(a);for(let r=0;re*t),1);n=Xe(a);let g=p?.outputPreferredLocations[r[e]];if("string"===n){if("gpu-buffer"===g||"ml-tensor"===g)throw new Error("String tensor is not supported on GPU.");let e=[];for(let t=0;t0){let e=s.jsepGetBuffer;if(!e)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let r=e(d),i=Qe(a,f);if(void 0===i||!Je(n))throw new Error(`Unsupported data type: ${n}`);u=!0,v.push([n,m,{gpuBuffer:r,download:s.jsepCreateDownloader(r,i,n),dispose:()=>{0!==s._OrtReleaseTensor(t)&&Ve("Can't release tensor.")}},"gpu-buffer"])}else if("ml-tensor"===g&&f>0){let e=s.jsepEnsureTensor;if(!e)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(void 0===Qe(a,f)||!et(n))throw new Error(`Unsupported data type: ${n}`);let r=await e(d,a,m,!1);u=!0,v.push([n,m,{mlTensor:r,download:s.jsepCreateMLTensorDownloader(d,n),dispose:()=>{s.jsepReleaseTensorId(d),s._OrtReleaseTensor(t)}},"ml-tensor"])}else{let e=new(Ye(n))(f);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(s.HEAPU8.subarray(d,d+e.byteLength)),v.push([n,m,e,"cpu"])}}finally{s.stackRestore(a),"string"===n&&d&&s._free(d),u||s._OrtReleaseTensor(t)}}return p&&!h&&(0!==s._OrtClearBoundOutputs(p.handle)&&Ve("Can't clear bound outputs."),wd.set(e,[u,d,c,p,h,!1])),v}finally{s.stackRestore(v),b.forEach((e=>s._OrtReleaseTensor(e))),y.forEach((e=>s._OrtReleaseTensor(e))),x.forEach((e=>s._free(e))),0!==_&&s._OrtReleaseRunOptions(_),w.forEach((e=>s._free(e)))}},kd=e=>{let t=Ne(),n=wd.get(e);if(!n)throw new Error("invalid session id");let r=n[0],i=t._OrtEndProfiling(r);0===i&&Ve("Can't get an profile file name."),t._OrtFree(i)},$d=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&"buffer"in e&&t.push(e.buffer)}return t}})),Qd=j((()=>{pe(),Xd(),Ql(),Xl(),Sd=()=>!!p.wasm.proxy&&typeof document<"u",Ed=!1,Pd=!1,Fd=!1,zd=new Map,Od=(e,t)=>{let n=zd.get(e);n?n.push(t):zd.set(e,[t])},Bd=()=>{if(Ed||!Pd||Fd||!Cd)throw new Error("worker not ready")},Ld=e=>{switch(e.data.type){case"init-wasm":Ed=!1,e.data.err?(Fd=!0,Id[1](e.data.err)):(Pd=!0,Id[0]()),Ad&&(URL.revokeObjectURL(Ad),Ad=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=zd.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Nd=async()=>{if(!Pd){if(Ed)throw new Error("multiple calls to 'initWasm()' detected.");if(Fd)throw new Error("previous call to 'initWasm()' failed.");if(Ed=!0,Sd())return new Promise(((e,t)=>{Cd?.terminate(),Ce().then((([n,r])=>{try{(Cd=r).onerror=e=>t(e),Cd.onmessage=Ld,Id=[e,t];let i={type:"init-wasm",in:p};Cd.postMessage(i),Ad=n}catch(e){t(e)}}),t)}));try{await Le(p.wasm),await gd(p),Pd=!0}catch(e){throw Fd=!0,e}finally{Ed=!1}}},Dd=async e=>{if(Sd())return Bd(),new Promise(((t,n)=>{Od("init-ep",[t,n]);let r={type:"init-ep",in:{epName:e,env:p}};Cd.postMessage(r)}));await _d(p,e)},Rd=async e=>Sd()?(Bd(),new Promise(((t,n)=>{Od("copy-from",[t,n]);let r={type:"copy-from",in:{buffer:e}};Cd.postMessage(r,[e.buffer])}))):yd(e),Vd=async(e,t)=>{if(Sd()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Bd(),new Promise(((n,r)=>{Od("create",[n,r]);let i={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Cd.postMessage(i,a)}))}return xd(e,t)},jd=async e=>{if(Sd())return Bd(),new Promise(((t,n)=>{Od("release",[t,n]);let r={type:"release",in:e};Cd.postMessage(r)}));vd(e)},qd=async(e,t,n,r,i,a)=>{if(Sd()){if(n.some((e=>"cpu"!==e[3])))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some((e=>e)))throw new Error("pre-allocated output tensor is not supported for proxy.");return Bd(),new Promise(((i,s)=>{Od("run",[i,s]);let o=n,l={type:"run",in:{sessionId:e,inputIndices:t,inputs:o,outputIndices:r,options:a}};Cd.postMessage(l,$d(o))}))}return Td(e,t,n,r,i,a)},Gd=async e=>{if(Sd())return Bd(),new Promise(((t,n)=>{Od("end-profiling",[t,n]);let r={type:"end-profiling",in:e};Cd.postMessage(r)}));kd(e)}})),Yd=j((()=>{pe(),Qd(),eu(),he(),tu(),Ud=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},Wd=e=>{switch(e[3]){case"cpu":return new C(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Je(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return C.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case"ml-tensor":{let t=e[0];if(!et(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return C.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw new Error(`invalid data location: ${e[3]}`)}},Hd=class{async fetchModelAndCopyToWasmMemory(e){return Rd(await nt(e))}async loadModel(e,t){let n;F(),n="string"==typeof e?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames]=await Vd(n,t),A()}async dispose(){return jd(this.sessionId)}async run(e,t,n){F();let r=[],i=[];Object.entries(e).forEach((e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(-1===a)throw new Error(`invalid input '${t}'`);r.push(n),i.push(a)}));let a=[],s=[];Object.entries(t).forEach((e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(-1===r)throw new Error(`invalid output '${t}'`);a.push(n),s.push(r)}));let o=r.map(((e,t)=>Ud(e,(()=>`input "${this.inputNames[i[t]]}"`)))),l=a.map(((e,t)=>e?Ud(e,(()=>`output "${this.outputNames[s[t]]}"`)):null)),u=await qd(this.sessionId,i,o,s,l,n),d={};for(let e=0;eec,initializeFlags:()=>Jd,wasmBackend:()=>tc});var Jd,ec,tc,nc=j((()=>{pe(),Qd(),Yd(),Xl(),Jd=()=>{if(("number"!=typeof p.wasm.initTimeout||p.wasm.initTimeout<0)&&(p.wasm.initTimeout=0),!1===p.wasm.simd&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),"boolean"!=typeof p.wasm.proxy&&(p.wasm.proxy=!1),"boolean"!=typeof p.wasm.trace&&(p.wasm.trace=!1),"number"!=typeof p.wasm.numThreads||!Number.isInteger(p.wasm.numThreads)||p.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)p.wasm.numThreads=1;else{let e=typeof navigator>"u"?V("node:os").cpus().length:navigator.hardwareConcurrency;p.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},tc=new(ec=class{async init(e){Jd(),await Nd(),await Dd(e)}async createInferenceSessionHandler(e,t){let n=new Hd;return await n.loadModel(e,t),Promise.resolve(n)}})}));pe(),pe(),pe();var rc=ce;{let e=(nc(),G(Zd)).wasmBackend;s("webgpu",e,5),s("webnn",e,5),s("cpu",e,10),s("wasm",e,10)}Object.defineProperty(p.versions,"web",{value:"1.21.0-dev.20241122-a2ba3cb547",enumerable:!0})} /** * @license * Copyright 2021 Google LLC. All Rights Reserved. @@ -172,7 +172,7 @@ var r,i,a,s,o,l,u,d,c,p,h,m,f,g,_,w,b,y,x,v,M,T,k,$,C,S,P,E,F,A,I,z,O,B,L=Object \*************************************/(e,t,n)=>{n.r(t),n.d(t,{BaseStreamer:()=>s,TextStreamer:()=>l,WhisperTextStreamer:()=>u});var r=n(/*! ../utils/core.js */"./src/utils/core.js"),i=n(/*! ../tokenizers.js */"./src/tokenizers.js"),a=n(/*! ../env.js */"./src/env.js");class s{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const o=a.apis.IS_PROCESS_AVAILABLE?e=>process.stdout.write(e):e=>console.log(e);class l extends s{constructor(e,{skip_prompt:t=!1,callback_function:n=null,token_callback_function:r=null,decode_kwargs:i={},...a}={}){super(),this.tokenizer=e,this.skip_prompt=t,this.callback_function=n??o,this.token_callback_function=r,this.decode_kwargs={...i,...a},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(e){if(e.length>1)throw Error("TextStreamer only supports batch size of 1");if(this.skip_prompt&&this.next_tokens_are_prompt)return void(this.next_tokens_are_prompt=!1);const t=e[0];this.token_callback_function?.(t),this.token_cache=(0,r.mergeArrays)(this.token_cache,t);const n=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let a;n.endsWith("\n")?(a=n.slice(this.print_len),this.token_cache=[],this.print_len=0):n.length>0&&(0,i.is_chinese_char)(n.charCodeAt(n.length-1))?(a=n.slice(this.print_len),this.print_len+=a.length):(a=n.slice(this.print_len,n.lastIndexOf(" ")+1),this.print_len+=a.length),this.on_finalized_text(a,!1)}end(){let e;if(this.token_cache.length>0){e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0}else e="";this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,t){e.length>0&&this.callback_function?.(e),t&&this.callback_function===o&&a.apis.IS_PROCESS_AVAILABLE&&this.callback_function?.("\n")}}class u extends l{constructor(e,{skip_prompt:t=!1,callback_function:n=null,token_callback_function:r=null,on_chunk_start:i=null,on_chunk_end:a=null,on_finalize:s=null,time_precision:o=.02,skip_special_tokens:l=!0,decode_kwargs:u={}}={}){super(e,{skip_prompt:t,callback_function:n,token_callback_function:r,decode_kwargs:{skip_special_tokens:l,...u}}),this.timestamp_begin=e.timestamp_begin,this.on_chunk_start=i,this.on_chunk_end=a,this.on_finalize=s,this.time_precision=o,this.waiting_for_timestamp=!1}put(e){if(e.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const t=e[0];if(1===t.length){const n=Number(t[0])-this.timestamp_begin;if(n>=0){const t=n*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(t):this.on_chunk_start?.(t),this.waiting_for_timestamp=!this.waiting_for_timestamp,e=[[]]}}return super.put(e)}end(){super.end(),this.on_finalize?.()}}},"./src/models.js": /*!***********************!*\ !*** ./src/models.js ***! - \***********************/(e,t,n)=>{n.r(t),n.d(t,{ASTForAudioClassification:()=>un,ASTModel:()=>ln,ASTPreTrainedModel:()=>on,AlbertForMaskedLM:()=>_t,AlbertForQuestionAnswering:()=>gt,AlbertForSequenceClassification:()=>ft,AlbertModel:()=>mt,AlbertPreTrainedModel:()=>ht,AutoModel:()=>jo,AutoModelForAudioClassification:()=>ol,AutoModelForAudioFrameClassification:()=>ul,AutoModelForCTC:()=>sl,AutoModelForCausalLM:()=>Ko,AutoModelForDepthEstimation:()=>hl,AutoModelForDocumentQuestionAnswering:()=>dl,AutoModelForImageClassification:()=>Jo,AutoModelForImageFeatureExtraction:()=>fl,AutoModelForImageMatting:()=>cl,AutoModelForImageSegmentation:()=>el,AutoModelForImageToImage:()=>pl,AutoModelForMaskGeneration:()=>al,AutoModelForMaskedLM:()=>Qo,AutoModelForNormalEstimation:()=>ml,AutoModelForObjectDetection:()=>rl,AutoModelForQuestionAnswering:()=>Yo,AutoModelForSemanticSegmentation:()=>tl,AutoModelForSeq2SeqLM:()=>Wo,AutoModelForSequenceClassification:()=>qo,AutoModelForSpeechSeq2Seq:()=>Uo,AutoModelForTextToSpectrogram:()=>Ho,AutoModelForTextToWaveform:()=>Xo,AutoModelForTokenClassification:()=>Go,AutoModelForUniversalSegmentation:()=>nl,AutoModelForVision2Seq:()=>Zo,AutoModelForXVector:()=>ll,AutoModelForZeroShotObjectDetection:()=>il,BartForConditionalGeneration:()=>Pt,BartForSequenceClassification:()=>Et,BartModel:()=>St,BartPretrainedModel:()=>Ct,BaseModelOutput:()=>K,BeitForImageClassification:()=>fi,BeitModel:()=>mi,BeitPreTrainedModel:()=>hi,BertForMaskedLM:()=>Z,BertForQuestionAnswering:()=>te,BertForSequenceClassification:()=>J,BertForTokenClassification:()=>ee,BertModel:()=>Y,BertPreTrainedModel:()=>Q,BlenderbotForConditionalGeneration:()=>Nt,BlenderbotModel:()=>Lt,BlenderbotPreTrainedModel:()=>Bt,BlenderbotSmallForConditionalGeneration:()=>Vt,BlenderbotSmallModel:()=>Rt,BlenderbotSmallPreTrainedModel:()=>Dt,BloomForCausalLM:()=>Er,BloomModel:()=>Pr,BloomPreTrainedModel:()=>Sr,CLIPModel:()=>yn,CLIPPreTrainedModel:()=>bn,CLIPSegForImageSegmentation:()=>In,CLIPSegModel:()=>An,CLIPSegPreTrainedModel:()=>Fn,CLIPTextModel:()=>xn,CLIPTextModelWithProjection:()=>vn,CLIPVisionModel:()=>Mn,CLIPVisionModelWithProjection:()=>Tn,CamembertForMaskedLM:()=>Te,CamembertForQuestionAnswering:()=>Ce,CamembertForSequenceClassification:()=>ke,CamembertForTokenClassification:()=>$e,CamembertModel:()=>Me,CamembertPreTrainedModel:()=>ve,CausalLMOutput:()=>vl,CausalLMOutputWithPast:()=>Ml,ChineseCLIPModel:()=>En,ChineseCLIPPreTrainedModel:()=>Pn,ClapAudioModelWithProjection:()=>Es,ClapModel:()=>Ss,ClapPreTrainedModel:()=>Cs,ClapTextModelWithProjection:()=>Ps,CodeGenForCausalLM:()=>er,CodeGenModel:()=>Jn,CodeGenPreTrainedModel:()=>Zn,CohereForCausalLM:()=>ur,CohereModel:()=>lr,CoherePreTrainedModel:()=>or,ConvBertForMaskedLM:()=>pe,ConvBertForQuestionAnswering:()=>fe,ConvBertForSequenceClassification:()=>he,ConvBertForTokenClassification:()=>me,ConvBertModel:()=>ce,ConvBertPreTrainedModel:()=>de,ConvNextForImageClassification:()=>pa,ConvNextModel:()=>ca,ConvNextPreTrainedModel:()=>da,ConvNextV2ForImageClassification:()=>fa,ConvNextV2Model:()=>ma,ConvNextV2PreTrainedModel:()=>ha,DPTForDepthEstimation:()=>Hi,DPTModel:()=>Ui,DPTPreTrainedModel:()=>Wi,DebertaForMaskedLM:()=>Ee,DebertaForQuestionAnswering:()=>Ie,DebertaForSequenceClassification:()=>Fe,DebertaForTokenClassification:()=>Ae,DebertaModel:()=>Pe,DebertaPreTrainedModel:()=>Se,DebertaV2ForMaskedLM:()=>Be,DebertaV2ForQuestionAnswering:()=>De,DebertaV2ForSequenceClassification:()=>Le,DebertaV2ForTokenClassification:()=>Ne,DebertaV2Model:()=>Oe,DebertaV2PreTrainedModel:()=>ze,DecisionTransformerModel:()=>so,DecisionTransformerPreTrainedModel:()=>ao,DeiTForImageClassification:()=>Ai,DeiTModel:()=>Fi,DeiTPreTrainedModel:()=>Ei,DepthAnythingForDepthEstimation:()=>Ki,DepthAnythingPreTrainedModel:()=>Xi,DepthProForDepthEstimation:()=>ta,DepthProPreTrainedModel:()=>ea,DetrForObjectDetection:()=>wi,DetrForSegmentation:()=>bi,DetrModel:()=>_i,DetrObjectDetectionOutput:()=>yi,DetrPreTrainedModel:()=>gi,DetrSegmentationOutput:()=>xi,Dinov2ForImageClassification:()=>wa,Dinov2Model:()=>_a,Dinov2PreTrainedModel:()=>ga,DistilBertForMaskedLM:()=>We,DistilBertForQuestionAnswering:()=>Ge,DistilBertForSequenceClassification:()=>je,DistilBertForTokenClassification:()=>qe,DistilBertModel:()=>Ve,DistilBertPreTrainedModel:()=>Re,DonutSwinModel:()=>ua,DonutSwinPreTrainedModel:()=>la,EfficientNetForImageClassification:()=>js,EfficientNetModel:()=>Vs,EfficientNetPreTrainedModel:()=>Rs,ElectraForMaskedLM:()=>we,ElectraForQuestionAnswering:()=>xe,ElectraForSequenceClassification:()=>be,ElectraForTokenClassification:()=>ye,ElectraModel:()=>_e,ElectraPreTrainedModel:()=>ge,EsmForMaskedLM:()=>Xe,EsmForSequenceClassification:()=>Ke,EsmForTokenClassification:()=>Qe,EsmModel:()=>He,EsmPreTrainedModel:()=>Ue,FalconForCausalLM:()=>$s,FalconModel:()=>ks,FalconPreTrainedModel:()=>Ts,FastViTForImageClassification:()=>Zr,FastViTModel:()=>Yr,FastViTPreTrainedModel:()=>Qr,Florence2ForConditionalGeneration:()=>wn,Florence2PreTrainedModel:()=>_n,GLPNForDepthEstimation:()=>oa,GLPNModel:()=>sa,GLPNPreTrainedModel:()=>aa,GPT2LMHeadModel:()=>Bn,GPT2Model:()=>On,GPT2PreTrainedModel:()=>zn,GPTBigCodeForCausalLM:()=>Yn,GPTBigCodeModel:()=>Qn,GPTBigCodePreTrainedModel:()=>Kn,GPTJForCausalLM:()=>Xn,GPTJModel:()=>Hn,GPTJPreTrainedModel:()=>Un,GPTNeoForCausalLM:()=>jn,GPTNeoModel:()=>Vn,GPTNeoPreTrainedModel:()=>Rn,GPTNeoXForCausalLM:()=>Wn,GPTNeoXModel:()=>Gn,GPTNeoXPreTrainedModel:()=>qn,Gemma2ForCausalLM:()=>fr,Gemma2Model:()=>mr,Gemma2PreTrainedModel:()=>hr,GemmaForCausalLM:()=>pr,GemmaModel:()=>cr,GemmaPreTrainedModel:()=>dr,GraniteForCausalLM:()=>sr,GraniteModel:()=>ar,GranitePreTrainedModel:()=>ir,GroupViTModel:()=>Kr,GroupViTPreTrainedModel:()=>Xr,HieraForImageClassification:()=>Oi,HieraModel:()=>zi,HieraPreTrainedModel:()=>Ii,HubertForCTC:()=>rs,HubertForSequenceClassification:()=>is,HubertModel:()=>ns,HubertPreTrainedModel:()=>ts,ImageMattingOutput:()=>Tl,JAISLMHeadModel:()=>Dn,JAISModel:()=>Nn,JAISPreTrainedModel:()=>Ln,LlamaForCausalLM:()=>rr,LlamaModel:()=>nr,LlamaPreTrainedModel:()=>tr,LlavaForConditionalGeneration:()=>fn,LlavaPreTrainedModel:()=>mn,LongT5ForConditionalGeneration:()=>Mt,LongT5Model:()=>vt,LongT5PreTrainedModel:()=>xt,M2M100ForConditionalGeneration:()=>Fa,M2M100Model:()=>Ea,M2M100PreTrainedModel:()=>Pa,MBartForCausalLM:()=>Ot,MBartForConditionalGeneration:()=>It,MBartForSequenceClassification:()=>zt,MBartModel:()=>At,MBartPreTrainedModel:()=>Ft,MPNetForMaskedLM:()=>it,MPNetForQuestionAnswering:()=>ot,MPNetForSequenceClassification:()=>at,MPNetForTokenClassification:()=>st,MPNetModel:()=>rt,MPNetPreTrainedModel:()=>nt,MT5ForConditionalGeneration:()=>$t,MT5Model:()=>kt,MT5PreTrainedModel:()=>Tt,MarianMTModel:()=>Sa,MarianModel:()=>Ca,MarianPreTrainedModel:()=>$a,MaskFormerForInstanceSegmentation:()=>ia,MaskFormerModel:()=>ra,MaskFormerPreTrainedModel:()=>na,MaskedLMOutput:()=>yl,MistralForCausalLM:()=>ys,MistralModel:()=>bs,MistralPreTrainedModel:()=>ws,MobileBertForMaskedLM:()=>Je,MobileBertForQuestionAnswering:()=>tt,MobileBertForSequenceClassification:()=>et,MobileBertModel:()=>Ze,MobileBertPreTrainedModel:()=>Ye,MobileNetV1ForImageClassification:()=>Ks,MobileNetV1Model:()=>Xs,MobileNetV1PreTrainedModel:()=>Hs,MobileNetV2ForImageClassification:()=>Zs,MobileNetV2Model:()=>Ys,MobileNetV2PreTrainedModel:()=>Qs,MobileNetV3ForImageClassification:()=>to,MobileNetV3Model:()=>eo,MobileNetV3PreTrainedModel:()=>Js,MobileNetV4ForImageClassification:()=>io,MobileNetV4Model:()=>ro,MobileNetV4PreTrainedModel:()=>no,MobileViTForImageClassification:()=>ri,MobileViTModel:()=>ni,MobileViTPreTrainedModel:()=>ti,MobileViTV2ForImageClassification:()=>si,MobileViTV2Model:()=>ai,MobileViTV2PreTrainedModel:()=>ii,ModelOutput:()=>X,Moondream1ForConditionalGeneration:()=>gn,MptForCausalLM:()=>Ir,MptModel:()=>Ar,MptPreTrainedModel:()=>Fr,MusicgenForCausalLM:()=>Ws,MusicgenForConditionalGeneration:()=>Us,MusicgenModel:()=>Gs,MusicgenPreTrainedModel:()=>qs,NomicBertModel:()=>re,NomicBertPreTrainedModel:()=>ne,OPTForCausalLM:()=>Br,OPTModel:()=>Or,OPTPreTrainedModel:()=>zr,OpenELMForCausalLM:()=>wr,OpenELMModel:()=>_r,OpenELMPreTrainedModel:()=>gr,OwlViTForObjectDetection:()=>ui,OwlViTModel:()=>li,OwlViTPreTrainedModel:()=>oi,Owlv2ForObjectDetection:()=>pi,Owlv2Model:()=>ci,Owlv2PreTrainedModel:()=>di,Phi3ForCausalLM:()=>Cr,Phi3Model:()=>$r,Phi3PreTrainedModel:()=>kr,PhiForCausalLM:()=>Tr,PhiModel:()=>Mr,PhiPreTrainedModel:()=>vr,PreTrainedModel:()=>H,PretrainedMixin:()=>oo,PvtForImageClassification:()=>jr,PvtModel:()=>Vr,PvtPreTrainedModel:()=>Rr,PyAnnoteForAudioFrameClassification:()=>Da,PyAnnoteModel:()=>Na,PyAnnotePreTrainedModel:()=>La,QuestionAnsweringModelOutput:()=>xl,Qwen2ForCausalLM:()=>xr,Qwen2Model:()=>yr,Qwen2PreTrainedModel:()=>br,RTDetrForObjectDetection:()=>Ti,RTDetrModel:()=>Mi,RTDetrObjectDetectionOutput:()=>ki,RTDetrPreTrainedModel:()=>vi,ResNetForImageClassification:()=>Ni,ResNetModel:()=>Li,ResNetPreTrainedModel:()=>Bi,RoFormerForMaskedLM:()=>se,RoFormerForQuestionAnswering:()=>ue,RoFormerForSequenceClassification:()=>oe,RoFormerForTokenClassification:()=>le,RoFormerModel:()=>ae,RoFormerPreTrainedModel:()=>ie,RobertaForMaskedLM:()=>Gt,RobertaForQuestionAnswering:()=>Ht,RobertaForSequenceClassification:()=>Wt,RobertaForTokenClassification:()=>Ut,RobertaModel:()=>qt,RobertaPreTrainedModel:()=>jt,SamImageSegmentationOutput:()=>ka,SamModel:()=>Ta,SamPreTrainedModel:()=>Ma,SapiensForDepthEstimation:()=>Zi,SapiensForNormalEstimation:()=>Ji,SapiensForSemanticSegmentation:()=>Yi,SapiensPreTrainedModel:()=>Qi,SegformerForImageClassification:()=>Os,SegformerForSemanticSegmentation:()=>Bs,SegformerModel:()=>zs,SegformerPreTrainedModel:()=>Is,Seq2SeqLMOutput:()=>gl,SequenceClassifierOutput:()=>_l,SiglipModel:()=>$n,SiglipPreTrainedModel:()=>kn,SiglipTextModel:()=>Cn,SiglipVisionModel:()=>Sn,SpeechT5ForSpeechToText:()=>hs,SpeechT5ForTextToSpeech:()=>ms,SpeechT5HifiGan:()=>fs,SpeechT5Model:()=>ps,SpeechT5PreTrainedModel:()=>cs,SqueezeBertForMaskedLM:()=>dt,SqueezeBertForQuestionAnswering:()=>pt,SqueezeBertForSequenceClassification:()=>ct,SqueezeBertModel:()=>ut,SqueezeBertPreTrainedModel:()=>lt,StableLmForCausalLM:()=>Ds,StableLmModel:()=>Ns,StableLmPreTrainedModel:()=>Ls,Starcoder2ForCausalLM:()=>Ms,Starcoder2Model:()=>vs,Starcoder2PreTrainedModel:()=>xs,Swin2SRForImageSuperResolution:()=>Gi,Swin2SRModel:()=>qi,Swin2SRPreTrainedModel:()=>ji,SwinForImageClassification:()=>Vi,SwinModel:()=>Ri,SwinPreTrainedModel:()=>Di,T5ForConditionalGeneration:()=>yt,T5Model:()=>bt,T5PreTrainedModel:()=>wt,TableTransformerForObjectDetection:()=>Si,TableTransformerModel:()=>Ci,TableTransformerObjectDetectionOutput:()=>Pi,TableTransformerPreTrainedModel:()=>$i,TokenClassifierOutput:()=>bl,TrOCRForCausalLM:()=>_s,TrOCRPreTrainedModel:()=>gs,UniSpeechForCTC:()=>Ga,UniSpeechForSequenceClassification:()=>Wa,UniSpeechModel:()=>qa,UniSpeechPreTrainedModel:()=>ja,UniSpeechSatForAudioFrameClassification:()=>Qa,UniSpeechSatForCTC:()=>Xa,UniSpeechSatForSequenceClassification:()=>Ka,UniSpeechSatModel:()=>Ha,UniSpeechSatPreTrainedModel:()=>Ua,ViTForImageClassification:()=>Dr,ViTMAEModel:()=>Gr,ViTMAEPreTrainedModel:()=>qr,ViTMSNForImageClassification:()=>Hr,ViTMSNModel:()=>Ur,ViTMSNPreTrainedModel:()=>Wr,ViTModel:()=>Nr,ViTPreTrainedModel:()=>Lr,VisionEncoderDecoderModel:()=>hn,VitMatteForImageMatting:()=>ei,VitMattePreTrainedModel:()=>Jr,VitsModel:()=>As,VitsModelOutput:()=>kl,VitsPreTrainedModel:()=>Fs,Wav2Vec2BertForCTC:()=>Ja,Wav2Vec2BertForSequenceClassification:()=>es,Wav2Vec2BertModel:()=>Za,Wav2Vec2BertPreTrainedModel:()=>Ya,Wav2Vec2ForAudioFrameClassification:()=>Ba,Wav2Vec2ForCTC:()=>za,Wav2Vec2ForSequenceClassification:()=>Oa,Wav2Vec2Model:()=>Ia,Wav2Vec2PreTrainedModel:()=>Aa,WavLMForAudioFrameClassification:()=>ds,WavLMForCTC:()=>os,WavLMForSequenceClassification:()=>ls,WavLMForXVector:()=>us,WavLMModel:()=>ss,WavLMPreTrainedModel:()=>as,WeSpeakerResNetModel:()=>Va,WeSpeakerResNetPreTrainedModel:()=>Ra,WhisperForConditionalGeneration:()=>pn,WhisperModel:()=>cn,WhisperPreTrainedModel:()=>dn,XLMForQuestionAnswering:()=>Jt,XLMForSequenceClassification:()=>Yt,XLMForTokenClassification:()=>Zt,XLMModel:()=>Kt,XLMPreTrainedModel:()=>Xt,XLMRobertaForMaskedLM:()=>nn,XLMRobertaForQuestionAnswering:()=>sn,XLMRobertaForSequenceClassification:()=>rn,XLMRobertaForTokenClassification:()=>an,XLMRobertaModel:()=>tn,XLMRobertaPreTrainedModel:()=>en,XLMWithLMHeadModel:()=>Qt,XVectorOutput:()=>wl,YolosForObjectDetection:()=>xa,YolosModel:()=>ya,YolosObjectDetectionOutput:()=>va,YolosPreTrainedModel:()=>ba,getPerf:()=>O});var r=n(/*! ./configs.js */"./src/configs.js"),i=n(/*! ./backends/onnx.js */"./src/backends/onnx.js"),a=n(/*! ./utils/dtypes.js */"./src/utils/dtypes.js"),s=n(/*! ./utils/generic.js */"./src/utils/generic.js"),o=n(/*! ./utils/core.js */"./src/utils/core.js"),l=n(/*! ./utils/hub.js */"./src/utils/hub.js"),u=n(/*! ./utils/constants.js */"./src/utils/constants.js"),d=n(/*! ./generation/logits_process.js */"./src/generation/logits_process.js"),c=n(/*! ./generation/configuration_utils.js */"./src/generation/configuration_utils.js"),p=n(/*! ./utils/tensor.js */"./src/utils/tensor.js"),h=n(/*! ./utils/maths.js */"./src/utils/maths.js"),m=n(/*! ./generation/stopping_criteria.js */"./src/generation/stopping_criteria.js"),f=n(/*! ./generation/logits_sampler.js */"./src/generation/logits_sampler.js"),g=n(/*! ./env.js */"./src/env.js"),_=n(/*! ./models/whisper/generation_whisper.js */"./src/models/whisper/generation_whisper.js"),w=n(/*! ./models/whisper/common_whisper.js */"./src/models/whisper/common_whisper.js");const b=0,y=1,x=2,v=3,M=4,T=5,k=6,$=7,C=new Map,S=new Map,P=new Map;async function E(e,t,n){return Object.fromEntries(await Promise.all(Object.keys(t).map((async s=>{const{buffer:o,session_options:u,session_config:d}=await async function(e,t,n){const s=n.config?.["transformers.js_config"]??{};let o=n.device??s.device;o&&"string"!=typeof o&&(o.hasOwnProperty(t)?o=o[t]:(console.warn(`device not specified for "${t}". Using the default device.`),o=null));const u=o??(g.apis.IS_NODE_ENV?"cpu":"wasm"),d=(0,i.deviceToExecutionProviders)(u);let c=n.dtype??s.dtype;"string"!=typeof c&&(c&&c.hasOwnProperty(t)?c=c[t]:(c=a.DEFAULT_DEVICE_DTYPE_MAPPING[u]??a.DATA_TYPES.fp32,console.warn(`dtype not specified for "${t}". Using the default dtype (${c}) for this device (${u}).`)));const p=c;if(!a.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(p))throw new Error(`Invalid dtype: ${p}. Should be one of: ${Object.keys(a.DATA_TYPES).join(", ")}`);if(p===a.DATA_TYPES.fp16&&"webgpu"===u&&!await(0,a.isWebGpuFp16Supported)())throw new Error(`The device (${u}) does not support fp16.`);const h=s.kv_cache_dtype?"string"==typeof s.kv_cache_dtype?s.kv_cache_dtype:s.kv_cache_dtype[p]??"float32":void 0;if(h&&!["float32","float16"].includes(h))throw new Error(`Invalid kv_cache_dtype: ${h}. Should be one of: float32, float16`);const m={dtype:p,kv_cache_dtype:h},f=a.DEFAULT_DTYPE_SUFFIX_MAPPING[p],_=`${n.subfolder??""}/${t}${f}.onnx`,w={...n.session_options};w.executionProviders??=d;const b=s.free_dimension_overrides;b?w.freeDimensionOverrides??=b:u.startsWith("webnn")&&!w.freeDimensionOverrides&&console.warn('WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.');const y=(0,l.getModelFile)(e,_,!0,n),x=n.use_external_data_format??s.use_external_data_format;let v=[];if(x&&(!0===x||"object"==typeof x&&x.hasOwnProperty(t)&&!0===x[t])){if(g.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const r=`${t}${f}.onnx_data`,i=`${n.subfolder??""}/${r}`;v.push(new Promise((async(t,a)=>{const s=await(0,l.getModelFile)(e,i,!0,n);t({path:r,data:s})})))}else void 0!==w.externalData&&(v=w.externalData.map((async t=>{if("string"==typeof t.data){const r=await(0,l.getModelFile)(e,t.data,!0,n);return{...t,data:r}}return t})));if(v.length>0&&(w.externalData=await Promise.all(v)),"webgpu"===u){const e=(0,r.getKeyValueShapes)(n.config,{prefix:"present"});if(Object.keys(e).length>0&&!(0,i.isONNXProxy)()){const t={};for(const n in e)t[n]="gpu-buffer";w.preferredOutputLocation=t}}return{buffer:await y,session_options:w,session_config:m}}(e,t[s],n);return[s,await(0,i.createInferenceSession)(o,u,d)]}))))}async function F(e,t,n){return Object.fromEntries(await Promise.all(Object.keys(t).map((async r=>[r,await(0,l.getModelJSON)(e,t[r],!1,n)]))))}const A=e=>new URLSearchParams(window.location.search).get(e);let I=1,z={warmup:0,inference:[],throughput:0};function O(){return z}async function B(e,t){z={warmup:0,inference:[],throughput:0};const n=function(e,t){const n=Object.create(null),r=[];for(const a of e.inputNames){const e=t[a];e instanceof p.Tensor?n[a]=(0,i.isONNXProxy)()?e.clone():e:r.push(a)}if(r.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${r.join(", ")}.`);const a=Object.keys(t).length,s=e.inputNames.length;if(a>s){let n=Object.keys(t).filter((t=>!e.inputNames.includes(t)));console.warn(`WARNING: Too many inputs were provided (${a} > ${s}). The following inputs will be ignored: "${n.join(", ")}".`)}return n}(e,t);try{const t=Object.fromEntries(Object.entries(n).map((([e,t])=>[e,t.ort_tensor])));let r,i=1;console.log("-- number of test runs --"),I=A("run")?parseInt(A("run")):1,console.log(I);let a,s,o=performance.now(),l=[];for(let n=0;nt.length!==e[0].length)))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new p.Tensor("int64",BigInt64Array.from(e.flat().map((e=>BigInt(e)))),[e.length,e[0].length])}return new p.Tensor("int64",BigInt64Array.from(e.map((e=>BigInt(e)))),[1,e.length])}function D(e){return new p.Tensor("bool",[e],[1])}async function R(e,t){let{encoder_outputs:n,input_ids:r,decoder_input_ids:i,...a}=t;if(!n){const r=(0,o.pick)(t,e.sessions.model.inputNames);n=(await V(e,r)).last_hidden_state}a.input_ids=i,a.encoder_hidden_states=n,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(a.encoder_attention_mask=t.attention_mask);return await j(e,a,!0)}async function V(e,t){const n=e.sessions.model,r=(0,o.pick)(t,n.inputNames);if(n.inputNames.includes("inputs_embeds")&&!r.inputs_embeds){if(!t.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");r.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}return n.inputNames.includes("token_type_ids")&&!r.token_type_ids&&(r.token_type_ids=new p.Tensor("int64",new BigInt64Array(r.input_ids.data.length),r.input_ids.dims)),await B(n,r)}async function j(e,t,n=!1){const r=e.sessions[n?"decoder_model_merged":"model"],{past_key_values:i,...a}=t;r.inputNames.includes("use_cache_branch")&&(a.use_cache_branch=D(!!i)),r.inputNames.includes("position_ids")&&a.attention_mask&&!a.position_ids&&(a.position_ids=function(e,t=null){const{input_ids:n,inputs_embeds:r,attention_mask:i}=e,[a,s]=i.dims,o=new BigInt64Array(i.data.length);for(let e=0;er.dims[1]);else if(tt==e.config.image_token_index))){const i=e.config.num_image_tokens;if(!i)throw new Error("`num_image_tokens` is missing in the model configuration.");const a=r.dims[1]-(t-i);n.input_ids=r.slice(null,[-a,null]),n.attention_mask=(0,p.ones)([1,t+a])}}return n}function W(e,t,n,r){return n.past_key_values&&(t=t.map((e=>[e.at(-1)]))),{...n,decoder_input_ids:N(t)}}function U(e,...t){return e.config.is_encoder_decoder?W(e,...t):G(e,...t)}class H extends s.Callable{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(e,t,n){super(),this.config=e,this.sessions=t,this.configs=n;const r=P.get(this.constructor),i=C.get(r);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,i){case M:this.can_generate=!0,this._forward=j,this._prepare_inputs_for_generation=G;break;case x:case v:case $:this.can_generate=!0,this._forward=R,this._prepare_inputs_for_generation=W;break;case y:this._forward=R;break;case k:this.can_generate=!0,this._forward=q,this._prepare_inputs_for_generation=U;break;default:this._forward=V}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const e=[];for(const t of Object.values(this.sessions))t?.handler?.dispose&&e.push(t.handler.dispose());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:i=null,local_files_only:a=!1,revision:s="main",model_file_name:o=null,subfolder:l="onnx",device:d=null,dtype:c=null,use_external_data_format:p=null,session_options:h={}}={}){let m={progress_callback:t,config:n,cache_dir:i,local_files_only:a,revision:s,model_file_name:o,subfolder:l,device:d,dtype:c,use_external_data_format:p,session_options:h};const f=P.get(this),g=C.get(f);let _;if(n=m.config=await r.AutoConfig.from_pretrained(e,m),g===M)_=await Promise.all([E(e,{model:m.model_file_name??"model"},m),F(e,{generation_config:"generation_config.json"},m)]);else if(g===x||g===v)_=await Promise.all([E(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},m),F(e,{generation_config:"generation_config.json"},m)]);else if(g===T)_=await Promise.all([E(e,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},m)]);else if(g===y)_=await Promise.all([E(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},m)]);else if(g===k){const t={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};n.is_encoder_decoder&&(t.model="encoder_model"),_=await Promise.all([E(e,t,m),F(e,{generation_config:"generation_config.json"},m)])}else g===$?_=await Promise.all([E(e,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},m),F(e,{generation_config:"generation_config.json"},m)]):(g!==b&&console.warn(`Model type for '${f??n?.model_type}' not found, assuming encoder-only architecture. Please report this at ${u.GITHUB_ISSUE_URL}.`),_=await Promise.all([E(e,{model:m.model_file_name??"model"},m)]));return new this(n,..._)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_warper(e){const t=new d.LogitsProcessorList;return null!==e.temperature&&1!==e.temperature&&t.push(new d.TemperatureLogitsWarper(e.temperature)),null!==e.top_k&&0!==e.top_k&&t.push(new d.TopKLogitsWarper(e.top_k)),null!==e.top_p&&e.top_p<1&&t.push(new d.TopPLogitsWarper(e.top_p)),t}_get_logits_processor(e,t,n=null){const r=new d.LogitsProcessorList;if(null!==e.repetition_penalty&&1!==e.repetition_penalty&&r.push(new d.RepetitionPenaltyLogitsProcessor(e.repetition_penalty)),null!==e.no_repeat_ngram_size&&e.no_repeat_ngram_size>0&&r.push(new d.NoRepeatNGramLogitsProcessor(e.no_repeat_ngram_size)),null!==e.bad_words_ids&&r.push(new d.NoBadWordsLogitsProcessor(e.bad_words_ids,e.eos_token_id)),null!==e.min_length&&null!==e.eos_token_id&&e.min_length>0&&r.push(new d.MinLengthLogitsProcessor(e.min_length,e.eos_token_id)),null!==e.min_new_tokens&&null!==e.eos_token_id&&e.min_new_tokens>0&&r.push(new d.MinNewTokensLengthLogitsProcessor(t,e.min_new_tokens,e.eos_token_id)),null!==e.forced_bos_token_id&&r.push(new d.ForcedBOSTokenLogitsProcessor(e.forced_bos_token_id)),null!==e.forced_eos_token_id&&r.push(new d.ForcedEOSTokenLogitsProcessor(e.max_length,e.forced_eos_token_id)),null!==e.begin_suppress_tokens){const n=t>1||null===e.forced_bos_token_id?t:t+1;r.push(new d.SuppressTokensAtBeginLogitsProcessor(e.begin_suppress_tokens,n))}return null!==e.guidance_scale&&e.guidance_scale>1&&r.push(new d.ClassifierFreeGuidanceLogitsProcessor(e.guidance_scale)),null!==n&&r.extend(n),r}_prepare_generation_config(e,t,n=c.GenerationConfig){const r={...this.config};for(const e of["decoder","generator","text_config"])e in r&&Object.assign(r,r[e]);const i=new n(r);return Object.assign(i,this.generation_config??{}),e&&Object.assign(i,e),t&&Object.assign(i,(0,o.pick)(t,Object.getOwnPropertyNames(i))),i}_get_stopping_criteria(e,t=null){const n=new m.StoppingCriteriaList;return null!==e.max_length&&n.push(new m.MaxLengthCriteria(e.max_length,this.config.max_position_embeddings??null)),null!==e.eos_token_id&&n.push(new m.EosTokenCriteria(e.eos_token_id)),t&&n.extend(t),n}_validate_model_class(){if(!this.can_generate){const e=[wo,xo,_o,po],t=P.get(this.constructor),n=new Set,r=this.config.model_type;for(const t of e){const e=t.get(r);e&&n.add(e[0])}let i=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw n.size>0&&(i+=` Please use the following class instead: ${[...n].join(", ")}`),Error(i)}}prepare_inputs_for_generation(...e){return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:n,is_encoder_decoder:r}){return n.past_key_values=this.getPastKeyValues(t,n.past_key_values),n.input_ids=new p.Tensor("int64",e.flat(),[e.length,1]),r||(n.attention_mask=(0,p.cat)([n.attention_mask,(0,p.ones)([n.attention_mask.dims[0],1])],1)),n.position_ids=null,n}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:n}){const r=(0,o.pick)(n,this.forward_params),i=this.main_input_name;if(i in r){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else r[i]=e;return{inputs_tensor:r[i],model_inputs:r,model_input_name:i}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:n,generation_config:r}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!t.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:e,pixel_values:n,attention_mask:r,...i}=t,a=await this._prepare_inputs_embeds(t);t={...i,...(0,o.pick)(a,["inputs_embeds","attention_mask"])}}let{last_hidden_state:i}=await V(this,t);if(null!==r.guidance_scale&&r.guidance_scale>1)i=(0,p.cat)([i,(0,p.full_like)(i,0)],0),"attention_mask"in t&&(t.attention_mask=(0,p.cat)([t.attention_mask,(0,p.zeros_like)(t.attention_mask)],0));else if(t.decoder_input_ids){const e=N(t.decoder_input_ids).dims[0];if(e!==i.dims[0]){if(1!==i.dims[0])throw new Error(`The encoder outputs have a different batch size (${i.dims[0]}) than the decoder inputs (${e}).`);i=(0,p.cat)(Array.from({length:e},(()=>i)),0)}}return t.encoder_outputs=i,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:n,decoder_start_token_id:r,bos_token_id:i,generation_config:a}){let{decoder_input_ids:s,...o}=n;if(s)Array.isArray(s[0])||(s=Array.from({length:e},(()=>s)));else if(r??=i,"musicgen"===this.config.model_type)s=Array.from({length:e*this.config.decoder.num_codebooks},(()=>[r]));else if(Array.isArray(r)){if(r.length!==e)throw new Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${r.length}`);s=r}else s=Array.from({length:e},(()=>[r]));return s=N(s),n.decoder_attention_mask=(0,p.ones_like)(s),{input_ids:s,model_inputs:o}}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,streamer:i=null,...a}){this._validate_model_class(),t=this._prepare_generation_config(t,a);let{inputs_tensor:s,model_inputs:o,model_input_name:l}=this._prepare_model_inputs({inputs:e,model_kwargs:a});const u=this.config.is_encoder_decoder;let d;u&&("encoder_outputs"in o||(o=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:s,model_inputs:o,model_input_name:l,generation_config:t}))),u?({input_ids:d,model_inputs:o}=this._prepare_decoder_input_ids_for_generation({batch_size:o[l].dims.at(0),model_input_name:l,model_kwargs:o,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t})):d=o[l];let c=d.dims.at(-1);null!==t.max_new_tokens&&(t.max_length=c+t.max_new_tokens);const h=this._get_logits_processor(t,c,n),m=this._get_stopping_criteria(t,r),g=o[l].dims.at(0),_=f.LogitsSampler.getSampler(t),w=new Array(g).fill(0),b=d.tolist();let y;i&&i.put(b);let x={};for(;;){if(o=this.prepare_inputs_for_generation(b,o,t),y=await this.forward(o),t.output_attentions&&t.return_dict_in_generate){const e=this.getAttentions(y);for(const t in e)t in x||(x[t]=[]),x[t].push(e[t])}const e=h(b,y.logits.slice(null,-1,null)),n=[];for(let t=0;te)))break;o=this._update_model_kwargs_for_generation({generated_input_ids:n,outputs:y,model_inputs:o,is_encoder_decoder:u})}i&&i.end();const v=this.getPastKeyValues(y,o.past_key_values,!0),M=new p.Tensor("int64",b.flat(),[b.length,b[0].length]);if(t.return_dict_in_generate)return{sequences:M,past_key_values:v,...x};for(const e of Object.values(y))"gpu-buffer"===e.location&&e.dispose();return M}getPastKeyValues(e,t,n=!1){const r=Object.create(null);for(const i in e)if(i.startsWith("present")){const a=i.replace("present","past_key_values"),s=i.includes("encoder");if(r[a]=s&&t?t[a]:e[i],t&&(!s||n)){const e=t[a];"gpu-buffer"===e.location&&e.dispose()}}return r}getAttentions(e){const t={};for(const n of["cross_attentions","encoder_attentions","decoder_attentions"])for(const r in e)r.startsWith(n)&&(n in t||(t[n]=[]),t[n].push(e[r]));return t}addPastKeyValues(e,t){if(t)Object.assign(e,t);else{const t=this.sessions.decoder_model_merged??this.sessions.model,n=t?.config?.kv_cache_dtype??"float32",i="float16"===n?new Uint16Array:[],a=(0,r.getKeyValueShapes)(this.config);for(const t in a)e[t]=new p.Tensor(n,i,a[t])}}async encode_image({pixel_values:e}){const t=(await B(this.sessions.vision_encoder,{pixel_values:e})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${t.dims[1]}).`),this.config.num_image_tokens=t.dims[1]),t}async encode_text({input_ids:e}){return(await B(this.sessions.embed_tokens,{input_ids:e})).inputs_embeds}}class X{}class K extends X{constructor({last_hidden_state:e,hidden_states:t=null,attentions:n=null}){super(),this.last_hidden_state=e,this.hidden_states=t,this.attentions=n}}class Q extends H{}class Y extends Q{}class Z extends Q{async _call(e){return new yl(await super._call(e))}}class J extends Q{async _call(e){return new _l(await super._call(e))}}class ee extends Q{async _call(e){return new bl(await super._call(e))}}class te extends Q{async _call(e){return new xl(await super._call(e))}}class ne extends H{}class re extends ne{}class ie extends H{}class ae extends ie{}class se extends ie{async _call(e){return new yl(await super._call(e))}}class oe extends ie{async _call(e){return new _l(await super._call(e))}}class le extends ie{async _call(e){return new bl(await super._call(e))}}class ue extends ie{async _call(e){return new xl(await super._call(e))}}class de extends H{}class ce extends de{}class pe extends de{async _call(e){return new yl(await super._call(e))}}class he extends de{async _call(e){return new _l(await super._call(e))}}class me extends de{async _call(e){return new bl(await super._call(e))}}class fe extends de{async _call(e){return new xl(await super._call(e))}}class ge extends H{}class _e extends ge{}class we extends ge{async _call(e){return new yl(await super._call(e))}}class be extends ge{async _call(e){return new _l(await super._call(e))}}class ye extends ge{async _call(e){return new bl(await super._call(e))}}class xe extends ge{async _call(e){return new xl(await super._call(e))}}class ve extends H{}class Me extends ve{}class Te extends ve{async _call(e){return new yl(await super._call(e))}}class ke extends ve{async _call(e){return new _l(await super._call(e))}}class $e extends ve{async _call(e){return new bl(await super._call(e))}}class Ce extends ve{async _call(e){return new xl(await super._call(e))}}class Se extends H{}class Pe extends Se{}class Ee extends Se{async _call(e){return new yl(await super._call(e))}}class Fe extends Se{async _call(e){return new _l(await super._call(e))}}class Ae extends Se{async _call(e){return new bl(await super._call(e))}}class Ie extends Se{async _call(e){return new xl(await super._call(e))}}class ze extends H{}class Oe extends ze{}class Be extends ze{async _call(e){return new yl(await super._call(e))}}class Le extends ze{async _call(e){return new _l(await super._call(e))}}class Ne extends ze{async _call(e){return new bl(await super._call(e))}}class De extends ze{async _call(e){return new xl(await super._call(e))}}class Re extends H{}class Ve extends Re{}class je extends Re{async _call(e){return new _l(await super._call(e))}}class qe extends Re{async _call(e){return new bl(await super._call(e))}}class Ge extends Re{async _call(e){return new xl(await super._call(e))}}class We extends Re{async _call(e){return new yl(await super._call(e))}}class Ue extends H{}class He extends Ue{}class Xe extends Ue{async _call(e){return new yl(await super._call(e))}}class Ke extends Ue{async _call(e){return new _l(await super._call(e))}}class Qe extends Ue{async _call(e){return new bl(await super._call(e))}}class Ye extends H{}class Ze extends Ye{}class Je extends Ye{async _call(e){return new yl(await super._call(e))}}class et extends Ye{async _call(e){return new _l(await super._call(e))}}class tt extends Ye{async _call(e){return new xl(await super._call(e))}}class nt extends H{}class rt extends nt{}class it extends nt{async _call(e){return new yl(await super._call(e))}}class at extends nt{async _call(e){return new _l(await super._call(e))}}class st extends nt{async _call(e){return new bl(await super._call(e))}}class ot extends nt{async _call(e){return new xl(await super._call(e))}}class lt extends H{}class ut extends lt{}class dt extends lt{async _call(e){return new yl(await super._call(e))}}class ct extends lt{async _call(e){return new _l(await super._call(e))}}class pt extends lt{async _call(e){return new xl(await super._call(e))}}class ht extends H{}class mt extends ht{}class ft extends ht{async _call(e){return new _l(await super._call(e))}}class gt extends ht{async _call(e){return new xl(await super._call(e))}}class _t extends ht{async _call(e){return new yl(await super._call(e))}}class wt extends H{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]}class bt extends wt{}class yt extends wt{}class xt extends H{}class vt extends xt{}class Mt extends xt{}class Tt extends H{}class kt extends Tt{}class $t extends Tt{}class Ct extends H{}class St extends Ct{}class Pt extends Ct{}class Et extends Ct{async _call(e){return new _l(await super._call(e))}}class Ft extends H{}class At extends Ft{}class It extends Ft{}class zt extends Ft{async _call(e){return new _l(await super._call(e))}}class Ot extends Ft{}class Bt extends H{}class Lt extends Bt{}class Nt extends Bt{}class Dt extends H{}class Rt extends Dt{}class Vt extends Dt{}class jt extends H{}class qt extends jt{}class Gt extends jt{async _call(e){return new yl(await super._call(e))}}class Wt extends jt{async _call(e){return new _l(await super._call(e))}}class Ut extends jt{async _call(e){return new bl(await super._call(e))}}class Ht extends jt{async _call(e){return new xl(await super._call(e))}}class Xt extends H{}class Kt extends Xt{}class Qt extends Xt{async _call(e){return new yl(await super._call(e))}}class Yt extends Xt{async _call(e){return new _l(await super._call(e))}}class Zt extends Xt{async _call(e){return new bl(await super._call(e))}}class Jt extends Xt{async _call(e){return new xl(await super._call(e))}}class en extends H{}class tn extends en{}class nn extends en{async _call(e){return new yl(await super._call(e))}}class rn extends en{async _call(e){return new _l(await super._call(e))}}class an extends en{async _call(e){return new bl(await super._call(e))}}class sn extends en{async _call(e){return new xl(await super._call(e))}}class on extends H{}class ln extends on{}class un extends on{}class dn extends H{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]}class cn extends dn{}class pn extends dn{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,_.WhisperGenerationConfig)}_retrieve_init_tokens(e){const t=[e.decoder_start_token_id];let n=e.language;const r=e.task;if(e.is_multilingual){n||(console.warn("No language specified - defaulting to English (en)."),n="en");const i=`<|${(0,w.whisper_language_to_code)(n)}|>`;t.push(e.lang_to_id[i]),t.push(e.task_to_id[r??"transcribe"])}else if(n||r)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter((e=>null!=e))}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,...i}){t=this._prepare_generation_config(t,i);const a=i.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(n??=new d.LogitsProcessorList,n.push(new d.WhisperTimeStampLogitsProcessor(t,a))),t.begin_suppress_tokens&&(n??=new d.LogitsProcessorList,n.push(new d.SuppressTokensAtBeginLogitsProcessor(t.begin_suppress_tokens,a.length))),t.return_token_timestamps){if(!t.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");"translate"===t.task&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),t.output_attentions=!0,t.return_dict_in_generate=!0}const s=await super.generate({inputs:e,generation_config:t,logits_processor:n,decoder_input_ids:a,...i});return t.return_token_timestamps&&(s.token_timestamps=this._extract_token_timestamps(s,t.alignment_heads,t.num_frames)),s}_extract_token_timestamps(e,t,n=null,r=.02){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");null==n&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let i=this.config.median_filter_width;void 0===i&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),i=7);const a=e.cross_attentions,s=Array.from({length:this.config.decoder_layers},((e,t)=>(0,p.cat)(a.map((e=>e[t])),2))),l=(0,p.stack)(t.map((([e,t])=>{if(e>=s.length)throw new Error(`Layer index ${e} is out of bounds for cross attentions (length ${s.length}).`);return n?s[e].slice(null,t,null,[0,n]):s[e].slice(null,t)}))).transpose(1,0,2,3),[u,d]=(0,p.std_mean)(l,-2,0,!0),c=l.clone();for(let e=0;en[t+1]-n[t])),s=(0,o.mergeArrays)([1],a).map((e=>!!e)),l=[];for(let e=0;ee.findIndex((e=>e==i)))),s=a.every((e=>-1===e)),o=a.every((e=>-1!==e));if(!s&&!o)throw new Error("Every input should contain either 0 or 1 image token.");if(s)return{inputs_embeds:e,attention_mask:r};const l=[],u=[];for(let n=0;ne*t),1);e.input_labels=new p.Tensor("int64",new BigInt64Array(n).fill(1n),t)}const t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(t.input_points=e.input_points),e.input_labels&&(t.input_labels=e.input_labels),e.input_boxes&&(t.input_boxes=e.input_boxes),await B(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new ka(await super._call(e))}}class ka extends X{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}}class $a extends H{}class Ca extends $a{}class Sa extends $a{}class Pa extends H{}class Ea extends Pa{}class Fa extends Pa{}class Aa extends H{}class Ia extends Aa{}class za extends Aa{async _call(e){return new vl(await super._call(e))}}class Oa extends Aa{async _call(e){return new _l(await super._call(e))}}class Ba extends Aa{async _call(e){return new bl(await super._call(e))}}class La extends H{}class Na extends La{}class Da extends La{async _call(e){return new bl(await super._call(e))}}class Ra extends H{}class Va extends Ra{}class ja extends H{}class qa extends ja{}class Ga extends ja{async _call(e){return new vl(await super._call(e))}}class Wa extends ja{async _call(e){return new _l(await super._call(e))}}class Ua extends H{}class Ha extends Ua{}class Xa extends Ua{async _call(e){return new vl(await super._call(e))}}class Ka extends Ua{async _call(e){return new _l(await super._call(e))}}class Qa extends Ua{async _call(e){return new bl(await super._call(e))}}class Ya extends H{}class Za extends Ya{}class Ja extends Ya{async _call(e){return new vl(await super._call(e))}}class es extends Ya{async _call(e){return new _l(await super._call(e))}}class ts extends H{}class ns extends Aa{}class rs extends Aa{async _call(e){return new vl(await super._call(e))}}class is extends Aa{async _call(e){return new _l(await super._call(e))}}class as extends H{}class ss extends as{}class os extends as{async _call(e){return new vl(await super._call(e))}}class ls extends as{async _call(e){return new _l(await super._call(e))}}class us extends as{async _call(e){return new wl(await super._call(e))}}class ds extends as{async _call(e){return new bl(await super._call(e))}}class cs extends H{}class ps extends cs{}class hs extends cs{}class ms extends cs{async generate_speech(e,t,{threshold:n=.5,minlenratio:r=0,maxlenratio:i=20,vocoder:a=null}={}){const s={input_ids:e},{encoder_outputs:o,encoder_attention_mask:l}=await V(this,s),u=o.dims[1]/this.config.reduction_factor,d=Math.floor(u*i),c=Math.floor(u*r),h=this.config.num_mel_bins;let m=[],f=null,g=null,_=0;for(;;){++_;const e=D(!!g);let r;r=g?g.output_sequence_out:new p.Tensor("float32",new Float32Array(h),[1,1,h]);let i={use_cache_branch:e,output_sequence:r,encoder_attention_mask:l,speaker_embeddings:t,encoder_hidden_states:o};this.addPastKeyValues(i,f),g=await B(this.sessions.decoder_model_merged,i),f=this.getPastKeyValues(g,f);const{prob:a,spectrum:s}=g;if(m.push(s),_>=c&&(Array.from(a.data).filter((e=>e>=n)).length>0||_>=d))break}const w=(0,p.cat)(m),{waveform:b}=await B(a.sessions.model,{spectrogram:w});return{spectrogram:w,waveform:b}}}class fs extends H{main_input_name="spectrogram"}class gs extends H{}class _s extends gs{}class ws extends H{}class bs extends ws{}class ys extends ws{}class xs extends H{}class vs extends xs{}class Ms extends xs{}class Ts extends H{}class ks extends Ts{}class $s extends Ts{}class Cs extends H{}class Ss extends Cs{}class Ps extends Cs{static async from_pretrained(e,t={}){return t.model_file_name??="text_model",super.from_pretrained(e,t)}}class Es extends Cs{static async from_pretrained(e,t={}){return t.model_file_name??="audio_model",super.from_pretrained(e,t)}}class Fs extends H{}class As extends Fs{async _call(e){return new kl(await super._call(e))}}class Is extends H{}class zs extends Is{}class Os extends Is{}class Bs extends Is{}class Ls extends H{}class Ns extends Ls{}class Ds extends Ls{}class Rs extends H{}class Vs extends Rs{}class js extends Rs{async _call(e){return new _l(await super._call(e))}}class qs extends H{}class Gs extends qs{}class Ws extends qs{}class Us extends H{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(e){const[t,n]=e.dims,r=this.config.decoder.num_codebooks,i=n-r;let a=0;for(let t=0;t0&&s<=i&&(e.data[a++]=e.data[t])}const s=Math.floor(t/r),o=a/(s*r);return new p.Tensor(e.type,e.data.slice(0,a),[s,r,o])}prepare_inputs_for_generation(e,t,n){let r=structuredClone(e);for(let e=0;e=t&&(r[e][t]=BigInt(this.config.decoder.pad_token_id));null!==n.guidance_scale&&n.guidance_scale>1&&(r=r.concat(r));return super.prepare_inputs_for_generation(r,t,n)}async generate(e){const t=await super.generate(e),n=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:r}=await B(this.sessions.encodec_decode,{audio_codes:n});return r}}class Hs extends H{}class Xs extends Hs{}class Ks extends Hs{async _call(e){return new _l(await super._call(e))}}class Qs extends H{}class Ys extends Qs{}class Zs extends Qs{async _call(e){return new _l(await super._call(e))}}class Js extends H{}class eo extends Js{}class to extends Js{async _call(e){return new _l(await super._call(e))}}class no extends H{}class ro extends no{}class io extends no{async _call(e){return new _l(await super._call(e))}}class ao extends H{}class so extends ao{}class oo{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:i=null,local_files_only:a=!1,revision:s="main",model_file_name:o=null,subfolder:l="onnx",device:u=null,dtype:d=null,use_external_data_format:c=null,session_options:p={}}={}){const h={progress_callback:t,config:n,cache_dir:i,local_files_only:a,revision:s,model_file_name:o,subfolder:l,device:u,dtype:d,use_external_data_format:c,session_options:p};if(h.config=await r.AutoConfig.from_pretrained(e,h),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const t of this.MODEL_CLASS_MAPPINGS){const n=t.get(h.config.model_type);if(n)return await n[1].from_pretrained(e,h)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${h.config.model_type}", attempting to construct from base class.`),await H.from_pretrained(e,h);throw Error(`Unsupported model type: ${h.config.model_type}`)}}const lo=new Map([["bert",["BertModel",Y]],["nomic_bert",["NomicBertModel",re]],["roformer",["RoFormerModel",ae]],["electra",["ElectraModel",_e]],["esm",["EsmModel",He]],["convbert",["ConvBertModel",ce]],["camembert",["CamembertModel",Me]],["deberta",["DebertaModel",Pe]],["deberta-v2",["DebertaV2Model",Oe]],["mpnet",["MPNetModel",rt]],["albert",["AlbertModel",mt]],["distilbert",["DistilBertModel",Ve]],["roberta",["RobertaModel",qt]],["xlm",["XLMModel",Kt]],["xlm-roberta",["XLMRobertaModel",tn]],["clap",["ClapModel",Ss]],["clip",["CLIPModel",yn]],["clipseg",["CLIPSegModel",An]],["chinese_clip",["ChineseCLIPModel",En]],["siglip",["SiglipModel",$n]],["mobilebert",["MobileBertModel",Ze]],["squeezebert",["SqueezeBertModel",ut]],["wav2vec2",["Wav2Vec2Model",Ia]],["wav2vec2-bert",["Wav2Vec2BertModel",Za]],["unispeech",["UniSpeechModel",qa]],["unispeech-sat",["UniSpeechSatModel",Ha]],["hubert",["HubertModel",ns]],["wavlm",["WavLMModel",ss]],["audio-spectrogram-transformer",["ASTModel",ln]],["vits",["VitsModel",As]],["pyannote",["PyAnnoteModel",Na]],["wespeaker-resnet",["WeSpeakerResNetModel",Va]],["detr",["DetrModel",_i]],["rt_detr",["RTDetrModel",Mi]],["table-transformer",["TableTransformerModel",Ci]],["vit",["ViTModel",Nr]],["pvt",["PvtModel",Vr]],["vit_msn",["ViTMSNModel",Ur]],["vit_mae",["ViTMAEModel",Gr]],["groupvit",["GroupViTModel",Kr]],["fastvit",["FastViTModel",Yr]],["mobilevit",["MobileViTModel",ni]],["mobilevitv2",["MobileViTV2Model",ai]],["owlvit",["OwlViTModel",li]],["owlv2",["Owlv2Model",ci]],["beit",["BeitModel",mi]],["deit",["DeiTModel",Fi]],["hiera",["HieraModel",zi]],["convnext",["ConvNextModel",ca]],["convnextv2",["ConvNextV2Model",ma]],["dinov2",["Dinov2Model",_a]],["resnet",["ResNetModel",Li]],["swin",["SwinModel",Ri]],["swin2sr",["Swin2SRModel",qi]],["donut-swin",["DonutSwinModel",ua]],["yolos",["YolosModel",ya]],["dpt",["DPTModel",Ui]],["glpn",["GLPNModel",sa]],["hifigan",["SpeechT5HifiGan",fs]],["efficientnet",["EfficientNetModel",Vs]],["decision_transformer",["DecisionTransformerModel",so]],["mobilenet_v1",["MobileNetV1Model",Xs]],["mobilenet_v2",["MobileNetV2Model",Ys]],["mobilenet_v3",["MobileNetV3Model",eo]],["mobilenet_v4",["MobileNetV4Model",ro]],["maskformer",["MaskFormerModel",ra]]]),uo=new Map([["t5",["T5Model",bt]],["longt5",["LongT5Model",vt]],["mt5",["MT5Model",kt]],["bart",["BartModel",St]],["mbart",["MBartModel",At]],["marian",["MarianModel",Ca]],["whisper",["WhisperModel",cn]],["m2m_100",["M2M100Model",Ea]],["blenderbot",["BlenderbotModel",Lt]],["blenderbot-small",["BlenderbotSmallModel",Rt]]]),co=new Map([["bloom",["BloomModel",Pr]],["jais",["JAISModel",Nn]],["gpt2",["GPT2Model",On]],["gptj",["GPTJModel",Hn]],["gpt_bigcode",["GPTBigCodeModel",Qn]],["gpt_neo",["GPTNeoModel",Vn]],["gpt_neox",["GPTNeoXModel",Gn]],["codegen",["CodeGenModel",Jn]],["llama",["LlamaModel",nr]],["granite",["GraniteModel",ar]],["cohere",["CohereModel",lr]],["gemma",["GemmaModel",cr]],["gemma2",["Gemma2Model",mr]],["openelm",["OpenELMModel",_r]],["qwen2",["Qwen2Model",yr]],["phi",["PhiModel",Mr]],["phi3",["Phi3Model",$r]],["mpt",["MptModel",Ar]],["opt",["OPTModel",Or]],["mistral",["MistralModel",bs]],["starcoder2",["Starcoder2Model",vs]],["falcon",["FalconModel",ks]],["stablelm",["StableLmModel",Ns]]]),po=new Map([["speecht5",["SpeechT5ForSpeechToText",hs]],["whisper",["WhisperForConditionalGeneration",pn]]]),ho=new Map([["speecht5",["SpeechT5ForTextToSpeech",ms]]]),mo=new Map([["vits",["VitsModel",As]],["musicgen",["MusicgenForConditionalGeneration",Us]]]),fo=new Map([["bert",["BertForSequenceClassification",J]],["roformer",["RoFormerForSequenceClassification",oe]],["electra",["ElectraForSequenceClassification",be]],["esm",["EsmForSequenceClassification",Ke]],["convbert",["ConvBertForSequenceClassification",he]],["camembert",["CamembertForSequenceClassification",ke]],["deberta",["DebertaForSequenceClassification",Fe]],["deberta-v2",["DebertaV2ForSequenceClassification",Le]],["mpnet",["MPNetForSequenceClassification",at]],["albert",["AlbertForSequenceClassification",ft]],["distilbert",["DistilBertForSequenceClassification",je]],["roberta",["RobertaForSequenceClassification",Wt]],["xlm",["XLMForSequenceClassification",Yt]],["xlm-roberta",["XLMRobertaForSequenceClassification",rn]],["bart",["BartForSequenceClassification",Et]],["mbart",["MBartForSequenceClassification",zt]],["mobilebert",["MobileBertForSequenceClassification",et]],["squeezebert",["SqueezeBertForSequenceClassification",ct]]]),go=new Map([["bert",["BertForTokenClassification",ee]],["roformer",["RoFormerForTokenClassification",le]],["electra",["ElectraForTokenClassification",ye]],["esm",["EsmForTokenClassification",Qe]],["convbert",["ConvBertForTokenClassification",me]],["camembert",["CamembertForTokenClassification",$e]],["deberta",["DebertaForTokenClassification",Ae]],["deberta-v2",["DebertaV2ForTokenClassification",Ne]],["mpnet",["MPNetForTokenClassification",st]],["distilbert",["DistilBertForTokenClassification",qe]],["roberta",["RobertaForTokenClassification",Ut]],["xlm",["XLMForTokenClassification",Zt]],["xlm-roberta",["XLMRobertaForTokenClassification",an]]]),_o=new Map([["t5",["T5ForConditionalGeneration",yt]],["longt5",["LongT5ForConditionalGeneration",Mt]],["mt5",["MT5ForConditionalGeneration",$t]],["bart",["BartForConditionalGeneration",Pt]],["mbart",["MBartForConditionalGeneration",It]],["marian",["MarianMTModel",Sa]],["m2m_100",["M2M100ForConditionalGeneration",Fa]],["blenderbot",["BlenderbotForConditionalGeneration",Nt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Vt]]]),wo=new Map([["bloom",["BloomForCausalLM",Er]],["gpt2",["GPT2LMHeadModel",Bn]],["jais",["JAISLMHeadModel",Dn]],["gptj",["GPTJForCausalLM",Xn]],["gpt_bigcode",["GPTBigCodeForCausalLM",Yn]],["gpt_neo",["GPTNeoForCausalLM",jn]],["gpt_neox",["GPTNeoXForCausalLM",Wn]],["codegen",["CodeGenForCausalLM",er]],["llama",["LlamaForCausalLM",rr]],["granite",["GraniteForCausalLM",sr]],["cohere",["CohereForCausalLM",ur]],["gemma",["GemmaForCausalLM",pr]],["gemma2",["Gemma2ForCausalLM",fr]],["openelm",["OpenELMForCausalLM",wr]],["qwen2",["Qwen2ForCausalLM",xr]],["phi",["PhiForCausalLM",Tr]],["phi3",["Phi3ForCausalLM",Cr]],["mpt",["MptForCausalLM",Ir]],["opt",["OPTForCausalLM",Br]],["mbart",["MBartForCausalLM",Ot]],["mistral",["MistralForCausalLM",ys]],["starcoder2",["Starcoder2ForCausalLM",Ms]],["falcon",["FalconForCausalLM",$s]],["trocr",["TrOCRForCausalLM",_s]],["stablelm",["StableLmForCausalLM",Ds]]]),bo=new Map([["bert",["BertForMaskedLM",Z]],["roformer",["RoFormerForMaskedLM",se]],["electra",["ElectraForMaskedLM",we]],["esm",["EsmForMaskedLM",Xe]],["convbert",["ConvBertForMaskedLM",pe]],["camembert",["CamembertForMaskedLM",Te]],["deberta",["DebertaForMaskedLM",Ee]],["deberta-v2",["DebertaV2ForMaskedLM",Be]],["mpnet",["MPNetForMaskedLM",it]],["albert",["AlbertForMaskedLM",_t]],["distilbert",["DistilBertForMaskedLM",We]],["roberta",["RobertaForMaskedLM",Gt]],["xlm",["XLMWithLMHeadModel",Qt]],["xlm-roberta",["XLMRobertaForMaskedLM",nn]],["mobilebert",["MobileBertForMaskedLM",Je]],["squeezebert",["SqueezeBertForMaskedLM",dt]]]),yo=new Map([["bert",["BertForQuestionAnswering",te]],["roformer",["RoFormerForQuestionAnswering",ue]],["electra",["ElectraForQuestionAnswering",xe]],["convbert",["ConvBertForQuestionAnswering",fe]],["camembert",["CamembertForQuestionAnswering",Ce]],["deberta",["DebertaForQuestionAnswering",Ie]],["deberta-v2",["DebertaV2ForQuestionAnswering",De]],["mpnet",["MPNetForQuestionAnswering",ot]],["albert",["AlbertForQuestionAnswering",gt]],["distilbert",["DistilBertForQuestionAnswering",Ge]],["roberta",["RobertaForQuestionAnswering",Ht]],["xlm",["XLMForQuestionAnswering",Jt]],["xlm-roberta",["XLMRobertaForQuestionAnswering",sn]],["mobilebert",["MobileBertForQuestionAnswering",tt]],["squeezebert",["SqueezeBertForQuestionAnswering",pt]]]),xo=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",hn]]]),vo=new Map([["llava",["LlavaForConditionalGeneration",fn]],["moondream1",["Moondream1ForConditionalGeneration",gn]],["florence2",["Florence2ForConditionalGeneration",wn]]]),Mo=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",hn]]]),To=new Map([["vit",["ViTForImageClassification",Dr]],["pvt",["PvtForImageClassification",jr]],["vit_msn",["ViTMSNForImageClassification",Hr]],["fastvit",["FastViTForImageClassification",Zr]],["mobilevit",["MobileViTForImageClassification",ri]],["mobilevitv2",["MobileViTV2ForImageClassification",si]],["beit",["BeitForImageClassification",fi]],["deit",["DeiTForImageClassification",Ai]],["hiera",["HieraForImageClassification",Oi]],["convnext",["ConvNextForImageClassification",pa]],["convnextv2",["ConvNextV2ForImageClassification",fa]],["dinov2",["Dinov2ForImageClassification",wa]],["resnet",["ResNetForImageClassification",Ni]],["swin",["SwinForImageClassification",Vi]],["segformer",["SegformerForImageClassification",Os]],["efficientnet",["EfficientNetForImageClassification",js]],["mobilenet_v1",["MobileNetV1ForImageClassification",Ks]],["mobilenet_v2",["MobileNetV2ForImageClassification",Zs]],["mobilenet_v3",["MobileNetV3ForImageClassification",to]],["mobilenet_v4",["MobileNetV4ForImageClassification",io]]]),ko=new Map([["detr",["DetrForObjectDetection",wi]],["rt_detr",["RTDetrForObjectDetection",Ti]],["table-transformer",["TableTransformerForObjectDetection",Si]],["yolos",["YolosForObjectDetection",xa]]]),$o=new Map([["owlvit",["OwlViTForObjectDetection",ui]],["owlv2",["Owlv2ForObjectDetection",pi]]]),Co=new Map([["detr",["DetrForSegmentation",bi]],["clipseg",["CLIPSegForImageSegmentation",In]]]),So=new Map([["segformer",["SegformerForSemanticSegmentation",Bs]],["sapiens",["SapiensForSemanticSegmentation",Yi]]]),Po=new Map([["detr",["DetrForSegmentation",bi]],["maskformer",["MaskFormerForInstanceSegmentation",ia]]]),Eo=new Map([["sam",["SamModel",Ta]]]),Fo=new Map([["wav2vec2",["Wav2Vec2ForCTC",za]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Ja]],["unispeech",["UniSpeechForCTC",Ga]],["unispeech-sat",["UniSpeechSatForCTC",Xa]],["wavlm",["WavLMForCTC",os]],["hubert",["HubertForCTC",rs]]]),Ao=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Oa]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",es]],["unispeech",["UniSpeechForSequenceClassification",Wa]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Ka]],["wavlm",["WavLMForSequenceClassification",ls]],["hubert",["HubertForSequenceClassification",is]],["audio-spectrogram-transformer",["ASTForAudioClassification",un]]]),Io=new Map([["wavlm",["WavLMForXVector",us]]]),zo=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Qa]],["wavlm",["WavLMForAudioFrameClassification",ds]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Ba]],["pyannote",["PyAnnoteForAudioFrameClassification",Da]]]),Oo=new Map([["vitmatte",["VitMatteForImageMatting",ei]]]),Bo=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Gi]]]),Lo=new Map([["dpt",["DPTForDepthEstimation",Hi]],["depth_anything",["DepthAnythingForDepthEstimation",Ki]],["glpn",["GLPNForDepthEstimation",oa]],["sapiens",["SapiensForDepthEstimation",Zi]],["depth_pro",["DepthProForDepthEstimation",ta]]]),No=new Map([["sapiens",["SapiensForNormalEstimation",Ji]]]),Do=new Map([["clip",["CLIPVisionModelWithProjection",Tn]],["siglip",["SiglipVisionModel",Sn]]]),Ro=[[lo,b],[uo,y],[co,M],[fo,b],[go,b],[_o,x],[po,x],[wo,M],[bo,b],[yo,b],[xo,v],[vo,k],[To,b],[Co,b],[Po,b],[So,b],[Oo,b],[Bo,b],[Lo,b],[No,b],[ko,b],[$o,b],[Eo,T],[Fo,b],[Ao,b],[ho,x],[mo,b],[Io,b],[zo,b],[Do,b]];for(const[e,t]of Ro)for(const[n,r]of e.values())C.set(n,t),P.set(r,n),S.set(n,r);const Vo=[["MusicgenForConditionalGeneration",Us,$],["CLIPTextModelWithProjection",vn,b],["SiglipTextModel",Cn,b],["ClapTextModelWithProjection",Ps,b],["ClapAudioModelWithProjection",Es,b]];for(const[e,t,n]of Vo)C.set(e,n),P.set(t,e),S.set(e,t);class jo extends oo{static MODEL_CLASS_MAPPINGS=Ro.map((e=>e[0]));static BASE_IF_FAIL=!0}class qo extends oo{static MODEL_CLASS_MAPPINGS=[fo]}class Go extends oo{static MODEL_CLASS_MAPPINGS=[go]}class Wo extends oo{static MODEL_CLASS_MAPPINGS=[_o]}class Uo extends oo{static MODEL_CLASS_MAPPINGS=[po]}class Ho extends oo{static MODEL_CLASS_MAPPINGS=[ho]}class Xo extends oo{static MODEL_CLASS_MAPPINGS=[mo]}class Ko extends oo{static MODEL_CLASS_MAPPINGS=[wo]}class Qo extends oo{static MODEL_CLASS_MAPPINGS=[bo]}class Yo extends oo{static MODEL_CLASS_MAPPINGS=[yo]}class Zo extends oo{static MODEL_CLASS_MAPPINGS=[xo]}class Jo extends oo{static MODEL_CLASS_MAPPINGS=[To]}class el extends oo{static MODEL_CLASS_MAPPINGS=[Co]}class tl extends oo{static MODEL_CLASS_MAPPINGS=[So]}class nl extends oo{static MODEL_CLASS_MAPPINGS=[Po]}class rl extends oo{static MODEL_CLASS_MAPPINGS=[ko]}class il extends oo{static MODEL_CLASS_MAPPINGS=[$o]}class al extends oo{static MODEL_CLASS_MAPPINGS=[Eo]}class sl extends oo{static MODEL_CLASS_MAPPINGS=[Fo]}class ol extends oo{static MODEL_CLASS_MAPPINGS=[Ao]}class ll extends oo{static MODEL_CLASS_MAPPINGS=[Io]}class ul extends oo{static MODEL_CLASS_MAPPINGS=[zo]}class dl extends oo{static MODEL_CLASS_MAPPINGS=[Mo]}class cl extends oo{static MODEL_CLASS_MAPPINGS=[Oo]}class pl extends oo{static MODEL_CLASS_MAPPINGS=[Bo]}class hl extends oo{static MODEL_CLASS_MAPPINGS=[Lo]}class ml extends oo{static MODEL_CLASS_MAPPINGS=[No]}class fl extends oo{static MODEL_CLASS_MAPPINGS=[Do]}class gl extends X{constructor({logits:e,past_key_values:t,encoder_outputs:n,decoder_attentions:r=null,cross_attentions:i=null}){super(),this.logits=e,this.past_key_values=t,this.encoder_outputs=n,this.decoder_attentions=r,this.cross_attentions=i}}class _l extends X{constructor({logits:e}){super(),this.logits=e}}class wl extends X{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}}class bl extends X{constructor({logits:e}){super(),this.logits=e}}class yl extends X{constructor({logits:e}){super(),this.logits=e}}class xl extends X{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}}class vl extends X{constructor({logits:e}){super(),this.logits=e}}class Ml extends X{constructor({logits:e,past_key_values:t}){super(),this.logits=e,this.past_key_values=t}}class Tl extends X{constructor({alphas:e}){super(),this.alphas=e}}class kl extends X{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}}},"./src/models/whisper/common_whisper.js": + \***********************/(e,t,n)=>{n.r(t),n.d(t,{ASTForAudioClassification:()=>un,ASTModel:()=>ln,ASTPreTrainedModel:()=>on,AlbertForMaskedLM:()=>_t,AlbertForQuestionAnswering:()=>gt,AlbertForSequenceClassification:()=>ft,AlbertModel:()=>mt,AlbertPreTrainedModel:()=>ht,AutoModel:()=>jo,AutoModelForAudioClassification:()=>ol,AutoModelForAudioFrameClassification:()=>ul,AutoModelForCTC:()=>sl,AutoModelForCausalLM:()=>Xo,AutoModelForDepthEstimation:()=>hl,AutoModelForDocumentQuestionAnswering:()=>dl,AutoModelForImageClassification:()=>Jo,AutoModelForImageFeatureExtraction:()=>fl,AutoModelForImageMatting:()=>cl,AutoModelForImageSegmentation:()=>el,AutoModelForImageToImage:()=>pl,AutoModelForMaskGeneration:()=>al,AutoModelForMaskedLM:()=>Qo,AutoModelForNormalEstimation:()=>ml,AutoModelForObjectDetection:()=>rl,AutoModelForQuestionAnswering:()=>Yo,AutoModelForSemanticSegmentation:()=>tl,AutoModelForSeq2SeqLM:()=>Uo,AutoModelForSequenceClassification:()=>qo,AutoModelForSpeechSeq2Seq:()=>Wo,AutoModelForTextToSpectrogram:()=>Ho,AutoModelForTextToWaveform:()=>Ko,AutoModelForTokenClassification:()=>Go,AutoModelForUniversalSegmentation:()=>nl,AutoModelForVision2Seq:()=>Zo,AutoModelForXVector:()=>ll,AutoModelForZeroShotObjectDetection:()=>il,BartForConditionalGeneration:()=>Et,BartForSequenceClassification:()=>Pt,BartModel:()=>Ct,BartPretrainedModel:()=>St,BaseModelOutput:()=>X,BeitForImageClassification:()=>fi,BeitModel:()=>mi,BeitPreTrainedModel:()=>hi,BertForMaskedLM:()=>Z,BertForQuestionAnswering:()=>te,BertForSequenceClassification:()=>J,BertForTokenClassification:()=>ee,BertModel:()=>Y,BertPreTrainedModel:()=>Q,BlenderbotForConditionalGeneration:()=>Nt,BlenderbotModel:()=>Lt,BlenderbotPreTrainedModel:()=>Bt,BlenderbotSmallForConditionalGeneration:()=>Vt,BlenderbotSmallModel:()=>Rt,BlenderbotSmallPreTrainedModel:()=>Dt,BloomForCausalLM:()=>Pr,BloomModel:()=>Er,BloomPreTrainedModel:()=>Cr,CLIPModel:()=>yn,CLIPPreTrainedModel:()=>bn,CLIPSegForImageSegmentation:()=>In,CLIPSegModel:()=>An,CLIPSegPreTrainedModel:()=>Fn,CLIPTextModel:()=>xn,CLIPTextModelWithProjection:()=>vn,CLIPVisionModel:()=>Mn,CLIPVisionModelWithProjection:()=>Tn,CamembertForMaskedLM:()=>Te,CamembertForQuestionAnswering:()=>Se,CamembertForSequenceClassification:()=>ke,CamembertForTokenClassification:()=>$e,CamembertModel:()=>Me,CamembertPreTrainedModel:()=>ve,CausalLMOutput:()=>vl,CausalLMOutputWithPast:()=>Ml,ChineseCLIPModel:()=>Pn,ChineseCLIPPreTrainedModel:()=>En,ClapAudioModelWithProjection:()=>Ps,ClapModel:()=>Cs,ClapPreTrainedModel:()=>Ss,ClapTextModelWithProjection:()=>Es,CodeGenForCausalLM:()=>er,CodeGenModel:()=>Jn,CodeGenPreTrainedModel:()=>Zn,CohereForCausalLM:()=>ur,CohereModel:()=>lr,CoherePreTrainedModel:()=>or,ConvBertForMaskedLM:()=>pe,ConvBertForQuestionAnswering:()=>fe,ConvBertForSequenceClassification:()=>he,ConvBertForTokenClassification:()=>me,ConvBertModel:()=>ce,ConvBertPreTrainedModel:()=>de,ConvNextForImageClassification:()=>pa,ConvNextModel:()=>ca,ConvNextPreTrainedModel:()=>da,ConvNextV2ForImageClassification:()=>fa,ConvNextV2Model:()=>ma,ConvNextV2PreTrainedModel:()=>ha,DPTForDepthEstimation:()=>Hi,DPTModel:()=>Wi,DPTPreTrainedModel:()=>Ui,DebertaForMaskedLM:()=>Pe,DebertaForQuestionAnswering:()=>Ie,DebertaForSequenceClassification:()=>Fe,DebertaForTokenClassification:()=>Ae,DebertaModel:()=>Ee,DebertaPreTrainedModel:()=>Ce,DebertaV2ForMaskedLM:()=>Be,DebertaV2ForQuestionAnswering:()=>De,DebertaV2ForSequenceClassification:()=>Le,DebertaV2ForTokenClassification:()=>Ne,DebertaV2Model:()=>Oe,DebertaV2PreTrainedModel:()=>ze,DecisionTransformerModel:()=>so,DecisionTransformerPreTrainedModel:()=>ao,DeiTForImageClassification:()=>Ai,DeiTModel:()=>Fi,DeiTPreTrainedModel:()=>Pi,DepthAnythingForDepthEstimation:()=>Xi,DepthAnythingPreTrainedModel:()=>Ki,DepthProForDepthEstimation:()=>ta,DepthProPreTrainedModel:()=>ea,DetrForObjectDetection:()=>wi,DetrForSegmentation:()=>bi,DetrModel:()=>_i,DetrObjectDetectionOutput:()=>yi,DetrPreTrainedModel:()=>gi,DetrSegmentationOutput:()=>xi,Dinov2ForImageClassification:()=>wa,Dinov2Model:()=>_a,Dinov2PreTrainedModel:()=>ga,DistilBertForMaskedLM:()=>Ue,DistilBertForQuestionAnswering:()=>Ge,DistilBertForSequenceClassification:()=>je,DistilBertForTokenClassification:()=>qe,DistilBertModel:()=>Ve,DistilBertPreTrainedModel:()=>Re,DonutSwinModel:()=>ua,DonutSwinPreTrainedModel:()=>la,EfficientNetForImageClassification:()=>js,EfficientNetModel:()=>Vs,EfficientNetPreTrainedModel:()=>Rs,ElectraForMaskedLM:()=>we,ElectraForQuestionAnswering:()=>xe,ElectraForSequenceClassification:()=>be,ElectraForTokenClassification:()=>ye,ElectraModel:()=>_e,ElectraPreTrainedModel:()=>ge,EsmForMaskedLM:()=>Ke,EsmForSequenceClassification:()=>Xe,EsmForTokenClassification:()=>Qe,EsmModel:()=>He,EsmPreTrainedModel:()=>We,FalconForCausalLM:()=>$s,FalconModel:()=>ks,FalconPreTrainedModel:()=>Ts,FastViTForImageClassification:()=>Zr,FastViTModel:()=>Yr,FastViTPreTrainedModel:()=>Qr,Florence2ForConditionalGeneration:()=>wn,Florence2PreTrainedModel:()=>_n,GLPNForDepthEstimation:()=>oa,GLPNModel:()=>sa,GLPNPreTrainedModel:()=>aa,GPT2LMHeadModel:()=>Bn,GPT2Model:()=>On,GPT2PreTrainedModel:()=>zn,GPTBigCodeForCausalLM:()=>Yn,GPTBigCodeModel:()=>Qn,GPTBigCodePreTrainedModel:()=>Xn,GPTJForCausalLM:()=>Kn,GPTJModel:()=>Hn,GPTJPreTrainedModel:()=>Wn,GPTNeoForCausalLM:()=>jn,GPTNeoModel:()=>Vn,GPTNeoPreTrainedModel:()=>Rn,GPTNeoXForCausalLM:()=>Un,GPTNeoXModel:()=>Gn,GPTNeoXPreTrainedModel:()=>qn,Gemma2ForCausalLM:()=>fr,Gemma2Model:()=>mr,Gemma2PreTrainedModel:()=>hr,GemmaForCausalLM:()=>pr,GemmaModel:()=>cr,GemmaPreTrainedModel:()=>dr,GraniteForCausalLM:()=>sr,GraniteModel:()=>ar,GranitePreTrainedModel:()=>ir,GroupViTModel:()=>Xr,GroupViTPreTrainedModel:()=>Kr,HieraForImageClassification:()=>Oi,HieraModel:()=>zi,HieraPreTrainedModel:()=>Ii,HubertForCTC:()=>rs,HubertForSequenceClassification:()=>is,HubertModel:()=>ns,HubertPreTrainedModel:()=>ts,ImageMattingOutput:()=>Tl,JAISLMHeadModel:()=>Dn,JAISModel:()=>Nn,JAISPreTrainedModel:()=>Ln,LlamaForCausalLM:()=>rr,LlamaModel:()=>nr,LlamaPreTrainedModel:()=>tr,LlavaForConditionalGeneration:()=>fn,LlavaPreTrainedModel:()=>mn,LongT5ForConditionalGeneration:()=>Mt,LongT5Model:()=>vt,LongT5PreTrainedModel:()=>xt,M2M100ForConditionalGeneration:()=>Fa,M2M100Model:()=>Pa,M2M100PreTrainedModel:()=>Ea,MBartForCausalLM:()=>Ot,MBartForConditionalGeneration:()=>It,MBartForSequenceClassification:()=>zt,MBartModel:()=>At,MBartPreTrainedModel:()=>Ft,MPNetForMaskedLM:()=>it,MPNetForQuestionAnswering:()=>ot,MPNetForSequenceClassification:()=>at,MPNetForTokenClassification:()=>st,MPNetModel:()=>rt,MPNetPreTrainedModel:()=>nt,MT5ForConditionalGeneration:()=>$t,MT5Model:()=>kt,MT5PreTrainedModel:()=>Tt,MarianMTModel:()=>Ca,MarianModel:()=>Sa,MarianPreTrainedModel:()=>$a,MaskFormerForInstanceSegmentation:()=>ia,MaskFormerModel:()=>ra,MaskFormerPreTrainedModel:()=>na,MaskedLMOutput:()=>yl,MistralForCausalLM:()=>ys,MistralModel:()=>bs,MistralPreTrainedModel:()=>ws,MobileBertForMaskedLM:()=>Je,MobileBertForQuestionAnswering:()=>tt,MobileBertForSequenceClassification:()=>et,MobileBertModel:()=>Ze,MobileBertPreTrainedModel:()=>Ye,MobileNetV1ForImageClassification:()=>Xs,MobileNetV1Model:()=>Ks,MobileNetV1PreTrainedModel:()=>Hs,MobileNetV2ForImageClassification:()=>Zs,MobileNetV2Model:()=>Ys,MobileNetV2PreTrainedModel:()=>Qs,MobileNetV3ForImageClassification:()=>to,MobileNetV3Model:()=>eo,MobileNetV3PreTrainedModel:()=>Js,MobileNetV4ForImageClassification:()=>io,MobileNetV4Model:()=>ro,MobileNetV4PreTrainedModel:()=>no,MobileViTForImageClassification:()=>ri,MobileViTModel:()=>ni,MobileViTPreTrainedModel:()=>ti,MobileViTV2ForImageClassification:()=>si,MobileViTV2Model:()=>ai,MobileViTV2PreTrainedModel:()=>ii,ModelOutput:()=>K,Moondream1ForConditionalGeneration:()=>gn,MptForCausalLM:()=>Ir,MptModel:()=>Ar,MptPreTrainedModel:()=>Fr,MusicgenForCausalLM:()=>Us,MusicgenForConditionalGeneration:()=>Ws,MusicgenModel:()=>Gs,MusicgenPreTrainedModel:()=>qs,NomicBertModel:()=>re,NomicBertPreTrainedModel:()=>ne,OPTForCausalLM:()=>Br,OPTModel:()=>Or,OPTPreTrainedModel:()=>zr,OpenELMForCausalLM:()=>wr,OpenELMModel:()=>_r,OpenELMPreTrainedModel:()=>gr,OwlViTForObjectDetection:()=>ui,OwlViTModel:()=>li,OwlViTPreTrainedModel:()=>oi,Owlv2ForObjectDetection:()=>pi,Owlv2Model:()=>ci,Owlv2PreTrainedModel:()=>di,Phi3ForCausalLM:()=>Sr,Phi3Model:()=>$r,Phi3PreTrainedModel:()=>kr,PhiForCausalLM:()=>Tr,PhiModel:()=>Mr,PhiPreTrainedModel:()=>vr,PreTrainedModel:()=>H,PretrainedMixin:()=>oo,PvtForImageClassification:()=>jr,PvtModel:()=>Vr,PvtPreTrainedModel:()=>Rr,PyAnnoteForAudioFrameClassification:()=>Da,PyAnnoteModel:()=>Na,PyAnnotePreTrainedModel:()=>La,QuestionAnsweringModelOutput:()=>xl,Qwen2ForCausalLM:()=>xr,Qwen2Model:()=>yr,Qwen2PreTrainedModel:()=>br,RTDetrForObjectDetection:()=>Ti,RTDetrModel:()=>Mi,RTDetrObjectDetectionOutput:()=>ki,RTDetrPreTrainedModel:()=>vi,ResNetForImageClassification:()=>Ni,ResNetModel:()=>Li,ResNetPreTrainedModel:()=>Bi,RoFormerForMaskedLM:()=>se,RoFormerForQuestionAnswering:()=>ue,RoFormerForSequenceClassification:()=>oe,RoFormerForTokenClassification:()=>le,RoFormerModel:()=>ae,RoFormerPreTrainedModel:()=>ie,RobertaForMaskedLM:()=>Gt,RobertaForQuestionAnswering:()=>Ht,RobertaForSequenceClassification:()=>Ut,RobertaForTokenClassification:()=>Wt,RobertaModel:()=>qt,RobertaPreTrainedModel:()=>jt,SamImageSegmentationOutput:()=>ka,SamModel:()=>Ta,SamPreTrainedModel:()=>Ma,SapiensForDepthEstimation:()=>Zi,SapiensForNormalEstimation:()=>Ji,SapiensForSemanticSegmentation:()=>Yi,SapiensPreTrainedModel:()=>Qi,SegformerForImageClassification:()=>Os,SegformerForSemanticSegmentation:()=>Bs,SegformerModel:()=>zs,SegformerPreTrainedModel:()=>Is,Seq2SeqLMOutput:()=>gl,SequenceClassifierOutput:()=>_l,SiglipModel:()=>$n,SiglipPreTrainedModel:()=>kn,SiglipTextModel:()=>Sn,SiglipVisionModel:()=>Cn,SpeechT5ForSpeechToText:()=>hs,SpeechT5ForTextToSpeech:()=>ms,SpeechT5HifiGan:()=>fs,SpeechT5Model:()=>ps,SpeechT5PreTrainedModel:()=>cs,SqueezeBertForMaskedLM:()=>dt,SqueezeBertForQuestionAnswering:()=>pt,SqueezeBertForSequenceClassification:()=>ct,SqueezeBertModel:()=>ut,SqueezeBertPreTrainedModel:()=>lt,StableLmForCausalLM:()=>Ds,StableLmModel:()=>Ns,StableLmPreTrainedModel:()=>Ls,Starcoder2ForCausalLM:()=>Ms,Starcoder2Model:()=>vs,Starcoder2PreTrainedModel:()=>xs,Swin2SRForImageSuperResolution:()=>Gi,Swin2SRModel:()=>qi,Swin2SRPreTrainedModel:()=>ji,SwinForImageClassification:()=>Vi,SwinModel:()=>Ri,SwinPreTrainedModel:()=>Di,T5ForConditionalGeneration:()=>yt,T5Model:()=>bt,T5PreTrainedModel:()=>wt,TableTransformerForObjectDetection:()=>Ci,TableTransformerModel:()=>Si,TableTransformerObjectDetectionOutput:()=>Ei,TableTransformerPreTrainedModel:()=>$i,TokenClassifierOutput:()=>bl,TrOCRForCausalLM:()=>_s,TrOCRPreTrainedModel:()=>gs,UniSpeechForCTC:()=>Ga,UniSpeechForSequenceClassification:()=>Ua,UniSpeechModel:()=>qa,UniSpeechPreTrainedModel:()=>ja,UniSpeechSatForAudioFrameClassification:()=>Qa,UniSpeechSatForCTC:()=>Ka,UniSpeechSatForSequenceClassification:()=>Xa,UniSpeechSatModel:()=>Ha,UniSpeechSatPreTrainedModel:()=>Wa,ViTForImageClassification:()=>Dr,ViTMAEModel:()=>Gr,ViTMAEPreTrainedModel:()=>qr,ViTMSNForImageClassification:()=>Hr,ViTMSNModel:()=>Wr,ViTMSNPreTrainedModel:()=>Ur,ViTModel:()=>Nr,ViTPreTrainedModel:()=>Lr,VisionEncoderDecoderModel:()=>hn,VitMatteForImageMatting:()=>ei,VitMattePreTrainedModel:()=>Jr,VitsModel:()=>As,VitsModelOutput:()=>kl,VitsPreTrainedModel:()=>Fs,Wav2Vec2BertForCTC:()=>Ja,Wav2Vec2BertForSequenceClassification:()=>es,Wav2Vec2BertModel:()=>Za,Wav2Vec2BertPreTrainedModel:()=>Ya,Wav2Vec2ForAudioFrameClassification:()=>Ba,Wav2Vec2ForCTC:()=>za,Wav2Vec2ForSequenceClassification:()=>Oa,Wav2Vec2Model:()=>Ia,Wav2Vec2PreTrainedModel:()=>Aa,WavLMForAudioFrameClassification:()=>ds,WavLMForCTC:()=>os,WavLMForSequenceClassification:()=>ls,WavLMForXVector:()=>us,WavLMModel:()=>ss,WavLMPreTrainedModel:()=>as,WeSpeakerResNetModel:()=>Va,WeSpeakerResNetPreTrainedModel:()=>Ra,WhisperForConditionalGeneration:()=>pn,WhisperModel:()=>cn,WhisperPreTrainedModel:()=>dn,XLMForQuestionAnswering:()=>Jt,XLMForSequenceClassification:()=>Yt,XLMForTokenClassification:()=>Zt,XLMModel:()=>Xt,XLMPreTrainedModel:()=>Kt,XLMRobertaForMaskedLM:()=>nn,XLMRobertaForQuestionAnswering:()=>sn,XLMRobertaForSequenceClassification:()=>rn,XLMRobertaForTokenClassification:()=>an,XLMRobertaModel:()=>tn,XLMRobertaPreTrainedModel:()=>en,XLMWithLMHeadModel:()=>Qt,XVectorOutput:()=>wl,YolosForObjectDetection:()=>xa,YolosModel:()=>ya,YolosObjectDetectionOutput:()=>va,YolosPreTrainedModel:()=>ba,getPerf:()=>O});var r=n(/*! ./configs.js */"./src/configs.js"),i=n(/*! ./backends/onnx.js */"./src/backends/onnx.js"),a=n(/*! ./utils/dtypes.js */"./src/utils/dtypes.js"),s=n(/*! ./utils/generic.js */"./src/utils/generic.js"),o=n(/*! ./utils/core.js */"./src/utils/core.js"),l=n(/*! ./utils/hub.js */"./src/utils/hub.js"),u=n(/*! ./utils/constants.js */"./src/utils/constants.js"),d=n(/*! ./generation/logits_process.js */"./src/generation/logits_process.js"),c=n(/*! ./generation/configuration_utils.js */"./src/generation/configuration_utils.js"),p=n(/*! ./utils/tensor.js */"./src/utils/tensor.js"),h=n(/*! ./utils/maths.js */"./src/utils/maths.js"),m=n(/*! ./generation/stopping_criteria.js */"./src/generation/stopping_criteria.js"),f=n(/*! ./generation/logits_sampler.js */"./src/generation/logits_sampler.js"),g=n(/*! ./env.js */"./src/env.js"),_=n(/*! ./models/whisper/generation_whisper.js */"./src/models/whisper/generation_whisper.js"),w=n(/*! ./models/whisper/common_whisper.js */"./src/models/whisper/common_whisper.js");const b=0,y=1,x=2,v=3,M=4,T=5,k=6,$=7,S=new Map,C=new Map,E=new Map;async function P(e,t,n){return Object.fromEntries(await Promise.all(Object.keys(t).map((async s=>{const{buffer:o,session_options:u,session_config:d}=await async function(e,t,n){const s=n.config?.["transformers.js_config"]??{};let o=n.device??s.device;o&&"string"!=typeof o&&(o.hasOwnProperty(t)?o=o[t]:(console.warn(`device not specified for "${t}". Using the default device.`),o=null));const u=o??(g.apis.IS_NODE_ENV?"cpu":"wasm"),d=(0,i.deviceToExecutionProviders)(u);let c=n.dtype??s.dtype;"string"!=typeof c&&(c&&c.hasOwnProperty(t)?c=c[t]:(c=a.DEFAULT_DEVICE_DTYPE_MAPPING[u]??a.DATA_TYPES.fp32,console.warn(`dtype not specified for "${t}". Using the default dtype (${c}) for this device (${u}).`)));const p=c;if(!a.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(p))throw new Error(`Invalid dtype: ${p}. Should be one of: ${Object.keys(a.DATA_TYPES).join(", ")}`);if(p===a.DATA_TYPES.fp16&&"webgpu"===u&&!await(0,a.isWebGpuFp16Supported)())throw new Error(`The device (${u}) does not support fp16.`);const h=s.kv_cache_dtype?"string"==typeof s.kv_cache_dtype?s.kv_cache_dtype:s.kv_cache_dtype[p]??"float32":void 0;if(h&&!["float32","float16"].includes(h))throw new Error(`Invalid kv_cache_dtype: ${h}. Should be one of: float32, float16`);const m={dtype:p,kv_cache_dtype:h},f=a.DEFAULT_DTYPE_SUFFIX_MAPPING[p],_=`${n.subfolder??""}/${t}${f}.onnx`,w={...n.session_options};w.executionProviders??=d;const b=s.free_dimension_overrides;b?w.freeDimensionOverrides??=b:u.startsWith("webnn")&&!w.freeDimensionOverrides&&console.warn('WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.');const y=(0,l.getModelFile)(e,_,!0,n),x=n.use_external_data_format??s.use_external_data_format;let v=[];if(x&&(!0===x||"object"==typeof x&&x.hasOwnProperty(t)&&!0===x[t])){if(g.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const r=`${t}${f}.onnx_data`,i=`${n.subfolder??""}/${r}`;v.push(new Promise((async(t,a)=>{const s=await(0,l.getModelFile)(e,i,!0,n);t({path:r,data:s})})))}else void 0!==w.externalData&&(v=w.externalData.map((async t=>{if("string"==typeof t.data){const r=await(0,l.getModelFile)(e,t.data,!0,n);return{...t,data:r}}return t})));if(v.length>0&&(w.externalData=await Promise.all(v)),"webgpu"===u){const e=(0,r.getKeyValueShapes)(n.config,{prefix:"present"});if(Object.keys(e).length>0&&!(0,i.isONNXProxy)()){const t={};for(const n in e)t[n]="gpu-buffer";w.preferredOutputLocation=t}}return{buffer:await y,session_options:w,session_config:m}}(e,t[s],n);return[s,await(0,i.createInferenceSession)(o,u,d)]}))))}async function F(e,t,n){return Object.fromEntries(await Promise.all(Object.keys(t).map((async r=>[r,await(0,l.getModelJSON)(e,t[r],!1,n)]))))}const A=e=>new URLSearchParams(window.location.search).get(e);let I=1,z={warmup:0,inference:[],throughput:0};function O(){return z}async function B(e,t){z={warmup:0,inference:[],throughput:0};const n=function(e,t){const n=Object.create(null),r=[];for(const a of e.inputNames){const e=t[a];e instanceof p.Tensor?n[a]=(0,i.isONNXProxy)()?e.clone():e:r.push(a)}if(r.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${r.join(", ")}.`);const a=Object.keys(t).length,s=e.inputNames.length;if(a>s){let n=Object.keys(t).filter((t=>!e.inputNames.includes(t)));console.warn(`WARNING: Too many inputs were provided (${a} > ${s}). The following inputs will be ignored: "${n.join(", ")}".`)}return n}(e,t);try{const t=Object.fromEntries(Object.entries(n).map((([e,t])=>[e,t.ort_tensor])));let r,i=1;console.log("-- number of test runs --"),I=A("run")?parseInt(A("run")):1,console.log(I);let a,s,o=performance.now(),l=[];for(let n=0;nt.length!==e[0].length)))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new p.Tensor("int64",BigInt64Array.from(e.flat().map((e=>BigInt(e)))),[e.length,e[0].length])}return new p.Tensor("int64",BigInt64Array.from(e.map((e=>BigInt(e)))),[1,e.length])}function D(e){return new p.Tensor("bool",[e],[1])}async function R(e,t){let{encoder_outputs:n,input_ids:r,decoder_input_ids:i,...a}=t;if(!n){const r=(0,o.pick)(t,e.sessions.model.inputNames);n=(await V(e,r)).last_hidden_state}a.input_ids=i,a.encoder_hidden_states=n,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(a.encoder_attention_mask=t.attention_mask);return await j(e,a,!0)}async function V(e,t){const n=e.sessions.model,r=(0,o.pick)(t,n.inputNames);if(n.inputNames.includes("inputs_embeds")&&!r.inputs_embeds){if(!t.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");r.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}return n.inputNames.includes("token_type_ids")&&!r.token_type_ids&&(r.token_type_ids=new p.Tensor("int64",new BigInt64Array(r.input_ids.data.length),r.input_ids.dims)),await B(n,r)}async function j(e,t,n=!1){const r=e.sessions[n?"decoder_model_merged":"model"],{past_key_values:i,...a}=t;r.inputNames.includes("use_cache_branch")&&(a.use_cache_branch=D(!!i)),r.inputNames.includes("position_ids")&&a.attention_mask&&!a.position_ids&&(a.position_ids=function(e,t=null){const{input_ids:n,inputs_embeds:r,attention_mask:i}=e,[a,s]=i.dims,o=new BigInt64Array(i.data.length);for(let e=0;er.dims[1]);else if(tt==e.config.image_token_index))){const i=e.config.num_image_tokens;if(!i)throw new Error("`num_image_tokens` is missing in the model configuration.");const a=r.dims[1]-(t-i);n.input_ids=r.slice(null,[-a,null]),n.attention_mask=(0,p.ones)([1,t+a])}}return n}function U(e,t,n,r){return n.past_key_values&&(t=t.map((e=>[e.at(-1)]))),{...n,decoder_input_ids:N(t)}}function W(e,...t){return e.config.is_encoder_decoder?U(e,...t):G(e,...t)}class H extends s.Callable{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(e,t,n){super(),this.config=e,this.sessions=t,this.configs=n;const r=E.get(this.constructor),i=S.get(r);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,i){case M:this.can_generate=!0,this._forward=j,this._prepare_inputs_for_generation=G;break;case x:case v:case $:this.can_generate=!0,this._forward=R,this._prepare_inputs_for_generation=U;break;case y:this._forward=R;break;case k:this.can_generate=!0,this._forward=q,this._prepare_inputs_for_generation=W;break;default:this._forward=V}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const e=[];for(const t of Object.values(this.sessions))t?.handler?.dispose&&e.push(t.handler.dispose());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:i=null,local_files_only:a=!1,revision:s="main",model_file_name:o=null,subfolder:l="onnx",device:d=null,dtype:c=null,use_external_data_format:p=null,session_options:h={}}={}){let m={progress_callback:t,config:n,cache_dir:i,local_files_only:a,revision:s,model_file_name:o,subfolder:l,device:d,dtype:c,use_external_data_format:p,session_options:h};const f=E.get(this),g=S.get(f);let _;if(n=m.config=await r.AutoConfig.from_pretrained(e,m),g===M)_=await Promise.all([P(e,{model:m.model_file_name??"model"},m),F(e,{generation_config:"generation_config.json"},m)]);else if(g===x||g===v)_=await Promise.all([P(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},m),F(e,{generation_config:"generation_config.json"},m)]);else if(g===T)_=await Promise.all([P(e,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},m)]);else if(g===y)_=await Promise.all([P(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},m)]);else if(g===k){const t={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};n.is_encoder_decoder&&(t.model="encoder_model"),_=await Promise.all([P(e,t,m),F(e,{generation_config:"generation_config.json"},m)])}else g===$?_=await Promise.all([P(e,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},m),F(e,{generation_config:"generation_config.json"},m)]):(g!==b&&console.warn(`Model type for '${f??n?.model_type}' not found, assuming encoder-only architecture. Please report this at ${u.GITHUB_ISSUE_URL}.`),_=await Promise.all([P(e,{model:m.model_file_name??"model"},m)]));return new this(n,..._)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_warper(e){const t=new d.LogitsProcessorList;return null!==e.temperature&&1!==e.temperature&&t.push(new d.TemperatureLogitsWarper(e.temperature)),null!==e.top_k&&0!==e.top_k&&t.push(new d.TopKLogitsWarper(e.top_k)),null!==e.top_p&&e.top_p<1&&t.push(new d.TopPLogitsWarper(e.top_p)),t}_get_logits_processor(e,t,n=null){const r=new d.LogitsProcessorList;if(null!==e.repetition_penalty&&1!==e.repetition_penalty&&r.push(new d.RepetitionPenaltyLogitsProcessor(e.repetition_penalty)),null!==e.no_repeat_ngram_size&&e.no_repeat_ngram_size>0&&r.push(new d.NoRepeatNGramLogitsProcessor(e.no_repeat_ngram_size)),null!==e.bad_words_ids&&r.push(new d.NoBadWordsLogitsProcessor(e.bad_words_ids,e.eos_token_id)),null!==e.min_length&&null!==e.eos_token_id&&e.min_length>0&&r.push(new d.MinLengthLogitsProcessor(e.min_length,e.eos_token_id)),null!==e.min_new_tokens&&null!==e.eos_token_id&&e.min_new_tokens>0&&r.push(new d.MinNewTokensLengthLogitsProcessor(t,e.min_new_tokens,e.eos_token_id)),null!==e.forced_bos_token_id&&r.push(new d.ForcedBOSTokenLogitsProcessor(e.forced_bos_token_id)),null!==e.forced_eos_token_id&&r.push(new d.ForcedEOSTokenLogitsProcessor(e.max_length,e.forced_eos_token_id)),null!==e.begin_suppress_tokens){const n=t>1||null===e.forced_bos_token_id?t:t+1;r.push(new d.SuppressTokensAtBeginLogitsProcessor(e.begin_suppress_tokens,n))}return null!==e.guidance_scale&&e.guidance_scale>1&&r.push(new d.ClassifierFreeGuidanceLogitsProcessor(e.guidance_scale)),null!==n&&r.extend(n),r}_prepare_generation_config(e,t,n=c.GenerationConfig){const r={...this.config};for(const e of["decoder","generator","text_config"])e in r&&Object.assign(r,r[e]);const i=new n(r);return Object.assign(i,this.generation_config??{}),e&&Object.assign(i,e),t&&Object.assign(i,(0,o.pick)(t,Object.getOwnPropertyNames(i))),i}_get_stopping_criteria(e,t=null){const n=new m.StoppingCriteriaList;return null!==e.max_length&&n.push(new m.MaxLengthCriteria(e.max_length,this.config.max_position_embeddings??null)),null!==e.eos_token_id&&n.push(new m.EosTokenCriteria(e.eos_token_id)),t&&n.extend(t),n}_validate_model_class(){if(!this.can_generate){const e=[wo,xo,_o,po],t=E.get(this.constructor),n=new Set,r=this.config.model_type;for(const t of e){const e=t.get(r);e&&n.add(e[0])}let i=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw n.size>0&&(i+=` Please use the following class instead: ${[...n].join(", ")}`),Error(i)}}prepare_inputs_for_generation(...e){return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:n,is_encoder_decoder:r}){return n.past_key_values=this.getPastKeyValues(t,n.past_key_values),n.input_ids=new p.Tensor("int64",e.flat(),[e.length,1]),r||(n.attention_mask=(0,p.cat)([n.attention_mask,(0,p.ones)([n.attention_mask.dims[0],1])],1)),n.position_ids=null,n}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:n}){const r=(0,o.pick)(n,this.forward_params),i=this.main_input_name;if(i in r){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else r[i]=e;return{inputs_tensor:r[i],model_inputs:r,model_input_name:i}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:n,generation_config:r}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!t.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:e,pixel_values:n,attention_mask:r,...i}=t,a=await this._prepare_inputs_embeds(t);t={...i,...(0,o.pick)(a,["inputs_embeds","attention_mask"])}}let{last_hidden_state:i}=await V(this,t);if(null!==r.guidance_scale&&r.guidance_scale>1)i=(0,p.cat)([i,(0,p.full_like)(i,0)],0),"attention_mask"in t&&(t.attention_mask=(0,p.cat)([t.attention_mask,(0,p.zeros_like)(t.attention_mask)],0));else if(t.decoder_input_ids){const e=N(t.decoder_input_ids).dims[0];if(e!==i.dims[0]){if(1!==i.dims[0])throw new Error(`The encoder outputs have a different batch size (${i.dims[0]}) than the decoder inputs (${e}).`);i=(0,p.cat)(Array.from({length:e},(()=>i)),0)}}return t.encoder_outputs=i,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:n,decoder_start_token_id:r,bos_token_id:i,generation_config:a}){let{decoder_input_ids:s,...o}=n;if(s)Array.isArray(s[0])||(s=Array.from({length:e},(()=>s)));else if(r??=i,"musicgen"===this.config.model_type)s=Array.from({length:e*this.config.decoder.num_codebooks},(()=>[r]));else if(Array.isArray(r)){if(r.length!==e)throw new Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${r.length}`);s=r}else s=Array.from({length:e},(()=>[r]));return s=N(s),n.decoder_attention_mask=(0,p.ones_like)(s),{input_ids:s,model_inputs:o}}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,streamer:i=null,...a}){this._validate_model_class(),t=this._prepare_generation_config(t,a);let{inputs_tensor:s,model_inputs:o,model_input_name:l}=this._prepare_model_inputs({inputs:e,model_kwargs:a});const u=this.config.is_encoder_decoder;let d;u&&("encoder_outputs"in o||(o=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:s,model_inputs:o,model_input_name:l,generation_config:t}))),u?({input_ids:d,model_inputs:o}=this._prepare_decoder_input_ids_for_generation({batch_size:o[l].dims.at(0),model_input_name:l,model_kwargs:o,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t})):d=o[l];let c=d.dims.at(-1);null!==t.max_new_tokens&&(t.max_length=c+t.max_new_tokens);const h=this._get_logits_processor(t,c,n),m=this._get_stopping_criteria(t,r),g=o[l].dims.at(0),_=f.LogitsSampler.getSampler(t),w=new Array(g).fill(0),b=d.tolist();let y;i&&i.put(b);let x={};for(;;){if(o=this.prepare_inputs_for_generation(b,o,t),y=await this.forward(o),t.output_attentions&&t.return_dict_in_generate){const e=this.getAttentions(y);for(const t in e)t in x||(x[t]=[]),x[t].push(e[t])}const e=h(b,y.logits.slice(null,-1,null)),n=[];for(let t=0;te)))break;o=this._update_model_kwargs_for_generation({generated_input_ids:n,outputs:y,model_inputs:o,is_encoder_decoder:u})}i&&i.end();const v=this.getPastKeyValues(y,o.past_key_values,!0),M=new p.Tensor("int64",b.flat(),[b.length,b[0].length]);if(t.return_dict_in_generate)return{sequences:M,past_key_values:v,...x};for(const e of Object.values(y))"gpu-buffer"===e.location&&e.dispose();return M}getPastKeyValues(e,t,n=!1){const r=Object.create(null);for(const i in e)if(i.startsWith("present")){const a=i.replace("present","past_key_values"),s=i.includes("encoder");if(r[a]=s&&t?t[a]:e[i],t&&(!s||n)){const e=t[a];"gpu-buffer"===e.location&&e.dispose()}}return r}getAttentions(e){const t={};for(const n of["cross_attentions","encoder_attentions","decoder_attentions"])for(const r in e)r.startsWith(n)&&(n in t||(t[n]=[]),t[n].push(e[r]));return t}addPastKeyValues(e,t){if(t)Object.assign(e,t);else{const t=this.sessions.decoder_model_merged??this.sessions.model,n=t?.config?.kv_cache_dtype??"float32",i="float16"===n?new Uint16Array:[],a=(0,r.getKeyValueShapes)(this.config);for(const t in a)e[t]=new p.Tensor(n,i,a[t])}}async encode_image({pixel_values:e}){const t=(await B(this.sessions.vision_encoder,{pixel_values:e})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${t.dims[1]}).`),this.config.num_image_tokens=t.dims[1]),t}async encode_text({input_ids:e}){return(await B(this.sessions.embed_tokens,{input_ids:e})).inputs_embeds}}class K{}class X extends K{constructor({last_hidden_state:e,hidden_states:t=null,attentions:n=null}){super(),this.last_hidden_state=e,this.hidden_states=t,this.attentions=n}}class Q extends H{}class Y extends Q{}class Z extends Q{async _call(e){return new yl(await super._call(e))}}class J extends Q{async _call(e){return new _l(await super._call(e))}}class ee extends Q{async _call(e){return new bl(await super._call(e))}}class te extends Q{async _call(e){return new xl(await super._call(e))}}class ne extends H{}class re extends ne{}class ie extends H{}class ae extends ie{}class se extends ie{async _call(e){return new yl(await super._call(e))}}class oe extends ie{async _call(e){return new _l(await super._call(e))}}class le extends ie{async _call(e){return new bl(await super._call(e))}}class ue extends ie{async _call(e){return new xl(await super._call(e))}}class de extends H{}class ce extends de{}class pe extends de{async _call(e){return new yl(await super._call(e))}}class he extends de{async _call(e){return new _l(await super._call(e))}}class me extends de{async _call(e){return new bl(await super._call(e))}}class fe extends de{async _call(e){return new xl(await super._call(e))}}class ge extends H{}class _e extends ge{}class we extends ge{async _call(e){return new yl(await super._call(e))}}class be extends ge{async _call(e){return new _l(await super._call(e))}}class ye extends ge{async _call(e){return new bl(await super._call(e))}}class xe extends ge{async _call(e){return new xl(await super._call(e))}}class ve extends H{}class Me extends ve{}class Te extends ve{async _call(e){return new yl(await super._call(e))}}class ke extends ve{async _call(e){return new _l(await super._call(e))}}class $e extends ve{async _call(e){return new bl(await super._call(e))}}class Se extends ve{async _call(e){return new xl(await super._call(e))}}class Ce extends H{}class Ee extends Ce{}class Pe extends Ce{async _call(e){return new yl(await super._call(e))}}class Fe extends Ce{async _call(e){return new _l(await super._call(e))}}class Ae extends Ce{async _call(e){return new bl(await super._call(e))}}class Ie extends Ce{async _call(e){return new xl(await super._call(e))}}class ze extends H{}class Oe extends ze{}class Be extends ze{async _call(e){return new yl(await super._call(e))}}class Le extends ze{async _call(e){return new _l(await super._call(e))}}class Ne extends ze{async _call(e){return new bl(await super._call(e))}}class De extends ze{async _call(e){return new xl(await super._call(e))}}class Re extends H{}class Ve extends Re{}class je extends Re{async _call(e){return new _l(await super._call(e))}}class qe extends Re{async _call(e){return new bl(await super._call(e))}}class Ge extends Re{async _call(e){return new xl(await super._call(e))}}class Ue extends Re{async _call(e){return new yl(await super._call(e))}}class We extends H{}class He extends We{}class Ke extends We{async _call(e){return new yl(await super._call(e))}}class Xe extends We{async _call(e){return new _l(await super._call(e))}}class Qe extends We{async _call(e){return new bl(await super._call(e))}}class Ye extends H{}class Ze extends Ye{}class Je extends Ye{async _call(e){return new yl(await super._call(e))}}class et extends Ye{async _call(e){return new _l(await super._call(e))}}class tt extends Ye{async _call(e){return new xl(await super._call(e))}}class nt extends H{}class rt extends nt{}class it extends nt{async _call(e){return new yl(await super._call(e))}}class at extends nt{async _call(e){return new _l(await super._call(e))}}class st extends nt{async _call(e){return new bl(await super._call(e))}}class ot extends nt{async _call(e){return new xl(await super._call(e))}}class lt extends H{}class ut extends lt{}class dt extends lt{async _call(e){return new yl(await super._call(e))}}class ct extends lt{async _call(e){return new _l(await super._call(e))}}class pt extends lt{async _call(e){return new xl(await super._call(e))}}class ht extends H{}class mt extends ht{}class ft extends ht{async _call(e){return new _l(await super._call(e))}}class gt extends ht{async _call(e){return new xl(await super._call(e))}}class _t extends ht{async _call(e){return new yl(await super._call(e))}}class wt extends H{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]}class bt extends wt{}class yt extends wt{}class xt extends H{}class vt extends xt{}class Mt extends xt{}class Tt extends H{}class kt extends Tt{}class $t extends Tt{}class St extends H{}class Ct extends St{}class Et extends St{}class Pt extends St{async _call(e){return new _l(await super._call(e))}}class Ft extends H{}class At extends Ft{}class It extends Ft{}class zt extends Ft{async _call(e){return new _l(await super._call(e))}}class Ot extends Ft{}class Bt extends H{}class Lt extends Bt{}class Nt extends Bt{}class Dt extends H{}class Rt extends Dt{}class Vt extends Dt{}class jt extends H{}class qt extends jt{}class Gt extends jt{async _call(e){return new yl(await super._call(e))}}class Ut extends jt{async _call(e){return new _l(await super._call(e))}}class Wt extends jt{async _call(e){return new bl(await super._call(e))}}class Ht extends jt{async _call(e){return new xl(await super._call(e))}}class Kt extends H{}class Xt extends Kt{}class Qt extends Kt{async _call(e){return new yl(await super._call(e))}}class Yt extends Kt{async _call(e){return new _l(await super._call(e))}}class Zt extends Kt{async _call(e){return new bl(await super._call(e))}}class Jt extends Kt{async _call(e){return new xl(await super._call(e))}}class en extends H{}class tn extends en{}class nn extends en{async _call(e){return new yl(await super._call(e))}}class rn extends en{async _call(e){return new _l(await super._call(e))}}class an extends en{async _call(e){return new bl(await super._call(e))}}class sn extends en{async _call(e){return new xl(await super._call(e))}}class on extends H{}class ln extends on{}class un extends on{}class dn extends H{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]}class cn extends dn{}class pn extends dn{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,_.WhisperGenerationConfig)}_retrieve_init_tokens(e){const t=[e.decoder_start_token_id];let n=e.language;const r=e.task;if(e.is_multilingual){n||(console.warn("No language specified - defaulting to English (en)."),n="en");const i=`<|${(0,w.whisper_language_to_code)(n)}|>`;t.push(e.lang_to_id[i]),t.push(e.task_to_id[r??"transcribe"])}else if(n||r)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter((e=>null!=e))}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,...i}){t=this._prepare_generation_config(t,i);const a=i.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(n??=new d.LogitsProcessorList,n.push(new d.WhisperTimeStampLogitsProcessor(t,a))),t.begin_suppress_tokens&&(n??=new d.LogitsProcessorList,n.push(new d.SuppressTokensAtBeginLogitsProcessor(t.begin_suppress_tokens,a.length))),t.return_token_timestamps){if(!t.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");"translate"===t.task&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),t.output_attentions=!0,t.return_dict_in_generate=!0}const s=await super.generate({inputs:e,generation_config:t,logits_processor:n,decoder_input_ids:a,...i});return t.return_token_timestamps&&(s.token_timestamps=this._extract_token_timestamps(s,t.alignment_heads,t.num_frames)),s}_extract_token_timestamps(e,t,n=null,r=.02){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");null==n&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let i=this.config.median_filter_width;void 0===i&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),i=7);const a=e.cross_attentions,s=Array.from({length:this.config.decoder_layers},((e,t)=>(0,p.cat)(a.map((e=>e[t])),2))),l=(0,p.stack)(t.map((([e,t])=>{if(e>=s.length)throw new Error(`Layer index ${e} is out of bounds for cross attentions (length ${s.length}).`);return n?s[e].slice(null,t,null,[0,n]):s[e].slice(null,t)}))).transpose(1,0,2,3),[u,d]=(0,p.std_mean)(l,-2,0,!0),c=l.clone();for(let e=0;en[t+1]-n[t])),s=(0,o.mergeArrays)([1],a).map((e=>!!e)),l=[];for(let e=0;ee.findIndex((e=>e==i)))),s=a.every((e=>-1===e)),o=a.every((e=>-1!==e));if(!s&&!o)throw new Error("Every input should contain either 0 or 1 image token.");if(s)return{inputs_embeds:e,attention_mask:r};const l=[],u=[];for(let n=0;ne*t),1);e.input_labels=new p.Tensor("int64",new BigInt64Array(n).fill(1n),t)}const t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(t.input_points=e.input_points),e.input_labels&&(t.input_labels=e.input_labels),e.input_boxes&&(t.input_boxes=e.input_boxes),await B(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new ka(await super._call(e))}}class ka extends K{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}}class $a extends H{}class Sa extends $a{}class Ca extends $a{}class Ea extends H{}class Pa extends Ea{}class Fa extends Ea{}class Aa extends H{}class Ia extends Aa{}class za extends Aa{async _call(e){return new vl(await super._call(e))}}class Oa extends Aa{async _call(e){return new _l(await super._call(e))}}class Ba extends Aa{async _call(e){return new bl(await super._call(e))}}class La extends H{}class Na extends La{}class Da extends La{async _call(e){return new bl(await super._call(e))}}class Ra extends H{}class Va extends Ra{}class ja extends H{}class qa extends ja{}class Ga extends ja{async _call(e){return new vl(await super._call(e))}}class Ua extends ja{async _call(e){return new _l(await super._call(e))}}class Wa extends H{}class Ha extends Wa{}class Ka extends Wa{async _call(e){return new vl(await super._call(e))}}class Xa extends Wa{async _call(e){return new _l(await super._call(e))}}class Qa extends Wa{async _call(e){return new bl(await super._call(e))}}class Ya extends H{}class Za extends Ya{}class Ja extends Ya{async _call(e){return new vl(await super._call(e))}}class es extends Ya{async _call(e){return new _l(await super._call(e))}}class ts extends H{}class ns extends Aa{}class rs extends Aa{async _call(e){return new vl(await super._call(e))}}class is extends Aa{async _call(e){return new _l(await super._call(e))}}class as extends H{}class ss extends as{}class os extends as{async _call(e){return new vl(await super._call(e))}}class ls extends as{async _call(e){return new _l(await super._call(e))}}class us extends as{async _call(e){return new wl(await super._call(e))}}class ds extends as{async _call(e){return new bl(await super._call(e))}}class cs extends H{}class ps extends cs{}class hs extends cs{}class ms extends cs{async generate_speech(e,t,{threshold:n=.5,minlenratio:r=0,maxlenratio:i=20,vocoder:a=null}={}){const s={input_ids:e},{encoder_outputs:o,encoder_attention_mask:l}=await V(this,s),u=o.dims[1]/this.config.reduction_factor,d=Math.floor(u*i),c=Math.floor(u*r),h=this.config.num_mel_bins;let m=[],f=null,g=null,_=0;for(;;){++_;const e=D(!!g);let r;r=g?g.output_sequence_out:new p.Tensor("float32",new Float32Array(h),[1,1,h]);let i={use_cache_branch:e,output_sequence:r,encoder_attention_mask:l,speaker_embeddings:t,encoder_hidden_states:o};this.addPastKeyValues(i,f),g=await B(this.sessions.decoder_model_merged,i),f=this.getPastKeyValues(g,f);const{prob:a,spectrum:s}=g;if(m.push(s),_>=c&&(Array.from(a.data).filter((e=>e>=n)).length>0||_>=d))break}const w=(0,p.cat)(m),{waveform:b}=await B(a.sessions.model,{spectrogram:w});return{spectrogram:w,waveform:b}}}class fs extends H{main_input_name="spectrogram"}class gs extends H{}class _s extends gs{}class ws extends H{}class bs extends ws{}class ys extends ws{}class xs extends H{}class vs extends xs{}class Ms extends xs{}class Ts extends H{}class ks extends Ts{}class $s extends Ts{}class Ss extends H{}class Cs extends Ss{}class Es extends Ss{static async from_pretrained(e,t={}){return t.model_file_name??="text_model",super.from_pretrained(e,t)}}class Ps extends Ss{static async from_pretrained(e,t={}){return t.model_file_name??="audio_model",super.from_pretrained(e,t)}}class Fs extends H{}class As extends Fs{async _call(e){return new kl(await super._call(e))}}class Is extends H{}class zs extends Is{}class Os extends Is{}class Bs extends Is{}class Ls extends H{}class Ns extends Ls{}class Ds extends Ls{}class Rs extends H{}class Vs extends Rs{}class js extends Rs{async _call(e){return new _l(await super._call(e))}}class qs extends H{}class Gs extends qs{}class Us extends qs{}class Ws extends H{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(e){const[t,n]=e.dims,r=this.config.decoder.num_codebooks,i=n-r;let a=0;for(let t=0;t0&&s<=i&&(e.data[a++]=e.data[t])}const s=Math.floor(t/r),o=a/(s*r);return new p.Tensor(e.type,e.data.slice(0,a),[s,r,o])}prepare_inputs_for_generation(e,t,n){let r=structuredClone(e);for(let e=0;e=t&&(r[e][t]=BigInt(this.config.decoder.pad_token_id));null!==n.guidance_scale&&n.guidance_scale>1&&(r=r.concat(r));return super.prepare_inputs_for_generation(r,t,n)}async generate(e){const t=await super.generate(e),n=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:r}=await B(this.sessions.encodec_decode,{audio_codes:n});return r}}class Hs extends H{}class Ks extends Hs{}class Xs extends Hs{async _call(e){return new _l(await super._call(e))}}class Qs extends H{}class Ys extends Qs{}class Zs extends Qs{async _call(e){return new _l(await super._call(e))}}class Js extends H{}class eo extends Js{}class to extends Js{async _call(e){return new _l(await super._call(e))}}class no extends H{}class ro extends no{}class io extends no{async _call(e){return new _l(await super._call(e))}}class ao extends H{}class so extends ao{}class oo{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:i=null,local_files_only:a=!1,revision:s="main",model_file_name:o=null,subfolder:l="onnx",device:u=null,dtype:d=null,use_external_data_format:c=null,session_options:p={}}={}){const h={progress_callback:t,config:n,cache_dir:i,local_files_only:a,revision:s,model_file_name:o,subfolder:l,device:u,dtype:d,use_external_data_format:c,session_options:p};if(h.config=await r.AutoConfig.from_pretrained(e,h),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const t of this.MODEL_CLASS_MAPPINGS){const n=t.get(h.config.model_type);if(n)return await n[1].from_pretrained(e,h)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${h.config.model_type}", attempting to construct from base class.`),await H.from_pretrained(e,h);throw Error(`Unsupported model type: ${h.config.model_type}`)}}const lo=new Map([["bert",["BertModel",Y]],["nomic_bert",["NomicBertModel",re]],["roformer",["RoFormerModel",ae]],["electra",["ElectraModel",_e]],["esm",["EsmModel",He]],["convbert",["ConvBertModel",ce]],["camembert",["CamembertModel",Me]],["deberta",["DebertaModel",Ee]],["deberta-v2",["DebertaV2Model",Oe]],["mpnet",["MPNetModel",rt]],["albert",["AlbertModel",mt]],["distilbert",["DistilBertModel",Ve]],["roberta",["RobertaModel",qt]],["xlm",["XLMModel",Xt]],["xlm-roberta",["XLMRobertaModel",tn]],["clap",["ClapModel",Cs]],["clip",["CLIPModel",yn]],["clipseg",["CLIPSegModel",An]],["chinese_clip",["ChineseCLIPModel",Pn]],["siglip",["SiglipModel",$n]],["mobilebert",["MobileBertModel",Ze]],["squeezebert",["SqueezeBertModel",ut]],["wav2vec2",["Wav2Vec2Model",Ia]],["wav2vec2-bert",["Wav2Vec2BertModel",Za]],["unispeech",["UniSpeechModel",qa]],["unispeech-sat",["UniSpeechSatModel",Ha]],["hubert",["HubertModel",ns]],["wavlm",["WavLMModel",ss]],["audio-spectrogram-transformer",["ASTModel",ln]],["vits",["VitsModel",As]],["pyannote",["PyAnnoteModel",Na]],["wespeaker-resnet",["WeSpeakerResNetModel",Va]],["detr",["DetrModel",_i]],["rt_detr",["RTDetrModel",Mi]],["table-transformer",["TableTransformerModel",Si]],["vit",["ViTModel",Nr]],["pvt",["PvtModel",Vr]],["vit_msn",["ViTMSNModel",Wr]],["vit_mae",["ViTMAEModel",Gr]],["groupvit",["GroupViTModel",Xr]],["fastvit",["FastViTModel",Yr]],["mobilevit",["MobileViTModel",ni]],["mobilevitv2",["MobileViTV2Model",ai]],["owlvit",["OwlViTModel",li]],["owlv2",["Owlv2Model",ci]],["beit",["BeitModel",mi]],["deit",["DeiTModel",Fi]],["hiera",["HieraModel",zi]],["convnext",["ConvNextModel",ca]],["convnextv2",["ConvNextV2Model",ma]],["dinov2",["Dinov2Model",_a]],["resnet",["ResNetModel",Li]],["swin",["SwinModel",Ri]],["swin2sr",["Swin2SRModel",qi]],["donut-swin",["DonutSwinModel",ua]],["yolos",["YolosModel",ya]],["dpt",["DPTModel",Wi]],["glpn",["GLPNModel",sa]],["hifigan",["SpeechT5HifiGan",fs]],["efficientnet",["EfficientNetModel",Vs]],["decision_transformer",["DecisionTransformerModel",so]],["mobilenet_v1",["MobileNetV1Model",Ks]],["mobilenet_v2",["MobileNetV2Model",Ys]],["mobilenet_v3",["MobileNetV3Model",eo]],["mobilenet_v4",["MobileNetV4Model",ro]],["maskformer",["MaskFormerModel",ra]]]),uo=new Map([["t5",["T5Model",bt]],["longt5",["LongT5Model",vt]],["mt5",["MT5Model",kt]],["bart",["BartModel",Ct]],["mbart",["MBartModel",At]],["marian",["MarianModel",Sa]],["whisper",["WhisperModel",cn]],["m2m_100",["M2M100Model",Pa]],["blenderbot",["BlenderbotModel",Lt]],["blenderbot-small",["BlenderbotSmallModel",Rt]]]),co=new Map([["bloom",["BloomModel",Er]],["jais",["JAISModel",Nn]],["gpt2",["GPT2Model",On]],["gptj",["GPTJModel",Hn]],["gpt_bigcode",["GPTBigCodeModel",Qn]],["gpt_neo",["GPTNeoModel",Vn]],["gpt_neox",["GPTNeoXModel",Gn]],["codegen",["CodeGenModel",Jn]],["llama",["LlamaModel",nr]],["granite",["GraniteModel",ar]],["cohere",["CohereModel",lr]],["gemma",["GemmaModel",cr]],["gemma2",["Gemma2Model",mr]],["openelm",["OpenELMModel",_r]],["qwen2",["Qwen2Model",yr]],["phi",["PhiModel",Mr]],["phi3",["Phi3Model",$r]],["mpt",["MptModel",Ar]],["opt",["OPTModel",Or]],["mistral",["MistralModel",bs]],["starcoder2",["Starcoder2Model",vs]],["falcon",["FalconModel",ks]],["stablelm",["StableLmModel",Ns]]]),po=new Map([["speecht5",["SpeechT5ForSpeechToText",hs]],["whisper",["WhisperForConditionalGeneration",pn]]]),ho=new Map([["speecht5",["SpeechT5ForTextToSpeech",ms]]]),mo=new Map([["vits",["VitsModel",As]],["musicgen",["MusicgenForConditionalGeneration",Ws]]]),fo=new Map([["bert",["BertForSequenceClassification",J]],["roformer",["RoFormerForSequenceClassification",oe]],["electra",["ElectraForSequenceClassification",be]],["esm",["EsmForSequenceClassification",Xe]],["convbert",["ConvBertForSequenceClassification",he]],["camembert",["CamembertForSequenceClassification",ke]],["deberta",["DebertaForSequenceClassification",Fe]],["deberta-v2",["DebertaV2ForSequenceClassification",Le]],["mpnet",["MPNetForSequenceClassification",at]],["albert",["AlbertForSequenceClassification",ft]],["distilbert",["DistilBertForSequenceClassification",je]],["roberta",["RobertaForSequenceClassification",Ut]],["xlm",["XLMForSequenceClassification",Yt]],["xlm-roberta",["XLMRobertaForSequenceClassification",rn]],["bart",["BartForSequenceClassification",Pt]],["mbart",["MBartForSequenceClassification",zt]],["mobilebert",["MobileBertForSequenceClassification",et]],["squeezebert",["SqueezeBertForSequenceClassification",ct]]]),go=new Map([["bert",["BertForTokenClassification",ee]],["roformer",["RoFormerForTokenClassification",le]],["electra",["ElectraForTokenClassification",ye]],["esm",["EsmForTokenClassification",Qe]],["convbert",["ConvBertForTokenClassification",me]],["camembert",["CamembertForTokenClassification",$e]],["deberta",["DebertaForTokenClassification",Ae]],["deberta-v2",["DebertaV2ForTokenClassification",Ne]],["mpnet",["MPNetForTokenClassification",st]],["distilbert",["DistilBertForTokenClassification",qe]],["roberta",["RobertaForTokenClassification",Wt]],["xlm",["XLMForTokenClassification",Zt]],["xlm-roberta",["XLMRobertaForTokenClassification",an]]]),_o=new Map([["t5",["T5ForConditionalGeneration",yt]],["longt5",["LongT5ForConditionalGeneration",Mt]],["mt5",["MT5ForConditionalGeneration",$t]],["bart",["BartForConditionalGeneration",Et]],["mbart",["MBartForConditionalGeneration",It]],["marian",["MarianMTModel",Ca]],["m2m_100",["M2M100ForConditionalGeneration",Fa]],["blenderbot",["BlenderbotForConditionalGeneration",Nt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Vt]]]),wo=new Map([["bloom",["BloomForCausalLM",Pr]],["gpt2",["GPT2LMHeadModel",Bn]],["jais",["JAISLMHeadModel",Dn]],["gptj",["GPTJForCausalLM",Kn]],["gpt_bigcode",["GPTBigCodeForCausalLM",Yn]],["gpt_neo",["GPTNeoForCausalLM",jn]],["gpt_neox",["GPTNeoXForCausalLM",Un]],["codegen",["CodeGenForCausalLM",er]],["llama",["LlamaForCausalLM",rr]],["granite",["GraniteForCausalLM",sr]],["cohere",["CohereForCausalLM",ur]],["gemma",["GemmaForCausalLM",pr]],["gemma2",["Gemma2ForCausalLM",fr]],["openelm",["OpenELMForCausalLM",wr]],["qwen2",["Qwen2ForCausalLM",xr]],["phi",["PhiForCausalLM",Tr]],["phi3",["Phi3ForCausalLM",Sr]],["mpt",["MptForCausalLM",Ir]],["opt",["OPTForCausalLM",Br]],["mbart",["MBartForCausalLM",Ot]],["mistral",["MistralForCausalLM",ys]],["starcoder2",["Starcoder2ForCausalLM",Ms]],["falcon",["FalconForCausalLM",$s]],["trocr",["TrOCRForCausalLM",_s]],["stablelm",["StableLmForCausalLM",Ds]]]),bo=new Map([["bert",["BertForMaskedLM",Z]],["roformer",["RoFormerForMaskedLM",se]],["electra",["ElectraForMaskedLM",we]],["esm",["EsmForMaskedLM",Ke]],["convbert",["ConvBertForMaskedLM",pe]],["camembert",["CamembertForMaskedLM",Te]],["deberta",["DebertaForMaskedLM",Pe]],["deberta-v2",["DebertaV2ForMaskedLM",Be]],["mpnet",["MPNetForMaskedLM",it]],["albert",["AlbertForMaskedLM",_t]],["distilbert",["DistilBertForMaskedLM",Ue]],["roberta",["RobertaForMaskedLM",Gt]],["xlm",["XLMWithLMHeadModel",Qt]],["xlm-roberta",["XLMRobertaForMaskedLM",nn]],["mobilebert",["MobileBertForMaskedLM",Je]],["squeezebert",["SqueezeBertForMaskedLM",dt]]]),yo=new Map([["bert",["BertForQuestionAnswering",te]],["roformer",["RoFormerForQuestionAnswering",ue]],["electra",["ElectraForQuestionAnswering",xe]],["convbert",["ConvBertForQuestionAnswering",fe]],["camembert",["CamembertForQuestionAnswering",Se]],["deberta",["DebertaForQuestionAnswering",Ie]],["deberta-v2",["DebertaV2ForQuestionAnswering",De]],["mpnet",["MPNetForQuestionAnswering",ot]],["albert",["AlbertForQuestionAnswering",gt]],["distilbert",["DistilBertForQuestionAnswering",Ge]],["roberta",["RobertaForQuestionAnswering",Ht]],["xlm",["XLMForQuestionAnswering",Jt]],["xlm-roberta",["XLMRobertaForQuestionAnswering",sn]],["mobilebert",["MobileBertForQuestionAnswering",tt]],["squeezebert",["SqueezeBertForQuestionAnswering",pt]]]),xo=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",hn]]]),vo=new Map([["llava",["LlavaForConditionalGeneration",fn]],["moondream1",["Moondream1ForConditionalGeneration",gn]],["florence2",["Florence2ForConditionalGeneration",wn]]]),Mo=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",hn]]]),To=new Map([["vit",["ViTForImageClassification",Dr]],["pvt",["PvtForImageClassification",jr]],["vit_msn",["ViTMSNForImageClassification",Hr]],["fastvit",["FastViTForImageClassification",Zr]],["mobilevit",["MobileViTForImageClassification",ri]],["mobilevitv2",["MobileViTV2ForImageClassification",si]],["beit",["BeitForImageClassification",fi]],["deit",["DeiTForImageClassification",Ai]],["hiera",["HieraForImageClassification",Oi]],["convnext",["ConvNextForImageClassification",pa]],["convnextv2",["ConvNextV2ForImageClassification",fa]],["dinov2",["Dinov2ForImageClassification",wa]],["resnet",["ResNetForImageClassification",Ni]],["swin",["SwinForImageClassification",Vi]],["segformer",["SegformerForImageClassification",Os]],["efficientnet",["EfficientNetForImageClassification",js]],["mobilenet_v1",["MobileNetV1ForImageClassification",Xs]],["mobilenet_v2",["MobileNetV2ForImageClassification",Zs]],["mobilenet_v3",["MobileNetV3ForImageClassification",to]],["mobilenet_v4",["MobileNetV4ForImageClassification",io]]]),ko=new Map([["detr",["DetrForObjectDetection",wi]],["rt_detr",["RTDetrForObjectDetection",Ti]],["table-transformer",["TableTransformerForObjectDetection",Ci]],["yolos",["YolosForObjectDetection",xa]]]),$o=new Map([["owlvit",["OwlViTForObjectDetection",ui]],["owlv2",["Owlv2ForObjectDetection",pi]]]),So=new Map([["detr",["DetrForSegmentation",bi]],["clipseg",["CLIPSegForImageSegmentation",In]]]),Co=new Map([["segformer",["SegformerForSemanticSegmentation",Bs]],["sapiens",["SapiensForSemanticSegmentation",Yi]]]),Eo=new Map([["detr",["DetrForSegmentation",bi]],["maskformer",["MaskFormerForInstanceSegmentation",ia]]]),Po=new Map([["sam",["SamModel",Ta]]]),Fo=new Map([["wav2vec2",["Wav2Vec2ForCTC",za]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Ja]],["unispeech",["UniSpeechForCTC",Ga]],["unispeech-sat",["UniSpeechSatForCTC",Ka]],["wavlm",["WavLMForCTC",os]],["hubert",["HubertForCTC",rs]]]),Ao=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Oa]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",es]],["unispeech",["UniSpeechForSequenceClassification",Ua]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Xa]],["wavlm",["WavLMForSequenceClassification",ls]],["hubert",["HubertForSequenceClassification",is]],["audio-spectrogram-transformer",["ASTForAudioClassification",un]]]),Io=new Map([["wavlm",["WavLMForXVector",us]]]),zo=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Qa]],["wavlm",["WavLMForAudioFrameClassification",ds]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Ba]],["pyannote",["PyAnnoteForAudioFrameClassification",Da]]]),Oo=new Map([["vitmatte",["VitMatteForImageMatting",ei]]]),Bo=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Gi]]]),Lo=new Map([["dpt",["DPTForDepthEstimation",Hi]],["depth_anything",["DepthAnythingForDepthEstimation",Xi]],["glpn",["GLPNForDepthEstimation",oa]],["sapiens",["SapiensForDepthEstimation",Zi]],["depth_pro",["DepthProForDepthEstimation",ta]]]),No=new Map([["sapiens",["SapiensForNormalEstimation",Ji]]]),Do=new Map([["clip",["CLIPVisionModelWithProjection",Tn]],["siglip",["SiglipVisionModel",Cn]]]),Ro=[[lo,b],[uo,y],[co,M],[fo,b],[go,b],[_o,x],[po,x],[wo,M],[bo,b],[yo,b],[xo,v],[vo,k],[To,b],[So,b],[Eo,b],[Co,b],[Oo,b],[Bo,b],[Lo,b],[No,b],[ko,b],[$o,b],[Po,T],[Fo,b],[Ao,b],[ho,x],[mo,b],[Io,b],[zo,b],[Do,b]];for(const[e,t]of Ro)for(const[n,r]of e.values())S.set(n,t),E.set(r,n),C.set(n,r);const Vo=[["MusicgenForConditionalGeneration",Ws,$],["CLIPTextModelWithProjection",vn,b],["SiglipTextModel",Sn,b],["ClapTextModelWithProjection",Es,b],["ClapAudioModelWithProjection",Ps,b]];for(const[e,t,n]of Vo)S.set(e,n),E.set(t,e),C.set(e,t);class jo extends oo{static MODEL_CLASS_MAPPINGS=Ro.map((e=>e[0]));static BASE_IF_FAIL=!0}class qo extends oo{static MODEL_CLASS_MAPPINGS=[fo]}class Go extends oo{static MODEL_CLASS_MAPPINGS=[go]}class Uo extends oo{static MODEL_CLASS_MAPPINGS=[_o]}class Wo extends oo{static MODEL_CLASS_MAPPINGS=[po]}class Ho extends oo{static MODEL_CLASS_MAPPINGS=[ho]}class Ko extends oo{static MODEL_CLASS_MAPPINGS=[mo]}class Xo extends oo{static MODEL_CLASS_MAPPINGS=[wo]}class Qo extends oo{static MODEL_CLASS_MAPPINGS=[bo]}class Yo extends oo{static MODEL_CLASS_MAPPINGS=[yo]}class Zo extends oo{static MODEL_CLASS_MAPPINGS=[xo]}class Jo extends oo{static MODEL_CLASS_MAPPINGS=[To]}class el extends oo{static MODEL_CLASS_MAPPINGS=[So]}class tl extends oo{static MODEL_CLASS_MAPPINGS=[Co]}class nl extends oo{static MODEL_CLASS_MAPPINGS=[Eo]}class rl extends oo{static MODEL_CLASS_MAPPINGS=[ko]}class il extends oo{static MODEL_CLASS_MAPPINGS=[$o]}class al extends oo{static MODEL_CLASS_MAPPINGS=[Po]}class sl extends oo{static MODEL_CLASS_MAPPINGS=[Fo]}class ol extends oo{static MODEL_CLASS_MAPPINGS=[Ao]}class ll extends oo{static MODEL_CLASS_MAPPINGS=[Io]}class ul extends oo{static MODEL_CLASS_MAPPINGS=[zo]}class dl extends oo{static MODEL_CLASS_MAPPINGS=[Mo]}class cl extends oo{static MODEL_CLASS_MAPPINGS=[Oo]}class pl extends oo{static MODEL_CLASS_MAPPINGS=[Bo]}class hl extends oo{static MODEL_CLASS_MAPPINGS=[Lo]}class ml extends oo{static MODEL_CLASS_MAPPINGS=[No]}class fl extends oo{static MODEL_CLASS_MAPPINGS=[Do]}class gl extends K{constructor({logits:e,past_key_values:t,encoder_outputs:n,decoder_attentions:r=null,cross_attentions:i=null}){super(),this.logits=e,this.past_key_values=t,this.encoder_outputs=n,this.decoder_attentions=r,this.cross_attentions=i}}class _l extends K{constructor({logits:e}){super(),this.logits=e}}class wl extends K{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}}class bl extends K{constructor({logits:e}){super(),this.logits=e}}class yl extends K{constructor({logits:e}){super(),this.logits=e}}class xl extends K{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}}class vl extends K{constructor({logits:e}){super(),this.logits=e}}class Ml extends K{constructor({logits:e,past_key_values:t}){super(),this.logits=e,this.past_key_values=t}}class Tl extends K{constructor({alphas:e}){super(),this.alphas=e}}class kl extends K{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}}},"./src/models/whisper/common_whisper.js": /*!**********************************************!*\ !*** ./src/models/whisper/common_whisper.js ***! \**********************************************/(e,t,n)=>{n.r(t),n.d(t,{WHISPER_LANGUAGE_MAPPING:()=>i,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>a,whisper_language_to_code:()=>s});const r=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],i=new Map(r),a=new Map([...r.map((([e,t])=>[t,e])),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function s(e){e=e.toLowerCase();let t=a.get(e);if(void 0===t){if(!i.has(e)){const t=2===e.length?i.keys():i.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(t)}`)}t=e}return t}},"./src/models/whisper/generation_whisper.js": @@ -184,16 +184,16 @@ var r,i,a,s,o,l,u,d,c,p,h,m,f,g,_,w,b,y,x,v,M,T,k,$,C,S,P,E,F,A,I,z,O,B,L=Object \*****************************/(e,t,n)=>{n.r(t),n.d(t,{TensorOpRegistry:()=>s});var r=n(/*! ../backends/onnx.js */"./src/backends/onnx.js"),i=n(/*! ../utils/tensor.js */"./src/utils/tensor.js");const a=async(e,t,n)=>{const a=await(0,r.createInferenceSession)(new Uint8Array(e),t);return async e=>{const t=Object.fromEntries(Object.entries(e).map((([e,t])=>[e,t.ort_tensor]))),r=await a.run(t);return Array.isArray(n)?n.map((e=>new i.Tensor(r[e]))):new i.Tensor(r[n])}};class s{static session_options={};static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=a([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=a([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=a([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=a([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=a([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=a([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}}},"./src/pipelines.js": /*!**************************!*\ !*** ./src/pipelines.js ***! - \**************************/(e,t,n)=>{n.r(t),n.d(t,{AudioClassificationPipeline:()=>S,AutomaticSpeechRecognitionPipeline:()=>E,DepthEstimationPipeline:()=>R,DocumentQuestionAnsweringPipeline:()=>L,FeatureExtractionPipeline:()=>$,FillMaskPipeline:()=>b,ImageClassificationPipeline:()=>A,ImageFeatureExtractionPipeline:()=>C,ImageSegmentationPipeline:()=>I,ImageToImagePipeline:()=>D,ImageToTextPipeline:()=>F,ObjectDetectionPipeline:()=>O,Pipeline:()=>f,QuestionAnsweringPipeline:()=>w,SummarizationPipeline:()=>x,Text2TextGenerationPipeline:()=>y,TextClassificationPipeline:()=>g,TextGenerationPipeline:()=>T,TextToAudioPipeline:()=>N,TokenClassificationPipeline:()=>_,TranslationPipeline:()=>v,ZeroShotAudioClassificationPipeline:()=>P,ZeroShotClassificationPipeline:()=>k,ZeroShotImageClassificationPipeline:()=>z,ZeroShotObjectDetectionPipeline:()=>B,pipeline:()=>q});var r=n(/*! ./tokenizers.js */"./src/tokenizers.js"),i=n(/*! ./models.js */"./src/models.js"),a=n(/*! ./processors.js */"./src/processors.js"),s=n(/*! ./utils/generic.js */"./src/utils/generic.js"),o=n(/*! ./utils/core.js */"./src/utils/core.js"),l=n(/*! ./utils/maths.js */"./src/utils/maths.js"),u=n(/*! ./utils/audio.js */"./src/utils/audio.js"),d=n(/*! ./utils/tensor.js */"./src/utils/tensor.js"),c=n(/*! ./utils/image.js */"./src/utils/image.js");async function p(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map((e=>c.RawImage.read(e))))}async function h(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map((e=>"string"==typeof e||e instanceof URL?(0,u.read_audio)(e,t):e instanceof Float64Array?new Float32Array(e):e)))}function m(e,t){t&&(e=e.map((e=>0|e)));const[n,r,i,a]=e;return{xmin:n,ymin:r,xmax:i,ymax:a}}class f extends s.Callable{constructor({task:e,model:t,tokenizer:n=null,processor:r=null}){super(),this.task=e,this.model=t,this.tokenizer=n,this.processor=r}async dispose(){await this.model.dispose()}}class g extends f{constructor(e){super(e)}async _call(e,{top_k:t=1}={}){const n=this.tokenizer(e,{padding:!0,truncation:!0}),r=await this.model(n),i="multi_label_classification"===this.model.config.problem_type?e=>e.sigmoid():e=>new d.Tensor("float32",(0,l.softmax)(e.data),e.dims),a=this.model.config.id2label,s=[];for(const e of r.logits){const n=i(e),r=await(0,d.topk)(n,t),o=r[0].tolist(),l=r[1].tolist().map(((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:o[t]})));1===t?s.push(...l):s.push(l)}return Array.isArray(e)||1===t?s:s[0]}}class _ extends f{constructor(e){super(e)}async _call(e,{ignore_labels:t=["O"]}={}){const n=Array.isArray(e),r=this.tokenizer(n?e:[e],{padding:!0,truncation:!0}),i=(await this.model(r)).logits,a=this.model.config.id2label,s=[];for(let e=0;ee==this.tokenizer.sep_token_id)),p=(u[e].map(((e,n)=>1==e&&(0===n||n>r&&-1===d.findIndex((e=>e==t[n]))))),i[e].tolist()),h=a[e].tolist();for(let n=1;ne==t[n])))&&(p[n]=-1/0,h[n]=-1/0);const m=(0,l.softmax)(p).map(((e,t)=>[e,t])),f=(0,l.softmax)(h).map(((e,t)=>[e,t]));m[0][0]=0,f[0][0]=0;const g=(0,o.product)(m,f).filter((e=>e[0][1]<=e[1][1])).map((e=>[e[0][1],e[1][1],e[0][0]*e[1][0]])).sort(((e,t)=>t[2]-e[2]));for(let e=0;ee==this.tokenizer.mask_token_id));if(-1===s)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const o=r[e][s],u=await(0,d.topk)(new d.Tensor("float32",(0,l.softmax)(o.data),o.dims),t),c=u[0].tolist(),p=u[1].tolist();i.push(p.map(((e,t)=>{const r=n.slice();return r[s]=e,{score:c[t],token:Number(e),token_str:this.tokenizer.model.vocab[e],sequence:this.tokenizer.decode(r,{skip_special_tokens:!0})}})))}return Array.isArray(e)?i:i[0]}}class y extends f{_key="generated_text";constructor(e){super(e)}async _call(e,t={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map((e=>this.model.config.prefix+e)));const n=this.model.config.task_specific_params;n&&n[this.task]&&n[this.task].prefix&&(e=e.map((e=>n[this.task].prefix+e)));const r=this.tokenizer,i={padding:!0,truncation:!0};let a;a=this instanceof v&&"_build_translation_inputs"in r?r._build_translation_inputs(e,i,t):r(e,i);const s=await this.model.generate({...a,...t});return r.batch_decode(s,{skip_special_tokens:!0}).map((e=>({[this._key]:e})))}}class x extends y{_key="summary_text";constructor(e){super(e)}}class v extends y{_key="translation_text";constructor(e){super(e)}}function M(e){return Array.isArray(e)&&e.every((e=>"role"in e&&"content"in e))}class T extends f{constructor(e){super(e)}async _call(e,t={}){let n,r=!1,i=!1;if("string"==typeof e)n=e=[e];else if(Array.isArray(e)&&e.every((e=>"string"==typeof e)))r=!0,n=e;else{if(M(e))e=[e];else{if(!Array.isArray(e)||!e.every(M))throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");r=!0}i=!0,n=e.map((e=>this.tokenizer.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0})))}const a=t.add_special_tokens??!1,s=!i&&(t.return_full_text??!0);this.tokenizer.padding_side="left";const o=this.tokenizer(n,{add_special_tokens:a,padding:!0,truncation:!0}),l=await this.model.generate({...o,...t}),u=this.tokenizer.batch_decode(l,{skip_special_tokens:!0});let d;!s&&o.input_ids.dims.at(-1)>0&&(d=this.tokenizer.batch_decode(o.input_ids,{skip_special_tokens:!0}).map((e=>e.length)));const c=Array.from({length:e.length},(e=>[]));for(let t=0;t[e.toLowerCase(),t]))),this.entailment_id=this.label2id.entailment,void 0===this.entailment_id&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,void 0===this.contradiction_id&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:n="This example is {}.",multi_label:r=!1}={}){const i=Array.isArray(e);i||(e=[e]),Array.isArray(t)||(t=[t]);const a=t.map((e=>n.replace("{}",e))),s=r||1===t.length,o=[];for(const n of e){const e=[];for(const t of a){const r=this.tokenizer(n,{text_pair:t,padding:!0,truncation:!0}),i=await this.model(r);s?e.push([i.logits.data[this.contradiction_id],i.logits.data[this.entailment_id]]):e.push(i.logits.data[this.entailment_id])}const r=(s?e.map((e=>(0,l.softmax)(e)[1])):(0,l.softmax)(e)).map(((e,t)=>[e,t])).sort(((e,t)=>t[0]-e[0]));o.push({sequence:n,labels:r.map((e=>t[e[1]])),scores:r.map((e=>e[0]))})}return i?o:o[0]}}class $ extends f{constructor(e){super(e)}async _call(e,{pooling:t="none",normalize:n=!1,quantize:r=!1,precision:i="binary"}={}){const a=this.tokenizer(e,{padding:!0,truncation:!0}),s=await this.model(a);let o=s.last_hidden_state??s.logits??s.token_embeddings;if("none"===t);else if("mean"===t)o=(0,d.mean_pooling)(o,a.attention_mask);else{if("cls"!==t)throw Error(`Pooling method '${t}' not supported.`);o=o.slice(null,0)}return n&&(o=o.normalize(2,-1)),r&&(o=(0,d.quantize_embeddings)(o,i)),o}}class C extends f{constructor(e){super(e)}async _call(e,{pool:t=null}={}){const n=await p(e),{pixel_values:r}=await this.processor(n),i=await this.model({pixel_values:r});let a;if(t){if(!("pooler_output"in i))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");a=i.pooler_output}else a=i.last_hidden_state??i.logits??i.image_embeds;return a}}class S extends f{constructor(e){super(e)}async _call(e,{top_k:t=5}={}){const n=this.processor.feature_extractor.config.sampling_rate,r=await h(e,n),i=this.model.config.id2label,a=[];for(const e of r){const n=await this.processor(e),r=(await this.model(n)).logits[0],s=await(0,d.topk)(new d.Tensor("float32",(0,l.softmax)(r.data),r.dims),t),o=s[0].tolist(),u=s[1].tolist().map(((e,t)=>({label:i?i[e]:`LABEL_${e}`,score:o[t]})));a.push(u)}return Array.isArray(e)?a:a[0]}}class P extends f{constructor(e){super(e)}async _call(e,t,{hypothesis_template:n="This is a sound of {}."}={}){const r=!Array.isArray(e);r&&(e=[e]);const i=t.map((e=>n.replace("{}",e))),a=this.tokenizer(i,{padding:!0,truncation:!0}),s=this.processor.feature_extractor.config.sampling_rate,o=await h(e,s),u=[];for(const e of o){const n=await this.processor(e),r=await this.model({...a,...n}),i=(0,l.softmax)(r.logits_per_audio.data);u.push([...i].map(((e,n)=>({score:e,label:t[n]}))))}return r?u[0]:u}}class E extends f{constructor(e){super(e)}async _call(e,t={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(e,t);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(e,t);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const n=!Array.isArray(e);n&&(e=[e]);const r=this.processor.feature_extractor.config.sampling_rate,i=await h(e,r),a=[];for(const e of i){const t=await this.processor(e),n=(await this.model(t)).logits[0],r=[];for(const e of n)r.push((0,l.max)(e.data)[1]);const i=this.tokenizer.decode(r);a.push({text:i})}return n?a[0]:a}async _call_whisper(e,t){const n=t.return_timestamps??!1,r=t.chunk_length_s??0,i=t.force_full_sequences??!1;let a=t.stride_length_s??null;const s={...t};"word"===n&&(s.return_token_timestamps=!0,s.return_timestamps=!1);const o=!Array.isArray(e);o&&(e=[e]);const u=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,d=this.processor.feature_extractor.config.hop_length,c=this.processor.feature_extractor.config.sampling_rate,p=await h(e,c),m=[];for(const e of p){let t=[];if(r>0){if(null===a)a=r/6;else if(r<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const n=c*r,i=c*a,s=n-2*i;let o=0;for(;;){const r=o+n,a=e.subarray(o,r),l=await this.processor(a),u=0===o,d=r>=e.length;if(t.push({stride:[a.length,u?0:i,d?0:i],input_features:l.input_features,is_last:d}),d)break;o+=s}}else t=[{stride:[e.length,0,0],input_features:(await this.processor(e)).input_features,is_last:!0}];for(const e of t){s.num_frames=Math.floor(e.stride[0]/d);const t=await this.model.generate({inputs:e.input_features,...s});"word"===n?(e.tokens=t.sequences.tolist()[0],e.token_timestamps=t.token_timestamps.tolist()[0].map((e=>(0,l.round)(e,2)))):e.tokens=t[0].tolist(),e.stride=e.stride.map((e=>e/c))}const[o,p]=this.tokenizer._decode_asr(t,{time_precision:u,return_timestamps:n,force_full_sequences:i});m.push({text:o,...p})}return o?m[0]:m}}class F extends f{constructor(e){super(e)}async _call(e,t={}){const n=Array.isArray(e),r=await p(e),{pixel_values:i}=await this.processor(r),a=[];for(const e of i){e.dims=[1,...e.dims];const n=await this.model.generate({inputs:e,...t}),r=this.tokenizer.batch_decode(n,{skip_special_tokens:!0}).map((e=>({generated_text:e.trim()})));a.push(r)}return n?a:a[0]}}class A extends f{constructor(e){super(e)}async _call(e,{top_k:t=5}={}){const n=await p(e),{pixel_values:r}=await this.processor(n),i=await this.model({pixel_values:r}),a=this.model.config.id2label,s=[];for(const e of i.logits){const n=await(0,d.topk)(new d.Tensor("float32",(0,l.softmax)(e.data),e.dims),t),r=n[0].tolist(),i=n[1].tolist().map(((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:r[t]})));s.push(i)}return Array.isArray(e)?s:s[0]}}class I extends f{constructor(e){super(e),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(e,{threshold:t=.5,mask_threshold:n=.5,overlap_mask_area_threshold:r=.8,label_ids_to_fuse:i=null,target_sizes:a=null,subtask:s=null}={}){if(Array.isArray(e)&&1!==e.length)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const o=await p(e),l=o.map((e=>[e.height,e.width])),{pixel_values:u,pixel_mask:d}=await this.processor(o),h=await this.model({pixel_values:u,pixel_mask:d});let m=null;if(null!==s)m=this.subtasks_mapping[s];else for(let[e,t]of Object.entries(this.subtasks_mapping))if(t in this.processor.feature_extractor){m=this.processor.feature_extractor[t].bind(this.processor.feature_extractor),s=e;break}const f=this.model.config.id2label,g=[];if("panoptic"===s||"instance"===s){const e=m(h,t,n,r,i,a??l)[0],s=e.segmentation;for(const t of e.segments_info){const e=new Uint8ClampedArray(s.data.length);for(let n=0;nn.replace("{}",e))),s=this.tokenizer(a,{padding:"siglip"!==this.model.config.model_type||"max_length",truncation:!0}),{pixel_values:o}=await this.processor(i),u=await this.model({...s,pixel_values:o}),d="siglip"===this.model.config.model_type?e=>e.sigmoid().data:e=>(0,l.softmax)(e.data),c=[];for(const e of u.logits_per_image){const n=[...d(e)].map(((e,n)=>({score:e,label:t[n]})));n.sort(((e,t)=>t.score-e.score)),c.push(n)}return r?c:c[0]}}class O extends f{constructor(e){super(e)}async _call(e,{threshold:t=.9,percentage:n=!1}={}){const r=Array.isArray(e);if(r&&1!==e.length)throw Error("Object detection pipeline currently only supports a batch size of 1.");const i=await p(e),a=n?null:i.map((e=>[e.height,e.width])),{pixel_values:s,pixel_mask:o}=await this.processor(i),l=await this.model({pixel_values:s,pixel_mask:o}),u=this.processor.feature_extractor.post_process_object_detection(l,t,a),d=this.model.config.id2label,c=u.map((e=>e.boxes.map(((t,r)=>({score:e.scores[r],label:d[e.classes[r]],box:m(t,!n)})))));return r?c:c[0]}}class B extends f{constructor(e){super(e)}async _call(e,t,{threshold:n=.1,top_k:r=null,percentage:i=!1}={}){const a=Array.isArray(e),s=await p(e),o=this.tokenizer(t,{padding:!0,truncation:!0}),l=await this.processor(s),u=[];for(let e=0;e({score:h.scores[n],label:t[h.classes[n]],box:m(e,!i)}))).sort(((e,t)=>t.score-e.score));null!==r&&(f=f.slice(0,r)),u.push(f)}return a?u:u[0]}}class L extends f{constructor(e){super(e)}async _call(e,t,n={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class N extends f{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _call(e,{speaker_embeddings:t=null}={}){return this.processor?this._call_text_to_spectrogram(e,{speaker_embeddings:t}):this._call_text_to_waveform(e)}async _call_text_to_waveform(e){const t=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:n}=await this.model(t),r=this.model.config.sampling_rate;return{audio:n.data,sampling_rate:r}}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await i.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),("string"==typeof t||t instanceof URL)&&(t=new Float32Array(await(await fetch(t)).arrayBuffer())),t instanceof Float32Array)t=new d.Tensor("float32",t,[1,t.length]);else if(!(t instanceof d.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:n}=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:r}=await this.model.generate_speech(n,t,{vocoder:this.vocoder}),a=this.processor.feature_extractor.config.sampling_rate;return{audio:r.data,sampling_rate:a}}}class D extends f{constructor(e){super(e)}async _call(e){const t=await p(e),n=await this.processor(t),r=await this.model(n),i=[];for(const e of r.reconstruction){const t=e.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");i.push(c.RawImage.fromTensor(t))}return i.length>1?i:i[0]}}class R extends f{constructor(e){super(e)}async _call(e){const t=await p(e),n=await this.processor(t),{predicted_depth:r}=await this.model(n),i=[];for(let e=0;e1?i:i[0]}}const V=Object.freeze({"text-classification":{tokenizer:r.AutoTokenizer,pipeline:g,model:i.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:r.AutoTokenizer,pipeline:_,model:i.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:r.AutoTokenizer,pipeline:w,model:i.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:r.AutoTokenizer,pipeline:b,model:i.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:r.AutoTokenizer,pipeline:x,model:i.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:r.AutoTokenizer,pipeline:v,model:i.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:r.AutoTokenizer,pipeline:y,model:i.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:r.AutoTokenizer,pipeline:T,model:i.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:r.AutoTokenizer,pipeline:k,model:i.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:S,model:i.AutoModelForAudioClassification,processor:a.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:r.AutoTokenizer,pipeline:P,model:i.AutoModel,processor:a.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:r.AutoTokenizer,pipeline:E,model:[i.AutoModelForSpeechSeq2Seq,i.AutoModelForCTC],processor:a.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:r.AutoTokenizer,pipeline:N,model:[i.AutoModelForTextToWaveform,i.AutoModelForTextToSpectrogram],processor:[a.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:r.AutoTokenizer,pipeline:F,model:i.AutoModelForVision2Seq,processor:a.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:A,model:i.AutoModelForImageClassification,processor:a.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:I,model:[i.AutoModelForImageSegmentation,i.AutoModelForSemanticSegmentation,i.AutoModelForUniversalSegmentation],processor:a.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:r.AutoTokenizer,pipeline:z,model:i.AutoModel,processor:a.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:O,model:i.AutoModelForObjectDetection,processor:a.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:r.AutoTokenizer,pipeline:B,model:i.AutoModelForZeroShotObjectDetection,processor:a.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:r.AutoTokenizer,pipeline:L,model:i.AutoModelForDocumentQuestionAnswering,processor:a.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:D,model:i.AutoModelForImageToImage,processor:a.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:R,model:i.AutoModelForDepthEstimation,processor:a.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:r.AutoTokenizer,pipeline:$,model:i.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:a.AutoProcessor,pipeline:C,model:[i.AutoModelForImageFeatureExtraction,i.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),j=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function q(e,t=null,{progress_callback:n=null,config:r=null,cache_dir:i=null,local_files_only:a=!1,revision:s="main",device:l=null,dtype:u=null,model_file_name:d=null,session_options:c={}}={}){e=j[e]??e;const p=V[e.split("_",1)[0]];if(!p)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(V)}]`);t||(t=p.default.model,console.log(`No model specified. Using default model: "${t}".`));const h={progress_callback:n,config:r,cache_dir:i,local_files_only:a,revision:s,device:l,dtype:u,model_file_name:d,session_options:c},m=new Map([["tokenizer",p.tokenizer],["model",p.model],["processor",p.processor]]),f=await async function(e,t,n){const r=Object.create(null),i=[];for(const[a,s]of e.entries()){if(!s)continue;let e;e=Array.isArray(s)?new Promise((async(e,r)=>{let i;for(const a of s){if(null===a)return void e(null);try{return void e(await a.from_pretrained(t,n))}catch(e){if(e.message?.includes("Unsupported model type"))i=e;else{if(!e.message?.includes("Could not locate file"))return void r(e);i=e}}}r(i)})):s.from_pretrained(t,n),r[a]=e,i.push(e)}await Promise.all(i);for(const[e,t]of Object.entries(r))r[e]=await t;return r}(m,t,h);f.task=e,(0,o.dispatchCallback)(n,{status:"ready",task:e,model:t});return new(0,p.pipeline)(f)}},"./src/processors.js": + \**************************/(e,t,n)=>{n.r(t),n.d(t,{AudioClassificationPipeline:()=>C,AutomaticSpeechRecognitionPipeline:()=>P,DepthEstimationPipeline:()=>R,DocumentQuestionAnsweringPipeline:()=>L,FeatureExtractionPipeline:()=>$,FillMaskPipeline:()=>b,ImageClassificationPipeline:()=>A,ImageFeatureExtractionPipeline:()=>S,ImageSegmentationPipeline:()=>I,ImageToImagePipeline:()=>D,ImageToTextPipeline:()=>F,ObjectDetectionPipeline:()=>O,Pipeline:()=>f,QuestionAnsweringPipeline:()=>w,SummarizationPipeline:()=>x,Text2TextGenerationPipeline:()=>y,TextClassificationPipeline:()=>g,TextGenerationPipeline:()=>T,TextToAudioPipeline:()=>N,TokenClassificationPipeline:()=>_,TranslationPipeline:()=>v,ZeroShotAudioClassificationPipeline:()=>E,ZeroShotClassificationPipeline:()=>k,ZeroShotImageClassificationPipeline:()=>z,ZeroShotObjectDetectionPipeline:()=>B,pipeline:()=>q});var r=n(/*! ./tokenizers.js */"./src/tokenizers.js"),i=n(/*! ./models.js */"./src/models.js"),a=n(/*! ./processors.js */"./src/processors.js"),s=n(/*! ./utils/generic.js */"./src/utils/generic.js"),o=n(/*! ./utils/core.js */"./src/utils/core.js"),l=n(/*! ./utils/maths.js */"./src/utils/maths.js"),u=n(/*! ./utils/audio.js */"./src/utils/audio.js"),d=n(/*! ./utils/tensor.js */"./src/utils/tensor.js"),c=n(/*! ./utils/image.js */"./src/utils/image.js");async function p(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map((e=>c.RawImage.read(e))))}async function h(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map((e=>"string"==typeof e||e instanceof URL?(0,u.read_audio)(e,t):e instanceof Float64Array?new Float32Array(e):e)))}function m(e,t){t&&(e=e.map((e=>0|e)));const[n,r,i,a]=e;return{xmin:n,ymin:r,xmax:i,ymax:a}}class f extends s.Callable{constructor({task:e,model:t,tokenizer:n=null,processor:r=null}){super(),this.task=e,this.model=t,this.tokenizer=n,this.processor=r}async dispose(){await this.model.dispose()}}class g extends f{constructor(e){super(e)}async _call(e,{top_k:t=1}={}){const n=this.tokenizer(e,{padding:!0,truncation:!0}),r=await this.model(n),i="multi_label_classification"===this.model.config.problem_type?e=>e.sigmoid():e=>new d.Tensor("float32",(0,l.softmax)(e.data),e.dims),a=this.model.config.id2label,s=[];for(const e of r.logits){const n=i(e),r=await(0,d.topk)(n,t),o=r[0].tolist(),l=r[1].tolist().map(((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:o[t]})));1===t?s.push(...l):s.push(l)}return Array.isArray(e)||1===t?s:s[0]}}class _ extends f{constructor(e){super(e)}async _call(e,{ignore_labels:t=["O"]}={}){const n=Array.isArray(e),r=this.tokenizer(n?e:[e],{padding:!0,truncation:!0}),i=(await this.model(r)).logits,a=this.model.config.id2label,s=[];for(let e=0;ee==this.tokenizer.sep_token_id)),p=(u[e].map(((e,n)=>1==e&&(0===n||n>r&&-1===d.findIndex((e=>e==t[n]))))),i[e].tolist()),h=a[e].tolist();for(let n=1;ne==t[n])))&&(p[n]=-1/0,h[n]=-1/0);const m=(0,l.softmax)(p).map(((e,t)=>[e,t])),f=(0,l.softmax)(h).map(((e,t)=>[e,t]));m[0][0]=0,f[0][0]=0;const g=(0,o.product)(m,f).filter((e=>e[0][1]<=e[1][1])).map((e=>[e[0][1],e[1][1],e[0][0]*e[1][0]])).sort(((e,t)=>t[2]-e[2]));for(let e=0;ee==this.tokenizer.mask_token_id));if(-1===s)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const o=r[e][s],u=await(0,d.topk)(new d.Tensor("float32",(0,l.softmax)(o.data),o.dims),t),c=u[0].tolist(),p=u[1].tolist();i.push(p.map(((e,t)=>{const r=n.slice();return r[s]=e,{score:c[t],token:Number(e),token_str:this.tokenizer.model.vocab[e],sequence:this.tokenizer.decode(r,{skip_special_tokens:!0})}})))}return Array.isArray(e)?i:i[0]}}class y extends f{_key="generated_text";constructor(e){super(e)}async _call(e,t={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map((e=>this.model.config.prefix+e)));const n=this.model.config.task_specific_params;n&&n[this.task]&&n[this.task].prefix&&(e=e.map((e=>n[this.task].prefix+e)));const r=this.tokenizer,i={padding:!0,truncation:!0};let a;a=this instanceof v&&"_build_translation_inputs"in r?r._build_translation_inputs(e,i,t):r(e,i);const s=await this.model.generate({...a,...t});return r.batch_decode(s,{skip_special_tokens:!0}).map((e=>({[this._key]:e})))}}class x extends y{_key="summary_text";constructor(e){super(e)}}class v extends y{_key="translation_text";constructor(e){super(e)}}function M(e){return Array.isArray(e)&&e.every((e=>"role"in e&&"content"in e))}class T extends f{constructor(e){super(e)}async _call(e,t={}){let n,r=!1,i=!1;if("string"==typeof e)n=e=[e];else if(Array.isArray(e)&&e.every((e=>"string"==typeof e)))r=!0,n=e;else{if(M(e))e=[e];else{if(!Array.isArray(e)||!e.every(M))throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");r=!0}i=!0,n=e.map((e=>this.tokenizer.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0})))}const a=t.add_special_tokens??!1,s=!i&&(t.return_full_text??!0);this.tokenizer.padding_side="left";const o=this.tokenizer(n,{add_special_tokens:a,padding:!0,truncation:!0}),l=await this.model.generate({...o,...t}),u=this.tokenizer.batch_decode(l,{skip_special_tokens:!0});let d;!s&&o.input_ids.dims.at(-1)>0&&(d=this.tokenizer.batch_decode(o.input_ids,{skip_special_tokens:!0}).map((e=>e.length)));const c=Array.from({length:e.length},(e=>[]));for(let t=0;t[e.toLowerCase(),t]))),this.entailment_id=this.label2id.entailment,void 0===this.entailment_id&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,void 0===this.contradiction_id&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:n="This example is {}.",multi_label:r=!1}={}){const i=Array.isArray(e);i||(e=[e]),Array.isArray(t)||(t=[t]);const a=t.map((e=>n.replace("{}",e))),s=r||1===t.length,o=[];for(const n of e){const e=[];for(const t of a){const r=this.tokenizer(n,{text_pair:t,padding:!0,truncation:!0}),i=await this.model(r);s?e.push([i.logits.data[this.contradiction_id],i.logits.data[this.entailment_id]]):e.push(i.logits.data[this.entailment_id])}const r=(s?e.map((e=>(0,l.softmax)(e)[1])):(0,l.softmax)(e)).map(((e,t)=>[e,t])).sort(((e,t)=>t[0]-e[0]));o.push({sequence:n,labels:r.map((e=>t[e[1]])),scores:r.map((e=>e[0]))})}return i?o:o[0]}}class $ extends f{constructor(e){super(e)}async _call(e,{pooling:t="none",normalize:n=!1,quantize:r=!1,precision:i="binary"}={}){const a=this.tokenizer(e,{padding:!0,truncation:!0}),s=await this.model(a);let o=s.last_hidden_state??s.logits??s.token_embeddings;if("none"===t);else if("mean"===t)o=(0,d.mean_pooling)(o,a.attention_mask);else{if("cls"!==t)throw Error(`Pooling method '${t}' not supported.`);o=o.slice(null,0)}return n&&(o=o.normalize(2,-1)),r&&(o=(0,d.quantize_embeddings)(o,i)),o}}class S extends f{constructor(e){super(e)}async _call(e,{pool:t=null}={}){const n=await p(e),{pixel_values:r}=await this.processor(n),i=await this.model({pixel_values:r});let a;if(t){if(!("pooler_output"in i))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");a=i.pooler_output}else a=i.last_hidden_state??i.logits??i.image_embeds;return a}}class C extends f{constructor(e){super(e)}async _call(e,{top_k:t=5}={}){const n=this.processor.feature_extractor.config.sampling_rate,r=await h(e,n),i=this.model.config.id2label,a=[];for(const e of r){const n=await this.processor(e),r=(await this.model(n)).logits[0],s=await(0,d.topk)(new d.Tensor("float32",(0,l.softmax)(r.data),r.dims),t),o=s[0].tolist(),u=s[1].tolist().map(((e,t)=>({label:i?i[e]:`LABEL_${e}`,score:o[t]})));a.push(u)}return Array.isArray(e)?a:a[0]}}class E extends f{constructor(e){super(e)}async _call(e,t,{hypothesis_template:n="This is a sound of {}."}={}){const r=!Array.isArray(e);r&&(e=[e]);const i=t.map((e=>n.replace("{}",e))),a=this.tokenizer(i,{padding:!0,truncation:!0}),s=this.processor.feature_extractor.config.sampling_rate,o=await h(e,s),u=[];for(const e of o){const n=await this.processor(e),r=await this.model({...a,...n}),i=(0,l.softmax)(r.logits_per_audio.data);u.push([...i].map(((e,n)=>({score:e,label:t[n]}))))}return r?u[0]:u}}class P extends f{constructor(e){super(e)}async _call(e,t={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(e,t);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(e,t);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const n=!Array.isArray(e);n&&(e=[e]);const r=this.processor.feature_extractor.config.sampling_rate,i=await h(e,r),a=[];for(const e of i){const t=await this.processor(e),n=(await this.model(t)).logits[0],r=[];for(const e of n)r.push((0,l.max)(e.data)[1]);const i=this.tokenizer.decode(r);a.push({text:i})}return n?a[0]:a}async _call_whisper(e,t){const n=t.return_timestamps??!1,r=t.chunk_length_s??0,i=t.force_full_sequences??!1;let a=t.stride_length_s??null;const s={...t};"word"===n&&(s.return_token_timestamps=!0,s.return_timestamps=!1);const o=!Array.isArray(e);o&&(e=[e]);const u=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,d=this.processor.feature_extractor.config.hop_length,c=this.processor.feature_extractor.config.sampling_rate,p=await h(e,c),m=[];for(const e of p){let t=[];if(r>0){if(null===a)a=r/6;else if(r<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const n=c*r,i=c*a,s=n-2*i;let o=0;for(;;){const r=o+n,a=e.subarray(o,r),l=await this.processor(a),u=0===o,d=r>=e.length;if(t.push({stride:[a.length,u?0:i,d?0:i],input_features:l.input_features,is_last:d}),d)break;o+=s}}else t=[{stride:[e.length,0,0],input_features:(await this.processor(e)).input_features,is_last:!0}];for(const e of t){s.num_frames=Math.floor(e.stride[0]/d);const t=await this.model.generate({inputs:e.input_features,...s});"word"===n?(e.tokens=t.sequences.tolist()[0],e.token_timestamps=t.token_timestamps.tolist()[0].map((e=>(0,l.round)(e,2)))):e.tokens=t[0].tolist(),e.stride=e.stride.map((e=>e/c))}const[o,p]=this.tokenizer._decode_asr(t,{time_precision:u,return_timestamps:n,force_full_sequences:i});m.push({text:o,...p})}return o?m[0]:m}}class F extends f{constructor(e){super(e)}async _call(e,t={}){const n=Array.isArray(e),r=await p(e),{pixel_values:i}=await this.processor(r),a=[];for(const e of i){e.dims=[1,...e.dims];const n=await this.model.generate({inputs:e,...t}),r=this.tokenizer.batch_decode(n,{skip_special_tokens:!0}).map((e=>({generated_text:e.trim()})));a.push(r)}return n?a:a[0]}}class A extends f{constructor(e){super(e)}async _call(e,{top_k:t=5}={}){const n=await p(e),{pixel_values:r}=await this.processor(n),i=await this.model({pixel_values:r}),a=this.model.config.id2label,s=[];for(const e of i.logits){const n=await(0,d.topk)(new d.Tensor("float32",(0,l.softmax)(e.data),e.dims),t),r=n[0].tolist(),i=n[1].tolist().map(((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:r[t]})));s.push(i)}return Array.isArray(e)?s:s[0]}}class I extends f{constructor(e){super(e),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(e,{threshold:t=.5,mask_threshold:n=.5,overlap_mask_area_threshold:r=.8,label_ids_to_fuse:i=null,target_sizes:a=null,subtask:s=null}={}){if(Array.isArray(e)&&1!==e.length)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const o=await p(e),l=o.map((e=>[e.height,e.width])),{pixel_values:u,pixel_mask:d}=await this.processor(o),h=await this.model({pixel_values:u,pixel_mask:d});let m=null;if(null!==s)m=this.subtasks_mapping[s];else for(let[e,t]of Object.entries(this.subtasks_mapping))if(t in this.processor.feature_extractor){m=this.processor.feature_extractor[t].bind(this.processor.feature_extractor),s=e;break}const f=this.model.config.id2label,g=[];if("panoptic"===s||"instance"===s){const e=m(h,t,n,r,i,a??l)[0],s=e.segmentation;for(const t of e.segments_info){const e=new Uint8ClampedArray(s.data.length);for(let n=0;nn.replace("{}",e))),s=this.tokenizer(a,{padding:"siglip"!==this.model.config.model_type||"max_length",truncation:!0}),{pixel_values:o}=await this.processor(i),u=await this.model({...s,pixel_values:o}),d="siglip"===this.model.config.model_type?e=>e.sigmoid().data:e=>(0,l.softmax)(e.data),c=[];for(const e of u.logits_per_image){const n=[...d(e)].map(((e,n)=>({score:e,label:t[n]})));n.sort(((e,t)=>t.score-e.score)),c.push(n)}return r?c:c[0]}}class O extends f{constructor(e){super(e)}async _call(e,{threshold:t=.9,percentage:n=!1}={}){const r=Array.isArray(e);if(r&&1!==e.length)throw Error("Object detection pipeline currently only supports a batch size of 1.");const i=await p(e),a=n?null:i.map((e=>[e.height,e.width])),{pixel_values:s,pixel_mask:o}=await this.processor(i),l=await this.model({pixel_values:s,pixel_mask:o}),u=this.processor.feature_extractor.post_process_object_detection(l,t,a),d=this.model.config.id2label,c=u.map((e=>e.boxes.map(((t,r)=>({score:e.scores[r],label:d[e.classes[r]],box:m(t,!n)})))));return r?c:c[0]}}class B extends f{constructor(e){super(e)}async _call(e,t,{threshold:n=.1,top_k:r=null,percentage:i=!1}={}){const a=Array.isArray(e),s=await p(e),o=this.tokenizer(t,{padding:!0,truncation:!0}),l=await this.processor(s),u=[];for(let e=0;e({score:h.scores[n],label:t[h.classes[n]],box:m(e,!i)}))).sort(((e,t)=>t.score-e.score));null!==r&&(f=f.slice(0,r)),u.push(f)}return a?u:u[0]}}class L extends f{constructor(e){super(e)}async _call(e,t,n={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class N extends f{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _call(e,{speaker_embeddings:t=null}={}){return this.processor?this._call_text_to_spectrogram(e,{speaker_embeddings:t}):this._call_text_to_waveform(e)}async _call_text_to_waveform(e){const t=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:n}=await this.model(t),r=this.model.config.sampling_rate;return{audio:n.data,sampling_rate:r}}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await i.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),("string"==typeof t||t instanceof URL)&&(t=new Float32Array(await(await fetch(t)).arrayBuffer())),t instanceof Float32Array)t=new d.Tensor("float32",t,[1,t.length]);else if(!(t instanceof d.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:n}=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:r}=await this.model.generate_speech(n,t,{vocoder:this.vocoder}),a=this.processor.feature_extractor.config.sampling_rate;return{audio:r.data,sampling_rate:a}}}class D extends f{constructor(e){super(e)}async _call(e){const t=await p(e),n=await this.processor(t),r=await this.model(n),i=[];for(const e of r.reconstruction){const t=e.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");i.push(c.RawImage.fromTensor(t))}return i.length>1?i:i[0]}}class R extends f{constructor(e){super(e)}async _call(e){const t=await p(e),n=await this.processor(t),{predicted_depth:r}=await this.model(n),i=[];for(let e=0;e1?i:i[0]}}const V=Object.freeze({"text-classification":{tokenizer:r.AutoTokenizer,pipeline:g,model:i.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:r.AutoTokenizer,pipeline:_,model:i.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:r.AutoTokenizer,pipeline:w,model:i.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:r.AutoTokenizer,pipeline:b,model:i.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:r.AutoTokenizer,pipeline:x,model:i.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:r.AutoTokenizer,pipeline:v,model:i.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:r.AutoTokenizer,pipeline:y,model:i.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:r.AutoTokenizer,pipeline:T,model:i.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:r.AutoTokenizer,pipeline:k,model:i.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:C,model:i.AutoModelForAudioClassification,processor:a.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:r.AutoTokenizer,pipeline:E,model:i.AutoModel,processor:a.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:r.AutoTokenizer,pipeline:P,model:[i.AutoModelForSpeechSeq2Seq,i.AutoModelForCTC],processor:a.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:r.AutoTokenizer,pipeline:N,model:[i.AutoModelForTextToWaveform,i.AutoModelForTextToSpectrogram],processor:[a.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:r.AutoTokenizer,pipeline:F,model:i.AutoModelForVision2Seq,processor:a.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:A,model:i.AutoModelForImageClassification,processor:a.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:I,model:[i.AutoModelForImageSegmentation,i.AutoModelForSemanticSegmentation,i.AutoModelForUniversalSegmentation],processor:a.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:r.AutoTokenizer,pipeline:z,model:i.AutoModel,processor:a.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:O,model:i.AutoModelForObjectDetection,processor:a.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:r.AutoTokenizer,pipeline:B,model:i.AutoModelForZeroShotObjectDetection,processor:a.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:r.AutoTokenizer,pipeline:L,model:i.AutoModelForDocumentQuestionAnswering,processor:a.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:D,model:i.AutoModelForImageToImage,processor:a.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:R,model:i.AutoModelForDepthEstimation,processor:a.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:r.AutoTokenizer,pipeline:$,model:i.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:a.AutoProcessor,pipeline:S,model:[i.AutoModelForImageFeatureExtraction,i.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),j=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function q(e,t=null,{progress_callback:n=null,config:r=null,cache_dir:i=null,local_files_only:a=!1,revision:s="main",device:l=null,dtype:u=null,model_file_name:d=null,session_options:c={}}={}){e=j[e]??e;const p=V[e.split("_",1)[0]];if(!p)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(V)}]`);t||(t=p.default.model,console.log(`No model specified. Using default model: "${t}".`));const h={progress_callback:n,config:r,cache_dir:i,local_files_only:a,revision:s,device:l,dtype:u,model_file_name:d,session_options:c},m=new Map([["tokenizer",p.tokenizer],["model",p.model],["processor",p.processor]]),f=await async function(e,t,n){const r=Object.create(null),i=[];for(const[a,s]of e.entries()){if(!s)continue;let e;e=Array.isArray(s)?new Promise((async(e,r)=>{let i;for(const a of s){if(null===a)return void e(null);try{return void e(await a.from_pretrained(t,n))}catch(e){if(e.message?.includes("Unsupported model type"))i=e;else{if(!e.message?.includes("Could not locate file"))return void r(e);i=e}}}r(i)})):s.from_pretrained(t,n),r[a]=e,i.push(e)}await Promise.all(i);for(const[e,t]of Object.entries(r))r[e]=await t;return r}(m,t,h);f.task=e,(0,o.dispatchCallback)(n,{status:"ready",task:e,model:t});return new(0,p.pipeline)(f)}},"./src/processors.js": /*!***************************!*\ !*** ./src/processors.js ***! - \***************************/(e,t,n)=>{n.r(t),n.d(t,{ASTFeatureExtractor:()=>ae,AutoProcessor:()=>we,BeitFeatureExtractor:()=>H,BitImageProcessor:()=>$,CLIPFeatureExtractor:()=>S,CLIPImageProcessor:()=>P,ChineseCLIPFeatureExtractor:()=>E,ClapFeatureExtractor:()=>se,ConvNextFeatureExtractor:()=>A,ConvNextImageProcessor:()=>I,DPTFeatureExtractor:()=>T,DPTImageProcessor:()=>k,DeiTFeatureExtractor:()=>U,DetrFeatureExtractor:()=>Q,DonutFeatureExtractor:()=>X,EfficientNetImageProcessor:()=>B,FeatureExtractor:()=>b,Florence2Processor:()=>_e,GLPNFeatureExtractor:()=>C,ImageFeatureExtractor:()=>y,MaskFormerFeatureExtractor:()=>Y,MobileNetV1FeatureExtractor:()=>L,MobileNetV2FeatureExtractor:()=>N,MobileNetV3FeatureExtractor:()=>D,MobileNetV4FeatureExtractor:()=>R,MobileViTFeatureExtractor:()=>V,MobileViTImageProcessor:()=>j,NougatImageProcessor:()=>K,OwlViTFeatureExtractor:()=>q,OwlViTProcessor:()=>ge,Owlv2ImageProcessor:()=>G,Processor:()=>de,PvtImageProcessor:()=>M,PyAnnoteFeatureExtractor:()=>oe,PyAnnoteProcessor:()=>me,RTDetrImageProcessor:()=>W,SamImageProcessor:()=>J,SamProcessor:()=>ce,SapiensFeatureExtractor:()=>x,SeamlessM4TFeatureExtractor:()=>ie,SegformerFeatureExtractor:()=>v,SiglipImageProcessor:()=>F,SpeechT5FeatureExtractor:()=>ue,SpeechT5Processor:()=>fe,Swin2SRImageProcessor:()=>ee,ViTFeatureExtractor:()=>z,ViTImageProcessor:()=>O,VitMatteImageProcessor:()=>te,Wav2Vec2FeatureExtractor:()=>re,Wav2Vec2ProcessorWithLM:()=>he,WeSpeakerFeatureExtractor:()=>le,WhisperFeatureExtractor:()=>ne,WhisperProcessor:()=>pe,YolosFeatureExtractor:()=>Z});var r=n(/*! ./utils/generic.js */"./src/utils/generic.js"),i=n(/*! ./utils/core.js */"./src/utils/core.js"),a=n(/*! ./utils/hub.js */"./src/utils/hub.js"),s=n(/*! ./utils/maths.js */"./src/utils/maths.js"),o=n(/*! ./utils/tensor.js */"./src/utils/tensor.js"),l=(n(/*! ./utils/image.js */"./src/utils/image.js"),n(/*! ./utils/audio.js */"./src/utils/audio.js"));function u([e,t,n,r]){return[e-n/2,t-r/2,e+n/2,t+r/2]}function d(e,t=.5,n=null,r=!1){const i=e.logits,a=e.pred_boxes,[o,l,d]=i.dims;if(null!==n&&n.length!==o)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=[];for(let e=0;et&&a.push(e)}else{let e=(0,s.max)(i.data)[1];if(e===d-1)continue;if(n=(0,s.softmax)(i.data),n[e]e*o[(t+1)%2]))),p.boxes.push(r),p.classes.push(t),p.scores.push(n[t])}}c.push(p)}return c}function c(e,t=null){const n=e.logits,r=n.dims[0];if(null!==t&&t.length!==r)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const i=[];for(let e=0;ed[n]&&(d[n]=t[n],c[n]=e)}const p=new Array(a.dims[0]);for(let e=0;evoid 0!==e));i.push({segmentation:u,labels:h})}return i}function p(e,t,n,r){const i=[],a=[],o=[];for(let l=0;ln&&(i.push(d),a.push(p),o.push(c))}return[i,a,o]}function h(e,t,n,r=.5,i=.8){const a=[];let s=0,o=0;const l=t[n].data;for(let t=0;t=r&&++o;let u=s>0&&o>0;if(u){u=s/o>i}return[u,a]}function m(e,t,n,r,i,a=null,s=null){const[l,u]=s??e[0].dims,d=new o.Tensor("int32",new Int32Array(l*u),[l,u]),c=[];if(null!==s)for(let t=0;tm[e]&&(p[e]=n,m[e]=i[e])}let f=0;const g=d.data;for(let a=0;ar&&(a=Math.floor(i)*t),ai?l=Math.floor(i*o/r):i>r&&(o=Math.floor(r*l/i)),await e.resize(l,o,{resample:n}))}async crop_margin(e,t=200){const n=e.clone().grayscale(),r=(0,s.min)(n.data)[0],i=(0,s.max)(n.data)[0]-r;if(0===i)return e;const a=t/255;let o=n.width,l=n.height,u=0,d=0;const c=n.data;for(let e=0;ethis.preprocess(e))));return{pixel_values:(0,o.stack)(n.map((e=>e.pixel_values)),0),original_sizes:n.map((e=>e.original_size)),reshaped_input_sizes:n.map((e=>e.reshaped_input_size))}}}class x extends y{post_process_semantic_segmentation(...e){return c(...e)}}class v extends y{post_process_semantic_segmentation(...e){return c(...e)}}class M extends y{}class T extends y{}class k extends T{}class $ extends y{}class C extends y{}class S extends y{}class P extends S{}class E extends y{}class F extends y{}class A extends y{constructor(e){super(e),this.crop_pct=this.config.crop_pct??.875}async resize(e){const t=this.size?.shortest_edge;if(void 0===t)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){const n=Math.floor(t/this.crop_pct),[r,i]=this.get_resize_output_image_size(e,{shortest_edge:n});e=await e.resize(r,i,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}}class I extends A{}class z extends y{}class O extends y{}class B extends y{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map((e=>e*e)))}}class L extends y{}class N extends y{}class D extends y{}class R extends y{}class V extends y{}class j extends V{}class q extends y{post_process_object_detection(...e){return d(...e)}}class G extends q{}class W extends y{post_process_object_detection(...e){return d(...e)}}class U extends y{}class H extends y{}class X extends y{pad_image(e,t,n,r={}){const[i,a,s]=t;let o=this.image_mean;Array.isArray(this.image_mean)||(o=new Array(s).fill(o));let l=this.image_std;Array.isArray(l)||(l=new Array(s).fill(o));const u=o.map(((e,t)=>-e/l[t]));return super.pad_image(e,t,n,{center:!0,constant_values:u,...r})}}class K extends X{}class Q extends y{async _call(e){const t=await super._call(e),n=[t.pixel_values.dims[0],64,64],r=(0,o.full)(n,1n);return{...t,pixel_mask:r}}post_process_object_detection(...e){return d(...e)}post_process_panoptic_segmentation(...e){return f(...e)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class Y extends y{post_process_panoptic_segmentation(...e){return f(...e)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class Z extends y{post_process_object_detection(...e){return d(...e)}}class J extends y{reshape_input_points(e,t,n,r=!1){e=structuredClone(e);let a=(0,i.calculateDimensions)(e);if(3===a.length)r||(a=[1,...a]),e=[e];else if(4!==a.length)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let r=0;re!==t.dims[n])))throw Error(`The first ${n.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new o.Tensor("int64",e.flat(1/0).map(BigInt),n)}async _call(e,{input_points:t=null,input_labels:n=null,input_boxes:r=null}={}){const i=await super._call(e);if(t&&(i.input_points=this.reshape_input_points(t,i.original_sizes,i.reshaped_input_sizes)),n){if(!i.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");i.input_labels=this.add_input_labels(n,i.input_points)}return r&&(i.input_boxes=this.reshape_input_points(r,i.original_sizes,i.reshaped_input_sizes,!0)),i}async post_process_masks(e,t,n,{mask_threshold:r=0,binarize:i=!0,pad_size:a=null}={}){const s=[],l=[(a=a??this.pad_size).height,a.width];for(let a=0;ar&&(t[n]=1);c=new o.Tensor("bool",t,c.dims)}s.push(c)}return s}generate_crop_boxes(e,t,{crop_n_layers:n=0,overlap_ratio:r=512/1500,points_per_crop:i=32,crop_n_points_downscale_factor:a=1}={}){}}class ee extends y{pad_image(e,t,n,r={}){const[i,a,s]=t;return super.pad_image(e,t,{width:a+(n-a%n)%n,height:i+(n-i%n)%n},{mode:"symmetric",center:!1,constant_values:-1,...r})}}class te extends y{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const n=await Promise.all(e.map((e=>this.preprocess(e)))),r=await Promise.all(t.map((e=>this.preprocess(e,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0}))));return{pixel_values:(0,o.stack)(n.map(((e,t)=>(0,o.cat)([e.pixel_values,r[t].pixel_values],0))),0),original_sizes:n.map((e=>e.original_size)),reshaped_input_sizes:n.map((e=>e.reshaped_input_size))}}}class ne extends b{constructor(e){super(e),this.config.mel_filters??=(0,l.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=(0,l.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(e){const t=await(0,l.spectrogram)(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),n=t.data,r=(0,s.max)(n)[0];for(let e=0;ethis.config.n_samples?(console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),t=e.slice(0,this.config.n_samples)):(t=new Float32Array(this.config.n_samples),t.set(e));return{input_features:(await this._extract_fbank_features(t)).unsqueeze_(0)}}}class re extends b{_zero_mean_unit_var_norm(e){const t=e.reduce(((e,t)=>e+t),0)/e.length,n=e.reduce(((e,n)=>e+(n-t)**2),0)/e.length;return e.map((e=>(e-t)/Math.sqrt(n+1e-7)))}async _call(e){g(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));const n=[1,t.length];return{input_values:new o.Tensor("float32",t,n),attention_mask:new o.Tensor("int64",new BigInt64Array(t.length).fill(1n),n)}}}class ie extends b{constructor(e){super(e);const t=this.config.sampling_rate,n=(0,l.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);for(let e=0;e32768*e)),(0,l.spectrogram)(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:n=2,do_normalize_per_mel_bins:r=!0,return_attention_mask:i=!0}={}){g(e,"SeamlessM4TFeatureExtractor");let a,s=await this._extract_fbank_features(e,this.config.max_length);if(r){const[e,t]=s.dims,n=s.data;for(let r=0;r0){const n=new Float32Array(t*(e+l));n.set(r),n.fill(this.config.padding_value,r.length);const u=e+l;s=new o.Tensor(s.type,n,[u,t]),i&&(a=new o.Tensor("int64",new BigInt64Array(u),[1,u]),a.data.fill(1n,0,e))}}const[l,u]=s.dims,d=this.config.stride;if(0!==l%d)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${d}).`);const c=s.view(1,Math.floor(l/d),u*d),p={input_features:c};if(i){const e=c.dims[1],t=new BigInt64Array(e);if(a){const e=a.data;for(let n=1,r=0;n0){if("rand_trunc"!==n)throw new Error(`Truncation strategy "${n}" not implemented`);{a=!0;const n=Math.floor(Math.random()*(s+1));e=e.subarray(n,n+t),i=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}}else{if(s<0){let n=new Float64Array(t);if(n.set(e),"repeat"===r)for(let r=e.length;r({id:e,start:t*n,end:r*n,confidence:i/(r-t)}))))}return r}}class le extends b{constructor(e){super(e);const t=this.config.sampling_rate,n=(0,l.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);for(let e=0;e32768*e)),(0,l.spectrogram)(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1.192092955078125e-7,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){g(e,"WeSpeakerFeatureExtractor");const t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(null===this.config.fbank_centering_span){const e=t.mean(1).data,n=t.data,[r,i,a]=t.dims;for(let t=0;t/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){"string"==typeof e&&(e=[e]);const t=[];for(const n of e)if(this.task_prompts_without_inputs.has(n))t.push(this.task_prompts_without_inputs.get(n));else{for(const[e,r]of this.task_prompts_with_input)if(n.includes(e)){t.push(r.replaceAll("{input}",n).replaceAll(e,""));break}t.length!==e.length&&t.push(n)}return t}post_process_generation(e,t,n){const r=this.tasks_answer_post_processing_type.get(t)??"pure_text";let i;switch(e=e.replaceAll("","").replaceAll("",""),r){case"pure_text":i=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const a="ocr"===r?"quad_boxes":"bboxes",s=e.matchAll(this.regexes[a]),o=[],l=[];for(const[e,t,...r]of s)o.push(t?t.trim():o.at(-1)??""),l.push(r.map(((e,t)=>(Number(e)+.5)/this.size_per_bin*n[t%2])));i={labels:o,[a]:l};break;default:throw new Error(`Task "${t}" (of type "${r}") not yet implemented.`)}return{[t]:i}}}class we{static FEATURE_EXTRACTOR_CLASS_MAPPING={ImageFeatureExtractor:y,WhisperFeatureExtractor:ne,ViTFeatureExtractor:z,MobileViTFeatureExtractor:V,MobileViTImageProcessor:j,MobileNetV1FeatureExtractor:L,MobileNetV2FeatureExtractor:N,MobileNetV3FeatureExtractor:D,MobileNetV4FeatureExtractor:R,OwlViTFeatureExtractor:q,Owlv2ImageProcessor:G,CLIPFeatureExtractor:S,CLIPImageProcessor:P,Florence2Processor:_e,ChineseCLIPFeatureExtractor:E,SiglipImageProcessor:F,ConvNextFeatureExtractor:A,ConvNextImageProcessor:I,SegformerFeatureExtractor:v,SapiensFeatureExtractor:x,BitImageProcessor:$,DPTImageProcessor:k,DPTFeatureExtractor:T,PvtImageProcessor:M,GLPNFeatureExtractor:C,BeitFeatureExtractor:H,DeiTFeatureExtractor:U,DetrFeatureExtractor:Q,RTDetrImageProcessor:W,MaskFormerFeatureExtractor:Y,YolosFeatureExtractor:Z,DonutFeatureExtractor:X,NougatImageProcessor:K,EfficientNetImageProcessor:B,ViTImageProcessor:O,VitMatteImageProcessor:te,SamImageProcessor:J,Swin2SRImageProcessor:ee,Wav2Vec2FeatureExtractor:re,SeamlessM4TFeatureExtractor:ie,SpeechT5FeatureExtractor:ue,ASTFeatureExtractor:ae,ClapFeatureExtractor:se,PyAnnoteFeatureExtractor:oe,WeSpeakerFeatureExtractor:le};static PROCESSOR_CLASS_MAPPING={WhisperProcessor:pe,Wav2Vec2ProcessorWithLM:he,PyAnnoteProcessor:me,SamProcessor:ce,SpeechT5Processor:fe,OwlViTProcessor:ge,Florence2Processor:_e};static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:s="main"}={}){let o=n??await(0,a.getModelJSON)(e,"preprocessor_config.json",!0,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:s}),l=o.feature_extractor_type??o.image_processor_type,u=this.FEATURE_EXTRACTOR_CLASS_MAPPING[l];if(!u){if(void 0===o.size)throw new Error(`Unknown Feature Extractor type: ${l}`);console.warn(`Feature extractor type "${l}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),u=y}return new(this.PROCESSOR_CLASS_MAPPING[o.processor_class]??de)(new u(o))}}},"./src/tokenizers.js": + \***************************/(e,t,n)=>{n.r(t),n.d(t,{ASTFeatureExtractor:()=>ae,AutoProcessor:()=>we,BeitFeatureExtractor:()=>H,BitImageProcessor:()=>$,CLIPFeatureExtractor:()=>C,CLIPImageProcessor:()=>E,ChineseCLIPFeatureExtractor:()=>P,ClapFeatureExtractor:()=>se,ConvNextFeatureExtractor:()=>A,ConvNextImageProcessor:()=>I,DPTFeatureExtractor:()=>T,DPTImageProcessor:()=>k,DeiTFeatureExtractor:()=>W,DetrFeatureExtractor:()=>Q,DonutFeatureExtractor:()=>K,EfficientNetImageProcessor:()=>B,FeatureExtractor:()=>b,Florence2Processor:()=>_e,GLPNFeatureExtractor:()=>S,ImageFeatureExtractor:()=>y,MaskFormerFeatureExtractor:()=>Y,MobileNetV1FeatureExtractor:()=>L,MobileNetV2FeatureExtractor:()=>N,MobileNetV3FeatureExtractor:()=>D,MobileNetV4FeatureExtractor:()=>R,MobileViTFeatureExtractor:()=>V,MobileViTImageProcessor:()=>j,NougatImageProcessor:()=>X,OwlViTFeatureExtractor:()=>q,OwlViTProcessor:()=>ge,Owlv2ImageProcessor:()=>G,Processor:()=>de,PvtImageProcessor:()=>M,PyAnnoteFeatureExtractor:()=>oe,PyAnnoteProcessor:()=>me,RTDetrImageProcessor:()=>U,SamImageProcessor:()=>J,SamProcessor:()=>ce,SapiensFeatureExtractor:()=>x,SeamlessM4TFeatureExtractor:()=>ie,SegformerFeatureExtractor:()=>v,SiglipImageProcessor:()=>F,SpeechT5FeatureExtractor:()=>ue,SpeechT5Processor:()=>fe,Swin2SRImageProcessor:()=>ee,ViTFeatureExtractor:()=>z,ViTImageProcessor:()=>O,VitMatteImageProcessor:()=>te,Wav2Vec2FeatureExtractor:()=>re,Wav2Vec2ProcessorWithLM:()=>he,WeSpeakerFeatureExtractor:()=>le,WhisperFeatureExtractor:()=>ne,WhisperProcessor:()=>pe,YolosFeatureExtractor:()=>Z});var r=n(/*! ./utils/generic.js */"./src/utils/generic.js"),i=n(/*! ./utils/core.js */"./src/utils/core.js"),a=n(/*! ./utils/hub.js */"./src/utils/hub.js"),s=n(/*! ./utils/maths.js */"./src/utils/maths.js"),o=n(/*! ./utils/tensor.js */"./src/utils/tensor.js"),l=(n(/*! ./utils/image.js */"./src/utils/image.js"),n(/*! ./utils/audio.js */"./src/utils/audio.js"));function u([e,t,n,r]){return[e-n/2,t-r/2,e+n/2,t+r/2]}function d(e,t=.5,n=null,r=!1){const i=e.logits,a=e.pred_boxes,[o,l,d]=i.dims;if(null!==n&&n.length!==o)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=[];for(let e=0;et&&a.push(e)}else{let e=(0,s.max)(i.data)[1];if(e===d-1)continue;if(n=(0,s.softmax)(i.data),n[e]e*o[(t+1)%2]))),p.boxes.push(r),p.classes.push(t),p.scores.push(n[t])}}c.push(p)}return c}function c(e,t=null){const n=e.logits,r=n.dims[0];if(null!==t&&t.length!==r)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const i=[];for(let e=0;ed[n]&&(d[n]=t[n],c[n]=e)}const p=new Array(a.dims[0]);for(let e=0;evoid 0!==e));i.push({segmentation:u,labels:h})}return i}function p(e,t,n,r){const i=[],a=[],o=[];for(let l=0;ln&&(i.push(d),a.push(p),o.push(c))}return[i,a,o]}function h(e,t,n,r=.5,i=.8){const a=[];let s=0,o=0;const l=t[n].data;for(let t=0;t=r&&++o;let u=s>0&&o>0;if(u){u=s/o>i}return[u,a]}function m(e,t,n,r,i,a=null,s=null){const[l,u]=s??e[0].dims,d=new o.Tensor("int32",new Int32Array(l*u),[l,u]),c=[];if(null!==s)for(let t=0;tm[e]&&(p[e]=n,m[e]=i[e])}let f=0;const g=d.data;for(let a=0;ar&&(a=Math.floor(i)*t),ai?l=Math.floor(i*o/r):i>r&&(o=Math.floor(r*l/i)),await e.resize(l,o,{resample:n}))}async crop_margin(e,t=200){const n=e.clone().grayscale(),r=(0,s.min)(n.data)[0],i=(0,s.max)(n.data)[0]-r;if(0===i)return e;const a=t/255;let o=n.width,l=n.height,u=0,d=0;const c=n.data;for(let e=0;ethis.preprocess(e))));return{pixel_values:(0,o.stack)(n.map((e=>e.pixel_values)),0),original_sizes:n.map((e=>e.original_size)),reshaped_input_sizes:n.map((e=>e.reshaped_input_size))}}}class x extends y{post_process_semantic_segmentation(...e){return c(...e)}}class v extends y{post_process_semantic_segmentation(...e){return c(...e)}}class M extends y{}class T extends y{}class k extends T{}class $ extends y{}class S extends y{}class C extends y{}class E extends C{}class P extends y{}class F extends y{}class A extends y{constructor(e){super(e),this.crop_pct=this.config.crop_pct??.875}async resize(e){const t=this.size?.shortest_edge;if(void 0===t)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){const n=Math.floor(t/this.crop_pct),[r,i]=this.get_resize_output_image_size(e,{shortest_edge:n});e=await e.resize(r,i,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}}class I extends A{}class z extends y{}class O extends y{}class B extends y{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map((e=>e*e)))}}class L extends y{}class N extends y{}class D extends y{}class R extends y{}class V extends y{}class j extends V{}class q extends y{post_process_object_detection(...e){return d(...e)}}class G extends q{}class U extends y{post_process_object_detection(...e){return d(...e)}}class W extends y{}class H extends y{}class K extends y{pad_image(e,t,n,r={}){const[i,a,s]=t;let o=this.image_mean;Array.isArray(this.image_mean)||(o=new Array(s).fill(o));let l=this.image_std;Array.isArray(l)||(l=new Array(s).fill(o));const u=o.map(((e,t)=>-e/l[t]));return super.pad_image(e,t,n,{center:!0,constant_values:u,...r})}}class X extends K{}class Q extends y{async _call(e){const t=await super._call(e),n=[t.pixel_values.dims[0],64,64],r=(0,o.full)(n,1n);return{...t,pixel_mask:r}}post_process_object_detection(...e){return d(...e)}post_process_panoptic_segmentation(...e){return f(...e)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class Y extends y{post_process_panoptic_segmentation(...e){return f(...e)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class Z extends y{post_process_object_detection(...e){return d(...e)}}class J extends y{reshape_input_points(e,t,n,r=!1){e=structuredClone(e);let a=(0,i.calculateDimensions)(e);if(3===a.length)r||(a=[1,...a]),e=[e];else if(4!==a.length)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let r=0;re!==t.dims[n])))throw Error(`The first ${n.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new o.Tensor("int64",e.flat(1/0).map(BigInt),n)}async _call(e,{input_points:t=null,input_labels:n=null,input_boxes:r=null}={}){const i=await super._call(e);if(t&&(i.input_points=this.reshape_input_points(t,i.original_sizes,i.reshaped_input_sizes)),n){if(!i.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");i.input_labels=this.add_input_labels(n,i.input_points)}return r&&(i.input_boxes=this.reshape_input_points(r,i.original_sizes,i.reshaped_input_sizes,!0)),i}async post_process_masks(e,t,n,{mask_threshold:r=0,binarize:i=!0,pad_size:a=null}={}){const s=[],l=[(a=a??this.pad_size).height,a.width];for(let a=0;ar&&(t[n]=1);c=new o.Tensor("bool",t,c.dims)}s.push(c)}return s}generate_crop_boxes(e,t,{crop_n_layers:n=0,overlap_ratio:r=512/1500,points_per_crop:i=32,crop_n_points_downscale_factor:a=1}={}){}}class ee extends y{pad_image(e,t,n,r={}){const[i,a,s]=t;return super.pad_image(e,t,{width:a+(n-a%n)%n,height:i+(n-i%n)%n},{mode:"symmetric",center:!1,constant_values:-1,...r})}}class te extends y{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const n=await Promise.all(e.map((e=>this.preprocess(e)))),r=await Promise.all(t.map((e=>this.preprocess(e,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0}))));return{pixel_values:(0,o.stack)(n.map(((e,t)=>(0,o.cat)([e.pixel_values,r[t].pixel_values],0))),0),original_sizes:n.map((e=>e.original_size)),reshaped_input_sizes:n.map((e=>e.reshaped_input_size))}}}class ne extends b{constructor(e){super(e),this.config.mel_filters??=(0,l.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=(0,l.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(e){const t=await(0,l.spectrogram)(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),n=t.data,r=(0,s.max)(n)[0];for(let e=0;ethis.config.n_samples?(console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),t=e.slice(0,this.config.n_samples)):(t=new Float32Array(this.config.n_samples),t.set(e));return{input_features:(await this._extract_fbank_features(t)).unsqueeze_(0)}}}class re extends b{_zero_mean_unit_var_norm(e){const t=e.reduce(((e,t)=>e+t),0)/e.length,n=e.reduce(((e,n)=>e+(n-t)**2),0)/e.length;return e.map((e=>(e-t)/Math.sqrt(n+1e-7)))}async _call(e){g(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));const n=[1,t.length];return{input_values:new o.Tensor("float32",t,n),attention_mask:new o.Tensor("int64",new BigInt64Array(t.length).fill(1n),n)}}}class ie extends b{constructor(e){super(e);const t=this.config.sampling_rate,n=(0,l.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);for(let e=0;e32768*e)),(0,l.spectrogram)(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:n=2,do_normalize_per_mel_bins:r=!0,return_attention_mask:i=!0}={}){g(e,"SeamlessM4TFeatureExtractor");let a,s=await this._extract_fbank_features(e,this.config.max_length);if(r){const[e,t]=s.dims,n=s.data;for(let r=0;r0){const n=new Float32Array(t*(e+l));n.set(r),n.fill(this.config.padding_value,r.length);const u=e+l;s=new o.Tensor(s.type,n,[u,t]),i&&(a=new o.Tensor("int64",new BigInt64Array(u),[1,u]),a.data.fill(1n,0,e))}}const[l,u]=s.dims,d=this.config.stride;if(0!==l%d)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${d}).`);const c=s.view(1,Math.floor(l/d),u*d),p={input_features:c};if(i){const e=c.dims[1],t=new BigInt64Array(e);if(a){const e=a.data;for(let n=1,r=0;n0){if("rand_trunc"!==n)throw new Error(`Truncation strategy "${n}" not implemented`);{a=!0;const n=Math.floor(Math.random()*(s+1));e=e.subarray(n,n+t),i=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}}else{if(s<0){let n=new Float64Array(t);if(n.set(e),"repeat"===r)for(let r=e.length;r({id:e,start:t*n,end:r*n,confidence:i/(r-t)}))))}return r}}class le extends b{constructor(e){super(e);const t=this.config.sampling_rate,n=(0,l.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);for(let e=0;e32768*e)),(0,l.spectrogram)(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1.192092955078125e-7,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){g(e,"WeSpeakerFeatureExtractor");const t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(null===this.config.fbank_centering_span){const e=t.mean(1).data,n=t.data,[r,i,a]=t.dims;for(let t=0;t/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){"string"==typeof e&&(e=[e]);const t=[];for(const n of e)if(this.task_prompts_without_inputs.has(n))t.push(this.task_prompts_without_inputs.get(n));else{for(const[e,r]of this.task_prompts_with_input)if(n.includes(e)){t.push(r.replaceAll("{input}",n).replaceAll(e,""));break}t.length!==e.length&&t.push(n)}return t}post_process_generation(e,t,n){const r=this.tasks_answer_post_processing_type.get(t)??"pure_text";let i;switch(e=e.replaceAll("","").replaceAll("",""),r){case"pure_text":i=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const a="ocr"===r?"quad_boxes":"bboxes",s=e.matchAll(this.regexes[a]),o=[],l=[];for(const[e,t,...r]of s)o.push(t?t.trim():o.at(-1)??""),l.push(r.map(((e,t)=>(Number(e)+.5)/this.size_per_bin*n[t%2])));i={labels:o,[a]:l};break;default:throw new Error(`Task "${t}" (of type "${r}") not yet implemented.`)}return{[t]:i}}}class we{static FEATURE_EXTRACTOR_CLASS_MAPPING={ImageFeatureExtractor:y,WhisperFeatureExtractor:ne,ViTFeatureExtractor:z,MobileViTFeatureExtractor:V,MobileViTImageProcessor:j,MobileNetV1FeatureExtractor:L,MobileNetV2FeatureExtractor:N,MobileNetV3FeatureExtractor:D,MobileNetV4FeatureExtractor:R,OwlViTFeatureExtractor:q,Owlv2ImageProcessor:G,CLIPFeatureExtractor:C,CLIPImageProcessor:E,Florence2Processor:_e,ChineseCLIPFeatureExtractor:P,SiglipImageProcessor:F,ConvNextFeatureExtractor:A,ConvNextImageProcessor:I,SegformerFeatureExtractor:v,SapiensFeatureExtractor:x,BitImageProcessor:$,DPTImageProcessor:k,DPTFeatureExtractor:T,PvtImageProcessor:M,GLPNFeatureExtractor:S,BeitFeatureExtractor:H,DeiTFeatureExtractor:W,DetrFeatureExtractor:Q,RTDetrImageProcessor:U,MaskFormerFeatureExtractor:Y,YolosFeatureExtractor:Z,DonutFeatureExtractor:K,NougatImageProcessor:X,EfficientNetImageProcessor:B,ViTImageProcessor:O,VitMatteImageProcessor:te,SamImageProcessor:J,Swin2SRImageProcessor:ee,Wav2Vec2FeatureExtractor:re,SeamlessM4TFeatureExtractor:ie,SpeechT5FeatureExtractor:ue,ASTFeatureExtractor:ae,ClapFeatureExtractor:se,PyAnnoteFeatureExtractor:oe,WeSpeakerFeatureExtractor:le};static PROCESSOR_CLASS_MAPPING={WhisperProcessor:pe,Wav2Vec2ProcessorWithLM:he,PyAnnoteProcessor:me,SamProcessor:ce,SpeechT5Processor:fe,OwlViTProcessor:ge,Florence2Processor:_e};static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:s="main"}={}){let o=n??await(0,a.getModelJSON)(e,"preprocessor_config.json",!0,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:s}),l=o.feature_extractor_type??o.image_processor_type,u=this.FEATURE_EXTRACTOR_CLASS_MAPPING[l];if(!u){if(void 0===o.size)throw new Error(`Unknown Feature Extractor type: ${l}`);console.warn(`Feature extractor type "${l}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),u=y}return new(this.PROCESSOR_CLASS_MAPPING[o.processor_class]??de)(new u(o))}}},"./src/tokenizers.js": /*!***************************!*\ !*** ./src/tokenizers.js ***! - \***************************/(e,t,n)=>{n.r(t),n.d(t,{AlbertTokenizer:()=>ve,AutoTokenizer:()=>ht,BartTokenizer:()=>Be,BertTokenizer:()=>xe,BlenderbotSmallTokenizer:()=>lt,BlenderbotTokenizer:()=>ot,BloomTokenizer:()=>Re,CLIPTokenizer:()=>rt,CamembertTokenizer:()=>Fe,CodeGenTokenizer:()=>nt,CodeLlamaTokenizer:()=>qe,CohereTokenizer:()=>pt,ConvBertTokenizer:()=>Se,DebertaTokenizer:()=>ke,DebertaV2Tokenizer:()=>$e,DistilBertTokenizer:()=>Ee,ElectraTokenizer:()=>Ie,EsmTokenizer:()=>Xe,FalconTokenizer:()=>Ue,GPT2Tokenizer:()=>Oe,GPTNeoXTokenizer:()=>He,GemmaTokenizer:()=>Qe,Grok1Tokenizer:()=>Ye,HerbertTokenizer:()=>Ce,LlamaTokenizer:()=>je,M2M100Tokenizer:()=>et,MBart50Tokenizer:()=>Ne,MBartTokenizer:()=>Le,MPNetTokenizer:()=>We,MarianTokenizer:()=>at,MobileBertTokenizer:()=>Me,NllbTokenizer:()=>Je,NougatTokenizer:()=>dt,PreTrainedTokenizer:()=>ye,Qwen2Tokenizer:()=>Ke,RoFormerTokenizer:()=>Pe,RobertaTokenizer:()=>De,SiglipTokenizer:()=>it,SpeechT5Tokenizer:()=>ut,SqueezeBertTokenizer:()=>Te,T5Tokenizer:()=>ze,TokenizerModel:()=>M,VitsTokenizer:()=>ct,Wav2Vec2CTCTokenizer:()=>st,WhisperTokenizer:()=>tt,XLMRobertaTokenizer:()=>Ge,XLMTokenizer:()=>Ae,is_chinese_char:()=>_});var r=n(/*! ./utils/generic.js */"./src/utils/generic.js"),i=n(/*! ./utils/core.js */"./src/utils/core.js"),a=n(/*! ./utils/hub.js */"./src/utils/hub.js"),s=n(/*! ./utils/maths.js */"./src/utils/maths.js"),o=n(/*! ./utils/tensor.js */"./src/utils/tensor.js"),l=n(/*! ./utils/data-structures.js */"./src/utils/data-structures.js"),u=n(/*! @huggingface/jinja */"./node_modules/@huggingface/jinja/dist/index.js"),d=n(/*! ./models/whisper/common_whisper.js */"./src/models/whisper/common_whisper.js");n(/*! ./utils/constants.js */"./src/utils/constants.js");async function c(e,t){const n=await Promise.all([(0,a.getModelJSON)(e,"tokenizer.json",!0,t),(0,a.getModelJSON)(e,"tokenizer_config.json",!0,t)]);return null!==t.legacy&&(n[1].legacy=t.legacy),n}function p(e,t=!0){if(void 0!==e.Regex){let t=e.Regex.replace(/\\([#&~])/g,"$1");for(const[e,n]of x)t=t.replaceAll(e,n);return new RegExp(t,"gu")}if(void 0!==e.String){const n=(0,i.escapeRegExp)(e.String);return new RegExp(t?n:`(${n})`,"gu")}return console.warn("Unknown pattern type:",e),null}function h(e){return new Map(Object.entries(e))}function m(e){const t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(1!==t[0])throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}function f(e){return e.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n\'t/g,"n't").replace(/ \'m/g,"'m").replace(/ \'s/g,"'s").replace(/ \'ve/g,"'ve").replace(/ \'re/g,"'re")}function g(e){return e.replace(/\p{M}/gu,"")}function _(e){return e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103}const w="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",b=new RegExp(`^[${w}]+$`,"gu"),y=".,!?…。,、।۔،",x=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],[` ?[^(\\s|[${y}])]+`,` ?[^\\s${y}]+`]]);class v{constructor(e){this.content=e.content,this.id=e.id,this.single_word=e.single_word??!1,this.lstrip=e.lstrip??!1,this.rstrip=e.rstrip??!1,this.special=e.special??!1,this.normalized=e.normalized??null}}class M extends r.Callable{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}static fromConfig(e,...t){switch(e.type){case"WordPiece":return new T(e);case"Unigram":return new k(e,...t);case"BPE":return new S(e);default:if(e.vocab)return Array.isArray(e.vocab)?new k(e,...t):new P(e,...t);throw new Error(`Unknown TokenizerModel type: ${e.type}`)}}_call(e){return e=this.encode(e),this.fuse_unk&&(e=function(e,t,n){const r=[];let i=0;for(;ithis.tokens_to_ids.get(e)??this.unk_token_id))}convert_ids_to_tokens(e){return e.map((e=>this.vocab[e]??this.unk_token))}}class T extends M{constructor(e){super(e),this.tokens_to_ids=h(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){const t=[];for(const n of e){const e=[...n];if(e.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let r=!1,i=0;const a=[];for(;i0&&(r=this.config.continuing_subword_prefix+r),this.tokens_to_ids.has(r)){n=r;break}--t}if(null===n){r=!0;break}a.push(n),i=t}r?t.push(this.unk_token):t.push(...a)}return t}}class k extends M{constructor(e,t){super(e);const n=e.vocab.length;this.vocab=new Array(n),this.scores=new Array(n);for(let t=0;t[e,t]))),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,s.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new l.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(e){const t=e.chars;let n=0;for(;n{const e=[...Array.from({length:"~".charCodeAt(0)-"!".charCodeAt(0)+1},((e,t)=>t+"!".charCodeAt(0))),...Array.from({length:"¬".charCodeAt(0)-"¡".charCodeAt(0)+1},((e,t)=>t+"¡".charCodeAt(0))),...Array.from({length:"ÿ".charCodeAt(0)-"®".charCodeAt(0)+1},((e,t)=>t+"®".charCodeAt(0)))],t=e.slice();let n=0;for(let r=0;r<256;++r)e.includes(r)||(e.push(r),t.push(256+n),n+=1);const r=t.map((e=>String.fromCharCode(e)));return Object.fromEntries(e.map(((e,t)=>[e,r[t]])))})(),C=(0,i.reverseDictionary)($);class S extends M{constructor(e){super(e),this.tokens_to_ids=h(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[e,t]of this.tokens_to_ids)this.vocab[t]=e;const t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map((e=>e.split(" ",2))),this.bpe_ranks=new Map(this.merges.map(((e,t)=>[JSON.stringify(e),t]))),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(e){if(0===e.length)return[];const t=this.cache.get(e);if(void 0!==t)return t;const n=Array.from(e);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){const e=new l.PriorityQueue(((e,t)=>e.score`<0x${e.toString(16).toUpperCase().padStart(2,"0")}>`));e.every((e=>this.tokens_to_ids.has(e)))?t.push(...e):t.push(this.unk_token)}else t.push(this.unk_token)}return t}}class P extends M{constructor(e,t){super(e),this.tokens_to_ids=h(t.target_lang?e.vocab[t.target_lang]:e.vocab),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){return e}}class E extends r.Callable{constructor(e){super(),this.config=e}static fromConfig(e){if(null===e)return null;switch(e.type){case"BertNormalizer":return new R(e);case"Precompiled":return new pe(e);case"Sequence":return new D(e);case"Replace":return new F(e);case"NFC":return new A(e);case"NFKC":return new I(e);case"NFKD":return new z(e);case"Strip":return new O(e);case"StripAccents":return new B(e);case"Lowercase":return new L(e);case"Prepend":return new N(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}normalize(e){throw Error("normalize should be implemented in subclass.")}_call(e){return this.normalize(e)}}class F extends E{normalize(e){const t=p(this.config.pattern);return null===t?e:e.replaceAll(t,this.config.content)}}class A extends E{normalize(e){return e=e.normalize("NFC")}}class I extends E{normalize(e){return e=e.normalize("NFKC")}}class z extends E{normalize(e){return e=e.normalize("NFKD")}}class O extends E{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}}class B extends E{normalize(e){return e=g(e)}}class L extends E{normalize(e){return e=e.toLowerCase()}}class N extends E{normalize(e){return e=this.config.prepend+e}}class D extends E{constructor(e){super(e),this.normalizers=e.normalizers.map((e=>E.fromConfig(e)))}normalize(e){return this.normalizers.reduce(((e,t)=>t.normalize(e)),e)}}class R extends E{_tokenize_chinese_chars(e){const t=[];for(let n=0;nthis.pre_tokenize_text(e,t))):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}}class j extends V{constructor(e){super(),this.pattern=new RegExp(`[^\\s${w}]+|[${w}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}}class q extends V{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=$,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e);return(this.use_regex?e.match(this.pattern)||[]:[e]).map((e=>Array.from(this.text_encoder.encode(e),(e=>this.byte_encoder[e])).join("")))}}class G extends V{constructor(e){super(),this.config=e,this.pattern=p(this.config.pattern,this.config.invert)}pre_tokenize_text(e,t){return null===this.pattern?[]:this.config.invert?e.match(this.pattern)||[]:function(e,t){const n=[];let r=0;for(const i of e.matchAll(t)){const t=i[0];r0&&n.push(t),r=i.index+t.length}return rH.fromConfig(e)))}post_process(e,t=null,n={}){let r;for(const i of this.processors)if(i instanceof Y){if(e=i.post_process(e).tokens,t){t=i.post_process(t).tokens}}else{const a=i.post_process(e,t,n);e=a.tokens,r=a.token_type_ids}return{tokens:e,token_type_ids:r}}}class J extends r.Callable{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=e.trim_offsets}static fromConfig(e){if(null===e)return null;switch(e.type){case"WordPiece":return new ie(e);case"Metaspace":return new ce(e);case"ByteLevel":return new ae(e);case"Replace":return new ee(e);case"ByteFallback":return new te(e);case"Fuse":return new ne(e);case"Strip":return new re(e);case"Sequence":return new oe(e);case"CTC":return new se(e);case"BPEDecoder":return new le(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}decode_chain(e){throw Error("`decode_chain` should be implemented in subclass.")}}class ee extends J{decode_chain(e){const t=p(this.config.pattern);return null===t?e:e.map((e=>e.replaceAll(t,this.config.content)))}}class te extends J{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const t=[];let n=[];for(const r of e){let e=null;if(6===r.length&&r.startsWith("<0x")&&r.endsWith(">")){const t=parseInt(r.slice(3,5),16);isNaN(t)||(e=t)}if(null!==e)n.push(e);else{if(n.length>0){const e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}t.push(r)}}if(n.length>0){const e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}return t}}class ne extends J{decode_chain(e){return[e.join("")]}}class re extends J{constructor(e){super(e),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(e){return e.map((e=>{let t=0;for(let n=0;n(0!==t&&(e=e.startsWith(this.config.prefix)?e.replace(this.config.prefix,""):" "+e),this.cleanup&&(e=f(e)),e)))}}class ae extends J{constructor(e){super(e),this.byte_decoder=C,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){const t=e.join(""),n=new Uint8Array([...t].map((e=>this.byte_decoder[e])));return this.text_decoder.decode(n)}decode_chain(e){const t=[];let n=[];for(const r of e)void 0!==this.added_tokens.find((e=>e.content===r))?(n.length>0&&(t.push(this.convert_tokens_to_string(n)),n=[]),t.push(r)):n.push(r);return n.length>0&&t.push(this.convert_tokens_to_string(n)),t}}class se extends J{constructor(e){super(e),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(e){if(0===e.length)return"";const t=[e[0]];for(let n=1;ne!==this.pad_token)).join("");return this.cleanup&&(n=f(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}}class oe extends J{constructor(e){super(e),this.decoders=e.decoders.map((e=>J.fromConfig(e)))}decode_chain(e){return this.decoders.reduce(((e,t)=>t.decode_chain(e)),e)}}class le extends J{constructor(e){super(e),this.suffix=this.config.suffix}decode_chain(e){return e.map(((t,n)=>t.replaceAll(this.suffix,n===e.length-1?"":" ")))}}class ue extends J{decode_chain(e){let t="";for(let n=1;ne.normalize("NFKC"))).join("~")}else e=e.normalize("NFKC");return e}}class he extends V{constructor(e){super(),this.tokenizers=e.pretokenizers.map((e=>V.fromConfig(e)))}pre_tokenize_text(e,t){return this.tokenizers.reduce(((e,n)=>n.pre_tokenize(e,t)),[e])}}class me extends V{constructor(e){super()}pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}}class fe extends V{constructor(e){super()}pre_tokenize_text(e,t){return function(e){return e.match(/\S+/g)||[]}(e)}}class ge extends V{constructor(e){super(),this.config=e,this.pattern=p(this.config.pattern),this.content=this.config.content}pre_tokenize_text(e,t){return null===this.pattern?[e]:[e.replaceAll(this.pattern,this.config.content)]}}const _e=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function we(e,t,n,r){for(const a of Object.keys(e)){const s=t-e[a].length,o=n(a),l=new Array(s).fill(o);e[a]="right"===r?(0,i.mergeArrays)(e[a],l):(0,i.mergeArrays)(l,e[a])}}function be(e,t){for(const n of Object.keys(e))e[n].length=t}class ye extends r.Callable{return_token_type_ids=!1;padding_side="right";constructor(e,t){super(),this._tokenizer_config=t,this.normalizer=E.fromConfig(e.normalizer),this.pre_tokenizer=V.fromConfig(e.pre_tokenizer),this.model=M.fromConfig(e.model,t),this.post_processor=H.fromConfig(e.post_processor),this.decoder=J.fromConfig(e.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const t of e.added_tokens){const e=new v(t);this.added_tokens.push(e),this.model.tokens_to_ids.set(e.content,e.id),this.model.vocab[e.id]=e.content,e.special&&(this.special_tokens.push(e.content),this.all_special_ids.push(e.id))}if(this.additional_special_tokens=t.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.slice().sort(((e,t)=>t.content.length-e.content.length)).map((e=>`${e.lstrip?"\\s*":""}(${(0,i.escapeRegExp)(e.content)})${e.rstrip?"\\s*":""}`)).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=t.model_max_length,this.remove_space=t.remove_space,this.clean_up_tokenization_spaces=t.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=t.do_lowercase_and_remove_accent??!1,t.padding_side&&(this.padding_side=t.padding_side),this.legacy=!1,this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){const e=Object.create(null);for(const{name:t,template:n}of this.chat_template){if("string"!=typeof t||"string"!=typeof n)throw new Error('Chat template must be a list of objects with "name" and "template" properties');e[t]=n}this.chat_template=e}this._compiled_template_cache=new Map}getToken(...e){for(const t of e){const e=this._tokenizer_config[t];if(e){if("object"==typeof e){if("AddedToken"===e.__type)return e.content;throw Error(`Unknown token: ${e}`)}return e}}return null}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a="main",legacy:s=null}={}){return new this(...await c(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a,legacy:s}))}_call(e,{text_pair:t=null,add_special_tokens:n=!0,padding:r=!1,truncation:i=null,max_length:a=null,return_tensor:l=!0,return_token_type_ids:u=null}={}){const d=Array.isArray(e);let c;if(d){if(0===e.length)throw Error("text array must be non-empty");if(null!==t){if(!Array.isArray(t))throw Error("text_pair must also be an array");if(e.length!==t.length)throw Error("text and text_pair must have the same length");c=e.map(((e,r)=>this._encode_plus(e,{text_pair:t[r],add_special_tokens:n,return_token_type_ids:u})))}else c=e.map((e=>this._encode_plus(e,{add_special_tokens:n,return_token_type_ids:u})))}else{if(null==e)throw Error("text may not be null or undefined");if(Array.isArray(t))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");c=[this._encode_plus(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:u})]}if(null===a?a="max_length"===r?this.model_max_length:(0,s.max)(c.map((e=>e.input_ids.length)))[0]:i||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),a=Math.min(a,this.model_max_length??1/0),r||i)for(let e=0;ea?i&&be(c[e],a):r&&we(c[e],a,(e=>"input_ids"===e?this.pad_token_id:0),this.padding_side));const p={};if(l){if((!r||!i)&&c.some((e=>{for(const t of Object.keys(e))if(e[t].length!==c[0][t]?.length)return!0;return!1})))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const e=[c.length,c[0].input_ids.length];for(const t of Object.keys(c[0]))p[t]=new o.Tensor("int64",BigInt64Array.from(c.flatMap((e=>e[t])).map(BigInt)),e)}else{for(const e of Object.keys(c[0]))p[e]=c.map((t=>t[e]));if(!d)for(const e of Object.keys(p))p[e]=p[e][0]}return p}_encode_text(e){if(null===e)return null;const t=(this.added_tokens_regex?e.split(this.added_tokens_regex).filter((e=>e)):[e]).map(((e,t)=>{if(void 0!==this.added_tokens.find((t=>t.content===e)))return e;{if(!0===this.remove_space&&(e=e.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(e=function(e){return g(e.toLowerCase())}(e)),null!==this.normalizer&&(e=this.normalizer(e)),0===e.length)return[];const n=null!==this.pre_tokenizer?this.pre_tokenizer(e,{section_index:t}):[e];return this.model(n)}})).flat();return t}_encode_plus(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){const{tokens:i,token_type_ids:a}=this._tokenize_helper(e,{pair:t,add_special_tokens:n}),s=this.model.convert_tokens_to_ids(i),o={input_ids:s,attention_mask:new Array(s.length).fill(1)};return(r??this.return_token_type_ids)&&a&&(o.token_type_ids=a),o}_tokenize_helper(e,{pair:t=null,add_special_tokens:n=!1}={}){const r=this._encode_text(e),a=this._encode_text(t);return this.post_processor?this.post_processor(r,a,{add_special_tokens:n}):{tokens:(0,i.mergeArrays)(r??[],a??[])}}tokenize(e,{pair:t=null,add_special_tokens:n=!1}={}){return this._tokenize_helper(e,{pair:t,add_special_tokens:n}).tokens}encode(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){return this._encode_plus(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:r}).input_ids}batch_decode(e,t={}){return e instanceof o.Tensor&&(e=e.tolist()),e.map((e=>this.decode(e,t)))}decode(e,t={}){if(e instanceof o.Tensor&&(e=m(e)),!Array.isArray(e)||0===e.length||!(0,i.isIntegralNumber)(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:n=null}){let r=this.model.convert_ids_to_tokens(e);t&&(r=r.filter((e=>!this.special_tokens.includes(e))));let i=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(i=i.replaceAll(this.decoder.end_of_word_suffix," "),t&&(i=i.trim())),(n??this.clean_up_tokenization_spaces)&&(i=f(i)),i}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&"object"==typeof this.chat_template){const n=this.chat_template;if(null!==e&&Object.hasOwn(n,e))e=n[e];else if(null===e)if(null!==t&&"tool_use"in n)e=n.tool_use;else{if(!("default"in n))throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(n).sort()}.`);e=n.default}}else if(null===e){if(!this.chat_template)throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");e=this.chat_template}return e}apply_chat_template(e,{tools:t=null,documents:n=null,chat_template:r=null,add_generation_prompt:i=!1,tokenize:a=!0,padding:s=!1,truncation:o=!1,max_length:l=null,return_tensor:d=!0,return_dict:c=!1,tokenizer_kwargs:p={},...h}={}){if("string"!=typeof(r=this.get_chat_template({chat_template:r,tools:t})))throw Error("chat_template must be a string, but got "+typeof r);let m=this._compiled_template_cache.get(r);void 0===m&&(m=new u.Template(r),this._compiled_template_cache.set(r,m));const f=Object.create(null);for(const e of _e){const t=this.getToken(e);t&&(f[e]=t)}const g=m.render({messages:e,add_generation_prompt:i,tools:t,documents:n,...f,...h});if(a){const e=this._call(g,{add_special_tokens:!1,padding:s,truncation:o,max_length:l,return_tensor:d,...p});return c?e:e.input_ids}return g}}class xe extends ye{return_token_type_ids=!0}class ve extends ye{return_token_type_ids=!0}class Me extends ye{return_token_type_ids=!0}class Te extends ye{return_token_type_ids=!0}class ke extends ye{return_token_type_ids=!0}class $e extends ye{return_token_type_ids=!0}class Ce extends ye{return_token_type_ids=!0}class Se extends ye{return_token_type_ids=!0}class Pe extends ye{return_token_type_ids=!0}class Ee extends ye{}class Fe extends ye{}class Ae extends ye{return_token_type_ids=!0;constructor(e,t){super(e,t),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class Ie extends ye{return_token_type_ids=!0}class ze extends ye{}class Oe extends ye{}class Be extends ye{}class Le extends ye{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter((e=>this.languageRegex.test(e))),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return Ze(this,e,t,n)}}class Ne extends Le{}class De extends ye{}class Re extends ye{}const Ve="▁";class je extends ye{padding_side="left";constructor(e,t){super(e,t),this.legacy=t.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new de({replacement:Ve,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(e){if(null===e)return null;if(this.legacy||0===e.length)return super._encode_text(e);let t=super._encode_text(Ve+e.replaceAll(Ve," "));return t.length>1&&t[0]===Ve&&this.special_tokens.includes(t[1])&&(t=t.slice(1)),t}}class qe extends ye{}class Ge extends ye{}class We extends ye{}class Ue extends ye{}class He extends ye{}class Xe extends ye{}class Ke extends ye{}class Qe extends ye{}class Ye extends ye{}function Ze(e,t,n,r){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in e&&e.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in e)||"function"!=typeof e.lang_to_token)throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const i=r.src_lang,a=r.tgt_lang;if(!e.language_codes.includes(a))throw new Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(void 0!==i){if(!e.language_codes.includes(i))throw new Error(`Source language code "${i}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(const t of e.post_processor.config.single)if("SpecialToken"in t&&e.languageRegex.test(t.SpecialToken.id)){t.SpecialToken.id=e.lang_to_token(i);break}}return r.forced_bos_token_id=e.model.convert_tokens_to_ids([e.lang_to_token(a)])[0],e._call(t,n)}class Je extends ye{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter((e=>this.languageRegex.test(e))),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return Ze(this,e,t,n)}}class et extends ye{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter((e=>this.languageRegex.test(e))).map((e=>e.slice(2,-2))),this.lang_to_token=e=>`__${e}__`}_build_translation_inputs(e,t,n){return Ze(this,e,t,n)}}class tt extends ye{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(e,{return_timestamps:t=!1,return_language:n=!1,time_precision:r=null,force_full_sequences:i=!0}={}){if(null===r)throw Error("Must specify time_precision");let a=null;const o="word"===t;function l(){return{language:a,timestamp:[null,null],text:""}}const u=[];let c=l(),p=0;const h=this.timestamp_begin;let m=[],f=[],g=!1,_=null;const w=new Set(this.all_special_ids);for(const n of e){const e=n.tokens,i=o?n.token_timestamps:null;let y=null,x=h;if("stride"in n){const[t,i,a]=n.stride;if(p-=i,_=t-a,i&&(x=i/r+h),a)for(let t=e.length-1;t>=0;--t){const n=Number(e[t]);if(n>=h){if(null!==y&&(n-h)*r<_)break;y=n}}}let v=[],M=[];for(let n=0;n=h){const e=(_-h)*r+p,t=(0,s.round)(e,2);if(null!==y&&_>=y)g=!0;else if(g||m.length>0&&_0?(m.push(v),o&&f.push(M)):m.every((e=>0===e.length))&&(c=l(),m=[],v=[],f=[],M=[])}if(m.length>0){if(i&&t)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[e,n]=this.findLongestCommonSequence(m,f),r=this.decode(e);c.text=r,o&&(c.words=this.collateWordTimestamps(e,n,a)),u.push(c)}let y=Object.create(null);const x=u.map((e=>e.text)).join("");if(t||n){for(let e=0;e0;let s=a?[]:null,o=a?t[0]:null;for(let l=1;le===g[n]&&o[i+n]<=t[l][m+n])).length:h.filter(((e,t)=>e===g[t])).length;const w=_/e+e/1e4;_>1&&w>d&&(d=w,c=[i,s,m,f])}const[h,m,f,g]=c,_=Math.floor((m+h)/2),w=Math.floor((g+f)/2);i.push(...n.slice(0,_)),n=u.slice(w),r=n.length,a&&(s.push(...o.slice(0,_)),o=t[l].slice(w))}return i.push(...n),a?(s.push(...o),[i,s]):[i,[]]}collateWordTimestamps(e,t,n){const[r,i,a]=this.combineTokensIntoWords(e,n),s=[];for(let e=0;e=r){const e=((t-r)*n).toFixed(2);i.push(`<|${e}|>`),i.push([])}else i[i.length-1].push(t);return i=i.map((e=>"string"==typeof e?e:super.decode(e,t))),i.join("")}splitTokensOnUnicode(e){const t=this.decode(e,{decode_with_timestamps:!0}),n=[],r=[],i=[];let a=[],s=[],o=0;for(let l=0;l=this.model.tokens_to_ids.get("<|endoftext|>"),p=l.startsWith(" "),h=l.trim(),m=o.test(h);if(c||p||m||0===i.length)i.push(l),a.push(u),s.push(d);else{const e=i.length-1;i[e]+=l,a[e].push(...u),s[e].push(...d)}}return[i,a,s]}mergePunctuations(e,t,n,r,a){const s=structuredClone(e),o=structuredClone(t),l=structuredClone(n);let u=s.length-2,d=s.length-1;for(;u>=0;)s[u].startsWith(" ")&&r.includes(s[u].trim())?(s[d]=s[u]+s[d],o[d]=(0,i.mergeArrays)(o[u],o[d]),l[d]=(0,i.mergeArrays)(l[u],l[d]),s[u]="",o[u]=[],l[u]=[]):d=u,--u;for(u=0,d=1;de)),o.filter((e=>e.length>0)),l.filter((e=>e.length>0))]}}class nt extends ye{}class rt extends ye{}class it extends ye{}class at extends ye{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter((e=>this.languageRegex.test(e))),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(null===e)return null;const[t,...n]=e.trim().split(this.languageRegex);if(0===n.length)return super._encode_text(t);if(2===n.length){const[e,t]=n;return this.supported_language_codes.includes(e)||console.warn(`Unsupported language code "${e}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,i.mergeArrays)([e],super._encode_text(t))}}}class st extends ye{}class ot extends ye{}class lt extends ye{}class ut extends ye{}class dt extends ye{}class ct extends ye{constructor(e,t){super(e,t),this.decoder=new ue({})}}class pt extends ye{}class ht{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:ze,DistilBertTokenizer:Ee,CamembertTokenizer:Fe,DebertaTokenizer:ke,DebertaV2Tokenizer:$e,BertTokenizer:xe,HerbertTokenizer:Ce,ConvBertTokenizer:Se,RoFormerTokenizer:Pe,XLMTokenizer:Ae,ElectraTokenizer:Ie,MobileBertTokenizer:Me,SqueezeBertTokenizer:Te,AlbertTokenizer:ve,GPT2Tokenizer:Oe,BartTokenizer:Be,MBartTokenizer:Le,MBart50Tokenizer:Ne,RobertaTokenizer:De,WhisperTokenizer:tt,CodeGenTokenizer:nt,CLIPTokenizer:rt,SiglipTokenizer:it,MarianTokenizer:at,BloomTokenizer:Re,NllbTokenizer:Je,M2M100Tokenizer:et,LlamaTokenizer:je,CodeLlamaTokenizer:qe,XLMRobertaTokenizer:Ge,MPNetTokenizer:We,FalconTokenizer:Ue,GPTNeoXTokenizer:He,EsmTokenizer:Xe,Wav2Vec2CTCTokenizer:st,BlenderbotTokenizer:ot,BlenderbotSmallTokenizer:lt,SpeechT5Tokenizer:ut,NougatTokenizer:dt,VitsTokenizer:ct,Qwen2Tokenizer:Ke,GemmaTokenizer:Qe,Grok1Tokenizer:Ye,CohereTokenizer:pt,PreTrainedTokenizer:ye};static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a="main",legacy:s=null}={}){const[o,l]=await c(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a,legacy:s}),u=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let d=this.TOKENIZER_CLASS_MAPPING[u];return d||(console.warn(`Unknown tokenizer class "${u}", attempting to construct from base class.`),d=ye),new d(o,l)}}},"./src/utils/audio.js": + \***************************/(e,t,n)=>{n.r(t),n.d(t,{AlbertTokenizer:()=>ve,AutoTokenizer:()=>ht,BartTokenizer:()=>Be,BertTokenizer:()=>xe,BlenderbotSmallTokenizer:()=>lt,BlenderbotTokenizer:()=>ot,BloomTokenizer:()=>Re,CLIPTokenizer:()=>rt,CamembertTokenizer:()=>Fe,CodeGenTokenizer:()=>nt,CodeLlamaTokenizer:()=>qe,CohereTokenizer:()=>pt,ConvBertTokenizer:()=>Ce,DebertaTokenizer:()=>ke,DebertaV2Tokenizer:()=>$e,DistilBertTokenizer:()=>Pe,ElectraTokenizer:()=>Ie,EsmTokenizer:()=>Ke,FalconTokenizer:()=>We,GPT2Tokenizer:()=>Oe,GPTNeoXTokenizer:()=>He,GemmaTokenizer:()=>Qe,Grok1Tokenizer:()=>Ye,HerbertTokenizer:()=>Se,LlamaTokenizer:()=>je,M2M100Tokenizer:()=>et,MBart50Tokenizer:()=>Ne,MBartTokenizer:()=>Le,MPNetTokenizer:()=>Ue,MarianTokenizer:()=>at,MobileBertTokenizer:()=>Me,NllbTokenizer:()=>Je,NougatTokenizer:()=>dt,PreTrainedTokenizer:()=>ye,Qwen2Tokenizer:()=>Xe,RoFormerTokenizer:()=>Ee,RobertaTokenizer:()=>De,SiglipTokenizer:()=>it,SpeechT5Tokenizer:()=>ut,SqueezeBertTokenizer:()=>Te,T5Tokenizer:()=>ze,TokenizerModel:()=>M,VitsTokenizer:()=>ct,Wav2Vec2CTCTokenizer:()=>st,WhisperTokenizer:()=>tt,XLMRobertaTokenizer:()=>Ge,XLMTokenizer:()=>Ae,is_chinese_char:()=>_});var r=n(/*! ./utils/generic.js */"./src/utils/generic.js"),i=n(/*! ./utils/core.js */"./src/utils/core.js"),a=n(/*! ./utils/hub.js */"./src/utils/hub.js"),s=n(/*! ./utils/maths.js */"./src/utils/maths.js"),o=n(/*! ./utils/tensor.js */"./src/utils/tensor.js"),l=n(/*! ./utils/data-structures.js */"./src/utils/data-structures.js"),u=n(/*! @huggingface/jinja */"./node_modules/@huggingface/jinja/dist/index.js"),d=n(/*! ./models/whisper/common_whisper.js */"./src/models/whisper/common_whisper.js");n(/*! ./utils/constants.js */"./src/utils/constants.js");async function c(e,t){const n=await Promise.all([(0,a.getModelJSON)(e,"tokenizer.json",!0,t),(0,a.getModelJSON)(e,"tokenizer_config.json",!0,t)]);return null!==t.legacy&&(n[1].legacy=t.legacy),n}function p(e,t=!0){if(void 0!==e.Regex){let t=e.Regex.replace(/\\([#&~])/g,"$1");for(const[e,n]of x)t=t.replaceAll(e,n);return new RegExp(t,"gu")}if(void 0!==e.String){const n=(0,i.escapeRegExp)(e.String);return new RegExp(t?n:`(${n})`,"gu")}return console.warn("Unknown pattern type:",e),null}function h(e){return new Map(Object.entries(e))}function m(e){const t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(1!==t[0])throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}function f(e){return e.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n\'t/g,"n't").replace(/ \'m/g,"'m").replace(/ \'s/g,"'s").replace(/ \'ve/g,"'ve").replace(/ \'re/g,"'re")}function g(e){return e.replace(/\p{M}/gu,"")}function _(e){return e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103}const w="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",b=new RegExp(`^[${w}]+$`,"gu"),y=".,!?…。,、।۔،",x=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],[` ?[^(\\s|[${y}])]+`,` ?[^\\s${y}]+`]]);class v{constructor(e){this.content=e.content,this.id=e.id,this.single_word=e.single_word??!1,this.lstrip=e.lstrip??!1,this.rstrip=e.rstrip??!1,this.special=e.special??!1,this.normalized=e.normalized??null}}class M extends r.Callable{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}static fromConfig(e,...t){switch(e.type){case"WordPiece":return new T(e);case"Unigram":return new k(e,...t);case"BPE":return new C(e);default:if(e.vocab)return Array.isArray(e.vocab)?new k(e,...t):new E(e,...t);throw new Error(`Unknown TokenizerModel type: ${e.type}`)}}_call(e){return e=this.encode(e),this.fuse_unk&&(e=function(e,t,n){const r=[];let i=0;for(;ithis.tokens_to_ids.get(e)??this.unk_token_id))}convert_ids_to_tokens(e){return e.map((e=>this.vocab[e]??this.unk_token))}}class T extends M{constructor(e){super(e),this.tokens_to_ids=h(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){const t=[];for(const n of e){const e=[...n];if(e.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let r=!1,i=0;const a=[];for(;i0&&(r=this.config.continuing_subword_prefix+r),this.tokens_to_ids.has(r)){n=r;break}--t}if(null===n){r=!0;break}a.push(n),i=t}r?t.push(this.unk_token):t.push(...a)}return t}}class k extends M{constructor(e,t){super(e);const n=e.vocab.length;this.vocab=new Array(n),this.scores=new Array(n);for(let t=0;t[e,t]))),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,s.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new l.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(e){const t=e.chars;let n=0;for(;n{const e=[...Array.from({length:"~".charCodeAt(0)-"!".charCodeAt(0)+1},((e,t)=>t+"!".charCodeAt(0))),...Array.from({length:"¬".charCodeAt(0)-"¡".charCodeAt(0)+1},((e,t)=>t+"¡".charCodeAt(0))),...Array.from({length:"ÿ".charCodeAt(0)-"®".charCodeAt(0)+1},((e,t)=>t+"®".charCodeAt(0)))],t=e.slice();let n=0;for(let r=0;r<256;++r)e.includes(r)||(e.push(r),t.push(256+n),n+=1);const r=t.map((e=>String.fromCharCode(e)));return Object.fromEntries(e.map(((e,t)=>[e,r[t]])))})(),S=(0,i.reverseDictionary)($);class C extends M{constructor(e){super(e),this.tokens_to_ids=h(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[e,t]of this.tokens_to_ids)this.vocab[t]=e;const t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map((e=>e.split(" ",2))),this.bpe_ranks=new Map(this.merges.map(((e,t)=>[JSON.stringify(e),t]))),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(e){if(0===e.length)return[];const t=this.cache.get(e);if(void 0!==t)return t;const n=Array.from(e);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){const e=new l.PriorityQueue(((e,t)=>e.score`<0x${e.toString(16).toUpperCase().padStart(2,"0")}>`));e.every((e=>this.tokens_to_ids.has(e)))?t.push(...e):t.push(this.unk_token)}else t.push(this.unk_token)}return t}}class E extends M{constructor(e,t){super(e),this.tokens_to_ids=h(t.target_lang?e.vocab[t.target_lang]:e.vocab),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){return e}}class P extends r.Callable{constructor(e){super(),this.config=e}static fromConfig(e){if(null===e)return null;switch(e.type){case"BertNormalizer":return new R(e);case"Precompiled":return new pe(e);case"Sequence":return new D(e);case"Replace":return new F(e);case"NFC":return new A(e);case"NFKC":return new I(e);case"NFKD":return new z(e);case"Strip":return new O(e);case"StripAccents":return new B(e);case"Lowercase":return new L(e);case"Prepend":return new N(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}normalize(e){throw Error("normalize should be implemented in subclass.")}_call(e){return this.normalize(e)}}class F extends P{normalize(e){const t=p(this.config.pattern);return null===t?e:e.replaceAll(t,this.config.content)}}class A extends P{normalize(e){return e=e.normalize("NFC")}}class I extends P{normalize(e){return e=e.normalize("NFKC")}}class z extends P{normalize(e){return e=e.normalize("NFKD")}}class O extends P{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}}class B extends P{normalize(e){return e=g(e)}}class L extends P{normalize(e){return e=e.toLowerCase()}}class N extends P{normalize(e){return e=this.config.prepend+e}}class D extends P{constructor(e){super(e),this.normalizers=e.normalizers.map((e=>P.fromConfig(e)))}normalize(e){return this.normalizers.reduce(((e,t)=>t.normalize(e)),e)}}class R extends P{_tokenize_chinese_chars(e){const t=[];for(let n=0;nthis.pre_tokenize_text(e,t))):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}}class j extends V{constructor(e){super(),this.pattern=new RegExp(`[^\\s${w}]+|[${w}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}}class q extends V{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=$,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e);return(this.use_regex?e.match(this.pattern)||[]:[e]).map((e=>Array.from(this.text_encoder.encode(e),(e=>this.byte_encoder[e])).join("")))}}class G extends V{constructor(e){super(),this.config=e,this.pattern=p(this.config.pattern,this.config.invert)}pre_tokenize_text(e,t){return null===this.pattern?[]:this.config.invert?e.match(this.pattern)||[]:function(e,t){const n=[];let r=0;for(const i of e.matchAll(t)){const t=i[0];r0&&n.push(t),r=i.index+t.length}return rH.fromConfig(e)))}post_process(e,t=null,n={}){let r;for(const i of this.processors)if(i instanceof Y){if(e=i.post_process(e).tokens,t){t=i.post_process(t).tokens}}else{const a=i.post_process(e,t,n);e=a.tokens,r=a.token_type_ids}return{tokens:e,token_type_ids:r}}}class J extends r.Callable{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=e.trim_offsets}static fromConfig(e){if(null===e)return null;switch(e.type){case"WordPiece":return new ie(e);case"Metaspace":return new ce(e);case"ByteLevel":return new ae(e);case"Replace":return new ee(e);case"ByteFallback":return new te(e);case"Fuse":return new ne(e);case"Strip":return new re(e);case"Sequence":return new oe(e);case"CTC":return new se(e);case"BPEDecoder":return new le(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}decode_chain(e){throw Error("`decode_chain` should be implemented in subclass.")}}class ee extends J{decode_chain(e){const t=p(this.config.pattern);return null===t?e:e.map((e=>e.replaceAll(t,this.config.content)))}}class te extends J{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){const t=[];let n=[];for(const r of e){let e=null;if(6===r.length&&r.startsWith("<0x")&&r.endsWith(">")){const t=parseInt(r.slice(3,5),16);isNaN(t)||(e=t)}if(null!==e)n.push(e);else{if(n.length>0){const e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}t.push(r)}}if(n.length>0){const e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}return t}}class ne extends J{decode_chain(e){return[e.join("")]}}class re extends J{constructor(e){super(e),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(e){return e.map((e=>{let t=0;for(let n=0;n(0!==t&&(e=e.startsWith(this.config.prefix)?e.replace(this.config.prefix,""):" "+e),this.cleanup&&(e=f(e)),e)))}}class ae extends J{constructor(e){super(e),this.byte_decoder=S,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){const t=e.join(""),n=new Uint8Array([...t].map((e=>this.byte_decoder[e])));return this.text_decoder.decode(n)}decode_chain(e){const t=[];let n=[];for(const r of e)void 0!==this.added_tokens.find((e=>e.content===r))?(n.length>0&&(t.push(this.convert_tokens_to_string(n)),n=[]),t.push(r)):n.push(r);return n.length>0&&t.push(this.convert_tokens_to_string(n)),t}}class se extends J{constructor(e){super(e),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(e){if(0===e.length)return"";const t=[e[0]];for(let n=1;ne!==this.pad_token)).join("");return this.cleanup&&(n=f(n).replaceAll(this.word_delimiter_token," ").trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}}class oe extends J{constructor(e){super(e),this.decoders=e.decoders.map((e=>J.fromConfig(e)))}decode_chain(e){return this.decoders.reduce(((e,t)=>t.decode_chain(e)),e)}}class le extends J{constructor(e){super(e),this.suffix=this.config.suffix}decode_chain(e){return e.map(((t,n)=>t.replaceAll(this.suffix,n===e.length-1?"":" ")))}}class ue extends J{decode_chain(e){let t="";for(let n=1;ne.normalize("NFKC"))).join("~")}else e=e.normalize("NFKC");return e}}class he extends V{constructor(e){super(),this.tokenizers=e.pretokenizers.map((e=>V.fromConfig(e)))}pre_tokenize_text(e,t){return this.tokenizers.reduce(((e,n)=>n.pre_tokenize(e,t)),[e])}}class me extends V{constructor(e){super()}pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}}class fe extends V{constructor(e){super()}pre_tokenize_text(e,t){return function(e){return e.match(/\S+/g)||[]}(e)}}class ge extends V{constructor(e){super(),this.config=e,this.pattern=p(this.config.pattern),this.content=this.config.content}pre_tokenize_text(e,t){return null===this.pattern?[e]:[e.replaceAll(this.pattern,this.config.content)]}}const _e=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function we(e,t,n,r){for(const a of Object.keys(e)){const s=t-e[a].length,o=n(a),l=new Array(s).fill(o);e[a]="right"===r?(0,i.mergeArrays)(e[a],l):(0,i.mergeArrays)(l,e[a])}}function be(e,t){for(const n of Object.keys(e))e[n].length=t}class ye extends r.Callable{return_token_type_ids=!1;padding_side="right";constructor(e,t){super(),this._tokenizer_config=t,this.normalizer=P.fromConfig(e.normalizer),this.pre_tokenizer=V.fromConfig(e.pre_tokenizer),this.model=M.fromConfig(e.model,t),this.post_processor=H.fromConfig(e.post_processor),this.decoder=J.fromConfig(e.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const t of e.added_tokens){const e=new v(t);this.added_tokens.push(e),this.model.tokens_to_ids.set(e.content,e.id),this.model.vocab[e.id]=e.content,e.special&&(this.special_tokens.push(e.content),this.all_special_ids.push(e.id))}if(this.additional_special_tokens=t.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.slice().sort(((e,t)=>t.content.length-e.content.length)).map((e=>`${e.lstrip?"\\s*":""}(${(0,i.escapeRegExp)(e.content)})${e.rstrip?"\\s*":""}`)).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=t.model_max_length,this.remove_space=t.remove_space,this.clean_up_tokenization_spaces=t.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=t.do_lowercase_and_remove_accent??!1,t.padding_side&&(this.padding_side=t.padding_side),this.legacy=!1,this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){const e=Object.create(null);for(const{name:t,template:n}of this.chat_template){if("string"!=typeof t||"string"!=typeof n)throw new Error('Chat template must be a list of objects with "name" and "template" properties');e[t]=n}this.chat_template=e}this._compiled_template_cache=new Map}getToken(...e){for(const t of e){const e=this._tokenizer_config[t];if(e){if("object"==typeof e){if("AddedToken"===e.__type)return e.content;throw Error(`Unknown token: ${e}`)}return e}}return null}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a="main",legacy:s=null}={}){return new this(...await c(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a,legacy:s}))}_call(e,{text_pair:t=null,add_special_tokens:n=!0,padding:r=!1,truncation:i=null,max_length:a=null,return_tensor:l=!0,return_token_type_ids:u=null}={}){const d=Array.isArray(e);let c;if(d){if(0===e.length)throw Error("text array must be non-empty");if(null!==t){if(!Array.isArray(t))throw Error("text_pair must also be an array");if(e.length!==t.length)throw Error("text and text_pair must have the same length");c=e.map(((e,r)=>this._encode_plus(e,{text_pair:t[r],add_special_tokens:n,return_token_type_ids:u})))}else c=e.map((e=>this._encode_plus(e,{add_special_tokens:n,return_token_type_ids:u})))}else{if(null==e)throw Error("text may not be null or undefined");if(Array.isArray(t))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");c=[this._encode_plus(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:u})]}if(null===a?a="max_length"===r?this.model_max_length:(0,s.max)(c.map((e=>e.input_ids.length)))[0]:i||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),a=Math.min(a,this.model_max_length??1/0),r||i)for(let e=0;ea?i&&be(c[e],a):r&&we(c[e],a,(e=>"input_ids"===e?this.pad_token_id:0),this.padding_side));const p={};if(l){if((!r||!i)&&c.some((e=>{for(const t of Object.keys(e))if(e[t].length!==c[0][t]?.length)return!0;return!1})))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const e=[c.length,c[0].input_ids.length];for(const t of Object.keys(c[0]))p[t]=new o.Tensor("int64",BigInt64Array.from(c.flatMap((e=>e[t])).map(BigInt)),e)}else{for(const e of Object.keys(c[0]))p[e]=c.map((t=>t[e]));if(!d)for(const e of Object.keys(p))p[e]=p[e][0]}return p}_encode_text(e){if(null===e)return null;const t=(this.added_tokens_regex?e.split(this.added_tokens_regex).filter((e=>e)):[e]).map(((e,t)=>{if(void 0!==this.added_tokens.find((t=>t.content===e)))return e;{if(!0===this.remove_space&&(e=e.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(e=function(e){return g(e.toLowerCase())}(e)),null!==this.normalizer&&(e=this.normalizer(e)),0===e.length)return[];const n=null!==this.pre_tokenizer?this.pre_tokenizer(e,{section_index:t}):[e];return this.model(n)}})).flat();return t}_encode_plus(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){const{tokens:i,token_type_ids:a}=this._tokenize_helper(e,{pair:t,add_special_tokens:n}),s=this.model.convert_tokens_to_ids(i),o={input_ids:s,attention_mask:new Array(s.length).fill(1)};return(r??this.return_token_type_ids)&&a&&(o.token_type_ids=a),o}_tokenize_helper(e,{pair:t=null,add_special_tokens:n=!1}={}){const r=this._encode_text(e),a=this._encode_text(t);return this.post_processor?this.post_processor(r,a,{add_special_tokens:n}):{tokens:(0,i.mergeArrays)(r??[],a??[])}}tokenize(e,{pair:t=null,add_special_tokens:n=!1}={}){return this._tokenize_helper(e,{pair:t,add_special_tokens:n}).tokens}encode(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){return this._encode_plus(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:r}).input_ids}batch_decode(e,t={}){return e instanceof o.Tensor&&(e=e.tolist()),e.map((e=>this.decode(e,t)))}decode(e,t={}){if(e instanceof o.Tensor&&(e=m(e)),!Array.isArray(e)||0===e.length||!(0,i.isIntegralNumber)(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:n=null}){let r=this.model.convert_ids_to_tokens(e);t&&(r=r.filter((e=>!this.special_tokens.includes(e))));let i=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(i=i.replaceAll(this.decoder.end_of_word_suffix," "),t&&(i=i.trim())),(n??this.clean_up_tokenization_spaces)&&(i=f(i)),i}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&"object"==typeof this.chat_template){const n=this.chat_template;if(null!==e&&Object.hasOwn(n,e))e=n[e];else if(null===e)if(null!==t&&"tool_use"in n)e=n.tool_use;else{if(!("default"in n))throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(n).sort()}.`);e=n.default}}else if(null===e){if(!this.chat_template)throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");e=this.chat_template}return e}apply_chat_template(e,{tools:t=null,documents:n=null,chat_template:r=null,add_generation_prompt:i=!1,tokenize:a=!0,padding:s=!1,truncation:o=!1,max_length:l=null,return_tensor:d=!0,return_dict:c=!1,tokenizer_kwargs:p={},...h}={}){if("string"!=typeof(r=this.get_chat_template({chat_template:r,tools:t})))throw Error("chat_template must be a string, but got "+typeof r);let m=this._compiled_template_cache.get(r);void 0===m&&(m=new u.Template(r),this._compiled_template_cache.set(r,m));const f=Object.create(null);for(const e of _e){const t=this.getToken(e);t&&(f[e]=t)}const g=m.render({messages:e,add_generation_prompt:i,tools:t,documents:n,...f,...h});if(a){const e=this._call(g,{add_special_tokens:!1,padding:s,truncation:o,max_length:l,return_tensor:d,...p});return c?e:e.input_ids}return g}}class xe extends ye{return_token_type_ids=!0}class ve extends ye{return_token_type_ids=!0}class Me extends ye{return_token_type_ids=!0}class Te extends ye{return_token_type_ids=!0}class ke extends ye{return_token_type_ids=!0}class $e extends ye{return_token_type_ids=!0}class Se extends ye{return_token_type_ids=!0}class Ce extends ye{return_token_type_ids=!0}class Ee extends ye{return_token_type_ids=!0}class Pe extends ye{}class Fe extends ye{}class Ae extends ye{return_token_type_ids=!0;constructor(e,t){super(e,t),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class Ie extends ye{return_token_type_ids=!0}class ze extends ye{}class Oe extends ye{}class Be extends ye{}class Le extends ye{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter((e=>this.languageRegex.test(e))),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return Ze(this,e,t,n)}}class Ne extends Le{}class De extends ye{}class Re extends ye{}const Ve="▁";class je extends ye{padding_side="left";constructor(e,t){super(e,t),this.legacy=t.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new de({replacement:Ve,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(e){if(null===e)return null;if(this.legacy||0===e.length)return super._encode_text(e);let t=super._encode_text(Ve+e.replaceAll(Ve," "));return t.length>1&&t[0]===Ve&&this.special_tokens.includes(t[1])&&(t=t.slice(1)),t}}class qe extends ye{}class Ge extends ye{}class Ue extends ye{}class We extends ye{}class He extends ye{}class Ke extends ye{}class Xe extends ye{}class Qe extends ye{}class Ye extends ye{}function Ze(e,t,n,r){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in e&&e.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in e)||"function"!=typeof e.lang_to_token)throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const i=r.src_lang,a=r.tgt_lang;if(!e.language_codes.includes(a))throw new Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(void 0!==i){if(!e.language_codes.includes(i))throw new Error(`Source language code "${i}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(const t of e.post_processor.config.single)if("SpecialToken"in t&&e.languageRegex.test(t.SpecialToken.id)){t.SpecialToken.id=e.lang_to_token(i);break}}return r.forced_bos_token_id=e.model.convert_tokens_to_ids([e.lang_to_token(a)])[0],e._call(t,n)}class Je extends ye{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter((e=>this.languageRegex.test(e))),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return Ze(this,e,t,n)}}class et extends ye{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter((e=>this.languageRegex.test(e))).map((e=>e.slice(2,-2))),this.lang_to_token=e=>`__${e}__`}_build_translation_inputs(e,t,n){return Ze(this,e,t,n)}}class tt extends ye{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(e,{return_timestamps:t=!1,return_language:n=!1,time_precision:r=null,force_full_sequences:i=!0}={}){if(null===r)throw Error("Must specify time_precision");let a=null;const o="word"===t;function l(){return{language:a,timestamp:[null,null],text:""}}const u=[];let c=l(),p=0;const h=this.timestamp_begin;let m=[],f=[],g=!1,_=null;const w=new Set(this.all_special_ids);for(const n of e){const e=n.tokens,i=o?n.token_timestamps:null;let y=null,x=h;if("stride"in n){const[t,i,a]=n.stride;if(p-=i,_=t-a,i&&(x=i/r+h),a)for(let t=e.length-1;t>=0;--t){const n=Number(e[t]);if(n>=h){if(null!==y&&(n-h)*r<_)break;y=n}}}let v=[],M=[];for(let n=0;n=h){const e=(_-h)*r+p,t=(0,s.round)(e,2);if(null!==y&&_>=y)g=!0;else if(g||m.length>0&&_0?(m.push(v),o&&f.push(M)):m.every((e=>0===e.length))&&(c=l(),m=[],v=[],f=[],M=[])}if(m.length>0){if(i&&t)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[e,n]=this.findLongestCommonSequence(m,f),r=this.decode(e);c.text=r,o&&(c.words=this.collateWordTimestamps(e,n,a)),u.push(c)}let y=Object.create(null);const x=u.map((e=>e.text)).join("");if(t||n){for(let e=0;e0;let s=a?[]:null,o=a?t[0]:null;for(let l=1;le===g[n]&&o[i+n]<=t[l][m+n])).length:h.filter(((e,t)=>e===g[t])).length;const w=_/e+e/1e4;_>1&&w>d&&(d=w,c=[i,s,m,f])}const[h,m,f,g]=c,_=Math.floor((m+h)/2),w=Math.floor((g+f)/2);i.push(...n.slice(0,_)),n=u.slice(w),r=n.length,a&&(s.push(...o.slice(0,_)),o=t[l].slice(w))}return i.push(...n),a?(s.push(...o),[i,s]):[i,[]]}collateWordTimestamps(e,t,n){const[r,i,a]=this.combineTokensIntoWords(e,n),s=[];for(let e=0;e=r){const e=((t-r)*n).toFixed(2);i.push(`<|${e}|>`),i.push([])}else i[i.length-1].push(t);return i=i.map((e=>"string"==typeof e?e:super.decode(e,t))),i.join("")}splitTokensOnUnicode(e){const t=this.decode(e,{decode_with_timestamps:!0}),n=[],r=[],i=[];let a=[],s=[],o=0;for(let l=0;l=this.model.tokens_to_ids.get("<|endoftext|>"),p=l.startsWith(" "),h=l.trim(),m=o.test(h);if(c||p||m||0===i.length)i.push(l),a.push(u),s.push(d);else{const e=i.length-1;i[e]+=l,a[e].push(...u),s[e].push(...d)}}return[i,a,s]}mergePunctuations(e,t,n,r,a){const s=structuredClone(e),o=structuredClone(t),l=structuredClone(n);let u=s.length-2,d=s.length-1;for(;u>=0;)s[u].startsWith(" ")&&r.includes(s[u].trim())?(s[d]=s[u]+s[d],o[d]=(0,i.mergeArrays)(o[u],o[d]),l[d]=(0,i.mergeArrays)(l[u],l[d]),s[u]="",o[u]=[],l[u]=[]):d=u,--u;for(u=0,d=1;de)),o.filter((e=>e.length>0)),l.filter((e=>e.length>0))]}}class nt extends ye{}class rt extends ye{}class it extends ye{}class at extends ye{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter((e=>this.languageRegex.test(e))),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(null===e)return null;const[t,...n]=e.trim().split(this.languageRegex);if(0===n.length)return super._encode_text(t);if(2===n.length){const[e,t]=n;return this.supported_language_codes.includes(e)||console.warn(`Unsupported language code "${e}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,i.mergeArrays)([e],super._encode_text(t))}}}class st extends ye{}class ot extends ye{}class lt extends ye{}class ut extends ye{}class dt extends ye{}class ct extends ye{constructor(e,t){super(e,t),this.decoder=new ue({})}}class pt extends ye{}class ht{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:ze,DistilBertTokenizer:Pe,CamembertTokenizer:Fe,DebertaTokenizer:ke,DebertaV2Tokenizer:$e,BertTokenizer:xe,HerbertTokenizer:Se,ConvBertTokenizer:Ce,RoFormerTokenizer:Ee,XLMTokenizer:Ae,ElectraTokenizer:Ie,MobileBertTokenizer:Me,SqueezeBertTokenizer:Te,AlbertTokenizer:ve,GPT2Tokenizer:Oe,BartTokenizer:Be,MBartTokenizer:Le,MBart50Tokenizer:Ne,RobertaTokenizer:De,WhisperTokenizer:tt,CodeGenTokenizer:nt,CLIPTokenizer:rt,SiglipTokenizer:it,MarianTokenizer:at,BloomTokenizer:Re,NllbTokenizer:Je,M2M100Tokenizer:et,LlamaTokenizer:je,CodeLlamaTokenizer:qe,XLMRobertaTokenizer:Ge,MPNetTokenizer:Ue,FalconTokenizer:We,GPTNeoXTokenizer:He,EsmTokenizer:Ke,Wav2Vec2CTCTokenizer:st,BlenderbotTokenizer:ot,BlenderbotSmallTokenizer:lt,SpeechT5Tokenizer:ut,NougatTokenizer:dt,VitsTokenizer:ct,Qwen2Tokenizer:Xe,GemmaTokenizer:Qe,Grok1Tokenizer:Ye,CohereTokenizer:pt,PreTrainedTokenizer:ye};static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a="main",legacy:s=null}={}){const[o,l]=await c(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a,legacy:s}),u=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let d=this.TOKENIZER_CLASS_MAPPING[u];return d||(console.warn(`Unknown tokenizer class "${u}", attempting to construct from base class.`),d=ye),new d(o,l)}}},"./src/utils/audio.js": /*!****************************!*\ !*** ./src/utils/audio.js ***! - \****************************/(e,t,n)=>{n.r(t),n.d(t,{hamming:()=>d,hanning:()=>u,mel_filter_bank:()=>f,read_audio:()=>o,spectrogram:()=>_,window_function:()=>w});var r=n(/*! ./hub.js */"./src/utils/hub.js"),i=n(/*! ./maths.js */"./src/utils/maths.js"),a=n(/*! ./core.js */"./src/utils/core.js"),s=n(/*! ./tensor.js */"./src/utils/tensor.js");async function o(e,t){if("undefined"==typeof AudioContext)throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const n=await(await(0,r.getFile)(e)).arrayBuffer(),i=new AudioContext({sampleRate:t});void 0===t&&console.warn(`No sampling rate provided, using default of ${i.sampleRate}Hz.`);const a=await i.decodeAudioData(n);let s;if(2===a.numberOfChannels){const e=Math.sqrt(2),t=a.getChannelData(0),n=a.getChannelData(1);s=new Float32Array(t.length);for(let r=0;r2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,n=15,r=27/Math.log(6.4))=>e>=t?n+Math.log(e/t)*r:3*e/200};function p(e,t="htk"){const n=c[t];if(!n)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return"number"==typeof e?n(e):e.map((e=>n(e)))}const h={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,n=15,r=Math.log(6.4)/27)=>e>=n?t*Math.exp(r*(e-n)):200*e/3};function m(e,t,n){const r=(t-e)/(n-1);return Float64Array.from({length:n},((t,n)=>e+r*n))}function f(e,t,n,r,i,a=null,s="htk",o=!1){if(null!==a&&"slaney"!==a)throw new Error('norm must be one of null or "slaney"');const l=m(p(n,s),p(r,s),t+2);let u,d=function(e,t="htk"){const n=h[t];if(!n)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return"number"==typeof e?n(e):e.map((e=>n(e)))}(l,s);if(o){const t=i/(2*e);u=p(Float64Array.from({length:e},((e,n)=>n*t)),s),d=l}else u=m(0,Math.floor(i/2),e);const c=function(e,t){const n=Float64Array.from({length:t.length-1},((e,n)=>t[n+1]-t[n])),r=Array.from({length:e.length},(()=>new Array(t.length)));for(let n=0;nnew Array(e.length)));for(let t=0;to)throw Error(`frame_length (${n}) may not be larger than fft_length (${o})`);if(k!==n)throw new Error(`Length of the window (${k}) must equal frame_length (${n})`);if(r<=0)throw new Error("hop_length must be greater than zero");if(null===l&&null!==h)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(u){if("reflect"!==d)throw new Error(`pad_mode="${d}" not implemented yet.`);const t=Math.floor((o-1)/2)+1;e=function(e,t,n){const r=new e.constructor(e.length+t+n),i=e.length-1;for(let n=0;n$?M&&(P=v):P=S=v);const E=new i.FFT(o),F=new Float64Array(o),A=new Float64Array(E.outputBufferSize),I=new Float32Array(C*P);for(let i=0;i=1;--e)F[e]-=p*F[e-1];F[0]*=1-p}for(let e=0;eMath.pow(e,.85)));break;default:throw new Error(`Unknown window type ${t}.`)}if(n&&(s=s.subarray(0,e)),null===r)return s;if(e>r)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${r})`);return s}},"./src/utils/constants.js": + \****************************/(e,t,n)=>{n.r(t),n.d(t,{hamming:()=>d,hanning:()=>u,mel_filter_bank:()=>f,read_audio:()=>o,spectrogram:()=>_,window_function:()=>w});var r=n(/*! ./hub.js */"./src/utils/hub.js"),i=n(/*! ./maths.js */"./src/utils/maths.js"),a=n(/*! ./core.js */"./src/utils/core.js"),s=n(/*! ./tensor.js */"./src/utils/tensor.js");async function o(e,t){if("undefined"==typeof AudioContext)throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const n=await(await(0,r.getFile)(e)).arrayBuffer(),i=new AudioContext({sampleRate:t});void 0===t&&console.warn(`No sampling rate provided, using default of ${i.sampleRate}Hz.`);const a=await i.decodeAudioData(n);let s;if(2===a.numberOfChannels){const e=Math.sqrt(2),t=a.getChannelData(0),n=a.getChannelData(1);s=new Float32Array(t.length);for(let r=0;r2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,n=15,r=27/Math.log(6.4))=>e>=t?n+Math.log(e/t)*r:3*e/200};function p(e,t="htk"){const n=c[t];if(!n)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return"number"==typeof e?n(e):e.map((e=>n(e)))}const h={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,n=15,r=Math.log(6.4)/27)=>e>=n?t*Math.exp(r*(e-n)):200*e/3};function m(e,t,n){const r=(t-e)/(n-1);return Float64Array.from({length:n},((t,n)=>e+r*n))}function f(e,t,n,r,i,a=null,s="htk",o=!1){if(null!==a&&"slaney"!==a)throw new Error('norm must be one of null or "slaney"');const l=m(p(n,s),p(r,s),t+2);let u,d=function(e,t="htk"){const n=h[t];if(!n)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return"number"==typeof e?n(e):e.map((e=>n(e)))}(l,s);if(o){const t=i/(2*e);u=p(Float64Array.from({length:e},((e,n)=>n*t)),s),d=l}else u=m(0,Math.floor(i/2),e);const c=function(e,t){const n=Float64Array.from({length:t.length-1},((e,n)=>t[n+1]-t[n])),r=Array.from({length:e.length},(()=>new Array(t.length)));for(let n=0;nnew Array(e.length)));for(let t=0;to)throw Error(`frame_length (${n}) may not be larger than fft_length (${o})`);if(k!==n)throw new Error(`Length of the window (${k}) must equal frame_length (${n})`);if(r<=0)throw new Error("hop_length must be greater than zero");if(null===l&&null!==h)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(u){if("reflect"!==d)throw new Error(`pad_mode="${d}" not implemented yet.`);const t=Math.floor((o-1)/2)+1;e=function(e,t,n){const r=new e.constructor(e.length+t+n),i=e.length-1;for(let n=0;n$?M&&(E=v):E=C=v);const P=new i.FFT(o),F=new Float64Array(o),A=new Float64Array(P.outputBufferSize),I=new Float32Array(S*E);for(let i=0;i=1;--e)F[e]-=p*F[e-1];F[0]*=1-p}for(let e=0;eMath.pow(e,.85)));break;default:throw new Error(`Unknown window type ${t}.`)}if(n&&(s=s.subarray(0,e)),null===r)return s;if(e>r)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${r})`);return s}},"./src/utils/constants.js": /*!********************************!*\ !*** ./src/utils/constants.js ***! \********************************/(e,t,n)=>{n.r(t),n.d(t,{GITHUB_ISSUE_URL:()=>r});const r="https://github.com/huggingface/transformers.js/issues/new/choose"},"./src/utils/core.js": @@ -220,11 +220,11 @@ var r,i,a,s,o,l,u,d,c,p,h,m,f,g,_,w,b,y,x,v,M,T,k,$,C,S,P,E,F,A,I,z,O,B,L=Object \****************************/(e,t,n)=>{n.r(t),n.d(t,{RawImage:()=>m});var r=n(/*! ./hub.js */"./src/utils/hub.js"),i=n(/*! ../env.js */"./src/env.js"),a=n(/*! ./tensor.js */"./src/utils/tensor.js"),s=n(/*! sharp */"?2b25");const o="undefined"!=typeof self,l=o&&"DedicatedWorkerGlobalScope"===self.constructor.name;let u,d,c;if(o)u=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(e,t)},c=self.createImageBitmap,d=self.ImageData;else{if(!s)throw new Error("Unable to load image processing library.");c=async e=>{const t=(await e.metadata()).channels,{data:n,info:r}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),i=new m(new Uint8ClampedArray(n),r.width,r.height,r.channels);return void 0!==t&&t!==r.channels&&i.convert(t),i}}const p={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},h=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class m{constructor(e,t,n,r){this.data=e,this.width=t,this.height=n,this.channels=r}get size(){return[this.width,this.height]}static async read(e){if(e instanceof m)return e;if("string"==typeof e||e instanceof URL)return await this.fromURL(e);throw new Error("Unsupported input type: "+typeof e)}static fromCanvas(e){if(!o)throw new Error("fromCanvas() is only supported in browser environments.");const t=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new m(t,e.width,e.height,4)}static async fromURL(e){const t=await(0,r.getFile)(e);if(200!==t.status)throw new Error(`Unable to read image from "${e}" (${t.status} ${t.statusText})`);const n=await t.blob();return this.fromBlob(n)}static async fromBlob(e){if(o){const t=await c(e),n=u(t.width,t.height).getContext("2d");return n.drawImage(t,0,0),new this(n.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}{const t=s(await e.arrayBuffer());return await c(t)}}static fromTensor(e,t="CHW"){if(3!==e.dims.length)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if("CHW"===t)e=e.transpose(1,2,0);else if("HWC"!==t)throw new Error(`Unsupported channel format: ${t}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new m(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(1===this.channels)return this;const e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let t=0,n=0;t=0?o=n:d=-n,r>=0?l=r:c=-r,s.drawImage(a,o,l,e,t,d,c,e,t);return new m(s.getImageData(0,0,e,t).data,e,t,4).convert(i)}{let i=this.toSharp();if(n>=0&&r>=0)i=i.extract({left:Math.floor(n),top:Math.floor(r),width:e,height:t});else if(n<=0&&r<=0){const a=Math.floor(-r),s=Math.floor(-n);i=i.extend({top:a,left:s,right:e-this.width-s,bottom:t-this.height-a})}else{let a=[0,0],s=0;r<0?(a[0]=Math.floor(-r),a[1]=t-this.height-a[0]):s=Math.floor(r);let o=[0,0],l=0;n<0?(o[0]=Math.floor(-n),o[1]=e-this.width-o[0]):l=Math.floor(n),i=i.extend({top:a[0],bottom:a[1],left:o[0],right:o[1]}).extract({left:l,top:s,width:e,height:t})}return await c(i)}}async toBlob(e="image/png",t=1){if(!o)throw new Error("toBlob() is only supported in browser environments.");const n=this.toCanvas();return await n.convertToBlob({type:e,quality:t})}toTensor(e="CHW"){let t=new a.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if("HWC"===e);else{if("CHW"!==e)throw new Error(`Unsupported channel format: ${e}`);t=t.permute(2,0,1)}return t}toCanvas(){if(!o)throw new Error("toCanvas() is only supported in browser environments.");const e=this.clone().rgba(),t=u(e.width,e.height),n=new d(e.data,e.width,e.height);return t.getContext("2d").putImageData(n,0,0),t}_update(e,t,n,r=null){return this.data=e,this.width=t,this.height=n,null!==r&&(this.channels=r),this}clone(){return new m(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(!o){if(i.env.useFS){const t=this.toSharp();return await t.toFile(e)}throw new Error("Unable to save the image because filesystem is disabled in this environment.")}{if(l)throw new Error("Unable to save an image from a Web Worker.");const t=e.split(".").pop().toLowerCase(),n=h.get(t)??"image/png",r=await this.toBlob(n),i=URL.createObjectURL(r),a=document.createElement("a");a.href=i,a.download=e,a.click(),a.remove()}}toSharp(){if(o)throw new Error("toSharp() is only supported in server-side environments.");return s(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js": /*!****************************!*\ !*** ./src/utils/maths.js ***! - \****************************/(e,t,n)=>{function r(e,[t,n,r],[i,a],s="bilinear",o=!1){const l=a/r,u=i/n,d=new e.constructor(i*a*t),c=n*r,p=i*a;for(let s=0;s=0;--e)i[e]=a,r[e]=t[n[e]],a*=r[e];const a=n.map(((e,t)=>i[n.indexOf(t)])),s=new e.constructor(e.length);for(let n=0;n=0;--e)r+=i%t[e]*a[e],i=Math.floor(i/t[e]);s[r]=e[n]}return[s,r]}function a(e){const t=c(e)[0],n=e.map((e=>Math.exp(e-t))),r=n.reduce(((e,t)=>e+t),0);return n.map((e=>e/r))}function s(e){const t=c(e)[0];let n=0;for(let r=0;re-t-r))}function o(e,t){let n=0;for(let r=0;re+t*t),0))}function d(e){if(0===e.length)throw Error("Array must not be empty");let t=e[0],n=0;for(let r=1;rt&&(t=e[r],n=r);return[Number(t),n]}function p(e){return e>0&&!(e&e-1)}n.r(t),n.d(t,{FFT:()=>f,bankers_round:()=>w,cos_sim:()=>l,dot:()=>o,dynamic_time_warping:()=>b,interpolate_data:()=>r,log_softmax:()=>s,magnitude:()=>u,max:()=>c,medianFilter:()=>g,min:()=>d,permute_data:()=>i,round:()=>_,softmax:()=>a});class h{constructor(e){if(this.size=0|e,this.size<=1||!p(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(2*this.size);for(let e=0;ee;e<<=1)++t;this._width=t%2==0?t-1:t,this._bitrev=new Int32Array(1<>>t&3)<>>1);for(let t=0;t>>1]=e[t];return n}toComplexArray(e,t){const n=t||this.createComplexArray();for(let t=0;t>>1],n[t+1]=0;return n}transform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,-1);for(let t=0;t>=2;s>=2;s>>=2){o=r/s<<1;const t=o>>>2;for(i=0;i>>1,s>>>1)}else for(i=0,a=0;i>>1,s>>>1,n)}const u=this.table;for(s>>=2;s>=2;s>>=2){o=r/s<<1;const t=o>>>1,a=t>>>1,l=a>>>1;for(i=0;i>>1;for(let t=2;t>1;++t){const n=(t+1-e)**2/2,r=Math.sqrt(o**2+l**2)**n,s=n*Math.atan2(l,o),u=2*t;i[u]=r*Math.cos(s),i[u+1]=r*Math.sin(s),a[u]=i[u],a[u+1]=-i[u+1]}this._slicedChirpBuffer=i.subarray(t,n),this._f=new h(r>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,n){const r=this._buffer1,i=this._buffer2,a=this._outBuffer1,s=this._outBuffer2,o=this._chirpBuffer,l=this._slicedChirpBuffer,u=this._a;if(n)for(let e=0;e>1];r[e]=i*l[e],r[n]=i*l[n]}else for(let e=0;e=e.length&&(i=2*(e.length-1)-i),r[a++]=e[i]}r.sort(),n[t]=r[i]}return n}function _(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}function w(e){const t=Math.round(e);return Math.abs(e)%1==.5?t%2==0?t:t-1:t}function b(e){const t=e.length,n=e[0].length,r=[t+1,n+1],i=Array.from({length:r[0]},(()=>Array(r[1]).fill(1/0)));i[0][0]=0;const a=Array.from({length:r[0]},(()=>Array(r[1]).fill(-1)));for(let t=1;t0||o>0;)switch(l.push(s-1),u.push(o-1),a[s][o]){case 0:--s,--o;break;case 1:--s;break;case 2:--o;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${s}, ${o}]. Please file a bug report.`)}return l.reverse(),u.reverse(),[l,u]}},"./src/utils/tensor.js": + \****************************/(e,t,n)=>{function r(e,[t,n,r],[i,a],s="bilinear",o=!1){const l=a/r,u=i/n,d=new e.constructor(i*a*t),c=n*r,p=i*a;for(let s=0;s=0;--e)i[e]=a,r[e]=t[n[e]],a*=r[e];const a=n.map(((e,t)=>i[n.indexOf(t)])),s=new e.constructor(e.length);for(let n=0;n=0;--e)r+=i%t[e]*a[e],i=Math.floor(i/t[e]);s[r]=e[n]}return[s,r]}function a(e){const t=c(e)[0],n=e.map((e=>Math.exp(e-t))),r=n.reduce(((e,t)=>e+t),0);return n.map((e=>e/r))}function s(e){const t=c(e)[0];let n=0;for(let r=0;re-t-r))}function o(e,t){let n=0;for(let r=0;re+t*t),0))}function d(e){if(0===e.length)throw Error("Array must not be empty");let t=e[0],n=0;for(let r=1;rt&&(t=e[r],n=r);return[Number(t),n]}function p(e){return e>0&&!(e&e-1)}n.r(t),n.d(t,{FFT:()=>f,bankers_round:()=>w,cos_sim:()=>l,dot:()=>o,dynamic_time_warping:()=>b,interpolate_data:()=>r,log_softmax:()=>s,magnitude:()=>u,max:()=>c,medianFilter:()=>g,min:()=>d,permute_data:()=>i,round:()=>_,softmax:()=>a});class h{constructor(e){if(this.size=0|e,this.size<=1||!p(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(2*this.size);for(let e=0;ee;e<<=1)++t;this._width=t%2==0?t-1:t,this._bitrev=new Int32Array(1<>>t&3)<>>1);for(let t=0;t>>1]=e[t];return n}toComplexArray(e,t){const n=t||this.createComplexArray();for(let t=0;t>>1],n[t+1]=0;return n}transform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,-1);for(let t=0;t>=2;s>=2;s>>=2){o=r/s<<1;const t=o>>>2;for(i=0;i>>1,s>>>1)}else for(i=0,a=0;i>>1,s>>>1,n)}const u=this.table;for(s>>=2;s>=2;s>>=2){o=r/s<<1;const t=o>>>1,a=t>>>1,l=a>>>1;for(i=0;i>>1;for(let t=2;t>1;++t){const n=(t+1-e)**2/2,r=Math.sqrt(o**2+l**2)**n,s=n*Math.atan2(l,o),u=2*t;i[u]=r*Math.cos(s),i[u+1]=r*Math.sin(s),a[u]=i[u],a[u+1]=-i[u+1]}this._slicedChirpBuffer=i.subarray(t,n),this._f=new h(r>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,n){const r=this._buffer1,i=this._buffer2,a=this._outBuffer1,s=this._outBuffer2,o=this._chirpBuffer,l=this._slicedChirpBuffer,u=this._a;if(n)for(let e=0;e>1];r[e]=i*l[e],r[n]=i*l[n]}else for(let e=0;e=e.length&&(i=2*(e.length-1)-i),r[a++]=e[i]}r.sort(),n[t]=r[i]}return n}function _(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}function w(e){const t=Math.round(e);return Math.abs(e)%1==.5?t%2==0?t:t-1:t}function b(e){const t=e.length,n=e[0].length,r=[t+1,n+1],i=Array.from({length:r[0]},(()=>Array(r[1]).fill(1/0)));i[0][0]=0;const a=Array.from({length:r[0]},(()=>Array(r[1]).fill(-1)));for(let t=1;t0||o>0;)switch(l.push(s-1),u.push(o-1),a[s][o]){case 0:--s,--o;break;case 1:--s;break;case 2:--o;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${s}, ${o}]. Please file a bug report.`)}return l.reverse(),u.reverse(),[l,u]}},"./src/utils/tensor.js": /*!*****************************!*\ !*** ./src/utils/tensor.js ***! - \*****************************/(e,t,n)=>{n.r(t),n.d(t,{Tensor:()=>o,cat:()=>b,full:()=>T,full_like:()=>k,interpolate:()=>u,interpolate_4d:()=>d,layer_norm:()=>f,matmul:()=>c,mean:()=>v,mean_pooling:()=>m,ones:()=>$,ones_like:()=>C,permute:()=>l,quantize_embeddings:()=>E,rfft:()=>p,stack:()=>y,std_mean:()=>x,topk:()=>h,zeros:()=>S,zeros_like:()=>P});var r=n(/*! ./maths.js */"./src/utils/maths.js"),i=n(/*! ../backends/onnx.js */"./src/backends/onnx.js"),a=n(/*! ../ops/registry.js */"./src/ops/registry.js");const s=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class o{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return(0,i.isONNXTensor)(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new i.Tensor(e[0],e[1],e[2]),new Proxy(this,{get:(e,t)=>{if("string"==typeof t){let n=Number(t);if(Number.isInteger(n))return e._getitem(n)}return e[t]},set:(e,t,n)=>e[t]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[e,...t]=this.dims;if(t.length>0){const n=t.reduce(((e,t)=>e*t));for(let r=0;r0){const t=n.reduce(((e,t)=>e*t));return this._subarray(e,t,n)}return new o(this.type,[this.data[e]],n)}indexOf(e){const t=this.data;for(let n=0;ne*t));if(n!==r)throw Error(`cannot reshape array of size ${n} into shape (${t})`);let i=e;for(let e=t.length-1;e>=0;e--)i=i.reduce(((n,r)=>{let i=n[n.length-1];return i.lengtha)throw new Error(`Invalid slice: ${i}`);const s=[Math.max(e,0),Math.min(a,this.dims[r])];n.push(s),t.push(s[1]-s[0])}}}const r=n.map((([e,t])=>t-e)),i=r.reduce(((e,t)=>e*t)),a=this.data,s=new a.constructor(i),l=this.stride();for(let e=0;e=0;--i){const e=r[i];t+=(a%e+n[i][0])*l[i],a=Math.floor(a/e)}s[e]=a[t]}return new o(this.type,s,t)}permute(...e){return l(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,t=!1){return this.norm(1,e,t)}norm(e="fro",t=null,n=!1){if("fro"===e)e=2;else if("string"==typeof e)throw Error(`Unsupported norm: ${e}`);const r=this.data;if(null===t){let t=r.reduce(((t,n)=>t+n**e),0)**(1/e);return new o(this.type,[t],[])}t=w(t,this.dims.length);const i=this.dims.slice();i[t]=1;const a=new r.constructor(r.length/this.dims[t]);for(let n=0;n=0;--e){const n=this.dims[e];if(e!==t){s+=r%n*a,a*=i[e]}r=Math.floor(r/n)}a[s]+=r[n]**e}if(1!==e)for(let t=0;t=0;--r){const e=this.dims[r];if(r!==t){n+=i%e*a,a*=this.dims[r]}i=Math.floor(i/e)}r[e]/=i[n]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return function(e){const t=new Array(e.length);for(let n=e.length-1,r=1;n>=0;--n)t[n]=r,r*=e[n];return t}(this.dims)}squeeze(e=null){return new o(this.type,this.data,g(this.dims,e))}squeeze_(e=null){return this.dims=g(this.dims,e),this}unsqueeze(e=null){return new o(this.type,this.data,_(this.dims,e))}unsqueeze_(e=null){return this.dims=_(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let n=this.dims.slice(0,e),r=this.dims.slice(e,t+1),i=this.dims.slice(t+1);return this.dims=[...n,r.reduce(((e,t)=>e*t),1),...i],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...e){let t=-1;for(let n=0;nr!==t?e*n:e),1);e[t]=n.length/r}return new o(this.type,n,e)}neg_(){const e=this.data;for(let t=0;t1!==e)):"number"==typeof t?1===e[t]&&e.splice(t,1):Array.isArray(t)&&(e=e.filter(((e,n)=>1!==e||!t.includes(n)))),e}function _(e,t){return t=w(t,e.length+1),(e=e.slice()).splice(t,0,1),e}function w(e,t,n=null,r=!0){if(r&&(e<-t||e>=t))throw new Error(`IndexError: index ${e} is out of bounds for dimension${null===n?"":" "+n} with size ${t}`);return e<0&&(e=(e%t+t)%t),e}function b(e,t=0){t=w(t,e[0].dims.length);const n=e[0].dims.slice();n[t]=e.reduce(((e,n)=>e+n.dims[t]),0);const r=n.reduce(((e,t)=>e*t),1),i=new e[0].data.constructor(r),a=e[0].type;if(0===t){let t=0;for(const n of e){const e=n.data;i.set(e,t),t+=e.length}}else{let r=0;for(let a=0;a=0;--i){const e=o[i];let u=s%e;i===t&&(u+=r),a+=u*l,l*=n[i],s=Math.floor(s/e)}i[a]=s[e]}r+=o[t]}}return new o(a,i,n)}function y(e,t=0){return b(e.map((e=>e.unsqueeze(t))),t)}function x(e,t=null,n=1,r=!1){const i=e.data,a=e.dims;if(null===t){const t=i.reduce(((e,t)=>e+t),0)/i.length,r=Math.sqrt(i.reduce(((e,n)=>e+(n-t)**2),0)/(i.length-n)),a=new o(e.type,[t],[]);return[new o(e.type,[r],[]),a]}const s=v(e,t=w(t,a.length),r),l=s.data,u=a.slice();u[t]=1;const d=new i.constructor(i.length/a[t]);for(let e=0;e=0;--r){const e=a[r];if(r!==t){n+=i%e*s,s*=u[r]}i=Math.floor(i/e)}d[n]+=(i[e]-l[n])**2}for(let e=0;ee+t),0);return new o(e.type,[t/r.length],[])}const i=e.dims;t=w(t,i.length);const a=i.slice();a[t]=1;const s=new r.constructor(r.length/i[t]);for(let e=0;e=0;--r){const e=i[r];if(r!==t){n+=s%e*o,o*=a[r]}s=Math.floor(s/e)}s[n]+=r[e]}if(1!==i[t])for(let e=0;ee*t),1);return new o(n,new r(i).fill(t),e)}function T(e,t){let n,r;if("number"==typeof t)n="float32",r=Float32Array;else{if("bigint"!=typeof t)throw new Error("Unsupported data type: "+typeof t);n="int64",r=BigInt64Array}return M(e,t,n,r)}function k(e,t){return T(e.dims,t)}function $(e){return M(e,1n,"int64",BigInt64Array)}function C(e){return $(e.dims)}function S(e){return M(e,0n,"int64",BigInt64Array)}function P(e){return S(e.dims)}function E(e,t){if(2!==e.dims.length)throw new Error("The tensor must have 2 dimensions");if(e.dims.at(-1)%8!=0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(t))throw new Error("The precision must be either 'binary' or 'ubinary'");const n="binary"===t,r=n?"int8":"uint8",i=n?Int8Array:Uint8Array,a=e.data,s=new i(a.length/8);for(let e=0;e0?1:0,r=Math.floor(e/8),i=e%8;s[r]|=t<<7-i,n&&0===i&&(s[r]-=128)}return new o(r,s,[e.dims[0],e.dims[1]/8])}}},r={};function i(e){var t=r[e];if(void 0!==t)return t.exports;var a=r[e]={exports:{}};return n[e](a,a.exports,i),a.exports}i.m=n,t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,i.t=function(n,r){if(1&r&&(n=this(n)),8&r)return n;if("object"==typeof n&&n){if(4&r&&n.__esModule)return n;if(16&r&&"function"==typeof n.then)return n}var a=Object.create(null);i.r(a);var s={};e=e||[null,t({}),t([]),t(t)];for(var o=2&r&&n;"object"==typeof o&&!~e.indexOf(o);o=t(o))Object.getOwnPropertyNames(o).forEach((e=>s[e]=()=>n[e]));return s.default=()=>n,i.d(a,s),a},i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;if("string"==typeof import.meta.url&&(e=import.meta.url),!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),i.p=e})(),i.b=new URL("./",import.meta.url);var a={}; + \*****************************/(e,t,n)=>{n.r(t),n.d(t,{Tensor:()=>o,cat:()=>b,full:()=>T,full_like:()=>k,interpolate:()=>u,interpolate_4d:()=>d,layer_norm:()=>f,matmul:()=>c,mean:()=>v,mean_pooling:()=>m,ones:()=>$,ones_like:()=>S,permute:()=>l,quantize_embeddings:()=>P,rfft:()=>p,stack:()=>y,std_mean:()=>x,topk:()=>h,zeros:()=>C,zeros_like:()=>E});var r=n(/*! ./maths.js */"./src/utils/maths.js"),i=n(/*! ../backends/onnx.js */"./src/backends/onnx.js"),a=n(/*! ../ops/registry.js */"./src/ops/registry.js");const s=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class o{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return(0,i.isONNXTensor)(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new i.Tensor(e[0],e[1],e[2]),new Proxy(this,{get:(e,t)=>{if("string"==typeof t){let n=Number(t);if(Number.isInteger(n))return e._getitem(n)}return e[t]},set:(e,t,n)=>e[t]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[e,...t]=this.dims;if(t.length>0){const n=t.reduce(((e,t)=>e*t));for(let r=0;r0){const t=n.reduce(((e,t)=>e*t));return this._subarray(e,t,n)}return new o(this.type,[this.data[e]],n)}indexOf(e){const t=this.data;for(let n=0;ne*t));if(n!==r)throw Error(`cannot reshape array of size ${n} into shape (${t})`);let i=e;for(let e=t.length-1;e>=0;e--)i=i.reduce(((n,r)=>{let i=n[n.length-1];return i.lengtha)throw new Error(`Invalid slice: ${i}`);const s=[Math.max(e,0),Math.min(a,this.dims[r])];n.push(s),t.push(s[1]-s[0])}}}const r=n.map((([e,t])=>t-e)),i=r.reduce(((e,t)=>e*t)),a=this.data,s=new a.constructor(i),l=this.stride();for(let e=0;e=0;--i){const e=r[i];t+=(a%e+n[i][0])*l[i],a=Math.floor(a/e)}s[e]=a[t]}return new o(this.type,s,t)}permute(...e){return l(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,t=!1){return this.norm(1,e,t)}norm(e="fro",t=null,n=!1){if("fro"===e)e=2;else if("string"==typeof e)throw Error(`Unsupported norm: ${e}`);const r=this.data;if(null===t){let t=r.reduce(((t,n)=>t+n**e),0)**(1/e);return new o(this.type,[t],[])}t=w(t,this.dims.length);const i=this.dims.slice();i[t]=1;const a=new r.constructor(r.length/this.dims[t]);for(let n=0;n=0;--e){const n=this.dims[e];if(e!==t){s+=r%n*a,a*=i[e]}r=Math.floor(r/n)}a[s]+=r[n]**e}if(1!==e)for(let t=0;t=0;--r){const e=this.dims[r];if(r!==t){n+=i%e*a,a*=this.dims[r]}i=Math.floor(i/e)}r[e]/=i[n]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return function(e){const t=new Array(e.length);for(let n=e.length-1,r=1;n>=0;--n)t[n]=r,r*=e[n];return t}(this.dims)}squeeze(e=null){return new o(this.type,this.data,g(this.dims,e))}squeeze_(e=null){return this.dims=g(this.dims,e),this}unsqueeze(e=null){return new o(this.type,this.data,_(this.dims,e))}unsqueeze_(e=null){return this.dims=_(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let n=this.dims.slice(0,e),r=this.dims.slice(e,t+1),i=this.dims.slice(t+1);return this.dims=[...n,r.reduce(((e,t)=>e*t),1),...i],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...e){let t=-1;for(let n=0;nr!==t?e*n:e),1);e[t]=n.length/r}return new o(this.type,n,e)}neg_(){const e=this.data;for(let t=0;t1!==e)):"number"==typeof t?1===e[t]&&e.splice(t,1):Array.isArray(t)&&(e=e.filter(((e,n)=>1!==e||!t.includes(n)))),e}function _(e,t){return t=w(t,e.length+1),(e=e.slice()).splice(t,0,1),e}function w(e,t,n=null,r=!0){if(r&&(e<-t||e>=t))throw new Error(`IndexError: index ${e} is out of bounds for dimension${null===n?"":" "+n} with size ${t}`);return e<0&&(e=(e%t+t)%t),e}function b(e,t=0){t=w(t,e[0].dims.length);const n=e[0].dims.slice();n[t]=e.reduce(((e,n)=>e+n.dims[t]),0);const r=n.reduce(((e,t)=>e*t),1),i=new e[0].data.constructor(r),a=e[0].type;if(0===t){let t=0;for(const n of e){const e=n.data;i.set(e,t),t+=e.length}}else{let r=0;for(let a=0;a=0;--i){const e=o[i];let u=s%e;i===t&&(u+=r),a+=u*l,l*=n[i],s=Math.floor(s/e)}i[a]=s[e]}r+=o[t]}}return new o(a,i,n)}function y(e,t=0){return b(e.map((e=>e.unsqueeze(t))),t)}function x(e,t=null,n=1,r=!1){const i=e.data,a=e.dims;if(null===t){const t=i.reduce(((e,t)=>e+t),0)/i.length,r=Math.sqrt(i.reduce(((e,n)=>e+(n-t)**2),0)/(i.length-n)),a=new o(e.type,[t],[]);return[new o(e.type,[r],[]),a]}const s=v(e,t=w(t,a.length),r),l=s.data,u=a.slice();u[t]=1;const d=new i.constructor(i.length/a[t]);for(let e=0;e=0;--r){const e=a[r];if(r!==t){n+=i%e*s,s*=u[r]}i=Math.floor(i/e)}d[n]+=(i[e]-l[n])**2}for(let e=0;ee+t),0);return new o(e.type,[t/r.length],[])}const i=e.dims;t=w(t,i.length);const a=i.slice();a[t]=1;const s=new r.constructor(r.length/i[t]);for(let e=0;e=0;--r){const e=i[r];if(r!==t){n+=s%e*o,o*=a[r]}s=Math.floor(s/e)}s[n]+=r[e]}if(1!==i[t])for(let e=0;ee*t),1);return new o(n,new r(i).fill(t),e)}function T(e,t){let n,r;if("number"==typeof t)n="float32",r=Float32Array;else{if("bigint"!=typeof t)throw new Error("Unsupported data type: "+typeof t);n="int64",r=BigInt64Array}return M(e,t,n,r)}function k(e,t){return T(e.dims,t)}function $(e){return M(e,1n,"int64",BigInt64Array)}function S(e){return $(e.dims)}function C(e){return M(e,0n,"int64",BigInt64Array)}function E(e){return C(e.dims)}function P(e,t){if(2!==e.dims.length)throw new Error("The tensor must have 2 dimensions");if(e.dims.at(-1)%8!=0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(t))throw new Error("The precision must be either 'binary' or 'ubinary'");const n="binary"===t,r=n?"int8":"uint8",i=n?Int8Array:Uint8Array,a=e.data,s=new i(a.length/8);for(let e=0;e0?1:0,r=Math.floor(e/8),i=e%8;s[r]|=t<<7-i,n&&0===i&&(s[r]-=128)}return new o(r,s,[e.dims[0],e.dims[1]/8])}}},r={};function i(e){var t=r[e];if(void 0!==t)return t.exports;var a=r[e]={exports:{}};return n[e](a,a.exports,i),a.exports}i.m=n,t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,i.t=function(n,r){if(1&r&&(n=this(n)),8&r)return n;if("object"==typeof n&&n){if(4&r&&n.__esModule)return n;if(16&r&&"function"==typeof n.then)return n}var a=Object.create(null);i.r(a);var s={};e=e||[null,t({}),t([]),t(t)];for(var o=2&r&&n;"object"==typeof o&&!~e.indexOf(o);o=t(o))Object.getOwnPropertyNames(o).forEach((e=>s[e]=()=>n[e]));return s.default=()=>n,i.d(a,s),a},i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;if("string"==typeof import.meta.url&&(e=import.meta.url),!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),i.p=e})(),i.b=new URL("./",import.meta.url);var a={}; /*!*****************************!*\ !*** ./src/transformers.js ***! - \*****************************/i.r(a),i.d(a,{ASTFeatureExtractor:()=>d.ASTFeatureExtractor,ASTForAudioClassification:()=>l.ASTForAudioClassification,ASTModel:()=>l.ASTModel,ASTPreTrainedModel:()=>l.ASTPreTrainedModel,AlbertForMaskedLM:()=>l.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>l.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>l.AlbertForSequenceClassification,AlbertModel:()=>l.AlbertModel,AlbertPreTrainedModel:()=>l.AlbertPreTrainedModel,AlbertTokenizer:()=>u.AlbertTokenizer,AudioClassificationPipeline:()=>o.AudioClassificationPipeline,AutoConfig:()=>c.AutoConfig,AutoModel:()=>l.AutoModel,AutoModelForAudioClassification:()=>l.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>l.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>l.AutoModelForCTC,AutoModelForCausalLM:()=>l.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>l.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>l.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>l.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>l.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>l.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>l.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>l.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>l.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>l.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>l.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>l.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>l.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>l.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>l.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>l.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>l.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>l.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>l.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>l.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>l.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>l.AutoModelForVision2Seq,AutoModelForXVector:()=>l.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>l.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>d.AutoProcessor,AutoTokenizer:()=>u.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>o.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>l.BartForConditionalGeneration,BartForSequenceClassification:()=>l.BartForSequenceClassification,BartModel:()=>l.BartModel,BartPretrainedModel:()=>l.BartPretrainedModel,BartTokenizer:()=>u.BartTokenizer,BaseModelOutput:()=>l.BaseModelOutput,BaseStreamer:()=>g.BaseStreamer,BeitFeatureExtractor:()=>d.BeitFeatureExtractor,BeitForImageClassification:()=>l.BeitForImageClassification,BeitModel:()=>l.BeitModel,BeitPreTrainedModel:()=>l.BeitPreTrainedModel,BertForMaskedLM:()=>l.BertForMaskedLM,BertForQuestionAnswering:()=>l.BertForQuestionAnswering,BertForSequenceClassification:()=>l.BertForSequenceClassification,BertForTokenClassification:()=>l.BertForTokenClassification,BertModel:()=>l.BertModel,BertPreTrainedModel:()=>l.BertPreTrainedModel,BertTokenizer:()=>u.BertTokenizer,BitImageProcessor:()=>d.BitImageProcessor,BlenderbotForConditionalGeneration:()=>l.BlenderbotForConditionalGeneration,BlenderbotModel:()=>l.BlenderbotModel,BlenderbotPreTrainedModel:()=>l.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>l.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>l.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>l.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>u.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>u.BlenderbotTokenizer,BloomForCausalLM:()=>l.BloomForCausalLM,BloomModel:()=>l.BloomModel,BloomPreTrainedModel:()=>l.BloomPreTrainedModel,BloomTokenizer:()=>u.BloomTokenizer,CLIPFeatureExtractor:()=>d.CLIPFeatureExtractor,CLIPImageProcessor:()=>d.CLIPImageProcessor,CLIPModel:()=>l.CLIPModel,CLIPPreTrainedModel:()=>l.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>l.CLIPSegForImageSegmentation,CLIPSegModel:()=>l.CLIPSegModel,CLIPSegPreTrainedModel:()=>l.CLIPSegPreTrainedModel,CLIPTextModel:()=>l.CLIPTextModel,CLIPTextModelWithProjection:()=>l.CLIPTextModelWithProjection,CLIPTokenizer:()=>u.CLIPTokenizer,CLIPVisionModel:()=>l.CLIPVisionModel,CLIPVisionModelWithProjection:()=>l.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>l.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>l.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>l.CamembertForSequenceClassification,CamembertForTokenClassification:()=>l.CamembertForTokenClassification,CamembertModel:()=>l.CamembertModel,CamembertPreTrainedModel:()=>l.CamembertPreTrainedModel,CamembertTokenizer:()=>u.CamembertTokenizer,CausalLMOutput:()=>l.CausalLMOutput,CausalLMOutputWithPast:()=>l.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>d.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>l.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>l.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>l.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>d.ClapFeatureExtractor,ClapModel:()=>l.ClapModel,ClapPreTrainedModel:()=>l.ClapPreTrainedModel,ClapTextModelWithProjection:()=>l.ClapTextModelWithProjection,CodeGenForCausalLM:()=>l.CodeGenForCausalLM,CodeGenModel:()=>l.CodeGenModel,CodeGenPreTrainedModel:()=>l.CodeGenPreTrainedModel,CodeGenTokenizer:()=>u.CodeGenTokenizer,CodeLlamaTokenizer:()=>u.CodeLlamaTokenizer,CohereForCausalLM:()=>l.CohereForCausalLM,CohereModel:()=>l.CohereModel,CoherePreTrainedModel:()=>l.CoherePreTrainedModel,CohereTokenizer:()=>u.CohereTokenizer,ConvBertForMaskedLM:()=>l.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>l.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>l.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>l.ConvBertForTokenClassification,ConvBertModel:()=>l.ConvBertModel,ConvBertPreTrainedModel:()=>l.ConvBertPreTrainedModel,ConvBertTokenizer:()=>u.ConvBertTokenizer,ConvNextFeatureExtractor:()=>d.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>l.ConvNextForImageClassification,ConvNextImageProcessor:()=>d.ConvNextImageProcessor,ConvNextModel:()=>l.ConvNextModel,ConvNextPreTrainedModel:()=>l.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>l.ConvNextV2ForImageClassification,ConvNextV2Model:()=>l.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>l.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>d.DPTFeatureExtractor,DPTForDepthEstimation:()=>l.DPTForDepthEstimation,DPTImageProcessor:()=>d.DPTImageProcessor,DPTModel:()=>l.DPTModel,DPTPreTrainedModel:()=>l.DPTPreTrainedModel,DebertaForMaskedLM:()=>l.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>l.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>l.DebertaForSequenceClassification,DebertaForTokenClassification:()=>l.DebertaForTokenClassification,DebertaModel:()=>l.DebertaModel,DebertaPreTrainedModel:()=>l.DebertaPreTrainedModel,DebertaTokenizer:()=>u.DebertaTokenizer,DebertaV2ForMaskedLM:()=>l.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>l.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>l.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>l.DebertaV2ForTokenClassification,DebertaV2Model:()=>l.DebertaV2Model,DebertaV2PreTrainedModel:()=>l.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>u.DebertaV2Tokenizer,DecisionTransformerModel:()=>l.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>l.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>d.DeiTFeatureExtractor,DeiTForImageClassification:()=>l.DeiTForImageClassification,DeiTModel:()=>l.DeiTModel,DeiTPreTrainedModel:()=>l.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>l.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>l.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>o.DepthEstimationPipeline,DepthProForDepthEstimation:()=>l.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>l.DepthProPreTrainedModel,DetrFeatureExtractor:()=>d.DetrFeatureExtractor,DetrForObjectDetection:()=>l.DetrForObjectDetection,DetrForSegmentation:()=>l.DetrForSegmentation,DetrModel:()=>l.DetrModel,DetrObjectDetectionOutput:()=>l.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>l.DetrPreTrainedModel,DetrSegmentationOutput:()=>l.DetrSegmentationOutput,Dinov2ForImageClassification:()=>l.Dinov2ForImageClassification,Dinov2Model:()=>l.Dinov2Model,Dinov2PreTrainedModel:()=>l.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>l.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>l.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>l.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>l.DistilBertForTokenClassification,DistilBertModel:()=>l.DistilBertModel,DistilBertPreTrainedModel:()=>l.DistilBertPreTrainedModel,DistilBertTokenizer:()=>u.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>o.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>d.DonutFeatureExtractor,DonutSwinModel:()=>l.DonutSwinModel,DonutSwinPreTrainedModel:()=>l.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>l.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>d.EfficientNetImageProcessor,EfficientNetModel:()=>l.EfficientNetModel,EfficientNetPreTrainedModel:()=>l.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>l.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>l.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>l.ElectraForSequenceClassification,ElectraForTokenClassification:()=>l.ElectraForTokenClassification,ElectraModel:()=>l.ElectraModel,ElectraPreTrainedModel:()=>l.ElectraPreTrainedModel,ElectraTokenizer:()=>u.ElectraTokenizer,EosTokenCriteria:()=>_.EosTokenCriteria,EsmForMaskedLM:()=>l.EsmForMaskedLM,EsmForSequenceClassification:()=>l.EsmForSequenceClassification,EsmForTokenClassification:()=>l.EsmForTokenClassification,EsmModel:()=>l.EsmModel,EsmPreTrainedModel:()=>l.EsmPreTrainedModel,EsmTokenizer:()=>u.EsmTokenizer,FFT:()=>f.FFT,FalconForCausalLM:()=>l.FalconForCausalLM,FalconModel:()=>l.FalconModel,FalconPreTrainedModel:()=>l.FalconPreTrainedModel,FalconTokenizer:()=>u.FalconTokenizer,FastViTForImageClassification:()=>l.FastViTForImageClassification,FastViTModel:()=>l.FastViTModel,FastViTPreTrainedModel:()=>l.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>o.FeatureExtractionPipeline,FeatureExtractor:()=>d.FeatureExtractor,FillMaskPipeline:()=>o.FillMaskPipeline,Florence2ForConditionalGeneration:()=>l.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>l.Florence2PreTrainedModel,Florence2Processor:()=>d.Florence2Processor,GLPNFeatureExtractor:()=>d.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>l.GLPNForDepthEstimation,GLPNModel:()=>l.GLPNModel,GLPNPreTrainedModel:()=>l.GLPNPreTrainedModel,GPT2LMHeadModel:()=>l.GPT2LMHeadModel,GPT2Model:()=>l.GPT2Model,GPT2PreTrainedModel:()=>l.GPT2PreTrainedModel,GPT2Tokenizer:()=>u.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>l.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>l.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>l.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>l.GPTJForCausalLM,GPTJModel:()=>l.GPTJModel,GPTJPreTrainedModel:()=>l.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>l.GPTNeoForCausalLM,GPTNeoModel:()=>l.GPTNeoModel,GPTNeoPreTrainedModel:()=>l.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>l.GPTNeoXForCausalLM,GPTNeoXModel:()=>l.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>l.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>u.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>l.Gemma2ForCausalLM,Gemma2Model:()=>l.Gemma2Model,Gemma2PreTrainedModel:()=>l.Gemma2PreTrainedModel,GemmaForCausalLM:()=>l.GemmaForCausalLM,GemmaModel:()=>l.GemmaModel,GemmaPreTrainedModel:()=>l.GemmaPreTrainedModel,GemmaTokenizer:()=>u.GemmaTokenizer,GraniteForCausalLM:()=>l.GraniteForCausalLM,GraniteModel:()=>l.GraniteModel,GranitePreTrainedModel:()=>l.GranitePreTrainedModel,Grok1Tokenizer:()=>u.Grok1Tokenizer,GroupViTModel:()=>l.GroupViTModel,GroupViTPreTrainedModel:()=>l.GroupViTPreTrainedModel,HerbertTokenizer:()=>u.HerbertTokenizer,HieraForImageClassification:()=>l.HieraForImageClassification,HieraModel:()=>l.HieraModel,HieraPreTrainedModel:()=>l.HieraPreTrainedModel,HubertForCTC:()=>l.HubertForCTC,HubertForSequenceClassification:()=>l.HubertForSequenceClassification,HubertModel:()=>l.HubertModel,HubertPreTrainedModel:()=>l.HubertPreTrainedModel,ImageClassificationPipeline:()=>o.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>o.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>d.ImageFeatureExtractor,ImageMattingOutput:()=>l.ImageMattingOutput,ImageSegmentationPipeline:()=>o.ImageSegmentationPipeline,ImageToImagePipeline:()=>o.ImageToImagePipeline,ImageToTextPipeline:()=>o.ImageToTextPipeline,InterruptableStoppingCriteria:()=>_.InterruptableStoppingCriteria,JAISLMHeadModel:()=>l.JAISLMHeadModel,JAISModel:()=>l.JAISModel,JAISPreTrainedModel:()=>l.JAISPreTrainedModel,LlamaForCausalLM:()=>l.LlamaForCausalLM,LlamaModel:()=>l.LlamaModel,LlamaPreTrainedModel:()=>l.LlamaPreTrainedModel,LlamaTokenizer:()=>u.LlamaTokenizer,LlavaForConditionalGeneration:()=>l.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>l.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>l.LongT5ForConditionalGeneration,LongT5Model:()=>l.LongT5Model,LongT5PreTrainedModel:()=>l.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>l.M2M100ForConditionalGeneration,M2M100Model:()=>l.M2M100Model,M2M100PreTrainedModel:()=>l.M2M100PreTrainedModel,M2M100Tokenizer:()=>u.M2M100Tokenizer,MBart50Tokenizer:()=>u.MBart50Tokenizer,MBartForCausalLM:()=>l.MBartForCausalLM,MBartForConditionalGeneration:()=>l.MBartForConditionalGeneration,MBartForSequenceClassification:()=>l.MBartForSequenceClassification,MBartModel:()=>l.MBartModel,MBartPreTrainedModel:()=>l.MBartPreTrainedModel,MBartTokenizer:()=>u.MBartTokenizer,MPNetForMaskedLM:()=>l.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>l.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>l.MPNetForSequenceClassification,MPNetForTokenClassification:()=>l.MPNetForTokenClassification,MPNetModel:()=>l.MPNetModel,MPNetPreTrainedModel:()=>l.MPNetPreTrainedModel,MPNetTokenizer:()=>u.MPNetTokenizer,MT5ForConditionalGeneration:()=>l.MT5ForConditionalGeneration,MT5Model:()=>l.MT5Model,MT5PreTrainedModel:()=>l.MT5PreTrainedModel,MarianMTModel:()=>l.MarianMTModel,MarianModel:()=>l.MarianModel,MarianPreTrainedModel:()=>l.MarianPreTrainedModel,MarianTokenizer:()=>u.MarianTokenizer,MaskFormerFeatureExtractor:()=>d.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>l.MaskFormerForInstanceSegmentation,MaskFormerModel:()=>l.MaskFormerModel,MaskFormerPreTrainedModel:()=>l.MaskFormerPreTrainedModel,MaskedLMOutput:()=>l.MaskedLMOutput,MaxLengthCriteria:()=>_.MaxLengthCriteria,MistralForCausalLM:()=>l.MistralForCausalLM,MistralModel:()=>l.MistralModel,MistralPreTrainedModel:()=>l.MistralPreTrainedModel,MobileBertForMaskedLM:()=>l.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>l.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>l.MobileBertForSequenceClassification,MobileBertModel:()=>l.MobileBertModel,MobileBertPreTrainedModel:()=>l.MobileBertPreTrainedModel,MobileBertTokenizer:()=>u.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>d.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>l.MobileNetV1ForImageClassification,MobileNetV1Model:()=>l.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>l.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>d.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>l.MobileNetV2ForImageClassification,MobileNetV2Model:()=>l.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>l.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>d.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>l.MobileNetV3ForImageClassification,MobileNetV3Model:()=>l.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>l.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>d.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>l.MobileNetV4ForImageClassification,MobileNetV4Model:()=>l.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>l.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>d.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>l.MobileViTForImageClassification,MobileViTImageProcessor:()=>d.MobileViTImageProcessor,MobileViTModel:()=>l.MobileViTModel,MobileViTPreTrainedModel:()=>l.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>l.MobileViTV2ForImageClassification,MobileViTV2Model:()=>l.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>l.MobileViTV2PreTrainedModel,ModelOutput:()=>l.ModelOutput,Moondream1ForConditionalGeneration:()=>l.Moondream1ForConditionalGeneration,MptForCausalLM:()=>l.MptForCausalLM,MptModel:()=>l.MptModel,MptPreTrainedModel:()=>l.MptPreTrainedModel,MusicgenForCausalLM:()=>l.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>l.MusicgenForConditionalGeneration,MusicgenModel:()=>l.MusicgenModel,MusicgenPreTrainedModel:()=>l.MusicgenPreTrainedModel,NllbTokenizer:()=>u.NllbTokenizer,NomicBertModel:()=>l.NomicBertModel,NomicBertPreTrainedModel:()=>l.NomicBertPreTrainedModel,NougatImageProcessor:()=>d.NougatImageProcessor,NougatTokenizer:()=>u.NougatTokenizer,OPTForCausalLM:()=>l.OPTForCausalLM,OPTModel:()=>l.OPTModel,OPTPreTrainedModel:()=>l.OPTPreTrainedModel,ObjectDetectionPipeline:()=>o.ObjectDetectionPipeline,OpenELMForCausalLM:()=>l.OpenELMForCausalLM,OpenELMModel:()=>l.OpenELMModel,OpenELMPreTrainedModel:()=>l.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>d.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>l.OwlViTForObjectDetection,OwlViTModel:()=>l.OwlViTModel,OwlViTPreTrainedModel:()=>l.OwlViTPreTrainedModel,OwlViTProcessor:()=>d.OwlViTProcessor,Owlv2ForObjectDetection:()=>l.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>d.Owlv2ImageProcessor,Owlv2Model:()=>l.Owlv2Model,Owlv2PreTrainedModel:()=>l.Owlv2PreTrainedModel,Phi3ForCausalLM:()=>l.Phi3ForCausalLM,Phi3Model:()=>l.Phi3Model,Phi3PreTrainedModel:()=>l.Phi3PreTrainedModel,PhiForCausalLM:()=>l.PhiForCausalLM,PhiModel:()=>l.PhiModel,PhiPreTrainedModel:()=>l.PhiPreTrainedModel,Pipeline:()=>o.Pipeline,PreTrainedModel:()=>l.PreTrainedModel,PreTrainedTokenizer:()=>u.PreTrainedTokenizer,PretrainedConfig:()=>c.PretrainedConfig,PretrainedMixin:()=>l.PretrainedMixin,Processor:()=>d.Processor,PvtForImageClassification:()=>l.PvtForImageClassification,PvtImageProcessor:()=>d.PvtImageProcessor,PvtModel:()=>l.PvtModel,PvtPreTrainedModel:()=>l.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>d.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>l.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>l.PyAnnoteModel,PyAnnotePreTrainedModel:()=>l.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>d.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>l.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>o.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>l.Qwen2ForCausalLM,Qwen2Model:()=>l.Qwen2Model,Qwen2PreTrainedModel:()=>l.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>u.Qwen2Tokenizer,RTDetrForObjectDetection:()=>l.RTDetrForObjectDetection,RTDetrImageProcessor:()=>d.RTDetrImageProcessor,RTDetrModel:()=>l.RTDetrModel,RTDetrObjectDetectionOutput:()=>l.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>l.RTDetrPreTrainedModel,RawImage:()=>h.RawImage,ResNetForImageClassification:()=>l.ResNetForImageClassification,ResNetModel:()=>l.ResNetModel,ResNetPreTrainedModel:()=>l.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>l.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>l.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>l.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>l.RoFormerForTokenClassification,RoFormerModel:()=>l.RoFormerModel,RoFormerPreTrainedModel:()=>l.RoFormerPreTrainedModel,RoFormerTokenizer:()=>u.RoFormerTokenizer,RobertaForMaskedLM:()=>l.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>l.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>l.RobertaForSequenceClassification,RobertaForTokenClassification:()=>l.RobertaForTokenClassification,RobertaModel:()=>l.RobertaModel,RobertaPreTrainedModel:()=>l.RobertaPreTrainedModel,RobertaTokenizer:()=>u.RobertaTokenizer,SamImageProcessor:()=>d.SamImageProcessor,SamImageSegmentationOutput:()=>l.SamImageSegmentationOutput,SamModel:()=>l.SamModel,SamPreTrainedModel:()=>l.SamPreTrainedModel,SamProcessor:()=>d.SamProcessor,SapiensFeatureExtractor:()=>d.SapiensFeatureExtractor,SapiensForDepthEstimation:()=>l.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>l.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>l.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>l.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>d.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>d.SegformerFeatureExtractor,SegformerForImageClassification:()=>l.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>l.SegformerForSemanticSegmentation,SegformerModel:()=>l.SegformerModel,SegformerPreTrainedModel:()=>l.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>l.Seq2SeqLMOutput,SequenceClassifierOutput:()=>l.SequenceClassifierOutput,SiglipImageProcessor:()=>d.SiglipImageProcessor,SiglipModel:()=>l.SiglipModel,SiglipPreTrainedModel:()=>l.SiglipPreTrainedModel,SiglipTextModel:()=>l.SiglipTextModel,SiglipTokenizer:()=>u.SiglipTokenizer,SiglipVisionModel:()=>l.SiglipVisionModel,SpeechT5FeatureExtractor:()=>d.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>l.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>l.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>l.SpeechT5HifiGan,SpeechT5Model:()=>l.SpeechT5Model,SpeechT5PreTrainedModel:()=>l.SpeechT5PreTrainedModel,SpeechT5Processor:()=>d.SpeechT5Processor,SpeechT5Tokenizer:()=>u.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>l.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>l.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>l.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>l.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>l.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>u.SqueezeBertTokenizer,StableLmForCausalLM:()=>l.StableLmForCausalLM,StableLmModel:()=>l.StableLmModel,StableLmPreTrainedModel:()=>l.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>l.Starcoder2ForCausalLM,Starcoder2Model:()=>l.Starcoder2Model,Starcoder2PreTrainedModel:()=>l.Starcoder2PreTrainedModel,StoppingCriteria:()=>_.StoppingCriteria,StoppingCriteriaList:()=>_.StoppingCriteriaList,SummarizationPipeline:()=>o.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>l.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>d.Swin2SRImageProcessor,Swin2SRModel:()=>l.Swin2SRModel,Swin2SRPreTrainedModel:()=>l.Swin2SRPreTrainedModel,SwinForImageClassification:()=>l.SwinForImageClassification,SwinModel:()=>l.SwinModel,SwinPreTrainedModel:()=>l.SwinPreTrainedModel,T5ForConditionalGeneration:()=>l.T5ForConditionalGeneration,T5Model:()=>l.T5Model,T5PreTrainedModel:()=>l.T5PreTrainedModel,T5Tokenizer:()=>u.T5Tokenizer,TableTransformerForObjectDetection:()=>l.TableTransformerForObjectDetection,TableTransformerModel:()=>l.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>l.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>l.TableTransformerPreTrainedModel,Tensor:()=>m.Tensor,Text2TextGenerationPipeline:()=>o.Text2TextGenerationPipeline,TextClassificationPipeline:()=>o.TextClassificationPipeline,TextGenerationPipeline:()=>o.TextGenerationPipeline,TextStreamer:()=>g.TextStreamer,TextToAudioPipeline:()=>o.TextToAudioPipeline,TokenClassificationPipeline:()=>o.TokenClassificationPipeline,TokenClassifierOutput:()=>l.TokenClassifierOutput,TokenizerModel:()=>u.TokenizerModel,TrOCRForCausalLM:()=>l.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>l.TrOCRPreTrainedModel,TranslationPipeline:()=>o.TranslationPipeline,UniSpeechForCTC:()=>l.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>l.UniSpeechForSequenceClassification,UniSpeechModel:()=>l.UniSpeechModel,UniSpeechPreTrainedModel:()=>l.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>l.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>l.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>l.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>l.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>l.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>d.ViTFeatureExtractor,ViTForImageClassification:()=>l.ViTForImageClassification,ViTImageProcessor:()=>d.ViTImageProcessor,ViTMAEModel:()=>l.ViTMAEModel,ViTMAEPreTrainedModel:()=>l.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>l.ViTMSNForImageClassification,ViTMSNModel:()=>l.ViTMSNModel,ViTMSNPreTrainedModel:()=>l.ViTMSNPreTrainedModel,ViTModel:()=>l.ViTModel,ViTPreTrainedModel:()=>l.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>l.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>l.VitMatteForImageMatting,VitMatteImageProcessor:()=>d.VitMatteImageProcessor,VitMattePreTrainedModel:()=>l.VitMattePreTrainedModel,VitsModel:()=>l.VitsModel,VitsModelOutput:()=>l.VitsModelOutput,VitsPreTrainedModel:()=>l.VitsPreTrainedModel,VitsTokenizer:()=>u.VitsTokenizer,Wav2Vec2BertForCTC:()=>l.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>l.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>l.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>l.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>u.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>d.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>l.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>l.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>l.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>l.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>l.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>d.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>l.WavLMForAudioFrameClassification,WavLMForCTC:()=>l.WavLMForCTC,WavLMForSequenceClassification:()=>l.WavLMForSequenceClassification,WavLMForXVector:()=>l.WavLMForXVector,WavLMModel:()=>l.WavLMModel,WavLMPreTrainedModel:()=>l.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>d.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>l.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>l.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>d.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>l.WhisperForConditionalGeneration,WhisperModel:()=>l.WhisperModel,WhisperPreTrainedModel:()=>l.WhisperPreTrainedModel,WhisperProcessor:()=>d.WhisperProcessor,WhisperTextStreamer:()=>g.WhisperTextStreamer,WhisperTokenizer:()=>u.WhisperTokenizer,XLMForQuestionAnswering:()=>l.XLMForQuestionAnswering,XLMForSequenceClassification:()=>l.XLMForSequenceClassification,XLMForTokenClassification:()=>l.XLMForTokenClassification,XLMModel:()=>l.XLMModel,XLMPreTrainedModel:()=>l.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>l.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>l.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>l.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>l.XLMRobertaForTokenClassification,XLMRobertaModel:()=>l.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>l.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>u.XLMRobertaTokenizer,XLMTokenizer:()=>u.XLMTokenizer,XLMWithLMHeadModel:()=>l.XLMWithLMHeadModel,XVectorOutput:()=>l.XVectorOutput,YolosFeatureExtractor:()=>d.YolosFeatureExtractor,YolosForObjectDetection:()=>l.YolosForObjectDetection,YolosModel:()=>l.YolosModel,YolosObjectDetectionOutput:()=>l.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>l.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>o.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>o.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>o.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>o.ZeroShotObjectDetectionPipeline,bankers_round:()=>f.bankers_round,cat:()=>m.cat,cos_sim:()=>f.cos_sim,dot:()=>f.dot,dynamic_time_warping:()=>f.dynamic_time_warping,env:()=>s.env,full:()=>m.full,full_like:()=>m.full_like,getKeyValueShapes:()=>c.getKeyValueShapes,getPerf:()=>l.getPerf,hamming:()=>p.hamming,hanning:()=>p.hanning,interpolate:()=>m.interpolate,interpolate_4d:()=>m.interpolate_4d,interpolate_data:()=>f.interpolate_data,is_chinese_char:()=>u.is_chinese_char,layer_norm:()=>m.layer_norm,log_softmax:()=>f.log_softmax,magnitude:()=>f.magnitude,matmul:()=>m.matmul,max:()=>f.max,mean:()=>m.mean,mean_pooling:()=>m.mean_pooling,medianFilter:()=>f.medianFilter,mel_filter_bank:()=>p.mel_filter_bank,min:()=>f.min,ones:()=>m.ones,ones_like:()=>m.ones_like,permute:()=>m.permute,permute_data:()=>f.permute_data,pipeline:()=>o.pipeline,quantize_embeddings:()=>m.quantize_embeddings,read_audio:()=>p.read_audio,rfft:()=>m.rfft,round:()=>f.round,softmax:()=>f.softmax,spectrogram:()=>p.spectrogram,stack:()=>m.stack,std_mean:()=>m.std_mean,topk:()=>m.topk,window_function:()=>p.window_function,zeros:()=>m.zeros,zeros_like:()=>m.zeros_like});var s=i(/*! ./env.js */"./src/env.js"),o=i(/*! ./pipelines.js */"./src/pipelines.js"),l=i(/*! ./models.js */"./src/models.js"),u=i(/*! ./tokenizers.js */"./src/tokenizers.js"),d=i(/*! ./processors.js */"./src/processors.js"),c=i(/*! ./configs.js */"./src/configs.js"),p=i(/*! ./utils/audio.js */"./src/utils/audio.js"),h=i(/*! ./utils/image.js */"./src/utils/image.js"),m=i(/*! ./utils/tensor.js */"./src/utils/tensor.js"),f=i(/*! ./utils/maths.js */"./src/utils/maths.js"),g=i(/*! ./generation/streamers.js */"./src/generation/streamers.js"),_=i(/*! ./generation/stopping_criteria.js */"./src/generation/stopping_criteria.js"),w=a.ASTFeatureExtractor,b=a.ASTForAudioClassification,y=a.ASTModel,x=a.ASTPreTrainedModel,v=a.AlbertForMaskedLM,M=a.AlbertForQuestionAnswering,T=a.AlbertForSequenceClassification,k=a.AlbertModel,$=a.AlbertPreTrainedModel,C=a.AlbertTokenizer,S=a.AudioClassificationPipeline,P=a.AutoConfig,E=a.AutoModel,F=a.AutoModelForAudioClassification,A=a.AutoModelForAudioFrameClassification,I=a.AutoModelForCTC,z=a.AutoModelForCausalLM,O=a.AutoModelForDepthEstimation,B=a.AutoModelForDocumentQuestionAnswering,L=a.AutoModelForImageClassification,N=a.AutoModelForImageFeatureExtraction,D=a.AutoModelForImageMatting,R=a.AutoModelForImageSegmentation,V=a.AutoModelForImageToImage,j=a.AutoModelForMaskGeneration,q=a.AutoModelForMaskedLM,G=a.AutoModelForNormalEstimation,W=a.AutoModelForObjectDetection,U=a.AutoModelForQuestionAnswering,H=a.AutoModelForSemanticSegmentation,X=a.AutoModelForSeq2SeqLM,K=a.AutoModelForSequenceClassification,Q=a.AutoModelForSpeechSeq2Seq,Y=a.AutoModelForTextToSpectrogram,Z=a.AutoModelForTextToWaveform,J=a.AutoModelForTokenClassification,ee=a.AutoModelForUniversalSegmentation,te=a.AutoModelForVision2Seq,ne=a.AutoModelForXVector,re=a.AutoModelForZeroShotObjectDetection,ie=a.AutoProcessor,ae=a.AutoTokenizer,se=a.AutomaticSpeechRecognitionPipeline,oe=a.BartForConditionalGeneration,le=a.BartForSequenceClassification,ue=a.BartModel,de=a.BartPretrainedModel,ce=a.BartTokenizer,pe=a.BaseModelOutput,he=a.BaseStreamer,me=a.BeitFeatureExtractor,fe=a.BeitForImageClassification,ge=a.BeitModel,_e=a.BeitPreTrainedModel,we=a.BertForMaskedLM,be=a.BertForQuestionAnswering,ye=a.BertForSequenceClassification,xe=a.BertForTokenClassification,ve=a.BertModel,Me=a.BertPreTrainedModel,Te=a.BertTokenizer,ke=a.BitImageProcessor,$e=a.BlenderbotForConditionalGeneration,Ce=a.BlenderbotModel,Se=a.BlenderbotPreTrainedModel,Pe=a.BlenderbotSmallForConditionalGeneration,Ee=a.BlenderbotSmallModel,Fe=a.BlenderbotSmallPreTrainedModel,Ae=a.BlenderbotSmallTokenizer,Ie=a.BlenderbotTokenizer,ze=a.BloomForCausalLM,Oe=a.BloomModel,Be=a.BloomPreTrainedModel,Le=a.BloomTokenizer,Ne=a.CLIPFeatureExtractor,De=a.CLIPImageProcessor,Re=a.CLIPModel,Ve=a.CLIPPreTrainedModel,je=a.CLIPSegForImageSegmentation,qe=a.CLIPSegModel,Ge=a.CLIPSegPreTrainedModel,We=a.CLIPTextModel,Ue=a.CLIPTextModelWithProjection,He=a.CLIPTokenizer,Xe=a.CLIPVisionModel,Ke=a.CLIPVisionModelWithProjection,Qe=a.CamembertForMaskedLM,Ye=a.CamembertForQuestionAnswering,Ze=a.CamembertForSequenceClassification,Je=a.CamembertForTokenClassification,et=a.CamembertModel,tt=a.CamembertPreTrainedModel,nt=a.CamembertTokenizer,rt=a.CausalLMOutput,it=a.CausalLMOutputWithPast,at=a.ChineseCLIPFeatureExtractor,st=a.ChineseCLIPModel,ot=a.ChineseCLIPPreTrainedModel,lt=a.ClapAudioModelWithProjection,ut=a.ClapFeatureExtractor,dt=a.ClapModel,ct=a.ClapPreTrainedModel,pt=a.ClapTextModelWithProjection,ht=a.CodeGenForCausalLM,mt=a.CodeGenModel,ft=a.CodeGenPreTrainedModel,gt=a.CodeGenTokenizer,_t=a.CodeLlamaTokenizer,wt=a.CohereForCausalLM,bt=a.CohereModel,yt=a.CoherePreTrainedModel,xt=a.CohereTokenizer,vt=a.ConvBertForMaskedLM,Mt=a.ConvBertForQuestionAnswering,Tt=a.ConvBertForSequenceClassification,kt=a.ConvBertForTokenClassification,$t=a.ConvBertModel,Ct=a.ConvBertPreTrainedModel,St=a.ConvBertTokenizer,Pt=a.ConvNextFeatureExtractor,Et=a.ConvNextForImageClassification,Ft=a.ConvNextImageProcessor,At=a.ConvNextModel,It=a.ConvNextPreTrainedModel,zt=a.ConvNextV2ForImageClassification,Ot=a.ConvNextV2Model,Bt=a.ConvNextV2PreTrainedModel,Lt=a.DPTFeatureExtractor,Nt=a.DPTForDepthEstimation,Dt=a.DPTImageProcessor,Rt=a.DPTModel,Vt=a.DPTPreTrainedModel,jt=a.DebertaForMaskedLM,qt=a.DebertaForQuestionAnswering,Gt=a.DebertaForSequenceClassification,Wt=a.DebertaForTokenClassification,Ut=a.DebertaModel,Ht=a.DebertaPreTrainedModel,Xt=a.DebertaTokenizer,Kt=a.DebertaV2ForMaskedLM,Qt=a.DebertaV2ForQuestionAnswering,Yt=a.DebertaV2ForSequenceClassification,Zt=a.DebertaV2ForTokenClassification,Jt=a.DebertaV2Model,en=a.DebertaV2PreTrainedModel,tn=a.DebertaV2Tokenizer,nn=a.DecisionTransformerModel,rn=a.DecisionTransformerPreTrainedModel,an=a.DeiTFeatureExtractor,sn=a.DeiTForImageClassification,on=a.DeiTModel,ln=a.DeiTPreTrainedModel,un=a.DepthAnythingForDepthEstimation,dn=a.DepthAnythingPreTrainedModel,cn=a.DepthEstimationPipeline,pn=a.DepthProForDepthEstimation,hn=a.DepthProPreTrainedModel,mn=a.DetrFeatureExtractor,fn=a.DetrForObjectDetection,gn=a.DetrForSegmentation,_n=a.DetrModel,wn=a.DetrObjectDetectionOutput,bn=a.DetrPreTrainedModel,yn=a.DetrSegmentationOutput,xn=a.Dinov2ForImageClassification,vn=a.Dinov2Model,Mn=a.Dinov2PreTrainedModel,Tn=a.DistilBertForMaskedLM,kn=a.DistilBertForQuestionAnswering,$n=a.DistilBertForSequenceClassification,Cn=a.DistilBertForTokenClassification,Sn=a.DistilBertModel,Pn=a.DistilBertPreTrainedModel,En=a.DistilBertTokenizer,Fn=a.DocumentQuestionAnsweringPipeline,An=a.DonutFeatureExtractor,In=a.DonutSwinModel,zn=a.DonutSwinPreTrainedModel,On=a.EfficientNetForImageClassification,Bn=a.EfficientNetImageProcessor,Ln=a.EfficientNetModel,Nn=a.EfficientNetPreTrainedModel,Dn=a.ElectraForMaskedLM,Rn=a.ElectraForQuestionAnswering,Vn=a.ElectraForSequenceClassification,jn=a.ElectraForTokenClassification,qn=a.ElectraModel,Gn=a.ElectraPreTrainedModel,Wn=a.ElectraTokenizer,Un=a.EosTokenCriteria,Hn=a.EsmForMaskedLM,Xn=a.EsmForSequenceClassification,Kn=a.EsmForTokenClassification,Qn=a.EsmModel,Yn=a.EsmPreTrainedModel,Zn=a.EsmTokenizer,Jn=a.FFT,er=a.FalconForCausalLM,tr=a.FalconModel,nr=a.FalconPreTrainedModel,rr=a.FalconTokenizer,ir=a.FastViTForImageClassification,ar=a.FastViTModel,sr=a.FastViTPreTrainedModel,or=a.FeatureExtractionPipeline,lr=a.FeatureExtractor,ur=a.FillMaskPipeline,dr=a.Florence2ForConditionalGeneration,cr=a.Florence2PreTrainedModel,pr=a.Florence2Processor,hr=a.GLPNFeatureExtractor,mr=a.GLPNForDepthEstimation,fr=a.GLPNModel,gr=a.GLPNPreTrainedModel,_r=a.GPT2LMHeadModel,wr=a.GPT2Model,br=a.GPT2PreTrainedModel,yr=a.GPT2Tokenizer,xr=a.GPTBigCodeForCausalLM,vr=a.GPTBigCodeModel,Mr=a.GPTBigCodePreTrainedModel,Tr=a.GPTJForCausalLM,kr=a.GPTJModel,$r=a.GPTJPreTrainedModel,Cr=a.GPTNeoForCausalLM,Sr=a.GPTNeoModel,Pr=a.GPTNeoPreTrainedModel,Er=a.GPTNeoXForCausalLM,Fr=a.GPTNeoXModel,Ar=a.GPTNeoXPreTrainedModel,Ir=a.GPTNeoXTokenizer,zr=a.Gemma2ForCausalLM,Or=a.Gemma2Model,Br=a.Gemma2PreTrainedModel,Lr=a.GemmaForCausalLM,Nr=a.GemmaModel,Dr=a.GemmaPreTrainedModel,Rr=a.GemmaTokenizer,Vr=a.GraniteForCausalLM,jr=a.GraniteModel,qr=a.GranitePreTrainedModel,Gr=a.Grok1Tokenizer,Wr=a.GroupViTModel,Ur=a.GroupViTPreTrainedModel,Hr=a.HerbertTokenizer,Xr=a.HieraForImageClassification,Kr=a.HieraModel,Qr=a.HieraPreTrainedModel,Yr=a.HubertForCTC,Zr=a.HubertForSequenceClassification,Jr=a.HubertModel,ei=a.HubertPreTrainedModel,ti=a.ImageClassificationPipeline,ni=a.ImageFeatureExtractionPipeline,ri=a.ImageFeatureExtractor,ii=a.ImageMattingOutput,ai=a.ImageSegmentationPipeline,si=a.ImageToImagePipeline,oi=a.ImageToTextPipeline,li=a.InterruptableStoppingCriteria,ui=a.JAISLMHeadModel,di=a.JAISModel,ci=a.JAISPreTrainedModel,pi=a.LlamaForCausalLM,hi=a.LlamaModel,mi=a.LlamaPreTrainedModel,fi=a.LlamaTokenizer,gi=a.LlavaForConditionalGeneration,_i=a.LlavaPreTrainedModel,wi=a.LongT5ForConditionalGeneration,bi=a.LongT5Model,yi=a.LongT5PreTrainedModel,xi=a.M2M100ForConditionalGeneration,vi=a.M2M100Model,Mi=a.M2M100PreTrainedModel,Ti=a.M2M100Tokenizer,ki=a.MBart50Tokenizer,$i=a.MBartForCausalLM,Ci=a.MBartForConditionalGeneration,Si=a.MBartForSequenceClassification,Pi=a.MBartModel,Ei=a.MBartPreTrainedModel,Fi=a.MBartTokenizer,Ai=a.MPNetForMaskedLM,Ii=a.MPNetForQuestionAnswering,zi=a.MPNetForSequenceClassification,Oi=a.MPNetForTokenClassification,Bi=a.MPNetModel,Li=a.MPNetPreTrainedModel,Ni=a.MPNetTokenizer,Di=a.MT5ForConditionalGeneration,Ri=a.MT5Model,Vi=a.MT5PreTrainedModel,ji=a.MarianMTModel,qi=a.MarianModel,Gi=a.MarianPreTrainedModel,Wi=a.MarianTokenizer,Ui=a.MaskFormerFeatureExtractor,Hi=a.MaskFormerForInstanceSegmentation,Xi=a.MaskFormerModel,Ki=a.MaskFormerPreTrainedModel,Qi=a.MaskedLMOutput,Yi=a.MaxLengthCriteria,Zi=a.MistralForCausalLM,Ji=a.MistralModel,ea=a.MistralPreTrainedModel,ta=a.MobileBertForMaskedLM,na=a.MobileBertForQuestionAnswering,ra=a.MobileBertForSequenceClassification,ia=a.MobileBertModel,aa=a.MobileBertPreTrainedModel,sa=a.MobileBertTokenizer,oa=a.MobileNetV1FeatureExtractor,la=a.MobileNetV1ForImageClassification,ua=a.MobileNetV1Model,da=a.MobileNetV1PreTrainedModel,ca=a.MobileNetV2FeatureExtractor,pa=a.MobileNetV2ForImageClassification,ha=a.MobileNetV2Model,ma=a.MobileNetV2PreTrainedModel,fa=a.MobileNetV3FeatureExtractor,ga=a.MobileNetV3ForImageClassification,_a=a.MobileNetV3Model,wa=a.MobileNetV3PreTrainedModel,ba=a.MobileNetV4FeatureExtractor,ya=a.MobileNetV4ForImageClassification,xa=a.MobileNetV4Model,va=a.MobileNetV4PreTrainedModel,Ma=a.MobileViTFeatureExtractor,Ta=a.MobileViTForImageClassification,ka=a.MobileViTImageProcessor,$a=a.MobileViTModel,Ca=a.MobileViTPreTrainedModel,Sa=a.MobileViTV2ForImageClassification,Pa=a.MobileViTV2Model,Ea=a.MobileViTV2PreTrainedModel,Fa=a.ModelOutput,Aa=a.Moondream1ForConditionalGeneration,Ia=a.MptForCausalLM,za=a.MptModel,Oa=a.MptPreTrainedModel,Ba=a.MusicgenForCausalLM,La=a.MusicgenForConditionalGeneration,Na=a.MusicgenModel,Da=a.MusicgenPreTrainedModel,Ra=a.NllbTokenizer,Va=a.NomicBertModel,ja=a.NomicBertPreTrainedModel,qa=a.NougatImageProcessor,Ga=a.NougatTokenizer,Wa=a.OPTForCausalLM,Ua=a.OPTModel,Ha=a.OPTPreTrainedModel,Xa=a.ObjectDetectionPipeline,Ka=a.OpenELMForCausalLM,Qa=a.OpenELMModel,Ya=a.OpenELMPreTrainedModel,Za=a.OwlViTFeatureExtractor,Ja=a.OwlViTForObjectDetection,es=a.OwlViTModel,ts=a.OwlViTPreTrainedModel,ns=a.OwlViTProcessor,rs=a.Owlv2ForObjectDetection,is=a.Owlv2ImageProcessor,as=a.Owlv2Model,ss=a.Owlv2PreTrainedModel,os=a.Phi3ForCausalLM,ls=a.Phi3Model,us=a.Phi3PreTrainedModel,ds=a.PhiForCausalLM,cs=a.PhiModel,ps=a.PhiPreTrainedModel,hs=a.Pipeline,ms=a.PreTrainedModel,fs=a.PreTrainedTokenizer,gs=a.PretrainedConfig,_s=a.PretrainedMixin,ws=a.Processor,bs=a.PvtForImageClassification,ys=a.PvtImageProcessor,xs=a.PvtModel,vs=a.PvtPreTrainedModel,Ms=a.PyAnnoteFeatureExtractor,Ts=a.PyAnnoteForAudioFrameClassification,ks=a.PyAnnoteModel,$s=a.PyAnnotePreTrainedModel,Cs=a.PyAnnoteProcessor,Ss=a.QuestionAnsweringModelOutput,Ps=a.QuestionAnsweringPipeline,Es=a.Qwen2ForCausalLM,Fs=a.Qwen2Model,As=a.Qwen2PreTrainedModel,Is=a.Qwen2Tokenizer,zs=a.RTDetrForObjectDetection,Os=a.RTDetrImageProcessor,Bs=a.RTDetrModel,Ls=a.RTDetrObjectDetectionOutput,Ns=a.RTDetrPreTrainedModel,Ds=a.RawImage,Rs=a.ResNetForImageClassification,Vs=a.ResNetModel,js=a.ResNetPreTrainedModel,qs=a.RoFormerForMaskedLM,Gs=a.RoFormerForQuestionAnswering,Ws=a.RoFormerForSequenceClassification,Us=a.RoFormerForTokenClassification,Hs=a.RoFormerModel,Xs=a.RoFormerPreTrainedModel,Ks=a.RoFormerTokenizer,Qs=a.RobertaForMaskedLM,Ys=a.RobertaForQuestionAnswering,Zs=a.RobertaForSequenceClassification,Js=a.RobertaForTokenClassification,eo=a.RobertaModel,to=a.RobertaPreTrainedModel,no=a.RobertaTokenizer,ro=a.SamImageProcessor,io=a.SamImageSegmentationOutput,ao=a.SamModel,so=a.SamPreTrainedModel,oo=a.SamProcessor,lo=a.SapiensFeatureExtractor,uo=a.SapiensForDepthEstimation,co=a.SapiensForNormalEstimation,po=a.SapiensForSemanticSegmentation,ho=a.SapiensPreTrainedModel,mo=a.SeamlessM4TFeatureExtractor,fo=a.SegformerFeatureExtractor,go=a.SegformerForImageClassification,_o=a.SegformerForSemanticSegmentation,wo=a.SegformerModel,bo=a.SegformerPreTrainedModel,yo=a.Seq2SeqLMOutput,xo=a.SequenceClassifierOutput,vo=a.SiglipImageProcessor,Mo=a.SiglipModel,To=a.SiglipPreTrainedModel,ko=a.SiglipTextModel,$o=a.SiglipTokenizer,Co=a.SiglipVisionModel,So=a.SpeechT5FeatureExtractor,Po=a.SpeechT5ForSpeechToText,Eo=a.SpeechT5ForTextToSpeech,Fo=a.SpeechT5HifiGan,Ao=a.SpeechT5Model,Io=a.SpeechT5PreTrainedModel,zo=a.SpeechT5Processor,Oo=a.SpeechT5Tokenizer,Bo=a.SqueezeBertForMaskedLM,Lo=a.SqueezeBertForQuestionAnswering,No=a.SqueezeBertForSequenceClassification,Do=a.SqueezeBertModel,Ro=a.SqueezeBertPreTrainedModel,Vo=a.SqueezeBertTokenizer,jo=a.StableLmForCausalLM,qo=a.StableLmModel,Go=a.StableLmPreTrainedModel,Wo=a.Starcoder2ForCausalLM,Uo=a.Starcoder2Model,Ho=a.Starcoder2PreTrainedModel,Xo=a.StoppingCriteria,Ko=a.StoppingCriteriaList,Qo=a.SummarizationPipeline,Yo=a.Swin2SRForImageSuperResolution,Zo=a.Swin2SRImageProcessor,Jo=a.Swin2SRModel,el=a.Swin2SRPreTrainedModel,tl=a.SwinForImageClassification,nl=a.SwinModel,rl=a.SwinPreTrainedModel,il=a.T5ForConditionalGeneration,al=a.T5Model,sl=a.T5PreTrainedModel,ol=a.T5Tokenizer,ll=a.TableTransformerForObjectDetection,ul=a.TableTransformerModel,dl=a.TableTransformerObjectDetectionOutput,cl=a.TableTransformerPreTrainedModel,pl=a.Tensor,hl=a.Text2TextGenerationPipeline,ml=a.TextClassificationPipeline,fl=a.TextGenerationPipeline,gl=a.TextStreamer,_l=a.TextToAudioPipeline,wl=a.TokenClassificationPipeline,bl=a.TokenClassifierOutput,yl=a.TokenizerModel,xl=a.TrOCRForCausalLM,vl=a.TrOCRPreTrainedModel,Ml=a.TranslationPipeline,Tl=a.UniSpeechForCTC,kl=a.UniSpeechForSequenceClassification,$l=a.UniSpeechModel,Cl=a.UniSpeechPreTrainedModel,Sl=a.UniSpeechSatForAudioFrameClassification,Pl=a.UniSpeechSatForCTC,El=a.UniSpeechSatForSequenceClassification,Fl=a.UniSpeechSatModel,Al=a.UniSpeechSatPreTrainedModel,Il=a.ViTFeatureExtractor,zl=a.ViTForImageClassification,Ol=a.ViTImageProcessor,Bl=a.ViTMAEModel,Ll=a.ViTMAEPreTrainedModel,Nl=a.ViTMSNForImageClassification,Dl=a.ViTMSNModel,Rl=a.ViTMSNPreTrainedModel,Vl=a.ViTModel,jl=a.ViTPreTrainedModel,ql=a.VisionEncoderDecoderModel,Gl=a.VitMatteForImageMatting,Wl=a.VitMatteImageProcessor,Ul=a.VitMattePreTrainedModel,Hl=a.VitsModel,Xl=a.VitsModelOutput,Kl=a.VitsPreTrainedModel,Ql=a.VitsTokenizer,Yl=a.Wav2Vec2BertForCTC,Zl=a.Wav2Vec2BertForSequenceClassification,Jl=a.Wav2Vec2BertModel,eu=a.Wav2Vec2BertPreTrainedModel,tu=a.Wav2Vec2CTCTokenizer,nu=a.Wav2Vec2FeatureExtractor,ru=a.Wav2Vec2ForAudioFrameClassification,iu=a.Wav2Vec2ForCTC,au=a.Wav2Vec2ForSequenceClassification,su=a.Wav2Vec2Model,ou=a.Wav2Vec2PreTrainedModel,lu=a.Wav2Vec2ProcessorWithLM,uu=a.WavLMForAudioFrameClassification,du=a.WavLMForCTC,cu=a.WavLMForSequenceClassification,pu=a.WavLMForXVector,hu=a.WavLMModel,mu=a.WavLMPreTrainedModel,fu=a.WeSpeakerFeatureExtractor,gu=a.WeSpeakerResNetModel,_u=a.WeSpeakerResNetPreTrainedModel,wu=a.WhisperFeatureExtractor,bu=a.WhisperForConditionalGeneration,yu=a.WhisperModel,xu=a.WhisperPreTrainedModel,vu=a.WhisperProcessor,Mu=a.WhisperTextStreamer,Tu=a.WhisperTokenizer,ku=a.XLMForQuestionAnswering,$u=a.XLMForSequenceClassification,Cu=a.XLMForTokenClassification,Su=a.XLMModel,Pu=a.XLMPreTrainedModel,Eu=a.XLMRobertaForMaskedLM,Fu=a.XLMRobertaForQuestionAnswering,Au=a.XLMRobertaForSequenceClassification,Iu=a.XLMRobertaForTokenClassification,zu=a.XLMRobertaModel,Ou=a.XLMRobertaPreTrainedModel,Bu=a.XLMRobertaTokenizer,Lu=a.XLMTokenizer,Nu=a.XLMWithLMHeadModel,Du=a.XVectorOutput,Ru=a.YolosFeatureExtractor,Vu=a.YolosForObjectDetection,ju=a.YolosModel,qu=a.YolosObjectDetectionOutput,Gu=a.YolosPreTrainedModel,Wu=a.ZeroShotAudioClassificationPipeline,Uu=a.ZeroShotClassificationPipeline,Hu=a.ZeroShotImageClassificationPipeline,Xu=a.ZeroShotObjectDetectionPipeline,Ku=a.bankers_round,Qu=a.cat,Yu=a.cos_sim,Zu=a.dot,Ju=a.dynamic_time_warping,ed=a.env,td=a.full,nd=a.full_like,rd=a.getKeyValueShapes,id=a.getPerf,ad=a.hamming,sd=a.hanning,od=a.interpolate,ld=a.interpolate_4d,ud=a.interpolate_data,dd=a.is_chinese_char,cd=a.layer_norm,pd=a.log_softmax,hd=a.magnitude,md=a.matmul,fd=a.max,gd=a.mean,_d=a.mean_pooling,wd=a.medianFilter,bd=a.mel_filter_bank,yd=a.min,xd=a.ones,vd=a.ones_like,Md=a.permute,Td=a.permute_data,kd=a.pipeline,$d=a.quantize_embeddings,Cd=a.read_audio,Sd=a.rfft,Pd=a.round,Ed=a.softmax,Fd=a.spectrogram,Ad=a.stack,Id=a.std_mean,zd=a.topk,Od=a.window_function,Bd=a.zeros,Ld=a.zeros_like;export{w as ASTFeatureExtractor,b as ASTForAudioClassification,y as ASTModel,x as ASTPreTrainedModel,v as AlbertForMaskedLM,M as AlbertForQuestionAnswering,T as AlbertForSequenceClassification,k as AlbertModel,$ as AlbertPreTrainedModel,C as AlbertTokenizer,S as AudioClassificationPipeline,P as AutoConfig,E as AutoModel,F as AutoModelForAudioClassification,A as AutoModelForAudioFrameClassification,I as AutoModelForCTC,z as AutoModelForCausalLM,O as AutoModelForDepthEstimation,B as AutoModelForDocumentQuestionAnswering,L as AutoModelForImageClassification,N as AutoModelForImageFeatureExtraction,D as AutoModelForImageMatting,R as AutoModelForImageSegmentation,V as AutoModelForImageToImage,j as AutoModelForMaskGeneration,q as AutoModelForMaskedLM,G as AutoModelForNormalEstimation,W as AutoModelForObjectDetection,U as AutoModelForQuestionAnswering,H as AutoModelForSemanticSegmentation,X as AutoModelForSeq2SeqLM,K as AutoModelForSequenceClassification,Q as AutoModelForSpeechSeq2Seq,Y as AutoModelForTextToSpectrogram,Z as AutoModelForTextToWaveform,J as AutoModelForTokenClassification,ee as AutoModelForUniversalSegmentation,te as AutoModelForVision2Seq,ne as AutoModelForXVector,re as AutoModelForZeroShotObjectDetection,ie as AutoProcessor,ae as AutoTokenizer,se as AutomaticSpeechRecognitionPipeline,oe as BartForConditionalGeneration,le as BartForSequenceClassification,ue as BartModel,de as BartPretrainedModel,ce as BartTokenizer,pe as BaseModelOutput,he as BaseStreamer,me as BeitFeatureExtractor,fe as BeitForImageClassification,ge as BeitModel,_e as BeitPreTrainedModel,we as BertForMaskedLM,be as BertForQuestionAnswering,ye as BertForSequenceClassification,xe as BertForTokenClassification,ve as BertModel,Me as BertPreTrainedModel,Te as BertTokenizer,ke as BitImageProcessor,$e as BlenderbotForConditionalGeneration,Ce as BlenderbotModel,Se as BlenderbotPreTrainedModel,Pe as BlenderbotSmallForConditionalGeneration,Ee as BlenderbotSmallModel,Fe as BlenderbotSmallPreTrainedModel,Ae as BlenderbotSmallTokenizer,Ie as BlenderbotTokenizer,ze as BloomForCausalLM,Oe as BloomModel,Be as BloomPreTrainedModel,Le as BloomTokenizer,Ne as CLIPFeatureExtractor,De as CLIPImageProcessor,Re as CLIPModel,Ve as CLIPPreTrainedModel,je as CLIPSegForImageSegmentation,qe as CLIPSegModel,Ge as CLIPSegPreTrainedModel,We as CLIPTextModel,Ue as CLIPTextModelWithProjection,He as CLIPTokenizer,Xe as CLIPVisionModel,Ke as CLIPVisionModelWithProjection,Qe as CamembertForMaskedLM,Ye as CamembertForQuestionAnswering,Ze as CamembertForSequenceClassification,Je as CamembertForTokenClassification,et as CamembertModel,tt as CamembertPreTrainedModel,nt as CamembertTokenizer,rt as CausalLMOutput,it as CausalLMOutputWithPast,at as ChineseCLIPFeatureExtractor,st as ChineseCLIPModel,ot as ChineseCLIPPreTrainedModel,lt as ClapAudioModelWithProjection,ut as ClapFeatureExtractor,dt as ClapModel,ct as ClapPreTrainedModel,pt as ClapTextModelWithProjection,ht as CodeGenForCausalLM,mt as CodeGenModel,ft as CodeGenPreTrainedModel,gt as CodeGenTokenizer,_t as CodeLlamaTokenizer,wt as CohereForCausalLM,bt as CohereModel,yt as CoherePreTrainedModel,xt as CohereTokenizer,vt as ConvBertForMaskedLM,Mt as ConvBertForQuestionAnswering,Tt as ConvBertForSequenceClassification,kt as ConvBertForTokenClassification,$t as ConvBertModel,Ct as ConvBertPreTrainedModel,St as ConvBertTokenizer,Pt as ConvNextFeatureExtractor,Et as ConvNextForImageClassification,Ft as ConvNextImageProcessor,At as ConvNextModel,It as ConvNextPreTrainedModel,zt as ConvNextV2ForImageClassification,Ot as ConvNextV2Model,Bt as ConvNextV2PreTrainedModel,Lt as DPTFeatureExtractor,Nt as DPTForDepthEstimation,Dt as DPTImageProcessor,Rt as DPTModel,Vt as DPTPreTrainedModel,jt as DebertaForMaskedLM,qt as DebertaForQuestionAnswering,Gt as DebertaForSequenceClassification,Wt as DebertaForTokenClassification,Ut as DebertaModel,Ht as DebertaPreTrainedModel,Xt as DebertaTokenizer,Kt as DebertaV2ForMaskedLM,Qt as DebertaV2ForQuestionAnswering,Yt as DebertaV2ForSequenceClassification,Zt as DebertaV2ForTokenClassification,Jt as DebertaV2Model,en as DebertaV2PreTrainedModel,tn as DebertaV2Tokenizer,nn as DecisionTransformerModel,rn as DecisionTransformerPreTrainedModel,an as DeiTFeatureExtractor,sn as DeiTForImageClassification,on as DeiTModel,ln as DeiTPreTrainedModel,un as DepthAnythingForDepthEstimation,dn as DepthAnythingPreTrainedModel,cn as DepthEstimationPipeline,pn as DepthProForDepthEstimation,hn as DepthProPreTrainedModel,mn as DetrFeatureExtractor,fn as DetrForObjectDetection,gn as DetrForSegmentation,_n as DetrModel,wn as DetrObjectDetectionOutput,bn as DetrPreTrainedModel,yn as DetrSegmentationOutput,xn as Dinov2ForImageClassification,vn as Dinov2Model,Mn as Dinov2PreTrainedModel,Tn as DistilBertForMaskedLM,kn as DistilBertForQuestionAnswering,$n as DistilBertForSequenceClassification,Cn as DistilBertForTokenClassification,Sn as DistilBertModel,Pn as DistilBertPreTrainedModel,En as DistilBertTokenizer,Fn as DocumentQuestionAnsweringPipeline,An as DonutFeatureExtractor,In as DonutSwinModel,zn as DonutSwinPreTrainedModel,On as EfficientNetForImageClassification,Bn as EfficientNetImageProcessor,Ln as EfficientNetModel,Nn as EfficientNetPreTrainedModel,Dn as ElectraForMaskedLM,Rn as ElectraForQuestionAnswering,Vn as ElectraForSequenceClassification,jn as ElectraForTokenClassification,qn as ElectraModel,Gn as ElectraPreTrainedModel,Wn as ElectraTokenizer,Un as EosTokenCriteria,Hn as EsmForMaskedLM,Xn as EsmForSequenceClassification,Kn as EsmForTokenClassification,Qn as EsmModel,Yn as EsmPreTrainedModel,Zn as EsmTokenizer,Jn as FFT,er as FalconForCausalLM,tr as FalconModel,nr as FalconPreTrainedModel,rr as FalconTokenizer,ir as FastViTForImageClassification,ar as FastViTModel,sr as FastViTPreTrainedModel,or as FeatureExtractionPipeline,lr as FeatureExtractor,ur as FillMaskPipeline,dr as Florence2ForConditionalGeneration,cr as Florence2PreTrainedModel,pr as Florence2Processor,hr as GLPNFeatureExtractor,mr as GLPNForDepthEstimation,fr as GLPNModel,gr as GLPNPreTrainedModel,_r as GPT2LMHeadModel,wr as GPT2Model,br as GPT2PreTrainedModel,yr as GPT2Tokenizer,xr as GPTBigCodeForCausalLM,vr as GPTBigCodeModel,Mr as GPTBigCodePreTrainedModel,Tr as GPTJForCausalLM,kr as GPTJModel,$r as GPTJPreTrainedModel,Cr as GPTNeoForCausalLM,Sr as GPTNeoModel,Pr as GPTNeoPreTrainedModel,Er as GPTNeoXForCausalLM,Fr as GPTNeoXModel,Ar as GPTNeoXPreTrainedModel,Ir as GPTNeoXTokenizer,zr as Gemma2ForCausalLM,Or as Gemma2Model,Br as Gemma2PreTrainedModel,Lr as GemmaForCausalLM,Nr as GemmaModel,Dr as GemmaPreTrainedModel,Rr as GemmaTokenizer,Vr as GraniteForCausalLM,jr as GraniteModel,qr as GranitePreTrainedModel,Gr as Grok1Tokenizer,Wr as GroupViTModel,Ur as GroupViTPreTrainedModel,Hr as HerbertTokenizer,Xr as HieraForImageClassification,Kr as HieraModel,Qr as HieraPreTrainedModel,Yr as HubertForCTC,Zr as HubertForSequenceClassification,Jr as HubertModel,ei as HubertPreTrainedModel,ti as ImageClassificationPipeline,ni as ImageFeatureExtractionPipeline,ri as ImageFeatureExtractor,ii as ImageMattingOutput,ai as ImageSegmentationPipeline,si as ImageToImagePipeline,oi as ImageToTextPipeline,li as InterruptableStoppingCriteria,ui as JAISLMHeadModel,di as JAISModel,ci as JAISPreTrainedModel,pi as LlamaForCausalLM,hi as LlamaModel,mi as LlamaPreTrainedModel,fi as LlamaTokenizer,gi as LlavaForConditionalGeneration,_i as LlavaPreTrainedModel,wi as LongT5ForConditionalGeneration,bi as LongT5Model,yi as LongT5PreTrainedModel,xi as M2M100ForConditionalGeneration,vi as M2M100Model,Mi as M2M100PreTrainedModel,Ti as M2M100Tokenizer,ki as MBart50Tokenizer,$i as MBartForCausalLM,Ci as MBartForConditionalGeneration,Si as MBartForSequenceClassification,Pi as MBartModel,Ei as MBartPreTrainedModel,Fi as MBartTokenizer,Ai as MPNetForMaskedLM,Ii as MPNetForQuestionAnswering,zi as MPNetForSequenceClassification,Oi as MPNetForTokenClassification,Bi as MPNetModel,Li as MPNetPreTrainedModel,Ni as MPNetTokenizer,Di as MT5ForConditionalGeneration,Ri as MT5Model,Vi as MT5PreTrainedModel,ji as MarianMTModel,qi as MarianModel,Gi as MarianPreTrainedModel,Wi as MarianTokenizer,Ui as MaskFormerFeatureExtractor,Hi as MaskFormerForInstanceSegmentation,Xi as MaskFormerModel,Ki as MaskFormerPreTrainedModel,Qi as MaskedLMOutput,Yi as MaxLengthCriteria,Zi as MistralForCausalLM,Ji as MistralModel,ea as MistralPreTrainedModel,ta as MobileBertForMaskedLM,na as MobileBertForQuestionAnswering,ra as MobileBertForSequenceClassification,ia as MobileBertModel,aa as MobileBertPreTrainedModel,sa as MobileBertTokenizer,oa as MobileNetV1FeatureExtractor,la as MobileNetV1ForImageClassification,ua as MobileNetV1Model,da as MobileNetV1PreTrainedModel,ca as MobileNetV2FeatureExtractor,pa as MobileNetV2ForImageClassification,ha as MobileNetV2Model,ma as MobileNetV2PreTrainedModel,fa as MobileNetV3FeatureExtractor,ga as MobileNetV3ForImageClassification,_a as MobileNetV3Model,wa as MobileNetV3PreTrainedModel,ba as MobileNetV4FeatureExtractor,ya as MobileNetV4ForImageClassification,xa as MobileNetV4Model,va as MobileNetV4PreTrainedModel,Ma as MobileViTFeatureExtractor,Ta as MobileViTForImageClassification,ka as MobileViTImageProcessor,$a as MobileViTModel,Ca as MobileViTPreTrainedModel,Sa as MobileViTV2ForImageClassification,Pa as MobileViTV2Model,Ea as MobileViTV2PreTrainedModel,Fa as ModelOutput,Aa as Moondream1ForConditionalGeneration,Ia as MptForCausalLM,za as MptModel,Oa as MptPreTrainedModel,Ba as MusicgenForCausalLM,La as MusicgenForConditionalGeneration,Na as MusicgenModel,Da as MusicgenPreTrainedModel,Ra as NllbTokenizer,Va as NomicBertModel,ja as NomicBertPreTrainedModel,qa as NougatImageProcessor,Ga as NougatTokenizer,Wa as OPTForCausalLM,Ua as OPTModel,Ha as OPTPreTrainedModel,Xa as ObjectDetectionPipeline,Ka as OpenELMForCausalLM,Qa as OpenELMModel,Ya as OpenELMPreTrainedModel,Za as OwlViTFeatureExtractor,Ja as OwlViTForObjectDetection,es as OwlViTModel,ts as OwlViTPreTrainedModel,ns as OwlViTProcessor,rs as Owlv2ForObjectDetection,is as Owlv2ImageProcessor,as as Owlv2Model,ss as Owlv2PreTrainedModel,os as Phi3ForCausalLM,ls as Phi3Model,us as Phi3PreTrainedModel,ds as PhiForCausalLM,cs as PhiModel,ps as PhiPreTrainedModel,hs as Pipeline,ms as PreTrainedModel,fs as PreTrainedTokenizer,gs as PretrainedConfig,_s as PretrainedMixin,ws as Processor,bs as PvtForImageClassification,ys as PvtImageProcessor,xs as PvtModel,vs as PvtPreTrainedModel,Ms as PyAnnoteFeatureExtractor,Ts as PyAnnoteForAudioFrameClassification,ks as PyAnnoteModel,$s as PyAnnotePreTrainedModel,Cs as PyAnnoteProcessor,Ss as QuestionAnsweringModelOutput,Ps as QuestionAnsweringPipeline,Es as Qwen2ForCausalLM,Fs as Qwen2Model,As as Qwen2PreTrainedModel,Is as Qwen2Tokenizer,zs as RTDetrForObjectDetection,Os as RTDetrImageProcessor,Bs as RTDetrModel,Ls as RTDetrObjectDetectionOutput,Ns as RTDetrPreTrainedModel,Ds as RawImage,Rs as ResNetForImageClassification,Vs as ResNetModel,js as ResNetPreTrainedModel,qs as RoFormerForMaskedLM,Gs as RoFormerForQuestionAnswering,Ws as RoFormerForSequenceClassification,Us as RoFormerForTokenClassification,Hs as RoFormerModel,Xs as RoFormerPreTrainedModel,Ks as RoFormerTokenizer,Qs as RobertaForMaskedLM,Ys as RobertaForQuestionAnswering,Zs as RobertaForSequenceClassification,Js as RobertaForTokenClassification,eo as RobertaModel,to as RobertaPreTrainedModel,no as RobertaTokenizer,ro as SamImageProcessor,io as SamImageSegmentationOutput,ao as SamModel,so as SamPreTrainedModel,oo as SamProcessor,lo as SapiensFeatureExtractor,uo as SapiensForDepthEstimation,co as SapiensForNormalEstimation,po as SapiensForSemanticSegmentation,ho as SapiensPreTrainedModel,mo as SeamlessM4TFeatureExtractor,fo as SegformerFeatureExtractor,go as SegformerForImageClassification,_o as SegformerForSemanticSegmentation,wo as SegformerModel,bo as SegformerPreTrainedModel,yo as Seq2SeqLMOutput,xo as SequenceClassifierOutput,vo as SiglipImageProcessor,Mo as SiglipModel,To as SiglipPreTrainedModel,ko as SiglipTextModel,$o as SiglipTokenizer,Co as SiglipVisionModel,So as SpeechT5FeatureExtractor,Po as SpeechT5ForSpeechToText,Eo as SpeechT5ForTextToSpeech,Fo as SpeechT5HifiGan,Ao as SpeechT5Model,Io as SpeechT5PreTrainedModel,zo as SpeechT5Processor,Oo as SpeechT5Tokenizer,Bo as SqueezeBertForMaskedLM,Lo as SqueezeBertForQuestionAnswering,No as SqueezeBertForSequenceClassification,Do as SqueezeBertModel,Ro as SqueezeBertPreTrainedModel,Vo as SqueezeBertTokenizer,jo as StableLmForCausalLM,qo as StableLmModel,Go as StableLmPreTrainedModel,Wo as Starcoder2ForCausalLM,Uo as Starcoder2Model,Ho as Starcoder2PreTrainedModel,Xo as StoppingCriteria,Ko as StoppingCriteriaList,Qo as SummarizationPipeline,Yo as Swin2SRForImageSuperResolution,Zo as Swin2SRImageProcessor,Jo as Swin2SRModel,el as Swin2SRPreTrainedModel,tl as SwinForImageClassification,nl as SwinModel,rl as SwinPreTrainedModel,il as T5ForConditionalGeneration,al as T5Model,sl as T5PreTrainedModel,ol as T5Tokenizer,ll as TableTransformerForObjectDetection,ul as TableTransformerModel,dl as TableTransformerObjectDetectionOutput,cl as TableTransformerPreTrainedModel,pl as Tensor,hl as Text2TextGenerationPipeline,ml as TextClassificationPipeline,fl as TextGenerationPipeline,gl as TextStreamer,_l as TextToAudioPipeline,wl as TokenClassificationPipeline,bl as TokenClassifierOutput,yl as TokenizerModel,xl as TrOCRForCausalLM,vl as TrOCRPreTrainedModel,Ml as TranslationPipeline,Tl as UniSpeechForCTC,kl as UniSpeechForSequenceClassification,$l as UniSpeechModel,Cl as UniSpeechPreTrainedModel,Sl as UniSpeechSatForAudioFrameClassification,Pl as UniSpeechSatForCTC,El as UniSpeechSatForSequenceClassification,Fl as UniSpeechSatModel,Al as UniSpeechSatPreTrainedModel,Il as ViTFeatureExtractor,zl as ViTForImageClassification,Ol as ViTImageProcessor,Bl as ViTMAEModel,Ll as ViTMAEPreTrainedModel,Nl as ViTMSNForImageClassification,Dl as ViTMSNModel,Rl as ViTMSNPreTrainedModel,Vl as ViTModel,jl as ViTPreTrainedModel,ql as VisionEncoderDecoderModel,Gl as VitMatteForImageMatting,Wl as VitMatteImageProcessor,Ul as VitMattePreTrainedModel,Hl as VitsModel,Xl as VitsModelOutput,Kl as VitsPreTrainedModel,Ql as VitsTokenizer,Yl as Wav2Vec2BertForCTC,Zl as Wav2Vec2BertForSequenceClassification,Jl as Wav2Vec2BertModel,eu as Wav2Vec2BertPreTrainedModel,tu as Wav2Vec2CTCTokenizer,nu as Wav2Vec2FeatureExtractor,ru as Wav2Vec2ForAudioFrameClassification,iu as Wav2Vec2ForCTC,au as Wav2Vec2ForSequenceClassification,su as Wav2Vec2Model,ou as Wav2Vec2PreTrainedModel,lu as Wav2Vec2ProcessorWithLM,uu as WavLMForAudioFrameClassification,du as WavLMForCTC,cu as WavLMForSequenceClassification,pu as WavLMForXVector,hu as WavLMModel,mu as WavLMPreTrainedModel,fu as WeSpeakerFeatureExtractor,gu as WeSpeakerResNetModel,_u as WeSpeakerResNetPreTrainedModel,wu as WhisperFeatureExtractor,bu as WhisperForConditionalGeneration,yu as WhisperModel,xu as WhisperPreTrainedModel,vu as WhisperProcessor,Mu as WhisperTextStreamer,Tu as WhisperTokenizer,ku as XLMForQuestionAnswering,$u as XLMForSequenceClassification,Cu as XLMForTokenClassification,Su as XLMModel,Pu as XLMPreTrainedModel,Eu as XLMRobertaForMaskedLM,Fu as XLMRobertaForQuestionAnswering,Au as XLMRobertaForSequenceClassification,Iu as XLMRobertaForTokenClassification,zu as XLMRobertaModel,Ou as XLMRobertaPreTrainedModel,Bu as XLMRobertaTokenizer,Lu as XLMTokenizer,Nu as XLMWithLMHeadModel,Du as XVectorOutput,Ru as YolosFeatureExtractor,Vu as YolosForObjectDetection,ju as YolosModel,qu as YolosObjectDetectionOutput,Gu as YolosPreTrainedModel,Wu as ZeroShotAudioClassificationPipeline,Uu as ZeroShotClassificationPipeline,Hu as ZeroShotImageClassificationPipeline,Xu as ZeroShotObjectDetectionPipeline,Ku as bankers_round,Qu as cat,Yu as cos_sim,Zu as dot,Ju as dynamic_time_warping,ed as env,td as full,nd as full_like,rd as getKeyValueShapes,id as getPerf,ad as hamming,sd as hanning,od as interpolate,ld as interpolate_4d,ud as interpolate_data,dd as is_chinese_char,cd as layer_norm,pd as log_softmax,hd as magnitude,md as matmul,fd as max,gd as mean,_d as mean_pooling,wd as medianFilter,bd as mel_filter_bank,yd as min,xd as ones,vd as ones_like,Md as permute,Td as permute_data,kd as pipeline,$d as quantize_embeddings,Cd as read_audio,Sd as rfft,Pd as round,Ed as softmax,Fd as spectrogram,Ad as stack,Id as std_mean,zd as topk,Od as window_function,Bd as zeros,Ld as zeros_like}; + \*****************************/i.r(a),i.d(a,{ASTFeatureExtractor:()=>d.ASTFeatureExtractor,ASTForAudioClassification:()=>l.ASTForAudioClassification,ASTModel:()=>l.ASTModel,ASTPreTrainedModel:()=>l.ASTPreTrainedModel,AlbertForMaskedLM:()=>l.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>l.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>l.AlbertForSequenceClassification,AlbertModel:()=>l.AlbertModel,AlbertPreTrainedModel:()=>l.AlbertPreTrainedModel,AlbertTokenizer:()=>u.AlbertTokenizer,AudioClassificationPipeline:()=>o.AudioClassificationPipeline,AutoConfig:()=>c.AutoConfig,AutoModel:()=>l.AutoModel,AutoModelForAudioClassification:()=>l.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>l.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>l.AutoModelForCTC,AutoModelForCausalLM:()=>l.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>l.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>l.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>l.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>l.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>l.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>l.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>l.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>l.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>l.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>l.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>l.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>l.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>l.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>l.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>l.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>l.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>l.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>l.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>l.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>l.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>l.AutoModelForVision2Seq,AutoModelForXVector:()=>l.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>l.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>d.AutoProcessor,AutoTokenizer:()=>u.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>o.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>l.BartForConditionalGeneration,BartForSequenceClassification:()=>l.BartForSequenceClassification,BartModel:()=>l.BartModel,BartPretrainedModel:()=>l.BartPretrainedModel,BartTokenizer:()=>u.BartTokenizer,BaseModelOutput:()=>l.BaseModelOutput,BaseStreamer:()=>g.BaseStreamer,BeitFeatureExtractor:()=>d.BeitFeatureExtractor,BeitForImageClassification:()=>l.BeitForImageClassification,BeitModel:()=>l.BeitModel,BeitPreTrainedModel:()=>l.BeitPreTrainedModel,BertForMaskedLM:()=>l.BertForMaskedLM,BertForQuestionAnswering:()=>l.BertForQuestionAnswering,BertForSequenceClassification:()=>l.BertForSequenceClassification,BertForTokenClassification:()=>l.BertForTokenClassification,BertModel:()=>l.BertModel,BertPreTrainedModel:()=>l.BertPreTrainedModel,BertTokenizer:()=>u.BertTokenizer,BitImageProcessor:()=>d.BitImageProcessor,BlenderbotForConditionalGeneration:()=>l.BlenderbotForConditionalGeneration,BlenderbotModel:()=>l.BlenderbotModel,BlenderbotPreTrainedModel:()=>l.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>l.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>l.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>l.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>u.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>u.BlenderbotTokenizer,BloomForCausalLM:()=>l.BloomForCausalLM,BloomModel:()=>l.BloomModel,BloomPreTrainedModel:()=>l.BloomPreTrainedModel,BloomTokenizer:()=>u.BloomTokenizer,CLIPFeatureExtractor:()=>d.CLIPFeatureExtractor,CLIPImageProcessor:()=>d.CLIPImageProcessor,CLIPModel:()=>l.CLIPModel,CLIPPreTrainedModel:()=>l.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>l.CLIPSegForImageSegmentation,CLIPSegModel:()=>l.CLIPSegModel,CLIPSegPreTrainedModel:()=>l.CLIPSegPreTrainedModel,CLIPTextModel:()=>l.CLIPTextModel,CLIPTextModelWithProjection:()=>l.CLIPTextModelWithProjection,CLIPTokenizer:()=>u.CLIPTokenizer,CLIPVisionModel:()=>l.CLIPVisionModel,CLIPVisionModelWithProjection:()=>l.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>l.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>l.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>l.CamembertForSequenceClassification,CamembertForTokenClassification:()=>l.CamembertForTokenClassification,CamembertModel:()=>l.CamembertModel,CamembertPreTrainedModel:()=>l.CamembertPreTrainedModel,CamembertTokenizer:()=>u.CamembertTokenizer,CausalLMOutput:()=>l.CausalLMOutput,CausalLMOutputWithPast:()=>l.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>d.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>l.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>l.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>l.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>d.ClapFeatureExtractor,ClapModel:()=>l.ClapModel,ClapPreTrainedModel:()=>l.ClapPreTrainedModel,ClapTextModelWithProjection:()=>l.ClapTextModelWithProjection,CodeGenForCausalLM:()=>l.CodeGenForCausalLM,CodeGenModel:()=>l.CodeGenModel,CodeGenPreTrainedModel:()=>l.CodeGenPreTrainedModel,CodeGenTokenizer:()=>u.CodeGenTokenizer,CodeLlamaTokenizer:()=>u.CodeLlamaTokenizer,CohereForCausalLM:()=>l.CohereForCausalLM,CohereModel:()=>l.CohereModel,CoherePreTrainedModel:()=>l.CoherePreTrainedModel,CohereTokenizer:()=>u.CohereTokenizer,ConvBertForMaskedLM:()=>l.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>l.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>l.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>l.ConvBertForTokenClassification,ConvBertModel:()=>l.ConvBertModel,ConvBertPreTrainedModel:()=>l.ConvBertPreTrainedModel,ConvBertTokenizer:()=>u.ConvBertTokenizer,ConvNextFeatureExtractor:()=>d.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>l.ConvNextForImageClassification,ConvNextImageProcessor:()=>d.ConvNextImageProcessor,ConvNextModel:()=>l.ConvNextModel,ConvNextPreTrainedModel:()=>l.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>l.ConvNextV2ForImageClassification,ConvNextV2Model:()=>l.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>l.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>d.DPTFeatureExtractor,DPTForDepthEstimation:()=>l.DPTForDepthEstimation,DPTImageProcessor:()=>d.DPTImageProcessor,DPTModel:()=>l.DPTModel,DPTPreTrainedModel:()=>l.DPTPreTrainedModel,DebertaForMaskedLM:()=>l.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>l.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>l.DebertaForSequenceClassification,DebertaForTokenClassification:()=>l.DebertaForTokenClassification,DebertaModel:()=>l.DebertaModel,DebertaPreTrainedModel:()=>l.DebertaPreTrainedModel,DebertaTokenizer:()=>u.DebertaTokenizer,DebertaV2ForMaskedLM:()=>l.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>l.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>l.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>l.DebertaV2ForTokenClassification,DebertaV2Model:()=>l.DebertaV2Model,DebertaV2PreTrainedModel:()=>l.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>u.DebertaV2Tokenizer,DecisionTransformerModel:()=>l.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>l.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>d.DeiTFeatureExtractor,DeiTForImageClassification:()=>l.DeiTForImageClassification,DeiTModel:()=>l.DeiTModel,DeiTPreTrainedModel:()=>l.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>l.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>l.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>o.DepthEstimationPipeline,DepthProForDepthEstimation:()=>l.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>l.DepthProPreTrainedModel,DetrFeatureExtractor:()=>d.DetrFeatureExtractor,DetrForObjectDetection:()=>l.DetrForObjectDetection,DetrForSegmentation:()=>l.DetrForSegmentation,DetrModel:()=>l.DetrModel,DetrObjectDetectionOutput:()=>l.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>l.DetrPreTrainedModel,DetrSegmentationOutput:()=>l.DetrSegmentationOutput,Dinov2ForImageClassification:()=>l.Dinov2ForImageClassification,Dinov2Model:()=>l.Dinov2Model,Dinov2PreTrainedModel:()=>l.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>l.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>l.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>l.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>l.DistilBertForTokenClassification,DistilBertModel:()=>l.DistilBertModel,DistilBertPreTrainedModel:()=>l.DistilBertPreTrainedModel,DistilBertTokenizer:()=>u.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>o.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>d.DonutFeatureExtractor,DonutSwinModel:()=>l.DonutSwinModel,DonutSwinPreTrainedModel:()=>l.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>l.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>d.EfficientNetImageProcessor,EfficientNetModel:()=>l.EfficientNetModel,EfficientNetPreTrainedModel:()=>l.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>l.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>l.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>l.ElectraForSequenceClassification,ElectraForTokenClassification:()=>l.ElectraForTokenClassification,ElectraModel:()=>l.ElectraModel,ElectraPreTrainedModel:()=>l.ElectraPreTrainedModel,ElectraTokenizer:()=>u.ElectraTokenizer,EosTokenCriteria:()=>_.EosTokenCriteria,EsmForMaskedLM:()=>l.EsmForMaskedLM,EsmForSequenceClassification:()=>l.EsmForSequenceClassification,EsmForTokenClassification:()=>l.EsmForTokenClassification,EsmModel:()=>l.EsmModel,EsmPreTrainedModel:()=>l.EsmPreTrainedModel,EsmTokenizer:()=>u.EsmTokenizer,FFT:()=>f.FFT,FalconForCausalLM:()=>l.FalconForCausalLM,FalconModel:()=>l.FalconModel,FalconPreTrainedModel:()=>l.FalconPreTrainedModel,FalconTokenizer:()=>u.FalconTokenizer,FastViTForImageClassification:()=>l.FastViTForImageClassification,FastViTModel:()=>l.FastViTModel,FastViTPreTrainedModel:()=>l.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>o.FeatureExtractionPipeline,FeatureExtractor:()=>d.FeatureExtractor,FillMaskPipeline:()=>o.FillMaskPipeline,Florence2ForConditionalGeneration:()=>l.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>l.Florence2PreTrainedModel,Florence2Processor:()=>d.Florence2Processor,GLPNFeatureExtractor:()=>d.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>l.GLPNForDepthEstimation,GLPNModel:()=>l.GLPNModel,GLPNPreTrainedModel:()=>l.GLPNPreTrainedModel,GPT2LMHeadModel:()=>l.GPT2LMHeadModel,GPT2Model:()=>l.GPT2Model,GPT2PreTrainedModel:()=>l.GPT2PreTrainedModel,GPT2Tokenizer:()=>u.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>l.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>l.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>l.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>l.GPTJForCausalLM,GPTJModel:()=>l.GPTJModel,GPTJPreTrainedModel:()=>l.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>l.GPTNeoForCausalLM,GPTNeoModel:()=>l.GPTNeoModel,GPTNeoPreTrainedModel:()=>l.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>l.GPTNeoXForCausalLM,GPTNeoXModel:()=>l.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>l.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>u.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>l.Gemma2ForCausalLM,Gemma2Model:()=>l.Gemma2Model,Gemma2PreTrainedModel:()=>l.Gemma2PreTrainedModel,GemmaForCausalLM:()=>l.GemmaForCausalLM,GemmaModel:()=>l.GemmaModel,GemmaPreTrainedModel:()=>l.GemmaPreTrainedModel,GemmaTokenizer:()=>u.GemmaTokenizer,GraniteForCausalLM:()=>l.GraniteForCausalLM,GraniteModel:()=>l.GraniteModel,GranitePreTrainedModel:()=>l.GranitePreTrainedModel,Grok1Tokenizer:()=>u.Grok1Tokenizer,GroupViTModel:()=>l.GroupViTModel,GroupViTPreTrainedModel:()=>l.GroupViTPreTrainedModel,HerbertTokenizer:()=>u.HerbertTokenizer,HieraForImageClassification:()=>l.HieraForImageClassification,HieraModel:()=>l.HieraModel,HieraPreTrainedModel:()=>l.HieraPreTrainedModel,HubertForCTC:()=>l.HubertForCTC,HubertForSequenceClassification:()=>l.HubertForSequenceClassification,HubertModel:()=>l.HubertModel,HubertPreTrainedModel:()=>l.HubertPreTrainedModel,ImageClassificationPipeline:()=>o.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>o.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>d.ImageFeatureExtractor,ImageMattingOutput:()=>l.ImageMattingOutput,ImageSegmentationPipeline:()=>o.ImageSegmentationPipeline,ImageToImagePipeline:()=>o.ImageToImagePipeline,ImageToTextPipeline:()=>o.ImageToTextPipeline,InterruptableStoppingCriteria:()=>_.InterruptableStoppingCriteria,JAISLMHeadModel:()=>l.JAISLMHeadModel,JAISModel:()=>l.JAISModel,JAISPreTrainedModel:()=>l.JAISPreTrainedModel,LlamaForCausalLM:()=>l.LlamaForCausalLM,LlamaModel:()=>l.LlamaModel,LlamaPreTrainedModel:()=>l.LlamaPreTrainedModel,LlamaTokenizer:()=>u.LlamaTokenizer,LlavaForConditionalGeneration:()=>l.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>l.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>l.LongT5ForConditionalGeneration,LongT5Model:()=>l.LongT5Model,LongT5PreTrainedModel:()=>l.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>l.M2M100ForConditionalGeneration,M2M100Model:()=>l.M2M100Model,M2M100PreTrainedModel:()=>l.M2M100PreTrainedModel,M2M100Tokenizer:()=>u.M2M100Tokenizer,MBart50Tokenizer:()=>u.MBart50Tokenizer,MBartForCausalLM:()=>l.MBartForCausalLM,MBartForConditionalGeneration:()=>l.MBartForConditionalGeneration,MBartForSequenceClassification:()=>l.MBartForSequenceClassification,MBartModel:()=>l.MBartModel,MBartPreTrainedModel:()=>l.MBartPreTrainedModel,MBartTokenizer:()=>u.MBartTokenizer,MPNetForMaskedLM:()=>l.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>l.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>l.MPNetForSequenceClassification,MPNetForTokenClassification:()=>l.MPNetForTokenClassification,MPNetModel:()=>l.MPNetModel,MPNetPreTrainedModel:()=>l.MPNetPreTrainedModel,MPNetTokenizer:()=>u.MPNetTokenizer,MT5ForConditionalGeneration:()=>l.MT5ForConditionalGeneration,MT5Model:()=>l.MT5Model,MT5PreTrainedModel:()=>l.MT5PreTrainedModel,MarianMTModel:()=>l.MarianMTModel,MarianModel:()=>l.MarianModel,MarianPreTrainedModel:()=>l.MarianPreTrainedModel,MarianTokenizer:()=>u.MarianTokenizer,MaskFormerFeatureExtractor:()=>d.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>l.MaskFormerForInstanceSegmentation,MaskFormerModel:()=>l.MaskFormerModel,MaskFormerPreTrainedModel:()=>l.MaskFormerPreTrainedModel,MaskedLMOutput:()=>l.MaskedLMOutput,MaxLengthCriteria:()=>_.MaxLengthCriteria,MistralForCausalLM:()=>l.MistralForCausalLM,MistralModel:()=>l.MistralModel,MistralPreTrainedModel:()=>l.MistralPreTrainedModel,MobileBertForMaskedLM:()=>l.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>l.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>l.MobileBertForSequenceClassification,MobileBertModel:()=>l.MobileBertModel,MobileBertPreTrainedModel:()=>l.MobileBertPreTrainedModel,MobileBertTokenizer:()=>u.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>d.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>l.MobileNetV1ForImageClassification,MobileNetV1Model:()=>l.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>l.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>d.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>l.MobileNetV2ForImageClassification,MobileNetV2Model:()=>l.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>l.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>d.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>l.MobileNetV3ForImageClassification,MobileNetV3Model:()=>l.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>l.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>d.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>l.MobileNetV4ForImageClassification,MobileNetV4Model:()=>l.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>l.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>d.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>l.MobileViTForImageClassification,MobileViTImageProcessor:()=>d.MobileViTImageProcessor,MobileViTModel:()=>l.MobileViTModel,MobileViTPreTrainedModel:()=>l.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>l.MobileViTV2ForImageClassification,MobileViTV2Model:()=>l.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>l.MobileViTV2PreTrainedModel,ModelOutput:()=>l.ModelOutput,Moondream1ForConditionalGeneration:()=>l.Moondream1ForConditionalGeneration,MptForCausalLM:()=>l.MptForCausalLM,MptModel:()=>l.MptModel,MptPreTrainedModel:()=>l.MptPreTrainedModel,MusicgenForCausalLM:()=>l.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>l.MusicgenForConditionalGeneration,MusicgenModel:()=>l.MusicgenModel,MusicgenPreTrainedModel:()=>l.MusicgenPreTrainedModel,NllbTokenizer:()=>u.NllbTokenizer,NomicBertModel:()=>l.NomicBertModel,NomicBertPreTrainedModel:()=>l.NomicBertPreTrainedModel,NougatImageProcessor:()=>d.NougatImageProcessor,NougatTokenizer:()=>u.NougatTokenizer,OPTForCausalLM:()=>l.OPTForCausalLM,OPTModel:()=>l.OPTModel,OPTPreTrainedModel:()=>l.OPTPreTrainedModel,ObjectDetectionPipeline:()=>o.ObjectDetectionPipeline,OpenELMForCausalLM:()=>l.OpenELMForCausalLM,OpenELMModel:()=>l.OpenELMModel,OpenELMPreTrainedModel:()=>l.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>d.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>l.OwlViTForObjectDetection,OwlViTModel:()=>l.OwlViTModel,OwlViTPreTrainedModel:()=>l.OwlViTPreTrainedModel,OwlViTProcessor:()=>d.OwlViTProcessor,Owlv2ForObjectDetection:()=>l.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>d.Owlv2ImageProcessor,Owlv2Model:()=>l.Owlv2Model,Owlv2PreTrainedModel:()=>l.Owlv2PreTrainedModel,Phi3ForCausalLM:()=>l.Phi3ForCausalLM,Phi3Model:()=>l.Phi3Model,Phi3PreTrainedModel:()=>l.Phi3PreTrainedModel,PhiForCausalLM:()=>l.PhiForCausalLM,PhiModel:()=>l.PhiModel,PhiPreTrainedModel:()=>l.PhiPreTrainedModel,Pipeline:()=>o.Pipeline,PreTrainedModel:()=>l.PreTrainedModel,PreTrainedTokenizer:()=>u.PreTrainedTokenizer,PretrainedConfig:()=>c.PretrainedConfig,PretrainedMixin:()=>l.PretrainedMixin,Processor:()=>d.Processor,PvtForImageClassification:()=>l.PvtForImageClassification,PvtImageProcessor:()=>d.PvtImageProcessor,PvtModel:()=>l.PvtModel,PvtPreTrainedModel:()=>l.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>d.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>l.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>l.PyAnnoteModel,PyAnnotePreTrainedModel:()=>l.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>d.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>l.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>o.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>l.Qwen2ForCausalLM,Qwen2Model:()=>l.Qwen2Model,Qwen2PreTrainedModel:()=>l.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>u.Qwen2Tokenizer,RTDetrForObjectDetection:()=>l.RTDetrForObjectDetection,RTDetrImageProcessor:()=>d.RTDetrImageProcessor,RTDetrModel:()=>l.RTDetrModel,RTDetrObjectDetectionOutput:()=>l.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>l.RTDetrPreTrainedModel,RawImage:()=>h.RawImage,ResNetForImageClassification:()=>l.ResNetForImageClassification,ResNetModel:()=>l.ResNetModel,ResNetPreTrainedModel:()=>l.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>l.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>l.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>l.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>l.RoFormerForTokenClassification,RoFormerModel:()=>l.RoFormerModel,RoFormerPreTrainedModel:()=>l.RoFormerPreTrainedModel,RoFormerTokenizer:()=>u.RoFormerTokenizer,RobertaForMaskedLM:()=>l.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>l.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>l.RobertaForSequenceClassification,RobertaForTokenClassification:()=>l.RobertaForTokenClassification,RobertaModel:()=>l.RobertaModel,RobertaPreTrainedModel:()=>l.RobertaPreTrainedModel,RobertaTokenizer:()=>u.RobertaTokenizer,SamImageProcessor:()=>d.SamImageProcessor,SamImageSegmentationOutput:()=>l.SamImageSegmentationOutput,SamModel:()=>l.SamModel,SamPreTrainedModel:()=>l.SamPreTrainedModel,SamProcessor:()=>d.SamProcessor,SapiensFeatureExtractor:()=>d.SapiensFeatureExtractor,SapiensForDepthEstimation:()=>l.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>l.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>l.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>l.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>d.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>d.SegformerFeatureExtractor,SegformerForImageClassification:()=>l.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>l.SegformerForSemanticSegmentation,SegformerModel:()=>l.SegformerModel,SegformerPreTrainedModel:()=>l.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>l.Seq2SeqLMOutput,SequenceClassifierOutput:()=>l.SequenceClassifierOutput,SiglipImageProcessor:()=>d.SiglipImageProcessor,SiglipModel:()=>l.SiglipModel,SiglipPreTrainedModel:()=>l.SiglipPreTrainedModel,SiglipTextModel:()=>l.SiglipTextModel,SiglipTokenizer:()=>u.SiglipTokenizer,SiglipVisionModel:()=>l.SiglipVisionModel,SpeechT5FeatureExtractor:()=>d.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>l.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>l.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>l.SpeechT5HifiGan,SpeechT5Model:()=>l.SpeechT5Model,SpeechT5PreTrainedModel:()=>l.SpeechT5PreTrainedModel,SpeechT5Processor:()=>d.SpeechT5Processor,SpeechT5Tokenizer:()=>u.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>l.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>l.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>l.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>l.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>l.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>u.SqueezeBertTokenizer,StableLmForCausalLM:()=>l.StableLmForCausalLM,StableLmModel:()=>l.StableLmModel,StableLmPreTrainedModel:()=>l.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>l.Starcoder2ForCausalLM,Starcoder2Model:()=>l.Starcoder2Model,Starcoder2PreTrainedModel:()=>l.Starcoder2PreTrainedModel,StoppingCriteria:()=>_.StoppingCriteria,StoppingCriteriaList:()=>_.StoppingCriteriaList,SummarizationPipeline:()=>o.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>l.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>d.Swin2SRImageProcessor,Swin2SRModel:()=>l.Swin2SRModel,Swin2SRPreTrainedModel:()=>l.Swin2SRPreTrainedModel,SwinForImageClassification:()=>l.SwinForImageClassification,SwinModel:()=>l.SwinModel,SwinPreTrainedModel:()=>l.SwinPreTrainedModel,T5ForConditionalGeneration:()=>l.T5ForConditionalGeneration,T5Model:()=>l.T5Model,T5PreTrainedModel:()=>l.T5PreTrainedModel,T5Tokenizer:()=>u.T5Tokenizer,TableTransformerForObjectDetection:()=>l.TableTransformerForObjectDetection,TableTransformerModel:()=>l.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>l.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>l.TableTransformerPreTrainedModel,Tensor:()=>m.Tensor,Text2TextGenerationPipeline:()=>o.Text2TextGenerationPipeline,TextClassificationPipeline:()=>o.TextClassificationPipeline,TextGenerationPipeline:()=>o.TextGenerationPipeline,TextStreamer:()=>g.TextStreamer,TextToAudioPipeline:()=>o.TextToAudioPipeline,TokenClassificationPipeline:()=>o.TokenClassificationPipeline,TokenClassifierOutput:()=>l.TokenClassifierOutput,TokenizerModel:()=>u.TokenizerModel,TrOCRForCausalLM:()=>l.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>l.TrOCRPreTrainedModel,TranslationPipeline:()=>o.TranslationPipeline,UniSpeechForCTC:()=>l.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>l.UniSpeechForSequenceClassification,UniSpeechModel:()=>l.UniSpeechModel,UniSpeechPreTrainedModel:()=>l.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>l.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>l.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>l.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>l.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>l.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>d.ViTFeatureExtractor,ViTForImageClassification:()=>l.ViTForImageClassification,ViTImageProcessor:()=>d.ViTImageProcessor,ViTMAEModel:()=>l.ViTMAEModel,ViTMAEPreTrainedModel:()=>l.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>l.ViTMSNForImageClassification,ViTMSNModel:()=>l.ViTMSNModel,ViTMSNPreTrainedModel:()=>l.ViTMSNPreTrainedModel,ViTModel:()=>l.ViTModel,ViTPreTrainedModel:()=>l.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>l.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>l.VitMatteForImageMatting,VitMatteImageProcessor:()=>d.VitMatteImageProcessor,VitMattePreTrainedModel:()=>l.VitMattePreTrainedModel,VitsModel:()=>l.VitsModel,VitsModelOutput:()=>l.VitsModelOutput,VitsPreTrainedModel:()=>l.VitsPreTrainedModel,VitsTokenizer:()=>u.VitsTokenizer,Wav2Vec2BertForCTC:()=>l.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>l.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>l.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>l.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>u.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>d.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>l.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>l.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>l.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>l.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>l.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>d.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>l.WavLMForAudioFrameClassification,WavLMForCTC:()=>l.WavLMForCTC,WavLMForSequenceClassification:()=>l.WavLMForSequenceClassification,WavLMForXVector:()=>l.WavLMForXVector,WavLMModel:()=>l.WavLMModel,WavLMPreTrainedModel:()=>l.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>d.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>l.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>l.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>d.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>l.WhisperForConditionalGeneration,WhisperModel:()=>l.WhisperModel,WhisperPreTrainedModel:()=>l.WhisperPreTrainedModel,WhisperProcessor:()=>d.WhisperProcessor,WhisperTextStreamer:()=>g.WhisperTextStreamer,WhisperTokenizer:()=>u.WhisperTokenizer,XLMForQuestionAnswering:()=>l.XLMForQuestionAnswering,XLMForSequenceClassification:()=>l.XLMForSequenceClassification,XLMForTokenClassification:()=>l.XLMForTokenClassification,XLMModel:()=>l.XLMModel,XLMPreTrainedModel:()=>l.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>l.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>l.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>l.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>l.XLMRobertaForTokenClassification,XLMRobertaModel:()=>l.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>l.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>u.XLMRobertaTokenizer,XLMTokenizer:()=>u.XLMTokenizer,XLMWithLMHeadModel:()=>l.XLMWithLMHeadModel,XVectorOutput:()=>l.XVectorOutput,YolosFeatureExtractor:()=>d.YolosFeatureExtractor,YolosForObjectDetection:()=>l.YolosForObjectDetection,YolosModel:()=>l.YolosModel,YolosObjectDetectionOutput:()=>l.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>l.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>o.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>o.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>o.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>o.ZeroShotObjectDetectionPipeline,bankers_round:()=>f.bankers_round,cat:()=>m.cat,cos_sim:()=>f.cos_sim,dot:()=>f.dot,dynamic_time_warping:()=>f.dynamic_time_warping,env:()=>s.env,full:()=>m.full,full_like:()=>m.full_like,getKeyValueShapes:()=>c.getKeyValueShapes,getPerf:()=>l.getPerf,hamming:()=>p.hamming,hanning:()=>p.hanning,interpolate:()=>m.interpolate,interpolate_4d:()=>m.interpolate_4d,interpolate_data:()=>f.interpolate_data,is_chinese_char:()=>u.is_chinese_char,layer_norm:()=>m.layer_norm,log_softmax:()=>f.log_softmax,magnitude:()=>f.magnitude,matmul:()=>m.matmul,max:()=>f.max,mean:()=>m.mean,mean_pooling:()=>m.mean_pooling,medianFilter:()=>f.medianFilter,mel_filter_bank:()=>p.mel_filter_bank,min:()=>f.min,ones:()=>m.ones,ones_like:()=>m.ones_like,permute:()=>m.permute,permute_data:()=>f.permute_data,pipeline:()=>o.pipeline,quantize_embeddings:()=>m.quantize_embeddings,read_audio:()=>p.read_audio,rfft:()=>m.rfft,round:()=>f.round,softmax:()=>f.softmax,spectrogram:()=>p.spectrogram,stack:()=>m.stack,std_mean:()=>m.std_mean,topk:()=>m.topk,window_function:()=>p.window_function,zeros:()=>m.zeros,zeros_like:()=>m.zeros_like});var s=i(/*! ./env.js */"./src/env.js"),o=i(/*! ./pipelines.js */"./src/pipelines.js"),l=i(/*! ./models.js */"./src/models.js"),u=i(/*! ./tokenizers.js */"./src/tokenizers.js"),d=i(/*! ./processors.js */"./src/processors.js"),c=i(/*! ./configs.js */"./src/configs.js"),p=i(/*! ./utils/audio.js */"./src/utils/audio.js"),h=i(/*! ./utils/image.js */"./src/utils/image.js"),m=i(/*! ./utils/tensor.js */"./src/utils/tensor.js"),f=i(/*! ./utils/maths.js */"./src/utils/maths.js"),g=i(/*! ./generation/streamers.js */"./src/generation/streamers.js"),_=i(/*! ./generation/stopping_criteria.js */"./src/generation/stopping_criteria.js"),w=a.ASTFeatureExtractor,b=a.ASTForAudioClassification,y=a.ASTModel,x=a.ASTPreTrainedModel,v=a.AlbertForMaskedLM,M=a.AlbertForQuestionAnswering,T=a.AlbertForSequenceClassification,k=a.AlbertModel,$=a.AlbertPreTrainedModel,S=a.AlbertTokenizer,C=a.AudioClassificationPipeline,E=a.AutoConfig,P=a.AutoModel,F=a.AutoModelForAudioClassification,A=a.AutoModelForAudioFrameClassification,I=a.AutoModelForCTC,z=a.AutoModelForCausalLM,O=a.AutoModelForDepthEstimation,B=a.AutoModelForDocumentQuestionAnswering,L=a.AutoModelForImageClassification,N=a.AutoModelForImageFeatureExtraction,D=a.AutoModelForImageMatting,R=a.AutoModelForImageSegmentation,V=a.AutoModelForImageToImage,j=a.AutoModelForMaskGeneration,q=a.AutoModelForMaskedLM,G=a.AutoModelForNormalEstimation,U=a.AutoModelForObjectDetection,W=a.AutoModelForQuestionAnswering,H=a.AutoModelForSemanticSegmentation,K=a.AutoModelForSeq2SeqLM,X=a.AutoModelForSequenceClassification,Q=a.AutoModelForSpeechSeq2Seq,Y=a.AutoModelForTextToSpectrogram,Z=a.AutoModelForTextToWaveform,J=a.AutoModelForTokenClassification,ee=a.AutoModelForUniversalSegmentation,te=a.AutoModelForVision2Seq,ne=a.AutoModelForXVector,re=a.AutoModelForZeroShotObjectDetection,ie=a.AutoProcessor,ae=a.AutoTokenizer,se=a.AutomaticSpeechRecognitionPipeline,oe=a.BartForConditionalGeneration,le=a.BartForSequenceClassification,ue=a.BartModel,de=a.BartPretrainedModel,ce=a.BartTokenizer,pe=a.BaseModelOutput,he=a.BaseStreamer,me=a.BeitFeatureExtractor,fe=a.BeitForImageClassification,ge=a.BeitModel,_e=a.BeitPreTrainedModel,we=a.BertForMaskedLM,be=a.BertForQuestionAnswering,ye=a.BertForSequenceClassification,xe=a.BertForTokenClassification,ve=a.BertModel,Me=a.BertPreTrainedModel,Te=a.BertTokenizer,ke=a.BitImageProcessor,$e=a.BlenderbotForConditionalGeneration,Se=a.BlenderbotModel,Ce=a.BlenderbotPreTrainedModel,Ee=a.BlenderbotSmallForConditionalGeneration,Pe=a.BlenderbotSmallModel,Fe=a.BlenderbotSmallPreTrainedModel,Ae=a.BlenderbotSmallTokenizer,Ie=a.BlenderbotTokenizer,ze=a.BloomForCausalLM,Oe=a.BloomModel,Be=a.BloomPreTrainedModel,Le=a.BloomTokenizer,Ne=a.CLIPFeatureExtractor,De=a.CLIPImageProcessor,Re=a.CLIPModel,Ve=a.CLIPPreTrainedModel,je=a.CLIPSegForImageSegmentation,qe=a.CLIPSegModel,Ge=a.CLIPSegPreTrainedModel,Ue=a.CLIPTextModel,We=a.CLIPTextModelWithProjection,He=a.CLIPTokenizer,Ke=a.CLIPVisionModel,Xe=a.CLIPVisionModelWithProjection,Qe=a.CamembertForMaskedLM,Ye=a.CamembertForQuestionAnswering,Ze=a.CamembertForSequenceClassification,Je=a.CamembertForTokenClassification,et=a.CamembertModel,tt=a.CamembertPreTrainedModel,nt=a.CamembertTokenizer,rt=a.CausalLMOutput,it=a.CausalLMOutputWithPast,at=a.ChineseCLIPFeatureExtractor,st=a.ChineseCLIPModel,ot=a.ChineseCLIPPreTrainedModel,lt=a.ClapAudioModelWithProjection,ut=a.ClapFeatureExtractor,dt=a.ClapModel,ct=a.ClapPreTrainedModel,pt=a.ClapTextModelWithProjection,ht=a.CodeGenForCausalLM,mt=a.CodeGenModel,ft=a.CodeGenPreTrainedModel,gt=a.CodeGenTokenizer,_t=a.CodeLlamaTokenizer,wt=a.CohereForCausalLM,bt=a.CohereModel,yt=a.CoherePreTrainedModel,xt=a.CohereTokenizer,vt=a.ConvBertForMaskedLM,Mt=a.ConvBertForQuestionAnswering,Tt=a.ConvBertForSequenceClassification,kt=a.ConvBertForTokenClassification,$t=a.ConvBertModel,St=a.ConvBertPreTrainedModel,Ct=a.ConvBertTokenizer,Et=a.ConvNextFeatureExtractor,Pt=a.ConvNextForImageClassification,Ft=a.ConvNextImageProcessor,At=a.ConvNextModel,It=a.ConvNextPreTrainedModel,zt=a.ConvNextV2ForImageClassification,Ot=a.ConvNextV2Model,Bt=a.ConvNextV2PreTrainedModel,Lt=a.DPTFeatureExtractor,Nt=a.DPTForDepthEstimation,Dt=a.DPTImageProcessor,Rt=a.DPTModel,Vt=a.DPTPreTrainedModel,jt=a.DebertaForMaskedLM,qt=a.DebertaForQuestionAnswering,Gt=a.DebertaForSequenceClassification,Ut=a.DebertaForTokenClassification,Wt=a.DebertaModel,Ht=a.DebertaPreTrainedModel,Kt=a.DebertaTokenizer,Xt=a.DebertaV2ForMaskedLM,Qt=a.DebertaV2ForQuestionAnswering,Yt=a.DebertaV2ForSequenceClassification,Zt=a.DebertaV2ForTokenClassification,Jt=a.DebertaV2Model,en=a.DebertaV2PreTrainedModel,tn=a.DebertaV2Tokenizer,nn=a.DecisionTransformerModel,rn=a.DecisionTransformerPreTrainedModel,an=a.DeiTFeatureExtractor,sn=a.DeiTForImageClassification,on=a.DeiTModel,ln=a.DeiTPreTrainedModel,un=a.DepthAnythingForDepthEstimation,dn=a.DepthAnythingPreTrainedModel,cn=a.DepthEstimationPipeline,pn=a.DepthProForDepthEstimation,hn=a.DepthProPreTrainedModel,mn=a.DetrFeatureExtractor,fn=a.DetrForObjectDetection,gn=a.DetrForSegmentation,_n=a.DetrModel,wn=a.DetrObjectDetectionOutput,bn=a.DetrPreTrainedModel,yn=a.DetrSegmentationOutput,xn=a.Dinov2ForImageClassification,vn=a.Dinov2Model,Mn=a.Dinov2PreTrainedModel,Tn=a.DistilBertForMaskedLM,kn=a.DistilBertForQuestionAnswering,$n=a.DistilBertForSequenceClassification,Sn=a.DistilBertForTokenClassification,Cn=a.DistilBertModel,En=a.DistilBertPreTrainedModel,Pn=a.DistilBertTokenizer,Fn=a.DocumentQuestionAnsweringPipeline,An=a.DonutFeatureExtractor,In=a.DonutSwinModel,zn=a.DonutSwinPreTrainedModel,On=a.EfficientNetForImageClassification,Bn=a.EfficientNetImageProcessor,Ln=a.EfficientNetModel,Nn=a.EfficientNetPreTrainedModel,Dn=a.ElectraForMaskedLM,Rn=a.ElectraForQuestionAnswering,Vn=a.ElectraForSequenceClassification,jn=a.ElectraForTokenClassification,qn=a.ElectraModel,Gn=a.ElectraPreTrainedModel,Un=a.ElectraTokenizer,Wn=a.EosTokenCriteria,Hn=a.EsmForMaskedLM,Kn=a.EsmForSequenceClassification,Xn=a.EsmForTokenClassification,Qn=a.EsmModel,Yn=a.EsmPreTrainedModel,Zn=a.EsmTokenizer,Jn=a.FFT,er=a.FalconForCausalLM,tr=a.FalconModel,nr=a.FalconPreTrainedModel,rr=a.FalconTokenizer,ir=a.FastViTForImageClassification,ar=a.FastViTModel,sr=a.FastViTPreTrainedModel,or=a.FeatureExtractionPipeline,lr=a.FeatureExtractor,ur=a.FillMaskPipeline,dr=a.Florence2ForConditionalGeneration,cr=a.Florence2PreTrainedModel,pr=a.Florence2Processor,hr=a.GLPNFeatureExtractor,mr=a.GLPNForDepthEstimation,fr=a.GLPNModel,gr=a.GLPNPreTrainedModel,_r=a.GPT2LMHeadModel,wr=a.GPT2Model,br=a.GPT2PreTrainedModel,yr=a.GPT2Tokenizer,xr=a.GPTBigCodeForCausalLM,vr=a.GPTBigCodeModel,Mr=a.GPTBigCodePreTrainedModel,Tr=a.GPTJForCausalLM,kr=a.GPTJModel,$r=a.GPTJPreTrainedModel,Sr=a.GPTNeoForCausalLM,Cr=a.GPTNeoModel,Er=a.GPTNeoPreTrainedModel,Pr=a.GPTNeoXForCausalLM,Fr=a.GPTNeoXModel,Ar=a.GPTNeoXPreTrainedModel,Ir=a.GPTNeoXTokenizer,zr=a.Gemma2ForCausalLM,Or=a.Gemma2Model,Br=a.Gemma2PreTrainedModel,Lr=a.GemmaForCausalLM,Nr=a.GemmaModel,Dr=a.GemmaPreTrainedModel,Rr=a.GemmaTokenizer,Vr=a.GraniteForCausalLM,jr=a.GraniteModel,qr=a.GranitePreTrainedModel,Gr=a.Grok1Tokenizer,Ur=a.GroupViTModel,Wr=a.GroupViTPreTrainedModel,Hr=a.HerbertTokenizer,Kr=a.HieraForImageClassification,Xr=a.HieraModel,Qr=a.HieraPreTrainedModel,Yr=a.HubertForCTC,Zr=a.HubertForSequenceClassification,Jr=a.HubertModel,ei=a.HubertPreTrainedModel,ti=a.ImageClassificationPipeline,ni=a.ImageFeatureExtractionPipeline,ri=a.ImageFeatureExtractor,ii=a.ImageMattingOutput,ai=a.ImageSegmentationPipeline,si=a.ImageToImagePipeline,oi=a.ImageToTextPipeline,li=a.InterruptableStoppingCriteria,ui=a.JAISLMHeadModel,di=a.JAISModel,ci=a.JAISPreTrainedModel,pi=a.LlamaForCausalLM,hi=a.LlamaModel,mi=a.LlamaPreTrainedModel,fi=a.LlamaTokenizer,gi=a.LlavaForConditionalGeneration,_i=a.LlavaPreTrainedModel,wi=a.LongT5ForConditionalGeneration,bi=a.LongT5Model,yi=a.LongT5PreTrainedModel,xi=a.M2M100ForConditionalGeneration,vi=a.M2M100Model,Mi=a.M2M100PreTrainedModel,Ti=a.M2M100Tokenizer,ki=a.MBart50Tokenizer,$i=a.MBartForCausalLM,Si=a.MBartForConditionalGeneration,Ci=a.MBartForSequenceClassification,Ei=a.MBartModel,Pi=a.MBartPreTrainedModel,Fi=a.MBartTokenizer,Ai=a.MPNetForMaskedLM,Ii=a.MPNetForQuestionAnswering,zi=a.MPNetForSequenceClassification,Oi=a.MPNetForTokenClassification,Bi=a.MPNetModel,Li=a.MPNetPreTrainedModel,Ni=a.MPNetTokenizer,Di=a.MT5ForConditionalGeneration,Ri=a.MT5Model,Vi=a.MT5PreTrainedModel,ji=a.MarianMTModel,qi=a.MarianModel,Gi=a.MarianPreTrainedModel,Ui=a.MarianTokenizer,Wi=a.MaskFormerFeatureExtractor,Hi=a.MaskFormerForInstanceSegmentation,Ki=a.MaskFormerModel,Xi=a.MaskFormerPreTrainedModel,Qi=a.MaskedLMOutput,Yi=a.MaxLengthCriteria,Zi=a.MistralForCausalLM,Ji=a.MistralModel,ea=a.MistralPreTrainedModel,ta=a.MobileBertForMaskedLM,na=a.MobileBertForQuestionAnswering,ra=a.MobileBertForSequenceClassification,ia=a.MobileBertModel,aa=a.MobileBertPreTrainedModel,sa=a.MobileBertTokenizer,oa=a.MobileNetV1FeatureExtractor,la=a.MobileNetV1ForImageClassification,ua=a.MobileNetV1Model,da=a.MobileNetV1PreTrainedModel,ca=a.MobileNetV2FeatureExtractor,pa=a.MobileNetV2ForImageClassification,ha=a.MobileNetV2Model,ma=a.MobileNetV2PreTrainedModel,fa=a.MobileNetV3FeatureExtractor,ga=a.MobileNetV3ForImageClassification,_a=a.MobileNetV3Model,wa=a.MobileNetV3PreTrainedModel,ba=a.MobileNetV4FeatureExtractor,ya=a.MobileNetV4ForImageClassification,xa=a.MobileNetV4Model,va=a.MobileNetV4PreTrainedModel,Ma=a.MobileViTFeatureExtractor,Ta=a.MobileViTForImageClassification,ka=a.MobileViTImageProcessor,$a=a.MobileViTModel,Sa=a.MobileViTPreTrainedModel,Ca=a.MobileViTV2ForImageClassification,Ea=a.MobileViTV2Model,Pa=a.MobileViTV2PreTrainedModel,Fa=a.ModelOutput,Aa=a.Moondream1ForConditionalGeneration,Ia=a.MptForCausalLM,za=a.MptModel,Oa=a.MptPreTrainedModel,Ba=a.MusicgenForCausalLM,La=a.MusicgenForConditionalGeneration,Na=a.MusicgenModel,Da=a.MusicgenPreTrainedModel,Ra=a.NllbTokenizer,Va=a.NomicBertModel,ja=a.NomicBertPreTrainedModel,qa=a.NougatImageProcessor,Ga=a.NougatTokenizer,Ua=a.OPTForCausalLM,Wa=a.OPTModel,Ha=a.OPTPreTrainedModel,Ka=a.ObjectDetectionPipeline,Xa=a.OpenELMForCausalLM,Qa=a.OpenELMModel,Ya=a.OpenELMPreTrainedModel,Za=a.OwlViTFeatureExtractor,Ja=a.OwlViTForObjectDetection,es=a.OwlViTModel,ts=a.OwlViTPreTrainedModel,ns=a.OwlViTProcessor,rs=a.Owlv2ForObjectDetection,is=a.Owlv2ImageProcessor,as=a.Owlv2Model,ss=a.Owlv2PreTrainedModel,os=a.Phi3ForCausalLM,ls=a.Phi3Model,us=a.Phi3PreTrainedModel,ds=a.PhiForCausalLM,cs=a.PhiModel,ps=a.PhiPreTrainedModel,hs=a.Pipeline,ms=a.PreTrainedModel,fs=a.PreTrainedTokenizer,gs=a.PretrainedConfig,_s=a.PretrainedMixin,ws=a.Processor,bs=a.PvtForImageClassification,ys=a.PvtImageProcessor,xs=a.PvtModel,vs=a.PvtPreTrainedModel,Ms=a.PyAnnoteFeatureExtractor,Ts=a.PyAnnoteForAudioFrameClassification,ks=a.PyAnnoteModel,$s=a.PyAnnotePreTrainedModel,Ss=a.PyAnnoteProcessor,Cs=a.QuestionAnsweringModelOutput,Es=a.QuestionAnsweringPipeline,Ps=a.Qwen2ForCausalLM,Fs=a.Qwen2Model,As=a.Qwen2PreTrainedModel,Is=a.Qwen2Tokenizer,zs=a.RTDetrForObjectDetection,Os=a.RTDetrImageProcessor,Bs=a.RTDetrModel,Ls=a.RTDetrObjectDetectionOutput,Ns=a.RTDetrPreTrainedModel,Ds=a.RawImage,Rs=a.ResNetForImageClassification,Vs=a.ResNetModel,js=a.ResNetPreTrainedModel,qs=a.RoFormerForMaskedLM,Gs=a.RoFormerForQuestionAnswering,Us=a.RoFormerForSequenceClassification,Ws=a.RoFormerForTokenClassification,Hs=a.RoFormerModel,Ks=a.RoFormerPreTrainedModel,Xs=a.RoFormerTokenizer,Qs=a.RobertaForMaskedLM,Ys=a.RobertaForQuestionAnswering,Zs=a.RobertaForSequenceClassification,Js=a.RobertaForTokenClassification,eo=a.RobertaModel,to=a.RobertaPreTrainedModel,no=a.RobertaTokenizer,ro=a.SamImageProcessor,io=a.SamImageSegmentationOutput,ao=a.SamModel,so=a.SamPreTrainedModel,oo=a.SamProcessor,lo=a.SapiensFeatureExtractor,uo=a.SapiensForDepthEstimation,co=a.SapiensForNormalEstimation,po=a.SapiensForSemanticSegmentation,ho=a.SapiensPreTrainedModel,mo=a.SeamlessM4TFeatureExtractor,fo=a.SegformerFeatureExtractor,go=a.SegformerForImageClassification,_o=a.SegformerForSemanticSegmentation,wo=a.SegformerModel,bo=a.SegformerPreTrainedModel,yo=a.Seq2SeqLMOutput,xo=a.SequenceClassifierOutput,vo=a.SiglipImageProcessor,Mo=a.SiglipModel,To=a.SiglipPreTrainedModel,ko=a.SiglipTextModel,$o=a.SiglipTokenizer,So=a.SiglipVisionModel,Co=a.SpeechT5FeatureExtractor,Eo=a.SpeechT5ForSpeechToText,Po=a.SpeechT5ForTextToSpeech,Fo=a.SpeechT5HifiGan,Ao=a.SpeechT5Model,Io=a.SpeechT5PreTrainedModel,zo=a.SpeechT5Processor,Oo=a.SpeechT5Tokenizer,Bo=a.SqueezeBertForMaskedLM,Lo=a.SqueezeBertForQuestionAnswering,No=a.SqueezeBertForSequenceClassification,Do=a.SqueezeBertModel,Ro=a.SqueezeBertPreTrainedModel,Vo=a.SqueezeBertTokenizer,jo=a.StableLmForCausalLM,qo=a.StableLmModel,Go=a.StableLmPreTrainedModel,Uo=a.Starcoder2ForCausalLM,Wo=a.Starcoder2Model,Ho=a.Starcoder2PreTrainedModel,Ko=a.StoppingCriteria,Xo=a.StoppingCriteriaList,Qo=a.SummarizationPipeline,Yo=a.Swin2SRForImageSuperResolution,Zo=a.Swin2SRImageProcessor,Jo=a.Swin2SRModel,el=a.Swin2SRPreTrainedModel,tl=a.SwinForImageClassification,nl=a.SwinModel,rl=a.SwinPreTrainedModel,il=a.T5ForConditionalGeneration,al=a.T5Model,sl=a.T5PreTrainedModel,ol=a.T5Tokenizer,ll=a.TableTransformerForObjectDetection,ul=a.TableTransformerModel,dl=a.TableTransformerObjectDetectionOutput,cl=a.TableTransformerPreTrainedModel,pl=a.Tensor,hl=a.Text2TextGenerationPipeline,ml=a.TextClassificationPipeline,fl=a.TextGenerationPipeline,gl=a.TextStreamer,_l=a.TextToAudioPipeline,wl=a.TokenClassificationPipeline,bl=a.TokenClassifierOutput,yl=a.TokenizerModel,xl=a.TrOCRForCausalLM,vl=a.TrOCRPreTrainedModel,Ml=a.TranslationPipeline,Tl=a.UniSpeechForCTC,kl=a.UniSpeechForSequenceClassification,$l=a.UniSpeechModel,Sl=a.UniSpeechPreTrainedModel,Cl=a.UniSpeechSatForAudioFrameClassification,El=a.UniSpeechSatForCTC,Pl=a.UniSpeechSatForSequenceClassification,Fl=a.UniSpeechSatModel,Al=a.UniSpeechSatPreTrainedModel,Il=a.ViTFeatureExtractor,zl=a.ViTForImageClassification,Ol=a.ViTImageProcessor,Bl=a.ViTMAEModel,Ll=a.ViTMAEPreTrainedModel,Nl=a.ViTMSNForImageClassification,Dl=a.ViTMSNModel,Rl=a.ViTMSNPreTrainedModel,Vl=a.ViTModel,jl=a.ViTPreTrainedModel,ql=a.VisionEncoderDecoderModel,Gl=a.VitMatteForImageMatting,Ul=a.VitMatteImageProcessor,Wl=a.VitMattePreTrainedModel,Hl=a.VitsModel,Kl=a.VitsModelOutput,Xl=a.VitsPreTrainedModel,Ql=a.VitsTokenizer,Yl=a.Wav2Vec2BertForCTC,Zl=a.Wav2Vec2BertForSequenceClassification,Jl=a.Wav2Vec2BertModel,eu=a.Wav2Vec2BertPreTrainedModel,tu=a.Wav2Vec2CTCTokenizer,nu=a.Wav2Vec2FeatureExtractor,ru=a.Wav2Vec2ForAudioFrameClassification,iu=a.Wav2Vec2ForCTC,au=a.Wav2Vec2ForSequenceClassification,su=a.Wav2Vec2Model,ou=a.Wav2Vec2PreTrainedModel,lu=a.Wav2Vec2ProcessorWithLM,uu=a.WavLMForAudioFrameClassification,du=a.WavLMForCTC,cu=a.WavLMForSequenceClassification,pu=a.WavLMForXVector,hu=a.WavLMModel,mu=a.WavLMPreTrainedModel,fu=a.WeSpeakerFeatureExtractor,gu=a.WeSpeakerResNetModel,_u=a.WeSpeakerResNetPreTrainedModel,wu=a.WhisperFeatureExtractor,bu=a.WhisperForConditionalGeneration,yu=a.WhisperModel,xu=a.WhisperPreTrainedModel,vu=a.WhisperProcessor,Mu=a.WhisperTextStreamer,Tu=a.WhisperTokenizer,ku=a.XLMForQuestionAnswering,$u=a.XLMForSequenceClassification,Su=a.XLMForTokenClassification,Cu=a.XLMModel,Eu=a.XLMPreTrainedModel,Pu=a.XLMRobertaForMaskedLM,Fu=a.XLMRobertaForQuestionAnswering,Au=a.XLMRobertaForSequenceClassification,Iu=a.XLMRobertaForTokenClassification,zu=a.XLMRobertaModel,Ou=a.XLMRobertaPreTrainedModel,Bu=a.XLMRobertaTokenizer,Lu=a.XLMTokenizer,Nu=a.XLMWithLMHeadModel,Du=a.XVectorOutput,Ru=a.YolosFeatureExtractor,Vu=a.YolosForObjectDetection,ju=a.YolosModel,qu=a.YolosObjectDetectionOutput,Gu=a.YolosPreTrainedModel,Uu=a.ZeroShotAudioClassificationPipeline,Wu=a.ZeroShotClassificationPipeline,Hu=a.ZeroShotImageClassificationPipeline,Ku=a.ZeroShotObjectDetectionPipeline,Xu=a.bankers_round,Qu=a.cat,Yu=a.cos_sim,Zu=a.dot,Ju=a.dynamic_time_warping,ed=a.env,td=a.full,nd=a.full_like,rd=a.getKeyValueShapes,id=a.getPerf,ad=a.hamming,sd=a.hanning,od=a.interpolate,ld=a.interpolate_4d,ud=a.interpolate_data,dd=a.is_chinese_char,cd=a.layer_norm,pd=a.log_softmax,hd=a.magnitude,md=a.matmul,fd=a.max,gd=a.mean,_d=a.mean_pooling,wd=a.medianFilter,bd=a.mel_filter_bank,yd=a.min,xd=a.ones,vd=a.ones_like,Md=a.permute,Td=a.permute_data,kd=a.pipeline,$d=a.quantize_embeddings,Sd=a.read_audio,Cd=a.rfft,Ed=a.round,Pd=a.softmax,Fd=a.spectrogram,Ad=a.stack,Id=a.std_mean,zd=a.topk,Od=a.window_function,Bd=a.zeros,Ld=a.zeros_like;export{w as ASTFeatureExtractor,b as ASTForAudioClassification,y as ASTModel,x as ASTPreTrainedModel,v as AlbertForMaskedLM,M as AlbertForQuestionAnswering,T as AlbertForSequenceClassification,k as AlbertModel,$ as AlbertPreTrainedModel,S as AlbertTokenizer,C as AudioClassificationPipeline,E as AutoConfig,P as AutoModel,F as AutoModelForAudioClassification,A as AutoModelForAudioFrameClassification,I as AutoModelForCTC,z as AutoModelForCausalLM,O as AutoModelForDepthEstimation,B as AutoModelForDocumentQuestionAnswering,L as AutoModelForImageClassification,N as AutoModelForImageFeatureExtraction,D as AutoModelForImageMatting,R as AutoModelForImageSegmentation,V as AutoModelForImageToImage,j as AutoModelForMaskGeneration,q as AutoModelForMaskedLM,G as AutoModelForNormalEstimation,U as AutoModelForObjectDetection,W as AutoModelForQuestionAnswering,H as AutoModelForSemanticSegmentation,K as AutoModelForSeq2SeqLM,X as AutoModelForSequenceClassification,Q as AutoModelForSpeechSeq2Seq,Y as AutoModelForTextToSpectrogram,Z as AutoModelForTextToWaveform,J as AutoModelForTokenClassification,ee as AutoModelForUniversalSegmentation,te as AutoModelForVision2Seq,ne as AutoModelForXVector,re as AutoModelForZeroShotObjectDetection,ie as AutoProcessor,ae as AutoTokenizer,se as AutomaticSpeechRecognitionPipeline,oe as BartForConditionalGeneration,le as BartForSequenceClassification,ue as BartModel,de as BartPretrainedModel,ce as BartTokenizer,pe as BaseModelOutput,he as BaseStreamer,me as BeitFeatureExtractor,fe as BeitForImageClassification,ge as BeitModel,_e as BeitPreTrainedModel,we as BertForMaskedLM,be as BertForQuestionAnswering,ye as BertForSequenceClassification,xe as BertForTokenClassification,ve as BertModel,Me as BertPreTrainedModel,Te as BertTokenizer,ke as BitImageProcessor,$e as BlenderbotForConditionalGeneration,Se as BlenderbotModel,Ce as BlenderbotPreTrainedModel,Ee as BlenderbotSmallForConditionalGeneration,Pe as BlenderbotSmallModel,Fe as BlenderbotSmallPreTrainedModel,Ae as BlenderbotSmallTokenizer,Ie as BlenderbotTokenizer,ze as BloomForCausalLM,Oe as BloomModel,Be as BloomPreTrainedModel,Le as BloomTokenizer,Ne as CLIPFeatureExtractor,De as CLIPImageProcessor,Re as CLIPModel,Ve as CLIPPreTrainedModel,je as CLIPSegForImageSegmentation,qe as CLIPSegModel,Ge as CLIPSegPreTrainedModel,Ue as CLIPTextModel,We as CLIPTextModelWithProjection,He as CLIPTokenizer,Ke as CLIPVisionModel,Xe as CLIPVisionModelWithProjection,Qe as CamembertForMaskedLM,Ye as CamembertForQuestionAnswering,Ze as CamembertForSequenceClassification,Je as CamembertForTokenClassification,et as CamembertModel,tt as CamembertPreTrainedModel,nt as CamembertTokenizer,rt as CausalLMOutput,it as CausalLMOutputWithPast,at as ChineseCLIPFeatureExtractor,st as ChineseCLIPModel,ot as ChineseCLIPPreTrainedModel,lt as ClapAudioModelWithProjection,ut as ClapFeatureExtractor,dt as ClapModel,ct as ClapPreTrainedModel,pt as ClapTextModelWithProjection,ht as CodeGenForCausalLM,mt as CodeGenModel,ft as CodeGenPreTrainedModel,gt as CodeGenTokenizer,_t as CodeLlamaTokenizer,wt as CohereForCausalLM,bt as CohereModel,yt as CoherePreTrainedModel,xt as CohereTokenizer,vt as ConvBertForMaskedLM,Mt as ConvBertForQuestionAnswering,Tt as ConvBertForSequenceClassification,kt as ConvBertForTokenClassification,$t as ConvBertModel,St as ConvBertPreTrainedModel,Ct as ConvBertTokenizer,Et as ConvNextFeatureExtractor,Pt as ConvNextForImageClassification,Ft as ConvNextImageProcessor,At as ConvNextModel,It as ConvNextPreTrainedModel,zt as ConvNextV2ForImageClassification,Ot as ConvNextV2Model,Bt as ConvNextV2PreTrainedModel,Lt as DPTFeatureExtractor,Nt as DPTForDepthEstimation,Dt as DPTImageProcessor,Rt as DPTModel,Vt as DPTPreTrainedModel,jt as DebertaForMaskedLM,qt as DebertaForQuestionAnswering,Gt as DebertaForSequenceClassification,Ut as DebertaForTokenClassification,Wt as DebertaModel,Ht as DebertaPreTrainedModel,Kt as DebertaTokenizer,Xt as DebertaV2ForMaskedLM,Qt as DebertaV2ForQuestionAnswering,Yt as DebertaV2ForSequenceClassification,Zt as DebertaV2ForTokenClassification,Jt as DebertaV2Model,en as DebertaV2PreTrainedModel,tn as DebertaV2Tokenizer,nn as DecisionTransformerModel,rn as DecisionTransformerPreTrainedModel,an as DeiTFeatureExtractor,sn as DeiTForImageClassification,on as DeiTModel,ln as DeiTPreTrainedModel,un as DepthAnythingForDepthEstimation,dn as DepthAnythingPreTrainedModel,cn as DepthEstimationPipeline,pn as DepthProForDepthEstimation,hn as DepthProPreTrainedModel,mn as DetrFeatureExtractor,fn as DetrForObjectDetection,gn as DetrForSegmentation,_n as DetrModel,wn as DetrObjectDetectionOutput,bn as DetrPreTrainedModel,yn as DetrSegmentationOutput,xn as Dinov2ForImageClassification,vn as Dinov2Model,Mn as Dinov2PreTrainedModel,Tn as DistilBertForMaskedLM,kn as DistilBertForQuestionAnswering,$n as DistilBertForSequenceClassification,Sn as DistilBertForTokenClassification,Cn as DistilBertModel,En as DistilBertPreTrainedModel,Pn as DistilBertTokenizer,Fn as DocumentQuestionAnsweringPipeline,An as DonutFeatureExtractor,In as DonutSwinModel,zn as DonutSwinPreTrainedModel,On as EfficientNetForImageClassification,Bn as EfficientNetImageProcessor,Ln as EfficientNetModel,Nn as EfficientNetPreTrainedModel,Dn as ElectraForMaskedLM,Rn as ElectraForQuestionAnswering,Vn as ElectraForSequenceClassification,jn as ElectraForTokenClassification,qn as ElectraModel,Gn as ElectraPreTrainedModel,Un as ElectraTokenizer,Wn as EosTokenCriteria,Hn as EsmForMaskedLM,Kn as EsmForSequenceClassification,Xn as EsmForTokenClassification,Qn as EsmModel,Yn as EsmPreTrainedModel,Zn as EsmTokenizer,Jn as FFT,er as FalconForCausalLM,tr as FalconModel,nr as FalconPreTrainedModel,rr as FalconTokenizer,ir as FastViTForImageClassification,ar as FastViTModel,sr as FastViTPreTrainedModel,or as FeatureExtractionPipeline,lr as FeatureExtractor,ur as FillMaskPipeline,dr as Florence2ForConditionalGeneration,cr as Florence2PreTrainedModel,pr as Florence2Processor,hr as GLPNFeatureExtractor,mr as GLPNForDepthEstimation,fr as GLPNModel,gr as GLPNPreTrainedModel,_r as GPT2LMHeadModel,wr as GPT2Model,br as GPT2PreTrainedModel,yr as GPT2Tokenizer,xr as GPTBigCodeForCausalLM,vr as GPTBigCodeModel,Mr as GPTBigCodePreTrainedModel,Tr as GPTJForCausalLM,kr as GPTJModel,$r as GPTJPreTrainedModel,Sr as GPTNeoForCausalLM,Cr as GPTNeoModel,Er as GPTNeoPreTrainedModel,Pr as GPTNeoXForCausalLM,Fr as GPTNeoXModel,Ar as GPTNeoXPreTrainedModel,Ir as GPTNeoXTokenizer,zr as Gemma2ForCausalLM,Or as Gemma2Model,Br as Gemma2PreTrainedModel,Lr as GemmaForCausalLM,Nr as GemmaModel,Dr as GemmaPreTrainedModel,Rr as GemmaTokenizer,Vr as GraniteForCausalLM,jr as GraniteModel,qr as GranitePreTrainedModel,Gr as Grok1Tokenizer,Ur as GroupViTModel,Wr as GroupViTPreTrainedModel,Hr as HerbertTokenizer,Kr as HieraForImageClassification,Xr as HieraModel,Qr as HieraPreTrainedModel,Yr as HubertForCTC,Zr as HubertForSequenceClassification,Jr as HubertModel,ei as HubertPreTrainedModel,ti as ImageClassificationPipeline,ni as ImageFeatureExtractionPipeline,ri as ImageFeatureExtractor,ii as ImageMattingOutput,ai as ImageSegmentationPipeline,si as ImageToImagePipeline,oi as ImageToTextPipeline,li as InterruptableStoppingCriteria,ui as JAISLMHeadModel,di as JAISModel,ci as JAISPreTrainedModel,pi as LlamaForCausalLM,hi as LlamaModel,mi as LlamaPreTrainedModel,fi as LlamaTokenizer,gi as LlavaForConditionalGeneration,_i as LlavaPreTrainedModel,wi as LongT5ForConditionalGeneration,bi as LongT5Model,yi as LongT5PreTrainedModel,xi as M2M100ForConditionalGeneration,vi as M2M100Model,Mi as M2M100PreTrainedModel,Ti as M2M100Tokenizer,ki as MBart50Tokenizer,$i as MBartForCausalLM,Si as MBartForConditionalGeneration,Ci as MBartForSequenceClassification,Ei as MBartModel,Pi as MBartPreTrainedModel,Fi as MBartTokenizer,Ai as MPNetForMaskedLM,Ii as MPNetForQuestionAnswering,zi as MPNetForSequenceClassification,Oi as MPNetForTokenClassification,Bi as MPNetModel,Li as MPNetPreTrainedModel,Ni as MPNetTokenizer,Di as MT5ForConditionalGeneration,Ri as MT5Model,Vi as MT5PreTrainedModel,ji as MarianMTModel,qi as MarianModel,Gi as MarianPreTrainedModel,Ui as MarianTokenizer,Wi as MaskFormerFeatureExtractor,Hi as MaskFormerForInstanceSegmentation,Ki as MaskFormerModel,Xi as MaskFormerPreTrainedModel,Qi as MaskedLMOutput,Yi as MaxLengthCriteria,Zi as MistralForCausalLM,Ji as MistralModel,ea as MistralPreTrainedModel,ta as MobileBertForMaskedLM,na as MobileBertForQuestionAnswering,ra as MobileBertForSequenceClassification,ia as MobileBertModel,aa as MobileBertPreTrainedModel,sa as MobileBertTokenizer,oa as MobileNetV1FeatureExtractor,la as MobileNetV1ForImageClassification,ua as MobileNetV1Model,da as MobileNetV1PreTrainedModel,ca as MobileNetV2FeatureExtractor,pa as MobileNetV2ForImageClassification,ha as MobileNetV2Model,ma as MobileNetV2PreTrainedModel,fa as MobileNetV3FeatureExtractor,ga as MobileNetV3ForImageClassification,_a as MobileNetV3Model,wa as MobileNetV3PreTrainedModel,ba as MobileNetV4FeatureExtractor,ya as MobileNetV4ForImageClassification,xa as MobileNetV4Model,va as MobileNetV4PreTrainedModel,Ma as MobileViTFeatureExtractor,Ta as MobileViTForImageClassification,ka as MobileViTImageProcessor,$a as MobileViTModel,Sa as MobileViTPreTrainedModel,Ca as MobileViTV2ForImageClassification,Ea as MobileViTV2Model,Pa as MobileViTV2PreTrainedModel,Fa as ModelOutput,Aa as Moondream1ForConditionalGeneration,Ia as MptForCausalLM,za as MptModel,Oa as MptPreTrainedModel,Ba as MusicgenForCausalLM,La as MusicgenForConditionalGeneration,Na as MusicgenModel,Da as MusicgenPreTrainedModel,Ra as NllbTokenizer,Va as NomicBertModel,ja as NomicBertPreTrainedModel,qa as NougatImageProcessor,Ga as NougatTokenizer,Ua as OPTForCausalLM,Wa as OPTModel,Ha as OPTPreTrainedModel,Ka as ObjectDetectionPipeline,Xa as OpenELMForCausalLM,Qa as OpenELMModel,Ya as OpenELMPreTrainedModel,Za as OwlViTFeatureExtractor,Ja as OwlViTForObjectDetection,es as OwlViTModel,ts as OwlViTPreTrainedModel,ns as OwlViTProcessor,rs as Owlv2ForObjectDetection,is as Owlv2ImageProcessor,as as Owlv2Model,ss as Owlv2PreTrainedModel,os as Phi3ForCausalLM,ls as Phi3Model,us as Phi3PreTrainedModel,ds as PhiForCausalLM,cs as PhiModel,ps as PhiPreTrainedModel,hs as Pipeline,ms as PreTrainedModel,fs as PreTrainedTokenizer,gs as PretrainedConfig,_s as PretrainedMixin,ws as Processor,bs as PvtForImageClassification,ys as PvtImageProcessor,xs as PvtModel,vs as PvtPreTrainedModel,Ms as PyAnnoteFeatureExtractor,Ts as PyAnnoteForAudioFrameClassification,ks as PyAnnoteModel,$s as PyAnnotePreTrainedModel,Ss as PyAnnoteProcessor,Cs as QuestionAnsweringModelOutput,Es as QuestionAnsweringPipeline,Ps as Qwen2ForCausalLM,Fs as Qwen2Model,As as Qwen2PreTrainedModel,Is as Qwen2Tokenizer,zs as RTDetrForObjectDetection,Os as RTDetrImageProcessor,Bs as RTDetrModel,Ls as RTDetrObjectDetectionOutput,Ns as RTDetrPreTrainedModel,Ds as RawImage,Rs as ResNetForImageClassification,Vs as ResNetModel,js as ResNetPreTrainedModel,qs as RoFormerForMaskedLM,Gs as RoFormerForQuestionAnswering,Us as RoFormerForSequenceClassification,Ws as RoFormerForTokenClassification,Hs as RoFormerModel,Ks as RoFormerPreTrainedModel,Xs as RoFormerTokenizer,Qs as RobertaForMaskedLM,Ys as RobertaForQuestionAnswering,Zs as RobertaForSequenceClassification,Js as RobertaForTokenClassification,eo as RobertaModel,to as RobertaPreTrainedModel,no as RobertaTokenizer,ro as SamImageProcessor,io as SamImageSegmentationOutput,ao as SamModel,so as SamPreTrainedModel,oo as SamProcessor,lo as SapiensFeatureExtractor,uo as SapiensForDepthEstimation,co as SapiensForNormalEstimation,po as SapiensForSemanticSegmentation,ho as SapiensPreTrainedModel,mo as SeamlessM4TFeatureExtractor,fo as SegformerFeatureExtractor,go as SegformerForImageClassification,_o as SegformerForSemanticSegmentation,wo as SegformerModel,bo as SegformerPreTrainedModel,yo as Seq2SeqLMOutput,xo as SequenceClassifierOutput,vo as SiglipImageProcessor,Mo as SiglipModel,To as SiglipPreTrainedModel,ko as SiglipTextModel,$o as SiglipTokenizer,So as SiglipVisionModel,Co as SpeechT5FeatureExtractor,Eo as SpeechT5ForSpeechToText,Po as SpeechT5ForTextToSpeech,Fo as SpeechT5HifiGan,Ao as SpeechT5Model,Io as SpeechT5PreTrainedModel,zo as SpeechT5Processor,Oo as SpeechT5Tokenizer,Bo as SqueezeBertForMaskedLM,Lo as SqueezeBertForQuestionAnswering,No as SqueezeBertForSequenceClassification,Do as SqueezeBertModel,Ro as SqueezeBertPreTrainedModel,Vo as SqueezeBertTokenizer,jo as StableLmForCausalLM,qo as StableLmModel,Go as StableLmPreTrainedModel,Uo as Starcoder2ForCausalLM,Wo as Starcoder2Model,Ho as Starcoder2PreTrainedModel,Ko as StoppingCriteria,Xo as StoppingCriteriaList,Qo as SummarizationPipeline,Yo as Swin2SRForImageSuperResolution,Zo as Swin2SRImageProcessor,Jo as Swin2SRModel,el as Swin2SRPreTrainedModel,tl as SwinForImageClassification,nl as SwinModel,rl as SwinPreTrainedModel,il as T5ForConditionalGeneration,al as T5Model,sl as T5PreTrainedModel,ol as T5Tokenizer,ll as TableTransformerForObjectDetection,ul as TableTransformerModel,dl as TableTransformerObjectDetectionOutput,cl as TableTransformerPreTrainedModel,pl as Tensor,hl as Text2TextGenerationPipeline,ml as TextClassificationPipeline,fl as TextGenerationPipeline,gl as TextStreamer,_l as TextToAudioPipeline,wl as TokenClassificationPipeline,bl as TokenClassifierOutput,yl as TokenizerModel,xl as TrOCRForCausalLM,vl as TrOCRPreTrainedModel,Ml as TranslationPipeline,Tl as UniSpeechForCTC,kl as UniSpeechForSequenceClassification,$l as UniSpeechModel,Sl as UniSpeechPreTrainedModel,Cl as UniSpeechSatForAudioFrameClassification,El as UniSpeechSatForCTC,Pl as UniSpeechSatForSequenceClassification,Fl as UniSpeechSatModel,Al as UniSpeechSatPreTrainedModel,Il as ViTFeatureExtractor,zl as ViTForImageClassification,Ol as ViTImageProcessor,Bl as ViTMAEModel,Ll as ViTMAEPreTrainedModel,Nl as ViTMSNForImageClassification,Dl as ViTMSNModel,Rl as ViTMSNPreTrainedModel,Vl as ViTModel,jl as ViTPreTrainedModel,ql as VisionEncoderDecoderModel,Gl as VitMatteForImageMatting,Ul as VitMatteImageProcessor,Wl as VitMattePreTrainedModel,Hl as VitsModel,Kl as VitsModelOutput,Xl as VitsPreTrainedModel,Ql as VitsTokenizer,Yl as Wav2Vec2BertForCTC,Zl as Wav2Vec2BertForSequenceClassification,Jl as Wav2Vec2BertModel,eu as Wav2Vec2BertPreTrainedModel,tu as Wav2Vec2CTCTokenizer,nu as Wav2Vec2FeatureExtractor,ru as Wav2Vec2ForAudioFrameClassification,iu as Wav2Vec2ForCTC,au as Wav2Vec2ForSequenceClassification,su as Wav2Vec2Model,ou as Wav2Vec2PreTrainedModel,lu as Wav2Vec2ProcessorWithLM,uu as WavLMForAudioFrameClassification,du as WavLMForCTC,cu as WavLMForSequenceClassification,pu as WavLMForXVector,hu as WavLMModel,mu as WavLMPreTrainedModel,fu as WeSpeakerFeatureExtractor,gu as WeSpeakerResNetModel,_u as WeSpeakerResNetPreTrainedModel,wu as WhisperFeatureExtractor,bu as WhisperForConditionalGeneration,yu as WhisperModel,xu as WhisperPreTrainedModel,vu as WhisperProcessor,Mu as WhisperTextStreamer,Tu as WhisperTokenizer,ku as XLMForQuestionAnswering,$u as XLMForSequenceClassification,Su as XLMForTokenClassification,Cu as XLMModel,Eu as XLMPreTrainedModel,Pu as XLMRobertaForMaskedLM,Fu as XLMRobertaForQuestionAnswering,Au as XLMRobertaForSequenceClassification,Iu as XLMRobertaForTokenClassification,zu as XLMRobertaModel,Ou as XLMRobertaPreTrainedModel,Bu as XLMRobertaTokenizer,Lu as XLMTokenizer,Nu as XLMWithLMHeadModel,Du as XVectorOutput,Ru as YolosFeatureExtractor,Vu as YolosForObjectDetection,ju as YolosModel,qu as YolosObjectDetectionOutput,Gu as YolosPreTrainedModel,Uu as ZeroShotAudioClassificationPipeline,Wu as ZeroShotClassificationPipeline,Hu as ZeroShotImageClassificationPipeline,Ku as ZeroShotObjectDetectionPipeline,Xu as bankers_round,Qu as cat,Yu as cos_sim,Zu as dot,Ju as dynamic_time_warping,ed as env,td as full,nd as full_like,rd as getKeyValueShapes,id as getPerf,ad as hamming,sd as hanning,od as interpolate,ld as interpolate_4d,ud as interpolate_data,dd as is_chinese_char,cd as layer_norm,pd as log_softmax,hd as magnitude,md as matmul,fd as max,gd as mean,_d as mean_pooling,wd as medianFilter,bd as mel_filter_bank,yd as min,xd as ones,vd as ones_like,Md as permute,Td as permute_data,kd as pipeline,$d as quantize_embeddings,Sd as read_audio,Cd as rfft,Ed as round,Pd as softmax,Fd as spectrogram,Ad as stack,Id as std_mean,zd as topk,Od as window_function,Bd as zeros,Ld as zeros_like}; //# sourceMappingURL=transformers.min.js.map \ No newline at end of file diff --git a/assets/dist_transformers/1.21.0-dev.20241122/transformers.min.js.map b/assets/dist_transformers/1.21.0-dev.20241122/transformers.min.js.map new file mode 100644 index 0000000..25361a9 --- /dev/null +++ b/assets/dist_transformers/1.21.0-dev.20241122/transformers.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transformers.min.js","mappings":"IACIA,EADAC,E;;;;;;;;;;;;;;;;;;;;;;;;;;;oKCCJ,IAAIC,EAAcC,OAAOC,OAAO,CAC9BC,KAAM,OAENC,eAAgB,iBAEhBC,eAAgB,iBAEhBC,cAAe,gBAEfC,WAAY,aAEZC,OAAQ,SAERC,UAAW,YAEXC,WAAY,aAEZC,cAAe,gBAEfC,eAAgB,iBAEhBC,eAAgB,iBAEhBC,gBAAiB,kBAEjBC,kBAAmB,oBAEnBC,mBAAoB,qBAEpBC,iBAAkB,mBAElBC,kBAAmB,oBAEnBC,MAAO,QAEPC,IAAK,MAELC,MAAO,QAEPC,KAAM,OAENC,aAAc,eAEdC,uBAAwB,yBAExBC,6BAA8B,+BAE9BC,yBAA0B,2BAE1BC,cAAe,gBAGfC,IAAK,MACLC,GAAI,KACJC,IAAK,MACLC,GAAI,KACJC,GAAI,KACJC,MAAO,QACPC,KAAM,OACNC,MAAO,QACPC,OAAQ,SACRC,OAAQ,SACRC,IAAK,MACLC,GAAI,KACJC,IAAK,gBACLC,MAAO,QACPC,SAAU,aAERC,EAAW1C,OAAOC,OAAO,CAC3B0C,IAAK5C,EAAY4B,IACjBiB,IAAK7C,EAAY8B,IACjBgB,GAAI9C,EAAY+B,GAChB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AAR17G,MAAkB07G,cAAwB17G,MAG5D07G,EAAW,MAAM,IAAI35I,MAAM,yDAChC25I,EAAYA,EAAUp+I,QAAQ,OAAQ,IAAIA,QAAQ,QAAS,IAAIA,QAAQ,YAAa,KACpF29I,EAAoB/7H,EAAIw8H,C,KCNxBT,EAAoBz3I,EAAI,IAAI6yC,IAAI,iBAAkBrW,K","sources":["webpack://@huggingface/transformers/webpack/runtime/create fake namespace object","webpack://@huggingface/transformers/./node_modules/@huggingface/jinja/dist/index.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/backend-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/env-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/env.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/inference-session.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/tensor.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/trace.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/training-session-impl.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/training-session.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-common/dist/esm/version.js","webpack://@huggingface/transformers/./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs","webpack://@huggingface/transformers/./src/backends/onnx.js","webpack://@huggingface/transformers/./src/configs.js","webpack://@huggingface/transformers/./src/env.js","webpack://@huggingface/transformers/./src/generation/configuration_utils.js","webpack://@huggingface/transformers/./src/generation/logits_process.js","webpack://@huggingface/transformers/./src/generation/logits_sampler.js","webpack://@huggingface/transformers/./src/generation/stopping_criteria.js","webpack://@huggingface/transformers/./src/generation/streamers.js","webpack://@huggingface/transformers/./src/models.js","webpack://@huggingface/transformers/./src/models/whisper/common_whisper.js","webpack://@huggingface/transformers/./src/models/whisper/generation_whisper.js","webpack://@huggingface/transformers/./src/ops/registry.js","webpack://@huggingface/transformers/./src/pipelines.js","webpack://@huggingface/transformers/./src/processors.js","webpack://@huggingface/transformers/./src/tokenizers.js","webpack://@huggingface/transformers/./src/utils/audio.js","webpack://@huggingface/transformers/./src/utils/constants.js","webpack://@huggingface/transformers/./src/utils/core.js","webpack://@huggingface/transformers/./src/utils/data-structures.js","webpack://@huggingface/transformers/./src/utils/devices.js","webpack://@huggingface/transformers/./src/utils/dtypes.js","webpack://@huggingface/transformers/./src/utils/generic.js","webpack://@huggingface/transformers/./src/utils/hub.js","webpack://@huggingface/transformers/./src/utils/image.js","webpack://@huggingface/transformers/./src/utils/maths.js","webpack://@huggingface/transformers/./src/utils/tensor.js","webpack://@huggingface/transformers/webpack/bootstrap","webpack://@huggingface/transformers/webpack/runtime/define property getters","webpack://@huggingface/transformers/webpack/runtime/hasOwnProperty shorthand","webpack://@huggingface/transformers/webpack/runtime/make namespace object","webpack://@huggingface/transformers/webpack/runtime/publicPath","webpack://@huggingface/transformers/webpack/runtime/import chunk loading"],"sourcesContent":["var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","// src/lexer.ts\nvar TOKEN_TYPES = Object.freeze({\n Text: \"Text\",\n // The text between Jinja statements or expressions\n NumericLiteral: \"NumericLiteral\",\n // e.g., 123\n BooleanLiteral: \"BooleanLiteral\",\n // true or false\n StringLiteral: \"StringLiteral\",\n // 'string'\n Identifier: \"Identifier\",\n // Variables, functions, etc.\n Equals: \"Equals\",\n // =\n OpenParen: \"OpenParen\",\n // (\n CloseParen: \"CloseParen\",\n // )\n OpenStatement: \"OpenStatement\",\n // {%\n CloseStatement: \"CloseStatement\",\n // %}\n OpenExpression: \"OpenExpression\",\n // {{\n CloseExpression: \"CloseExpression\",\n // }}\n OpenSquareBracket: \"OpenSquareBracket\",\n // [\n CloseSquareBracket: \"CloseSquareBracket\",\n // ]\n OpenCurlyBracket: \"OpenCurlyBracket\",\n // {\n CloseCurlyBracket: \"CloseCurlyBracket\",\n // }\n Comma: \"Comma\",\n // ,\n Dot: \"Dot\",\n // .\n Colon: \"Colon\",\n // :\n Pipe: \"Pipe\",\n // |\n CallOperator: \"CallOperator\",\n // ()\n AdditiveBinaryOperator: \"AdditiveBinaryOperator\",\n // + -\n MultiplicativeBinaryOperator: \"MultiplicativeBinaryOperator\",\n // * / %\n ComparisonBinaryOperator: \"ComparisonBinaryOperator\",\n // < > <= >= == !=\n UnaryOperator: \"UnaryOperator\",\n // ! - +\n // Keywords\n Set: \"Set\",\n If: \"If\",\n For: \"For\",\n In: \"In\",\n Is: \"Is\",\n NotIn: \"NotIn\",\n Else: \"Else\",\n EndIf: \"EndIf\",\n ElseIf: \"ElseIf\",\n EndFor: \"EndFor\",\n And: \"And\",\n Or: \"Or\",\n Not: \"UnaryOperator\",\n Macro: \"Macro\",\n EndMacro: \"EndMacro\"\n});\nvar KEYWORDS = Object.freeze({\n set: TOKEN_TYPES.Set,\n for: TOKEN_TYPES.For,\n in: TOKEN_TYPES.In,\n is: TOKEN_TYPES.Is,\n if: TOKEN_TYPES.If,\n else: TOKEN_TYPES.Else,\n endif: TOKEN_TYPES.EndIf,\n elif: TOKEN_TYPES.ElseIf,\n endfor: TOKEN_TYPES.EndFor,\n and: TOKEN_TYPES.And,\n or: TOKEN_TYPES.Or,\n not: TOKEN_TYPES.Not,\n \"not in\": TOKEN_TYPES.NotIn,\n macro: TOKEN_TYPES.Macro,\n endmacro: TOKEN_TYPES.EndMacro,\n // Literals\n true: TOKEN_TYPES.BooleanLiteral,\n false: TOKEN_TYPES.BooleanLiteral,\n // NOTE: According to the Jinja docs: The special constants true, false, and none are indeed lowercase.\n // Because that caused confusion in the past, (True used to expand to an undefined variable that was considered false),\n // all three can now also be written in title case (True, False, and None). However, for consistency, (all Jinja identifiers are lowercase)\n // you should use the lowercase versions.\n True: TOKEN_TYPES.BooleanLiteral,\n False: TOKEN_TYPES.BooleanLiteral\n});\nvar Token = class {\n /**\n * Constructs a new Token.\n * @param {string} value The raw value as seen inside the source code.\n * @param {TokenType} type The type of token.\n */\n constructor(value, type) {\n this.value = value;\n this.type = type;\n }\n};\nfunction isWord(char) {\n return /\\w/.test(char);\n}\nfunction isInteger(char) {\n return /[0-9]/.test(char);\n}\nvar ORDERED_MAPPING_TABLE = [\n // Control sequences\n [\"{%\", TOKEN_TYPES.OpenStatement],\n [\"%}\", TOKEN_TYPES.CloseStatement],\n [\"{{\", TOKEN_TYPES.OpenExpression],\n [\"}}\", TOKEN_TYPES.CloseExpression],\n // Single character tokens\n [\"(\", TOKEN_TYPES.OpenParen],\n [\")\", TOKEN_TYPES.CloseParen],\n [\"{\", TOKEN_TYPES.OpenCurlyBracket],\n [\"}\", TOKEN_TYPES.CloseCurlyBracket],\n [\"[\", TOKEN_TYPES.OpenSquareBracket],\n [\"]\", TOKEN_TYPES.CloseSquareBracket],\n [\",\", TOKEN_TYPES.Comma],\n [\".\", TOKEN_TYPES.Dot],\n [\":\", TOKEN_TYPES.Colon],\n [\"|\", TOKEN_TYPES.Pipe],\n // Comparison operators\n [\"<=\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\">=\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\"==\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\"!=\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\"<\", TOKEN_TYPES.ComparisonBinaryOperator],\n [\">\", TOKEN_TYPES.ComparisonBinaryOperator],\n // Arithmetic operators\n [\"+\", TOKEN_TYPES.AdditiveBinaryOperator],\n [\"-\", TOKEN_TYPES.AdditiveBinaryOperator],\n [\"*\", TOKEN_TYPES.MultiplicativeBinaryOperator],\n [\"/\", TOKEN_TYPES.MultiplicativeBinaryOperator],\n [\"%\", TOKEN_TYPES.MultiplicativeBinaryOperator],\n // Assignment operator\n [\"=\", TOKEN_TYPES.Equals]\n];\nvar ESCAPE_CHARACTERS = /* @__PURE__ */ new Map([\n [\"n\", \"\\n\"],\n // New line\n [\"t\", \"\t\"],\n // Horizontal tab\n [\"r\", \"\\r\"],\n // Carriage return\n [\"b\", \"\\b\"],\n // Backspace\n [\"f\", \"\\f\"],\n // Form feed\n [\"v\", \"\\v\"],\n // Vertical tab\n [\"'\", \"'\"],\n // Single quote\n ['\"', '\"'],\n // Double quote\n [\"\\\\\", \"\\\\\"]\n // Backslash\n]);\nfunction preprocess(template, options = {}) {\n if (template.endsWith(\"\\n\")) {\n template = template.slice(0, -1);\n }\n template = template.replace(/{#.*?#}/gs, \"{##}\");\n if (options.lstrip_blocks) {\n template = template.replace(/^[ \\t]*({[#%])/gm, \"$1\");\n }\n if (options.trim_blocks) {\n template = template.replace(/([#%]})\\n/g, \"$1\");\n }\n return template.replace(/{##}/g, \"\").replace(/-%}\\s*/g, \"%}\").replace(/\\s*{%-/g, \"{%\").replace(/-}}\\s*/g, \"}}\").replace(/\\s*{{-/g, \"{{\");\n}\nfunction tokenize(source, options = {}) {\n const tokens = [];\n const src = preprocess(source, options);\n let cursorPosition = 0;\n const consumeWhile = (predicate) => {\n let str = \"\";\n while (predicate(src[cursorPosition])) {\n if (src[cursorPosition] === \"\\\\\") {\n ++cursorPosition;\n if (cursorPosition >= src.length)\n throw new SyntaxError(\"Unexpected end of input\");\n const escaped = src[cursorPosition++];\n const unescaped = ESCAPE_CHARACTERS.get(escaped);\n if (unescaped === void 0) {\n throw new SyntaxError(`Unexpected escaped character: ${escaped}`);\n }\n str += unescaped;\n continue;\n }\n str += src[cursorPosition++];\n if (cursorPosition >= src.length)\n throw new SyntaxError(\"Unexpected end of input\");\n }\n return str;\n };\n main:\n while (cursorPosition < src.length) {\n const lastTokenType = tokens.at(-1)?.type;\n if (lastTokenType === void 0 || lastTokenType === TOKEN_TYPES.CloseStatement || lastTokenType === TOKEN_TYPES.CloseExpression) {\n let text = \"\";\n while (cursorPosition < src.length && // Keep going until we hit the next Jinja statement or expression\n !(src[cursorPosition] === \"{\" && (src[cursorPosition + 1] === \"%\" || src[cursorPosition + 1] === \"{\"))) {\n text += src[cursorPosition++];\n }\n if (text.length > 0) {\n tokens.push(new Token(text, TOKEN_TYPES.Text));\n continue;\n }\n }\n consumeWhile((char2) => /\\s/.test(char2));\n const char = src[cursorPosition];\n if (char === \"-\" || char === \"+\") {\n const lastTokenType2 = tokens.at(-1)?.type;\n if (lastTokenType2 === TOKEN_TYPES.Text || lastTokenType2 === void 0) {\n throw new SyntaxError(`Unexpected character: ${char}`);\n }\n switch (lastTokenType2) {\n case TOKEN_TYPES.Identifier:\n case TOKEN_TYPES.NumericLiteral:\n case TOKEN_TYPES.BooleanLiteral:\n case TOKEN_TYPES.StringLiteral:\n case TOKEN_TYPES.CloseParen:\n case TOKEN_TYPES.CloseSquareBracket:\n break;\n default: {\n ++cursorPosition;\n const num = consumeWhile(isInteger);\n tokens.push(\n new Token(`${char}${num}`, num.length > 0 ? TOKEN_TYPES.NumericLiteral : TOKEN_TYPES.UnaryOperator)\n );\n continue;\n }\n }\n }\n for (const [char2, token] of ORDERED_MAPPING_TABLE) {\n const slice2 = src.slice(cursorPosition, cursorPosition + char2.length);\n if (slice2 === char2) {\n tokens.push(new Token(char2, token));\n cursorPosition += char2.length;\n continue main;\n }\n }\n if (char === \"'\" || char === '\"') {\n ++cursorPosition;\n const str = consumeWhile((c) => c !== char);\n tokens.push(new Token(str, TOKEN_TYPES.StringLiteral));\n ++cursorPosition;\n continue;\n }\n if (isInteger(char)) {\n const num = consumeWhile(isInteger);\n tokens.push(new Token(num, TOKEN_TYPES.NumericLiteral));\n continue;\n }\n if (isWord(char)) {\n const word = consumeWhile(isWord);\n const type = Object.hasOwn(KEYWORDS, word) ? KEYWORDS[word] : TOKEN_TYPES.Identifier;\n if (type === TOKEN_TYPES.In && tokens.at(-1)?.type === TOKEN_TYPES.Not) {\n tokens.pop();\n tokens.push(new Token(\"not in\", TOKEN_TYPES.NotIn));\n } else {\n tokens.push(new Token(word, type));\n }\n continue;\n }\n throw new SyntaxError(`Unexpected character: ${char}`);\n }\n return tokens;\n}\n\n// src/ast.ts\nvar Statement = class {\n type = \"Statement\";\n};\nvar Program = class extends Statement {\n constructor(body) {\n super();\n this.body = body;\n }\n type = \"Program\";\n};\nvar If = class extends Statement {\n constructor(test, body, alternate) {\n super();\n this.test = test;\n this.body = body;\n this.alternate = alternate;\n }\n type = \"If\";\n};\nvar For = class extends Statement {\n constructor(loopvar, iterable, body, defaultBlock) {\n super();\n this.loopvar = loopvar;\n this.iterable = iterable;\n this.body = body;\n this.defaultBlock = defaultBlock;\n }\n type = \"For\";\n};\nvar SetStatement = class extends Statement {\n constructor(assignee, value) {\n super();\n this.assignee = assignee;\n this.value = value;\n }\n type = \"Set\";\n};\nvar Macro = class extends Statement {\n constructor(name, args, body) {\n super();\n this.name = name;\n this.args = args;\n this.body = body;\n }\n type = \"Macro\";\n};\nvar Expression = class extends Statement {\n type = \"Expression\";\n};\nvar MemberExpression = class extends Expression {\n constructor(object, property, computed) {\n super();\n this.object = object;\n this.property = property;\n this.computed = computed;\n }\n type = \"MemberExpression\";\n};\nvar CallExpression = class extends Expression {\n constructor(callee, args) {\n super();\n this.callee = callee;\n this.args = args;\n }\n type = \"CallExpression\";\n};\nvar Identifier = class extends Expression {\n /**\n * @param {string} value The name of the identifier\n */\n constructor(value) {\n super();\n this.value = value;\n }\n type = \"Identifier\";\n};\nvar Literal = class extends Expression {\n constructor(value) {\n super();\n this.value = value;\n }\n type = \"Literal\";\n};\nvar NumericLiteral = class extends Literal {\n type = \"NumericLiteral\";\n};\nvar StringLiteral = class extends Literal {\n type = \"StringLiteral\";\n};\nvar BooleanLiteral = class extends Literal {\n type = \"BooleanLiteral\";\n};\nvar ArrayLiteral = class extends Literal {\n type = \"ArrayLiteral\";\n};\nvar TupleLiteral = class extends Literal {\n type = \"TupleLiteral\";\n};\nvar ObjectLiteral = class extends Literal {\n type = \"ObjectLiteral\";\n};\nvar BinaryExpression = class extends Expression {\n constructor(operator, left, right) {\n super();\n this.operator = operator;\n this.left = left;\n this.right = right;\n }\n type = \"BinaryExpression\";\n};\nvar FilterExpression = class extends Expression {\n constructor(operand, filter) {\n super();\n this.operand = operand;\n this.filter = filter;\n }\n type = \"FilterExpression\";\n};\nvar SelectExpression = class extends Expression {\n constructor(iterable, test) {\n super();\n this.iterable = iterable;\n this.test = test;\n }\n type = \"SelectExpression\";\n};\nvar TestExpression = class extends Expression {\n constructor(operand, negate, test) {\n super();\n this.operand = operand;\n this.negate = negate;\n this.test = test;\n }\n type = \"TestExpression\";\n};\nvar UnaryExpression = class extends Expression {\n constructor(operator, argument) {\n super();\n this.operator = operator;\n this.argument = argument;\n }\n type = \"UnaryExpression\";\n};\nvar SliceExpression = class extends Expression {\n constructor(start = void 0, stop = void 0, step = void 0) {\n super();\n this.start = start;\n this.stop = stop;\n this.step = step;\n }\n type = \"SliceExpression\";\n};\nvar KeywordArgumentExpression = class extends Expression {\n constructor(key, value) {\n super();\n this.key = key;\n this.value = value;\n }\n type = \"KeywordArgumentExpression\";\n};\n\n// src/parser.ts\nfunction parse(tokens) {\n const program = new Program([]);\n let current = 0;\n function expect(type, error) {\n const prev = tokens[current++];\n if (!prev || prev.type !== type) {\n throw new Error(`Parser Error: ${error}. ${prev.type} !== ${type}.`);\n }\n return prev;\n }\n function parseAny() {\n switch (tokens[current].type) {\n case TOKEN_TYPES.Text:\n return parseText();\n case TOKEN_TYPES.OpenStatement:\n return parseJinjaStatement();\n case TOKEN_TYPES.OpenExpression:\n return parseJinjaExpression();\n default:\n throw new SyntaxError(`Unexpected token type: ${tokens[current].type}`);\n }\n }\n function not(...types) {\n return current + types.length <= tokens.length && types.some((type, i) => type !== tokens[current + i].type);\n }\n function is(...types) {\n return current + types.length <= tokens.length && types.every((type, i) => type === tokens[current + i].type);\n }\n function parseText() {\n return new StringLiteral(expect(TOKEN_TYPES.Text, \"Expected text token\").value);\n }\n function parseJinjaStatement() {\n expect(TOKEN_TYPES.OpenStatement, \"Expected opening statement token\");\n let result;\n switch (tokens[current].type) {\n case TOKEN_TYPES.Set:\n ++current;\n result = parseSetStatement();\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n break;\n case TOKEN_TYPES.If:\n ++current;\n result = parseIfStatement();\n expect(TOKEN_TYPES.OpenStatement, \"Expected {% token\");\n expect(TOKEN_TYPES.EndIf, \"Expected endif token\");\n expect(TOKEN_TYPES.CloseStatement, \"Expected %} token\");\n break;\n case TOKEN_TYPES.Macro:\n ++current;\n result = parseMacroStatement();\n expect(TOKEN_TYPES.OpenStatement, \"Expected {% token\");\n expect(TOKEN_TYPES.EndMacro, \"Expected endmacro token\");\n expect(TOKEN_TYPES.CloseStatement, \"Expected %} token\");\n break;\n case TOKEN_TYPES.For:\n ++current;\n result = parseForStatement();\n expect(TOKEN_TYPES.OpenStatement, \"Expected {% token\");\n expect(TOKEN_TYPES.EndFor, \"Expected endfor token\");\n expect(TOKEN_TYPES.CloseStatement, \"Expected %} token\");\n break;\n default:\n throw new SyntaxError(`Unknown statement type: ${tokens[current].type}`);\n }\n return result;\n }\n function parseJinjaExpression() {\n expect(TOKEN_TYPES.OpenExpression, \"Expected opening expression token\");\n const result = parseExpression();\n expect(TOKEN_TYPES.CloseExpression, \"Expected closing expression token\");\n return result;\n }\n function parseSetStatement() {\n const left = parseExpression();\n if (is(TOKEN_TYPES.Equals)) {\n ++current;\n const value = parseSetStatement();\n return new SetStatement(left, value);\n }\n return left;\n }\n function parseIfStatement() {\n const test = parseExpression();\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n const body = [];\n const alternate = [];\n while (!(tokens[current]?.type === TOKEN_TYPES.OpenStatement && (tokens[current + 1]?.type === TOKEN_TYPES.ElseIf || tokens[current + 1]?.type === TOKEN_TYPES.Else || tokens[current + 1]?.type === TOKEN_TYPES.EndIf))) {\n body.push(parseAny());\n }\n if (tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type !== TOKEN_TYPES.EndIf) {\n ++current;\n if (is(TOKEN_TYPES.ElseIf)) {\n expect(TOKEN_TYPES.ElseIf, \"Expected elseif token\");\n alternate.push(parseIfStatement());\n } else {\n expect(TOKEN_TYPES.Else, \"Expected else token\");\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n while (!(tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type === TOKEN_TYPES.EndIf)) {\n alternate.push(parseAny());\n }\n }\n }\n return new If(test, body, alternate);\n }\n function parseMacroStatement() {\n const name = parsePrimaryExpression();\n if (name.type !== \"Identifier\") {\n throw new SyntaxError(`Expected identifier following macro statement`);\n }\n const args = parseArgs();\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n const body = [];\n while (not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.EndMacro)) {\n body.push(parseAny());\n }\n return new Macro(name, args, body);\n }\n function parseExpressionSequence(primary = false) {\n const fn = primary ? parsePrimaryExpression : parseExpression;\n const expressions = [fn()];\n const isTuple = is(TOKEN_TYPES.Comma);\n while (isTuple) {\n ++current;\n expressions.push(fn());\n if (!is(TOKEN_TYPES.Comma)) {\n break;\n }\n }\n return isTuple ? new TupleLiteral(expressions) : expressions[0];\n }\n function parseForStatement() {\n const loopVariable = parseExpressionSequence(true);\n if (!(loopVariable instanceof Identifier || loopVariable instanceof TupleLiteral)) {\n throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${loopVariable.type} instead`);\n }\n expect(TOKEN_TYPES.In, \"Expected `in` keyword following loop variable\");\n const iterable = parseExpression();\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n const body = [];\n while (not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.EndFor) && not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.Else)) {\n body.push(parseAny());\n }\n const alternative = [];\n if (is(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.Else)) {\n ++current;\n ++current;\n expect(TOKEN_TYPES.CloseStatement, \"Expected closing statement token\");\n while (not(TOKEN_TYPES.OpenStatement, TOKEN_TYPES.EndFor)) {\n alternative.push(parseAny());\n }\n }\n return new For(loopVariable, iterable, body, alternative);\n }\n function parseExpression() {\n return parseIfExpression();\n }\n function parseIfExpression() {\n const a = parseLogicalOrExpression();\n if (is(TOKEN_TYPES.If)) {\n ++current;\n const predicate = parseLogicalOrExpression();\n if (is(TOKEN_TYPES.Else)) {\n ++current;\n const b = parseLogicalOrExpression();\n return new If(predicate, [a], [b]);\n } else {\n return new SelectExpression(a, predicate);\n }\n }\n return a;\n }\n function parseLogicalOrExpression() {\n let left = parseLogicalAndExpression();\n while (is(TOKEN_TYPES.Or)) {\n const operator = tokens[current];\n ++current;\n const right = parseLogicalAndExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseLogicalAndExpression() {\n let left = parseLogicalNegationExpression();\n while (is(TOKEN_TYPES.And)) {\n const operator = tokens[current];\n ++current;\n const right = parseLogicalNegationExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseLogicalNegationExpression() {\n let right;\n while (is(TOKEN_TYPES.Not)) {\n const operator = tokens[current];\n ++current;\n const arg = parseLogicalNegationExpression();\n right = new UnaryExpression(operator, arg);\n }\n return right ?? parseComparisonExpression();\n }\n function parseComparisonExpression() {\n let left = parseAdditiveExpression();\n while (is(TOKEN_TYPES.ComparisonBinaryOperator) || is(TOKEN_TYPES.In) || is(TOKEN_TYPES.NotIn)) {\n const operator = tokens[current];\n ++current;\n const right = parseAdditiveExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseAdditiveExpression() {\n let left = parseMultiplicativeExpression();\n while (is(TOKEN_TYPES.AdditiveBinaryOperator)) {\n const operator = tokens[current];\n ++current;\n const right = parseMultiplicativeExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseCallMemberExpression() {\n const member = parseMemberExpression();\n if (is(TOKEN_TYPES.OpenParen)) {\n return parseCallExpression(member);\n }\n return member;\n }\n function parseCallExpression(callee) {\n let callExpression = new CallExpression(callee, parseArgs());\n if (is(TOKEN_TYPES.OpenParen)) {\n callExpression = parseCallExpression(callExpression);\n }\n return callExpression;\n }\n function parseArgs() {\n expect(TOKEN_TYPES.OpenParen, \"Expected opening parenthesis for arguments list\");\n const args = parseArgumentsList();\n expect(TOKEN_TYPES.CloseParen, \"Expected closing parenthesis for arguments list\");\n return args;\n }\n function parseArgumentsList() {\n const args = [];\n while (!is(TOKEN_TYPES.CloseParen)) {\n let argument = parseExpression();\n if (is(TOKEN_TYPES.Equals)) {\n ++current;\n if (!(argument instanceof Identifier)) {\n throw new SyntaxError(`Expected identifier for keyword argument`);\n }\n const value = parseExpression();\n argument = new KeywordArgumentExpression(argument, value);\n }\n args.push(argument);\n if (is(TOKEN_TYPES.Comma)) {\n ++current;\n }\n }\n return args;\n }\n function parseMemberExpressionArgumentsList() {\n const slices = [];\n let isSlice = false;\n while (!is(TOKEN_TYPES.CloseSquareBracket)) {\n if (is(TOKEN_TYPES.Colon)) {\n slices.push(void 0);\n ++current;\n isSlice = true;\n } else {\n slices.push(parseExpression());\n if (is(TOKEN_TYPES.Colon)) {\n ++current;\n isSlice = true;\n }\n }\n }\n if (slices.length === 0) {\n throw new SyntaxError(`Expected at least one argument for member/slice expression`);\n }\n if (isSlice) {\n if (slices.length > 3) {\n throw new SyntaxError(`Expected 0-3 arguments for slice expression`);\n }\n return new SliceExpression(...slices);\n }\n return slices[0];\n }\n function parseMemberExpression() {\n let object = parsePrimaryExpression();\n while (is(TOKEN_TYPES.Dot) || is(TOKEN_TYPES.OpenSquareBracket)) {\n const operator = tokens[current];\n ++current;\n let property;\n const computed = operator.type !== TOKEN_TYPES.Dot;\n if (computed) {\n property = parseMemberExpressionArgumentsList();\n expect(TOKEN_TYPES.CloseSquareBracket, \"Expected closing square bracket\");\n } else {\n property = parsePrimaryExpression();\n if (property.type !== \"Identifier\") {\n throw new SyntaxError(`Expected identifier following dot operator`);\n }\n }\n object = new MemberExpression(object, property, computed);\n }\n return object;\n }\n function parseMultiplicativeExpression() {\n let left = parseTestExpression();\n while (is(TOKEN_TYPES.MultiplicativeBinaryOperator)) {\n const operator = tokens[current];\n ++current;\n const right = parseTestExpression();\n left = new BinaryExpression(operator, left, right);\n }\n return left;\n }\n function parseTestExpression() {\n let operand = parseFilterExpression();\n while (is(TOKEN_TYPES.Is)) {\n ++current;\n const negate = is(TOKEN_TYPES.Not);\n if (negate) {\n ++current;\n }\n let filter = parsePrimaryExpression();\n if (filter instanceof BooleanLiteral) {\n filter = new Identifier(filter.value.toString());\n }\n if (!(filter instanceof Identifier)) {\n throw new SyntaxError(`Expected identifier for the test`);\n }\n operand = new TestExpression(operand, negate, filter);\n }\n return operand;\n }\n function parseFilterExpression() {\n let operand = parseCallMemberExpression();\n while (is(TOKEN_TYPES.Pipe)) {\n ++current;\n let filter = parsePrimaryExpression();\n if (!(filter instanceof Identifier)) {\n throw new SyntaxError(`Expected identifier for the filter`);\n }\n if (is(TOKEN_TYPES.OpenParen)) {\n filter = parseCallExpression(filter);\n }\n operand = new FilterExpression(operand, filter);\n }\n return operand;\n }\n function parsePrimaryExpression() {\n const token = tokens[current];\n switch (token.type) {\n case TOKEN_TYPES.NumericLiteral:\n ++current;\n return new NumericLiteral(Number(token.value));\n case TOKEN_TYPES.StringLiteral:\n ++current;\n return new StringLiteral(token.value);\n case TOKEN_TYPES.BooleanLiteral:\n ++current;\n return new BooleanLiteral(token.value.toLowerCase() === \"true\");\n case TOKEN_TYPES.Identifier:\n ++current;\n return new Identifier(token.value);\n case TOKEN_TYPES.OpenParen: {\n ++current;\n const expression = parseExpressionSequence();\n if (tokens[current].type !== TOKEN_TYPES.CloseParen) {\n throw new SyntaxError(`Expected closing parenthesis, got ${tokens[current].type} instead`);\n }\n ++current;\n return expression;\n }\n case TOKEN_TYPES.OpenSquareBracket: {\n ++current;\n const values = [];\n while (!is(TOKEN_TYPES.CloseSquareBracket)) {\n values.push(parseExpression());\n if (is(TOKEN_TYPES.Comma)) {\n ++current;\n }\n }\n ++current;\n return new ArrayLiteral(values);\n }\n case TOKEN_TYPES.OpenCurlyBracket: {\n ++current;\n const values = /* @__PURE__ */ new Map();\n while (!is(TOKEN_TYPES.CloseCurlyBracket)) {\n const key = parseExpression();\n expect(TOKEN_TYPES.Colon, \"Expected colon between key and value in object literal\");\n const value = parseExpression();\n values.set(key, value);\n if (is(TOKEN_TYPES.Comma)) {\n ++current;\n }\n }\n ++current;\n return new ObjectLiteral(values);\n }\n default:\n throw new SyntaxError(`Unexpected token: ${token.type}`);\n }\n }\n while (current < tokens.length) {\n program.body.push(parseAny());\n }\n return program;\n}\n\n// src/utils.ts\nfunction range(start, stop, step = 1) {\n if (stop === void 0) {\n stop = start;\n start = 0;\n }\n const result = [];\n for (let i = start; i < stop; i += step) {\n result.push(i);\n }\n return result;\n}\nfunction slice(array, start, stop, step = 1) {\n const direction = Math.sign(step);\n if (direction >= 0) {\n start = (start ??= 0) < 0 ? Math.max(array.length + start, 0) : Math.min(start, array.length);\n stop = (stop ??= array.length) < 0 ? Math.max(array.length + stop, 0) : Math.min(stop, array.length);\n } else {\n start = (start ??= array.length - 1) < 0 ? Math.max(array.length + start, -1) : Math.min(start, array.length - 1);\n stop = (stop ??= -1) < -1 ? Math.max(array.length + stop, -1) : Math.min(stop, array.length - 1);\n }\n const result = [];\n for (let i = start; direction * i < direction * stop; i += step) {\n result.push(array[i]);\n }\n return result;\n}\nfunction titleCase(value) {\n return value.replace(/\\b\\w/g, (c) => c.toUpperCase());\n}\n\n// src/runtime.ts\nvar RuntimeValue = class {\n type = \"RuntimeValue\";\n value;\n /**\n * A collection of built-in functions for this type.\n */\n builtins = /* @__PURE__ */ new Map();\n /**\n * Creates a new RuntimeValue.\n */\n constructor(value = void 0) {\n this.value = value;\n }\n /**\n * Determines truthiness or falsiness of the runtime value.\n * This function should be overridden by subclasses if it has custom truthiness criteria.\n * @returns {BooleanValue} BooleanValue(true) if the value is truthy, BooleanValue(false) otherwise.\n */\n __bool__() {\n return new BooleanValue(!!this.value);\n }\n};\nvar NumericValue = class extends RuntimeValue {\n type = \"NumericValue\";\n};\nvar StringValue = class extends RuntimeValue {\n type = \"StringValue\";\n builtins = /* @__PURE__ */ new Map([\n [\n \"upper\",\n new FunctionValue(() => {\n return new StringValue(this.value.toUpperCase());\n })\n ],\n [\n \"lower\",\n new FunctionValue(() => {\n return new StringValue(this.value.toLowerCase());\n })\n ],\n [\n \"strip\",\n new FunctionValue(() => {\n return new StringValue(this.value.trim());\n })\n ],\n [\n \"title\",\n new FunctionValue(() => {\n return new StringValue(titleCase(this.value));\n })\n ],\n [\"length\", new NumericValue(this.value.length)]\n ]);\n};\nvar BooleanValue = class extends RuntimeValue {\n type = \"BooleanValue\";\n};\nvar ObjectValue = class extends RuntimeValue {\n type = \"ObjectValue\";\n /**\n * NOTE: necessary to override since all JavaScript arrays are considered truthy,\n * while only non-empty Python arrays are consider truthy.\n *\n * e.g.,\n * - JavaScript: {} && 5 -> 5\n * - Python: {} and 5 -> {}\n */\n __bool__() {\n return new BooleanValue(this.value.size > 0);\n }\n builtins = /* @__PURE__ */ new Map([\n [\n \"get\",\n new FunctionValue(([key, defaultValue]) => {\n if (!(key instanceof StringValue)) {\n throw new Error(`Object key must be a string: got ${key.type}`);\n }\n return this.value.get(key.value) ?? defaultValue ?? new NullValue();\n })\n ],\n [\n \"items\",\n new FunctionValue(() => {\n return new ArrayValue(\n Array.from(this.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value]))\n );\n })\n ]\n ]);\n};\nvar KeywordArgumentsValue = class extends ObjectValue {\n type = \"KeywordArgumentsValue\";\n};\nvar ArrayValue = class extends RuntimeValue {\n type = \"ArrayValue\";\n builtins = /* @__PURE__ */ new Map([[\"length\", new NumericValue(this.value.length)]]);\n /**\n * NOTE: necessary to override since all JavaScript arrays are considered truthy,\n * while only non-empty Python arrays are consider truthy.\n *\n * e.g.,\n * - JavaScript: [] && 5 -> 5\n * - Python: [] and 5 -> []\n */\n __bool__() {\n return new BooleanValue(this.value.length > 0);\n }\n};\nvar TupleValue = class extends ArrayValue {\n type = \"TupleValue\";\n};\nvar FunctionValue = class extends RuntimeValue {\n type = \"FunctionValue\";\n};\nvar NullValue = class extends RuntimeValue {\n type = \"NullValue\";\n};\nvar UndefinedValue = class extends RuntimeValue {\n type = \"UndefinedValue\";\n};\nvar Environment = class {\n constructor(parent) {\n this.parent = parent;\n }\n /**\n * The variables declared in this environment.\n */\n variables = /* @__PURE__ */ new Map([\n [\n \"namespace\",\n new FunctionValue((args) => {\n if (args.length === 0) {\n return new ObjectValue(/* @__PURE__ */ new Map());\n }\n if (args.length !== 1 || !(args[0] instanceof ObjectValue)) {\n throw new Error(\"`namespace` expects either zero arguments or a single object argument\");\n }\n return args[0];\n })\n ]\n ]);\n /**\n * The tests available in this environment.\n */\n tests = /* @__PURE__ */ new Map([\n [\"boolean\", (operand) => operand.type === \"BooleanValue\"],\n [\"callable\", (operand) => operand instanceof FunctionValue],\n [\n \"odd\",\n (operand) => {\n if (operand.type !== \"NumericValue\") {\n throw new Error(`Cannot apply test \"odd\" to type: ${operand.type}`);\n }\n return operand.value % 2 !== 0;\n }\n ],\n [\n \"even\",\n (operand) => {\n if (operand.type !== \"NumericValue\") {\n throw new Error(`Cannot apply test \"even\" to type: ${operand.type}`);\n }\n return operand.value % 2 === 0;\n }\n ],\n [\"false\", (operand) => operand.type === \"BooleanValue\" && !operand.value],\n [\"true\", (operand) => operand.type === \"BooleanValue\" && operand.value],\n [\"string\", (operand) => operand.type === \"StringValue\"],\n [\"number\", (operand) => operand.type === \"NumericValue\"],\n [\"integer\", (operand) => operand.type === \"NumericValue\" && Number.isInteger(operand.value)],\n [\"iterable\", (operand) => operand instanceof ArrayValue || operand instanceof StringValue],\n [\n \"lower\",\n (operand) => {\n const str = operand.value;\n return operand.type === \"StringValue\" && str === str.toLowerCase();\n }\n ],\n [\n \"upper\",\n (operand) => {\n const str = operand.value;\n return operand.type === \"StringValue\" && str === str.toUpperCase();\n }\n ],\n [\"none\", (operand) => operand.type === \"NullValue\"],\n [\"defined\", (operand) => operand.type !== \"UndefinedValue\"],\n [\"undefined\", (operand) => operand.type === \"UndefinedValue\"],\n [\"equalto\", (a, b) => a.value === b.value],\n [\"eq\", (a, b) => a.value === b.value]\n ]);\n /**\n * Set the value of a variable in the current environment.\n */\n set(name, value) {\n return this.declareVariable(name, convertToRuntimeValues(value));\n }\n declareVariable(name, value) {\n if (this.variables.has(name)) {\n throw new SyntaxError(`Variable already declared: ${name}`);\n }\n this.variables.set(name, value);\n return value;\n }\n // private assignVariable(name: string, value: AnyRuntimeValue): AnyRuntimeValue {\n // \tconst env = this.resolve(name);\n // \tenv.variables.set(name, value);\n // \treturn value;\n // }\n /**\n * Set variable in the current scope.\n * See https://jinja.palletsprojects.com/en/3.0.x/templates/#assignments for more information.\n */\n setVariable(name, value) {\n this.variables.set(name, value);\n return value;\n }\n /**\n * Resolve the environment in which the variable is declared.\n * @param {string} name The name of the variable.\n * @returns {Environment} The environment in which the variable is declared.\n */\n resolve(name) {\n if (this.variables.has(name)) {\n return this;\n }\n if (this.parent) {\n return this.parent.resolve(name);\n }\n throw new Error(`Unknown variable: ${name}`);\n }\n lookupVariable(name) {\n try {\n return this.resolve(name).variables.get(name) ?? new UndefinedValue();\n } catch {\n return new UndefinedValue();\n }\n }\n};\nvar Interpreter = class {\n global;\n constructor(env) {\n this.global = env ?? new Environment();\n }\n /**\n * Run the program.\n */\n run(program) {\n return this.evaluate(program, this.global);\n }\n /**\n * Evaluates expressions following the binary operation type.\n */\n evaluateBinaryExpression(node, environment) {\n const left = this.evaluate(node.left, environment);\n switch (node.operator.value) {\n case \"and\":\n return left.__bool__().value ? this.evaluate(node.right, environment) : left;\n case \"or\":\n return left.__bool__().value ? left : this.evaluate(node.right, environment);\n }\n const right = this.evaluate(node.right, environment);\n switch (node.operator.value) {\n case \"==\":\n return new BooleanValue(left.value == right.value);\n case \"!=\":\n return new BooleanValue(left.value != right.value);\n }\n if (left instanceof UndefinedValue || right instanceof UndefinedValue) {\n throw new Error(\"Cannot perform operation on undefined values\");\n } else if (left instanceof NullValue || right instanceof NullValue) {\n throw new Error(\"Cannot perform operation on null values\");\n } else if (left instanceof NumericValue && right instanceof NumericValue) {\n switch (node.operator.value) {\n case \"+\":\n return new NumericValue(left.value + right.value);\n case \"-\":\n return new NumericValue(left.value - right.value);\n case \"*\":\n return new NumericValue(left.value * right.value);\n case \"/\":\n return new NumericValue(left.value / right.value);\n case \"%\":\n return new NumericValue(left.value % right.value);\n case \"<\":\n return new BooleanValue(left.value < right.value);\n case \">\":\n return new BooleanValue(left.value > right.value);\n case \">=\":\n return new BooleanValue(left.value >= right.value);\n case \"<=\":\n return new BooleanValue(left.value <= right.value);\n }\n } else if (left instanceof ArrayValue && right instanceof ArrayValue) {\n switch (node.operator.value) {\n case \"+\":\n return new ArrayValue(left.value.concat(right.value));\n }\n } else if (right instanceof ArrayValue) {\n const member = right.value.find((x) => x.value === left.value) !== void 0;\n switch (node.operator.value) {\n case \"in\":\n return new BooleanValue(member);\n case \"not in\":\n return new BooleanValue(!member);\n }\n }\n if (left instanceof StringValue || right instanceof StringValue) {\n switch (node.operator.value) {\n case \"+\":\n return new StringValue(left.value.toString() + right.value.toString());\n }\n }\n if (left instanceof StringValue && right instanceof StringValue) {\n switch (node.operator.value) {\n case \"in\":\n return new BooleanValue(right.value.includes(left.value));\n case \"not in\":\n return new BooleanValue(!right.value.includes(left.value));\n }\n }\n if (left instanceof StringValue && right instanceof ObjectValue) {\n switch (node.operator.value) {\n case \"in\":\n return new BooleanValue(right.value.has(left.value));\n case \"not in\":\n return new BooleanValue(!right.value.has(left.value));\n }\n }\n throw new SyntaxError(`Unknown operator \"${node.operator.value}\" between ${left.type} and ${right.type}`);\n }\n evaluateArguments(args, environment) {\n const positionalArguments = [];\n const keywordArguments = /* @__PURE__ */ new Map();\n for (const argument of args) {\n if (argument.type === \"KeywordArgumentExpression\") {\n const kwarg = argument;\n keywordArguments.set(kwarg.key.value, this.evaluate(kwarg.value, environment));\n } else {\n if (keywordArguments.size > 0) {\n throw new Error(\"Positional arguments must come before keyword arguments\");\n }\n positionalArguments.push(this.evaluate(argument, environment));\n }\n }\n return [positionalArguments, keywordArguments];\n }\n /**\n * Evaluates expressions following the filter operation type.\n */\n evaluateFilterExpression(node, environment) {\n const operand = this.evaluate(node.operand, environment);\n if (node.filter.type === \"Identifier\") {\n const filter = node.filter;\n if (filter.value === \"tojson\") {\n return new StringValue(toJSON(operand));\n }\n if (operand instanceof ArrayValue) {\n switch (filter.value) {\n case \"list\":\n return operand;\n case \"first\":\n return operand.value[0];\n case \"last\":\n return operand.value[operand.value.length - 1];\n case \"length\":\n return new NumericValue(operand.value.length);\n case \"reverse\":\n return new ArrayValue(operand.value.reverse());\n case \"sort\":\n return new ArrayValue(\n operand.value.sort((a, b) => {\n if (a.type !== b.type) {\n throw new Error(`Cannot compare different types: ${a.type} and ${b.type}`);\n }\n switch (a.type) {\n case \"NumericValue\":\n return a.value - b.value;\n case \"StringValue\":\n return a.value.localeCompare(b.value);\n default:\n throw new Error(`Cannot compare type: ${a.type}`);\n }\n })\n );\n default:\n throw new Error(`Unknown ArrayValue filter: ${filter.value}`);\n }\n } else if (operand instanceof StringValue) {\n switch (filter.value) {\n case \"length\":\n return new NumericValue(operand.value.length);\n case \"upper\":\n return new StringValue(operand.value.toUpperCase());\n case \"lower\":\n return new StringValue(operand.value.toLowerCase());\n case \"title\":\n return new StringValue(titleCase(operand.value));\n case \"capitalize\":\n return new StringValue(operand.value.charAt(0).toUpperCase() + operand.value.slice(1));\n case \"trim\":\n return new StringValue(operand.value.trim());\n case \"indent\":\n return new StringValue(\n operand.value.split(\"\\n\").map(\n (x, i) => (\n // By default, don't indent the first line or empty lines\n i === 0 || x.length === 0 ? x : \" \" + x\n )\n ).join(\"\\n\")\n );\n case \"string\":\n return operand;\n default:\n throw new Error(`Unknown StringValue filter: ${filter.value}`);\n }\n } else if (operand instanceof NumericValue) {\n switch (filter.value) {\n case \"abs\":\n return new NumericValue(Math.abs(operand.value));\n default:\n throw new Error(`Unknown NumericValue filter: ${filter.value}`);\n }\n } else if (operand instanceof ObjectValue) {\n switch (filter.value) {\n case \"items\":\n return new ArrayValue(\n Array.from(operand.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value]))\n );\n case \"length\":\n return new NumericValue(operand.value.size);\n default:\n throw new Error(`Unknown ObjectValue filter: ${filter.value}`);\n }\n }\n throw new Error(`Cannot apply filter \"${filter.value}\" to type: ${operand.type}`);\n } else if (node.filter.type === \"CallExpression\") {\n const filter = node.filter;\n if (filter.callee.type !== \"Identifier\") {\n throw new Error(`Unknown filter: ${filter.callee.type}`);\n }\n const filterName = filter.callee.value;\n if (filterName === \"tojson\") {\n const [, kwargs] = this.evaluateArguments(filter.args, environment);\n const indent = kwargs.get(\"indent\") ?? new NullValue();\n if (!(indent instanceof NumericValue || indent instanceof NullValue)) {\n throw new Error(\"If set, indent must be a number\");\n }\n return new StringValue(toJSON(operand, indent.value));\n }\n if (operand instanceof ArrayValue) {\n switch (filterName) {\n case \"selectattr\": {\n if (operand.value.some((x) => !(x instanceof ObjectValue))) {\n throw new Error(\"`selectattr` can only be applied to array of objects\");\n }\n if (filter.args.some((x) => x.type !== \"StringLiteral\")) {\n throw new Error(\"arguments of `selectattr` must be strings\");\n }\n const [attr, testName, value] = filter.args.map((x) => this.evaluate(x, environment));\n let testFunction;\n if (testName) {\n const test = environment.tests.get(testName.value);\n if (!test) {\n throw new Error(`Unknown test: ${testName.value}`);\n }\n testFunction = test;\n } else {\n testFunction = (...x) => x[0].__bool__().value;\n }\n const filtered = operand.value.filter((item) => {\n const a = item.value.get(attr.value);\n if (a) {\n return testFunction(a, value);\n }\n return false;\n });\n return new ArrayValue(filtered);\n }\n case \"map\": {\n const [, kwargs] = this.evaluateArguments(filter.args, environment);\n if (kwargs.has(\"attribute\")) {\n const attr = kwargs.get(\"attribute\");\n if (!(attr instanceof StringValue)) {\n throw new Error(\"attribute must be a string\");\n }\n const defaultValue = kwargs.get(\"default\");\n const mapped = operand.value.map((item) => {\n if (!(item instanceof ObjectValue)) {\n throw new Error(\"items in map must be an object\");\n }\n return item.value.get(attr.value) ?? defaultValue ?? new UndefinedValue();\n });\n return new ArrayValue(mapped);\n } else {\n throw new Error(\"`map` expressions without `attribute` set are not currently supported.\");\n }\n }\n }\n throw new Error(`Unknown ArrayValue filter: ${filterName}`);\n } else if (operand instanceof StringValue) {\n switch (filterName) {\n case \"indent\": {\n const [args, kwargs] = this.evaluateArguments(filter.args, environment);\n const width = args.at(0) ?? kwargs.get(\"width\") ?? new NumericValue(4);\n if (!(width instanceof NumericValue)) {\n throw new Error(\"width must be a number\");\n }\n const first = args.at(1) ?? kwargs.get(\"first\") ?? new BooleanValue(false);\n const blank = args.at(2) ?? kwargs.get(\"blank\") ?? new BooleanValue(false);\n const lines = operand.value.split(\"\\n\");\n const indent = \" \".repeat(width.value);\n const indented = lines.map(\n (x, i) => !first.value && i === 0 || !blank.value && x.length === 0 ? x : indent + x\n );\n return new StringValue(indented.join(\"\\n\"));\n }\n }\n throw new Error(`Unknown StringValue filter: ${filterName}`);\n } else {\n throw new Error(`Cannot apply filter \"${filterName}\" to type: ${operand.type}`);\n }\n }\n throw new Error(`Unknown filter: ${node.filter.type}`);\n }\n /**\n * Evaluates expressions following the test operation type.\n */\n evaluateTestExpression(node, environment) {\n const operand = this.evaluate(node.operand, environment);\n const test = environment.tests.get(node.test.value);\n if (!test) {\n throw new Error(`Unknown test: ${node.test.value}`);\n }\n const result = test(operand);\n return new BooleanValue(node.negate ? !result : result);\n }\n /**\n * Evaluates expressions following the unary operation type.\n */\n evaluateUnaryExpression(node, environment) {\n const argument = this.evaluate(node.argument, environment);\n switch (node.operator.value) {\n case \"not\":\n return new BooleanValue(!argument.value);\n default:\n throw new SyntaxError(`Unknown operator: ${node.operator.value}`);\n }\n }\n evalProgram(program, environment) {\n return this.evaluateBlock(program.body, environment);\n }\n evaluateBlock(statements, environment) {\n let result = \"\";\n for (const statement of statements) {\n const lastEvaluated = this.evaluate(statement, environment);\n if (lastEvaluated.type !== \"NullValue\" && lastEvaluated.type !== \"UndefinedValue\") {\n result += lastEvaluated.value;\n }\n }\n return new StringValue(result);\n }\n evaluateIdentifier(node, environment) {\n return environment.lookupVariable(node.value);\n }\n evaluateCallExpression(expr, environment) {\n const [args, kwargs] = this.evaluateArguments(expr.args, environment);\n if (kwargs.size > 0) {\n args.push(new KeywordArgumentsValue(kwargs));\n }\n const fn = this.evaluate(expr.callee, environment);\n if (fn.type !== \"FunctionValue\") {\n throw new Error(`Cannot call something that is not a function: got ${fn.type}`);\n }\n return fn.value(args, environment);\n }\n evaluateSliceExpression(object, expr, environment) {\n if (!(object instanceof ArrayValue || object instanceof StringValue)) {\n throw new Error(\"Slice object must be an array or string\");\n }\n const start = this.evaluate(expr.start, environment);\n const stop = this.evaluate(expr.stop, environment);\n const step = this.evaluate(expr.step, environment);\n if (!(start instanceof NumericValue || start instanceof UndefinedValue)) {\n throw new Error(\"Slice start must be numeric or undefined\");\n }\n if (!(stop instanceof NumericValue || stop instanceof UndefinedValue)) {\n throw new Error(\"Slice stop must be numeric or undefined\");\n }\n if (!(step instanceof NumericValue || step instanceof UndefinedValue)) {\n throw new Error(\"Slice step must be numeric or undefined\");\n }\n if (object instanceof ArrayValue) {\n return new ArrayValue(slice(object.value, start.value, stop.value, step.value));\n } else {\n return new StringValue(slice(Array.from(object.value), start.value, stop.value, step.value).join(\"\"));\n }\n }\n evaluateMemberExpression(expr, environment) {\n const object = this.evaluate(expr.object, environment);\n let property;\n if (expr.computed) {\n if (expr.property.type === \"SliceExpression\") {\n return this.evaluateSliceExpression(object, expr.property, environment);\n } else {\n property = this.evaluate(expr.property, environment);\n }\n } else {\n property = new StringValue(expr.property.value);\n }\n let value;\n if (object instanceof ObjectValue) {\n if (!(property instanceof StringValue)) {\n throw new Error(`Cannot access property with non-string: got ${property.type}`);\n }\n value = object.value.get(property.value) ?? object.builtins.get(property.value);\n } else if (object instanceof ArrayValue || object instanceof StringValue) {\n if (property instanceof NumericValue) {\n value = object.value.at(property.value);\n if (object instanceof StringValue) {\n value = new StringValue(object.value.at(property.value));\n }\n } else if (property instanceof StringValue) {\n value = object.builtins.get(property.value);\n } else {\n throw new Error(`Cannot access property with non-string/non-number: got ${property.type}`);\n }\n } else {\n if (!(property instanceof StringValue)) {\n throw new Error(`Cannot access property with non-string: got ${property.type}`);\n }\n value = object.builtins.get(property.value);\n }\n return value instanceof RuntimeValue ? value : new UndefinedValue();\n }\n evaluateSet(node, environment) {\n const rhs = this.evaluate(node.value, environment);\n if (node.assignee.type === \"Identifier\") {\n const variableName = node.assignee.value;\n environment.setVariable(variableName, rhs);\n } else if (node.assignee.type === \"MemberExpression\") {\n const member = node.assignee;\n const object = this.evaluate(member.object, environment);\n if (!(object instanceof ObjectValue)) {\n throw new Error(\"Cannot assign to member of non-object\");\n }\n if (member.property.type !== \"Identifier\") {\n throw new Error(\"Cannot assign to member with non-identifier property\");\n }\n object.value.set(member.property.value, rhs);\n } else {\n throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(node.assignee)}`);\n }\n return new NullValue();\n }\n evaluateIf(node, environment) {\n const test = this.evaluate(node.test, environment);\n return this.evaluateBlock(test.__bool__().value ? node.body : node.alternate, environment);\n }\n evaluateFor(node, environment) {\n const scope = new Environment(environment);\n let test, iterable;\n if (node.iterable.type === \"SelectExpression\") {\n const select = node.iterable;\n iterable = this.evaluate(select.iterable, scope);\n test = select.test;\n } else {\n iterable = this.evaluate(node.iterable, scope);\n }\n if (!(iterable instanceof ArrayValue)) {\n throw new Error(`Expected iterable type in for loop: got ${iterable.type}`);\n }\n const items = [];\n const scopeUpdateFunctions = [];\n for (let i = 0; i < iterable.value.length; ++i) {\n const loopScope = new Environment(scope);\n const current = iterable.value[i];\n let scopeUpdateFunction;\n if (node.loopvar.type === \"Identifier\") {\n scopeUpdateFunction = (scope2) => scope2.setVariable(node.loopvar.value, current);\n } else if (node.loopvar.type === \"TupleLiteral\") {\n const loopvar = node.loopvar;\n if (current.type !== \"ArrayValue\") {\n throw new Error(`Cannot unpack non-iterable type: ${current.type}`);\n }\n const c = current;\n if (loopvar.value.length !== c.value.length) {\n throw new Error(`Too ${loopvar.value.length > c.value.length ? \"few\" : \"many\"} items to unpack`);\n }\n scopeUpdateFunction = (scope2) => {\n for (let j = 0; j < loopvar.value.length; ++j) {\n if (loopvar.value[j].type !== \"Identifier\") {\n throw new Error(`Cannot unpack non-identifier type: ${loopvar.value[j].type}`);\n }\n scope2.setVariable(loopvar.value[j].value, c.value[j]);\n }\n };\n } else {\n throw new Error(`Invalid loop variable(s): ${node.loopvar.type}`);\n }\n if (test) {\n scopeUpdateFunction(loopScope);\n const testValue = this.evaluate(test, loopScope);\n if (!testValue.__bool__().value) {\n continue;\n }\n }\n items.push(current);\n scopeUpdateFunctions.push(scopeUpdateFunction);\n }\n let result = \"\";\n let noIteration = true;\n for (let i = 0; i < items.length; ++i) {\n const loop = /* @__PURE__ */ new Map([\n [\"index\", new NumericValue(i + 1)],\n [\"index0\", new NumericValue(i)],\n [\"revindex\", new NumericValue(items.length - i)],\n [\"revindex0\", new NumericValue(items.length - i - 1)],\n [\"first\", new BooleanValue(i === 0)],\n [\"last\", new BooleanValue(i === items.length - 1)],\n [\"length\", new NumericValue(items.length)],\n [\"previtem\", i > 0 ? items[i - 1] : new UndefinedValue()],\n [\"nextitem\", i < items.length - 1 ? items[i + 1] : new UndefinedValue()]\n ]);\n scope.setVariable(\"loop\", new ObjectValue(loop));\n scopeUpdateFunctions[i](scope);\n const evaluated = this.evaluateBlock(node.body, scope);\n result += evaluated.value;\n noIteration = false;\n }\n if (noIteration) {\n const defaultEvaluated = this.evaluateBlock(node.defaultBlock, scope);\n result += defaultEvaluated.value;\n }\n return new StringValue(result);\n }\n /**\n * See https://jinja.palletsprojects.com/en/3.1.x/templates/#macros for more information.\n */\n evaluateMacro(node, environment) {\n environment.setVariable(\n node.name.value,\n new FunctionValue((args, scope) => {\n const macroScope = new Environment(scope);\n args = args.slice();\n let kwargs;\n if (args.at(-1)?.type === \"KeywordArgumentsValue\") {\n kwargs = args.pop();\n }\n for (let i = 0; i < node.args.length; ++i) {\n const nodeArg = node.args[i];\n const passedArg = args[i];\n if (nodeArg.type === \"Identifier\") {\n const identifier = nodeArg;\n if (!passedArg) {\n throw new Error(`Missing positional argument: ${identifier.value}`);\n }\n macroScope.setVariable(identifier.value, passedArg);\n } else if (nodeArg.type === \"KeywordArgumentExpression\") {\n const kwarg = nodeArg;\n const value = passedArg ?? // Try positional arguments first\n kwargs?.value.get(kwarg.key.value) ?? // Look in user-passed kwargs\n this.evaluate(kwarg.value, macroScope);\n macroScope.setVariable(kwarg.key.value, value);\n } else {\n throw new Error(`Unknown argument type: ${nodeArg.type}`);\n }\n }\n return this.evaluateBlock(node.body, macroScope);\n })\n );\n return new NullValue();\n }\n evaluate(statement, environment) {\n if (statement === void 0)\n return new UndefinedValue();\n switch (statement.type) {\n case \"Program\":\n return this.evalProgram(statement, environment);\n case \"Set\":\n return this.evaluateSet(statement, environment);\n case \"If\":\n return this.evaluateIf(statement, environment);\n case \"For\":\n return this.evaluateFor(statement, environment);\n case \"Macro\":\n return this.evaluateMacro(statement, environment);\n case \"NumericLiteral\":\n return new NumericValue(Number(statement.value));\n case \"StringLiteral\":\n return new StringValue(statement.value);\n case \"BooleanLiteral\":\n return new BooleanValue(statement.value);\n case \"ArrayLiteral\":\n return new ArrayValue(statement.value.map((x) => this.evaluate(x, environment)));\n case \"TupleLiteral\":\n return new TupleValue(statement.value.map((x) => this.evaluate(x, environment)));\n case \"ObjectLiteral\": {\n const mapping = /* @__PURE__ */ new Map();\n for (const [key, value] of statement.value) {\n const evaluatedKey = this.evaluate(key, environment);\n if (!(evaluatedKey instanceof StringValue)) {\n throw new Error(`Object keys must be strings: got ${evaluatedKey.type}`);\n }\n mapping.set(evaluatedKey.value, this.evaluate(value, environment));\n }\n return new ObjectValue(mapping);\n }\n case \"Identifier\":\n return this.evaluateIdentifier(statement, environment);\n case \"CallExpression\":\n return this.evaluateCallExpression(statement, environment);\n case \"MemberExpression\":\n return this.evaluateMemberExpression(statement, environment);\n case \"UnaryExpression\":\n return this.evaluateUnaryExpression(statement, environment);\n case \"BinaryExpression\":\n return this.evaluateBinaryExpression(statement, environment);\n case \"FilterExpression\":\n return this.evaluateFilterExpression(statement, environment);\n case \"TestExpression\":\n return this.evaluateTestExpression(statement, environment);\n default:\n throw new SyntaxError(`Unknown node type: ${statement.type}`);\n }\n }\n};\nfunction convertToRuntimeValues(input) {\n switch (typeof input) {\n case \"number\":\n return new NumericValue(input);\n case \"string\":\n return new StringValue(input);\n case \"boolean\":\n return new BooleanValue(input);\n case \"undefined\":\n return new UndefinedValue();\n case \"object\":\n if (input === null) {\n return new NullValue();\n } else if (Array.isArray(input)) {\n return new ArrayValue(input.map(convertToRuntimeValues));\n } else {\n return new ObjectValue(\n new Map(Object.entries(input).map(([key, value]) => [key, convertToRuntimeValues(value)]))\n );\n }\n case \"function\":\n return new FunctionValue((args, _scope) => {\n const result = input(...args.map((x) => x.value)) ?? null;\n return convertToRuntimeValues(result);\n });\n default:\n throw new Error(`Cannot convert to runtime value: ${input}`);\n }\n}\nfunction toJSON(input, indent, depth) {\n const currentDepth = depth ?? 0;\n switch (input.type) {\n case \"NullValue\":\n case \"UndefinedValue\":\n return \"null\";\n case \"NumericValue\":\n case \"StringValue\":\n case \"BooleanValue\":\n return JSON.stringify(input.value);\n case \"ArrayValue\":\n case \"ObjectValue\": {\n const indentValue = indent ? \" \".repeat(indent) : \"\";\n const basePadding = \"\\n\" + indentValue.repeat(currentDepth);\n const childrenPadding = basePadding + indentValue;\n if (input.type === \"ArrayValue\") {\n const core = input.value.map((x) => toJSON(x, indent, currentDepth + 1));\n return indent ? `[${childrenPadding}${core.join(`,${childrenPadding}`)}${basePadding}]` : `[${core.join(\", \")}]`;\n } else {\n const core = Array.from(input.value.entries()).map(([key, value]) => {\n const v = `\"${key}\": ${toJSON(value, indent, currentDepth + 1)}`;\n return indent ? `${childrenPadding}${v}` : v;\n });\n return indent ? `{${core.join(\",\")}${basePadding}}` : `{${core.join(\", \")}}`;\n }\n }\n default:\n throw new Error(`Cannot convert to JSON: ${input.type}`);\n }\n}\n\n// src/index.ts\nvar Template = class {\n parsed;\n /**\n * @param {string} template The template string\n */\n constructor(template) {\n const tokens = tokenize(template, {\n lstrip_blocks: true,\n trim_blocks: true\n });\n this.parsed = parse(tokens);\n }\n render(items) {\n const env = new Environment();\n env.set(\"false\", false);\n env.set(\"true\", true);\n env.set(\"raise_exception\", (args) => {\n throw new Error(args);\n });\n env.set(\"range\", range);\n for (const [key, value] of Object.entries(items)) {\n env.set(key, value);\n }\n const interpreter = new Interpreter(env);\n const result = interpreter.run(this.parsed);\n return result.value;\n }\n};\nexport {\n Environment,\n Interpreter,\n Template,\n parse,\n tokenize\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nconst backends = new Map();\nconst backendsSortedByPriority = [];\n/**\n * Register a backend.\n *\n * @param name - the name as a key to lookup as an execution provider.\n * @param backend - the backend object.\n * @param priority - an integer indicating the priority of the backend. Higher number means higher priority. if priority\n * < 0, it will be considered as a 'beta' version and will not be used as a fallback backend by default.\n *\n * @ignore\n */\nexport const registerBackend = (name, backend, priority) => {\n if (backend && typeof backend.init === 'function' && typeof backend.createInferenceSessionHandler === 'function') {\n const currentBackend = backends.get(name);\n if (currentBackend === undefined) {\n backends.set(name, { backend, priority });\n }\n else if (currentBackend.priority > priority) {\n // same name is already registered with a higher priority. skip registeration.\n return;\n }\n else if (currentBackend.priority === priority) {\n if (currentBackend.backend !== backend) {\n throw new Error(`cannot register backend \"${name}\" using priority ${priority}`);\n }\n }\n if (priority >= 0) {\n const i = backendsSortedByPriority.indexOf(name);\n if (i !== -1) {\n backendsSortedByPriority.splice(i, 1);\n }\n for (let i = 0; i < backendsSortedByPriority.length; i++) {\n if (backends.get(backendsSortedByPriority[i]).priority <= priority) {\n backendsSortedByPriority.splice(i, 0, name);\n return;\n }\n }\n backendsSortedByPriority.push(name);\n }\n return;\n }\n throw new TypeError('not a valid backend');\n};\n/**\n * Try to resolve and initialize a backend.\n *\n * @param backendName - the name of the backend.\n * @returns the backend instance if resolved and initialized successfully, or an error message if failed.\n */\nconst tryResolveAndInitializeBackend = async (backendName) => {\n const backendInfo = backends.get(backendName);\n if (!backendInfo) {\n return 'backend not found.';\n }\n if (backendInfo.initialized) {\n return backendInfo.backend;\n }\n else if (backendInfo.aborted) {\n return backendInfo.error;\n }\n else {\n const isInitializing = !!backendInfo.initPromise;\n try {\n if (!isInitializing) {\n backendInfo.initPromise = backendInfo.backend.init(backendName);\n }\n await backendInfo.initPromise;\n backendInfo.initialized = true;\n return backendInfo.backend;\n }\n catch (e) {\n if (!isInitializing) {\n backendInfo.error = `${e}`;\n backendInfo.aborted = true;\n }\n return backendInfo.error;\n }\n finally {\n delete backendInfo.initPromise;\n }\n }\n};\n/**\n * Resolve execution providers from the specific session options.\n *\n * @param options - the session options object.\n * @returns a promise that resolves to a tuple of an initialized backend instance and a session options object with\n * filtered EP list.\n *\n * @ignore\n */\nexport const resolveBackendAndExecutionProviders = async (options) => {\n // extract backend hints from session options\n const eps = options.executionProviders || [];\n const backendHints = eps.map(i => typeof i === 'string' ? i : i.name);\n const backendNames = backendHints.length === 0 ? backendsSortedByPriority : backendHints;\n // try to resolve and initialize all requested backends\n let backend;\n const errors = [];\n const availableBackendNames = new Set();\n for (const backendName of backendNames) {\n const resolveResult = await tryResolveAndInitializeBackend(backendName);\n if (typeof resolveResult === 'string') {\n errors.push({ name: backendName, err: resolveResult });\n }\n else {\n if (!backend) {\n backend = resolveResult;\n }\n if (backend === resolveResult) {\n availableBackendNames.add(backendName);\n }\n }\n }\n // if no backend is available, throw error.\n if (!backend) {\n throw new Error(`no available backend found. ERR: ${errors.map(e => `[${e.name}] ${e.err}`).join(', ')}`);\n }\n // for each explicitly requested backend, if it's not available, output warning message.\n for (const { name, err } of errors) {\n if (backendHints.includes(name)) {\n // eslint-disable-next-line no-console\n console.warn(`removing requested execution provider \"${name}\" from session options because it is not available: ${err}`);\n }\n }\n const filteredEps = eps.filter(i => availableBackendNames.has(typeof i === 'string' ? i : i.name));\n return [\n backend, new Proxy(options, {\n get: (target, prop) => {\n if (prop === 'executionProviders') {\n return filteredEps;\n }\n return Reflect.get(target, prop);\n }\n })\n ];\n};\n//# sourceMappingURL=backend-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { version } from './version.js';\nlet logLevelValue = 'warning';\nexport const env = {\n wasm: {},\n webgl: {},\n webgpu: {},\n versions: { common: version },\n set logLevel(value) {\n if (value === undefined) {\n return;\n }\n if (typeof value !== 'string' || ['verbose', 'info', 'warning', 'error', 'fatal'].indexOf(value) === -1) {\n throw new Error(`Unsupported logging level: ${value}`);\n }\n logLevelValue = value;\n },\n get logLevel() {\n return logLevelValue;\n },\n};\n// set property 'logLevel' so that they can be correctly transferred to worker by `postMessage()`.\nObject.defineProperty(env, 'logLevel', { enumerable: true });\n//# sourceMappingURL=env-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { env as envImpl } from './env-impl.js';\n/**\n * Represent a set of flags as a global singleton.\n */\nexport const env = envImpl;\n//# sourceMappingURL=env.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { resolveBackendAndExecutionProviders } from './backend-impl.js';\nimport { Tensor } from './tensor.js';\nimport { TRACE_FUNC_BEGIN, TRACE_FUNC_END } from './trace.js';\nexport class InferenceSession {\n constructor(handler) {\n this.handler = handler;\n }\n async run(feeds, arg1, arg2) {\n TRACE_FUNC_BEGIN();\n const fetches = {};\n let options = {};\n // check inputs\n if (typeof feeds !== 'object' || feeds === null || feeds instanceof Tensor || Array.isArray(feeds)) {\n throw new TypeError('\\'feeds\\' must be an object that use input names as keys and OnnxValue as corresponding values.');\n }\n let isFetchesEmpty = true;\n // determine which override is being used\n if (typeof arg1 === 'object') {\n if (arg1 === null) {\n throw new TypeError('Unexpected argument[1]: cannot be null.');\n }\n if (arg1 instanceof Tensor) {\n throw new TypeError('\\'fetches\\' cannot be a Tensor');\n }\n if (Array.isArray(arg1)) {\n if (arg1.length === 0) {\n throw new TypeError('\\'fetches\\' cannot be an empty array.');\n }\n isFetchesEmpty = false;\n // output names\n for (const name of arg1) {\n if (typeof name !== 'string') {\n throw new TypeError('\\'fetches\\' must be a string array or an object.');\n }\n if (this.outputNames.indexOf(name) === -1) {\n throw new RangeError(`'fetches' contains invalid output name: ${name}.`);\n }\n fetches[name] = null;\n }\n if (typeof arg2 === 'object' && arg2 !== null) {\n options = arg2;\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else {\n // decide whether arg1 is fetches or options\n // if any output name is present and its value is valid OnnxValue, we consider it fetches\n let isFetches = false;\n const arg1Keys = Object.getOwnPropertyNames(arg1);\n for (const name of this.outputNames) {\n if (arg1Keys.indexOf(name) !== -1) {\n const v = arg1[name];\n if (v === null || v instanceof Tensor) {\n isFetches = true;\n isFetchesEmpty = false;\n fetches[name] = v;\n }\n }\n }\n if (isFetches) {\n if (typeof arg2 === 'object' && arg2 !== null) {\n options = arg2;\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else {\n options = arg1;\n }\n }\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('Unexpected argument[1]: must be \\'fetches\\' or \\'options\\'.');\n }\n // check if all inputs are in feed\n for (const name of this.inputNames) {\n if (typeof feeds[name] === 'undefined') {\n throw new Error(`input '${name}' is missing in 'feeds'.`);\n }\n }\n // if no fetches is specified, we use the full output names list\n if (isFetchesEmpty) {\n for (const name of this.outputNames) {\n fetches[name] = null;\n }\n }\n // feeds, fetches and options are prepared\n const results = await this.handler.run(feeds, fetches, options);\n const returnValue = {};\n for (const key in results) {\n if (Object.hasOwnProperty.call(results, key)) {\n const result = results[key];\n if (result instanceof Tensor) {\n returnValue[key] = result;\n }\n else {\n returnValue[key] = new Tensor(result.type, result.data, result.dims);\n }\n }\n }\n TRACE_FUNC_END();\n return returnValue;\n }\n async release() {\n return this.handler.dispose();\n }\n static async create(arg0, arg1, arg2, arg3) {\n TRACE_FUNC_BEGIN();\n // either load from a file or buffer\n let filePathOrUint8Array;\n let options = {};\n if (typeof arg0 === 'string') {\n filePathOrUint8Array = arg0;\n if (typeof arg1 === 'object' && arg1 !== null) {\n options = arg1;\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else if (arg0 instanceof Uint8Array) {\n filePathOrUint8Array = arg0;\n if (typeof arg1 === 'object' && arg1 !== null) {\n options = arg1;\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else if (arg0 instanceof ArrayBuffer ||\n (typeof SharedArrayBuffer !== 'undefined' && arg0 instanceof SharedArrayBuffer)) {\n const buffer = arg0;\n let byteOffset = 0;\n let byteLength = arg0.byteLength;\n if (typeof arg1 === 'object' && arg1 !== null) {\n options = arg1;\n }\n else if (typeof arg1 === 'number') {\n byteOffset = arg1;\n if (!Number.isSafeInteger(byteOffset)) {\n throw new RangeError('\\'byteOffset\\' must be an integer.');\n }\n if (byteOffset < 0 || byteOffset >= buffer.byteLength) {\n throw new RangeError(`'byteOffset' is out of range [0, ${buffer.byteLength}).`);\n }\n byteLength = arg0.byteLength - byteOffset;\n if (typeof arg2 === 'number') {\n byteLength = arg2;\n if (!Number.isSafeInteger(byteLength)) {\n throw new RangeError('\\'byteLength\\' must be an integer.');\n }\n if (byteLength <= 0 || byteOffset + byteLength > buffer.byteLength) {\n throw new RangeError(`'byteLength' is out of range (0, ${buffer.byteLength - byteOffset}].`);\n }\n if (typeof arg3 === 'object' && arg3 !== null) {\n options = arg3;\n }\n else if (typeof arg3 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'byteLength\\' must be a number.');\n }\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n filePathOrUint8Array = new Uint8Array(buffer, byteOffset, byteLength);\n }\n else {\n throw new TypeError('Unexpected argument[0]: must be \\'path\\' or \\'buffer\\'.');\n }\n // resolve backend, update session options with validated EPs, and create session handler\n const [backend, optionsWithValidatedEPs] = await resolveBackendAndExecutionProviders(options);\n const handler = await backend.createInferenceSessionHandler(filePathOrUint8Array, optionsWithValidatedEPs);\n TRACE_FUNC_END();\n return new InferenceSession(handler);\n }\n startProfiling() {\n this.handler.startProfiling();\n }\n endProfiling() {\n this.handler.endProfiling();\n }\n get inputNames() {\n return this.handler.inputNames;\n }\n get outputNames() {\n return this.handler.outputNames;\n }\n}\n//# sourceMappingURL=inference-session-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { InferenceSession as InferenceSessionImpl } from './inference-session-impl.js';\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const InferenceSession = InferenceSessionImpl;\n//# sourceMappingURL=inference-session.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n/**\n * implementation of Tensor.toDataURL()\n */\nexport const tensorToDataURL = (tensor, options) => {\n const canvas = typeof document !== 'undefined' ? document.createElement('canvas') : (new OffscreenCanvas(1, 1));\n canvas.width = tensor.dims[3];\n canvas.height = tensor.dims[2];\n const pixels2DContext = canvas.getContext('2d');\n if (pixels2DContext != null) {\n // Default values for height and width & format\n let width;\n let height;\n if (options?.tensorLayout !== undefined && options.tensorLayout === 'NHWC') {\n width = tensor.dims[2];\n height = tensor.dims[3];\n }\n else { // Default layout is NCWH\n width = tensor.dims[3];\n height = tensor.dims[2];\n }\n const inputformat = options?.format !== undefined ? options.format : 'RGB';\n const norm = options?.norm;\n let normMean;\n let normBias;\n if (norm === undefined || norm.mean === undefined) {\n normMean = [255, 255, 255, 255];\n }\n else {\n if (typeof (norm.mean) === 'number') {\n normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n }\n else {\n normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 0];\n if (norm.mean[3] !== undefined) {\n normMean[3] = norm.mean[3];\n }\n }\n }\n if (norm === undefined || norm.bias === undefined) {\n normBias = [0, 0, 0, 0];\n }\n else {\n if (typeof (norm.bias) === 'number') {\n normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n }\n else {\n normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];\n if (norm.bias[3] !== undefined) {\n normBias[3] = norm.bias[3];\n }\n }\n }\n const stride = height * width;\n // Default pointer assignments\n let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;\n // Updating the pointer assignments based on the input image format\n if (inputformat === 'RGBA') {\n rTensorPointer = 0;\n gTensorPointer = stride;\n bTensorPointer = stride * 2;\n aTensorPointer = stride * 3;\n }\n else if (inputformat === 'RGB') {\n rTensorPointer = 0;\n gTensorPointer = stride;\n bTensorPointer = stride * 2;\n }\n else if (inputformat === 'RBG') {\n rTensorPointer = 0;\n bTensorPointer = stride;\n gTensorPointer = stride * 2;\n }\n for (let i = 0; i < height; i++) {\n for (let j = 0; j < width; j++) {\n const R = (tensor.data[rTensorPointer++] - normBias[0]) * normMean[0]; // R value\n const G = (tensor.data[gTensorPointer++] - normBias[1]) * normMean[1]; // G value\n const B = (tensor.data[bTensorPointer++] - normBias[2]) * normMean[2]; // B value\n const A = aTensorPointer === -1 ?\n 255 :\n (tensor.data[aTensorPointer++] - normBias[3]) * normMean[3]; // A value\n // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n pixels2DContext.fillStyle = 'rgba(' + R + ',' + G + ',' + B + ',' + A + ')';\n pixels2DContext.fillRect(j, i, 1, 1);\n }\n }\n if ('toDataURL' in canvas) {\n return canvas.toDataURL();\n }\n else {\n throw new Error('toDataURL is not supported');\n }\n }\n else {\n throw new Error('Can not access image data');\n }\n};\n/**\n * implementation of Tensor.toImageData()\n */\nexport const tensorToImageData = (tensor, options) => {\n const pixels2DContext = typeof document !== 'undefined' ?\n document.createElement('canvas').getContext('2d') :\n new OffscreenCanvas(1, 1).getContext('2d');\n let image;\n if (pixels2DContext != null) {\n // Default values for height and width & format\n let width;\n let height;\n let channels;\n if (options?.tensorLayout !== undefined && options.tensorLayout === 'NHWC') {\n width = tensor.dims[2];\n height = tensor.dims[1];\n channels = tensor.dims[3];\n }\n else { // Default layout is NCWH\n width = tensor.dims[3];\n height = tensor.dims[2];\n channels = tensor.dims[1];\n }\n const inputformat = options !== undefined ? (options.format !== undefined ? options.format : 'RGB') : 'RGB';\n const norm = options?.norm;\n let normMean;\n let normBias;\n if (norm === undefined || norm.mean === undefined) {\n normMean = [255, 255, 255, 255];\n }\n else {\n if (typeof (norm.mean) === 'number') {\n normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n }\n else {\n normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 255];\n if (norm.mean[3] !== undefined) {\n normMean[3] = norm.mean[3];\n }\n }\n }\n if (norm === undefined || norm.bias === undefined) {\n normBias = [0, 0, 0, 0];\n }\n else {\n if (typeof (norm.bias) === 'number') {\n normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n }\n else {\n normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];\n if (norm.bias[3] !== undefined) {\n normBias[3] = norm.bias[3];\n }\n }\n }\n const stride = height * width;\n if (options !== undefined) {\n if (options.format !== undefined && (channels === 4 && options.format !== 'RGBA') ||\n (channels === 3 && (options.format !== 'RGB' && options.format !== 'BGR'))) {\n throw new Error('Tensor format doesn\\'t match input tensor dims');\n }\n }\n // Default pointer assignments\n const step = 4;\n let rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;\n let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;\n // Updating the pointer assignments based on the input image format\n if (inputformat === 'RGBA') {\n rTensorPointer = 0;\n gTensorPointer = stride;\n bTensorPointer = stride * 2;\n aTensorPointer = stride * 3;\n }\n else if (inputformat === 'RGB') {\n rTensorPointer = 0;\n gTensorPointer = stride;\n bTensorPointer = stride * 2;\n }\n else if (inputformat === 'RBG') {\n rTensorPointer = 0;\n bTensorPointer = stride;\n gTensorPointer = stride * 2;\n }\n image = pixels2DContext.createImageData(width, height);\n for (let i = 0; i < height * width; rImagePointer += step, gImagePointer += step, bImagePointer += step, aImagePointer += step, i++) {\n image.data[rImagePointer] = (tensor.data[rTensorPointer++] - normBias[0]) * normMean[0]; // R value\n image.data[gImagePointer] = (tensor.data[gTensorPointer++] - normBias[1]) * normMean[1]; // G value\n image.data[bImagePointer] = (tensor.data[bTensorPointer++] - normBias[2]) * normMean[2]; // B value\n image.data[aImagePointer] = aTensorPointer === -1 ?\n 255 :\n (tensor.data[aTensorPointer++] - normBias[3]) * normMean[3]; // A value\n }\n }\n else {\n throw new Error('Can not access image data');\n }\n return image;\n};\n//# sourceMappingURL=tensor-conversion-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { Tensor } from './tensor-impl.js';\n/**\n * Create a new tensor object from image object\n *\n * @param buffer - Extracted image buffer data - assuming RGBA format\n * @param imageFormat - input image configuration - required configurations height, width, format\n * @param tensorFormat - output tensor configuration - Default is RGB format\n */\nexport const bufferToTensor = (buffer, options) => {\n if (buffer === undefined) {\n throw new Error('Image buffer must be defined');\n }\n if (options.height === undefined || options.width === undefined) {\n throw new Error('Image height and width must be defined');\n }\n if (options.tensorLayout === 'NHWC') {\n throw new Error('NHWC Tensor layout is not supported yet');\n }\n const { height, width } = options;\n const norm = options.norm ?? { mean: 255, bias: 0 };\n let normMean;\n let normBias;\n if (typeof (norm.mean) === 'number') {\n normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n }\n else {\n normMean = [norm.mean[0], norm.mean[1], norm.mean[2], norm.mean[3] ?? 255];\n }\n if (typeof (norm.bias) === 'number') {\n normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n }\n else {\n normBias = [norm.bias[0], norm.bias[1], norm.bias[2], norm.bias[3] ?? 0];\n }\n const inputformat = options.format !== undefined ? options.format : 'RGBA';\n // default value is RGBA since imagedata and HTMLImageElement uses it\n const outputformat = options.tensorFormat !== undefined ? (options.tensorFormat !== undefined ? options.tensorFormat : 'RGB') : 'RGB';\n const stride = height * width;\n const float32Data = outputformat === 'RGBA' ? new Float32Array(stride * 4) : new Float32Array(stride * 3);\n // Default pointer assignments\n let step = 4, rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;\n let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1;\n // Updating the pointer assignments based on the input image format\n if (inputformat === 'RGB') {\n step = 3;\n rImagePointer = 0;\n gImagePointer = 1;\n bImagePointer = 2;\n aImagePointer = -1;\n }\n // Updating the pointer assignments based on the output tensor format\n if (outputformat === 'RGBA') {\n aTensorPointer = stride * 3;\n }\n else if (outputformat === 'RBG') {\n rTensorPointer = 0;\n bTensorPointer = stride;\n gTensorPointer = stride * 2;\n }\n else if (outputformat === 'BGR') {\n bTensorPointer = 0;\n gTensorPointer = stride;\n rTensorPointer = stride * 2;\n }\n for (let i = 0; i < stride; i++, rImagePointer += step, bImagePointer += step, gImagePointer += step, aImagePointer += step) {\n float32Data[rTensorPointer++] = (buffer[rImagePointer] + normBias[0]) / normMean[0];\n float32Data[gTensorPointer++] = (buffer[gImagePointer] + normBias[1]) / normMean[1];\n float32Data[bTensorPointer++] = (buffer[bImagePointer] + normBias[2]) / normMean[2];\n if (aTensorPointer !== -1 && aImagePointer !== -1) {\n float32Data[aTensorPointer++] = (buffer[aImagePointer] + normBias[3]) / normMean[3];\n }\n }\n // Float32Array -> ort.Tensor\n const outputTensor = outputformat === 'RGBA' ? new Tensor('float32', float32Data, [1, 4, height, width]) :\n new Tensor('float32', float32Data, [1, 3, height, width]);\n return outputTensor;\n};\n/**\n * implementation of Tensor.fromImage().\n */\nexport const tensorFromImage = async (image, options) => {\n // checking the type of image object\n const isHTMLImageEle = typeof (HTMLImageElement) !== 'undefined' && image instanceof HTMLImageElement;\n const isImageDataEle = typeof (ImageData) !== 'undefined' && image instanceof ImageData;\n const isImageBitmap = typeof (ImageBitmap) !== 'undefined' && image instanceof ImageBitmap;\n const isString = typeof image === 'string';\n let data;\n let bufferToTensorOptions = options ?? {};\n const createCanvas = () => {\n if (typeof document !== 'undefined') {\n return document.createElement('canvas');\n }\n else if (typeof OffscreenCanvas !== 'undefined') {\n return new OffscreenCanvas(1, 1);\n }\n else {\n throw new Error('Canvas is not supported');\n }\n };\n const createCanvasContext = (canvas) => {\n if (canvas instanceof HTMLCanvasElement) {\n return canvas.getContext('2d');\n }\n else if (canvas instanceof OffscreenCanvas) {\n return canvas.getContext('2d');\n }\n else {\n return null;\n }\n };\n // filling and checking image configuration options\n if (isHTMLImageEle) {\n // HTMLImageElement - image object - format is RGBA by default\n const canvas = createCanvas();\n canvas.width = image.width;\n canvas.height = image.height;\n const pixels2DContext = createCanvasContext(canvas);\n if (pixels2DContext != null) {\n let height = image.height;\n let width = image.width;\n if (options !== undefined && options.resizedHeight !== undefined && options.resizedWidth !== undefined) {\n height = options.resizedHeight;\n width = options.resizedWidth;\n }\n if (options !== undefined) {\n bufferToTensorOptions = options;\n if (options.tensorFormat !== undefined) {\n throw new Error('Image input config format must be RGBA for HTMLImageElement');\n }\n else {\n bufferToTensorOptions.tensorFormat = 'RGBA';\n }\n bufferToTensorOptions.height = height;\n bufferToTensorOptions.width = width;\n }\n else {\n bufferToTensorOptions.tensorFormat = 'RGBA';\n bufferToTensorOptions.height = height;\n bufferToTensorOptions.width = width;\n }\n pixels2DContext.drawImage(image, 0, 0);\n data = pixels2DContext.getImageData(0, 0, width, height).data;\n }\n else {\n throw new Error('Can not access image data');\n }\n }\n else if (isImageDataEle) {\n let height;\n let width;\n if (options !== undefined && options.resizedWidth !== undefined && options.resizedHeight !== undefined) {\n height = options.resizedHeight;\n width = options.resizedWidth;\n }\n else {\n height = image.height;\n width = image.width;\n }\n if (options !== undefined) {\n bufferToTensorOptions = options;\n }\n bufferToTensorOptions.format = 'RGBA';\n bufferToTensorOptions.height = height;\n bufferToTensorOptions.width = width;\n if (options !== undefined) {\n const tempCanvas = createCanvas();\n tempCanvas.width = width;\n tempCanvas.height = height;\n const pixels2DContext = createCanvasContext(tempCanvas);\n if (pixels2DContext != null) {\n pixels2DContext.putImageData(image, 0, 0);\n data = pixels2DContext.getImageData(0, 0, width, height).data;\n }\n else {\n throw new Error('Can not access image data');\n }\n }\n else {\n data = image.data;\n }\n }\n else if (isImageBitmap) {\n // ImageBitmap - image object - format must be provided by user\n if (options === undefined) {\n throw new Error('Please provide image config with format for Imagebitmap');\n }\n const canvas = createCanvas();\n canvas.width = image.width;\n canvas.height = image.height;\n const pixels2DContext = createCanvasContext(canvas);\n if (pixels2DContext != null) {\n const height = image.height;\n const width = image.width;\n pixels2DContext.drawImage(image, 0, 0, width, height);\n data = pixels2DContext.getImageData(0, 0, width, height).data;\n bufferToTensorOptions.height = height;\n bufferToTensorOptions.width = width;\n return bufferToTensor(data, bufferToTensorOptions);\n }\n else {\n throw new Error('Can not access image data');\n }\n }\n else if (isString) {\n return new Promise((resolve, reject) => {\n const canvas = createCanvas();\n const context = createCanvasContext(canvas);\n if (!image || !context) {\n return reject();\n }\n const newImage = new Image();\n newImage.crossOrigin = 'Anonymous';\n newImage.src = image;\n newImage.onload = () => {\n canvas.width = newImage.width;\n canvas.height = newImage.height;\n context.drawImage(newImage, 0, 0, canvas.width, canvas.height);\n const img = context.getImageData(0, 0, canvas.width, canvas.height);\n bufferToTensorOptions.height = canvas.height;\n bufferToTensorOptions.width = canvas.width;\n resolve(bufferToTensor(img.data, bufferToTensorOptions));\n };\n });\n }\n else {\n throw new Error('Input data provided is not supported - aborted tensor creation');\n }\n if (data !== undefined) {\n return bufferToTensor(data, bufferToTensorOptions);\n }\n else {\n throw new Error('Input data provided is not supported - aborted tensor creation');\n }\n};\n/**\n * implementation of Tensor.fromTexture().\n */\nexport const tensorFromTexture = (texture, options) => {\n const { width, height, download, dispose } = options;\n // Always assume RGBAF32. TODO: support different texture format\n const dims = [1, height, width, 4];\n return new Tensor({ location: 'texture', type: 'float32', texture, dims, download, dispose });\n};\n/**\n * implementation of Tensor.fromGpuBuffer().\n */\nexport const tensorFromGpuBuffer = (gpuBuffer, options) => {\n const { dataType, dims, download, dispose } = options;\n return new Tensor({ location: 'gpu-buffer', type: dataType ?? 'float32', gpuBuffer, dims, download, dispose });\n};\n/**\n * implementation of Tensor.fromPinnedBuffer().\n */\nexport const tensorFromPinnedBuffer = (type, buffer, dims) => new Tensor({ location: 'cpu-pinned', type, data: buffer, dims: dims ?? [buffer.length] });\n//# sourceMappingURL=tensor-factory-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.\nexport const NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = new Map([\n ['float32', Float32Array],\n ['uint8', Uint8Array],\n ['int8', Int8Array],\n ['uint16', Uint16Array],\n ['int16', Int16Array],\n ['int32', Int32Array],\n ['bool', Uint8Array],\n ['float64', Float64Array],\n ['uint32', Uint32Array],\n]);\n// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.\nexport const NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = new Map([\n [Float32Array, 'float32'],\n [Uint8Array, 'uint8'],\n [Int8Array, 'int8'],\n [Uint16Array, 'uint16'],\n [Int16Array, 'int16'],\n [Int32Array, 'int32'],\n [Float64Array, 'float64'],\n [Uint32Array, 'uint32'],\n]);\n// the following code allows delaying execution of BigInt/Float16Array checking. This allows lazy initialization for\n// NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP and NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP, which allows BigInt/Float16Array\n// polyfill if available.\nlet isTypedArrayChecked = false;\nexport const checkTypedArray = () => {\n if (!isTypedArrayChecked) {\n isTypedArrayChecked = true;\n const isBigInt64ArrayAvailable = typeof BigInt64Array !== 'undefined' && BigInt64Array.from;\n const isBigUint64ArrayAvailable = typeof BigUint64Array !== 'undefined' && BigUint64Array.from;\n const isFloat16ArrayAvailable = typeof Float16Array !== 'undefined' && Float16Array.from;\n if (isBigInt64ArrayAvailable) {\n NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('int64', BigInt64Array);\n NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, 'int64');\n }\n if (isBigUint64ArrayAvailable) {\n NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('uint64', BigUint64Array);\n NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, 'uint64');\n }\n if (isFloat16ArrayAvailable) {\n NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('float16', Float16Array);\n NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(Float16Array, 'float16');\n }\n else {\n // if Float16Array is not available, use 'Uint16Array' to store the data.\n NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('float16', Uint16Array);\n }\n }\n};\n//# sourceMappingURL=tensor-impl-type-mapping.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { tensorToDataURL, tensorToImageData } from './tensor-conversion-impl.js';\nimport { tensorFromGpuBuffer, tensorFromImage, tensorFromPinnedBuffer, tensorFromTexture } from './tensor-factory-impl.js';\nimport { checkTypedArray, NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP, NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP } from './tensor-impl-type-mapping.js';\nimport { calculateSize, tensorReshape } from './tensor-utils-impl.js';\n/**\n * the implementation of Tensor interface.\n *\n * @ignore\n */\nexport class Tensor {\n /**\n * implementation.\n */\n constructor(arg0, arg1, arg2) {\n // perform one-time check for BigInt/Float16Array support\n checkTypedArray();\n let type;\n let dims;\n if (typeof arg0 === 'object' && 'location' in arg0) {\n //\n // constructing tensor from specific location\n //\n this.dataLocation = arg0.location;\n type = arg0.type;\n dims = arg0.dims;\n switch (arg0.location) {\n case 'cpu-pinned': {\n const expectedTypedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(type);\n if (!expectedTypedArrayConstructor) {\n throw new TypeError(`unsupported type \"${type}\" to create tensor from pinned buffer`);\n }\n if (!(arg0.data instanceof expectedTypedArrayConstructor)) {\n throw new TypeError(`buffer should be of type ${expectedTypedArrayConstructor.name}`);\n }\n this.cpuData = arg0.data;\n break;\n }\n case 'texture': {\n if (type !== 'float32') {\n throw new TypeError(`unsupported type \"${type}\" to create tensor from texture`);\n }\n this.gpuTextureData = arg0.texture;\n this.downloader = arg0.download;\n this.disposer = arg0.dispose;\n break;\n }\n case 'gpu-buffer': {\n if ((type !== 'float32' && type !== 'float16' && type !== 'int32' && type !== 'int64' && type !== 'uint32' &&\n type !== 'uint8' && type !== 'bool')) {\n throw new TypeError(`unsupported type \"${type}\" to create tensor from gpu buffer`);\n }\n this.gpuBufferData = arg0.gpuBuffer;\n this.downloader = arg0.download;\n this.disposer = arg0.dispose;\n break;\n }\n default:\n throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`);\n }\n }\n else {\n //\n // constructing tensor of location 'cpu'\n //\n let data;\n let maybeDims;\n // check whether arg0 is type or data\n if (typeof arg0 === 'string') {\n //\n // Override: constructor(type, data, ...)\n //\n type = arg0;\n maybeDims = arg2;\n if (arg0 === 'string') {\n // string tensor\n if (!Array.isArray(arg1)) {\n throw new TypeError('A string tensor\\'s data must be a string array.');\n }\n // we don't check whether every element in the array is string; this is too slow. we assume it's correct and\n // error will be populated at inference\n data = arg1;\n }\n else {\n // numeric tensor\n const typedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(arg0);\n if (typedArrayConstructor === undefined) {\n throw new TypeError(`Unsupported tensor type: ${arg0}.`);\n }\n if (Array.isArray(arg1)) {\n if (arg0 === 'float16' && typedArrayConstructor === Uint16Array) {\n // When no Float16Array polyfill is used, we cannot create 'float16' tensor from number array.\n //\n // Throw error here because when user try to use number array as data,\n // e.g. new Tensor('float16', [1, 2, 3, 4], dims)), it will actually call\n // Uint16Array.from(arg1) which generates wrong data.\n throw new TypeError('Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.');\n }\n else if (arg0 === 'uint64' || arg0 === 'int64') {\n // use 'as any' here because:\n // 1. TypeScript's check on type of 'Array.isArray()' does not work with readonly arrays.\n // see https://github.com/microsoft/TypeScript/issues/17002\n // 2. TypeScript's check on union type of '(BigInt64ArrayConstructor|BigUint64ArrayConstructor).from()'\n // does not accept parameter mapFn.\n // 3. parameters of 'SupportedTypedArrayConstructors.from()' does not match the requirement of the union\n // type.\n // assume 'arg1' is of type \"readonly number[]|readonly bigint[]\" here.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data = typedArrayConstructor.from(arg1, BigInt);\n }\n else {\n // assume 'arg1' is of type \"readonly number[]\" here.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data = typedArrayConstructor.from(arg1);\n }\n }\n else if (arg1 instanceof typedArrayConstructor) {\n data = arg1;\n }\n else {\n throw new TypeError(`A ${type} tensor's data must be type of ${typedArrayConstructor}`);\n }\n }\n }\n else {\n //\n // Override: constructor(data, ...)\n //\n maybeDims = arg1;\n if (Array.isArray(arg0)) {\n // only boolean[] and string[] is supported\n if (arg0.length === 0) {\n throw new TypeError('Tensor type cannot be inferred from an empty array.');\n }\n const firstElementType = typeof arg0[0];\n if (firstElementType === 'string') {\n type = 'string';\n data = arg0;\n }\n else if (firstElementType === 'boolean') {\n type = 'bool';\n // 'arg0' is of type 'boolean[]'. Uint8Array.from(boolean[]) actually works, but typescript thinks this is\n // wrong type. We use 'as any' to make it happy.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data = Uint8Array.from(arg0);\n }\n else {\n throw new TypeError(`Invalid element type of data array: ${firstElementType}.`);\n }\n }\n else {\n // get tensor type from TypedArray\n const mappedType = NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(arg0.constructor);\n if (mappedType === undefined) {\n throw new TypeError(`Unsupported type for tensor data: ${arg0.constructor}.`);\n }\n type = mappedType;\n data = arg0;\n }\n }\n // type and data is processed, now processing dims\n if (maybeDims === undefined) {\n // assume 1-D tensor if dims omitted\n maybeDims = [data.length];\n }\n else if (!Array.isArray(maybeDims)) {\n throw new TypeError('A tensor\\'s dims must be a number array');\n }\n dims = maybeDims;\n this.cpuData = data;\n this.dataLocation = 'cpu';\n }\n // perform check on dims\n const size = calculateSize(dims);\n // if data is on CPU, check whether data length matches tensor size\n if (this.cpuData && size !== this.cpuData.length) {\n throw new Error(`Tensor's size(${size}) does not match data length(${this.cpuData.length}).`);\n }\n this.type = type;\n this.dims = dims;\n this.size = size;\n }\n // #endregion\n // #region factory\n static async fromImage(image, options) {\n return tensorFromImage(image, options);\n }\n static fromTexture(texture, options) {\n return tensorFromTexture(texture, options);\n }\n static fromGpuBuffer(gpuBuffer, options) {\n return tensorFromGpuBuffer(gpuBuffer, options);\n }\n static fromPinnedBuffer(type, buffer, dims) {\n return tensorFromPinnedBuffer(type, buffer, dims);\n }\n // #endregion\n // #region conversions\n toDataURL(options) {\n return tensorToDataURL(this, options);\n }\n toImageData(options) {\n return tensorToImageData(this, options);\n }\n // #endregion\n // #region properties\n get data() {\n this.ensureValid();\n if (!this.cpuData) {\n throw new Error('The data is not on CPU. Use `getData()` to download GPU data to CPU, ' +\n 'or use `texture` or `gpuBuffer` property to access the GPU data directly.');\n }\n return this.cpuData;\n }\n get location() {\n return this.dataLocation;\n }\n get texture() {\n this.ensureValid();\n if (!this.gpuTextureData) {\n throw new Error('The data is not stored as a WebGL texture.');\n }\n return this.gpuTextureData;\n }\n get gpuBuffer() {\n this.ensureValid();\n if (!this.gpuBufferData) {\n throw new Error('The data is not stored as a WebGPU buffer.');\n }\n return this.gpuBufferData;\n }\n // #endregion\n // #region methods\n async getData(releaseData) {\n this.ensureValid();\n switch (this.dataLocation) {\n case 'cpu':\n case 'cpu-pinned':\n return this.data;\n case 'texture':\n case 'gpu-buffer': {\n if (!this.downloader) {\n throw new Error('The current tensor is not created with a specified data downloader.');\n }\n if (this.isDownloading) {\n throw new Error('The current tensor is being downloaded.');\n }\n try {\n this.isDownloading = true;\n const data = await this.downloader();\n this.downloader = undefined;\n this.dataLocation = 'cpu';\n this.cpuData = data;\n if (releaseData && this.disposer) {\n this.disposer();\n this.disposer = undefined;\n }\n return data;\n }\n finally {\n this.isDownloading = false;\n }\n }\n default:\n throw new Error(`cannot get data from location: ${this.dataLocation}`);\n }\n }\n dispose() {\n if (this.isDownloading) {\n throw new Error('The current tensor is being downloaded.');\n }\n if (this.disposer) {\n this.disposer();\n this.disposer = undefined;\n }\n this.cpuData = undefined;\n this.gpuTextureData = undefined;\n this.gpuBufferData = undefined;\n this.downloader = undefined;\n this.isDownloading = undefined;\n this.dataLocation = 'none';\n }\n // #endregion\n // #region tensor utilities\n ensureValid() {\n if (this.dataLocation === 'none') {\n throw new Error('The tensor is disposed.');\n }\n }\n reshape(dims) {\n this.ensureValid();\n if (this.downloader || this.disposer) {\n throw new Error('Cannot reshape a tensor that owns GPU resource.');\n }\n return tensorReshape(this, dims);\n }\n}\n//# sourceMappingURL=tensor-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { Tensor } from './tensor-impl.js';\n/**\n * calculate size from dims.\n *\n * @param dims the dims array. May be an illegal input.\n */\nexport const calculateSize = (dims) => {\n let size = 1;\n for (let i = 0; i < dims.length; i++) {\n const dim = dims[i];\n if (typeof dim !== 'number' || !Number.isSafeInteger(dim)) {\n throw new TypeError(`dims[${i}] must be an integer, got: ${dim}`);\n }\n if (dim < 0) {\n throw new RangeError(`dims[${i}] must be a non-negative integer, got: ${dim}`);\n }\n size *= dim;\n }\n return size;\n};\n/**\n * implementation of Tensor.reshape()\n */\nexport const tensorReshape = (tensor, dims) => {\n switch (tensor.location) {\n case 'cpu':\n return new Tensor(tensor.type, tensor.data, dims);\n case 'cpu-pinned':\n return new Tensor({\n location: 'cpu-pinned',\n data: tensor.data,\n type: tensor.type,\n dims,\n });\n case 'texture':\n return new Tensor({\n location: 'texture',\n texture: tensor.texture,\n type: tensor.type,\n dims,\n });\n case 'gpu-buffer':\n return new Tensor({\n location: 'gpu-buffer',\n gpuBuffer: tensor.gpuBuffer,\n type: tensor.type,\n dims,\n });\n default:\n throw new Error(`tensorReshape: tensor location ${tensor.location} is not supported`);\n }\n};\n//# sourceMappingURL=tensor-utils-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { Tensor as TensorImpl } from './tensor-impl.js';\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const Tensor = TensorImpl;\n//# sourceMappingURL=tensor.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { env } from './env-impl.js';\n/**\n * @ignore\n */\nexport const TRACE = (deviceType, label) => {\n if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n return;\n }\n // eslint-disable-next-line no-console\n console.timeStamp(`${deviceType}::ORT::${label}`);\n};\nconst TRACE_FUNC = (msg, extraMsg) => {\n const stack = new Error().stack?.split(/\\r\\n|\\r|\\n/g) || [];\n let hasTraceFunc = false;\n for (let i = 0; i < stack.length; i++) {\n if (hasTraceFunc && !stack[i].includes('TRACE_FUNC')) {\n let label = `FUNC_${msg}::${stack[i].trim().split(' ')[1]}`;\n if (extraMsg) {\n label += `::${extraMsg}`;\n }\n TRACE('CPU', label);\n return;\n }\n if (stack[i].includes('TRACE_FUNC')) {\n hasTraceFunc = true;\n }\n }\n};\n/**\n * @ignore\n */\nexport const TRACE_FUNC_BEGIN = (extraMsg) => {\n if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n return;\n }\n TRACE_FUNC('BEGIN', extraMsg);\n};\n/**\n * @ignore\n */\nexport const TRACE_FUNC_END = (extraMsg) => {\n if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n return;\n }\n TRACE_FUNC('END', extraMsg);\n};\n//# sourceMappingURL=trace.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { resolveBackendAndExecutionProviders } from './backend-impl.js';\nimport { Tensor } from './tensor.js';\nconst noBackendErrMsg = 'Training backend could not be resolved. ' +\n 'Make sure you\\'re using the correct configuration & WebAssembly files.';\nexport class TrainingSession {\n constructor(handler, hasOptimizerModel, hasEvalModel) {\n this.handler = handler;\n this.hasOptimizerModel = hasOptimizerModel;\n this.hasEvalModel = hasEvalModel;\n }\n get trainingInputNames() {\n return this.handler.inputNames;\n }\n get trainingOutputNames() {\n return this.handler.outputNames;\n }\n get evalInputNames() {\n if (this.hasEvalModel) {\n return this.handler.evalInputNames;\n }\n else {\n throw new Error('This training session has no evalModel loaded.');\n }\n }\n get evalOutputNames() {\n if (this.hasEvalModel) {\n return this.handler.evalOutputNames;\n }\n else {\n throw new Error('This training session has no evalModel loaded.');\n }\n }\n static async create(trainingOptions, sessionOptions) {\n const evalModel = trainingOptions.evalModel || '';\n const optimizerModel = trainingOptions.optimizerModel || '';\n const options = sessionOptions || {};\n // resolve backend, update session options with validated EPs, and create session handler\n const [backend, optionsWithValidatedEPs] = await resolveBackendAndExecutionProviders(options);\n if (backend.createTrainingSessionHandler) {\n const handler = await backend.createTrainingSessionHandler(trainingOptions.checkpointState, trainingOptions.trainModel, evalModel, optimizerModel, optionsWithValidatedEPs);\n return new TrainingSession(handler, !!trainingOptions.optimizerModel, !!trainingOptions.evalModel);\n }\n else {\n throw new Error(noBackendErrMsg);\n }\n }\n /**\n * Helper function for runTrainStep and future runStep methods that handles the type-narrowing conversion from\n * the given parameters to SessionHandler.FetchesType and RunOptions.\n *\n * @param inputNames the feeds object is checked that they contain all input names in the provided list of input\n * names.\n * @param outputNames the fetches object is checked that their keys match up with valid names in the list of output\n * names.\n * @param feeds the required input\n * @param arg1 narrowed & converted into the SessionHandler.FetchesType or RunOptions object\n * @param arg2 optional RunOptions object.\n * @returns\n */\n typeNarrowingForRunStep(inputNames, outputNames, feeds, arg1, arg2) {\n const fetches = {};\n let options = {};\n // check inputs\n if (typeof feeds !== 'object' || feeds === null || feeds instanceof Tensor || Array.isArray(feeds)) {\n throw new TypeError('\\'feeds\\' must be an object that use input names as keys and OnnxValue as corresponding values.');\n }\n let isFetchesEmpty = true;\n // determine which override is being used\n if (typeof arg1 === 'object') {\n if (arg1 === null) {\n throw new TypeError('Unexpected argument[1]: cannot be null.');\n }\n if (arg1 instanceof Tensor) {\n throw new TypeError('\\'fetches\\' cannot be a Tensor');\n }\n if (Array.isArray(arg1)) {\n if (arg1.length === 0) {\n throw new TypeError('\\'fetches\\' cannot be an empty array.');\n }\n isFetchesEmpty = false;\n // output names\n for (const name of arg1) {\n if (typeof name !== 'string') {\n throw new TypeError('\\'fetches\\' must be a string array or an object.');\n }\n if (outputNames.indexOf(name) === -1) {\n throw new RangeError(`'fetches' contains invalid output name: ${name}.`);\n }\n fetches[name] = null;\n }\n if (typeof arg2 === 'object' && arg2 !== null) {\n options = arg2;\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else {\n // decide whether arg1 is fetches or options\n // if any output name is present and its value is valid OnnxValue, we consider it fetches\n let isFetches = false;\n const arg1Keys = Object.getOwnPropertyNames(arg1);\n for (const name of outputNames) {\n if (arg1Keys.indexOf(name) !== -1) {\n const v = arg1[name];\n if (v === null || v instanceof Tensor) {\n isFetches = true;\n isFetchesEmpty = false;\n fetches[name] = v;\n }\n }\n }\n if (isFetches) {\n if (typeof arg2 === 'object' && arg2 !== null) {\n options = arg2;\n }\n else if (typeof arg2 !== 'undefined') {\n throw new TypeError('\\'options\\' must be an object.');\n }\n }\n else {\n options = arg1;\n }\n }\n }\n else if (typeof arg1 !== 'undefined') {\n throw new TypeError('Unexpected argument[1]: must be \\'fetches\\' or \\'options\\'.');\n }\n // check if all inputs are in feed\n for (const name of inputNames) {\n if (typeof feeds[name] === 'undefined') {\n throw new Error(`input '${name}' is missing in 'feeds'.`);\n }\n }\n // if no fetches is specified, we use the full output names list\n if (isFetchesEmpty) {\n for (const name of outputNames) {\n fetches[name] = null;\n }\n }\n return [fetches, options];\n }\n /**\n * Helper method for runTrainStep and any other runStep methods. Takes the ReturnType result from the SessionHandler\n * and changes it into a map of Tensors.\n *\n * @param results\n * @returns\n */\n convertHandlerReturnTypeToMapOfTensors(results) {\n const returnValue = {};\n for (const key in results) {\n if (Object.hasOwnProperty.call(results, key)) {\n const result = results[key];\n if (result instanceof Tensor) {\n returnValue[key] = result;\n }\n else {\n returnValue[key] = new Tensor(result.type, result.data, result.dims);\n }\n }\n }\n return returnValue;\n }\n async lazyResetGrad() {\n await this.handler.lazyResetGrad();\n }\n async runTrainStep(feeds, arg1, arg2) {\n const [fetches, options] = this.typeNarrowingForRunStep(this.trainingInputNames, this.trainingOutputNames, feeds, arg1, arg2);\n const results = await this.handler.runTrainStep(feeds, fetches, options);\n return this.convertHandlerReturnTypeToMapOfTensors(results);\n }\n async runOptimizerStep(options) {\n if (this.hasOptimizerModel) {\n await this.handler.runOptimizerStep(options || {});\n }\n else {\n throw new Error('This TrainingSession has no OptimizerModel loaded.');\n }\n }\n async runEvalStep(feeds, arg1, arg2) {\n if (this.hasEvalModel) {\n const [fetches, options] = this.typeNarrowingForRunStep(this.evalInputNames, this.evalOutputNames, feeds, arg1, arg2);\n const results = await this.handler.runEvalStep(feeds, fetches, options);\n return this.convertHandlerReturnTypeToMapOfTensors(results);\n }\n else {\n throw new Error('This TrainingSession has no EvalModel loaded.');\n }\n }\n async getParametersSize(trainableOnly = true) {\n return this.handler.getParametersSize(trainableOnly);\n }\n async loadParametersBuffer(array, trainableOnly = true) {\n const paramsSize = await this.getParametersSize(trainableOnly);\n // checking that the size of the Uint8Array is equivalent to the byte length of a Float32Array of the number\n // of parameters\n if (array.length !== 4 * paramsSize) {\n throw new Error('Size of the buffer passed into loadParametersBuffer must match the number of parameters in ' +\n 'the model. Please use getParametersSize method to check.');\n }\n return this.handler.loadParametersBuffer(array, trainableOnly);\n }\n async getContiguousParameters(trainableOnly = true) {\n return this.handler.getContiguousParameters(trainableOnly);\n }\n async release() {\n return this.handler.dispose();\n }\n}\n//# sourceMappingURL=training-session-impl.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\nimport { TrainingSession as TrainingSessionImpl } from './training-session-impl.js';\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const TrainingSession = TrainingSessionImpl;\n//# sourceMappingURL=training-session.js.map","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n// This file is generated by /js/scripts/update-version.ts\n// Do not modify file content manually.\nexport const version = '1.19.2';\n//# sourceMappingURL=version.js.map","/*!\n * ONNX Runtime Web v1.21.0-dev.20241122-a2ba3cb547\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\nvar Ln=Object.defineProperty;var Bp=Object.getOwnPropertyDescriptor;var Dp=Object.getOwnPropertyNames;var Mp=Object.prototype.hasOwnProperty;var Gn=(e=>typeof require<\"u\"?require:typeof Proxy<\"u\"?new Proxy(e,{get:(t,r)=>(typeof require<\"u\"?require:t)[r]}):e)(function(e){if(typeof require<\"u\")return require.apply(this,arguments);throw Error('Dynamic require of \"'+e+'\" is not supported')});var R=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ft=(e,t)=>{for(var r in t)Ln(e,r,{get:t[r],enumerable:!0})},Rp=(e,t,r,n)=>{if(t&&typeof t==\"object\"||typeof t==\"function\")for(let o of Dp(t))!Mp.call(e,o)&&o!==r&&Ln(e,o,{get:()=>t[o],enumerable:!(n=Bp(t,o))||n.enumerable});return e};var br=e=>Rp(Ln({},\"__esModule\",{value:!0}),e);var yr,$t,xt,Up,_r,wr=R(()=>{\"use strict\";yr=new Map,$t=[],xt=(e,t,r)=>{if(t&&typeof t.init==\"function\"&&typeof t.createInferenceSessionHandler==\"function\"){let n=yr.get(e);if(n===void 0)yr.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend \"${e}\" using priority ${r}`)}if(r>=0){let o=$t.indexOf(e);o!==-1&&$t.splice(o,1);for(let i=0;i<$t.length;i++)if(yr.get($t[i]).priority<=r){$t.splice(i,0,e);return}$t.push(e)}return}throw new TypeError(\"not a valid backend\")},Up=async e=>{let t=yr.get(e);if(!t)return\"backend not found.\";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},_r=async e=>{let t=e.executionProviders||[],r=t.map(d=>typeof d==\"string\"?d:d.name),n=r.length===0?$t:r,o,i=[],a=new Set;for(let d of n){let p=await Up(d);typeof p==\"string\"?i.push({name:d,err:p}):(o||(o=p),o===p&&a.add(d))}if(!o)throw new Error(`no available backend found. ERR: ${i.map(d=>`[${d.name}] ${d.err}`).join(\", \")}`);for(let{name:d,err:p}of i)r.includes(d)&&console.warn(`removing requested execution provider \"${d}\" from session options because it is not available: ${p}`);let l=t.filter(d=>a.has(typeof d==\"string\"?d:d.name));return[o,new Proxy(e,{get:(d,p)=>p===\"executionProviders\"?l:Reflect.get(d,p)})]}});var ea=R(()=>{\"use strict\";wr()});var ta,ra=R(()=>{\"use strict\";ta=\"1.21.0-dev.20241026-05fbb43b34\"});var na,Re,Hn=R(()=>{\"use strict\";ra();na=\"warning\",Re={wasm:{},webgl:{},webgpu:{},versions:{common:ta},set logLevel(e){if(e!==void 0){if(typeof e!=\"string\"||[\"verbose\",\"info\",\"warning\",\"error\",\"fatal\"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);na=e}},get logLevel(){return na}};Object.defineProperty(Re,\"logLevel\",{enumerable:!0})});var we,oa=R(()=>{\"use strict\";Hn();we=Re});var ia,aa,sa=R(()=>{\"use strict\";ia=(e,t)=>{let r=typeof document<\"u\"?document.createElement(\"canvas\"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext(\"2d\");if(n!=null){let o,i;t?.tensorLayout!==void 0&&t.tensorLayout===\"NHWC\"?(o=e.dims[2],i=e.dims[3]):(o=e.dims[3],i=e.dims[2]);let a=t?.format!==void 0?t.format:\"RGB\",l=t?.norm,d,p;l===void 0||l.mean===void 0?d=[255,255,255,255]:typeof l.mean==\"number\"?d=[l.mean,l.mean,l.mean,l.mean]:(d=[l.mean[0],l.mean[1],l.mean[2],0],l.mean[3]!==void 0&&(d[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias==\"number\"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let m=i*o,u=0,h=m,_=m*2,y=-1;a===\"RGBA\"?(u=0,h=m,_=m*2,y=m*3):a===\"RGB\"?(u=0,h=m,_=m*2):a===\"RBG\"&&(u=0,_=m,h=m*2);for(let g=0;g{let r=typeof document<\"u\"?document.createElement(\"canvas\").getContext(\"2d\"):new OffscreenCanvas(1,1).getContext(\"2d\"),n;if(r!=null){let o,i,a;t?.tensorLayout!==void 0&&t.tensorLayout===\"NHWC\"?(o=e.dims[2],i=e.dims[1],a=e.dims[3]):(o=e.dims[3],i=e.dims[2],a=e.dims[1]);let l=t!==void 0&&t.format!==void 0?t.format:\"RGB\",d=t?.norm,p,m;d===void 0||d.mean===void 0?p=[255,255,255,255]:typeof d.mean==\"number\"?p=[d.mean,d.mean,d.mean,d.mean]:(p=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(p[3]=d.mean[3])),d===void 0||d.bias===void 0?m=[0,0,0,0]:typeof d.bias==\"number\"?m=[d.bias,d.bias,d.bias,d.bias]:(m=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(m[3]=d.bias[3]));let u=i*o;if(t!==void 0&&(t.format!==void 0&&a===4&&t.format!==\"RGBA\"||a===3&&t.format!==\"RGB\"&&t.format!==\"BGR\"))throw new Error(\"Tensor format doesn't match input tensor dims\");let h=4,_=0,y=1,g=2,x=3,$=0,v=u,S=u*2,T=-1;l===\"RGBA\"?($=0,v=u,S=u*2,T=u*3):l===\"RGB\"?($=0,v=u,S=u*2):l===\"RBG\"&&($=0,S=u,v=u*2),n=r.createImageData(o,i);for(let C=0;C{\"use strict\";vr();Fn=(e,t)=>{if(e===void 0)throw new Error(\"Image buffer must be defined\");if(t.height===void 0||t.width===void 0)throw new Error(\"Image height and width must be defined\");if(t.tensorLayout===\"NHWC\")throw new Error(\"NHWC Tensor layout is not supported yet\");let{height:r,width:n}=t,o=t.norm??{mean:255,bias:0},i,a;typeof o.mean==\"number\"?i=[o.mean,o.mean,o.mean,o.mean]:i=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias==\"number\"?a=[o.bias,o.bias,o.bias,o.bias]:a=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let l=t.format!==void 0?t.format:\"RGBA\",d=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:\"RGB\",p=r*n,m=d===\"RGBA\"?new Float32Array(p*4):new Float32Array(p*3),u=4,h=0,_=1,y=2,g=3,x=0,$=p,v=p*2,S=-1;l===\"RGB\"&&(u=3,h=0,_=1,y=2,g=-1),d===\"RGBA\"?S=p*3:d===\"RBG\"?(x=0,v=p,$=p*2):d===\"BGR\"&&(v=0,$=p,x=p*2);for(let C=0;C{let r=typeof HTMLImageElement<\"u\"&&e instanceof HTMLImageElement,n=typeof ImageData<\"u\"&&e instanceof ImageData,o=typeof ImageBitmap<\"u\"&&e instanceof ImageBitmap,i=typeof e==\"string\",a,l=t??{},d=()=>{if(typeof document<\"u\")return document.createElement(\"canvas\");if(typeof OffscreenCanvas<\"u\")return new OffscreenCanvas(1,1);throw new Error(\"Canvas is not supported\")},p=m=>typeof HTMLCanvasElement<\"u\"&&m instanceof HTMLCanvasElement||m instanceof OffscreenCanvas?m.getContext(\"2d\"):null;if(r){let m=d();m.width=e.width,m.height=e.height;let u=p(m);if(u!=null){let h=e.height,_=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(h=t.resizedHeight,_=t.resizedWidth),t!==void 0){if(l=t,t.tensorFormat!==void 0)throw new Error(\"Image input config format must be RGBA for HTMLImageElement\");l.tensorFormat=\"RGBA\",l.height=h,l.width=_}else l.tensorFormat=\"RGBA\",l.height=h,l.width=_;u.drawImage(e,0,0),a=u.getImageData(0,0,_,h).data}else throw new Error(\"Can not access image data\")}else if(n){let m,u;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(m=t.resizedHeight,u=t.resizedWidth):(m=e.height,u=e.width),t!==void 0&&(l=t),l.format=\"RGBA\",l.height=m,l.width=u,t!==void 0){let h=d();h.width=u,h.height=m;let _=p(h);if(_!=null)_.putImageData(e,0,0),a=_.getImageData(0,0,u,m).data;else throw new Error(\"Can not access image data\")}else a=e.data}else if(o){if(t===void 0)throw new Error(\"Please provide image config with format for Imagebitmap\");let m=d();m.width=e.width,m.height=e.height;let u=p(m);if(u!=null){let h=e.height,_=e.width;return u.drawImage(e,0,0,_,h),a=u.getImageData(0,0,_,h).data,l.height=h,l.width=_,Fn(a,l)}else throw new Error(\"Can not access image data\")}else{if(i)return new Promise((m,u)=>{let h=d(),_=p(h);if(!e||!_)return u();let y=new Image;y.crossOrigin=\"Anonymous\",y.src=e,y.onload=()=>{h.width=y.width,h.height=y.height,_.drawImage(y,0,0,h.width,h.height);let g=_.getImageData(0,0,h.width,h.height);l.height=h.height,l.width=h.width,m(Fn(g.data,l))}});throw new Error(\"Input data provided is not supported - aborted tensor creation\")}if(a!==void 0)return Fn(a,l);throw new Error(\"Input data provided is not supported - aborted tensor creation\")},la=(e,t)=>{let{width:r,height:n,download:o,dispose:i}=t,a=[1,n,r,4];return new ze({location:\"texture\",type:\"float32\",texture:e,dims:a,download:o,dispose:i})},da=(e,t)=>{let{dataType:r,dims:n,download:o,dispose:i}=t;return new ze({location:\"gpu-buffer\",type:r??\"float32\",gpuBuffer:e,dims:n,download:o,dispose:i})},ca=(e,t)=>{let{dataType:r,dims:n,download:o,dispose:i}=t;return new ze({location:\"ml-tensor\",type:r??\"float32\",mlTensor:e,dims:n,download:o,dispose:i})},pa=(e,t,r)=>new ze({location:\"cpu-pinned\",type:e,data:t,dims:r??[t.length]})});var St,qt,fa,ha,ga=R(()=>{\"use strict\";St=new Map([[\"float32\",Float32Array],[\"uint8\",Uint8Array],[\"int8\",Int8Array],[\"uint16\",Uint16Array],[\"int16\",Int16Array],[\"int32\",Int32Array],[\"bool\",Uint8Array],[\"float64\",Float64Array],[\"uint32\",Uint32Array],[\"int4\",Uint8Array],[\"uint4\",Uint8Array]]),qt=new Map([[Float32Array,\"float32\"],[Uint8Array,\"uint8\"],[Int8Array,\"int8\"],[Uint16Array,\"uint16\"],[Int16Array,\"int16\"],[Int32Array,\"int32\"],[Float64Array,\"float64\"],[Uint32Array,\"uint32\"]]),fa=!1,ha=()=>{if(!fa){fa=!0;let e=typeof BigInt64Array<\"u\"&&BigInt64Array.from,t=typeof BigUint64Array<\"u\"&&BigUint64Array.from,r=typeof Float16Array<\"u\"&&Float16Array.from;e&&(St.set(\"int64\",BigInt64Array),qt.set(BigInt64Array,\"int64\")),t&&(St.set(\"uint64\",BigUint64Array),qt.set(BigUint64Array,\"uint64\")),r?(St.set(\"float16\",Float16Array),qt.set(Float16Array,\"float16\")):St.set(\"float16\",Uint16Array)}}});var ba,ya,_a=R(()=>{\"use strict\";vr();ba=e=>{let t=1;for(let r=0;r{switch(e.location){case\"cpu\":return new ze(e.type,e.data,t);case\"cpu-pinned\":return new ze({location:\"cpu-pinned\",data:e.data,type:e.type,dims:t});case\"texture\":return new ze({location:\"texture\",texture:e.texture,type:e.type,dims:t});case\"gpu-buffer\":return new ze({location:\"gpu-buffer\",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case\"ml-tensor\":return new ze({location:\"ml-tensor\",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}});var ze,vr=R(()=>{\"use strict\";sa();ma();ga();_a();ze=class{constructor(t,r,n){ha();let o,i;if(typeof t==\"object\"&&\"location\"in t)switch(this.dataLocation=t.location,o=t.type,i=t.dims,t.location){case\"cpu-pinned\":{let l=St.get(o);if(!l)throw new TypeError(`unsupported type \"${o}\" to create tensor from pinned buffer`);if(!(t.data instanceof l))throw new TypeError(`buffer should be of type ${l.name}`);this.cpuData=t.data;break}case\"texture\":{if(o!==\"float32\")throw new TypeError(`unsupported type \"${o}\" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case\"gpu-buffer\":{if(o!==\"float32\"&&o!==\"float16\"&&o!==\"int32\"&&o!==\"int64\"&&o!==\"uint32\"&&o!==\"uint8\"&&o!==\"bool\"&&o!==\"uint4\"&&o!==\"int4\")throw new TypeError(`unsupported type \"${o}\" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case\"ml-tensor\":{if(o!==\"float32\"&&o!==\"float16\"&&o!==\"int32\"&&o!==\"int64\"&&o!==\"uint32\"&&o!==\"uint64\"&&o!==\"int8\"&&o!==\"uint8\"&&o!==\"bool\"&&o!==\"uint4\"&&o!==\"int4\")throw new TypeError(`unsupported type \"${o}\" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let l,d;if(typeof t==\"string\")if(o=t,d=n,t===\"string\"){if(!Array.isArray(r))throw new TypeError(\"A string tensor's data must be a string array.\");l=r}else{let p=St.get(t);if(p===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t===\"float16\"&&p===Uint16Array||t===\"uint4\"||t===\"int4\")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${p.name} as data.`);t===\"uint64\"||t===\"int64\"?l=p.from(r,BigInt):l=p.from(r)}else if(r instanceof p)l=r;else if(r instanceof Uint8ClampedArray)if(t===\"uint8\")l=Uint8Array.from(r);else throw new TypeError(\"A Uint8ClampedArray tensor's data must be type of uint8\");else throw new TypeError(`A ${o} tensor's data must be type of ${p}`)}else if(d=r,Array.isArray(t)){if(t.length===0)throw new TypeError(\"Tensor type cannot be inferred from an empty array.\");let p=typeof t[0];if(p===\"string\")o=\"string\",l=t;else if(p===\"boolean\")o=\"bool\",l=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${p}.`)}else if(t instanceof Uint8ClampedArray)o=\"uint8\",l=Uint8Array.from(t);else{let p=qt.get(t.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);o=p,l=t}if(d===void 0)d=[l.length];else if(!Array.isArray(d))throw new TypeError(\"A tensor's dims must be a number array\");i=d,this.cpuData=l,this.dataLocation=\"cpu\"}let a=ba(i);if(this.cpuData&&a!==this.cpuData.length&&!((o===\"uint4\"||o===\"int4\")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=i,this.size=a}static async fromImage(t,r){return ua(t,r)}static fromTexture(t,r){return la(t,r)}static fromGpuBuffer(t,r){return da(t,r)}static fromMLTensor(t,r){return ca(t,r)}static fromPinnedBuffer(t,r,n){return pa(t,r,n)}toDataURL(t){return ia(this,t)}toImageData(t){return aa(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error(\"The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.\");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error(\"The data is not stored as a WebGL texture.\");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error(\"The data is not stored as a WebGPU buffer.\");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error(\"The data is not stored as a WebNN MLTensor.\");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case\"cpu\":case\"cpu-pinned\":return this.data;case\"texture\":case\"gpu-buffer\":case\"ml-tensor\":{if(!this.downloader)throw new Error(\"The current tensor is not created with a specified data downloader.\");if(this.isDownloading)throw new Error(\"The current tensor is being downloaded.\");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation=\"cpu\",this.cpuData=r,t&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error(\"The current tensor is being downloaded.\");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=\"none\"}ensureValid(){if(this.dataLocation===\"none\")throw new Error(\"The tensor is disposed.\")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error(\"Cannot reshape a tensor that owns GPU resource.\");return ya(this,t)}}});var Oe,$r=R(()=>{\"use strict\";vr();Oe=ze});var xr,wa,Ue,De,qn=R(()=>{\"use strict\";Hn();xr=(e,t)=>{(typeof Re.trace>\"u\"?!Re.wasm.trace:!Re.trace)||console.timeStamp(`${e}::ORT::${t}`)},wa=(e,t)=>{let r=new Error().stack?.split(/\\r\\n|\\r|\\n/g)||[],n=!1;for(let o=0;o{(typeof Re.trace>\"u\"?!Re.wasm.trace:!Re.trace)||wa(\"BEGIN\",e)},De=e=>{(typeof Re.trace>\"u\"?!Re.wasm.trace:!Re.trace)||wa(\"END\",e)}});var Sr,va=R(()=>{\"use strict\";wr();$r();qn();Sr=class e{constructor(t){this.handler=t}async run(t,r,n){Ue();let o={},i={};if(typeof t!=\"object\"||t===null||t instanceof Oe||Array.isArray(t))throw new TypeError(\"'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.\");let a=!0;if(typeof r==\"object\"){if(r===null)throw new TypeError(\"Unexpected argument[1]: cannot be null.\");if(r instanceof Oe)throw new TypeError(\"'fetches' cannot be a Tensor\");if(Array.isArray(r)){if(r.length===0)throw new TypeError(\"'fetches' cannot be an empty array.\");a=!1;for(let p of r){if(typeof p!=\"string\")throw new TypeError(\"'fetches' must be a string array or an object.\");if(this.outputNames.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);o[p]=null}if(typeof n==\"object\"&&n!==null)i=n;else if(typeof n<\"u\")throw new TypeError(\"'options' must be an object.\")}else{let p=!1,m=Object.getOwnPropertyNames(r);for(let u of this.outputNames)if(m.indexOf(u)!==-1){let h=r[u];(h===null||h instanceof Oe)&&(p=!0,a=!1,o[u]=h)}if(p){if(typeof n==\"object\"&&n!==null)i=n;else if(typeof n<\"u\")throw new TypeError(\"'options' must be an object.\")}else i=r}}else if(typeof r<\"u\")throw new TypeError(\"Unexpected argument[1]: must be 'fetches' or 'options'.\");for(let p of this.inputNames)if(typeof t[p]>\"u\")throw new Error(`input '${p}' is missing in 'feeds'.`);if(a)for(let p of this.outputNames)o[p]=null;let l=await this.handler.run(t,o,i),d={};for(let p in l)if(Object.hasOwnProperty.call(l,p)){let m=l[p];m instanceof Oe?d[p]=m:d[p]=new Oe(m.type,m.data,m.dims)}return De(),d}async release(){return this.handler.dispose()}static async create(t,r,n,o){Ue();let i,a={};if(typeof t==\"string\"){if(i=t,typeof r==\"object\"&&r!==null)a=r;else if(typeof r<\"u\")throw new TypeError(\"'options' must be an object.\")}else if(t instanceof Uint8Array){if(i=t,typeof r==\"object\"&&r!==null)a=r;else if(typeof r<\"u\")throw new TypeError(\"'options' must be an object.\")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<\"u\"&&t instanceof SharedArrayBuffer){let m=t,u=0,h=t.byteLength;if(typeof r==\"object\"&&r!==null)a=r;else if(typeof r==\"number\"){if(u=r,!Number.isSafeInteger(u))throw new RangeError(\"'byteOffset' must be an integer.\");if(u<0||u>=m.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${m.byteLength}).`);if(h=t.byteLength-u,typeof n==\"number\"){if(h=n,!Number.isSafeInteger(h))throw new RangeError(\"'byteLength' must be an integer.\");if(h<=0||u+h>m.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${m.byteLength-u}].`);if(typeof o==\"object\"&&o!==null)a=o;else if(typeof o<\"u\")throw new TypeError(\"'options' must be an object.\")}else if(typeof n<\"u\")throw new TypeError(\"'byteLength' must be a number.\")}else if(typeof r<\"u\")throw new TypeError(\"'options' must be an object.\");i=new Uint8Array(m,u,h)}else throw new TypeError(\"Unexpected argument[0]: must be 'path' or 'buffer'.\");let[l,d]=await _r(a),p=await l.createInferenceSessionHandler(i,d);return De(),new e(p)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}});var Np,$a=R(()=>{\"use strict\";va();Np=Sr});var xa=R(()=>{\"use strict\"});var Sa=R(()=>{\"use strict\"});var Ta=R(()=>{\"use strict\"});var Ia=R(()=>{\"use strict\"});var Vp,Tr,Ca=R(()=>{\"use strict\";wr();$r();Vp=\"Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.\",Tr=class e{constructor(t,r,n){this.handler=t,this.hasOptimizerModel=r,this.hasEvalModel=n}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error(\"This training session has no evalModel loaded.\")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error(\"This training session has no evalModel loaded.\")}static async create(t,r){let n=t.evalModel||\"\",o=t.optimizerModel||\"\",i=r||{},[a,l]=await _r(i);if(a.createTrainingSessionHandler){let d=await a.createTrainingSessionHandler(t.checkpointState,t.trainModel,n,o,l);return new e(d,!!t.optimizerModel,!!t.evalModel)}else throw new Error(Vp)}typeNarrowingForRunStep(t,r,n,o,i){let a={},l={};if(typeof n!=\"object\"||n===null||n instanceof Oe||Array.isArray(n))throw new TypeError(\"'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.\");let d=!0;if(typeof o==\"object\"){if(o===null)throw new TypeError(\"Unexpected argument[1]: cannot be null.\");if(o instanceof Oe)throw new TypeError(\"'fetches' cannot be a Tensor\");if(Array.isArray(o)){if(o.length===0)throw new TypeError(\"'fetches' cannot be an empty array.\");d=!1;for(let p of o){if(typeof p!=\"string\")throw new TypeError(\"'fetches' must be a string array or an object.\");if(r.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);a[p]=null}if(typeof i==\"object\"&&i!==null)l=i;else if(typeof i<\"u\")throw new TypeError(\"'options' must be an object.\")}else{let p=!1,m=Object.getOwnPropertyNames(o);for(let u of r)if(m.indexOf(u)!==-1){let h=o[u];(h===null||h instanceof Oe)&&(p=!0,d=!1,a[u]=h)}if(p){if(typeof i==\"object\"&&i!==null)l=i;else if(typeof i<\"u\")throw new TypeError(\"'options' must be an object.\")}else l=o}}else if(typeof o<\"u\")throw new TypeError(\"Unexpected argument[1]: must be 'fetches' or 'options'.\");for(let p of t)if(typeof n[p]>\"u\")throw new Error(`input '${p}' is missing in 'feeds'.`);if(d)for(let p of r)a[p]=null;return[a,l]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let n in t)if(Object.hasOwnProperty.call(t,n)){let o=t[n];o instanceof Oe?r[n]=o:r[n]=new Oe(o.type,o.data,o.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,n){let[o,i]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,n),a=await this.handler.runTrainStep(t,o,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}async runOptimizerStep(t){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(t||{});else throw new Error(\"This TrainingSession has no OptimizerModel loaded.\")}async runEvalStep(t,r,n){if(this.hasEvalModel){let[o,i]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,n),a=await this.handler.runEvalStep(t,o,i);return this.convertHandlerReturnTypeToMapOfTensors(a)}else throw new Error(\"This TrainingSession has no EvalModel loaded.\")}async getParametersSize(t=!0){return this.handler.getParametersSize(t)}async loadParametersBuffer(t,r=!0){let n=await this.getParametersSize(r);if(t.length!==4*n)throw new Error(\"Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.\");return this.handler.loadParametersBuffer(t,r)}async getContiguousParameters(t=!0){return this.handler.getContiguousParameters(t)}async release(){return this.handler.dispose()}}});var Wp,Aa=R(()=>{\"use strict\";Ca();Wp=Tr});var jn={};Ft(jn,{InferenceSession:()=>Np,TRACE:()=>xr,TRACE_FUNC_BEGIN:()=>Ue,TRACE_FUNC_END:()=>De,Tensor:()=>Oe,TrainingSession:()=>Wp,env:()=>we,registerBackend:()=>xt});var We=R(()=>{\"use strict\";ea();oa();$a();$r();xa();Sa();qn();Ta();Ia();Aa()});var Ir=R(()=>{\"use strict\"});var za={};Ft(za,{default:()=>Lp});var Ea,Pa,Lp,Oa=R(()=>{\"use strict\";Kn();ht();jt();Ea=\"ort-wasm-proxy-worker\",Pa=globalThis.self?.name===Ea;Pa&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case\"init-wasm\":Cr(r.wasm).then(()=>{Ar(r).then(()=>{postMessage({type:t})},n=>{postMessage({type:t,err:n})})},n=>{postMessage({type:t,err:n})});break;case\"init-ep\":{let{epName:n,env:o}=r;kr(o,n).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case\"copy-from\":{let{buffer:n}=r,o=Kt(n);postMessage({type:t,out:o});break}case\"create\":{let{model:n,options:o}=r;Er(n,o).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case\"release\":Pr(r),postMessage({type:t});break;case\"run\":{let{sessionId:n,inputIndices:o,inputs:i,outputIndices:a,options:l}=r;zr(n,o,i,a,new Array(a.length).fill(null),l).then(d=>{d.some(p=>p[3]!==\"cpu\")?postMessage({type:t,err:\"Proxy does not support non-cpu tensor location.\"}):postMessage({type:t,out:d},Br([...i,...d]))},d=>{postMessage({type:t,err:d})});break}case\"end-profiling\":Or(r),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}});Lp=Pa?null:e=>new Worker(e??Dt,{type:\"module\",name:Ea})});var Da={};Ft(Da,{default:()=>Gp});var Yn,Ba,Gp,Ma=R(()=>{\"use strict\";Ba=(Yn=import.meta.url,async function(e={}){function t(){return se.buffer!=ee.buffer&&be(),ee}function r(){return se.buffer!=ee.buffer&&be(),ne}function n(){return se.buffer!=ee.buffer&&be(),ve}function o(){return se.buffer!=ee.buffer&&be(),Be}function i(){return se.buffer!=ee.buffer&&be(),$e}function a(){return se.buffer!=ee.buffer&&be(),de}function l(){return se.buffer!=ee.buffer&&be(),V}function d(){return se.buffer!=ee.buffer&&be(),Ge}var p,m,u=Object.assign({},e),h=new Promise((s,c)=>{p=s,m=c}),_=typeof window==\"object\",y=typeof importScripts==\"function\",g=y&&self.name==\"em-pthread\";u.mountExternalData=(s,c)=>{s.startsWith(\"./\")&&(s=s.substring(2)),(u.Eb||(u.Eb=new Map)).set(s,c)},u.unmountExternalData=()=>{delete u.Eb};var x=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let $=()=>{let s=(f,b,w)=>(...I)=>{let B=Qe,D=b?.();I=f(...I);let L=b?.();return D!==L&&(f=L,w(D),b=w=null),Qe!=B?new Promise((H,Q)=>{Bn={resolve:H,reject:Q}}):I},c=f=>async(...b)=>{try{if(u.Fb)throw Error(\"Session already started\");let w=u.Fb={fc:b[0],errors:[]},I=await f(...b);if(u.Fb!==w)throw Error(\"Session mismatch\");u.Gb?.flush();let B=w.errors;if(0L),0u._OrtCreateSession,f=>u._OrtCreateSession=f),u._OrtRun=c(s(u._OrtRun,()=>u._OrtRun,f=>u._OrtRun=f)),u._OrtRunWithBinding=c(s(u._OrtRunWithBinding,()=>u._OrtRunWithBinding,f=>u._OrtRunWithBinding=f)),u._OrtBindInput=s(u._OrtBindInput,()=>u._OrtBindInput,f=>u._OrtBindInput=f),$=void 0};u.jsepInit=(s,c)=>{if($?.(),s===\"webgpu\"){[u.Gb,u.Ub,u.Yb,u.Nb,u.Xb,u.jb,u.Zb,u.bc,u.Vb,u.Wb,u.$b]=c;let f=u.Gb;u.jsepRegisterBuffer=(b,w,I,B)=>f.registerBuffer(b,w,I,B),u.jsepGetBuffer=b=>f.getBuffer(b),u.jsepCreateDownloader=(b,w,I)=>f.createDownloader(b,w,I),u.jsepOnCreateSession=b=>{f.onCreateSession(b)},u.jsepOnReleaseSession=b=>{f.onReleaseSession(b)},u.jsepOnRunStart=b=>f.onRunStart(b),u.cc=(b,w)=>{f.upload(b,w)}}else if(s===\"webnn\"){[u.Gb,u.ac,u.Ob,u.jsepEnsureTensor,u.dc,u.jsepDownloadTensor]=c,u.jsepReleaseTensorId=u.Ob;let f=u.Gb;u.jsepOnRunStart=b=>f.onRunStart(b),u.jsepRegisterMLContext=(b,w)=>{f.registerMLContext(b,w)},u.jsepOnReleaseSession=b=>{f.onReleaseSession(b)},u.jsepCreateMLTensorDownloader=(b,w)=>f.createMLTensorDownloader(b,w),u.jsepRegisterMLTensor=(b,w,I)=>f.registerMLTensor(b,w,I),u.jsepCreateMLContext=b=>f.createMLContext(b),u.jsepRegisterMLConstant=(b,w,I,B,D)=>f.registerMLConstant(b,w,I,B,D,u.Eb)}};var v,S,T=Object.assign({},u),C=\"./this.program\",A=(s,c)=>{throw c},P=\"\";(_||y)&&(y?P=self.location.href:typeof document<\"u\"&&document.currentScript&&(P=document.currentScript.src),Yn&&(P=Yn),P=P.startsWith(\"blob:\")?\"\":P.substr(0,P.replace(/[?#].*/,\"\").lastIndexOf(\"/\")+1),y&&(S=s=>{var c=new XMLHttpRequest;return c.open(\"GET\",s,!1),c.responseType=\"arraybuffer\",c.send(null),new Uint8Array(c.response)}),v=(s,c,f)=>{var b=new XMLHttpRequest;b.open(\"GET\",s,!0),b.responseType=\"arraybuffer\",b.onload=()=>{b.status==200||b.status==0&&b.response?c(b.response):f()},b.onerror=f,b.send(null)});var O,U=console.log.bind(console),G=console.error.bind(console),q=U,K=G;if(Object.assign(u,T),T=null,g){let s=function(c){try{var f=c.data,b=f.cmd;if(b===\"load\"){let w=[];self.onmessage=I=>w.push(I),self.startWorker=()=>{postMessage({cmd:\"loaded\"});for(let I of w)s(I);self.onmessage=s};for(let I of f.handlers)u[I]&&!u[I].proxy||(u[I]=(...B)=>{postMessage({Mb:\"callHandler\",oc:I,args:B})},I==\"print\"&&(q=u[I]),I==\"printErr\"&&(K=u[I]));se=f.wasmMemory,be(),W(f.wasmModule)}else if(b===\"run\"){Un(f.pthread_ptr,0,0,1,0,0),Pn(f.pthread_ptr),yc(),Fo(),Y||(Li(),Y=!0);try{_c(f.start_routine,f.arg)}catch(w){if(w!=\"unwind\")throw w}}else b===\"cancel\"?Bt()&&hr(-1):f.target!==\"setimmediate\"&&(b===\"checkMailbox\"?Y&&ar():b&&(K(`worker: received unknown command ${b}`),K(f)))}catch(w){throw Gi(),w}};var hg=s,W,Y=!1;K=function(...c){c=c.join(\" \"),console.error(c)},self.alert=function(...c){postMessage({Mb:\"alert\",text:c.join(\" \"),qc:Bt()})},u.instantiateWasm=(c,f)=>new Promise(b=>{W=w=>{w=new WebAssembly.Instance(w,Vo()),f(w),b()}}),self.onunhandledrejection=c=>{throw c.reason||c},self.onmessage=s}u.wasmBinary&&(O=u.wasmBinary);var se,X,re,ee,ne,ve,Be,$e,de,V,j,he,Ge,_e=!1;function be(){var s=se.buffer;u.HEAP8=ee=new Int8Array(s),u.HEAP16=ve=new Int16Array(s),u.HEAPU8=ne=new Uint8Array(s),u.HEAPU16=Be=new Uint16Array(s),u.HEAP32=$e=new Int32Array(s),u.HEAPU32=de=new Uint32Array(s),u.HEAPF32=V=new Float32Array(s),u.HEAPF64=Ge=new Float64Array(s),u.HEAP64=j=new BigInt64Array(s),u.HEAPU64=he=new BigUint64Array(s)}if(!g){if(!((se=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof x))throw K(\"requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag\"),Error(\"bad memory\");be()}var Ke=[],Lt=[],bn=[],Gt=0,yn=null,Ht=null;function Do(){if(--Gt==0&&(yn!==null&&(clearInterval(yn),yn=null),Ht)){var s=Ht;Ht=null,s()}}function dt(s){throw K(s=\"Aborted(\"+s+\")\"),_e=!0,re=1,s=new WebAssembly.RuntimeError(s+\". Build with -sASSERTIONS for more info.\"),m(s),s}var _n,Mo=s=>s.startsWith(\"data:application/octet-stream;base64,\"),Ro=s=>s.startsWith(\"file://\");function Uo(s){if(s==_n&&O)return new Uint8Array(O);if(S)return S(s);throw\"both async and sync fetching of the wasm failed\"}function No(s,c,f){return function(b){if(!O&&(_||y)){if(typeof fetch==\"function\"&&!Ro(b))return fetch(b,{credentials:\"same-origin\"}).then(w=>{if(!w.ok)throw`failed to load wasm binary file at '${b}'`;return w.arrayBuffer()}).catch(()=>Uo(b));if(v)return new Promise((w,I)=>{v(b,B=>w(new Uint8Array(B)),I)})}return Promise.resolve().then(()=>Uo(b))}(s).then(b=>WebAssembly.instantiate(b,c)).then(f,b=>{K(`failed to asynchronously prepare wasm: ${b}`),dt(b)})}function Vo(){return{a:{O:bc,Aa:gc,b:vc,aa:Yo,B:Xo,qa:Jo,Y:ti,_:ri,ra:ni,oa:oi,ha:ii,na:ai,L:si,Z:ui,W:li,pa:di,X:ci,wa:$c,F:Sc,Q:Tc,P:Cc,E:kc,u:Ec,q:Pc,G:zc,A:Nc,R:Vc,ua:Wc,ka:Lc,U:Gc,ba:Hc,H:Fc,ja:Pn,ta:qc,t:jc,x:Zc,o:Qc,m:Jc,c:kn,n:ep,k:np,w:op,p:ip,f:ap,s:sp,l:up,e:lp,j:dp,i:cp,h:pp,d:mp,ea:fp,fa:hp,ga:gp,ca:Ti,da:Ii,T:bp,g:yp,D:_p,I:wp,M:vp,y:$p,sa:xp,V:Sp,v:Ai,z:Tp,N:Ip,S:Cp,za:Ap,ya:kp,la:Pi,ma:zi,$:Sn,C:Oi,K:Bi,ia:Di,J:Mi,a:se,xa:xn,va:Ni,r:zp}}}var wn={873844:(s,c,f,b,w)=>{if(u===void 0||!u.Eb)return 1;if((s=Te(Number(s>>>0))).startsWith(\"./\")&&(s=s.substring(2)),!(s=u.Eb.get(s)))return 2;if(c=Number(c>>>0),f=Number(f>>>0),b=Number(b>>>0),c+f>s.byteLength)return 3;try{let I=s.subarray(c,c+f);switch(w){case 0:r().set(I,b>>>0);break;case 1:u.cc(b,I);break;default:return 4}return 0}catch{return 4}},874559:(s,c,f)=>{u.dc(s,r().subarray(c>>>0,c+f>>>0))},874622:()=>u.ac(),874663:s=>{u.Ob(s)},874699:()=>{u.Vb()},874730:()=>{u.Wb()},874759:()=>{u.$b()},874784:s=>u.Ub(s),874817:s=>u.Yb(s),874849:(s,c,f)=>{u.Nb(Number(s),Number(c),Number(f),!0)},874912:(s,c,f)=>{u.Nb(Number(s),Number(c),Number(f))},874969:()=>typeof wasmOffsetConverter<\"u\",875026:s=>{u.jb(\"Abs\",s,void 0)},875077:s=>{u.jb(\"Neg\",s,void 0)},875128:s=>{u.jb(\"Floor\",s,void 0)},875181:s=>{u.jb(\"Ceil\",s,void 0)},875233:s=>{u.jb(\"Reciprocal\",s,void 0)},875291:s=>{u.jb(\"Sqrt\",s,void 0)},875343:s=>{u.jb(\"Exp\",s,void 0)},875394:s=>{u.jb(\"Erf\",s,void 0)},875445:s=>{u.jb(\"Sigmoid\",s,void 0)},875500:(s,c,f)=>{u.jb(\"HardSigmoid\",s,{alpha:c,beta:f})},875579:s=>{u.jb(\"Log\",s,void 0)},875630:s=>{u.jb(\"Sin\",s,void 0)},875681:s=>{u.jb(\"Cos\",s,void 0)},875732:s=>{u.jb(\"Tan\",s,void 0)},875783:s=>{u.jb(\"Asin\",s,void 0)},875835:s=>{u.jb(\"Acos\",s,void 0)},875887:s=>{u.jb(\"Atan\",s,void 0)},875939:s=>{u.jb(\"Sinh\",s,void 0)},875991:s=>{u.jb(\"Cosh\",s,void 0)},876043:s=>{u.jb(\"Asinh\",s,void 0)},876096:s=>{u.jb(\"Acosh\",s,void 0)},876149:s=>{u.jb(\"Atanh\",s,void 0)},876202:s=>{u.jb(\"Tanh\",s,void 0)},876254:s=>{u.jb(\"Not\",s,void 0)},876305:(s,c,f)=>{u.jb(\"Clip\",s,{min:c,max:f})},876374:s=>{u.jb(\"Clip\",s,void 0)},876426:(s,c)=>{u.jb(\"Elu\",s,{alpha:c})},876484:s=>{u.jb(\"Gelu\",s,void 0)},876536:s=>{u.jb(\"Relu\",s,void 0)},876588:(s,c)=>{u.jb(\"LeakyRelu\",s,{alpha:c})},876652:(s,c)=>{u.jb(\"ThresholdedRelu\",s,{alpha:c})},876722:(s,c)=>{u.jb(\"Cast\",s,{to:c})},876780:s=>{u.jb(\"Add\",s,void 0)},876831:s=>{u.jb(\"Sub\",s,void 0)},876882:s=>{u.jb(\"Mul\",s,void 0)},876933:s=>{u.jb(\"Div\",s,void 0)},876984:s=>{u.jb(\"Pow\",s,void 0)},877035:s=>{u.jb(\"Equal\",s,void 0)},877088:s=>{u.jb(\"Greater\",s,void 0)},877143:s=>{u.jb(\"GreaterOrEqual\",s,void 0)},877205:s=>{u.jb(\"Less\",s,void 0)},877257:s=>{u.jb(\"LessOrEqual\",s,void 0)},877316:(s,c,f,b,w)=>{u.jb(\"ReduceMean\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},877491:(s,c,f,b,w)=>{u.jb(\"ReduceMax\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},877665:(s,c,f,b,w)=>{u.jb(\"ReduceMin\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},877839:(s,c,f,b,w)=>{u.jb(\"ReduceProd\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},878014:(s,c,f,b,w)=>{u.jb(\"ReduceSum\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},878188:(s,c,f,b,w)=>{u.jb(\"ReduceL1\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},878361:(s,c,f,b,w)=>{u.jb(\"ReduceL2\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},878534:(s,c,f,b,w)=>{u.jb(\"ReduceLogSum\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},878711:(s,c,f,b,w)=>{u.jb(\"ReduceSumSquare\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},878891:(s,c,f,b,w)=>{u.jb(\"ReduceLogSumExp\",s,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},879071:s=>{u.jb(\"Where\",s,void 0)},879124:(s,c,f)=>{u.jb(\"Transpose\",s,{perm:c?Array.from(i().subarray(Number(c)>>>0,Number(f)>>>0)):[]})},879248:(s,c,f,b)=>{u.jb(\"DepthToSpace\",s,{blocksize:c,mode:Te(f),format:b?\"NHWC\":\"NCHW\"})},879381:(s,c,f,b)=>{u.jb(\"DepthToSpace\",s,{blocksize:c,mode:Te(f),format:b?\"NHWC\":\"NCHW\"})},879514:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z,le)=>{u.jb(\"ConvTranspose\",s,{format:L?\"NHWC\":\"NCHW\",autoPad:c,dilations:[f],group:b,kernelShape:[w],pads:[I,B],strides:[D],wIsConst:()=>!!t()[H>>>0],outputPadding:Q?Array.from(i().subarray(Number(Q)>>>0,Number(ce)>>>0)):[],outputShape:ge?Array.from(i().subarray(Number(ge)>>>0,Number(z)>>>0)):[],activation:Te(le)})},879947:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z)=>{u.jb(\"ConvTranspose\",s,{format:D?\"NHWC\":\"NCHW\",autoPad:c,dilations:Array.from(i().subarray(Number(f)>>>0,2+(Number(f)>>>0)>>>0)),group:b,kernelShape:Array.from(i().subarray(Number(w)>>>0,2+(Number(w)>>>0)>>>0)),pads:Array.from(i().subarray(Number(I)>>>0,4+(Number(I)>>>0)>>>0)),strides:Array.from(i().subarray(Number(B)>>>0,2+(Number(B)>>>0)>>>0)),wIsConst:()=>!!t()[L>>>0],outputPadding:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],outputShape:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[],activation:Te(z)})},880608:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z,le)=>{u.jb(\"ConvTranspose\",s,{format:L?\"NHWC\":\"NCHW\",autoPad:c,dilations:[f],group:b,kernelShape:[w],pads:[I,B],strides:[D],wIsConst:()=>!!t()[H>>>0],outputPadding:Q?Array.from(i().subarray(Number(Q)>>>0,Number(ce)>>>0)):[],outputShape:ge?Array.from(i().subarray(Number(ge)>>>0,Number(z)>>>0)):[],activation:Te(le)})},881041:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z)=>{u.jb(\"ConvTranspose\",s,{format:D?\"NHWC\":\"NCHW\",autoPad:c,dilations:Array.from(i().subarray(Number(f)>>>0,2+(Number(f)>>>0)>>>0)),group:b,kernelShape:Array.from(i().subarray(Number(w)>>>0,2+(Number(w)>>>0)>>>0)),pads:Array.from(i().subarray(Number(I)>>>0,4+(Number(I)>>>0)>>>0)),strides:Array.from(i().subarray(Number(B)>>>0,2+(Number(B)>>>0)>>>0)),wIsConst:()=>!!t()[L>>>0],outputPadding:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],outputShape:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[],activation:Te(z)})},881702:(s,c)=>{u.jb(\"GlobalAveragePool\",s,{format:c?\"NHWC\":\"NCHW\"})},881793:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z)=>{u.jb(\"AveragePool\",s,{format:z?\"NHWC\":\"NCHW\",auto_pad:c,ceil_mode:f,count_include_pad:b,storage_order:w,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(B)>>>0)):[],kernel_shape:D?Array.from(i().subarray(Number(D)>>>0,Number(L)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},882272:(s,c)=>{u.jb(\"GlobalAveragePool\",s,{format:c?\"NHWC\":\"NCHW\"})},882363:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z)=>{u.jb(\"AveragePool\",s,{format:z?\"NHWC\":\"NCHW\",auto_pad:c,ceil_mode:f,count_include_pad:b,storage_order:w,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(B)>>>0)):[],kernel_shape:D?Array.from(i().subarray(Number(D)>>>0,Number(L)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},882842:(s,c)=>{u.jb(\"GlobalMaxPool\",s,{format:c?\"NHWC\":\"NCHW\"})},882929:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z)=>{u.jb(\"MaxPool\",s,{format:z?\"NHWC\":\"NCHW\",auto_pad:c,ceil_mode:f,count_include_pad:b,storage_order:w,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(B)>>>0)):[],kernel_shape:D?Array.from(i().subarray(Number(D)>>>0,Number(L)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},883404:(s,c)=>{u.jb(\"GlobalMaxPool\",s,{format:c?\"NHWC\":\"NCHW\"})},883491:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z)=>{u.jb(\"MaxPool\",s,{format:z?\"NHWC\":\"NCHW\",auto_pad:c,ceil_mode:f,count_include_pad:b,storage_order:w,dilations:I?Array.from(i().subarray(Number(I)>>>0,Number(B)>>>0)):[],kernel_shape:D?Array.from(i().subarray(Number(D)>>>0,Number(L)>>>0)):[],pads:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],strides:ce?Array.from(i().subarray(Number(ce)>>>0,Number(ge)>>>0)):[]})},883966:(s,c,f,b,w)=>{u.jb(\"Gemm\",s,{alpha:c,beta:f,transA:b,transB:w})},884070:s=>{u.jb(\"MatMul\",s,void 0)},884124:(s,c,f,b)=>{u.jb(\"ArgMax\",s,{keepDims:!!c,selectLastIndex:!!f,axis:b})},884232:(s,c,f,b)=>{u.jb(\"ArgMin\",s,{keepDims:!!c,selectLastIndex:!!f,axis:b})},884340:(s,c)=>{u.jb(\"Softmax\",s,{axis:c})},884403:(s,c)=>{u.jb(\"Concat\",s,{axis:c})},884463:(s,c,f,b,w)=>{u.jb(\"Split\",s,{axis:c,numOutputs:f,splitSizes:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},884619:s=>{u.jb(\"Expand\",s,void 0)},884673:(s,c)=>{u.jb(\"Gather\",s,{axis:Number(c)})},884744:(s,c)=>{u.jb(\"GatherElements\",s,{axis:Number(c)})},884823:(s,c,f,b,w,I,B,D,L,H,Q)=>{u.jb(\"Resize\",s,{antialias:c,axes:f?Array.from(i().subarray(Number(f)>>>0,Number(b)>>>0)):[],coordinateTransformMode:Te(w),cubicCoeffA:I,excludeOutside:B,extrapolationValue:D,keepAspectRatioPolicy:Te(L),mode:Te(H),nearestMode:Te(Q)})},885185:(s,c,f,b,w,I,B)=>{u.jb(\"Slice\",s,{starts:c?Array.from(i().subarray(Number(c)>>>0,Number(f)>>>0)):[],ends:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[],axes:I?Array.from(i().subarray(Number(I)>>>0,Number(B)>>>0)):[]})},885449:s=>{u.jb(\"Tile\",s,void 0)},885501:(s,c,f)=>{u.jb(\"InstanceNormalization\",s,{epsilon:c,format:f?\"NHWC\":\"NCHW\"})},885615:(s,c,f)=>{u.jb(\"InstanceNormalization\",s,{epsilon:c,format:f?\"NHWC\":\"NCHW\"})},885729:s=>{u.jb(\"Range\",s,void 0)},885782:(s,c)=>{u.jb(\"Einsum\",s,{equation:Te(c)})},885863:(s,c,f,b,w)=>{u.jb(\"Pad\",s,{mode:c,value:f,pads:b?Array.from(i().subarray(Number(b)>>>0,Number(w)>>>0)):[]})},886006:(s,c,f,b,w,I)=>{u.jb(\"BatchNormalization\",s,{epsilon:c,momentum:f,spatial:!!w,trainingMode:!!b,format:I?\"NHWC\":\"NCHW\"})},886175:(s,c,f,b,w,I)=>{u.jb(\"BatchNormalization\",s,{epsilon:c,momentum:f,spatial:!!w,trainingMode:!!b,format:I?\"NHWC\":\"NCHW\"})},886344:(s,c,f)=>{u.jb(\"CumSum\",s,{exclusive:Number(c),reverse:Number(f)})},886441:(s,c,f)=>{u.jb(\"DequantizeLinear\",s,{axis:c,blockSize:f})},886531:(s,c,f,b,w)=>{u.jb(\"GridSample\",s,{align_corners:c,mode:Te(f),padding_mode:Te(b),format:w?\"NHWC\":\"NCHW\"})},886701:(s,c,f,b,w)=>{u.jb(\"GridSample\",s,{align_corners:c,mode:Te(f),padding_mode:Te(b),format:w?\"NHWC\":\"NCHW\"})},886871:(s,c)=>{u.jb(\"ScatterND\",s,{reduction:Te(c)})},886956:(s,c,f,b,w,I,B,D,L)=>{u.jb(\"Attention\",s,{numHeads:c,isUnidirectional:f,maskFilterValue:b,scale:w,doRotary:I,qkvHiddenSizes:B?Array.from(i().subarray(Number(D)>>>0,Number(D)+B>>>0)):[],pastPresentShareBuffer:!!L})},887228:s=>{u.jb(\"BiasAdd\",s,void 0)},887283:s=>{u.jb(\"BiasSplitGelu\",s,void 0)},887344:s=>{u.jb(\"FastGelu\",s,void 0)},887400:(s,c,f,b,w,I,B,D,L,H,Q,ce,ge,z,le,Ie)=>{u.jb(\"Conv\",s,{format:ce?\"NHWC\":\"NCHW\",auto_pad:c,dilations:f?Array.from(i().subarray(Number(f)>>>0,Number(b)>>>0)):[],group:w,kernel_shape:I?Array.from(i().subarray(Number(I)>>>0,Number(B)>>>0)):[],pads:D?Array.from(i().subarray(Number(D)>>>0,Number(L)>>>0)):[],strides:H?Array.from(i().subarray(Number(H)>>>0,Number(Q)>>>0)):[],w_is_const:()=>!!t()[Number(ge)>>>0],activation:Te(z),activation_params:le?Array.from(l().subarray(Number(le)>>>0,Number(Ie)>>>0)):[]})},887984:s=>{u.jb(\"Gelu\",s,void 0)},888036:(s,c,f,b,w,I,B,D,L)=>{u.jb(\"GroupQueryAttention\",s,{numHeads:c,kvNumHeads:f,scale:b,softcap:w,doRotary:I,rotaryInterleaved:B,smoothSoftmax:D,localWindowSize:L})},888253:(s,c,f,b)=>{u.jb(\"LayerNormalization\",s,{axis:c,epsilon:f,simplified:!!b})},888364:(s,c,f,b)=>{u.jb(\"LayerNormalization\",s,{axis:c,epsilon:f,simplified:!!b})},888475:(s,c,f,b,w,I)=>{u.jb(\"MatMulNBits\",s,{k:c,n:f,accuracyLevel:b,bits:w,blockSize:I})},888602:(s,c,f,b,w,I)=>{u.jb(\"MultiHeadAttention\",s,{numHeads:c,isUnidirectional:f,maskFilterValue:b,scale:w,doRotary:I})},888761:(s,c)=>{u.jb(\"QuickGelu\",s,{alpha:c})},888825:(s,c,f,b,w)=>{u.jb(\"RotaryEmbedding\",s,{interleaved:!!c,numHeads:f,rotaryEmbeddingDim:b,scale:w})},888964:(s,c,f)=>{u.jb(\"SkipLayerNormalization\",s,{epsilon:c,simplified:!!f})},889066:(s,c,f)=>{u.jb(\"SkipLayerNormalization\",s,{epsilon:c,simplified:!!f})},889168:(s,c,f,b)=>{u.jb(\"GatherBlockQuantized\",s,{gatherAxis:c,quantizeAxis:f,blockSize:b})},889289:s=>{u.Zb(s)},889323:(s,c)=>u.bc(Number(s),Number(c),u.Fb.fc,u.Fb.errors)};function gc(s,c,f){return wi(async()=>{await u.Xb(Number(s),Number(c),Number(f))})}function bc(){return typeof wasmOffsetConverter<\"u\"}function vn(s){this.name=\"ExitStatus\",this.message=`Program terminated with exit(${s})`,this.status=s}var $n=s=>{s.terminate(),s.onmessage=()=>{}},Wo=s=>{ct.length==0&&(jo(),qo(ct[0]));var c=ct.pop();if(!c)return 6;wt.push(c),Ye[s.Ab]=c,c.Ab=s.Ab;var f={cmd:\"run\",start_routine:s.hc,arg:s.Qb,pthread_ptr:s.Ab};return c.postMessage(f,s.mc),0},_t=0,xe=(s,c,...f)=>{for(var b=2*f.length,w=Wn(),I=Vn(8*b),B=I>>>3,D=0;D>>0]=L)}return s=Hi(s,0,b,I,c),gr(w),s};function xn(s){if(g)return xe(0,1,s);if(re=s,!(0<_t)){for(var c of wt)$n(c);for(c of ct)$n(c);ct=[],wt=[],Ye=[],_e=!0}A(s,new vn(s))}function Lo(s){if(g)return xe(1,0,s);Sn(s)}var Sn=s=>{if(re=s,g)throw Lo(s),\"unwind\";xn(s)},ct=[],wt=[],Go=[],Ye={},Ho=s=>{var c=s.Ab;delete Ye[c],ct.push(s),wt.splice(wt.indexOf(s),1),s.Ab=0,Nn(c)};function Fo(){Go.forEach(s=>s())}var qo=s=>new Promise(c=>{s.onmessage=w=>{var I=(w=w.data).cmd;if(w.targetThread&&w.targetThread!=Bt()){var B=Ye[w.targetThread];B?B.postMessage(w,w.transferList):K(`Internal error! Worker sent a message \"${I}\" to target pthread ${w.targetThread}, but that thread no longer exists!`)}else I===\"checkMailbox\"?ar():I===\"spawnThread\"?Wo(w):I===\"cleanupThread\"?Ho(Ye[w.thread]):I===\"killThread\"?(w=w.thread,I=Ye[w],delete Ye[w],$n(I),Nn(w),wt.splice(wt.indexOf(I),1),I.Ab=0):I===\"cancelThread\"?Ye[w.thread].postMessage({cmd:\"cancel\"}):I===\"loaded\"?(s.loaded=!0,c(s)):I===\"alert\"?alert(`Thread ${w.threadId}: ${w.text}`):w.target===\"setimmediate\"?s.postMessage(w):I===\"callHandler\"?u[w.handler](...w.args):I&&K(`worker sent an unknown command ${I}`)},s.onerror=w=>{throw K(`worker sent an error! ${w.filename}:${w.lineno}: ${w.message}`),w};var f,b=[];for(f of[])u.hasOwnProperty(f)&&b.push(f);s.postMessage({cmd:\"load\",handlers:b,wasmMemory:se,wasmModule:X})});function jo(){var s=new Worker(new URL(import.meta.url),{type:\"module\",workerData:\"em-pthread\",name:\"em-pthread\"});ct.push(s)}var ir=s=>{for(;0{var s=Bt(),c=a()[s+52>>>2>>>0];s=a()[s+56>>>2>>>0],qi(c,c-s),gr(c)},_c=(s,c)=>{_t=0,s=ji(s,c),0<_t?re=s:hr(s)};class wc{constructor(c){this.Jb=c-24}}function vc(s,c,f){var b=new wc(s>>>=0);throw c>>>=0,f>>>=0,a()[b.Jb+16>>>2>>>0]=0,a()[b.Jb+4>>>2>>>0]=c,a()[b.Jb+8>>>2>>>0]=f,s}function Ko(s,c,f,b){return g?xe(2,1,s,c,f,b):Yo(s,c,f,b)}function Yo(s,c,f,b){if(s>>>=0,c>>>=0,f>>>=0,b>>>=0,x===void 0)return K(\"Current environment does not support SharedArrayBuffer, pthreads are not available!\"),6;var w=[];return g&&w.length===0?Ko(s,c,f,b):(s={hc:f,Ab:s,Qb:b,mc:w},g?(s.Mb=\"spawnThread\",postMessage(s,w),0):Wo(s))}var Zo=typeof TextDecoder<\"u\"?new TextDecoder(\"utf8\"):void 0,Qo=(s,c,f)=>{var b=(c>>>=0)+f;for(f=c;s[f]&&!(f>=b);)++f;if(16(w=(240&w)==224?(15&w)<<12|I<<6|B:(7&w)<<18|I<<12|B<<6|63&s[c++])?b+=String.fromCharCode(w):(w-=65536,b+=String.fromCharCode(55296|w>>10,56320|1023&w))}}else b+=String.fromCharCode(w)}return b},Te=(s,c)=>(s>>>=0)?Qo(r(),s,c):\"\";function Xo(s,c,f){return g?xe(3,1,s,c,f):0}function Jo(s,c){if(g)return xe(4,1,s,c)}var Tn=s=>{for(var c=0,f=0;f=b?c++:2047>=b?c+=2:55296<=b&&57343>=b?(c+=4,++f):c+=3}return c},ei=(s,c,f,b)=>{if(!(0>>=0;b=f+b-1;for(var I=0;I=B&&(B=65536+((1023&B)<<10)|1023&s.charCodeAt(++I)),127>=B){if(f>=b)break;c[f++>>>0]=B}else{if(2047>=B){if(f+1>=b)break;c[f++>>>0]=192|B>>6}else{if(65535>=B){if(f+2>=b)break;c[f++>>>0]=224|B>>12}else{if(f+3>=b)break;c[f++>>>0]=240|B>>18,c[f++>>>0]=128|B>>12&63}c[f++>>>0]=128|B>>6&63}c[f++>>>0]=128|63&B}}return c[f>>>0]=0,f-w},Pt=(s,c,f)=>ei(s,r(),c,f);function ti(s,c){if(g)return xe(5,1,s,c)}function ri(s,c,f){if(g)return xe(6,1,s,c,f)}function ni(s,c,f){return g?xe(7,1,s,c,f):0}function oi(s,c){if(g)return xe(8,1,s,c)}function ii(s,c,f){if(g)return xe(9,1,s,c,f)}function ai(s,c,f,b){if(g)return xe(10,1,s,c,f,b)}function si(s,c,f,b){if(g)return xe(11,1,s,c,f,b)}function ui(s,c,f,b){if(g)return xe(12,1,s,c,f,b)}function li(s){if(g)return xe(13,1,s)}function di(s,c){if(g)return xe(14,1,s,c)}function ci(s,c,f){if(g)return xe(15,1,s,c,f)}var pi,pt,$c=()=>{dt(\"\")},Ze=s=>{for(var c=\"\";r()[s>>>0];)c+=pi[r()[s++>>>0]];return c},In={},Cn={},xc={};function at(s,c,f={}){if(!(\"argPackAdvance\"in c))throw new TypeError(\"registerType registeredInstance requires argPackAdvance\");return function(b,w,I={}){var B=w.name;if(!b)throw new pt(`type \"${B}\" must have a positive integer typeid pointer`);if(Cn.hasOwnProperty(b)){if(I.Sb)return;throw new pt(`Cannot register type '${B}' twice`)}Cn[b]=w,delete xc[b],In.hasOwnProperty(b)&&(w=In[b],delete In[b],w.forEach(D=>D()))}(s,c,f)}var mi=(s,c,f)=>{switch(c){case 1:return f?b=>t()[b>>>0]:b=>r()[b>>>0];case 2:return f?b=>n()[b>>>1>>>0]:b=>o()[b>>>1>>>0];case 4:return f?b=>i()[b>>>2>>>0]:b=>a()[b>>>2>>>0];case 8:return f?b=>j[b>>>3]:b=>he[b>>>3];default:throw new TypeError(`invalid integer width (${c}): ${s}`)}};function Sc(s,c,f){f>>>=0,at(s>>>=0,{name:c=Ze(c>>>0),fromWireType:b=>b,toWireType:function(b,w){if(typeof w!=\"bigint\"&&typeof w!=\"number\")throw w=w===null?\"null\":(b=typeof w)==\"object\"||b===\"array\"||b===\"function\"?w.toString():\"\"+w,new TypeError(`Cannot convert \"${w}\" to ${this.name}`);return typeof w==\"number\"&&(w=BigInt(w)),w},argPackAdvance:mt,readValueFromPointer:mi(c,f,c.indexOf(\"u\")==-1),Db:null})}var mt=8;function Tc(s,c,f,b){at(s>>>=0,{name:c=Ze(c>>>0),fromWireType:function(w){return!!w},toWireType:function(w,I){return I?f:b},argPackAdvance:mt,readValueFromPointer:function(w){return this.fromWireType(r()[w>>>0])},Db:null})}var An=[],st=[];function kn(s){9<(s>>>=0)&&--st[s+1]==0&&(st[s]=void 0,An.push(s))}var Ne=s=>{if(!s)throw new pt(\"Cannot use deleted val. handle = \"+s);return st[s]},Ve=s=>{switch(s){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let c=An.pop()||st.length;return st[c]=s,st[c+1]=1,c}};function En(s){return this.fromWireType(a()[s>>>2>>>0])}var Ic={name:\"emscripten::val\",fromWireType:s=>{var c=Ne(s);return kn(s),c},toWireType:(s,c)=>Ve(c),argPackAdvance:mt,readValueFromPointer:En,Db:null};function Cc(s){return at(s>>>0,Ic)}var Ac=(s,c)=>{switch(c){case 4:return function(f){return this.fromWireType(l()[f>>>2>>>0])};case 8:return function(f){return this.fromWireType(d()[f>>>3>>>0])};default:throw new TypeError(`invalid float width (${c}): ${s}`)}};function kc(s,c,f){f>>>=0,at(s>>>=0,{name:c=Ze(c>>>0),fromWireType:b=>b,toWireType:(b,w)=>w,argPackAdvance:mt,readValueFromPointer:Ac(c,f),Db:null})}function Ec(s,c,f,b,w){if(s>>>=0,f>>>=0,c=Ze(c>>>0),w===-1&&(w=4294967295),w=D=>D,b===0){var I=32-8*f;w=D=>D<>>I}var B=c.includes(\"unsigned\")?function(D,L){return L>>>0}:function(D,L){return L};at(s,{name:c,fromWireType:w,toWireType:B,argPackAdvance:mt,readValueFromPointer:mi(c,f,b!==0),Db:null})}function Pc(s,c,f){function b(I){var B=a()[I>>>2>>>0];return I=a()[I+4>>>2>>>0],new w(t().buffer,I,B)}var w=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][c];at(s>>>=0,{name:f=Ze(f>>>0),fromWireType:b,argPackAdvance:mt,readValueFromPointer:b},{Sb:!0})}function zc(s,c){s>>>=0;var f=(c=Ze(c>>>0))===\"std::string\";at(s,{name:c,fromWireType:function(b){var w=a()[b>>>2>>>0],I=b+4;if(f)for(var B=I,D=0;D<=w;++D){var L=I+D;if(D==w||r()[L>>>0]==0){if(B=Te(B,L-B),H===void 0)var H=B;else H+=String.fromCharCode(0),H+=B;B=L+1}}else{for(H=Array(w),D=0;D>>0]);H=H.join(\"\")}return Xe(b),H},toWireType:function(b,w){w instanceof ArrayBuffer&&(w=new Uint8Array(w));var I=typeof w==\"string\";if(!(I||w instanceof Uint8Array||w instanceof Uint8ClampedArray||w instanceof Int8Array))throw new pt(\"Cannot pass non-string to std::string\");var B=f&&I?Tn(w):w.length,D=fr(4+B+1),L=D+4;if(a()[D>>>2>>>0]=B,f&&I)Pt(w,L,B+1);else if(I)for(I=0;I>>0]=H}else for(I=0;I>>0]=w[I];return b!==null&&b.push(Xe,D),D},argPackAdvance:mt,readValueFromPointer:En,Db(b){Xe(b)}})}var fi=typeof TextDecoder<\"u\"?new TextDecoder(\"utf-16le\"):void 0,Oc=(s,c)=>{for(var f=s>>1,b=f+c/2;!(f>=b)&&o()[f>>>0];)++f;if(32<(f<<=1)-s&&fi)return fi.decode(r().slice(s,f));for(f=\"\",b=0;!(b>=c/2);++b){var w=n()[s+2*b>>>1>>>0];if(w==0)break;f+=String.fromCharCode(w)}return f},Bc=(s,c,f)=>{if(f??=2147483647,2>f)return 0;var b=c;f=(f-=2)<2*s.length?f/2:s.length;for(var w=0;w>>1>>>0]=I,c+=2}return n()[c>>>1>>>0]=0,c-b},Dc=s=>2*s.length,Mc=(s,c)=>{for(var f=0,b=\"\";!(f>=c/4);){var w=i()[s+4*f>>>2>>>0];if(w==0)break;++f,65536<=w?(w-=65536,b+=String.fromCharCode(55296|w>>10,56320|1023&w)):b+=String.fromCharCode(w)}return b},Rc=(s,c,f)=>{if(c>>>=0,f??=2147483647,4>f)return 0;var b=c;f=b+f-4;for(var w=0;w=I&&(I=65536+((1023&I)<<10)|1023&s.charCodeAt(++w)),i()[c>>>2>>>0]=I,(c+=4)+4>f)break}return i()[c>>>2>>>0]=0,c-b},Uc=s=>{for(var c=0,f=0;f=b&&++f,c+=4}return c};function Nc(s,c,f){if(s>>>=0,c>>>=0,f=Ze(f>>>=0),c===2)var b=Oc,w=Bc,I=Dc,B=D=>o()[D>>>1>>>0];else c===4&&(b=Mc,w=Rc,I=Uc,B=D=>a()[D>>>2>>>0]);at(s,{name:f,fromWireType:D=>{for(var L,H=a()[D>>>2>>>0],Q=D+4,ce=0;ce<=H;++ce){var ge=D+4+ce*c;ce!=H&&B(ge)!=0||(Q=b(Q,ge-Q),L===void 0?L=Q:(L+=String.fromCharCode(0),L+=Q),Q=ge+c)}return Xe(D),L},toWireType:(D,L)=>{if(typeof L!=\"string\")throw new pt(`Cannot pass non-string to C++ string type ${f}`);var H=I(L),Q=fr(4+H+c);return a()[Q>>>2>>>0]=H/c,w(L,Q+4,H+c),D!==null&&D.push(Xe,Q),Q},argPackAdvance:mt,readValueFromPointer:En,Db(D){Xe(D)}})}function Vc(s,c){at(s>>>=0,{Tb:!0,name:c=Ze(c>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Wc=()=>1;function Lc(s){Un(s>>>0,!y,1,!_,131072,!1),Fo()}var hi=s=>{if(!_e)try{if(s(),!(0<_t))try{g?hr(re):Sn(re)}catch(c){c instanceof vn||c==\"unwind\"||A(1,c)}}catch(c){c instanceof vn||c==\"unwind\"||A(1,c)}};function Pn(s){s>>>=0,typeof Atomics.nc==\"function\"&&(Atomics.nc(i(),s>>>2,s).value.then(ar),s+=128,Atomics.store(i(),s>>>2,1))}var ar=()=>{var s=Bt();s&&(Pn(s),hi(Fi))};function Gc(s,c){(s>>>=0)==c>>>0?setTimeout(ar):g?postMessage({targetThread:s,cmd:\"checkMailbox\"}):(s=Ye[s])&&s.postMessage({cmd:\"checkMailbox\"})}var zn=[];function Hc(s,c,f,b,w){for(c>>>=0,b/=2,zn.length=b,f=w>>>0>>>3,w=0;w>>0];return(c?wn[c]:Op[s])(...zn)}function Fc(s){s>>>=0,g?postMessage({cmd:\"cleanupThread\",thread:s}):Ho(Ye[s])}function qc(s){}var On=(s,c)=>{var f=Cn[s];if(f===void 0)throw s=Wi(s),f=Ze(s),Xe(s),new pt(`${c} has unknown type ${f}`);return f},gi=(s,c,f)=>{var b=[];return s=s.toWireType(b,f),b.length&&(a()[c>>>2>>>0]=Ve(b)),s};function jc(s,c,f){return c>>>=0,f>>>=0,s=Ne(s>>>0),c=On(c,\"emval::as\"),gi(c,f,s)}var sr=s=>{try{s()}catch(c){dt(c)}},ft=0,Qe=null,bi=0,ur=[],yi={},_i={},Kc=0,Bn=null,Yc=[];function wi(s){return function(c){if(!_e){if(ft===0){var f=!1,b=!1;c((w=0)=>{if(!_e&&(bi=w,f=!0,b)){ft=2,sr(()=>Zi(Qe)),typeof Browser<\"u\"&&Browser.Kb.Rb&&Browser.Kb.resume(),w=!1;try{var I=function(){var L=i()[Qe+8>>>2>>>0];return L=Z[_i[L]],--_t,L()}()}catch(L){I=L,w=!0}var B=!1;if(!Qe){var D=Bn;D&&(Bn=null,(w?D.reject:D.resolve)(I),B=!0)}if(w&&!B)throw I}}),b=!0,f||(ft=1,Qe=function(){var w=fr(65548),I=w+12;a()[w>>>2>>>0]=I,a()[w+4>>>2>>>0]=I+65536,I=ur[0];var B=yi[I];return B===void 0&&(B=Kc++,yi[I]=B,_i[B]=I),I=B,i()[w+8>>>2>>>0]=I,w}(),typeof Browser<\"u\"&&Browser.Kb.Rb&&Browser.Kb.pause(),sr(()=>Ki(Qe)))}else ft===2?(ft=0,sr(Qi),Xe(Qe),Qe=null,Yc.forEach(hi)):dt(`invalid state: ${ft}`);return bi}}(c=>{s().then(c)})}function Zc(s){return s>>>=0,wi(()=>(s=Ne(s)).then(Ve))}var lr=[];function Qc(s,c,f,b){return f>>>=0,b>>>=0,(s=lr[s>>>0])(null,c=Ne(c>>>0),f,b)}var Xc={},dr=s=>{var c=Xc[s];return c===void 0?Ze(s):c};function Jc(s,c,f,b,w){return f>>>=0,b>>>=0,w>>>=0,(s=lr[s>>>0])(c=Ne(c>>>0),c[f=dr(f)],b,w)}var vi=()=>typeof globalThis==\"object\"?globalThis:Function(\"return this\")();function ep(s){return(s>>>=0)==0?Ve(vi()):(s=dr(s),Ve(vi()[s]))}var tp=s=>{var c=lr.length;return lr.push(s),c},rp=(s,c)=>{for(var f=Array(s),b=0;b>>2>>>0],\"parameter \"+b);return f},$i=(s,c)=>Object.defineProperty(c,\"name\",{value:s});function np(s,c,f){var b=(c=rp(s,c>>>0)).shift();s--;var w=`return function (obj, func, destructorsRef, args) {\n`,I=0,B=[];f===0&&B.push(\"obj\");for(var D=[\"retType\"],L=[b],H=0;HQ.name).join(\", \")}) => ${b.name}>`,tp($i(f,s))}function op(s){return s=dr(s>>>0),Ve(u[s])}function ip(s,c){return c>>>=0,s=Ne(s>>>0),c=Ne(c),Ve(s[c])}function ap(s){9<(s>>>=0)&&(st[s+1]+=1)}function sp(){return Ve([])}function up(s){s=Ne(s>>>0);for(var c=Array(s.length),f=0;f>>0))}function dp(){return Ve({})}function cp(s){for(var c=Ne(s>>>=0);c.length;){var f=c.pop();c.pop()(f)}kn(s)}function pp(s,c,f){c>>>=0,f>>>=0,s=Ne(s>>>0),c=Ne(c),f=Ne(f),s[c]=f}function mp(s,c){return c>>>=0,s=(s=On(s>>>0,\"_emval_take_value\")).readValueFromPointer(c),Ve(s)}function fp(s,c){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),i()[c>>>2>>>0]=s.getUTCSeconds(),i()[c+4>>>2>>>0]=s.getUTCMinutes(),i()[c+8>>>2>>>0]=s.getUTCHours(),i()[c+12>>>2>>>0]=s.getUTCDate(),i()[c+16>>>2>>>0]=s.getUTCMonth(),i()[c+20>>>2>>>0]=s.getUTCFullYear()-1900,i()[c+24>>>2>>>0]=s.getUTCDay(),s=(s.getTime()-Date.UTC(s.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[c+28>>>2>>>0]=s}var zt=s=>s%4==0&&(s%100!=0||s%400==0),xi=[0,31,60,91,121,152,182,213,244,274,305,335],Si=[0,31,59,90,120,151,181,212,243,273,304,334];function hp(s,c){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),i()[c>>>2>>>0]=s.getSeconds(),i()[c+4>>>2>>>0]=s.getMinutes(),i()[c+8>>>2>>>0]=s.getHours(),i()[c+12>>>2>>>0]=s.getDate(),i()[c+16>>>2>>>0]=s.getMonth(),i()[c+20>>>2>>>0]=s.getFullYear()-1900,i()[c+24>>>2>>>0]=s.getDay();var f=(zt(s.getFullYear())?xi:Si)[s.getMonth()]+s.getDate()-1|0;i()[c+28>>>2>>>0]=f,i()[c+36>>>2>>>0]=-60*s.getTimezoneOffset(),f=new Date(s.getFullYear(),6,1).getTimezoneOffset();var b=new Date(s.getFullYear(),0,1).getTimezoneOffset();s=0|(f!=b&&s.getTimezoneOffset()==Math.min(b,f)),i()[c+32>>>2>>>0]=s}function gp(s){s>>>=0;var c=new Date(i()[s+20>>>2>>>0]+1900,i()[s+16>>>2>>>0],i()[s+12>>>2>>>0],i()[s+8>>>2>>>0],i()[s+4>>>2>>>0],i()[s>>>2>>>0],0),f=i()[s+32>>>2>>>0],b=c.getTimezoneOffset(),w=new Date(c.getFullYear(),6,1).getTimezoneOffset(),I=new Date(c.getFullYear(),0,1).getTimezoneOffset(),B=Math.min(I,w);return 0>f?i()[s+32>>>2>>>0]=+(w!=I&&B==b):0>>2>>>0]=c.getDay(),f=(zt(c.getFullYear())?xi:Si)[c.getMonth()]+c.getDate()-1|0,i()[s+28>>>2>>>0]=f,i()[s>>>2>>>0]=c.getSeconds(),i()[s+4>>>2>>>0]=c.getMinutes(),i()[s+8>>>2>>>0]=c.getHours(),i()[s+12>>>2>>>0]=c.getDate(),i()[s+16>>>2>>>0]=c.getMonth(),i()[s+20>>>2>>>0]=c.getYear(),s=c.getTime(),BigInt(isNaN(s)?-1:s/1e3)}function Ti(s,c,f,b,w,I,B){return g?xe(16,1,s,c,f,b,w,I,B):-52}function Ii(s,c,f,b,w,I){if(g)return xe(17,1,s,c,f,b,w,I)}function bp(s,c,f,b){s>>>=0,c>>>=0,f>>>=0,b>>>=0;var w=new Date().getFullYear(),I=new Date(w,0,1),B=new Date(w,6,1);w=I.getTimezoneOffset();var D=B.getTimezoneOffset(),L=Math.max(w,D);a()[s>>>2>>>0]=60*L,i()[c>>>2>>>0]=+(w!=D),I=(s=H=>H.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:\"short\"}).split(\" \")[1])(I),B=s(B),D{Dn.length=0;for(var f;f=r()[s++>>>0];){var b=f!=105;c+=(b&=f!=112)&&c%8?4:0,Dn.push(f==112?a()[c>>>2>>>0]:f==106?j[c>>>3]:f==105?i()[c>>>2>>>0]:d()[c>>>3>>>0]),c+=b?8:4}return Dn};function yp(s,c,f){return s>>>=0,c=Ci(c>>>0,f>>>0),wn[s](...c)}function _p(s,c,f){return s>>>=0,c=Ci(c>>>0,f>>>0),wn[s](...c)}var wp=()=>{},vp=()=>Date.now();function $p(s,c){return K(Te(s>>>0,c>>>0))}var Ai,xp=()=>{throw _t+=1,\"unwind\"};function Sp(){return 4294901760}Ai=()=>performance.timeOrigin+performance.now();var Tp=()=>navigator.hardwareConcurrency;function Ip(){return dt(\"Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER\"),0}function Cp(s){s>>>=0;var c=r().length;if(s<=c||4294901760=f;f*=2){var b=c*(1+.2/f);b=Math.min(b,s+100663296);var w=Math;b=Math.max(s,b);e:{w=(w.min.call(w,4294901760,b+(65536-b%65536)%65536)-se.buffer.byteLength+65535)/65536;try{se.grow(w),be();var I=1;break e}catch{}I=void 0}if(I)return!0}return!1}var cr=()=>(dt(\"Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER\"),0),Ot={},ki=s=>{s.forEach(c=>{var f=cr();f&&(Ot[f]=c)})};function Ap(){var s=Error().stack.toString().split(`\n`);return s[0]==\"Error\"&&s.shift(),ki(s),Ot.Pb=cr(),Ot.ec=s,Ot.Pb}function kp(s,c,f){if(s>>>=0,c>>>=0,Ot.Pb==s)var b=Ot.ec;else(b=Error().stack.toString().split(`\n`))[0]==\"Error\"&&b.shift(),ki(b);for(var w=3;b[w]&&cr()!=s;)++w;for(s=0;s>>2>>>0]=cr();return s}var Mn,Rn={},Ei=()=>{if(!Mn){var s,c={USER:\"web_user\",LOGNAME:\"web_user\",PATH:\"/\",PWD:\"/\",HOME:\"/home/web_user\",LANG:(typeof navigator==\"object\"&&navigator.languages&&navigator.languages[0]||\"C\").replace(\"-\",\"_\")+\".UTF-8\",_:C||\"./this.program\"};for(s in Rn)Rn[s]===void 0?delete c[s]:c[s]=Rn[s];var f=[];for(s in c)f.push(`${s}=${c[s]}`);Mn=f}return Mn};function Pi(s,c){if(g)return xe(18,1,s,c);s>>>=0,c>>>=0;var f=0;return Ei().forEach((b,w)=>{var I=c+f;for(w=a()[s+4*w>>>2>>>0]=I,I=0;I>>0]=b.charCodeAt(I);t()[w>>>0]=0,f+=b.length+1}),0}function zi(s,c){if(g)return xe(19,1,s,c);s>>>=0,c>>>=0;var f=Ei();a()[s>>>2>>>0]=f.length;var b=0;return f.forEach(w=>b+=w.length+1),a()[c>>>2>>>0]=b,0}function Oi(s){return g?xe(20,1,s):52}function Bi(s,c,f,b){return g?xe(21,1,s,c,f,b):52}function Di(s,c,f,b){return g?xe(22,1,s,c,f,b):70}var Ep=[null,[],[]];function Mi(s,c,f,b){if(g)return xe(23,1,s,c,f,b);c>>>=0,f>>>=0,b>>>=0;for(var w=0,I=0;I>>2>>>0],D=a()[c+4>>>2>>>0];c+=8;for(var L=0;L>>0],Q=Ep[s];H===0||H===10?((s===1?q:K)(Qo(Q,0)),Q.length=0):Q.push(H)}w+=D}return a()[b>>>2>>>0]=w,0}var Ri=[31,29,31,30,31,30,31,31,30,31,30,31],Ui=[31,28,31,30,31,30,31,31,30,31,30,31],Pp=(s,c)=>{t().set(s,c>>>0)};function Ni(s,c,f,b){function w(z,le,Ie){for(z=typeof z==\"number\"?z.toString():z||\"\";z.lengthJi?-1:0vt-z.getDate())){z.setDate(z.getDate()+le);break}le-=vt-z.getDate()+1,z.setDate(1),11>Ie?z.setMonth(Ie+1):(z.setMonth(0),z.setFullYear(z.getFullYear()+1))}return Ie=new Date(z.getFullYear()+1,0,4),le=D(new Date(z.getFullYear(),0,4)),Ie=D(Ie),0>=B(le,z)?0>=B(Ie,z)?z.getFullYear()+1:z.getFullYear():z.getFullYear()-1}s>>>=0,c>>>=0,f>>>=0,b>>>=0;var H=a()[b+40>>>2>>>0];for(var Q in b={kc:i()[b>>>2>>>0],jc:i()[b+4>>>2>>>0],Hb:i()[b+8>>>2>>>0],Lb:i()[b+12>>>2>>>0],Ib:i()[b+16>>>2>>>0],Cb:i()[b+20>>>2>>>0],ub:i()[b+24>>>2>>>0],Bb:i()[b+28>>>2>>>0],rc:i()[b+32>>>2>>>0],ic:i()[b+36>>>2>>>0],lc:H?Te(H):\"\"},f=Te(f),H={\"%c\":\"%a %b %d %H:%M:%S %Y\",\"%D\":\"%m/%d/%y\",\"%F\":\"%Y-%m-%d\",\"%h\":\"%b\",\"%r\":\"%I:%M:%S %p\",\"%R\":\"%H:%M\",\"%T\":\"%H:%M:%S\",\"%x\":\"%m/%d/%y\",\"%X\":\"%H:%M:%S\",\"%Ec\":\"%c\",\"%EC\":\"%C\",\"%Ex\":\"%m/%d/%y\",\"%EX\":\"%H:%M:%S\",\"%Ey\":\"%y\",\"%EY\":\"%Y\",\"%Od\":\"%d\",\"%Oe\":\"%e\",\"%OH\":\"%H\",\"%OI\":\"%I\",\"%Om\":\"%m\",\"%OM\":\"%M\",\"%OS\":\"%S\",\"%Ou\":\"%u\",\"%OU\":\"%U\",\"%OV\":\"%V\",\"%Ow\":\"%w\",\"%OW\":\"%W\",\"%Oy\":\"%y\"})f=f.replace(new RegExp(Q,\"g\"),H[Q]);var ce=\"Sunday Monday Tuesday Wednesday Thursday Friday Saturday\".split(\" \"),ge=\"January February March April May June July August September October November December\".split(\" \");for(Q in H={\"%a\":z=>ce[z.ub].substring(0,3),\"%A\":z=>ce[z.ub],\"%b\":z=>ge[z.Ib].substring(0,3),\"%B\":z=>ge[z.Ib],\"%C\":z=>I((z.Cb+1900)/100|0,2),\"%d\":z=>I(z.Lb,2),\"%e\":z=>w(z.Lb,2,\" \"),\"%g\":z=>L(z).toString().substring(2),\"%G\":L,\"%H\":z=>I(z.Hb,2),\"%I\":z=>((z=z.Hb)==0?z=12:12{for(var le=0,Ie=0;Ie<=z.Ib-1;le+=(zt(z.Cb+1900)?Ri:Ui)[Ie++]);return I(z.Lb+le,3)},\"%m\":z=>I(z.Ib+1,2),\"%M\":z=>I(z.jc,2),\"%n\":()=>`\n`,\"%p\":z=>0<=z.Hb&&12>z.Hb?\"AM\":\"PM\",\"%S\":z=>I(z.kc,2),\"%t\":()=>\"\t\",\"%u\":z=>z.ub||7,\"%U\":z=>I(Math.floor((z.Bb+7-z.ub)/7),2),\"%V\":z=>{var le=Math.floor((z.Bb+7-(z.ub+6)%7)/7);if(2>=(z.ub+371-z.Bb-2)%7&&le++,le)le==53&&((Ie=(z.ub+371-z.Bb)%7)==4||Ie==3&&zt(z.Cb)||(le=1));else{le=52;var Ie=(z.ub+7-z.Bb-1)%7;(Ie==4||Ie==5&&zt(z.Cb%400-1))&&le++}return I(le,2)},\"%w\":z=>z.ub,\"%W\":z=>I(Math.floor((z.Bb+7-(z.ub+6)%7)/7),2),\"%y\":z=>(z.Cb+1900).toString().substring(2),\"%Y\":z=>z.Cb+1900,\"%z\":z=>{var le=0<=(z=z.ic);return z=Math.abs(z)/60,(le?\"+\":\"-\")+(\"0000\"+(z/60*100+z%60)).slice(-4)},\"%Z\":z=>z.lc,\"%%\":()=>\"%\"},f=f.replace(/%%/g,\"\\0\\0\"),H)f.includes(Q)&&(f=f.replace(new RegExp(Q,\"g\"),H[Q](b)));return Q=function(z){var le=Array(Tn(z)+1);return ei(z,le,0,le.length),le}(f=f.replace(/\\0\\0/g,\"%\")),Q.length>c?0:(Pp(Q,s),Q.length-1)}function zp(s,c,f,b){return Ni(s>>>0,c>>>0,f>>>0,b>>>0)}g||function(){for(var s=u.numThreads-1;s--;)jo();Ke.unshift(()=>{Gt++,function(c){g?c():Promise.all(ct.map(qo)).then(c)}(()=>Do())})}();for(var Vi=Array(256),pr=0;256>pr;++pr)Vi[pr]=String.fromCharCode(pr);pi=Vi,pt=u.BindingError=class extends Error{constructor(s){super(s),this.name=\"BindingError\"}},u.InternalError=class extends Error{constructor(s){super(s),this.name=\"InternalError\"}},st.push(0,1,void 0,1,null,1,!0,1,!1,1),u.count_emval_handles=()=>st.length/2-5-An.length;var Op=[xn,Lo,Ko,Xo,Jo,ti,ri,ni,oi,ii,ai,si,ui,li,di,ci,Ti,Ii,Pi,zi,Oi,Bi,Di,Mi],Z=function(){function s(f,b){return Z=f.exports,Z=function(){var w=Z,I={};for(let[B,D]of Object.entries(w))I[B]=typeof D==\"function\"?(...L)=>{ur.push(B);try{return D(...L)}finally{_e||(ur.pop(),Qe&&ft===1&&ur.length===0&&(ft=0,_t+=1,sr(Yi),typeof Fibers<\"u\"&&Fibers.sc()))}}:D;return I}(),Z=function(){var w=Z,I=D=>L=>D(L)>>>0,B=D=>()=>D()>>>0;return(w=Object.assign({},w)).Ca=I(w.Ca),w.fb=B(w.fb),w.hb=I(w.hb),w.emscripten_main_runtime_thread_id=B(w.emscripten_main_runtime_thread_id),w.sb=I(w.sb),w.tb=B(w.tb),w}(),Go.push(Z.ib),Lt.unshift(Z.Ba),X=b,Do(),Z}var c=Vo();if(Gt++,u.instantiateWasm)try{return u.instantiateWasm(c,s)}catch(f){K(`Module.instantiateWasm callback failed with error: ${f}`),m(f)}return _n||=u.locateFile?Mo(\"ort-wasm-simd-threaded.jsep.wasm\")?\"ort-wasm-simd-threaded.jsep.wasm\":u.locateFile?u.locateFile(\"ort-wasm-simd-threaded.jsep.wasm\",P):P+\"ort-wasm-simd-threaded.jsep.wasm\":new URL(\"ort-wasm-simd-threaded.jsep.wasm\",import.meta.url).href,function(f,b){var w=_n;return O||typeof WebAssembly.instantiateStreaming!=\"function\"||Mo(w)||Ro(w)||typeof fetch!=\"function\"?No(w,f,b):fetch(w,{credentials:\"same-origin\"}).then(I=>WebAssembly.instantiateStreaming(I,f).then(b,function(B){return K(`wasm streaming compile failed: ${B}`),K(\"falling back to ArrayBuffer instantiation\"),No(w,f,b)}))}(c,function(f){s(f.instance,f.module)}).catch(m),{}}(),Wi=s=>(Wi=Z.Ca)(s),Li=()=>(Li=Z.Da)();u._OrtInit=(s,c)=>(u._OrtInit=Z.Ea)(s,c),u._OrtGetLastError=(s,c)=>(u._OrtGetLastError=Z.Fa)(s,c),u._OrtCreateSessionOptions=(s,c,f,b,w,I,B,D,L,H)=>(u._OrtCreateSessionOptions=Z.Ga)(s,c,f,b,w,I,B,D,L,H),u._OrtAppendExecutionProvider=(s,c)=>(u._OrtAppendExecutionProvider=Z.Ha)(s,c),u._OrtAddFreeDimensionOverride=(s,c,f)=>(u._OrtAddFreeDimensionOverride=Z.Ia)(s,c,f),u._OrtAddSessionConfigEntry=(s,c,f)=>(u._OrtAddSessionConfigEntry=Z.Ja)(s,c,f),u._OrtReleaseSessionOptions=s=>(u._OrtReleaseSessionOptions=Z.Ka)(s),u._OrtCreateSession=(s,c,f)=>(u._OrtCreateSession=Z.La)(s,c,f),u._OrtReleaseSession=s=>(u._OrtReleaseSession=Z.Ma)(s),u._OrtGetInputOutputCount=(s,c,f)=>(u._OrtGetInputOutputCount=Z.Na)(s,c,f),u._OrtGetInputName=(s,c)=>(u._OrtGetInputName=Z.Oa)(s,c),u._OrtGetOutputName=(s,c)=>(u._OrtGetOutputName=Z.Pa)(s,c),u._OrtFree=s=>(u._OrtFree=Z.Qa)(s),u._OrtCreateTensor=(s,c,f,b,w,I)=>(u._OrtCreateTensor=Z.Ra)(s,c,f,b,w,I),u._OrtGetTensorData=(s,c,f,b,w)=>(u._OrtGetTensorData=Z.Sa)(s,c,f,b,w),u._OrtReleaseTensor=s=>(u._OrtReleaseTensor=Z.Ta)(s),u._OrtCreateRunOptions=(s,c,f,b)=>(u._OrtCreateRunOptions=Z.Ua)(s,c,f,b),u._OrtAddRunConfigEntry=(s,c,f)=>(u._OrtAddRunConfigEntry=Z.Va)(s,c,f),u._OrtReleaseRunOptions=s=>(u._OrtReleaseRunOptions=Z.Wa)(s),u._OrtCreateBinding=s=>(u._OrtCreateBinding=Z.Xa)(s),u._OrtBindInput=(s,c,f)=>(u._OrtBindInput=Z.Ya)(s,c,f),u._OrtBindOutput=(s,c,f,b)=>(u._OrtBindOutput=Z.Za)(s,c,f,b),u._OrtClearBoundOutputs=s=>(u._OrtClearBoundOutputs=Z._a)(s),u._OrtReleaseBinding=s=>(u._OrtReleaseBinding=Z.$a)(s),u._OrtRunWithBinding=(s,c,f,b,w)=>(u._OrtRunWithBinding=Z.ab)(s,c,f,b,w),u._OrtRun=(s,c,f,b,w,I,B,D)=>(u._OrtRun=Z.bb)(s,c,f,b,w,I,B,D),u._OrtEndProfiling=s=>(u._OrtEndProfiling=Z.cb)(s),u._JsepOutput=(s,c,f)=>(u._JsepOutput=Z.db)(s,c,f),u._JsepGetNodeName=s=>(u._JsepGetNodeName=Z.eb)(s);var mr,Bt=()=>(Bt=Z.fb)(),Xe=u._free=s=>(Xe=u._free=Z.gb)(s),fr=u._malloc=s=>(fr=u._malloc=Z.hb)(s),Un=(s,c,f,b,w,I)=>(Un=Z.kb)(s,c,f,b,w,I),Gi=()=>(Gi=Z.lb)(),Hi=(s,c,f,b,w)=>(Hi=Z.mb)(s,c,f,b,w),Nn=s=>(Nn=Z.nb)(s),hr=s=>(hr=Z.ob)(s),Fi=()=>(Fi=Z.pb)(),qi=(s,c)=>(qi=Z.qb)(s,c),gr=s=>(gr=Z.rb)(s),Vn=s=>(Vn=Z.sb)(s),Wn=()=>(Wn=Z.tb)(),ji=u.dynCall_ii=(s,c)=>(ji=u.dynCall_ii=Z.vb)(s,c),Ki=s=>(Ki=Z.wb)(s),Yi=()=>(Yi=Z.xb)(),Zi=s=>(Zi=Z.yb)(s),Qi=()=>(Qi=Z.zb)();function Xi(){0Wn(),u.stackRestore=s=>gr(s),u.stackAlloc=s=>Vn(s),u.setValue=function(s,c,f=\"i8\"){switch(f.endsWith(\"*\")&&(f=\"*\"),f){case\"i1\":case\"i8\":t()[s>>>0]=c;break;case\"i16\":n()[s>>>1>>>0]=c;break;case\"i32\":i()[s>>>2>>>0]=c;break;case\"i64\":j[s>>>3]=BigInt(c);break;case\"float\":l()[s>>>2>>>0]=c;break;case\"double\":d()[s>>>3>>>0]=c;break;case\"*\":a()[s>>>2>>>0]=c;break;default:dt(`invalid type for setValue: ${f}`)}},u.getValue=function(s,c=\"i8\"){switch(c.endsWith(\"*\")&&(c=\"*\"),c){case\"i1\":case\"i8\":return t()[s>>>0];case\"i16\":return n()[s>>>1>>>0];case\"i32\":return i()[s>>>2>>>0];case\"i64\":return j[s>>>3];case\"float\":return l()[s>>>2>>>0];case\"double\":return d()[s>>>3>>>0];case\"*\":return a()[s>>>2>>>0];default:dt(`invalid type for getValue: ${c}`)}},u.UTF8ToString=Te,u.stringToUTF8=Pt,u.lengthBytesUTF8=Tn,Ht=function s(){mr||Xi(),mr||(Ht=s)},Xi(),u.PTR_SIZE=4,h}),Gp=Ba;globalThis.self?.name===\"em-pthread\"&&Ba()});var Dt,Hp,Fp,qp,Ra,Ua,jp,Na,jt=R(()=>{\"use strict\";Ir();Dt=!1?void 0:import.meta.url??(typeof document<\"u\"?document.currentScript?.src:typeof self<\"u\"?self.location?.href:void 0),Hp=!1||typeof location>\"u\"?void 0:location.origin,Fp=(e,t)=>{try{let r=t??Dt;return(r?new URL(e,r):new URL(e)).origin===Hp}catch{return!1}},qp=async e=>{let r=await(await fetch(e,{credentials:\"same-origin\"})).blob();return URL.createObjectURL(r)},Ra=(Oa(),br(za)).default,Ua=async()=>{if(!Dt)throw new Error(\"Failed to load proxy worker: cannot determine the script source URL.\");if(Fp(Dt))return[void 0,Ra()];let e=await qp(Dt);return[e,Ra(e)]},jp=(Ma(),br(Da)).default,Na=async(e,t,r)=>[void 0,jp]});var Zn,Qn,Dr,Va,Kp,Yp,Cr,Ce,ht=R(()=>{\"use strict\";jt();Qn=!1,Dr=!1,Va=!1,Kp=()=>{if(typeof SharedArrayBuffer>\"u\")return!1;try{return typeof MessageChannel<\"u\"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Yp=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Cr=async e=>{if(Qn)return Promise.resolve();if(Dr)throw new Error(\"multiple calls to 'initializeWebAssembly()' detected.\");if(Va)throw new Error(\"previous call to 'initializeWebAssembly()' failed.\");Dr=!0;let t=e.initTimeout,r=e.numThreads;if(!Yp())throw new Error(\"WebAssembly SIMD is not supported in the current environment.\");let n=Kp();r>1&&!n&&(typeof self<\"u\"&&!self.crossOriginIsolated&&console.warn(\"env.wasm.numThreads is set to \"+r+\", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info.\"),console.warn(\"WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading.\"),e.numThreads=r=1);let o=e.wasmPaths,i=typeof o==\"string\"?o:void 0,a=o?.mjs,l=a?.href??a,d=o?.wasm,p=d?.href??d,m=e.wasmBinary,[u,h]=await Na(l,i,r>1),_=!1,y=[];if(t>0&&y.push(new Promise(g=>{setTimeout(()=>{_=!0,g()},t)})),y.push(new Promise((g,x)=>{let $={numThreads:r};m?$.wasmBinary=m:(p||i)&&($.locateFile=(v,S)=>p??(i??S)+v),h($).then(v=>{Dr=!1,Qn=!0,Zn=v,g(),u&&URL.revokeObjectURL(u)},v=>{Dr=!1,Va=!0,x(v)})})),await Promise.race(y),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ce=()=>{if(Qn&&Zn)return Zn;throw new Error(\"WebAssembly is not initialized yet.\")}});var Ae,Yt,pe,Mr=R(()=>{\"use strict\";ht();Ae=(e,t)=>{let r=Ce(),n=r.lengthBytesUTF8(e)+1,o=r._malloc(n);return r.stringToUTF8(e,o,n),t.push(o),o},Yt=(e,t,r,n)=>{if(typeof e==\"object\"&&e!==null){if(r.has(e))throw new Error(\"Circular reference in options\");r.add(e)}Object.entries(e).forEach(([o,i])=>{let a=t?t+o:o;if(typeof i==\"object\")Yt(i,a+\".\",r,n);else if(typeof i==\"string\"||typeof i==\"number\")n(a,i.toString());else if(typeof i==\"boolean\")n(a,i?\"1\":\"0\");else throw new Error(`Can't handle extra config type: ${typeof i}`)})},pe=e=>{let t=Ce(),r=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetLastError(o,o+n);let i=Number(t.getValue(o,n===4?\"i32\":\"i64\")),a=t.getValue(o+n,\"*\"),l=a?t.UTF8ToString(a):\"\";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${l}`)}finally{t.stackRestore(r)}}});var Wa,La=R(()=>{\"use strict\";ht();Mr();Wa=e=>{let t=Ce(),r=0,n=[],o=e||{};try{if(e?.logSeverityLevel===void 0)o.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=\"number\"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)o.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=\"number\"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(o.terminate=!1);let i=0;return e?.tag!==void 0&&(i=Ae(e.tag,n)),r=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,i),r===0&&pe(\"Can't create run options.\"),e?.extra!==void 0&&Yt(e.extra,\"\",new WeakSet,(a,l)=>{let d=Ae(a,n),p=Ae(l,n);t._OrtAddRunConfigEntry(r,d,p)!==0&&pe(`Can't set a run config entry: ${a} - ${l}.`)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(a=>t._free(a)),i}}});var Zp,Qp,Xp,Jp,Ga,Ha=R(()=>{\"use strict\";ht();Mr();Zp=e=>{switch(e){case\"disabled\":return 0;case\"basic\":return 1;case\"extended\":return 2;case\"all\":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},Qp=e=>{switch(e){case\"sequential\":return 0;case\"parallel\":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Xp=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly=\"1\"),e.executionProviders&&e.executionProviders.some(r=>(typeof r==\"string\"?r:r.name)===\"webgpu\")&&(e.enableMemPattern=!1)},Jp=(e,t,r)=>{for(let n of t){let o=typeof n==\"string\"?n:n.name;switch(o){case\"webnn\":if(o=\"WEBNN\",typeof n!=\"string\"){let l=n?.deviceType;if(l){let d=Ae(\"deviceType\",r),p=Ae(l,r);Ce()._OrtAddSessionConfigEntry(e,d,p)!==0&&pe(`Can't set a session config entry: 'deviceType' - ${l}.`)}}break;case\"webgpu\":if(o=\"JS\",typeof n!=\"string\"){let a=n;if(a?.preferredLayout){if(a.preferredLayout!==\"NCHW\"&&a.preferredLayout!==\"NHWC\")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${a.preferredLayout}`);let l=Ae(\"preferredLayout\",r),d=Ae(a.preferredLayout,r);Ce()._OrtAddSessionConfigEntry(e,l,d)!==0&&pe(`Can't set a session config entry: 'preferredLayout' - ${a.preferredLayout}.`)}}break;case\"wasm\":case\"cpu\":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=Ae(o,r);Ce()._OrtAppendExecutionProvider(e,i)!==0&&pe(`Can't append execution provider: ${o}.`)}},Ga=e=>{let t=Ce(),r=0,n=[],o=e||{};Xp(o);try{let i=Zp(o.graphOptimizationLevel??\"all\"),a=Qp(o.executionMode??\"sequential\"),l=typeof o.logId==\"string\"?Ae(o.logId,n):0,d=o.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let p=o.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let m=typeof o.optimizedModelFilePath==\"string\"?Ae(o.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(i,!!o.enableCpuMemArena,!!o.enableMemPattern,a,!!o.enableProfiling,0,l,d,p,m),r===0&&pe(\"Can't create session options.\"),o.executionProviders&&Jp(r,o.executionProviders,n),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!=\"boolean\")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);let u=Ae(\"enableGraphCapture\",n),h=Ae(o.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,u,h)!==0&&pe(`Can't set a session config entry: 'enableGraphCapture' - ${o.enableGraphCapture}.`)}if(o.freeDimensionOverrides)for(let[u,h]of Object.entries(o.freeDimensionOverrides)){if(typeof u!=\"string\")throw new Error(`free dimension override name must be a string: ${u}`);if(typeof h!=\"number\"||!Number.isInteger(h)||h<0)throw new Error(`free dimension override value must be a non-negative integer: ${h}`);let _=Ae(u,n);t._OrtAddFreeDimensionOverride(r,_,h)!==0&&pe(`Can't set a free dimension override: ${u} - ${h}.`)}return o.extra!==void 0&&Yt(o.extra,\"\",new WeakSet,(u,h)=>{let _=Ae(u,n),y=Ae(h,n);t._OrtAddSessionConfigEntry(r,_,y)!==0&&pe(`Can't set a session config entry: ${u} - ${h}.`)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&pe(\"Can't release session options.\"),n.forEach(a=>t._free(a)),i}}});var Zt,gt,Tt,Rr,Qt,Ur,Nr,Xn,te=R(()=>{\"use strict\";Zt=e=>{switch(e){case\"int8\":return 3;case\"uint8\":return 2;case\"bool\":return 9;case\"int16\":return 5;case\"uint16\":return 4;case\"int32\":return 6;case\"uint32\":return 12;case\"float16\":return 10;case\"float32\":return 1;case\"float64\":return 11;case\"string\":return 8;case\"int64\":return 7;case\"uint64\":return 13;case\"int4\":return 22;case\"uint4\":return 21;default:throw new Error(`unsupported data type: ${e}`)}},gt=e=>{switch(e){case 3:return\"int8\";case 2:return\"uint8\";case 9:return\"bool\";case 5:return\"int16\";case 4:return\"uint16\";case 6:return\"int32\";case 12:return\"uint32\";case 10:return\"float16\";case 1:return\"float32\";case 11:return\"float64\";case 8:return\"string\";case 7:return\"int64\";case 13:return\"uint64\";case 22:return\"int4\";case 21:return\"uint4\";default:throw new Error(`unsupported data type: ${e}`)}},Tt=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t==\"number\"?t:t.reduce((o,i)=>o*i,1);return r>0?Math.ceil(n*r):void 0},Rr=e=>{switch(e){case\"float16\":return typeof Float16Array<\"u\"&&Float16Array.from?Float16Array:Uint16Array;case\"float32\":return Float32Array;case\"uint8\":return Uint8Array;case\"int8\":return Int8Array;case\"uint16\":return Uint16Array;case\"int16\":return Int16Array;case\"int32\":return Int32Array;case\"bool\":return Uint8Array;case\"float64\":return Float64Array;case\"uint32\":return Uint32Array;case\"int64\":return BigInt64Array;case\"uint64\":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Qt=e=>{switch(e){case\"verbose\":return 0;case\"info\":return 1;case\"warning\":return 2;case\"error\":return 3;case\"fatal\":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},Ur=e=>e===\"float32\"||e===\"float16\"||e===\"int32\"||e===\"int64\"||e===\"uint32\"||e===\"uint8\"||e===\"bool\"||e===\"uint4\"||e===\"int4\",Nr=e=>e===\"float32\"||e===\"float16\"||e===\"int32\"||e===\"int64\"||e===\"uint32\"||e===\"uint64\"||e===\"int8\"||e===\"uint8\"||e===\"bool\"||e===\"uint4\"||e===\"int4\",Xn=e=>{switch(e){case\"none\":return 0;case\"cpu\":return 1;case\"cpu-pinned\":return 2;case\"texture\":return 3;case\"gpu-buffer\":return 4;case\"ml-tensor\":return 5;default:throw new Error(`unsupported data location: ${e}`)}}});var Xt,Jn=R(()=>{\"use strict\";Ir();Xt=async e=>{if(typeof e==\"string\")if(!1)try{let{readFile:t}=Gn(\"node:fs/promises\");return new Uint8Array(await t(e))}catch(t){if(t.code===\"ERR_FS_FILE_TOO_LARGE\"){let{createReadStream:r}=Gn(\"node:fs\"),n=r(e),o=[];for await(let i of n)o.push(i);return new Uint8Array(Buffer.concat(o))}throw t}else{let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get(\"Content-Length\"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=t.body.getReader(),i;try{i=new ArrayBuffer(n)}catch(l){if(l instanceof RangeError){let d=Math.ceil(n/65536);i=new WebAssembly.Memory({initial:d,maximum:d}).buffer}else throw l}let a=0;for(;;){let{done:l,value:d}=await o.read();if(l)break;let p=d.byteLength;new Uint8Array(i,a,p).set(d),a+=p}return new Uint8Array(i,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}});var em,tm,Fa,qa,Vr,rm,ue,Je=R(()=>{\"use strict\";te();em=[\"V\",\"I\",\"W\",\"E\",\"F\"],tm=(e,t)=>{console.log(`[${em[e]},${new Date().toISOString()}]${t}`)},Vr=(e,t)=>{Fa=e,qa=t},rm=(e,t)=>{let r=Qt(e),n=Qt(Fa);r>=n&&tm(r,typeof t==\"function\"?t():t)},ue=(...e)=>{qa&&rm(...e)}});var Wr,eo=R(()=>{\"use strict\";te();Wr=(e,t)=>new(Rr(t))(e)});var Lr=R(()=>{\"use strict\"});var ja,to,ro,nm,om,Ka,oo,no,Za,Qa=R(()=>{\"use strict\";Je();Lr();ja=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),to=[],ro=e=>Math.ceil(Number(e)/16)*16,nm=e=>{for(let t=0;tom++,oo=async(e,t,r,n)=>{let o=ro(r),i=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=e.getCommandEncoder();e.endComputePass(),a.copyBufferToBuffer(t,0,i,0,o),e.flush(),await i.mapAsync(GPUMapMode.READ);let l=i.getMappedRange();if(n){let d=n();return d.set(new Uint8Array(l,0,r)),d}else return new Uint8Array(l.slice(0,r))}finally{i.destroy()}},no=class{constructor(t){this.backend=t;this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[r]of ja)to.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(t,r){let n=r.buffer,o=r.byteOffset,i=r.byteLength,a=ro(i),l=this.storageCache.get(t);if(!l)throw new Error(\"gpu data for uploading does not exist\");if(Number(l.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${l.originalSize}, data size=${i}`);let d=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=d.getMappedRange();new Uint8Array(p).set(new Uint8Array(n,o,i)),d.unmap();let m=this.backend.device.createCommandEncoder();m.copyBufferToBuffer(d,0,l.gpuData.buffer,0,a),this.backend.device.queue.submit([m.finish()]),d.destroy(),ue(\"verbose\",()=>`[WebGPU] GpuDataManager.upload(id=${t})`)}memcpy(t,r){let n=this.storageCache.get(t);if(!n)throw new Error(\"source gpu data for memcpy does not exist\");let o=this.storageCache.get(r);if(!o)throw new Error(\"destination gpu data for memcpy does not exist\");if(n.originalSize!==o.originalSize)throw new Error(\"inconsistent source and destination gpu data size\");let i=ro(n.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(n.gpuData.buffer,0,o.gpuData.buffer,0,i)}registerExternalBuffer(t,r,n){let o;if(n){if(o=n[0],t===n[1])return ue(\"verbose\",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, buffer is the same, skip.`),o;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.\n Please use the previous external buffer!`)}else o=Ka();return this.storageCache.set(o,{gpuData:{id:o,type:0,buffer:t},originalSize:r}),ue(\"verbose\",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, registered.`),o}unregisterExternalBuffer(t){t!==void 0&&(this.storageCache.delete(t),ue(\"verbose\",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`))}create(t,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=nm(t),o,i=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let p=(i?this.freeBuffers:this.freeUniformBuffers).get(n);p?p.length>0?o=p.pop():o=this.backend.device.createBuffer({size:n,usage:r}):o=this.backend.device.createBuffer({size:n,usage:r})}else o=this.backend.device.createBuffer({size:n,usage:r});let l={id:Ka(),type:0,buffer:o};return this.storageCache.set(l.id,{gpuData:l,originalSize:Number(t)}),ue(\"verbose\",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${l.id}`),l}get(t){return this.storageCache.get(t)?.gpuData}release(t){let r=typeof t==\"bigint\"?Number(t):t,n=this.storageCache.get(r);if(!n){if(this.storageCache.size===0)return 0;throw new Error(\"releasing data does not exist\")}return ue(\"verbose\",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${n.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(t,r){let n=this.storageCache.get(Number(t));if(!n)throw new Error(\"data does not exist\");await oo(this.backend,n.gpuData.buffer,n.originalSize,r)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus===\"default\"){for(let t of this.buffersPending){let r=ja.get(t.size);if((t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(t.size)||[];r===void 0||n.length>=r?t.destroy():n.push(t)}else if((t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(t.size)||[];r===void 0||n.length>=r?t.destroy():n.push(t)}else t.destroy()}this.buffersPending=[]}else{let t=this.capturedPendingBuffers.get(this.backend.currentSessionId);t||(t=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,t));for(let r of this.buffersPending)t.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(t){let r=this.capturedPendingBuffers.get(t);r&&(r.forEach(n=>{n.destroy()}),this.capturedPendingBuffers.delete(t)),this.sessionCount-=1,this.sessionCount===0&&(ue(\"warning\",()=>\"[WebGPU] Clearing webgpu buffer cache\"),this.storageCache.forEach(n=>{n.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Za=(...e)=>new no(...e)});var io,J,Se=R(()=>{\"use strict\";io=class{constructor(t){Object.assign(this,t)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(t=>`${this[t]}`).join(\";\")),this.key}},J=e=>new io(e)});var ao,et,k,It,Gr,Xa,Ja,oe=R(()=>{\"use strict\";ao=class{static calcMatMulShape(t,r){return t[1]!==r[0]?void 0:[t[0],r[1]]}},et=class{static calcShape(t,r,n=!1){let o=t.length,i=r.length;if(o===0)return r;if(i===0)return t;let a=Math.max(t.length,r.length),l=new Array(a);if(n){if(o<2||i<2)return;let d=ao.calcMatMulShape([t[o-2],t[o-1]],[r[i-2],r[i-1]]);if(d===void 0)return;[l[a-2],l[a-1]]=d}for(let d=n?3:1;d<=a;d++){let p=o-d<0?1:t[o-d],m=i-d<0?1:r[i-d];if(p!==m&&p>1&&m>1)return;let u=Math.max(p,m);if(p&&m)l[a-d]=Math.max(p,m);else{if(u>1)return;l[a-d]=0}}return l}static isValidBroadcast(t,r){let n=t.length,o=r.length;if(n>o)return!1;for(let i=1;i<=n;i++)if(t[n-i]!==1&&t[n-i]!==r[o-i])return!1;return!0}},k=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let o=new Array(n),i=n-1;for(;i>=0;){if(t[i]%r===0){o[i]=t[i]/r;break}if(r%t[i]!==0)throw new Error(\"cannot convert shape\");o[i]=1,r/=t[i],i--}for(i--;i>=0;i--)o[i]=t[i];return o}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let o=1;for(let i=r;i=0;--o)n[o]=n[o+1]*t[o+1];return n}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error(\"unsupported axis for this operation.\");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(n=>this.normalizeAxis(n,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(n=>t[n]):t.slice().reverse()}static padShape(t,r){let n=t.length;return t.map((o,i)=>o+r[i]+r[i+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,o)=>n===r[o])}},It=class e{static adjustPoolAttributes(t,r,n,o,i,a){if(!t&&n.length!==r.length-2)throw new Error(\"length of specified kernel shapes should be 2 less than length of input dimensions\");if(t)for(let l=0;l=n.length?n.push(r[l+2]):n[l]=r[l+2];for(let l=0;l=n[l]||a[l+n.length]>=n[l])throw new Error(\"pads should be smaller than kernel\")}}static adjustPadsBasedOnAutoPad(t,r,n,o,i,a,l){if(l){if(i.length!==2*(t.length-2))throw new Error(\"length of pads should be twice the length of data dimensions\");if(r.length!==t.length-2)throw new Error(\"length of strides should be the length of data dimensions\");if(o.length!==t.length-2)throw new Error(\"length of kernel shapes should be the length of data dimensions\");for(let d=0;d{\"use strict\";te();oe();Ct=64,uo=(e,t)=>{if(t===3)throw new Error(\"vec3 has same alignment as vec4, use vec4 instead\");switch(Number(e)){case 10:return t>1?`vec${t}`:\"f16\";case 1:return t>1?`vec${t}`:\"f32\";case 6:return t>1?`vec${t}`:\"i32\";case 12:return t>1?`vec${t}`:\"u32\";case 7:if(t>1)throw new Error(\"currently not supported vecX of uint64 yet\");return[\"vec2\",\"i32\"];case 13:if(t>1)throw new Error(\"currently not supported vecX of uint64 yet\");return[\"vec2\",\"u32\"];case 9:if(t!==4)throw new Error(\"bool must be vec4\");return[\"u32\",\"vec4\"];case 22:return\"i32\";case 21:return\"u32\";default:throw new Error(`Unknown data type: ${e}`)}},ye=(e,t=1)=>{let r=uo(e,t);return typeof r==\"string\"?r:r[0]},ke=(e,t=1)=>{let r=uo(e,t);return typeof r==\"string\"?r:r[1]},N=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:k.computeStrides(r)})}),t},me=e=>e%4===0?4:e%2===0?2:1,lo=(e=\"f32\",t,r=\"0\")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,At=(e,t,r)=>e===\"f32\"?r:t===1?`f32(${r})`:`vec${t}(${r})`,He=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,F=(e,t,r,n)=>e.startsWith(\"uniforms.\")&&r>4?typeof t==\"string\"?n===\"f16\"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n===\"f16\"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Hr=(e,t,r,n,o)=>{let i=typeof r==\"number\",a=i?r:r.length,l=[...new Array(a).keys()],d=a<2?\"u32\":a<=4?`vec${a}`:`array`,p=uo(t,o),m=typeof p==\"string\"?p:p[1],u=typeof p==\"string\"?p:p[0],h={indices:d,value:m,storage:u,tensor:t},_=V=>typeof V==\"string\"?V:`${V}u`,y={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},g=i?\"uniforms.\":\"\",x=`${g}${e}_shape`,$=`${g}${e}_strides`,v=\"\";for(let V=0;V ${h.indices} {\n var indices: ${h.indices};\n var current = offset;\n ${v}\n return indices;\n }`,T=V=>(y.offsetToIndices=!0,a<2?V:`o2i_${e}(${V})`),C=[];if(a>=2)for(let V=a-1;V>=0;V--)C.push(`${F($,V,a)} * (indices[${V}])`);let A=a<2?\"\":`\n fn i2o_${e}(indices: ${h.indices}) -> u32 {\n return ${C.join(\"+\")};\n }`,P=V=>(y.indicesToOffset=!0,a<2?V:`i2o_${e}(${V})`),O=(...V)=>a===0?\"0u\":`${h.indices}(${V.map(_).join(\",\")})`,U=(V,j)=>a<2?`${V}`:`${F(V,j,a)}`,G=(V,j,he)=>a<2?`${V}=${he};`:`${F(V,j,a)}=${he};`,q={},K=(V,j)=>{y.broadcastedIndicesToOffset=!0;let he=`${j.name}broadcastedIndicesTo${e}Offset`;if(he in q)return`${he}(${V})`;let Ge=[];for(let _e=a-1;_e>=0;_e--){let be=j.indicesGet(\"outputIndices\",_e+j.rank-a);Ge.push(`${U($,_e)} * (${be} % ${U(x,_e)})`)}return q[he]=`fn ${he}(outputIndices: ${j.type.indices}) -> u32 {\n return ${Ge.length>0?Ge.join(\"+\"):\"0u\"};\n }`,`${he}(${V})`},W=(V,j)=>(()=>{if(h.storage===h.value)return`${e}[${V}]=${j};`;if(h.storage===\"vec2\"&&h.value===\"i32\")return`${e}[${V}]=vec2(u32(${j}), select(0u, 0xFFFFFFFFu, ${j} < 0));`;if(h.storage===\"vec2\"&&h.value===\"u32\")return`${e}[${V}]=vec2(u32(${j}), 0u);`;if(h.storage===\"u32\"&&h.value===\"vec4\")return`${e}[${V}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${j}));`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),Y=V=>(()=>{if(h.storage===h.value)return`${e}[${V}]`;if(h.storage===\"vec2\"&&h.value===\"i32\")return`i32(${e}[${V}].x)`;if(h.storage===\"vec2\"&&h.value===\"u32\")return`u32(${e}[${V}].x)`;if(h.storage===\"u32\"&&h.value===\"vec4\")return`vec4(bool(${e}[${V}] & 0xFFu), bool(${e}[${V}] & 0xFF00u), bool(${e}[${V}] & 0xFF0000u), bool(${e}[${V}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),se=a<2?\"\":`\n fn get_${e}ByIndices(indices: ${h.indices}) -> ${m} {\n return ${Y(`i2o_${e}(indices)`)};\n }`,X=a<2?\"\":(()=>{let V=l.map(he=>`d${he}: u32`).join(\", \"),j=l.map(he=>`d${he}`).join(\", \");return`\n fn get_${e}(${V}) -> ${m} {\n return get_${e}ByIndices(${O(j)});\n }`})(),re=(...V)=>{if(V.length!==a)throw new Error(`indices length must be ${a}`);let j=V.map(_).join(\",\");return a===0?Y(\"0u\"):a===1?Y(j[0]):(y.get=!0,y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}(${j})`)},ee=V=>a<2?Y(V):(y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}ByIndices(${V})`),ne=a<2?\"\":`\n fn set_${e}ByIndices(indices: ${h.indices}, value: ${m}) {\n ${W(`i2o_${e}(indices)`,\"value\")}\n }`,ve=a<2?\"\":(()=>{let V=l.map(he=>`d${he}: u32`).join(\", \"),j=l.map(he=>`d${he}`).join(\", \");return`\n fn set_${e}(${V}, value: ${m}) {\n set_${e}ByIndices(${O(j)}, value);\n }`})();return{impl:()=>{let V=[],j=!1;return y.offsetToIndices&&(V.push(S),j=!0),y.indicesToOffset&&(V.push(A),j=!0),y.broadcastedIndicesToOffset&&(Object.values(q).forEach(he=>V.push(he)),j=!0),y.set&&(V.push(ve),j=!0),y.setByIndices&&(V.push(ne),j=!0),y.get&&(V.push(X),j=!0),y.getByIndices&&(V.push(se),j=!0),!i&&j&&V.unshift(`const ${x} = ${h.indices}(${r.join(\",\")});`,`const ${$} = ${h.indices}(${k.computeStrides(r).join(\",\")});`),V.join(`\n`)},type:h,offsetToIndices:T,indicesToOffset:P,broadcastedIndicesToOffset:K,indices:O,indicesGet:U,indicesSet:G,set:(...V)=>{if(V.length!==a+1)throw new Error(`indices length must be ${a}`);let j=V[a];if(typeof j!=\"string\")throw new Error(\"value must be string\");let he=V.slice(0,a).map(_).join(\",\");return a===0?W(\"0u\",j):a===1?W(he[0],j):(y.set=!0,y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}(${he}, ${j})`)},setByOffset:W,setByIndices:(V,j)=>a<2?W(V,j):(y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}ByIndices(${V}, ${j});`),get:re,getByOffset:Y,getByIndices:ee,usage:n,name:e,strides:$,shape:x,rank:a}},E=(e,t,r,n=1)=>Hr(e,t,r,\"input\",n),M=(e,t,r,n=1)=>Hr(e,t,r,\"output\",n),es=(e,t,r)=>Hr(e,t,r,\"atomicOutput\",1),Fr=(e,t,r,n=1)=>Hr(e,t,r,\"internal\",n),so=class{constructor(t,r){this.normalizedDispatchGroup=t;this.limits=r;this.internalVariables=[];this.variables=[];this.uniforms=[];this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t==\"number\"?`${t}u`:t}) { return; }`}mainStart(t=Ct){let r=typeof t==\"number\"?t:t[0],n=typeof t==\"number\"?1:t[1],o=typeof t==\"number\"?1:t[2];if(r>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||o>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*n*o>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=i?`@builtin(global_invocation_id) global_id : vec3,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3,\n @builtin(local_invocation_id) local_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(num_workgroups) num_workgroups : vec3`,l=i?`let global_idx = global_id.x;\n let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] +\n workgroup_id.y * num_workgroups[0] + workgroup_id.x;\n let global_idx = workgroup_index * ${r*n*o}u + local_idx;`;return`@compute @workgroup_size(${r}, ${n}, ${o})\n fn main(${a}) {\n ${l}\n `}appendVariableUniforms(t){t.rank!==0&&(t.shape.startsWith(\"uniforms.\")&&this.uniforms.push({name:t.shape.replace(\"uniforms.\",\"\"),type:\"u32\",length:t.rank}),t.strides.startsWith(\"uniforms.\")&&this.uniforms.push({name:t.strides.replace(\"uniforms.\",\"\"),type:\"u32\",length:t.rank}))}declareVariable(t,r){if(t.usage===\"internal\")throw new Error(\"cannot use internal variable with declareVariable(). use registerInternalVariables() instead.\");this.variables.push(t),this.appendVariableUniforms(t);let n=t.usage===\"input\"?\"read\":\"read_write\",o=t.usage===\"atomicOutput\"?\"atomic\":t.type.storage;return`@group(0) @binding(${r}) var ${t.name}: array<${o}>;`}declareVariables(...t){return t.map(r=>this.declareVariable(r,this.variableIndex++)).join(`\n`)}registerInternalVariable(t){if(t.usage!==\"internal\")throw new Error(\"cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.\");this.internalVariables.push(t),this.appendVariableUniforms(t)}registerInternalVariables(...t){return t.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(t,r,n=1){return this.uniforms.push({name:t,type:r,length:n}),this}registerUniforms(t){return this.uniforms=this.uniforms.concat(t),this}uniformDeclaration(){if(this.uniforms.length===0)return\"\";let t=[];for(let{name:r,type:n,length:o}of this.uniforms)if(o&&o>4)n===\"f16\"?t.push(`@align(16) ${r}:array, ${Math.ceil(o/8)}>`):t.push(`${r}:array, ${Math.ceil(o/4)}>`);else{let i=o==null||o===1?n:`vec${o}<${n}>`;t.push(`${r}:${i}`)}return`\n struct Uniforms { ${t.join(\", \")} };\n @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(t=>t.impl()).join(`\n`)+this.internalVariables.map(t=>t.impl()).join(`\n`)}get variablesInfo(){if(this.uniforms.length===0)return;let t=r=>[12,10,1,6][[\"u32\",\"f16\",\"f32\",\"i32\"].indexOf(r)];return this.uniforms.map(r=>[t(r.type),r.length??1])}},ts=(e,t)=>new so(e,t)});var im,rs,am,sm,um,lm,Ee,ns,os,ut=R(()=>{\"use strict\";te();oe();Se();ae();im=e=>{if(!e||e.length!==1)throw new Error(\"Transpose requires 1 input.\")},rs=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,am=(e,t)=>k.sortBasedOnPerm(e,rs(e.length,t)),sm=(e,t,r,n)=>{let o=`fn perm(i: ${n.type.indices}) -> ${r.type.indices} {\n var a: ${r.type.indices};`;for(let i=0;i{let r=[],n=[];for(let o=0;o{let r=0;for(let n=0;n{let r=e.dataType,n=e.dims.length,o=rs(n,t),i=am(e.dims,o),a=e.dims,l=i,d=lm(o,e.dims),p;if(d)return p=g=>{let x=E(\"input\",r,a,4),$=M(\"output\",r,l,4);return`\n ${g.registerUniform(\"output_size\",\"u32\").declareVariables(x,$)}\n ${g.mainStart()}\n ${g.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n output[global_idx] = input[global_idx];\n }`},{name:\"TransposeCopy\",shaderCache:{inputDependencies:[\"type\"]},getRunData:()=>{let g=k.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(g/64/4)},programUniforms:[{type:12,data:Math.ceil(g/4)}]}},getShaderSource:p};let{newShape:m,newPerm:u}=um(e.dims,o),h=k.areEqual(u,[2,3,1]),_=k.areEqual(u,[3,1,2]);if(m.length===2||h||_){a=h?[m[0],m[1]*m[2]]:_?[m[0]*m[1],m[2]]:m,l=[a[1],a[0]];let g=16;return p=x=>{let $=E(\"a\",r,a.length),v=M(\"output\",r,l.length);return`\n ${x.registerUniform(\"output_size\",\"u32\").declareVariables($,v)}\n var tile : array, ${g}>;\n ${x.mainStart([g,g,1])}\n let stride = (uniforms.output_shape[1] - 1) / ${g} + 1;\n let workgroup_id_x = workgroup_index % stride;\n let workgroup_id_y = workgroup_index / stride;\n let input_col = workgroup_id_y * ${g}u + local_id.x;\n let input_row = workgroup_id_x * ${g}u + local_id.y;\n if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) {\n tile[local_id.y][local_id.x] = ${$.getByIndices(`${$.type.indices}(input_row, input_col)`)};\n }\n workgroupBarrier();\n\n let output_col = workgroup_id_x * ${g}u + local_id.x;\n let output_row = workgroup_id_y * ${g}u + local_id.y;\n if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) {\n ${v.setByIndices(`${v.type.indices}(output_row, output_col)`,\"tile[local_id.x][local_id.y]\")}\n }\n }`},{name:\"TransposeShared\",shaderCache:{inputDependencies:[\"type\"]},getRunData:()=>{let x=k.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(l[1]/g),y:Math.ceil(l[0]/g)},programUniforms:[{type:12,data:x},...N(a,l)]}},getShaderSource:p}}return p=g=>{let x=E(\"a\",r,a.length),$=M(\"output\",r,l.length);return`\n ${g.registerUniform(\"output_size\",\"u32\").declareVariables(x,$)}\n\n ${sm(o,n,x,$)}\n\n ${g.mainStart()}\n ${g.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let indices = ${$.offsetToIndices(\"global_idx\")};\n let aIndices = perm(indices);\n\n ${$.setByOffset(\"global_idx\",x.getByIndices(\"aIndices\"))}\n }`},{name:\"Transpose\",shaderCache:{hint:`${t}`,inputDependencies:[\"rank\"]},getRunData:()=>{let g=k.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:[{type:12,data:g},...N(a,l)]}},getShaderSource:p}},ns=(e,t)=>{im(e.inputs),e.compute(Ee(e.inputs[0],t.perm))},os=e=>J({perm:e.perm})});var dm,cm,pm,mm,fm,hm,gm,bm,ym,_m,tt,is,as,ss,us,ls,ds,cs,ps,ms,fs,hs=R(()=>{\"use strict\";te();oe();ae();qr();ut();dm={max:\"select(bestValue, candidate, candidate > bestValue)\",min:\"select(bestValue, candidate, candidate < bestValue)\",mean:\"bestValue + candidate\",sum:\"bestValue + candidate\",prod:\"bestValue * candidate\",sumSquare:\"bestValue + candidate * candidate\",logSumExp:\"bestValue + exp(candidate)\",l1:\"bestValue + abs(candidate)\",l2:\"bestValue + candidate * candidate\",logSum:\"bestValue + candidate\"},cm={max:\"select(bestValue, candidate, candidate > bestValue)\",min:\"select(bestValue, candidate, candidate < bestValue)\",mean:\"bestValue + candidate\",sum:\"bestValue + candidate\",prod:\"bestValue * candidate\",sumSquare:\"bestValue + candidate\",logSumExp:\"bestValue + candidate\",l1:\"bestValue + candidate\",l2:\"bestValue + candidate\",logSum:\"bestValue + candidate\"},pm={max:\"_A[offset]\",min:\"_A[offset]\",mean:\"0\",sum:\"0\",prod:\"1\",sumSquare:\"0\",logSumExp:\"0\",l1:\"0\",l2:\"0\",logSum:\"0\"},mm={max:\"bestValue\",min:\"bestValue\",sum:\"bestValue\",prod:\"bestValue\",sumSquare:\"bestValue\",logSumExp:\"log(bestValue)\",l1:\"bestValue\",l2:\"sqrt(bestValue)\",logSum:\"log(bestValue)\"},fm=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let i=0;ie[i]);return[r,o]},gm=(e,t)=>{let r=e.length+t.length,n=[],o=0;for(let i=0;i{for(let r=0;r{let r=[];if(!bm(e,t)){for(let n=0;nr.push(n))}return r},_m=(e,t,r,n,o,i,a)=>{let l=r[0].dims,d=k.size(i),p=k.size(a),m=E(\"_A\",r[0].dataType,l),u=M(\"output\",o,i),h=64;d===1&&(h=256);let _=`\n var aBestValues : array;\n `,y=g=>`\n ${g.registerUniform(\"reduceSize\",\"u32\").declareVariables(m,u)}\n ${_}\n fn DIV_CEIL(a : u32, b : u32) -> u32 {\n return ((a - 1u) / b + 1u);\n }\n ${g.mainStart(h)}\n\n let outputIndex = global_idx / ${h};\n let offset = outputIndex * uniforms.reduceSize;\n\n var bestValue = f32(${pm[n]});\n let Length = uniforms.reduceSize;\n for (var k = local_idx; k < Length; k = k + ${h}) {\n let candidate = f32(${m.getByOffset(\"offset + k\")});\n bestValue = ${dm[n]};\n }\n aBestValues[local_idx] = bestValue;\n workgroupBarrier();\n\n var reduceSize = min(Length, ${h}u);\n for (var currentSize = reduceSize / 2u; reduceSize > 1u;\n currentSize = reduceSize / 2u) {\n let interval = DIV_CEIL(reduceSize, 2u);\n if (local_idx < currentSize) {\n let candidate = aBestValues[local_idx + interval];\n bestValue = ${cm[n]};\n aBestValues[local_idx] = bestValue;\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (local_idx == 0u) {\n ${u.setByOffset(\"outputIndex\",`${n===\"mean\"?`${u.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${u.type.storage}(${mm[n]})`}`)};\n }\n }`;return{name:e,shaderCache:{hint:`${t};${h}`,inputDependencies:[\"type\"]},getShaderSource:y,getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:d},programUniforms:[{type:12,data:p}]})}},tt=(e,t,r,n)=>{let o=e.inputs.length===1?r:co(e.inputs,r),i=o.axes;i.length===0&&!o.noopWithEmptyAxes&&(i=e.inputs[0].dims.map((_,y)=>y));let a=k.normalizeAxes(i,e.inputs[0].dims.length),l=a,d=e.inputs[0],p=ym(l,e.inputs[0].dims.length);p.length>0&&(d=e.compute(Ee(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],l=fm(l.length,d.dims.length));let[m,u]=hm(d.dims,l),h=m;o.keepDims&&(h=gm(m,a)),e.compute(_m(t,o.cacheKey,[d],n,e.inputs[0].dataType,h,u),{inputs:[d]})},is=(e,t)=>{tt(e,\"ReduceMeanShared\",t,\"mean\")},as=(e,t)=>{tt(e,\"ReduceL1Shared\",t,\"l1\")},ss=(e,t)=>{tt(e,\"ReduceL2Shared\",t,\"l2\")},us=(e,t)=>{tt(e,\"ReduceLogSumExpShared\",t,\"logSumExp\")},ls=(e,t)=>{tt(e,\"ReduceMaxShared\",t,\"max\")},ds=(e,t)=>{tt(e,\"ReduceMinShared\",t,\"min\")},cs=(e,t)=>{tt(e,\"ReduceProdShared\",t,\"prod\")},ps=(e,t)=>{tt(e,\"ReduceSumShared\",t,\"sum\")},ms=(e,t)=>{tt(e,\"ReduceSumSquareShared\",t,\"sumSquare\")},fs=(e,t)=>{tt(e,\"ReduceLogSumShared\",t,\"logSum\")}});var rt,wm,jr,co,nt,vm,$m,xm,Sm,Tm,Im,Cm,Am,km,Em,ot,gs,bs,ys,_s,ws,vs,$s,xs,Ss,Ts,qr=R(()=>{\"use strict\";te();oe();Se();ae();hs();rt=e=>{if(!e||e.length===0||e.length>2)throw new Error(\"Reduce op requires 1 or 2 inputs.\");if(e.length===2&&e[1].dims.length!==1)throw new Error(\"Invalid axes input dims.\")},wm=e=>[\"\",\"\",`var value = ${e.getByIndices(\"input_indices\")};`,\"\"],jr=(e,t,r,n,o,i,a=!1,l=!1)=>{let d=[],p=r[0].dims,m=p.length,u=k.normalizeAxes(o,m),h=!l&&u.length===0;p.forEach((x,$)=>{h||u.indexOf($)>=0?a&&d.push(1):d.push(x)});let _=d.length,y=k.size(d);return{name:e,shaderCache:t,getShaderSource:x=>{let $=[],v=E(\"_A\",r[0].dataType,m),S=M(\"output\",i,_),T=n(v,S,u),C=T[2];for(let A=0,P=0;A=0?(a&&P++,C=`for(var j${A}: u32 = 0; j${A} < ${p[A]}; j${A}++) {\n ${T[2].includes(\"last_index\")?`let last_index = j${A};`:\"\"}\n ${v.indicesSet(\"input_indices\",A,`j${A}`)}\n ${C}\n }`):($.push(`${v.indicesSet(\"input_indices\",A,S.indicesGet(\"output_indices\",P))};`),P++);return`\n\n ${x.registerUniform(\"output_size\",\"u32\").declareVariables(v,S)}\n\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n var input_indices: ${v.type.indices};\n let output_indices = ${S.offsetToIndices(\"global_idx\")};\n\n ${$.join(`\n`)}\n ${T[0]} // init ops for reduce max/min\n ${T[1]}\n ${C}\n ${T[3]}\n ${T.length===4?S.setByOffset(\"global_idx\",\"value\"):T.slice(4).join(`\n`)}\n }`},getRunData:()=>({outputs:[{dims:d,dataType:i}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:[{type:12,data:y},...N(p,d)]})}},co=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),J({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},nt=(e,t,r,n)=>{let o=e.inputs,i=o.length===1?r:co(o,r);e.compute(jr(t,{hint:i.cacheKey,inputDependencies:[\"rank\"]},[o[0]],i.noopWithEmptyAxes&&i.axes.length===0?wm:n,i.axes,o[0].dataType,i.keepDims,i.noopWithEmptyAxes),{inputs:[0]})},vm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceLogSum\",t,(n,o)=>[`var value = ${o.type.storage}(0);`,\"\",`value += ${n.getByIndices(\"input_indices\")};`,\"value = log(value);\"])},$m=(e,t)=>{rt(e.inputs),nt(e,\"ReduceL1\",t,(n,o)=>[`var value = ${o.type.storage}(0);`,\"\",`value += abs(${n.getByIndices(\"input_indices\")});`,\"\"])},xm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceL2\",t,(n,o)=>[`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`,\"\",`t = ${n.getByIndices(\"input_indices\")}; value += (t * t);`,\"value = sqrt(value);\"])},Sm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceLogSumExp\",t,(n,o)=>[`var value = ${o.type.storage}(0);`,\"\",`value += exp(${n.getByIndices(\"input_indices\")});`,\"value = log(value);\"])},Tm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceMax\",t,(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(n.indicesSet(\"input_indices\",l,0));return[`${a.join(`\n`)}`,`var value = ${n.getByIndices(\"input_indices\")};`,`value = max(value, ${n.getByIndices(\"input_indices\")});`,\"\"]})},Im=(e,t)=>{rt(e.inputs),nt(e,\"ReduceMean\",t,(n,o,i)=>{let a=1;for(let l=0;l=0||i.length===0)&&(a*=e.inputs[0].dims[l]);return[\"var sum = f32(0);\",\"\",`sum += f32(${n.getByIndices(\"input_indices\")});`,`let value = ${o.type.value}(sum / ${a});`]})},Cm=(e,t)=>{rt(e.inputs),nt(e,\"ReduceMin\",t,(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(`input_indices[${l}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${n.getByIndices(\"input_indices\")};`,`value = min(value, ${n.getByIndices(\"input_indices\")});`,\"\"]})},Am=(e,t)=>{rt(e.inputs),nt(e,\"ReduceProd\",t,(n,o)=>[`var value = ${o.type.storage}(1);`,\"\",`value *= ${n.getByIndices(\"input_indices\")};`,\"\"])},km=(e,t)=>{rt(e.inputs),nt(e,\"ReduceSum\",t,(n,o)=>[`var value = ${o.type.storage}(0);`,\"\",`value += ${n.getByIndices(\"input_indices\")};`,\"\"])},Em=(e,t)=>{rt(e.inputs),nt(e,\"ReduceSumSquare\",t,(n,o)=>[`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`,\"\",`t = ${n.getByIndices(\"input_indices\")}; value += t * t;`,\"\"])},ot=(e,t,r)=>{if(t.length===0)return r;let n=1,o=1;for(let i=0;i1024},gs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Im(e,t):is(e,t)},bs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?$m(e,t):as(e,t)},ys=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?xm(e,t):ss(e,t)},_s=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Sm(e,t):us(e,t)},ws=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Tm(e,t):ls(e,t)},vs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Cm(e,t):ds(e,t)},$s=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Am(e,t):cs(e,t)},xs=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?km(e,t):ps(e,t)},Ss=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Em(e,t):ms(e,t)},Ts=(e,t)=>{ot(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?vm(e,t):fs(e,t)}});var Is,Cs,As,po,ks=R(()=>{\"use strict\";te();Se();qr();Is=e=>{if(!e||e.length===0||e.length>2)throw new Error(\"ArgMinMaxOp op requires 1 or 2 inputs.\");if(e[0].dataType!==1)throw new Error(\"Invalid input type.\")},Cs=(e,t)=>{Is(e.inputs);let r=(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(`input_indices[${l}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${n.getByIndices(\"input_indices\")};\nvar best_index : i32 = 0;`,`if (${n.getByIndices(\"input_indices\")} ${t.selectLastIndex>0?\"<=\":\"<\"} value) {\n value = ${n.getByIndices(\"input_indices\")};\n best_index = i32(last_index);\n }`,\"\",o.setByOffset(\"global_idx\",\"best_index\")]};e.compute(jr(\"ArgMin\",{hint:t.cacheKey,inputDependencies:[\"rank\"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},As=(e,t)=>{Is(e.inputs);let r=(n,o,i)=>{let a=[];for(let l=0;l=0||i.length===0)&&a.push(`input_indices[${l}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${n.getByIndices(\"input_indices\")};\nvar best_index : i32 = 0;`,`if (${n.getByIndices(\"input_indices\")} ${t.selectLastIndex>0?\">=\":\">\"} value) {\n value = ${n.getByIndices(\"input_indices\")};\n best_index = i32(last_index);\n }`,\"\",o.setByOffset(\"global_idx\",\"best_index\")]};e.compute(jr(\"argMax\",{hint:t.cacheKey,inputDependencies:[\"rank\"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},po=e=>J(e)});var Pm,mo,zm,Om,Bm,Rt,Dm,Es,Kr=R(()=>{\"use strict\";te();oe();Lr();ae();Pm=(e,t)=>{let r=e[0],n=e[1],o=e[2],i=e[3],a=e[4],l=e[5];if(a&&l)throw new Error(\"Attention cannot have both past and attention_bias\");if(r.dims.length!==3)throw new Error('Input \"input\" must have 3 dimensions');let d=r.dims[0],p=r.dims[1],m=r.dims[2];if(o.dims.length!==1)throw new Error('Input \"bias\" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input \"weights\" is expected to have 2 dimensions');if(n.dims[0]!==m)throw new Error(\"Input 1 dimension 0 should have same length as dimension 2 of input 0\");if(o.dims[0]!==n.dims[1])throw new Error('Input \"bias\" dimension 0 should have same length as dimension 1 of input \"weights\"');let u=o.dims[0]/3,h=u,_=h;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error(\"qkv_hidden_sizes attribute should have 3 elements\");for(let S of t.qkvHiddenSizes)if(S%t.numHeads!==0)throw new Error(\"qkv_hidden_sizes should be divisible by num_heads\");u=t.qkvHiddenSizes[0],h=t.qkvHiddenSizes[1],_=t.qkvHiddenSizes[2]}let y=p;if(u!==h)throw new Error(\"qkv_hidden_sizes first element should be same as the second\");if(o.dims[0]!==u+h+_)throw new Error('Input \"bias\" dimension 0 should have same length as sum of Q/K/V hidden sizes');let g=0;if(a){if(h!==_)throw new Error('Input \"past\" expect k_hidden_size == v_hidden_size');if(a.dims.length!==5)throw new Error('Input \"past\" must have 5 dimensions');if(a.dims[0]!==2)throw new Error('Input \"past\" first dimension must be 2');if(a.dims[1]!==d)throw new Error('Input \"past\" second dimension must be batch_size');if(a.dims[2]!==t.numHeads)throw new Error('Input \"past\" third dimension must be num_heads');if(a.dims[4]!==h/t.numHeads)throw new Error('Input \"past\" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(g=a.dims[3])}let x=y+g,$=-1,v=0;if(i)throw new Error(\"Mask not supported\");if(a)throw new Error(\"past is not supported\");if(l){if(l.dims.length!==4)throw new Error('Input \"attention_bias\" must have 4 dimensions');if(l.dims[0]!==d||l.dims[1]!==t.numHeads||l.dims[2]!==p||l.dims[3]!==x)throw new Error('Expect \"attention_bias\" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:d,sequenceLength:p,pastSequenceLength:g,kvSequenceLength:y,totalSequenceLength:x,maxSequenceLength:$,inputHiddenSize:m,hiddenSize:u,vHiddenSize:_,headSize:Math.floor(u/t.numHeads),vHeadSize:Math.floor(_/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:v,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},mo=(e,t,r)=>t&&e?`\n let total_sequence_length_input = u32(${t.getByOffset(\"0\")});\n let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);\n let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;\n let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input;\n total_sequence_length = u32(${e?.getByOffset(\"batchIdx\")}) + 1;\n var past_sequence_length: u32 = 0;\n if (is_first_prompt == false) {\n past_sequence_length = total_sequence_length - sequence_length;\n }\n `:`\n ${r?\"let past_sequence_length = uniforms.past_sequence_length\":\"\"};\n let present_sequence_length = total_sequence_length;\n `,zm=(e,t,r,n,o,i,a,l)=>{let d=me(a?1:i),p=64,m=i/d;m{let v=M(\"x\",e.dataType,e.dims,d),S=[v],T=a?E(\"seq_lens\",a.dataType,a.dims):void 0;T&&S.push(T);let C=l?E(\"total_sequence_length_input\",l.dataType,l.dims):void 0;C&&S.push(C);let A=ke(e.dataType),P=[{name:\"batch_size\",type:\"u32\"},{name:\"num_heads\",type:\"u32\"},{name:\"past_sequence_length\",type:\"u32\"},{name:\"sequence_length\",type:\"u32\"},{name:\"total_sequence_length\",type:\"u32\"},{name:\"elements_per_thread\",type:\"u32\"}];return`\n var thread_max: array;\n var thread_sum: array;\n ${$.registerUniforms(P).declareVariables(...S)}\n ${$.mainStart([p,1,1])}\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let sequence_length = uniforms.sequence_length;\n var total_sequence_length = uniforms.total_sequence_length;\n ${mo(T,C,!1)}\n let local_offset = local_idx * uniforms.elements_per_thread;\n let offset = (global_idx / ${p}) * uniforms.total_sequence_length + local_offset;\n let seq_causal_length = ${a?\"u32(past_sequence_length + workgroup_id.y + 1)\":\"total_sequence_length\"};\n var thread_max_vector = ${y}(-3.402823e+38f);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n thread_max_vector = max(${y}(x[offset + i]), thread_max_vector);\n }\n thread_max[local_idx] = ${(()=>{switch(d){case 1:return\"thread_max_vector\";case 2:return\"max(thread_max_vector.x, thread_max_vector.y)\";case 4:return\"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))\";default:throw new Error(`Unsupported components: ${d}`)}})()};\n workgroupBarrier();\n\n var max_value = f32(-3.402823e+38f);\n for (var i = 0u; i < ${p}; i++) {\n max_value = max(thread_max[i], max_value);\n }\n\n var sum_vector = ${y}(0);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n sum_vector += exp(${y}(x[offset + i]) - max_value);\n }\n thread_sum[local_idx] = ${(()=>{switch(d){case 1:return\"sum_vector\";case 2:return\"sum_vector.x + sum_vector.y\";case 4:return\"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w\";default:throw new Error(`Unsupported components: ${d}`)}})()};\n workgroupBarrier();\n\n var sum: f32 = 0;\n for (var i = 0u; i < ${p}; i++) {\n sum += thread_sum[i];\n }\n\n if (sum == 0) {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n x[offset + i] = ${v.type.value}(${A}(1.0) / ${A}(seq_causal_length));\n }\n } else {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n var f32input = ${y}(x[offset + i]);\n x[offset + i] = ${v.type.value}(exp(f32input - max_value) / sum);\n }\n }\n ${a?`\n for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) {\n x[offset + total_seq_id] = ${v.type.value}(${A}(0));\n }`:\"\"};\n }`};return{name:\"AttentionProbsSoftmax\",shaderCache:{hint:`${p};${_};${d}`,inputDependencies:g},getShaderSource:x,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(i/p),y:o,z:t*r},programUniforms:h})}},Om=(e,t,r,n,o,i,a,l,d)=>{let p=a+i.kvSequenceLength,m=[i.batchSize,i.numHeads,i.sequenceLength,p],u=e>1&&n,h=i.kvNumHeads?i.kvNumHeads:i.numHeads,_=u?[i.batchSize,h,p,i.headSize]:void 0,y=i.nReps?i.nReps:1,g=i.scale===0?1/Math.sqrt(i.headSize):i.scale,x=me(i.headSize),$=i.headSize/x,v=12,S={x:Math.ceil(p/v),y:Math.ceil(i.sequenceLength/v),z:i.batchSize*i.numHeads},T=[{type:12,data:i.sequenceLength},{type:12,data:$},{type:12,data:p},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:1,data:g},{type:12,data:a},{type:12,data:i.kvSequenceLength},{type:12,data:y}],C=u&&n&&k.size(n.dims)>0,A=[\"type\",\"type\"];C&&A.push(\"type\"),o&&A.push(\"type\"),l&&A.push(\"type\"),d&&A.push(\"type\");let P=[{dims:m,dataType:t.dataType,gpuDataType:0}];u&&P.push({dims:_,dataType:t.dataType,gpuDataType:0});let O=U=>{let G=E(\"q\",t.dataType,t.dims,x),q=E(\"key\",r.dataType,r.dims,x),K=[G,q];if(C){let ne=E(\"past_key\",n.dataType,n.dims,x);K.push(ne)}o&&K.push(E(\"attention_bias\",o.dataType,o.dims));let W=l?E(\"seq_lens\",l.dataType,l.dims):void 0;W&&K.push(W);let Y=d?E(\"total_sequence_length_input\",d.dataType,d.dims):void 0;Y&&K.push(Y);let se=M(\"output\",t.dataType,m),X=[se];u&&X.push(M(\"present_key\",t.dataType,_,x));let re=ke(1,x),ee=[{name:\"M\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"num_heads\",type:\"u32\"},{name:\"head_size\",type:\"u32\"},{name:\"alpha\",type:\"f32\"},{name:\"past_sequence_length\",type:\"u32\"},{name:\"kv_sequence_length\",type:\"u32\"},{name:\"n_reps\",type:\"u32\"}];return`\n const TILE_SIZE = ${v}u;\n\n var tileQ: array<${G.type.storage}, ${v*v}>;\n var tileK: array<${G.type.storage}, ${v*v}>;\n ${U.registerUniforms(ee).declareVariables(...K,...X)}\n ${U.mainStart([v,v,1])}\n // x holds the N and y holds the M\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let kvHeadIdx = ${y===1?\"headIdx\":\"headIdx / uniforms.n_reps\"};\n let kv_num_heads = ${y===1?\"uniforms.num_heads\":\"uniforms.num_heads / uniforms.n_reps\"};\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let m = workgroup_id.y * TILE_SIZE;\n let n = workgroup_id.x * TILE_SIZE;\n let sequence_length = uniforms.M;\n var total_sequence_length = uniforms.N;\n ${mo(W,Y,!0)}\n let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx;\n let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;\n ${C&&u?\"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;\":\"\"};\n let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K;\n ${u?\"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;\":\"\"}\n var value = ${re}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {\n var idx = TILE_SIZE * local_id.y + local_id.x;\n ${(()=>C&&u?`\n if (n + local_id.y < past_sequence_length) {\n tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x];\n } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {\n tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x];\n }`:`\n if (n + local_id.y < uniforms.kv_sequence_length) {\n tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x];\n }`)()}\n ${u?`if (n + local_id.y < present_sequence_length) {\n present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];\n }`:\"\"}\n }\n workgroupBarrier();\n\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {\n value += ${re}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);\n }\n\n workgroupBarrier();\n }\n\n if (global_id.y < uniforms.M && global_id.x < total_sequence_length) {\n let headOffset = workgroup_id.z * uniforms.M * uniforms.N;\n let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;\n var sum: f32 = ${(()=>{switch(x){case 1:return\"value\";case 2:return\"value.x + value.y\";case 4:return\"value.x + value.y + value.z + value.w\";default:throw new Error(`Unsupported components: ${x}`)}})()};\n output[outputIdx] = ${se.type.value} (sum * uniforms.alpha) + ${o?\"attention_bias[outputIdx]\":\"0.0\"};\n }\n }`};return{name:\"AttentionProbs\",shaderCache:{hint:`${x};${o!==void 0};${n!==void 0};${e}`,inputDependencies:A},getRunData:()=>({outputs:P,dispatchGroup:S,programUniforms:T}),getShaderSource:O}},Bm=(e,t,r,n,o,i,a=void 0,l=void 0)=>{let d=i+o.kvSequenceLength,p=o.nReps?o.nReps:1,m=o.vHiddenSize*p,u=e>1&&n,h=o.kvNumHeads?o.kvNumHeads:o.numHeads,_=u?[o.batchSize,h,d,o.headSize]:void 0,y=[o.batchSize,o.sequenceLength,m],g=12,x={x:Math.ceil(o.vHeadSize/g),y:Math.ceil(o.sequenceLength/g),z:o.batchSize*o.numHeads},$=[{type:12,data:o.sequenceLength},{type:12,data:d},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:m},{type:12,data:i},{type:12,data:o.kvSequenceLength},{type:12,data:p}],v=u&&n&&k.size(n.dims)>0,S=[\"type\",\"type\"];v&&S.push(\"type\"),a&&S.push(\"type\"),l&&S.push(\"type\");let T=[{dims:y,dataType:t.dataType,gpuDataType:0}];u&&T.push({dims:_,dataType:t.dataType,gpuDataType:0});let C=A=>{let P=E(\"probs\",t.dataType,t.dims),O=E(\"v\",r.dataType,r.dims),U=[P,O];v&&U.push(E(\"past_value\",n.dataType,n.dims));let G=a?E(\"seq_lens\",a.dataType,a.dims):void 0;a&&U.push(G);let q=l?E(\"total_sequence_length_input\",l.dataType,l.dims):void 0;l&&U.push(q);let W=[M(\"output\",t.dataType,y)];u&&W.push(M(\"present_value\",t.dataType,_));let Y=[{name:\"M\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"num_heads\",type:\"u32\"},{name:\"head_size\",type:\"u32\"},{name:\"v_hidden_size\",type:\"u32\"},{name:\"past_sequence_length\",type:\"u32\"},{name:\"kv_sequence_length\",type:\"u32\"},{name:\"n_reps\",type:\"u32\"}];return`\n const TILE_SIZE = ${g}u;\n var tileQ: array<${P.type.value}, ${g*g}>;\n var tileV: array<${P.type.value}, ${g*g}>;\n ${A.registerUniforms(Y).declareVariables(...U,...W)}\n ${A.mainStart([g,g,1])}\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let kvHeadIdx = ${p===1?\"headIdx\":\"headIdx / uniforms.n_reps\"};\n let kv_num_heads = ${p===1?\"uniforms.num_heads\":\"uniforms.num_heads / uniforms.n_reps\"};\n let m = global_id.y;\n let n = global_id.x;\n let sequence_length = uniforms.M;\n var total_sequence_length = uniforms.K;\n ${mo(G,q,!0)}\n let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;\n let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch\n ${v&&u?\"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;\":\"\"};\n let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n;\n ${u?\"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;\":\"\"}\n var value = ${P.type.storage}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n var idx = TILE_SIZE * local_id.y + local_id.x;\n ${(()=>v&&u?`\n if (w + local_id.y < past_sequence_length) {\n tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N];\n } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {\n tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N];\n }\n `:`\n if (w + local_id.y < uniforms.kv_sequence_length) {\n tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N];\n }`)()}\n ${u?`\n if (w + local_id.y < present_sequence_length) {\n present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx];\n }`:\"\"}\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) {\n value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x];\n }\n workgroupBarrier();\n }\n\n // we need to transpose output from BNSH_v to BSND_v\n if (m < uniforms.M && n < uniforms.N) {\n let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size\n + headIdx * uniforms.N + n;\n output[outputIdx] = value;\n }\n }`};return{name:\"AttentionScore\",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:S},getRunData:()=>({outputs:T,dispatchGroup:x,programUniforms:$}),getShaderSource:C}},Rt=(e,t,r,n,o,i,a,l,d,p,m=void 0,u=void 0)=>{let h=Math.min(e.outputCount,1+(a?1:0)+(l?1:0)),_=h>1?p.pastSequenceLength:0,y=_+p.kvSequenceLength,g=d&&k.size(d.dims)>0?d:void 0,x=[t,r];h>1&&a&&k.size(a.dims)>0&&x.push(a),g&&x.push(g),m&&x.push(m),u&&x.push(u);let $=e.compute(Om(h,t,r,a,g,p,_,m,u),{inputs:x,outputs:h>1?[-1,1]:[-1]})[0];e.compute(zm($,p.batchSize,p.numHeads,_,p.sequenceLength,y,m,u),{inputs:m&&u?[$,m,u]:[$],outputs:[]});let v=[$,n];h>1&&l&&k.size(l.dims)>0&&v.push(l),m&&v.push(m),u&&v.push(u),e.compute(Bm(h,$,n,l,p,_,m,u),{inputs:v,outputs:h>1?[0,2]:[0]})},Dm=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,o=t.inputHiddenSize,i=t.headSize,a=12,l={x:Math.ceil(t.headSize/a),y:Math.ceil(t.sequenceLength/a),z:t.batchSize*t.numHeads},d=[e.inputs[0],e.inputs[1],e.inputs[2]],p=[{type:12,data:n},{type:12,data:o},{type:12,data:i},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],m=u=>{let h=M(\"output_q\",d[0].dataType,r),_=M(\"output_k\",d[0].dataType,r),y=M(\"output_v\",d[0].dataType,r),g=E(\"input\",d[0].dataType,d[0].dims),x=E(\"weight\",d[1].dataType,d[1].dims),$=E(\"bias\",d[2].dataType,d[2].dims),v=g.type.storage,S=[{name:\"M\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"num_heads\",type:\"u32\"},{name:\"head_size\",type:\"u32\"},{name:\"hidden_size\",type:\"u32\"},{name:\"ldb\",type:\"u32\"}];return`\n const TILE_SIZE = ${a}u;\n var tileInput: array<${v}, ${a*a}>;\n var tileWeightQ: array<${v}, ${a*a}>;\n var tileWeightK: array<${v}, ${a*a}>;\n var tileWeightV: array<${v}, ${a*a}>;\n ${u.registerUniforms(S).declareVariables(g,x,$,h,_,y)}\n ${u.mainStart([a,a,1])}\n let batchIndex = workgroup_id.z / uniforms.num_heads;\n let headNumber = workgroup_id.z % uniforms.num_heads;\n let m = global_id.y;\n let n = global_id.x;\n\n let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;\n let biasOffsetQ = headNumber * uniforms.head_size;\n let biasOffsetK = uniforms.hidden_size + biasOffsetQ;\n let biasOffsetV = uniforms.hidden_size + biasOffsetK;\n\n var valueQ = ${v}(0);\n var valueK = ${v}(0);\n var valueV = ${v}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n let offset = n + (w + local_id.y) * uniforms.ldb;\n tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];\n tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];\n tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:l,programUniforms:p}),getShaderSource:m},{inputs:d,outputs:[-1,-1,-1]})},Es=(e,t)=>{let r=Pm(e.inputs,t),[n,o,i]=Dm(e,r);return Rt(e,n,o,i,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r)}});var Mm,Rm,Um,Ps,zs=R(()=>{\"use strict\";We();te();oe();Se();ae();Mm=(e,t)=>{if(!e||e.length!==5)throw new Error(\"BatchNormalization requires 5 inputs\");let r=(n,o,i)=>{let a=o.length;if(a!==n.length)throw new Error(`${i}: num dimensions != ${a}`);o.forEach((l,d)=>{if(l!==n[d])throw new Error(`${i}: dim[${d}] do not match`)})};if(e[0].dims.length>1){let n=t.format===\"NHWC\"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,n,\"Invalid input scale\"),r(e[2].dims,n,\"Invalid input B\"),r(e[3].dims,n,\"Invalid input mean\"),r(e[4].dims,n,\"Invalid input var\")}else r(e[1].dims,[1],\"Invalid input scale\"),r(e[2].dims,[1],\"Invalid input B\"),r(e[3].dims,[1],\"Invalid input mean\"),r(e[4].dims,[1],\"Invalid input var\")},Rm=(e,t)=>{let{epsilon:r,spatial:n,format:o}=t,i=e[0].dims,a=n?me(i[i.length-1]):1,l=o===\"NHWC\"&&i.length>1?a:1,d=k.size(i)/a,p=n,m=p?i.length:i,u=E(\"x\",e[0].dataType,e[0].dims,a),h=E(\"scale\",e[1].dataType,e[1].dims,l),_=E(\"bias\",e[2].dataType,e[2].dims,l),y=E(\"inputMean\",e[3].dataType,e[3].dims,l),g=E(\"inputVar\",e[4].dataType,e[4].dims,l),x=M(\"y\",e[0].dataType,m,a),$=()=>{let S=\"\";if(n)S=`let cOffset = ${i.length===1?\"0u\":o===\"NHWC\"?`outputIndices[${i.length-1}] / ${a}`:\"outputIndices[1]\"};`;else if(o===\"NCHW\")S=`\n ${x.indicesSet(\"outputIndices\",\"0\",\"0\")}\n let cOffset = ${x.indicesToOffset(\"outputIndices\")};`;else{S=`var cIndices = ${h.type.indices}(0);\n cIndices[0] = outputIndices[${i.length-1}];`;for(let T=1;T`\n const epsilon = ${r};\n ${S.registerUniform(\"outputSize\",\"u32\").declareVariables(u,h,_,y,g,x)}\n ${S.mainStart()}\n ${S.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n var outputIndices = ${x.offsetToIndices(`global_idx * ${a}`)};\n ${$()}\n let scale = ${h.getByOffset(\"cOffset\")};\n let bias = ${_.getByOffset(\"cOffset\")};\n let inputMean = ${y.getByOffset(\"cOffset\")};\n let inputVar = ${g.getByOffset(\"cOffset\")};\n let x = ${u.getByOffset(\"global_idx\")};\n let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;\n ${x.setByOffset(\"global_idx\",\"value\")}\n }`;return{name:\"BatchNormalization\",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${a}`,inputDependencies:p?[\"rank\",\"type\",\"type\",\"type\",\"type\"]:void 0},getShaderSource:v,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p?[{type:12,data:d},...N(i)]:[{type:12,data:d}]})}},Um=e=>J(e),Ps=(e,t)=>{let{inputs:r,outputCount:n}=e,o=Um({...t,outputCount:n});if(we.webgpu.validateInputContent&&Mm(r,o),t.trainingMode)throw new Error(\"BatchNormalization trainingMode is not supported yet.\");e.compute(Rm(r,o))}});var Nm,Vm,Os,Bs=R(()=>{\"use strict\";oe();ae();Nm=e=>{if(e[0].dims.length!==3)throw new Error(\"input should have 3 dimensions\");if(![320,640,1280].includes(e[0].dims[2]))throw new Error(\"number of channels should be 320, 640 or 1280\");if(e[1].dims.length!==1)throw new Error(\"bias is expected to have 1 dimensions\");if(e[0].dims[2]!==e[1].dims[0])throw new Error(\"last dimension of input and bias are not the same\")},Vm=e=>{let t=e[0].dims,r=e[0].dims[2],n=k.size(t)/4,o=e[0].dataType,i=E(\"input\",o,t,4),a=E(\"bias\",o,[r],4),l=E(\"residual\",o,t,4),d=M(\"output\",o,t,4);return{name:\"BiasAdd\",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:m=>`\n const channels = ${r}u / 4;\n ${m.declareVariables(i,a,l,d)}\n\n ${m.mainStart()}\n ${m.guardAgainstOutOfBoundsWorkgroupSizes(n)}\n let value = ${i.getByOffset(\"global_idx\")}\n + ${a.getByOffset(\"global_idx % channels\")} + ${l.getByOffset(\"global_idx\")};\n ${d.setByOffset(\"global_idx\",\"value\")}\n }`}},Os=e=>{Nm(e.inputs),e.compute(Vm(e.inputs))}});var Wm,fe,Ds,Ms,Rs,Us,Ns,Vs,Ws,Ls,Gs,Lm,Hs,Fs,qs,js,Jt,Ks,Yr,Ys,Zs,Qs,Xs,Js,eu,tu,ru,nu,ou,iu,au,su,uu,lu,du,cu,pu,fo,ho,mu,fu,hu,Gm,Hm,gu,Zr=R(()=>{\"use strict\";te();oe();Se();ae();Wm=(e,t,r,n,o,i,a)=>{let l=Math.ceil(t/4),d=\"\";typeof o==\"string\"?d=`${o}(a)`:d=o(\"a\");let p=E(\"inputData\",r,[l],4),m=M(\"outputData\",n,[l],4),u=[{name:\"vec_size\",type:\"u32\"}];return a&&u.push(...a),`\n ${e.registerUniforms(u).declareVariables(p,m)}\n\n ${i??\"\"}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.vec_size\")}\n\n let a = ${p.getByOffset(\"global_idx\")};\n ${m.setByOffset(\"global_idx\",d)}\n }`},fe=(e,t,r,n,o,i=e.dataType,a,l)=>{let d=[{type:12,data:Math.ceil(k.size(e.dims)/4)}];return a&&d.push(...a),{name:t,shaderCache:{hint:o,inputDependencies:[\"type\"]},getShaderSource:p=>Wm(p,k.size(e.dims),e.dataType,i,r,n,l),getRunData:p=>({outputs:[{dims:e.dims,dataType:i}],dispatchGroup:{x:Math.ceil(k.size(p[0].dims)/64/4)},programUniforms:d})}},Ds=e=>{e.compute(fe(e.inputs[0],\"Abs\",\"abs\"))},Ms=e=>{e.compute(fe(e.inputs[0],\"Acos\",\"acos\"))},Rs=e=>{e.compute(fe(e.inputs[0],\"Acosh\",\"acosh\"))},Us=e=>{e.compute(fe(e.inputs[0],\"Asin\",\"asin\"))},Ns=e=>{e.compute(fe(e.inputs[0],\"Asinh\",\"asinh\"))},Vs=e=>{e.compute(fe(e.inputs[0],\"Atan\",\"atan\"))},Ws=e=>{e.compute(fe(e.inputs[0],\"Atanh\",\"atanh\"))},Ls=e=>J(e),Gs=(e,t)=>{let r;switch(t.to){case 10:r=\"vec4\";break;case 1:r=\"vec4\";break;case 12:r=\"vec4\";break;case 6:r=\"vec4\";break;case 9:r=\"vec4\";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(fe(e.inputs[0],\"Cast\",r,void 0,t.cacheKey,t.to))},Lm=e=>{let t,r,n=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,r=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,r=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error(\"Unsupport data type\")}return J({min:t,max:r})},Hs=(e,t)=>{let r=t||Lm(e.inputs),n=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Clip\",o=>`clamp(${o}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,r.cacheKey,void 0,[{type:e.inputs[0].dataType,data:r.min},{type:e.inputs[0].dataType,data:r.max}],[{name:\"min\",type:n},{name:\"max\",type:n}]),{inputs:[0]})},Fs=e=>{e.compute(fe(e.inputs[0],\"Ceil\",\"ceil\"))},qs=e=>{e.compute(fe(e.inputs[0],\"Cos\",\"cos\"))},js=e=>{e.compute(fe(e.inputs[0],\"Cosh\",\"cosh\"))},Jt=e=>J(e),Ks=(e,t)=>{let r=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Elu\",n=>`elu_vf32(${n})`,`\n const elu_alpha_ = ${r}(${t.alpha});\n\n fn elu_f32(a: ${r}) -> ${r} {\n return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);\n }\n\n fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> {\n return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));\n }`,t.cacheKey))},Yr=(e=\"f32\")=>`\nconst r0: ${e} = 0.3275911;\nconst r1: ${e} = 0.254829592;\nconst r2: ${e} = -0.284496736;\nconst r3: ${e} = 1.421413741;\nconst r4: ${e} = -1.453152027;\nconst r5: ${e} = 1.061405429;\n\nfn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {\n let absv = abs(v);\n let x = 1.0 / (1.0 + r0 * absv);\n return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));\n}`,Ys=e=>{let t=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Erf\",r=>`erf_vf32(${r})`,Yr(t)))},Zs=e=>{e.compute(fe(e.inputs[0],\"Exp\",\"exp\"))},Qs=e=>{e.compute(fe(e.inputs[0],\"Floor\",\"floor\"))},Xs=e=>{let t=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Gelu\",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Yr(t)))},Js=(e,t)=>{let r=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"LeakyRelu\",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},eu=e=>{e.compute(fe(e.inputs[0],\"Not\",t=>`!${t}`))},tu=e=>{e.compute(fe(e.inputs[0],\"Neg\",t=>`-${t}`))},ru=e=>{e.compute(fe(e.inputs[0],\"Reciprocal\",t=>`1.0/${t}`))},nu=e=>{let t=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"Relu\",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},ou=e=>{e.compute(fe(e.inputs[0],\"Sigmoid\",t=>`(1.0 / (1.0 + exp(-${t})))`))},iu=e=>J(e),au=(e,t)=>{let r=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"HardSigmoid\",n=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${n} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},su=e=>{e.compute(fe(e.inputs[0],\"Sin\",\"sin\"))},uu=e=>{e.compute(fe(e.inputs[0],\"Sinh\",\"sinh\"))},lu=e=>{e.compute(fe(e.inputs[0],\"Sqrt\",\"sqrt\"))},du=e=>{e.compute(fe(e.inputs[0],\"Tan\",\"tan\"))},cu=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,pu=e=>{e.compute(fe(e.inputs[0],\"Tanh\",cu))},fo=(e=\"f32\")=>`\nconst fast_gelu_a: ${e} = 0.5;\nconst fast_gelu_b: ${e} = 0.7978845608028654;\nconst fast_gelu_c: ${e} = 0.035677408136300125;\n\nfn tanh_v(v: vec4<${e}>) -> vec4<${e}> {\n return ${cu(\"v\")};\n}\n`,ho=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,mu=e=>{let t=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"FastGelu\",ho,fo(t),void 0,e.inputs[0].dataType))},fu=(e,t)=>{let r=ke(e.inputs[0].dataType);return e.compute(fe(e.inputs[0],\"ThresholdedRelu\",n=>`select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},hu=e=>{e.compute(fe(e.inputs[0],\"Log\",\"log\"))},Gm=(e,t)=>`\nconst alpha = vec4<${e}>(${t});\nconst one = ${e}(1.0);\nconst zero = ${e}(0.0);\n\nfn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {\n let v = x *alpha;\n var x1 : vec4<${e}>;\n for (var i = 0; i < 4; i = i + 1) {\n if (v[i] >= zero) {\n x1[i] = one / (one + exp(-v[i]));\n } else {\n x1[i] = one - one / (one + exp(v[i]));\n }\n }\n return x * x1;\n}\n`,Hm=e=>`quick_gelu_impl(${e})`,gu=(e,t)=>{let r=ke(e.inputs[0].dataType);e.compute(fe(e.inputs[0],\"QuickGelu\",Hm,Gm(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}});var Fm,qm,yu,_u=R(()=>{\"use strict\";oe();ae();Zr();Fm=e=>{if(e[0].dims.length!==3)throw new Error(\"input should have 3 dimensions\");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error(\"hidden state should be 2560, 5120 or 10240\");if(e[1].dims.length!==1)throw new Error(\"bias is expected to have 1 dimensions\");if(e[0].dims[2]!==e[1].dims[0])throw new Error(\"last dimension of input and bias are not the same\")},qm=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=E(\"input\",e[0].dataType,e[0].dims,4),n=E(\"bias\",e[0].dataType,[e[0].dims[2]],4),o=M(\"output\",e[0].dataType,t,4),i=k.size(t)/4,a=ye(e[0].dataType);return{name:\"BiasSplitGelu\",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:d=>`\n const M_SQRT2 = sqrt(2.0);\n const halfChannels = ${e[0].dims[2]/4/2}u;\n\n ${d.declareVariables(r,n,o)}\n\n ${Yr(a)}\n\n ${d.mainStart()}\n ${d.guardAgainstOutOfBoundsWorkgroupSizes(i)}\n let biasIdx = global_idx % halfChannels;\n let batchIndex = global_idx / halfChannels;\n let inputOffset = biasIdx + batchIndex * halfChannels * 2;\n let valueLeft = input[inputOffset] + bias[biasIdx];\n let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];\n let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);\n\n ${o.setByOffset(\"global_idx\",\"valueLeft * geluRight\")}\n }`}},yu=e=>{Fm(e.inputs),e.compute(qm(e.inputs))}});var jm,Km,it,wu,vu,$u,xu,Su,Tu,Iu,Cu,Au,ku,Eu=R(()=>{\"use strict\";te();oe();ae();jm=(e,t,r,n,o,i,a,l,d,p,m,u)=>{let h,_;typeof l==\"string\"?h=_=(v,S)=>`${l}((${v}),(${S}))`:typeof l==\"function\"?h=_=l:(h=l.scalar,_=l.vector);let y=M(\"outputData\",m,n.length,4),g=E(\"aData\",d,t.length,4),x=E(\"bData\",p,r.length,4),$;if(o)if(i){let v=k.size(t)===1,S=k.size(r)===1,T=t.length>0&&t[t.length-1]%4===0,C=r.length>0&&r[r.length-1]%4===0;v||S?$=y.setByOffset(\"global_idx\",_(v?`${g.type.value}(${g.getByOffset(\"0\")}.x)`:g.getByOffset(\"global_idx\"),S?`${x.type.value}(${x.getByOffset(\"0\")}.x)`:x.getByOffset(\"global_idx\"))):$=`\n let outputIndices = ${y.offsetToIndices(\"global_idx * 4u\")};\n let offsetA = ${g.broadcastedIndicesToOffset(\"outputIndices\",y)};\n let offsetB = ${x.broadcastedIndicesToOffset(\"outputIndices\",y)};\n ${y.setByOffset(\"global_idx\",_(a||T?g.getByOffset(\"offsetA / 4u\"):`${g.type.value}(${g.getByOffset(\"offsetA / 4u\")}[offsetA % 4u])`,a||C?x.getByOffset(\"offsetB / 4u\"):`${x.type.value}(${x.getByOffset(\"offsetB / 4u\")}[offsetB % 4u])`))}\n `}else $=y.setByOffset(\"global_idx\",_(g.getByOffset(\"global_idx\"),x.getByOffset(\"global_idx\")));else{if(!i)throw new Error(\"no necessary to use scalar implementation for element-wise binary op implementation.\");let v=(S,T,C=\"\")=>{let A=`aData[indexA${T}][componentA${T}]`,P=`bData[indexB${T}][componentB${T}]`;return`\n let outputIndices${T} = ${y.offsetToIndices(`global_idx * 4u + ${T}u`)};\n let offsetA${T} = ${g.broadcastedIndicesToOffset(`outputIndices${T}`,y)};\n let offsetB${T} = ${x.broadcastedIndicesToOffset(`outputIndices${T}`,y)};\n let indexA${T} = offsetA${T} / 4u;\n let indexB${T} = offsetB${T} / 4u;\n let componentA${T} = offsetA${T} % 4u;\n let componentB${T} = offsetB${T} % 4u;\n ${S}[${T}] = ${C}(${h(A,P)});\n `};m===9?$=`\n var data = vec4(0);\n ${v(\"data\",0,\"u32\")}\n ${v(\"data\",1,\"u32\")}\n ${v(\"data\",2,\"u32\")}\n ${v(\"data\",3,\"u32\")}\n outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:$=`\n ${v(\"outputData[global_idx]\",0)}\n ${v(\"outputData[global_idx]\",1)}\n ${v(\"outputData[global_idx]\",2)}\n ${v(\"outputData[global_idx]\",3)}\n `}return`\n ${e.registerUniform(\"vec_size\",\"u32\").declareVariables(g,x,y)}\n\n ${u??\"\"}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.vec_size\")}\n ${$}\n }`},Km=(e,t,r,n,o,i,a=r.dataType)=>{let l=r.dims.map(g=>Number(g)??1),d=n.dims.map(g=>Number(g)??1),p=!k.areEqual(l,d),m=l,u=k.size(l),h=!1,_=!1,y=[p];if(p){let g=et.calcShape(l,d,!1);if(!g)throw new Error(\"Can't perform binary op on the given tensors\");m=g.slice(),u=k.size(m);let x=k.size(l)===1,$=k.size(d)===1,v=l.length>0&&l[l.length-1]%4===0,S=d.length>0&&d[d.length-1]%4===0;y.push(x),y.push($),y.push(v),y.push(S);let T=1;for(let C=1;Cg.toString()).join(\"_\"),inputDependencies:[\"rank\",\"rank\"]},getShaderSource:g=>jm(g,l,d,m,h,p,_,o,r.dataType,n.dataType,a,i),getRunData:()=>({outputs:[{dims:m,dataType:a}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:Math.ceil(k.size(m)/4)},...N(l,d,m)]})}},it=(e,t,r,n,o,i)=>{e.compute(Km(t,o??\"\",e.inputs[0],e.inputs[1],r,n,i))},wu=e=>{it(e,\"Add\",(t,r)=>`${t}+${r}`)},vu=e=>{it(e,\"Div\",(t,r)=>`${t}/${r}`)},$u=e=>{it(e,\"Equal\",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},xu=e=>{it(e,\"Mul\",(t,r)=>`${t}*${r}`)},Su=e=>{let t=E(\"input\",e.inputs[0].dataType,e.inputs[0].dims).type.value;it(e,\"Pow\",{scalar:(n,o)=>`pow_custom(${n},${o})`,vector:(n,o)=>`pow_vector_custom(${n},${o})`},`\n fn pow_custom(a : ${t}, b : ${t}) -> ${t} {\n if (b == ${t}(0.0)) {\n return ${t}(1.0);\n } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {\n return ${t}(pow(f32(a), f32(b))); // NaN\n }\n return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t===\"i32\"?\"round\":\"\"}(pow(f32(abs(a)), f32(b))));\n }\n fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {\n // TODO: implement vectorized pow\n return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));\n }\n `)},Tu=e=>{it(e,\"Sub\",(t,r)=>`${t}-${r}`)},Iu=e=>{it(e,\"Greater\",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},Cu=e=>{it(e,\"Less\",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Au=e=>{it(e,\"GreaterOrEqual\",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},ku=e=>{it(e,\"LessOrEqual\",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}});var Zm,Qm,Xm,Jm,Pu,zu,Ou=R(()=>{\"use strict\";te();oe();Se();ae();Zm=(e,t)=>{if(!e||e.length<1)throw new Error(\"too few inputs\");let r=0,n=e[r],o=n.dataType,i=n.dims.length;e.forEach((a,l)=>{if(l!==r){if(a.dataType!==o)throw new Error(\"input tensors should be one type\");if(a.dims.length!==i)throw new Error(\"input tensors should have the same shape\");a.dims.forEach((d,p)=>{if(p!==t&&d!==n.dims[p])throw new Error(\"non concat dimensions must match\")})}})},Qm=(e,t)=>`\n fn calculateInputIndex(index: u32) -> u32 {\n let sizeInConcatAxis = array(${t});\n for (var i: u32 = 0u; i < ${e}; i += 1u ) {\n if (index < sizeInConcatAxis[i]) {\n return i;\n }\n }\n return ${e}u;\n }`,Xm=(e,t)=>{let r=e.length,n=[];for(let o=0;o{let o=k.size(r),i=new Array(e.length),a=new Array(e.length),l=0,d=[],p=[],m=[{type:12,data:o}];for(let g=0;g`uniforms.sizeInConcatAxis${g}`).join(\",\"),y=g=>`\n\n ${(()=>{g.registerUniform(\"outputSize\",\"u32\");for(let x=0;x(${_});\n ${h} -= sizeInConcatAxis[inputIndex - 1u];\n }\n\n ${Xm(a,u)}\n }`;return{name:\"Concat\",shaderCache:{hint:`${t}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:m}),getShaderSource:y}},Pu=(e,t)=>{let r=e.inputs,n=r[0].dims,o=k.normalizeAxis(t.axis,n.length);Zm(r,o);let i=n.slice();i[o]=r.reduce((l,d)=>l+(d.dims.length>o?d.dims[o]:0),0);let a=r.filter(l=>k.size(l.dims)>0);e.compute(Jm(a,o,i,r[0].dataType),{inputs:a})},zu=e=>J({axis:e.axis})});var Fe,qe,je,Qr,bt=R(()=>{\"use strict\";te();oe();Fe=(e,t,r=\"f32\")=>{switch(e.activation){case\"Relu\":return`value = max(value, ${t}(0.0));`;case\"Sigmoid\":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case\"Clip\":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case\"HardSigmoid\":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case\"LeakyRelu\":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case\"Tanh\":return`let e2x = exp(-2.0 * abs(value));\n value = sign(value) * (1.0 - e2x) / (1.0 + e2x);\n `;case\"\":return\"\";default:throw new Error(`Unsupported activation ${e.activation}`)}},qe=(e,t)=>{e.activation===\"Clip\"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation===\"HardSigmoid\"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation===\"LeakyRelu\"&&t.push({type:1,data:e.alpha})},je=(e,t)=>{e.activation===\"Clip\"?t.push({name:\"clip_max\",type:\"f32\"},{name:\"clip_min\",type:\"f32\"}):e.activation===\"HardSigmoid\"?t.push({name:\"alpha\",type:\"f32\"},{name:\"beta\",type:\"f32\"}):e.activation===\"LeakyRelu\"&&t.push({name:\"alpha\",type:\"f32\"})},Qr=e=>{let t=e?.activation||\"\";if(t===\"HardSigmoid\"){let[r,n]=e?.activation_params||[.2,.5];return{activation:t,alpha:r,beta:n}}else if(t===\"Clip\"){let[r,n]=e?.activation_params||[Xa,Ja];return{activation:t,clipMax:n,clipMin:r}}else if(t===\"LeakyRelu\"){let[r]=e?.activation_params||[.01];return{activation:t,alpha:r}}return{activation:t}}});var Pe,Bu,Xr=R(()=>{\"use strict\";Pe=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},Bu=e=>`\n ${e?\"value = value + getBiasByOutputCoords(coords);\":\"\"}\n `});var Du,Mu=R(()=>{\"use strict\";Du=e=>`\nfn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 {\n return dot(coords, vec4(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n}\nfn getOutputIndexFromCoords(coords : vec4) -> i32 {\n return dot(coords, vec4(\n i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));\n}\n`});var er,Jr,en=R(()=>{\"use strict\";te();oe();ae();bt();er=(e,t,r,n,o)=>{let i=n-r;return`\n ${Array.from({length:r}).map((a,l)=>`\n if (${F(t.shape,l,t.rank)} != 1) {\n ${t.indicesSet(e,l,F(o,l+i,n))}\n } else {\n ${t.indicesSet(e,l,0)}\n }`).join(\"\")}\n`},Jr=(e,t,r,n,o=!1,i)=>{let a=e[0].dims,l=e[1].dims,d=a[a.length-2],p=l[l.length-1],m=a[a.length-1],u=me(p),h=me(m),_=me(d),y=k.size(r)/u/_,g=e.length>2,x=n?n.slice(0,-2):r.slice(0,-2),v=[k.size(x),d,p],S=[{type:12,data:y},{type:12,data:d},{type:12,data:p},{type:12,data:m}];qe(t,S),S.push(...N(x,a,l)),g&&S.push(...N(e[2].dims)),S.push(...N(v));let T=C=>{let A=Fr(\"batch_dims\",e[0].dataType,x.length),P=E(\"a\",e[0].dataType,a.length,h),O=E(\"b\",e[1].dataType,l.length,u),U=M(\"output\",e[0].dataType,v.length,u),G=ye(U.type.tensor),q=Fe(t,U.type.value,G),K=[P,O],W=\"\";if(g){let X=o?u:1;K.push(E(\"bias\",e[2].dataType,e[2].dims.length,X)),W=`${o?`value += bias[col / ${X}];`:`value += ${U.type.value}(bias[row + i]);`}`}let Y=[{name:\"output_size\",type:\"u32\"},{name:\"M\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"K\",type:\"u32\"}];je(t,Y);let se=()=>{let X=`var a_data: ${P.type.value};`;for(let re=0;re;\n for (var k: u32 = 0u; k < uniforms.K; k = k + ${h}) {\n ${se()}\n }\n for (var i = 0u; i < ${_}u; i++) {\n var value = values[i];\n ${W}\n ${q}\n let cur_indices = ${U.type.indices}(batch, row + i, col);\n let offset = ${U.indicesToOffset(\"cur_indices\")};\n ${U.setByOffset(`offset / ${u}`,\"value\")};\n }\n }\n `};return{name:\"MatMulNaive\",shaderCache:{hint:`${t.activation};${u};${h};${_};${o}`,inputDependencies:g?[\"rank\",\"rank\",\"rank\"]:[\"rank\",\"rank\"]},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:S}),getShaderSource:T}}});var ef,tf,go,Ru,rf,bo,nf,tr,tn=R(()=>{\"use strict\";te();oe();ae();bt();en();Xr();ef=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart / innerElementSize + inputCol${t?\", batchIndices\":\"\"});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRow + innerRow,\n kStart / innerElementSize + inputCol${t?\", batchIndices\":\"\"});\n `,tf=(e,t)=>e?`\n let ACached0 = mm_Asub[k * innerElementSize][localRow];\n let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];\n let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];\n ${t===3?\"\":\"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];\"}\n for (var i = 0; i < rowPerThread; i = i + 1) {\n acc[i] = BCached0 * ACached0[i] + acc[i];\n acc[i] = BCached1 * ACached1[i] + acc[i];\n acc[i] = BCached2 * ACached2[i] + acc[i];\n ${t===3?\"\":\"acc[i] = BCached3 * ACached3[i] + acc[i];\"}\n }`:`\n for (var i = 0; i < rowPerThread; i = i + 1) {\n let ACached = mm_Asub[tileRow + i][k];\n acc[i] = BCached0 * ACached.x + acc[i];\n acc[i] = BCached1 * ACached.y + acc[i];\n acc[i] = BCached2 * ACached.z + acc[i];\n ${t===3?\"\":\"acc[i] = BCached3 * ACached.w + acc[i];\"}\n }`,go=(e,t,r=\"f32\",n,o=!1,i=32,a=!1,l=32)=>{let d=t[1]*e[1],p=t[0]*e[0],m=o?d:i,u=o?i:d,h=m/t[0],_=i/t[1];if(!((o&&h===4&&e[1]===4||!o&&(h===3||h===4))&&m%t[0]===0&&i%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${h} and workPerThread[1] ${e[1]} must be 4.\n Otherwise, innerElementSize ${h} must be 3 or 4.\n tileAWidth ${m} must be divisible by workgroupSize[0]${t[0]}. tileInner ${i} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`\nvar mm_Asub: array, ${m/h}>, ${u}>;\nvar mm_Bsub: array, ${p/e[0]}>, ${i}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${h};\nconst tileInner = ${i};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let localRow = i32(localId.y);\n let tileRow = localRow * rowPerThread;\n let tileCol = i32(localId.x);\n\n let globalRow =i32(globalId.y) * rowPerThread;\n let globalCol = i32(globalId.x);\n let batch = ${a?\"0\":\"i32(globalId.z)\"};\n ${n?`let batchIndices = ${n.offsetToIndices(\"u32(batch)\")};`:\"\"}\n let globalRowStart = i32(workgroupId.y) * ${d};\n\n let num_tiles = ${a?`${Math.ceil(l/i)}`:\"(uniforms.dim_inner - 1) / tileInner + 1\"};\n var kStart = ${a?`i32(globalId.z) * ${l}`:\"0\"};\n\n var acc: array, rowPerThread>;\n\n // Loop over shared dimension.\n let tileRowB = localRow * ${_};\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileCol;\n ${ef(o,n)}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?\", batchIndices\":\"\"});\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {\n let BCached0 = mm_Bsub[k * innerElementSize][tileCol];\n let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];\n let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];\n ${h===3?\"\":\"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];\"}\n\n ${tf(o,h)}\n }\n\n workgroupBarrier();\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);\n }\n}`},Ru=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart + inputCol${t?\", batchIndices\":\"\"});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRowStart + inputRow,\n kStart + inputCol${t?\", batchIndices\":\"\"});\n `,rf=e=>e?\"let ACached = mm_Asub[k][tileRow + innerRow];\":\"let ACached = mm_Asub[tileRow + innerRow][k];\",bo=(e,t,r=\"f32\",n,o=!1,i=32,a=!1,l=32,d=!1)=>{let p=e[1]*t[1],m=e[0]*t[0],u=o?p:i,h=o?i:p;if(!(h%t[1]===0&&u%t[0]===0&&i%t[1]===0))throw new Error(`tileAHight ${h} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${u} must be divisible by workgroupSize[0]${t[0]}, tileInner ${i} must be divisible by workgroupSize[1]${t[1]}`);let _=h/t[1],y=u/t[0],g=i/t[1],x=d?`\n let localRow = i32(localId.y);\n let localCol = i32(localId.x);\n let globalRowStart = i32(workgroupId.y) * ${p};\n let globalColStart = i32(workgroupId.x) * ${m};\n\n // Loop over shared dimension.\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var inputRow = localRow; inputRow < ${h}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${t[0]}) {\n ${Ru(o,n)}\n }\n }\n // Load one tile of B into local memory.\n for (var inputRow = localRow; inputRow < ${i}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${m}; inputCol = inputCol + ${t[0]}) {\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalColStart + inputCol${n?\", batchIndices\":\"\"});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] +\n ACached * BCached[innerCol];\n }\n }\n }\n workgroupBarrier();\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let gRow = globalRowStart + localRow + innerRow * ${t[1]};\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let gCol = globalColStart + localCol + innerCol * ${t[0]};\n mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);\n }\n }\n `:`\nlet tileRow = i32(localId.y) * rowPerThread;\nlet tileCol = i32(localId.x) * colPerThread;\n\nlet globalRow = i32(globalId.y) * rowPerThread;\nlet globalCol = i32(globalId.x) * colPerThread;\nlet globalRowStart = i32(workgroupId.y) * ${p};\n\nlet tileRowA = i32(localId.y) * ${_};\nlet tileColA = i32(localId.x) * ${y};\nlet tileRowB = i32(localId.y) * ${g};\n// Loop over shared dimension.\nfor (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${y}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${Ru(o,n)}\n }\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${g}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol + innerCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalCol + innerCol${n?\", batchIndices\":\"\"});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][tileCol + inner];\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n ${rf(o)}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];\n }\n }\n }\n\n workgroupBarrier();\n}\n\nfor (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n mm_write(batch, globalRow + innerRow, globalCol + innerCol,\n acc[innerRow][innerCol]);\n }\n}\n`;return`\n var mm_Asub : array, ${h}>;\n var mm_Bsub : array, ${i}>;\n const rowPerThread = ${e[1]};\n const colPerThread = ${e[0]};\n const tileInner = ${i};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let batch = ${a?\"0\":\"i32(globalId.z)\"};\n ${n?`let batchIndices = ${n.offsetToIndices(\"u32(batch)\")};`:\"\"}\n let num_tiles = ${a?`${Math.ceil(l/i)}`:\"(uniforms.dim_inner - 1) / tileInner + 1\"};\n var kStart = ${a?`i32(globalId.z) * ${l}`:\"0\"};\n\n var acc : array, rowPerThread>;\n ${x}\n }\n`},nf=(e,t,r,n,o=!1)=>{let[i,a,l,d]=n,p=ye(n[0].type.tensor);return`\n fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${Pe(e,p)} {\n var value = ${Pe(e,p)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)\n {\n var aIndices: ${a.type.indices};\n ${er(\"aIndices\",a,a.rank-2,i.rank,\"batchIndices\")}\n ${a.indicesSet(\"aIndices\",a.rank-2,\"u32(row)\")}\n ${a.indicesSet(\"aIndices\",a.rank-1,\"u32(colIn)\")}\n value = ${a.getByIndices(\"aIndices\")};\n }\n return value;\n }\n\n fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${Pe(e,p)} {\n var value = ${Pe(e,p)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)\n {\n var bIndices: ${l.type.indices};\n ${er(\"bIndices\",l,l.rank-2,i.rank,\"batchIndices\")}\n ${l.indicesSet(\"bIndices\",l.rank-2,\"u32(row)\")}\n ${l.indicesSet(\"bIndices\",l.rank-1,\"u32(colIn)\")}\n value = ${l.getByIndices(\"bIndices\")};\n }\n return value;\n }\n\n fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Pe(e,p)}) {\n let col = colIn * ${e};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueIn;\n let coords = vec3(batch, row, colIn);\n ${t?`value = value + ${o?\"bias[colIn]\":`${Pe(e,p)}(bias[row])`};`:\"\"}\n ${r}\n ${d.setByIndices(\"vec3(coords)\",\"value\")}\n }\n }\n `},tr=(e,t,r,n,o=!1,i)=>{let a=e[0].dims,l=e[1].dims,d=a.slice(0,-2),p=l.slice(0,-2),m=n?n.slice(0,-2):r.slice(0,-2),u=k.size(m),h=a[a.length-2],_=a[a.length-1],y=l[l.length-1],g=_%4===0&&y%4===0,x=h<=8?[4,1,1]:[4,4,1],$=[8,8,1],v=[Math.ceil(y/$[0]/x[0]),Math.ceil(h/$[1]/x[1]),Math.ceil(u/$[2]/x[2])],S=g?4:1,T=[...d,h,_/S],C=T.length,A=[...p,_,y/S],P=A.length,O=[u,h,y/S],U=[{type:6,data:h},{type:6,data:y},{type:6,data:_}];qe(t,U),U.push(...N(m,T,A));let G=[\"rank\",\"rank\"],q=e.length>2;q&&(U.push(...N(e[2].dims)),G.push(\"rank\")),U.push(...N(O));let K=W=>{let Y=m.length,se=Fr(\"batchDims\",e[0].dataType,Y,1),X=ye(e[0].dataType),re=E(\"a\",e[0].dataType,C,S),ee=E(\"b\",e[1].dataType,P,S),ne=M(\"result\",e[0].dataType,O.length,S),ve=[re,ee];if(q){let j=o?S:1;ve.push(E(\"bias\",e[2].dataType,e[2].dims.length,j))}let Be=[{name:\"dim_a_outer\",type:\"i32\"},{name:\"dim_b_outer\",type:\"i32\"},{name:\"dim_inner\",type:\"i32\"}];je(t,Be);let $e=ye(ne.type.tensor),de=Fe(t,ne.type.value,$e),V=nf(S,q,de,[se,re,ee,ne],o);return`\n ${W.registerUniforms(Be).registerInternalVariables(se).declareVariables(...ve,ne)}\n ${V}\n ${g?go(x,$,X,se):bo(x,$,X,se)}\n `};return{name:\"MatMul\",shaderCache:{hint:`${x};${t.activation};${g};${o}`,inputDependencies:G},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:v[0],y:v[1],z:v[2]},programUniforms:U}),getShaderSource:K}}});var of,Uu,Nu=R(()=>{\"use strict\";te();Je();ae();bt();Xr();Mu();tn();of=(e,t,r,n,o=!1,i,a=4,l=4,d=4,p=\"f32\")=>{let m=G=>{switch(G){case 1:return\"resData = x[xIndex];\";case 3:return`resData = vec3<${p}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return\"resData = x[xIndex / 4];\";default:throw new Error(`innerElementSize ${G} is not supported.`)}},u=G=>{switch(G){case 1:return\"return w[row * i32(uniforms.w_shape[3]) + colIn];\";case 4:return\"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];\";default:throw new Error(`innerElementSize ${G} is not supported.`)}},h=e?`\n let coord = vec4(batch, xRow, xCol, xCh);\n `:`\n let coord = vec4(batch, xCh, xRow, xCol);\n `,_=e?`\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n `:`\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n `,y=e?\"i32(uniforms.x_shape[1])\":\"i32(uniforms.x_shape[2])\",g=e?\"i32(uniforms.x_shape[2])\":\"i32(uniforms.x_shape[3])\",x=e?\"row\":\"col\",$=e?\"col\":\"row\",v=`\n let inChannels = i32(uniforms.w_shape[2]);\n let outWidth = ${e?\"i32(uniforms.result_shape[2])\":\"i32(uniforms.result_shape[3])\"};\n let outRow = ${x} / outWidth;\n let outCol = ${x} % outWidth;\n\n let WRow = ${$} / (i32(uniforms.w_shape[1]) * inChannels);\n let WCol = ${$} / inChannels % i32(uniforms.w_shape[1]);\n let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];\n let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];\n let xCh = ${$} % inChannels;\n var resData = ${Pe(a,p)}(0.0);\n // The bounds checking is always needed since we use it to pad zero for\n // the 'same' padding type.\n if (xRow >= 0 && xRow < ${y} && xCol >= 0 && xCol < ${g}) {\n ${h}\n let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape));\n ${m(a)}\n }\n return resData;`,S=e?t&&n?`\n let col = colIn * ${a};\n ${v}`:`\n let col = colIn * ${a};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${v}\n }\n return ${Pe(a,p)}(0.0);`:n&&r?`\n let col = colIn * ${a};\n ${v}`:`\n let col = colIn * ${a};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${v}\n }\n return ${Pe(a,p)}(0.0);`,T=`${u(l)}`,C=Pe(d,p),A=e?Pe(a,p):Pe(l,p),P=e?Pe(l,p):Pe(a,p),O=Fe(i,C,p);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${A} {\n ${e?S:T}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${P} {\n ${e?T:S}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${C}) {\n let col = colIn * ${d};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)\n {\n var value = valueIn;\n let outWidth = ${e?\"i32(uniforms.result_shape[2])\":\"i32(uniforms.result_shape[3])\"};\n ${_}\n ${Bu(o)}\n ${O}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`},Uu=(e,t,r,n,o,i,a,l,d)=>{let p=t.format===\"NHWC\",m=p?e[0].dims[3]:e[0].dims[1],u=r[0],h=p?r[2]:r[3],_=p?r[1]:r[2],y=p?r[3]:r[1],g=p&&(m%4===0||m%3===0)&&y%4===0,x=p?y:h*_,$=p?h*_:y,v=[8,8,1],S=n<=8?[4,1,1]:[4,4,1],T=[Math.ceil(x/v[0]/S[0]),Math.ceil($/v[1]/S[1]),Math.ceil(u/v[2]/S[2])];ue(\"verbose\",()=>`[conv2d_mm_webgpu] dispatch = ${T}`);let C=g?p&&m%4!==0?3:4:1,A=v[1]*S[1],P=v[0]*S[0],O=Math.max(v[0]*C,v[1]),U=n%A===0,G=o%P===0,q=i%O===0,K=g?[C,4,4]:[1,1,1],W=[{type:6,data:n},{type:6,data:o},{type:6,data:i},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];qe(t,W),W.push(...N(e[0].dims,e[1].dims));let Y=[\"rank\",\"rank\"];a&&(W.push(...N(e[2].dims)),Y.push(\"rank\")),W.push(...N(r));let se=X=>{let re=[{name:\"dim_a_outer\",type:\"i32\"},{name:\"dim_b_outer\",type:\"i32\"},{name:\"dim_inner\",type:\"i32\"},{name:\"pad\",type:\"i32\",length:2},{name:\"stride\",type:\"i32\",length:2},{name:\"dilation\",type:\"i32\",length:2}];je(t,re);let ee=g?4:1,ne=ye(e[0].dataType),ve=`\n fn setOutputAtIndex(flatIndex : i32, value : ${g?`vec4<${ne}>`:ne}) {\n result[flatIndex] = ${g?`vec4<${ne}>`:ne}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${g?`vec4<${ne}>`:ne}) {\n let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${g?\"/ 4\":\"\"}, value);\n }`,Be=E(\"x\",e[0].dataType,e[0].dims.length,C===3?1:C),$e=E(\"w\",e[1].dataType,e[1].dims.length,ee),de=[Be,$e],V=M(\"result\",e[0].dataType,r.length,ee);if(a){let j=E(\"bias\",e[2].dataType,e[2].dims.length,ee);de.push(j),ve+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${g?`vec4<${ne}>`:ne} {\n return bias[coords.${p?\"w\":\"y\"}${g?\"/ 4\":\"\"}];\n }`}return`\n ${Du(\"uniforms.result_strides\")}\n //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4,\n // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2,\n // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };\n ${X.registerUniforms(re).declareVariables(...de,V)}\n ${ve}\n ${of(p,U,G,q,a,t,K[0],K[1],K[2],ne)}\n ${g?go(S,v,ne,void 0,!p,O):bo(S,v,ne,void 0,!p,O,!1,void 0,l)}`};return{name:\"Conv2DMatMul\",shaderCache:{hint:`${t.cacheKey};${C};${g};${U};${G};${q};${A};${P};${O}`,inputDependencies:Y},getRunData:()=>({outputs:[{dims:d?d(r):r,dataType:e[0].dataType}],dispatchGroup:{x:T[0],y:T[1],z:T[2]},programUniforms:W}),getShaderSource:se}}});var af,Vu,rn,sf,Wu,uf,Lu,Gu,Hu=R(()=>{\"use strict\";te();Je();oe();ae();bt();Xr();af=e=>{let t=1;for(let r=0;rtypeof e==\"number\"?[e,e,e]:e,rn=(e,t)=>t<=1?e:e+(e-1)*(t-1),sf=(e,t,r,n=1)=>{let o=rn(t,n);return Math.floor((e[0]*(r-1)-r+o)/2)},Wu=(e,t,r,n,o)=>{o==null&&(o=sf(e,t[0],n[0]));let i=[0,0,0,r];for(let a=0;a<3;a++)e[a]+2*o>=t[a]&&(i[a]=Math.trunc((e[a]-t[a]+2*o)/n[a]+1));return i},uf=(e,t,r,n,o,i,a,l,d,p)=>{let m,u,h,_;if(e===\"VALID\"&&(e=0),typeof e==\"number\"){m={top:e,bottom:e,left:e,right:e,front:e,back:e};let y=Wu([t,r,n,1],[l,d,p],1,[o,i,a],e);u=y[0],h=y[1],_=y[2]}else if(Array.isArray(e)){if(!e.every((g,x,$)=>g===$[0]))throw Error(`Unsupported padding parameter: ${e}`);m={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let y=Wu([t,r,n,1],[l,d,p],1,[o,i,a],e[0]);u=y[0],h=y[1],_=y[2]}else if(e===\"SAME_UPPER\"){u=Math.ceil(t/o),h=Math.ceil(r/i),_=Math.ceil(n/a);let y=(u-1)*o+l-t,g=(h-1)*i+d-r,x=(_-1)*a+p-n,$=Math.floor(y/2),v=y-$,S=Math.floor(g/2),T=g-S,C=Math.floor(x/2),A=x-C;m={top:S,bottom:T,left:C,right:A,front:$,back:v}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:m,outDepth:u,outHeight:h,outWidth:_}},Lu=(e,t,r,n,o,i=!1,a=\"channelsLast\")=>{let l,d,p,m,u;if(a===\"channelsLast\")[l,d,p,m,u]=e;else if(a===\"channelsFirst\")[l,u,d,p,m]=e;else throw new Error(`Unknown dataFormat ${a}`);let[h,,_,y,g]=t,[x,$,v]=Vu(r),[S,T,C]=Vu(n),A=rn(_,S),P=rn(y,T),O=rn(g,C),{padInfo:U,outDepth:G,outHeight:q,outWidth:K}=uf(o,d,p,m,x,$,v,A,P,O),W=i?h*u:h,Y=[0,0,0,0,0];return a===\"channelsFirst\"?Y=[l,W,G,q,K]:a===\"channelsLast\"&&(Y=[l,G,q,K,W]),{batchSize:l,dataFormat:a,inDepth:d,inHeight:p,inWidth:m,inChannels:u,outDepth:G,outHeight:q,outWidth:K,outChannels:W,padInfo:U,strideDepth:x,strideHeight:$,strideWidth:v,filterDepth:_,filterHeight:y,filterWidth:g,effectiveFilterDepth:A,effectiveFilterHeight:P,effectiveFilterWidth:O,dilationDepth:S,dilationHeight:T,dilationWidth:C,inShape:e,outShape:Y,filterShape:t}},Gu=(e,t,r,n,o,i)=>{let a=i===\"channelsLast\",l=a?e[0].dims[3]:e[0].dims[1],d=!1,p=[64,1,1],m={x:r.map((v,S)=>S)},u=[Math.ceil(af(m.x.map(v=>r[v]))/p[0]),1,1];ue(\"verbose\",()=>`[conv3d_naive_webgpu] dispatch = ${u}`);let h=d?a&&l%4!==0?3:4:1,_=k.size(r),y=[{type:12,data:_},{type:12,data:n},{type:12,data:o},{type:12,data:t.strides},{type:12,data:t.dilations}];qe(t,y),y.push(...N(e[0].dims,e[1].dims));let g=[\"rank\",\"rank\"],x=e.length===3;x&&(y.push(...N(e[2].dims)),g.push(\"rank\")),y.push(...N(r));let $=v=>{let S=[{name:\"output_size\",type:\"u32\"},{name:\"filter_dims\",type:\"u32\",length:n.length},{name:\"pads\",type:\"u32\",length:o.length},{name:\"strides\",type:\"u32\",length:t.strides.length},{name:\"dilations\",type:\"u32\",length:t.dilations.length}];je(t,S);let T=d?4:1,C=ye(e[0].dataType),A=E(\"x\",e[0].dataType,e[0].dims.length,h===3?1:h),P=E(\"W\",e[1].dataType,e[1].dims.length,T),O=[A,P],U=M(\"result\",e[0].dataType,r.length,T),G=\"\";if(x){let W=E(\"bias\",e[2].dataType,e[2].dims.length,T);O.push(W),G+=`\n fn getBiasByOutputCoords(coords : array) -> ${d?`vec4<${C}>`:C} {\n return bias[${a?F(\"coords\",4,5):F(\"coords\",1,5)}${d?\"/ 4\":\"\"}];\n }`}let q=Pe(h,C),K=Fe(t,q,C);return`\n ${G}\n fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {\n let aIndices = array(d0, d1, d2, d3, d4);\n return ${A.getByIndices(\"aIndices\")};\n }\n fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {\n let aIndices = array(d0, d1, d2, d3, d4);\n return ${P.getByIndices(\"aIndices\")};\n }\n ${v.registerUniforms(S).declareVariables(...O,U)}\n ${v.mainStart()}\n ${v.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let coords = ${U.offsetToIndices(\"global_idx\")};\n let batch = ${F(\"coords\",0,A.rank)};\n let d2 = ${a?F(\"coords\",A.rank-1,A.rank):F(\"coords\",1,A.rank)};\n let xFRCCorner = vec3(${a?F(\"coords\",1,A.rank):F(\"coords\",2,A.rank)},\n ${a?F(\"coords\",2,A.rank):F(\"coords\",3,A.rank)},\n ${a?F(\"coords\",3,A.rank):F(\"coords\",4,A.rank)}) * uniforms.strides - uniforms.pads;\n let xFCorner = xFRCCorner.x;\n let xRCorner = xFRCCorner.y;\n let xCCorner = xFRCCorner.z;\n let xShapeY = ${a?F(\"uniforms.x_shape\",1,A.rank):F(\"uniforms.x_shape\",2,A.rank)};\n let xShapeZ = ${a?F(\"uniforms.x_shape\",2,A.rank):F(\"uniforms.x_shape\",3,A.rank)};\n let xShapeW = ${a?F(\"uniforms.x_shape\",3,A.rank):F(\"uniforms.x_shape\",4,A.rank)};\n let xShapeU = ${a?F(\"uniforms.x_shape\",4,A.rank):F(\"uniforms.x_shape\",1,A.rank)};\n let inputDepthNearestVec4 = (xShapeU / 4) * 4;\n let inputDepthVec4Remainder = xShapeU % 4;\n\n var value = 0.0;\n for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) {\n let xF = xFCorner + wF * uniforms.dilations[0];\n if (xF < 0 || xF >= xShapeY) {\n continue;\n }\n\n for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) {\n let xR = xRCorner + wR * uniforms.dilations[1];\n if (xR < 0 || xR >= xShapeZ) {\n continue;\n }\n\n for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) {\n let xC = xCCorner + wC * uniforms.dilations[2];\n if (xC < 0 || xC >= xShapeW) {\n continue;\n }\n\n for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) {\n ${a?`let 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 `:`let xValues = vec4(\n getX(batch, d1, xF, xR, xC),\n getX(batch, d1 + 1, xF, xR, xC),\n getX(batch, d1 + 2, xF, xR, xC),\n getX(batch, d1 + 3, xF, xR, xC));\n `}\n let wValues = vec4(\n getW(d2, d1, wF, wR, wC),\n getW(d2, d1 + 1, wF, wR, wC),\n getW(d2, d1 + 2, wF, wR, wC),\n getW(d2, d1 + 3, wF, wR, wC));\n value += dot(xValues, wValues);\n }\n if (inputDepthVec4Remainder == 1) {\n ${a?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4)\n * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC)\n * getW(d2, inputDepthNearestVec4, wF, wR, wC);`}\n } else if (inputDepthVec4Remainder == 2) {\n ${a?`let xValues = vec2(\n getX(batch, xF, xR, xC, inputDepthNearestVec4),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1));\n `:`let xValues = vec2(\n getX(batch, inputDepthNearestVec4, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC));\n `}\n let wValues = vec2(\n getW(d2, inputDepthNearestVec4, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC));\n value += dot(xValues, wValues);\n } else if (inputDepthVec4Remainder == 3) {\n ${a?`let xValues = vec3(\n getX(batch, xF, xR, xC, inputDepthNearestVec4),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2));\n `:`let xValues = vec3(\n getX(batch, inputDepthNearestVec4, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC));\n `}\n let wValues = vec3(\n getW(d2, inputDepthNearestVec4, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC));\n value += dot(xValues, wValues);\n }\n }\n }\n }\n ${x?\"value = value + getBiasByOutputCoords(coords)\":\"\"};\n ${K}\n result[global_idx] = f32(value);\n }`};return{name:\"Conv3DNaive\",shaderCache:{hint:`${t.cacheKey};${a};${h};${x}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:u[0],y:u[1],z:u[2]},programUniforms:y}),getShaderSource:$}}});var Fu,qu,ju=R(()=>{\"use strict\";te();oe();ae();bt();Fu=(e,t,r,n)=>{let o=e.length>2,i=o?\"value += b[output_channel];\":\"\",a=e[0].dims,l=e[1].dims,d=t.format===\"NHWC\",p=d?r[3]:r[1],m=p/t.group,u=d&&m>=4?me(p):1,h=k.size(r)/u,_=[{type:12,data:h},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:m}];qe(t,_),_.push(...N(a,[l[0],l[1],l[2],l[3]/u]));let y=o?[\"rank\",\"rank\",\"rank\"]:[\"rank\",\"rank\"];_.push(...N([r[0],r[1],r[2],r[3]/u]));let g=x=>{let $=M(\"output\",e[0].dataType,r.length,u),v=ye($.type.tensor),S=Fe(t,$.type.value,v),T=E(\"x\",e[0].dataType,a.length),C=E(\"w\",e[1].dataType,l.length,u),A=[T,C];o&&A.push(E(\"b\",e[2].dataType,e[2].dims,u));let P=[{name:\"output_size\",type:\"u32\"},{name:\"dilations\",type:\"u32\",length:t.dilations.length},{name:\"strides\",type:\"u32\",length:2},{name:\"pads\",type:\"u32\",length:2},{name:\"output_channels_per_group\",type:\"u32\"}];je(t,P);let O=d?`\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) {\n continue;\n }\n\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) {\n let input_channel = in_channel_offset + wInChannel;\n let xVal = ${T.get(\"batch\",\"xHeight\",\"xWidth\",\"input_channel\")};\n let wVal = ${C.get(\"wHeight\",\"wWidth\",\"wInChannel\",\"output_channel\")};\n value += xVal * wVal;\n }\n }\n }\n `:`\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {\n let input_channel = in_channel_offset + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) {\n continue;\n }\n\n let xVal = ${T.get(\"batch\",\"input_channel\",\"xHeight\",\"xWidth\")};\n let wVal = ${C.get(\"output_channel\",\"wInChannel\",\"wHeight\",\"wWidth\")};\n value += xVal * wVal;\n }\n }\n }\n `;return`\n ${x.registerUniforms(P).declareVariables(...A,$)}\n\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let outputIndices = ${$.offsetToIndices(\"global_idx\")};\n let batch: u32 = outputIndices[0];\n let output_channel: u32 = outputIndices[${d?3:1}];\n let xRCCorner: vec2 = vec2(outputIndices[${d?1:2}], outputIndices[${d?2:3}]) * uniforms.strides - uniforms.pads;\n let group_id: u32 = output_channel * ${u} / uniforms.output_channels_per_group;\n var in_channel_offset = group_id * uniforms.w_shape[${d?2:1}];\n\n var value: ${$.type.value} = ${$.type.value}(0);\n ${O}\n ${i}\n ${S}\n ${$.setByOffset(\"global_idx\",\"value\")}\n }`};return{name:\"GroupedConv\",shaderCache:{hint:`${t.cacheKey}_${u}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:_}),getShaderSource:g}},qu=(e,t,r,n)=>{let o=e.length>2,i=me(r[3]),a=me(r[2]),l=k.size(r)/i/a,d=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/i],p=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/i],m=[r[0],r[1],r[2],r[3]/i],u=[{type:12,data:l},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];qe(t,u),u.push(...N(d,p,m));let h=(a-1)*t.strides[1]+p[1],_=y=>{let g=M(\"output\",e[0].dataType,m.length,i),x=ye(g.type.tensor),$=Fe(t,g.type.value,x),v=E(\"x\",e[0].dataType,d.length,i),S=E(\"w\",e[1].dataType,p.length,i),T=[v,S];o&&T.push(E(\"b\",e[2].dataType,e[2].dims,i));let C=o?\"value += b[output_channel];\":\"\",A=[{name:\"output_size\",type:\"u32\"},{name:\"strides\",type:\"i32\",length:2},{name:\"pads\",type:\"i32\",length:2}];return je(t,A),`\n ${y.registerUniforms(A).declareVariables(...T,g)}\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let width0 = uniforms.output_shape[3];\n let output_channel = global_idx % width0;\n var index1 = global_idx / width0;\n let width1 = uniforms.output_shape[2] / ${a}u;\n let col = (index1 % width1) * ${a}u;\n index1 = index1 / width1;\n let row = index1 % uniforms.output_shape[1];\n let batch = index1 / uniforms.output_shape[1];\n\n let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads;\n\n var x_vals: array<${v.type.value}, ${h}>;\n var values: array<${g.type.value}, ${a}>;\n let input_channel = output_channel;\n // Use constant instead of uniform can give better performance for w's height/width.\n for (var w_height: u32 = 0u; w_height < ${p[0]}; w_height++) {\n let x_height = x_corner.x + i32(w_height);\n if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {\n for (var i = 0; i < ${h}; i++) {\n let x_width = x_corner.y + i;\n if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {\n x_vals[i] = ${v.get(\"batch\",\"u32(x_height)\",\"u32(x_width)\",\"input_channel\")};\n } else {\n x_vals[i] = ${v.type.value}(0);\n }\n }\n for (var w_width: u32 = 0u; w_width < ${p[1]}; w_width++) {\n let w_val = ${S.get(\"w_height\",\"w_width\",\"0\",\"output_channel\")};\n for (var i = 0u; i < ${a}u; i++) {\n values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);\n }\n }\n }\n }\n\n for (var i = 0u; i < ${a}u; i++) {\n var value = values[i];\n ${C}\n ${$}\n ${g.set(\"batch\",\"row\",\"col + i\",\"output_channel\",\"value\")};\n }\n }`};return{name:\"GroupedConv-Vectorize\",shaderCache:{hint:`${t.cacheKey};${i};${a};${h};${p[0]};${p[1]}`,inputDependencies:o?[\"rank\",\"rank\",\"type\"]:[\"rank\",\"rank\"]},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:_}}});var lf,yo,df,_o,wo,Ku,cf,pf,vo,Yu=R(()=>{\"use strict\";oe();Nu();Hu();tn();ju();bt();en();ut();lf=(e,t,r,n,o,i)=>{let a=e[0],l=e.slice(i?1:2,i?3:4),d=l.length,p=t[0],u=t.slice(2).map((y,g)=>y+(y-1)*(r[g]-1)),_=l.map((y,g)=>y+n[g]+n[g+d]).map((y,g)=>Math.floor((y-u[g]+o[g])/o[g]));return _.splice(0,0,a),_.splice(i?3:1,0,p),_},yo=[2,3,1,0],df=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error(\"Conv requires 2 or 3 inputs\");if(e[0].dims.length>5)throw new Error(\"greater than 5D is not supported\");if(e[0].dims.length!==e[1].dims.length)throw new Error(\"filter does not have same dimension as input\");let r=e[0].dims[t.format===\"NHWC\"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(r!==n)throw new Error(\"FILTER_IN_CHANNEL should be equal to DATA_CHANNEL\");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error(\"invalid bias\");let o=e[0].dims.length-2;if(t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error(\"invalid kernel shape\")},_o=(e,t)=>{let r=e.kernelShape.slice();r.length{let t=Qr(e),r=e.format,n=[\"NOTSET\",\"VALID\",\"SAME_UPPER\",\"SAME_LOWER\"][e.auto_pad],o=e.dilations,i=e.group,a=e.kernel_shape,l=e.pads,d=e.strides,p=e.w_is_const();return{autoPad:n,format:r,dilations:o,group:i,kernelShape:a,pads:l,strides:d,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},Ku=(e,t,r,n)=>{let o=r.format===\"NHWC\",i=lf(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,o);if(r.group!==1){let A=[t[0]];if(o){let O=e.kernelCustomData.wT??e.compute(Ee(t[1],yo),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=O),A.push(O)}else A.push(t[1]);t.length===3&&A.push(t[2]),!e.adapterInfo.isArchitecture(\"ampere\")&&o&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(qu(A,r,i,n),{inputs:A}):e.compute(Fu(A,r,i,n),{inputs:A});return}let a=t.length===3,l=t[0].dims[o?1:2],d=t[0].dims[o?2:3],p=t[0].dims[o?3:1],m=t[1].dims[2],u=t[1].dims[3],h=i[o?1:2],_=i[o?2:3],y=i[o?3:1],g=o&&m===l&&u===d&&r.pads[0]===0&&r.pads[1]===0;if(g||m===1&&u===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let A=i[0],P,O,U,G=[];if(o){let W=e.kernelCustomData.wT??e.compute(Ee(t[1],yo),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=W),g){let Y=l*d*p;P=t[0].reshape([1,A,Y]),O=W.reshape([1,Y,y]),U=[1,A,y]}else P=t[0].reshape([A,l*d,p]),O=W.reshape([1,p,y]),U=[A,h*_,y];G.push(P),G.push(O)}else P=t[0].reshape([A,p,l*d]),O=t[1].reshape([1,y,p]),U=[A,y,h*_],G.push(O),G.push(P);a&&G.push(t[2]);let q=U[2],K=G[0].dims[G[0].dims.length-1];q<8&&K<8?e.compute(Jr(G,r,i,U,o,n),{inputs:G}):e.compute(tr(G,r,i,U,o,n),{inputs:G});return}let x=!0,$=e.kernelCustomData.wT??e.compute(Ee(t[1],yo),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=$);let v=[t[0],$];a&&v.push(t[2]);let S=o?h*_:y,T=o?y:h*_,C=m*u*p;e.compute(Uu(v,r,i,S,T,C,a,x,n),{inputs:v})},cf=(e,t)=>{let r=t.format===\"NHWC\",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=[0,t.pads[0],0,t.pads[1]],i=[1].concat(t.strides),a=[1].concat(t.dilations),l=[1].concat(t.kernelShape),d=_o({...t,pads:o,strides:i,dilations:a,kernelShape:l},n);Ku(e,n,d,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},pf=(e,t,r)=>{let n=r.format===\"NHWC\"?\"channelsLast\":\"channelsFirst\",o=_o(r,t),i=r.autoPad===\"NOTSET\"?r.pads:r.autoPad,a=Lu(t[0].dims,t[1].dims,r.strides,r.dilations,i,!1,n);e.compute(Gu(t,o,a.outShape,[a.filterDepth,a.filterHeight,a.filterWidth],[a.padInfo.front,a.padInfo.top,a.padInfo.left],n))},vo=(e,t)=>{if(df(e.inputs,t),e.inputs[0].dims.length===3)cf(e,t);else if(e.inputs[0].dims.length===5)pf(e,e.inputs,t);else{let r=_o(t,e.inputs);Ku(e,e.inputs,r)}}});var Zu,Qu=R(()=>{\"use strict\";te();Je();oe();ae();Zu=(e,t,r)=>{let n=e.length>2,o=t.outputShape,i=t.format===\"NHWC\",a=t.group,l=e[1].dims,d=l[2]/a,p=l[3],m=i?me(p):1,u=k.size(o)/m,h=[Math.ceil(u/64),1,1];ue(\"verbose\",()=>`[conv2d_backprop_webgpu] dispatch = ${h}`);let _=[\"rank\",\"rank\"],y=[t.strides[0],t.strides[1]],g=[t.kernelShape[i?1:2],t.kernelShape[i?2:3]],x=[t.dilations[0],t.dilations[1]],$=[g[0]+(t.dilations[0]<=1?0:(t.kernelShape[i?1:2]-1)*(t.dilations[0]-1)),g[1]+(t.dilations[1]<=1?0:(t.kernelShape[i?2:3]-1)*(t.dilations[1]-1))],v=[$[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),$[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],S=[{type:12,data:u},{type:12,data:y},{type:12,data:g},{type:12,data:x},{type:12,data:$},{type:6,data:v},{type:12,data:d},{type:12,data:p},...N(e[0].dims,e[1].dims)];n&&(S.push(...N(e[2].dims)),_.push(\"rank\")),S.push(...N(o));let T=C=>{let A=[{name:\"output_size\",type:\"u32\"},{name:\"strides\",type:\"u32\",length:y.length},{name:\"filter_dims\",type:\"u32\",length:g.length},{name:\"dilations\",type:\"u32\",length:g.length},{name:\"effective_filter_dims\",type:\"u32\",length:$.length},{name:\"pads\",type:\"i32\",length:v.length},{name:\"input_channels_per_group\",type:\"u32\"},{name:\"output_channels_per_group\",type:\"u32\"}],P=ye(e[0].dataType),O=i?1:2,U=i?2:3,G=i?3:1,q=E(\"W\",e[1].dataType,e[1].dims.length,m),K=E(\"Dy\",e[0].dataType,e[0].dims.length),W=[K,q];n&&W.push(E(\"bias\",e[2].dataType,[o[G]].length,m));let Y=M(\"result\",e[0].dataType,o.length,m),se=`\n let outputIndices = ${Y.offsetToIndices(`global_idx * ${m}`)};\n let batch = ${Y.indicesGet(\"outputIndices\",0)};\n let d1 = ${Y.indicesGet(\"outputIndices\",G)};\n let r = ${Y.indicesGet(\"outputIndices\",O)};\n let c = ${Y.indicesGet(\"outputIndices\",U)};\n let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads;\n let dyRCorner = dyCorner.x;\n let dyCCorner = dyCorner.y;\n let groupId = d1 / uniforms.output_channels_per_group;\n let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;\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 var dotProd = ${Y.type.value}(0.0);\n for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {\n if (wR % uniforms.dilations.x != 0) {\n continue;\n }\n let dyR = (${P}(dyRCorner) + ${P}(wR)) / ${P}(uniforms.strides[0]);\n let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;\n if (dyR < 0.0 || dyR >= ${P}(uniforms.Dy_shape[${O}]) || fract(dyR) > 0.0 ||\n wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {\n if (wC % uniforms.dilations.y != 0) {\n continue;\n }\n let dyC = (${P}(dyCCorner) + ${P}(wC)) / ${P}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;\n if (dyC < 0.0 || dyC >= ${P}(uniforms.Dy_shape[${U}]) ||\n fract(dyC) > 0.0 || wCPerm < 0) {\n continue;\n }\n let idyC: u32 = u32(dyC);\n var inputChannel = groupId * uniforms.input_channels_per_group;\n for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) {\n let xValue = ${i?K.get(\"batch\",\"idyR\",\"idyC\",\"inputChannel\"):K.get(\"batch\",\"inputChannel\",\"idyR\",\"idyC\")};\n let w_offset = ${q.indicesToOffset(`${q.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)};\n let wValue = ${q.getByOffset(`w_offset / ${m}`)};\n dotProd = dotProd + xValue * wValue;\n inputChannel = inputChannel + 1;\n }\n }\n }\n let value = dotProd${n?` + bias[d1 / ${m}]`:\"\"};\n ${Y.setByOffset(\"global_idx\",\"value\")};\n `;return`\n ${C.registerUniforms(A).declareVariables(...W,Y)}\n ${C.mainStart()}\n ${C.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")};\n ${se}}`};return{name:\"ConvTranspose2D\",shaderCache:{hint:`${t.cacheKey};${m}`,inputDependencies:_},getRunData:()=>({dispatchGroup:{x:h[0],y:h[1],z:h[2]},outputs:[{dims:r?r(o):o,dataType:e[0].dataType}],programUniforms:S}),getShaderSource:T}}});var mf,ff,hf,Xu,Ju,gf,el,bf,tl,rl=R(()=>{\"use strict\";Qu();bt();ut();mf=(e,t,r,n,o,i)=>(e-1)*t+r+(n-1)*o+1-i,ff=(e,t,r,n,o)=>{let i=Math.floor(e/2);t===\"SAME_UPPER\"?(r[n]=i,r[o]=e-i):t===\"SAME_LOWER\"&&(r[n]=e-i,r[o]=i)},hf=(e,t,r,n,o,i,a,l,d,p)=>{let m=e.length-2,u=p.length===0;d.length{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((u,h)=>u*h,1)===0){r.length=0;for(let u=2;uu+h,0)===0){let u=t[0].dims.length-2;d=new Array(u).fill(1)}let p=e.strides.slice();if(p.reduce((u,h)=>u+h,0)===0){let u=t[0].dims.length-2;p=new Array(u).fill(1)}hf(l,r,d,e.autoPad,e.group,o,p,n,a,i);let m=Object.assign({},e);return Object.assign(m,{kernelShape:r,pads:o,outputPadding:a,outputShape:i,dilations:d,strides:p}),m},Ju=e=>{let t=Qr(e),r=e.format,n=[\"NOTSET\",\"VALID\",\"SAME_UPPER\",\"SAME_LOWER\"][typeof e.autoPad>\"u\"?0:e.autoPad],o=e.dilations,i=e.group,a=e.kernelShape,l=e.pads,d=e.strides,p=e.wIsConst(),m=e.outputPadding,u=e.outputShape;return{autoPad:n,format:r,dilations:o,group:i,kernelShape:a,outputPadding:m,outputShape:u,pads:l,strides:d,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},gf=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error(\"Conv requires 2 or 3 inputs\");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error(\"currently only support 2-dimensional conv\");if(e[0].dims.length!==e[1].dims.length)throw new Error(\"filter does not have same dimension as input\");let r=e[0].dims[t.format===\"NHWC\"?e[0].dims.length-1:1],n=e[1].dims[0];if(r!==n)throw new Error(\"FILTER_IN_CHANNEL should be equal to DATA_CHANNEL\");let o=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error(\"invalid bias\");let i=e[0].dims.length-2;if(t.dilations.reduce((m,u)=>m+u,0)>0&&t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.reduce((m,u)=>m+u,0)>0&&t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.reduce((m,u)=>m+u,0)>0&&t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.outputPadding.length!==i&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${i}D`);if(t.kernelShape.reduce((m,u)=>m+u,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error(\"invalid kernel shape\");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error(\"invalid output shape\")},el=(e,t,r,n)=>{let o=e.kernelCustomData.wT??e.compute(Ee(t[1],[2,3,0,1]),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let i=[t[0],o];t.length===3&&i.push(t[2]),e.compute(Zu(i,r,n),{inputs:i})},bf=(e,t)=>{let r=t.format===\"NHWC\",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=t.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let i=t.dilations;(i.length===0||i[0]===0)&&(i=[1]);let a=t.strides;(a.length===0||a[0]===0)&&(a=[1]);let l=t.pads;l.length===0&&(l=[0,0]),l=[0,l[0],0,l[1]],a=[1].concat(a),i=[1].concat(i),o=[1].concat(o);let d=Xu({...t,pads:l,strides:a,dilations:i,kernelShape:o},n);el(e,n,d,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},tl=(e,t)=>{if(gf(e.inputs,t),e.inputs[0].dims.length===3)bf(e,t);else{let r=Xu(t,e.inputs);el(e,e.inputs,r)}}});var yf,nl,ol,il=R(()=>{\"use strict\";te();oe();Se();ae();yf=(e,t,r,n)=>{let o=k.size(t),i=t.length,a=E(\"input\",e,i),l=M(\"output\",e,i),d=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),p=k.normalizeAxis(d,i),m=u=>{let h=` i32(${a.indicesGet(\"inputIndices\",\"uniforms.axis\")}) `,_=F(\"uniforms.input_shape\",\"uniforms.axis\",i),y=n.reverse?h+(n.exclusive?\" + 1\":\"\"):\"0\",g=n.reverse?_:h+(n.exclusive?\"\":\" + 1\");return`\n ${u.registerUniform(\"outputSize\",\"u32\").registerUniform(\"axis\",\"u32\").declareVariables(a,l)}\n ${u.mainStart()}\n ${u.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n var inputIndices = ${l.offsetToIndices(\"global_idx\")};\n var sum = ${l.type.value}(0);\n let first : i32 = ${y};\n let last : i32 = ${g};\n for (var i : i32 = first; i < last; i++) {\n ${a.indicesSet(\"inputIndices\",\"uniforms.axis\",\"u32(i)\")};\n sum = sum + ${a.getByIndices(\"inputIndices\")};\n }\n ${l.setByOffset(\"global_idx\",\"sum\")};\n }`};return{name:\"CumSum\",shaderCache:{hint:n.cacheKey,inputDependencies:[\"rank\"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:p},...N(t,t)]}),getShaderSource:m}},nl=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,o=e.inputs[1];e.compute(yf(n,r,o,t),{inputs:[0]})},ol=e=>{let t=e.exclusive===1,r=e.reverse===1;return J({exclusive:t,reverse:r})}});var _f,wf,vf,al,sl,ul=R(()=>{\"use strict\";te();oe();Se();ae();_f=e=>{if(!e||e.length!==1)throw new Error(\"DepthToSpace requires 1 input.\");if(e[0].dims.length!==4)throw new Error(\"DepthToSpace requires 4D input.\")},wf=(e,t,r,n)=>{let o=[];o.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} {\n var a: ${r.type.indices};`);for(let i=0;i{let r,n,o,i,a,l,d=t.format===\"NHWC\",p=t.blocksize,m=t.mode===\"DCR\";d?([r,n,o,i]=e.dims,a=m?[r,n,o,p,p,i/p**2]:[r,n,o,i/p**2,p,p],l=m?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,o,i]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],a=m?[r,p,p,i/p**2,n,o]:[r,i/p**2,p,p,n,o],l=m?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let u=e.reshape(a),h=u.dims.length,_=e.dataType,y=E(\"a\",_,h),g=M(\"output\",_,h),x=$=>`\n ${$.registerUniform(\"output_size\",\"u32\").declareVariables(y,g)}\n\n ${wf(l,h,y,g)}\n\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let indices = ${g.offsetToIndices(\"global_idx\")};\n let aIndices = perm(indices);\n\n ${g.setByOffset(\"global_idx\",y.getByIndices(\"aIndices\"))}\n }`;return{name:\"DepthToSpace\",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:[\"rank\"]},getRunData:$=>{let v=d?[r,n*p,o*p,i/p**2]:[r,i/p**2,n*p,o*p],S=k.size(v),T=u.dims,C=k.sortBasedOnPerm(T,l);return{outputs:[{dims:v,dataType:$[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...N(T,C)]}},getShaderSource:x}},al=(e,t)=>{_f(e.inputs),e.compute(vf(e.inputs[0],t))},sl=e=>J({blocksize:e.blocksize,mode:e.mode,format:e.format})});var $o,nn,ll,$f,xf,xo,So,dl,Sf,cl,pl,ml=R(()=>{\"use strict\";te();oe();Se();ae();$o=\"[a-zA-Z]|\\\\.\\\\.\\\\.\",nn=\"(\"+$o+\")+\",ll=\"^\"+nn+\"$\",$f=\"(\"+nn+\",)*\"+nn,xf=\"^\"+$f+\"$\",xo=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,r){let n=this.symbolToIndices.get(t);n===void 0?n=[r]:n.push(r),this.symbolToIndices.set(t,n)}},So=class{constructor(t,r){this.equation=r;this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[n,o]=r.includes(\"->\")?r.split(\"->\",2):[r,\"\"];if(!n.match(RegExp(xf)))throw new Error(\"Invalid LHS term\");if(n.split(\",\").forEach((l,d)=>{let p=t[d].dims.slice();if(!l.match(RegExp(ll)))throw new Error(\"Invalid LHS term\");let m=this.processTerm(l,!0,p,d);this.lhs.push(m)}),o===\"\")o+=[...this.symbolToInfo.entries()].filter(([l,d])=>d.count===1||l===\"...\").map(([l])=>l).join(\"\");else if(!o.match(RegExp(nn)))throw new Error(\"Invalid RHS\");o.match(RegExp($o,\"g\"))?.forEach(l=>{if(l===\"...\")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let d=this.symbolToInfo.get(l);if(d===void 0)throw new Error(\"Invalid RHS symbol\");this.outputDims.push(d.dimValue)}}),this.rhs=this.processTerm(o,!1,this.outputDims)}addSymbol(t,r,n){let o=this.symbolToInfo.get(t);if(o!==void 0){if(o.dimValue!==r&&o.count!==1)throw new Error(\"Dimension mismatch\");o.count++,o.inputIndices.push(n)}else o={count:1,dimValue:r,inputIndices:[n]};this.symbolToInfo.set(t,o)}processTerm(t,r,n,o=-1){let i=n.length,a=!1,l=[],d=0;if(!t.match(RegExp(ll))&&!r&&t!==\"\")throw new Error(\"Invalid LHS term\");let p=t.match(RegExp($o,\"g\")),m=new xo(o);return p?.forEach((u,h)=>{if(u===\"...\"){if(a)throw new Error(\"Only one ellipsis is allowed per input term\");a=!0;let _=i-p.length+1;if(_<0)throw new Error(\"Ellipsis out of bounds\");if(l=n.slice(d,d+_),this.hasEllipsis){if(this.ellipsisDims.length!==l.length||this.ellipsisDims.toString()!==l.toString())throw new Error(\"Ellipsis dimensions mismatch\")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=l;else throw new Error(\"Ellipsis must be specified in the LHS\");for(let y=0;ye+\"_max\",Sf=(e,t,r,n)=>{let i=e.map(m=>m.length).map((m,u)=>E(`input${u}`,t,m)),a=k.size(n),l=M(\"output\",t,n.length),d=[...r.symbolToInfo.keys()].filter(m=>!r.rhs.symbolToIndices.has(m)),p=m=>{let u=[],h=\"var prod = 1.0;\",_=\"var sum = 0.0;\",y=\"sum += prod;\",g=[],x=[],$=[],v=[],S=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((C,A)=>{if(r.rhs.symbolToIndices.has(A)){let P=r.rhs.symbolToIndices.get(A)?.[0];P!==void 0&&r.lhs.forEach((O,U)=>{if(C.inputIndices.includes(U)){let G=O.symbolToIndices.get(A);if(G===void 0)throw new Error(\"Invalid symbol error\");G.forEach(q=>{u.push(`${i[U].indicesSet(`input${U}Indices`,q,l.indicesGet(\"outputIndices\",P))}`)})}})}else r.lhs.forEach((P,O)=>{if(C.inputIndices.includes(O)){let U=P.symbolToIndices.get(A);if(U===void 0)throw new Error(\"Invalid symbol error\");U.forEach(G=>{g.push(`${i[O].indicesSet(`input${O}Indices`,G,`${A}`)}`)}),v.push(`prod *= ${i[O].getByIndices(`input${O}Indices`)};`)}}),x.push(`for(var ${A}: u32 = 0; ${A} < uniforms.${dl(A)}; ${A}++) {`),$.push(\"}\")});let T=S?[...u,`let sum = ${i.map((C,A)=>C.getByIndices(`input${A}Indices`)).join(\" * \")};`]:[...u,_,...x,...g,h,...v,y,...$];return`\n ${m.registerUniforms(d.map(C=>({name:`${dl(C)}`,type:\"u32\"}))).registerUniform(\"outputSize\",\"u32\").declareVariables(...i,l)}\n\n ${m.mainStart()}\n ${m.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n var outputIndices = ${l.offsetToIndices(\"global_idx\")};\n ${i.map((C,A)=>`var input${A}Indices: ${i[A].type.indices};`).join(`\n`)}\n ${T.join(`\n`)};\n ${l.setByOffset(\"global_idx\",\"sum\")};\n }`};return{name:\"Einsum\",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>\"rank\")},getRunData:()=>{let m=d.filter(h=>r.symbolToInfo.has(h)).map(h=>({type:12,data:r.symbolToInfo.get(h)?.dimValue||0}));m.push({type:12,data:a});let u=e.map((h,_)=>[...N(h)]).reduce((h,_)=>h.concat(_),m);return u.push(...N(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:u}},getShaderSource:p}},cl=(e,t)=>{let r=new So(e.inputs,t.equation),n=r.outputDims,o=e.inputs.map((i,a)=>i.dims);e.compute(Sf(o,e.inputs[0].dataType,r,n))},pl=e=>{let t=e.equation.replace(/\\s+/g,\"\");return J({equation:t})}});var Tf,fl,If,Cf,hl,gl=R(()=>{\"use strict\";te();oe();ae();Tf=e=>{if(!e||e.length!==2)throw new Error(\"Expand requires 2 input.\");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=r.length{let r=e.length-t.length,n=[];for(let o=0;oe.length>t.length?fl(e,t):fl(t,e),Cf=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=If(t,r),o=e[0].dataType,i=o===9||k.size(t)===1,a=o===9||t.length>0&&t[t.length-1]%4===0?4:1,l=i||n.length>0&&n[n.length-1]%4===0?4:1,d=Math.ceil(k.size(n)/l),p=u=>{let h=E(\"input\",o,t.length,a),_=M(\"output\",o,n.length,l),y;if(o===9){let g=(x,$,v=\"\")=>`\n let outputIndices${$} = ${_.offsetToIndices(`outputOffset + ${$}u`)};\n let offset${$} = ${h.broadcastedIndicesToOffset(`outputIndices${$}`,_)};\n let index${$} = offset${$} / 4u;\n let component${$} = offset${$} % 4u;\n ${x}[${$}] = ${v}(${h.getByOffset(`index${$}`)}[component${$}]);\n `;y=`\n let outputOffset = global_idx * ${l};\n var data = vec4(0);\n ${g(\"data\",0,\"u32\")}\n ${g(\"data\",1,\"u32\")}\n ${g(\"data\",2,\"u32\")}\n ${g(\"data\",3,\"u32\")}\n ${_.setByOffset(\"global_idx\",\"data\")}\n }`}else y=`\n let outputIndices = ${_.offsetToIndices(`global_idx * ${l}`)};\n let inputOffset = ${h.broadcastedIndicesToOffset(\"outputIndices\",_)};\n let data = ${_.type.value}(${h.getByOffset(`inputOffset / ${a}`)});\n ${_.setByOffset(\"global_idx\",\"data\")}\n }`;return`\n ${u.registerUniform(\"vec_size\",\"u32\").declareVariables(h,_)}\n ${u.mainStart()}\n ${u.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.vec_size\")}\n ${y}`},m=[{type:12,data:d},...N(t,n)];return{name:\"Expand\",shaderCache:{hint:`${n.length};${a}${l}`,inputDependencies:[\"rank\"]},getShaderSource:p,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:m})}},hl=e=>{Tf(e.inputs),e.compute(Cf(e.inputs),{inputs:[0]})}});var Af,bl,yl=R(()=>{\"use strict\";te();oe();ae();Zr();Af=e=>{let t=e[0].dataType,r=k.size(e[0].dims),n=k.size(e[1].dims),o=n%4===0,i=a=>{let l=E(\"x\",t,[1],4),d=E(\"bias\",t,[1],4),p=M(\"y\",t,[1],4),m=[{name:\"output_vec_size\",type:\"u32\"},{name:\"bias_size\",type:\"u32\"}],u=_=>`\n let bias${_}_offset: u32 = (global_idx * 4 + ${_}) % uniforms.bias_size;\n let bias${_} = ${d.getByOffset(`bias${_}_offset / 4`)}[bias${_}_offset % 4];`,h=o?`\n let bias = ${d.getByOffset(\"global_idx % (uniforms.bias_size / 4)\")};`:`${u(0)}${u(1)}${u(2)}${u(3)}\n let bias = ${l.type.value}(bias0, bias1, bias2, bias3);`;return`${a.registerUniforms(m).declareVariables(l,d,p)}\n\n ${fo(ke(t))}\n\n ${a.mainStart(Ct)}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_vec_size\")}\n\n let x = ${l.getByOffset(\"global_idx\")};\n ${h}\n let x_in = x + bias;\n ${p.setByOffset(\"global_idx\",ho(\"x_in\"))}\n }`};return{name:\"FastGeluWithBias\",shaderCache:{hint:`${o}`,inputDependencies:[\"type\",\"type\"]},getShaderSource:i,getRunData:a=>({outputs:[{dims:a[0].dims,dataType:a[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/Ct/4)}})}},bl=e=>{e.inputs.length<2||k.size(e.inputs[1].dims)===0?mu(e):e.compute(Af(e.inputs))}});var kf,Ef,_l,wl,vl=R(()=>{\"use strict\";te();oe();Se();ae();kf=e=>{if(!e||e.length!==2)throw new Error(\"Gather requires 2 inputs.\")},Ef=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r.length,i=k.normalizeAxis(t.axis,o),a=r.slice(0);a.splice(i,1,...n);let l=r[i],d=e[0].dataType===9?4:1,p=Math.ceil(k.size(a)/d),m=[{type:12,data:p},{type:6,data:l},{type:12,data:i},...N(e[0].dims,e[1].dims,a)],u=h=>{let _=E(\"data\",e[0].dataType,e[0].dims.length,d),y=E(\"inputIndices\",e[1].dataType,e[1].dims.length),g=M(\"output\",e[0].dataType,a.length,d),x=v=>{let S=n.length,T=`var indicesIndices${v} = ${y.type.indices}(0);`;for(let C=0;C1?`indicesIndices${v}[${C}]`:`indicesIndices${v}`} = ${a.length>1?`outputIndices${v}[uniforms.axis + ${C}]`:`outputIndices${v}`};`;T+=`\n var idx${v} = ${y.getByIndices(`indicesIndices${v}`)};\n if (idx${v} < 0) {\n idx${v} = idx${v} + uniforms.axisDimLimit;\n }\n var dataIndices${v} : ${_.type.indices};\n `;for(let C=0,A=0;C1?`dataIndices${v}[${C}]`:`dataIndices${v}`} = u32(idx${v});`,A+=S):(T+=`${o>1?`dataIndices${v}[${C}]`:`dataIndices${v}`} = ${a.length>1?`outputIndices${v}[${A}]`:`outputIndices${v}`};`,A++);return T},$;if(e[0].dataType===9){let v=(S,T,C=\"\")=>`\n let outputIndices${T} = ${g.offsetToIndices(`outputOffset + ${T}u`)};\n ${x(T)};\n let offset${T} = ${_.indicesToOffset(`dataIndices${T}`)};\n let index${T} = offset${T} / 4u;\n let component${T} = offset${T} % 4u;\n ${S}[${T}] = ${C}(${_.getByOffset(`index${T}`)}[component${T}]);\n `;$=`\n let outputOffset = global_idx * ${d};\n var value = vec4(0);\n ${v(\"value\",0,\"u32\")}\n ${v(\"value\",1,\"u32\")}\n ${v(\"value\",2,\"u32\")}\n ${v(\"value\",3,\"u32\")}\n ${g.setByOffset(\"global_idx\",\"value\")}\n `}else $=`\n let outputIndices = ${g.offsetToIndices(\"global_idx\")};\n ${x(\"\")};\n let value = ${_.getByIndices(\"dataIndices\")};\n ${g.setByOffset(\"global_idx\",\"value\")};\n `;return`\n ${h.registerUniform(\"outputSize\",\"u32\").registerUniform(\"axisDimLimit\",\"i32\").registerUniform(\"axis\",\"u32\").declareVariables(_,y,g)}\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n ${$}\n }`};return{name:\"Gather\",shaderCache:{hint:t.cacheKey,inputDependencies:[\"rank\",\"rank\"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:m}),getShaderSource:u}},_l=e=>J({axis:e.axis}),wl=(e,t)=>{let r=e.inputs;kf(r),e.compute(Ef(e.inputs,t))}});var Pf,zf,$l,xl,Sl=R(()=>{\"use strict\";te();oe();Se();ae();Pf=(e,t)=>{if(e.length<3||e.length>4)throw new Error(\"GatherBlockQuantized requires 3 or 4 inputs.\");let r=k.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,o=e[0],i=e[2],a=e.length===4?e[3]:void 0;if(i.dims.length!==o.dims.length||!o.dims.map((l,d)=>d===r?Math.ceil(l/n)===i.dims[d]:l===i.dims[d]).reduce((l,d)=>l&&d,!0))throw new Error(\"Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.\");if(a){if(a.dataType!==o.dataType)throw new Error(\"Zero point must have the same data type as the input tensor.\");if(a.dims.length!==i.dims.length||!a.dims.map((l,d)=>l===i.dims[d]).reduce((l,d)=>l&&d,!0))throw new Error(\"Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.\")}},zf=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r.length,i=k.normalizeAxis(t.gatherAxis,o),a=k.normalizeAxis(t.quantizeAxis,o),l=r.slice(0);l.splice(i,1,...n);let d=k.size(l),p=e[2].dataType,u=e[0].dataType===22,h=[{type:12,data:d},{type:12,data:a},{type:12,data:i},{type:12,data:t.blockSize},...N(...e.map((y,g)=>y.dims),l)],_=y=>{let g=E(\"data\",e[0].dataType,e[0].dims.length),x=E(\"inputIndices\",e[1].dataType,e[1].dims.length),$=E(\"scales\",e[2].dataType,e[2].dims.length),v=e.length>3?E(\"zeroPoint\",e[3].dataType,e[3].dims.length):void 0,S=M(\"output\",p,l.length),T=[g,x,$];v&&T.push(v);let C=[{name:\"output_size\",type:\"u32\"},{name:\"quantize_axis\",type:\"u32\"},{name:\"gather_axis\",type:\"u32\"},{name:\"block_size\",type:\"u32\"}];return`\n ${y.registerUniforms(C).declareVariables(...T,S)}\n ${y.mainStart()}\n let output_indices = ${S.offsetToIndices(\"global_idx\")};\n var indices_indices = ${x.type.indices}(0);\n ${(()=>n.length>1?`\n for (var i: u32 = 0; i < ${n.length}; i++) {\n let index = ${S.indicesGet(\"output_indices\",\"uniforms.gather_axis + i\")};\n ${x.indicesSet(\"indices_indices\",\"i\",\"index\")};\n }`:`indices_indices = ${S.indicesGet(\"output_indices\",\"uniforms.gather_axis\")};`)()};\n var data_indices = ${g.type.indices}(0);\n for (var i: u32 = 0; i < uniforms.gather_axis; i++) {\n let index = ${S.indicesGet(\"output_indices\",\"i\")};\n ${g.indicesSet(\"data_indices\",\"i\",\"index\")};\n }\n var index_from_indices = ${x.getByIndices(\"indices_indices\")};\n if (index_from_indices < 0) {\n index_from_indices += ${r[i]};\n }\n ${g.indicesSet(\"data_indices\",\"uniforms.gather_axis\",\"u32(index_from_indices)\")};\n for (var i = uniforms.gather_axis + 1; i < ${l.length}; i++) {\n let index = ${S.indicesGet(\"output_indices\",`i + ${n.length} - 1`)};\n ${g.indicesSet(\"data_indices\",\"i\",\"index\")};\n }\n let data_offset = ${g.indicesToOffset(\"data_indices\")};\n let data_index = data_offset % 8;\n // Convert 4-bit packed data to 8-bit packed data.\n let packed_4bit_quantized_data = ${g.getByOffset(\"data_offset / 8\")};\n let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f;\n let quantized_data_vec = ${u?\"unpack4xI8\":\"unpack4xU8\"}(u32(packed_8bit_quantized_data));\n let quantized_data = quantized_data_vec[data_index / 2];\n var scale_indices = data_indices;\n let quantize_axis_index = ${$.indicesGet(\"data_indices\",\"uniforms.quantize_axis\")} / uniforms.block_size;\n ${$.indicesSet(\"scale_indices\",\"uniforms.quantize_axis\",\"quantize_axis_index\")};\n var scale = ${$.getByIndices(\"scale_indices\")};\n ${(()=>v?`\n let zero_point_indices = scale_indices;\n let zero_point_offset = ${v.indicesToOffset(\"zero_point_indices\")};\n let zero_point_index = zero_point_offset % 8;\n let packed_4bit_zero_points = ${v.getByOffset(\"zero_point_offset / 8\")};\n let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f;\n let zero_point_vec = ${u?\"unpack4xI8\":\"unpack4xU8\"}(u32(packed_8bit_zero_points));\n let zero_point = zero_point_vec[zero_point_index / 2];`:\"var zero_point = 0\")()};\n let dequantized_data = ${ke(p)}(quantized_data - zero_point) * scale;\n ${S.setByOffset(\"global_idx\",\"dequantized_data\")};\n }`};return{name:\"GatherBlockQuantized\",shaderCache:{hint:`${t.cacheKey};${e.filter((y,g)=>g!==1).map(y=>y.dims.join(\"_\")).join(\";\")}`,inputDependencies:Array.from({length:e.length},(y,g)=>\"rank\")},getRunData:()=>({outputs:[{dims:l,dataType:p}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:h}),getShaderSource:_}},$l=(e,t)=>{let r=e.inputs;Pf(r,t),e.compute(zf(e.inputs,t))},xl=e=>J({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})});var Of,Bf,Tl,Il,Cl=R(()=>{\"use strict\";te();oe();Se();ae();Of=e=>{if(!e||e.length!==2)throw new Error(\"GatherElements requires 2 inputs.\");if(e[0].dims.length<1)throw new Error(\"GatherElements requires that the data input be rank >= 1.\");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and\n indices input tensors be of same rank.`)},Bf=(e,t)=>{let r=e[0].dims,n=e[0].dataType,o=r.length,i=e[1].dims,a=e[1].dataType,l=k.normalizeAxis(t.axis,o),d=r[l],p=i.slice(0),m=k.size(p),u=E(\"input\",n,o),h=E(\"indicesInput\",a,i.length),_=M(\"output\",n,p.length),y=[{type:12,data:m},{type:6,data:d},{type:12,data:l}];return y.push(...N(r,i,p)),{name:\"GatherElements\",shaderCache:{inputDependencies:[\"rank\",\"rank\"]},getRunData:()=>({outputs:[{dims:p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:y}),getShaderSource:$=>`\n ${$.registerUniform(\"outputSize\",\"u32\").registerUniform(\"axisDimLimit\",\"i32\").registerUniform(\"axis\",\"u32\").declareVariables(u,h,_)}\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n\n let outputIndices = ${_.offsetToIndices(\"global_idx\")};\n\n var idx = ${h.getByOffset(\"global_idx\")};\n if (idx < 0) {\n idx = idx + uniforms.axisDimLimit;\n }\n var inputIndices = ${u.type.indices}(outputIndices);\n ${u.indicesSet(\"inputIndices\",\"uniforms.axis\",\"u32(idx)\")};\n let value = ${u.getByIndices(\"inputIndices\")};\n\n ${_.setByOffset(\"global_idx\",\"value\")};\n }`}},Tl=e=>J({axis:e.axis}),Il=(e,t)=>{let r=e.inputs;Of(r),e.compute(Bf(e.inputs,t))}});var Df,Mf,Al,kl,El=R(()=>{\"use strict\";te();oe();ae();Df=e=>{if(!e)throw new Error(\"Input is missing\");if(e.length<2||e.length>3)throw new Error(\"Invaid input number.\");if(e.length===3&&e[2].dims.length>2)throw new Error(\"Invalid input shape of C\");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error(\"Input types are mismatched\")},Mf=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[o,i,a]=Gr.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),l=[o,i];if(!l)throw new Error(\"Can't use gemm on the given tensors\");let d=16,p=Math.ceil(i/d),m=Math.ceil(o/d),u=!0,h=k.size(l),_=[{type:12,data:u?p:h},{type:12,data:o},{type:12,data:i},{type:12,data:a},{type:1,data:t.alpha},{type:1,data:t.beta}],y=[\"type\",\"type\"];e.length===3&&(_.push(...N(e[2].dims)),y.push(\"rank\")),_.push(...N(l));let g=$=>{let v=\"\";t.transA&&t.transB?v=\"value += a[k * uniforms.M + m] * b[n * uniforms.K + k];\":t.transA&&!t.transB?v=\"value += a[k * uniforms.M + m] * b[k * uniforms.N + n];\":!t.transA&&t.transB?v=\"value += a[m * uniforms.K + k] * b[n * uniforms.K + k];\":!t.transA&&!t.transB&&(v=\"value += a[m * uniforms.K + k] * b[k * uniforms.N + n];\");let S=t.alpha===1?\"\":\"value *= uniforms.alpha;\",T=E(\"a\",e[0].dataType,e[0].dims),C=E(\"b\",e[1].dataType,e[1].dims),A=T.type.value,P=null,O=[T,C];e.length===3&&(P=E(\"c\",e[2].dataType,e[2].dims.length),O.push(P));let U=M(\"output\",e[0].dataType,l.length);O.push(U);let G=[{name:\"output_size\",type:\"u32\"},{name:\"M\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"alpha\",type:\"f32\"},{name:\"beta\",type:\"f32\"}];return`\n ${$.registerUniforms(G).declareVariables(...O)}\n\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let m = global_idx / uniforms.N;\n let n = global_idx % uniforms.N;\n\n var value = ${A}(0);\n for (var k: u32 = 0u; k < uniforms.K; k++) {\n ${v}\n }\n\n ${S}\n ${(()=>P!=null?`let cOffset = ${P.broadcastedIndicesToOffset(\"vec2(m, n)\",U)}; value += ${A}(uniforms.beta) * ${P.getByOffset(\"cOffset\")};`:\"\")()}\n output[global_idx] = value;\n }`},x=$=>{let v=E(\"a\",e[0].dataType,e[0].dims),S=E(\"b\",e[1].dataType,e[1].dims),T=null,C=[v,S];e.length===3&&(T=E(\"c\",e[2].dataType,e[2].dims.length),C.push(T));let A=M(\"output\",e[0].dataType,l.length);C.push(A);let P=[{name:\"num_tile_n\",type:\"u32\"},{name:\"M\",type:\"u32\"},{name:\"N\",type:\"u32\"},{name:\"K\",type:\"u32\"},{name:\"alpha\",type:\"f32\"},{name:\"beta\",type:\"f32\"}],O=\"\",U=\"\";t.transA&&t.transB?(U=`\n var col = tile_row_start + local_id.x;\n var row = k_start + local_id.y;\n if (col < uniforms.M && row < uniforms.K) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${v.type.value}(0);\n }\n\n col = k_start + local_id.x;\n row = tile_col_start + local_id.y;\n if (col < uniforms.K && row < uniforms.N) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${S.type.value}(0);\n }\n `,O=\"value += tile_a[k][local_id.y] * tile_b[local_id.x][k];\"):t.transA&&!t.transB?(U=`\n var col = tile_row_start + local_id.x;\n var row = k_start + local_id.y;\n if (col < uniforms.M && row < uniforms.K) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${v.type.value}(0);\n }\n\n col = tile_col_start + local_id.x;\n row = k_start + local_id.y;\n if (col < uniforms.N && row < uniforms.K) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${S.type.value}(0);\n }\n `,O=\"value += tile_a[k][local_id.y] * tile_b[k][local_id.x];\"):!t.transA&&t.transB?(U=`\n var col = k_start + local_id.x;\n var row = tile_row_start + local_id.y;\n if (col < uniforms.K && row < uniforms.M) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${v.type.value}(0);\n }\n\n col = k_start + local_id.x;\n row = tile_col_start + local_id.y;\n if (col < uniforms.K && row < uniforms.N) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${S.type.value}(0);\n }\n `,O=\"value += tile_a[local_id.y][k] * tile_b[local_id.x][k];\"):!t.transA&&!t.transB&&(U=`\n var col = k_start + local_id.x;\n var row = tile_row_start + local_id.y;\n if (col < uniforms.K && row < uniforms.M) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${v.type.value}(0);\n }\n\n col = tile_col_start + local_id.x;\n row = k_start + local_id.y;\n if (col < uniforms.N && row < uniforms.K) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${S.type.value}(0);\n }\n `,O=\"value += tile_a[local_id.y][k] * tile_b[k][local_id.x];\");let G=t.alpha===1?\"\":\"value *= uniforms.alpha;\";return`\n ${$.registerUniforms(P).declareVariables(...C)}\n var tile_a: array, ${d}>;\n var tile_b: array, ${d}>;\n ${$.mainStart([d,d,1])}\n let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${d};\n let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${d};\n let num_tiles = (uniforms.K - 1) / ${d} + 1;\n var k_start = 0u;\n var value = ${A.type.value}(0);\n for (var t: u32 = 0u; t < num_tiles; t++) {\n ${U}\n k_start = k_start + ${d};\n workgroupBarrier();\n\n for (var k: u32 = 0u; k < ${d}; k++) {\n ${O}\n }\n workgroupBarrier();\n }\n\n ${G}\n let m = tile_row_start + local_id.y;\n let n = tile_col_start + local_id.x;\n ${(()=>T!=null?`let cOffset = ${T.broadcastedIndicesToOffset(\"vec2(m, n)\",A)}; value += ${A.type.value}(uniforms.beta) * ${T.getByOffset(\"cOffset\")};`:\"\")()}\n if (m < uniforms.M && n < uniforms.N) {\n output[m * uniforms.N + n] = value;\n }\n }`};return u?{name:\"GemmShared\",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:p*m},programUniforms:_}),getShaderSource:x}:{name:\"Gemm\",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:_}),getShaderSource:g}},Al=e=>{let t=e.transA,r=e.transB,n=e.alpha,o=e.beta;return{transA:t,transB:r,alpha:n,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},kl=(e,t)=>{Df(e.inputs),e.compute(Mf(e.inputs,t))}});var lt,yt,Ut,Nt,Rf,Uf,Nf,Vf,Wf,Lf,Gf,Hf,Pl,zl,Ol=R(()=>{\"use strict\";te();oe();Se();ae();[lt,yt,Ut,Nt]=[0,1,2,3],Rf=e=>{if(e[0].dims.length!==4)throw new Error(\"only 4-D tensor is supported.\");if(e[0].dims.length!==e[1].dims.length)throw new Error(\"input dimensions must be equal to grid dimensions\");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error(\"grid batch size must match input batch size\")},Uf=`\n fn gs_get_cubic_coeffs(x: f32) -> vec4 {\n let cubic_alpha = -0.75f;\n let x_abs = abs(x);\n var coeffs: vec4;\n coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha);\n coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1);\n coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1);\n coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha);\n return coeffs;\n }\n`,Nf=e=>`\n fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} {\n var v: vec4;\n var coeffs = gs_get_cubic_coeffs(x);\n for (var i = 0; i < 4; i++) {\n v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3];\n }\n coeffs = gs_get_cubic_coeffs(y);\n let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]);\n return pixel;\n }\n`,Vf=e=>`\n fn gs_denormalize(n: f32, length: i32) -> f32 {\n ${e.alignCorners===0?`\n // alignCorners: false => [-1, 1] to [-0.5, length - 0.5]\n return ((n + 1.0) * f32(length) - 1.0) / 2.0;\n `:`\n // alignCorners: true => [-1, 1] to [0, length - 1]\n return (n + 1.0) / 2.0 * (f32(length - 1));\n `}\n }\n`,Wf=e=>`\n ${e.paddingMode===\"reflection\"?`\n fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 {\n var dx = 0.0;\n var fx = f32(x);\n let range = x_max - x_min;\n if (fx < x_min) {\n dx = x_min - fx;\n let n = u32(dx / range);\n let r = dx - f32(n) * range;\n if (n % 2 == 0) {\n fx = x_min + r;\n } else {\n fx = x_max - r;\n }\n } else if (fx > x_max) {\n dx = fx - x_max;\n let n = u32(dx / range);\n let r = dx - f32(n) * range;\n if (n % 2 == 0) {\n fx = x_max - r;\n } else {\n fx = x_min + r;\n }\n }\n return u32(fx);\n }`:\"\"}\n`,Lf=(e,t,r)=>`\n fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} {\n var pixel = ${t}(0);\n var indices = vec4(0);\n indices[${lt}] = batch;\n indices[${yt}] = channel;`+(()=>{switch(r.paddingMode){case\"zeros\":return`\n if (r >= 0 && r < H && c >=0 && c < W) {\n indices[${Ut}] = u32(r);\n indices[${Nt}] = u32(c);\n }\n `;case\"border\":return`\n indices[${Ut}] = u32(clamp(r, 0, H - 1));\n indices[${Nt}] = u32(clamp(c, 0, W - 1));\n `;case\"reflection\":return`\n indices[${Ut}] = gs_reflect(r, border[1], border[3]);\n indices[${Nt}] = gs_reflect(c, border[0], border[2]);\n `;default:throw new Error(`padding mode ${r.paddingMode} is not supported`)}})()+`\n return ${e.getByIndices(\"indices\")};\n }\n`,Gf=(e,t,r)=>(()=>{switch(r.mode){case\"nearest\":return`\n let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${lt}], indices[${yt}], border);\n `;case\"bilinear\":return`\n let x1 = i32(floor(x));\n let y1 = i32(floor(y));\n let x2 = x1 + 1;\n let y2 = y1 + 1;\n\n let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${lt}], indices[${yt}], border);\n let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${lt}], indices[${yt}], border);\n let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${lt}], indices[${yt}], border);\n let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${lt}], indices[${yt}], border);\n\n let dx2 = ${t}(f32(x2) - x);\n let dx1 = ${t}(x - f32(x1));\n let dy2 = ${t}(f32(y2) - y);\n let dy1 = ${t}(y - f32(y1));\n let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22);\n `;case\"bicubic\":return`\n let x0 = i32(floor(x)) - 1;\n let y0 = i32(floor(y)) - 1;\n var p: mat4x4<${t}>;\n for (var h = 0; h < 4; h++) {\n for (var w = 0; w < 4; w++) {\n p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${lt}], indices[${yt}], border);\n }\n }\n\n let dx = x - f32(x0 + 1);\n let dy = y - f32(y0 + 1);\n let result = gs_bicubic_interpolate(p, dx, dy);\n `;default:throw new Error(`mode ${r.mode} is not supported`)}})()+`${e.setByOffset(\"global_idx\",\"result\")}`,Hf=(e,t)=>{let r=E(\"x\",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=E(\"grid\",e[1].dataType,n.length,2),i=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format===\"NHWC\"&&(i=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[lt,yt,Ut,Nt]=[0,3,1,2]);let a=M(\"output\",e[0].dataType,i.length),l=r.type.value,d=k.size(i),p=[{type:12,data:d},...N(e[0].dims,n,i)],m=u=>`\n ${u.registerUniform(\"output_size\",\"u32\").declareVariables(r,o,a)}\n ${Uf}\n ${Nf(l)}\n ${Vf(t)}\n ${Wf(t)}\n ${Lf(r,l,t)}\n\n ${u.mainStart()}\n ${u.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let H_in = i32(uniforms.x_shape[${Ut}]);\n let W_in = i32(uniforms.x_shape[${Nt}]);\n\n ${t.alignCorners===0?`\n let x_min = -0.5;\n let x_max = f32(W_in) - 0.5;\n let y_min = -0.5;\n let y_max = f32(H_in) - 0.5;\n `:`\n let x_min = 0.0;\n let x_max = f32(W_in) - 1.0;\n let y_min = 0.0;\n let y_max = f32(H_in) - 1.0;\n `};\n let border = vec4(x_min, y_min, x_max, y_max);\n\n let indices = ${a.offsetToIndices(\"global_idx\")};\n var grid_indices = vec3(indices[${lt}], indices[${Ut}], indices[${Nt}]);\n let nxy = ${o.getByIndices(\"grid_indices\")};\n var x = gs_denormalize(f32(nxy[0]), W_in);\n var y = gs_denormalize(f32(nxy[1]), H_in);\n\n ${Gf(a,l,t)}\n }`;return{name:\"GridSample\",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:[\"type\",\"type\"]},getRunData:u=>{let h=k.size(i);return{outputs:[{dims:i,dataType:u[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:p}},getShaderSource:m}},Pl=(e,t)=>{Rf(e.inputs),e.compute(Hf(e.inputs,t))},zl=e=>J({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})});var Me,jf,Dl,Bl,Kf,rr,Ml,To=R(()=>{\"use strict\";te();oe();Se();Lr();Kr();ae();ut();Me=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,jf=(e,t)=>{let r=e[0],n=Me(e,1),o=Me(e,2),i=Me(e,3),a=Me(e,4),l=Me(e,5),d=Me(e,6),p=Me(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error(\"Input query is expected to have 3 or 5 dimensions\");let m=r.dims[0],u=r.dims[1],h=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],_=u,y=0,g=0,x=Math.floor(h/t.numHeads);if(d&&p&&k.size(d.dims)&&k.size(p.dims)){if(d.dims.length!==4)throw new Error('Input \"past_key\" is expected to have 4 dimensions');if(d.dims[0]!==m||d.dims[1]!==t.numHeads||d.dims[3]!==x)throw new Error('Input \"past_key\" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[0]!==m||p.dims[1]!==t.numHeads||p.dims[3]!==x)throw new Error('Input \"past_value\" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.dims[2]!==p.dims[2])throw new Error('Input \"past_key\" and \"past_value\" shall have same dim 2 (past_sequence_length)');if(p.dims.length!==4)throw new Error('Input \"past_value\" is expected to have 4 dimensions');y=d.dims[2],g=d.dims[2]}else if(d&&k.size(d.dims)||p&&k.size(p.dims))throw new Error('Input \"past_key\" and \"past_value\" shall be both present or both absent');let $;if(n&&k.size(n.dims)>0){if(r.dims.length!==3)throw new Error('Input \"query\" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input \"key\" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input \"query\" and \"key\" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input \"query\" and \"key\" shall have same dim 2 (hidden_size)');$=2,_=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==x)throw new Error('Expect \"key\" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect \"value\" be none when \"key\" has packed kv format.');$=5,_=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==x)throw new Error('Expect \"key\" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');$=0,_=n.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input \"query\" is expected to have 5 dimensions when key is empty');if(r.dims[2]!==t.numHeads||r.dims[3]!==3)throw new Error('Expect \"query\" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');$=3}if(i&&k.size(i.dims)>0){if(i.dims.length!==1)throw new Error('Input \"bias\" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error(\"bias is not allowed for packed kv.\")}let v=y+_,S=0;if(a&&k.size(a.dims)>0){S=8;let P=a.dims;throw P.length===1?P[0]===m?S=1:P[0]===3*m+2&&(S=3):P.length===2&&P[0]===m&&P[1]===v&&(S=5),S===8?new Error('Input \"key_padding_mask\" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error(\"Mask not supported\")}let T=!1,C=h;if(o&&k.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input \"value\" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input \"query\" and \"value\" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(_!==o.dims[1])throw new Error('Input \"key\" and \"value\" shall have the same dim 1 (kv_sequence_length)');C=o.dims[2]}else{if(_!==o.dims[2])throw new Error('Input \"key\" and \"value\" shall have the same dim 2 (kv_sequence_length)');C=o.dims[1]*o.dims[3],T=!0}}let A=!1;if(a&&k.size(a.dims)>0)throw new Error(\"Key padding mask is not supported\");if(l&&k.size(l.dims)>0){if(l.dims.length!==4)throw new Error('Input \"attention_bias\" is expected to have 4 dimensions');if(l.dims[0]!==m||l.dims[1]!==t.numHeads||l.dims[2]!==u||l.dims[3]!==v)throw new Error('Expect \"attention_bias\" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:m,sequenceLength:u,pastSequenceLength:y,kvSequenceLength:_,totalSequenceLength:v,maxSequenceLength:g,inputHiddenSize:0,hiddenSize:h,vHiddenSize:C,headSize:x,vHeadSize:Math.floor(C/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:S,scale:t.scale,broadcastResPosBias:A,passPastInKv:T,qkvFormat:$}},Dl=e=>J({...e}),Bl=J({perm:[0,2,1,3]}),Kf=(e,t,r,n,o,i,a)=>{let l=[n,o,i],d=k.size(l),p=[{type:12,data:d},{type:12,data:a},{type:12,data:i}],m=u=>{let h=M(\"qkv_with_bias\",t.dataType,l),_=E(\"qkv\",t.dataType,l),y=E(\"bias\",r.dataType,l),g=[{name:\"output_size\",type:\"u32\"},{name:\"bias_offset\",type:\"u32\"},{name:\"hidden_size\",type:\"u32\"}];return`\n ${u.registerUniforms(g).declareVariables(_,y,h)}\n ${u.mainStart()}\n ${u.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;\n\n qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];\n }`};return e.compute({name:\"MultiHeadAttentionAddBias\",shaderCache:{inputDependencies:[\"type\",\"type\"]},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p}),getShaderSource:m},{inputs:[t,r],outputs:[-1]})[0]},rr=(e,t,r,n,o,i,a,l)=>{let d=i;if(a&&k.size(a.dims)>0){if(n===1)throw new Error(\"AddBiasReshape is not implemented. Please export your model with packed QKV or KV\");return d=Kf(e,i,a,t,n,r*o,l),d=d.reshape([t,n,r,o]),r===1||n===1?d:e.compute(Ee(d,Bl.perm),{inputs:[d],outputs:[-1]})[0]}else return i.dims.length===3&&(d=i.reshape([t,n,r,o])),r===1||n===1?d:e.compute(Ee(d,Bl.perm),{inputs:[d],outputs:[-1]})[0]},Ml=(e,t)=>{let r=jf(e.inputs,t),n=e.inputs[0],o=Me(e.inputs,1),i=Me(e.inputs,2),a=Me(e.inputs,3),l=Me(e.inputs,4),d=Me(e.inputs,5),p=Me(e.inputs,6),m=Me(e.inputs,7);if(n.dims.length===5)throw new Error(\"Packed QKV is not implemented\");if(o?.dims.length===5)throw new Error(\"Packed KV is not implemented\");let u=o&&i&&o.dims.length===4&&i.dims.length===4,h=rr(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,a,0);if(u)return Rt(e,h,o,i,l,void 0,p,m,d,r);if(!o||!i)throw new Error(\"key and value must be provided\");let _=rr(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,o,a,r.hiddenSize),y=rr(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,i,a,2*r.hiddenSize);Rt(e,h,_,y,l,void 0,p,m,d,r)}});var Yf,Zf,Qf,Xf,Io,Rl,Ul,Co=R(()=>{\"use strict\";te();oe();Se();ae();Yf=e=>{if(!e||e.length<1)throw new Error(\"too few inputs\")},Zf=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>r.push(Number(o))),n=r.length),J({numOutputs:n,axis:t.axis,splitSizes:r})},Qf=e=>`\nfn calculateOutputIndex(index: u32) -> u32 {\n for (var i: u32 = 0u; i < ${e}u; i += 1u ) {\n if (index < ${F(\"uniforms.size_in_split_axis\",\"i\",e)}) {\n return i;\n }\n }\n return ${e}u;\n}`,Xf=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=k.size(r),o=e[0].dataType,i=k.normalizeAxis(t.axis,r.length),a=new Array(t.numOutputs),l=E(\"input\",o,r.length),d=new Array(t.numOutputs),p=[],m=[],u=0,h=[{type:12,data:n}];for(let y=0;y`\n ${y.registerUniform(\"input_size\",\"u32\").registerUniform(\"size_in_split_axis\",\"u32\",d.length).declareVariables(l,...a)}\n ${Qf(d.length)}\n ${Xf(a)}\n\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.input_size\")}\n\n var indices = ${l.offsetToIndices(\"global_idx\")};\n var index = ${l.indicesGet(\"indices\",i)};\n let output_number = calculateOutputIndex(index);\n if (output_number != 0) {\n index -= ${F(\"uniforms.size_in_split_axis\",\"output_number - 1u\",d.length)};\n ${l.indicesSet(\"indices\",i,\"index\")};\n }\n writeBufferData(output_number, indices, global_idx);\n }`;return{name:\"Split\",shaderCache:{hint:t.cacheKey,inputDependencies:[\"rank\"]},getShaderSource:_,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:h})}},Rl=(e,t)=>{Yf(e.inputs);let r=e.inputs.length===1?t:Zf(e.inputs,t);e.compute(Io(e.inputs,r),{inputs:[0]})},Ul=e=>{let t=e.axis,r=e.splitSizes,n=e.numOutputs<0?r.length:e.numOutputs;if(n!==r.length)throw new Error(\"numOutputs and splitSizes lengh must be equal\");return J({axis:t,numOutputs:n,splitSizes:r})}});var Jf,eh,Nl,Vl,Wl=R(()=>{\"use strict\";Se();Kr();To();Co();ut();Jf=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error(\"cos_cache and sin_cache inputs are required if do_rotary is specified\");let r=e[0],n=e[1],o=e[2],i=e[3],a=e[4];if(t.localWindowSize!==-1)throw new Error(\"Local attention is not supported\");if(t.softcap!==0)throw new Error(\"Softcap is not supported\");if(t.rotaryInterleaved!==0)throw new Error(\"Rotary interleaved is not supported\");if(t.smoothSoftmax)throw new Error(\"Smooth softmax is not supported\");if(r.dims.length!==3&&r.dims.length!==5)throw new Error(\"Input query is expected to have 3 or 5 dimensions\");let l=!1,d=r.dims[0],p=r.dims[1],m=r.dims.length===3?l?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],u=p,h=0,_=!n||n.dims.length===0,y=Math.floor(_?m/(t.numHeads+2*t.kvNumHeads):m/t.numHeads);_&&(m=y*t.numHeads);let g=i&&i.dims.length!==0,x=a&&a.dims.length!==0;if(g&&i.dims.length===4&&i.dims[0]===d&&i.dims[1]!==t.kvNumHeads&&i.dims[2]===t.kvNumHeads&&i.dims[3]===y)throw new Error(\"BSNH pastKey/pastValue is not supported\");if(g&&x){if(i.dims.length!==4)throw new Error('Input \"past_key\" is expected to have 4 dimensions');if(a.dims.length!==4)throw new Error('Input \"past_value\" is expected to have 4 dimensions');h=i.dims[2]}else if(g||x)throw new Error('Input \"past_key\" and \"past_value\" shall be both present or both absent');let v=1;if(n&&n.dims.length>0){if(r.dims.length!==3)throw new Error('Input \"query\" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input \"key\" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input \"query\" and \"key\" shall have same dim 0 (batch size)');if(n.dims.length===3){if(r.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of \"query\" should be a multiple of \"key\"');u=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==y)throw new Error('Expect \"key\" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect \"value\" be none when \"key\" has packed kv format.');u=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==y)throw new Error('Expect \"key\" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');u=n.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input \"query\" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error('Expect \"query\" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');v=3}let S=0,T=!1,C=t.kvNumHeads?y*t.kvNumHeads:m;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input \"value\" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input \"query\" and \"value\" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(u!==o.dims[1])throw new Error('Input \"key\" and \"value\" shall have the same dim 1 (kv_sequence_length)');C=o.dims[2]}else{if(u!==o.dims[2])throw new Error('Input \"past_key\" and \"past_value\" shall have the same dim 2 (kv_sequence_length)');C=o.dims[1]*o.dims[3],T=!0}}let A=e.length>4?e[5]:void 0;if(A&&A.dims.length!==1&&A.dims[0]!==d)throw new Error('Input \"seqlens\" is expected to have 1 dimension and the same dim 0 as batch_size');let P=-1,O=-1,U=!1;return{batchSize:d,sequenceLength:p,pastSequenceLength:h,kvSequenceLength:u,totalSequenceLength:P,maxSequenceLength:O,inputHiddenSize:0,hiddenSize:m,vHiddenSize:C,headSize:y,vHeadSize:Math.floor(C/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:S,scale:t.scale,broadcastResPosBias:U,passPastInKv:T,qkvFormat:v}},eh=J({perm:[0,2,1,3]}),Nl=(e,t,r)=>{let n=t,o=r.kvNumHeads;return t.dims.length===3&&r.kvSequenceLength!==0&&(n=t.reshape([r.batchSize,r.kvSequenceLength,o,r.headSize]),n=e.compute(Ee(n,eh.perm),{inputs:[n],outputs:[-1]})[0]),n},Vl=(e,t)=>{let r=Jf(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error(\"Packed QKV is not implemented\");if(e.inputs[1]?.dims.length===5)throw new Error(\"Packed KV is not implemented\");let n=e.inputs[0],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,i=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,a=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,l=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,d=e.inputs.length>4?e.inputs[5]:void 0,p=e.inputs.length>5?e.inputs[6]:void 0,m=r.kvNumHeads?r.kvNumHeads:r.numHeads,u=J({axis:2,numOutputs:3,splitSizes:[r.numHeads*r.headSize,m*r.headSize,m*r.headSize]}),[h,_,y]=!o&&!i?e.compute(Io([n],u),{inputs:[n],outputs:[-1,-1,-1]}):[n,o,i],g=rr(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,h,void 0,0);Rt(e,g,Nl(e,_,r),Nl(e,y,r),void 0,void 0,a,l,void 0,r,d,p)}});var Ll,th,rh,Gl,Hl=R(()=>{\"use strict\";te();oe();ut();ae();Ll=(e,t,r,n,o,i,a,l)=>{let d=me(i),p=d===1?\"f32\":`vec${d}f`,m=d===1?\"vec2f\":`mat2x${d}f`,u=o*a,h=64;u===1&&(h=256);let _=[o,a,i/d],y=[o,a,2],g=[\"rank\",\"type\",\"type\"],x=[];x.push(...N(_,y));let $=v=>{let S=E(\"x\",t.dataType,3,d),T=E(\"scale\",r.dataType,r.dims),C=E(\"bias\",n.dataType,n.dims),A=M(\"output\",1,3,2),P=[S,T,C,A];return`\n var workgroup_shared : array<${m}, ${h}>;\n const workgroup_size = ${h}u;\n ${v.declareVariables(...P)}\n ${v.mainStart(h)}\n let batch = workgroup_index / uniforms.x_shape[1];\n let channel = workgroup_index % uniforms.x_shape[1];\n let hight = uniforms.x_shape[2];\n // initialize workgroup memory\n var sum = ${p}(0);\n var squared_sum = ${p}(0);\n for (var h = local_idx; h < hight; h += workgroup_size) {\n let value = ${p}(${S.get(\"batch\",\"channel\",\"h\")});\n sum += value;\n squared_sum += value * value;\n }\n workgroup_shared[local_idx] = ${m}(sum, squared_sum);\n workgroupBarrier();\n\n for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) {\n if (local_idx < currSize) {\n workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize];\n }\n workgroupBarrier();\n }\n if (local_idx == 0) {\n let sum_final = ${He(\"workgroup_shared[0][0]\",d)} / f32(hight * ${d});\n let squared_sum_final = ${He(\"workgroup_shared[0][1]\",d)} / f32(hight * ${d});\n\n let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${l}));\n let channel_scale = inv_std_dev * f32(scale[channel]);\n let channel_shift = f32(bias[channel]) - sum_final * channel_scale;\n output[workgroup_index] = vec2f(channel_scale, channel_shift);\n }\n }`};return e.compute({name:\"InstanceNormComputeChannelScaleShift\",shaderCache:{hint:`${d};${l};${h}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:y,dataType:1}],dispatchGroup:{x:u},programUniforms:x}),getShaderSource:$},{inputs:[t,r,n],outputs:[-1]})[0]},th=(e,t,r)=>{let n=t[0].dims,o=n,i=2,a=n[0],l=n[1],d=k.sizeFromDimension(n,i),p=me(d),m=k.size(o)/p,u=Ll(e,t[0],t[1],t[2],a,d,l,r.epsilon),h=[a,l,d/p],_=[a,l],y=[\"type\",\"none\"],g=x=>{let $=E(\"x\",t[0].dataType,h.length,p),v=E(\"scale_shift\",1,_.length,2),S=M(\"output\",t[0].dataType,h.length,p),T=[$,v,S];return`\n ${x.registerUniform(\"output_size\",\"u32\").declareVariables(...T)}\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let outputIndices = ${S.offsetToIndices(\"global_idx\")};\n let batch = outputIndices[0];\n let channel = outputIndices[1];\n let scale_shift = ${v.getByIndices(\"vec2(batch, channel)\")};\n let value = ${$.getByOffset(\"global_idx\")} * ${S.type.value}(scale_shift.x) + ${S.type.value}(scale_shift.y);\n ${S.setByOffset(\"global_idx\",\"value\")};\n }`};e.compute({name:\"InstanceNormalization\",shaderCache:{hint:`${p}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...N(h,_,h)]}),getShaderSource:g},{inputs:[t[0],u]})},rh=(e,t,r)=>{let n=t[0].dims,o=n,i=n[0],a=n[n.length-1],l=k.sizeFromDimension(n,1)/a,d=me(a),p=k.size(o)/d,m=[{type:12,data:l},{type:12,data:Math.floor(a/d)}],u=[\"type\",\"type\"],h=!1,_=[0,n.length-1];for(let $=0;$n[_[v]])),g=Ll(e,y,t[1],t[2],i,l,a,r.epsilon),x=$=>{let v=ye(t[0].dataType),S=d===1?\"vec2f\":`mat${d}x2f`,T=P=>{let O=P===0?\"x\":\"y\",U=d===1?\"f32\":`vec${d}f`;switch(d){case 1:return`${v}(${U}(scale.${O}))`;case 2:return`vec2<${v}>(${U}(scale[0].${O}, scale[1].${O}))`;case 4:return`vec4<${v}>(${U}(scale[0].${O}, scale[1].${O}, scale[2].${O}, scale[3].${O}))`;default:throw new Error(`Not supported compoents ${d}`)}},C=E(\"input\",t[0].dataType,t[0].dims,d),A=M(\"output\",t[0].dataType,o,d);return`\n @group(0) @binding(0) var input : array<${C.type.storage}>;\n @group(0) @binding(1) var scale_input : array<${S}>;\n @group(0) @binding(2) var output : array<${A.type.storage}>;\n struct Uniforms {H: u32, C : u32};\n @group(0) @binding(3) var uniforms: Uniforms;\n\n ${$.mainStart()}\n let current_image_number = global_idx / (uniforms.C * uniforms.H);\n let current_channel_number = global_idx % uniforms.C;\n\n let scale_offset = current_image_number * uniforms.C + current_channel_number;\n let scale = scale_input[scale_offset];\n output[global_idx] = fma(input[global_idx], ${T(0)}, ${T(1)});\n }`};e.compute({name:\"InstanceNormalizationNHWC\",shaderCache:{hint:`${d}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:m}),getShaderSource:x},{inputs:[t[0],g]})},Gl=(e,t)=>{t.format===\"NHWC\"?rh(e,e.inputs,t):th(e,e.inputs,t)}});var nh,oh,Fl,ql=R(()=>{\"use strict\";te();oe();ae();nh=e=>{if(!e||e.length<2)throw new Error(\"layerNorm requires at least 2 inputs.\")},oh=(e,t,r)=>{let n=t.simplified,o=e[0].dims,i=e[1],a=!n&&e[2],l=o,d=k.normalizeAxis(t.axis,o.length),p=k.sizeToDimension(o,d),m=k.sizeFromDimension(o,d),u=k.size(i.dims),h=a?k.size(a.dims):0;if(u!==m||a&&h!==m)throw new Error(`Size of X.shape()[axis:] == ${m}.\n Size of scale and bias (if provided) must match this.\n Got scale size of ${u} and bias size of ${h}`);let _=[];for(let C=0;C1,v=r>2,S=C=>{let A=ye(e[0].dataType),P=[E(\"x\",e[0].dataType,e[0].dims,y),E(\"scale\",i.dataType,i.dims,y)];a&&P.push(E(\"bias\",a.dataType,a.dims,y)),P.push(M(\"output\",e[0].dataType,l,y)),$&&P.push(M(\"mean_data_output\",1,_)),v&&P.push(M(\"inv_std_output\",1,_));let O=[{name:\"norm_count\",type:\"u32\"},{name:\"norm_size\",type:\"f32\"},{name:\"norm_size_vectorized\",type:\"u32\"},{name:\"epsilon\",type:\"f32\"}];return`\n ${C.registerUniforms(O).declareVariables(...P)}\n ${C.mainStart()}\n ${C.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.norm_count\")}\n let offset = global_idx * uniforms.norm_size_vectorized;\n var mean_vector = ${lo(\"f32\",y)};\n var mean_square_vector = ${lo(\"f32\",y)};\n\n for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {\n let value = ${At(A,y,\"x[h + offset]\")};\n mean_vector += value;\n mean_square_vector += value * value;\n }\n let mean = ${He(\"mean_vector\",y)} / uniforms.norm_size;\n let inv_std_dev = inverseSqrt(${He(\"mean_square_vector\",y)} / uniforms.norm_size ${n?\"\":\"- mean * mean\"} + uniforms.epsilon);\n\n for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {\n let f32input = ${At(A,y,\"x[j + offset]\")};\n let f32scale = ${At(A,y,\"scale[j]\")};\n output[j + offset] = ${P[0].type.value}((f32input ${n?\"\":\"- mean\"}) * inv_std_dev * f32scale\n ${a?`+ ${At(A,y,\"bias[j]\")}`:\"\"}\n );\n }\n\n ${$?\"mean_data_output[global_idx] = mean\":\"\"};\n ${v?\"inv_std_output[global_idx] = inv_std_dev\":\"\"};\n }`},T=[{dims:l,dataType:e[0].dataType}];return $&&T.push({dims:_,dataType:1}),v&&T.push({dims:_,dataType:1}),{name:\"LayerNormalization\",shaderCache:{hint:`${y};${r};${n}`,inputDependencies:g},getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(p/64)},programUniforms:x}),getShaderSource:S}},Fl=(e,t)=>{nh(e.inputs),e.compute(oh(e.inputs,t,e.outputCount))}});var ih,jl,Kl=R(()=>{\"use strict\";oe();en();tn();ih=e=>{if(!e||e.length!==2)throw new Error(\"MatMul requires 2 inputs.\");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error(\"shared dimension does not match.\")},jl=e=>{ih(e.inputs);let t=et.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error(\"Can't use matmul on the given tensors\");let r=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];if(r<8&&n<8)e.compute(Jr(e.inputs,{activation:\"\"},t));else{let o=t[t.length-2],i=k.size(e.inputs[0].dims.slice(0,-2)),a=k.size(e.inputs[1].dims.slice(0,-2));if(i!==1&&o===1&&a===1){let l=e.inputs[0].reshape([1,i,n]),d=e.inputs[1].reshape([1,n,r]),p=[1,i,r],m=[l,d];e.compute(tr(m,{activation:\"\"},t,p),{inputs:m})}else e.compute(tr(e.inputs,{activation:\"\"},t))}}});var ah,sh,uh,Yl,Zl,Ql=R(()=>{\"use strict\";te();oe();Se();ae();ah=(e,t)=>{if(e.length<3||e.length>4)throw new Error(\"MatMulNBits requires 3 or 4 inputs\");let r=e[0],n=r.dims.length;if(r.dims[n-1]!==t.k)throw new Error(\"The last dim of input shape does not match the k value\");let o=Math.floor((t.k+t.blockSize-1)/t.blockSize),i=t.blockSize/8*t.bits,a=e[1];if(!k.areEqual(a.dims,[t.n,o,i]))throw new Error(\"The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize\");let d=e[2].dims;if(k.size(d)!==t.n*o)throw new Error(\"scales input size error.\");if(e.length===4){let m=e[3].dims,u=t.bits>4?t.n*o:t.n*Math.floor((o+1)/2);if(k.size(m)!==u)throw new Error(\"zeroPoints input size error.\")}},sh=(e,t)=>{let r=e[0].dims,n=r.length,o=r[n-2],i=t.k,a=t.n,l=r.slice(0,n-2),d=k.size(l),m=e[1].dims[2]/4,u=e[0].dataType,h=me(t.k),_=me(m),y=me(a),g=l.concat([o,a]),x=o>1&&a/y%2===0?2:1,$=k.size(g)/y/x,v=64,S=[],T=[d,o,i/h],C=k.convertShape(e[1].dims).slice();C.splice(-1,1,m/_),S.push(...N(T)),S.push(...N(C)),S.push(...N(e[2].dims)),e.length===4&&S.push(...N(k.convertShape(e[3].dims)));let A=[d,o,a/y];S.push(...N(A));let P=O=>{let U=T.length,G=E(\"a\",e[0].dataType,U,h),q=E(\"b\",12,C.length,_),K=E(\"scales\",e[2].dataType,e[2].dims.length),W=[G,q,K],Y=e.length===4?E(\"zero_points\",12,e[3].dims.length):void 0;Y&&W.push(Y);let se=A.length,X=M(\"output\",e[0].dataType,se,y),re=ye(e[0].dataType),ee=(()=>{switch(h){case 1:return`array<${re}, 8>`;case 2:return`mat4x2<${re}>`;case 4:return`mat2x4<${re}>`;default:throw new Error(`${h}-component is not supported.`)}})(),ne=()=>{let $e=`\n // reuse a data\n var input_offset = ${G.indicesToOffset(`${G.type.indices}(batch, row, word_offset)`)};\n var a_data: ${ee};\n for (var j: u32 = 0; j < ${8/h}; j++) {\n a_data[j] = ${G.getByOffset(\"input_offset\")};\n input_offset++;\n }\n `;for(let de=0;de> 4) & b_mask);\n b_quantized_values = ${ee}(${Array.from({length:4},(V,j)=>`${re}(b_value_lower[${j}]), ${re}(b_value_upper[${j}])`).join(\", \")});\n b_dequantized_values = ${(()=>h===1?`${ee}(${Array.from({length:8},(V,j)=>`(b_quantized_values[${j}] - ${Y?`zero_point${de}`:\"zero_point\"}) * scale${de}`).join(\", \")});`:`(b_quantized_values - ${ee}(${Array(8).fill(`${Y?`zero_point${de}`:\"zero_point\"}`).join(\",\")})) * scale${de};`)()};\n workgroup_shared[local_id.x * ${x} + ${Math.floor(de/y)}]${y>1?`[${de%y}]`:\"\"} += ${Array.from({length:8/h},(V,j)=>`${h===1?`a_data[${j}] * b_dequantized_values[${j}]`:`dot(a_data[${j}], b_dequantized_values[${j}])`}`).join(\" + \")};\n `;return $e},ve=()=>{let $e=`\n var col_index = col * ${y};\n ${Y?`\n let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2;\n var zero_point_byte_count: u32;\n var zero_point_word_index: u32;\n var zero_point_byte_offset: u32;\n let zero_point_nibble_offset: u32 = block & 0x1u;\n var zero_point_bits_offset: u32;\n var zero_point_word: u32;`:`\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${re}(8);`}\n `;for(let de=0;de> 0x1u);\n zero_point_word_index = zero_point_byte_count >> 0x2u;\n zero_point_byte_offset = zero_point_byte_count & 0x3u;\n zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n zero_point_word = ${Y.getByOffset(\"zero_point_word_index\")} >> zero_point_bits_offset;\n let zero_point${de} = ${re}((zero_point_word) & 0xFu);`:\"\"}\n col_index += 1;`;return $e},Be=()=>{let $e=`col_index = col * ${y};`;for(let de=0;de;\n var b_value_upper: vec4;\n var b_quantized_values: ${ee};\n var b_dequantized_values: ${ee};`,$e};return`\n var workgroup_shared: array<${X.type.value}, ${x*v}>;\n ${O.declareVariables(...W,X)}\n ${O.mainStart([v,1,1])}\n let output_indices = ${X.offsetToIndices(`(global_idx / ${v}) * ${x}`)};\n let col = output_indices[2];\n let row = output_indices[1];\n let batch = output_indices[0];\n let nBlocksPerCol = uniforms.b_shape[1];\n\n for (var block = local_id.x; block < nBlocksPerCol; block += ${v}) {\n //process one block\n var word_offset: u32 = block * ${t.blockSize/h};\n ${ve()}\n for (var word: u32 = 0; word < ${m}; word += ${_}) {\n ${Be()}\n for (var i: u32 = 0; i < ${_}; i++) {\n ${ne()}\n word_offset += ${8/h};\n }\n }\n }\n workgroupBarrier();\n\n if (local_id.x < ${x}) {\n var output_value: ${X.type.value} = ${X.type.value}(0);\n var workgroup_shared_offset: u32 = local_id.x;\n for (var b: u32 = 0u; b < ${v}u; b++) {\n output_value += workgroup_shared[workgroup_shared_offset];\n workgroup_shared_offset += ${x};\n }\n ${X.setByIndices(`${X.type.indices}(batch, row, col + local_id.x)`,\"output_value\")};\n }\n }`};return{name:\"MatMulNBits\",shaderCache:{hint:`${t.blockSize};${t.bits};${h};${_};${y};${x};${v}`,inputDependencies:Array(e.length).fill(\"rank\")},getRunData:()=>({outputs:[{dims:g,dataType:u}],dispatchGroup:{x:$},programUniforms:S}),getShaderSource:P}},uh=(e,t)=>{let r=e[0].dims,n=r.length,o=r[n-2],i=t.k,a=t.n,l=r.slice(0,n-2),d=k.size(l),m=e[1].dims[2]/4,u=e[0].dataType,h=me(t.k),_=me(m),y=l.concat([o,a]),g=128,x=a%8===0?8:a%4===0?4:1,$=g/x,v=$*_*8,S=v/h,T=v/t.blockSize,C=k.size(y)/x,A=[],P=[d,o,i/h],O=k.convertShape(e[1].dims).slice();O.splice(-1,1,m/_),A.push(...N(P)),A.push(...N(O)),A.push(...N(e[2].dims)),e.length===4&&A.push(...N(k.convertShape(e[3].dims)));let U=[d,o,a];A.push(...N(U));let G=q=>{let K=P.length,W=E(\"a\",e[0].dataType,K,h),Y=E(\"b\",12,O.length,_),se=E(\"scales\",e[2].dataType,e[2].dims.length),X=[W,Y,se],re=e.length===4?E(\"zero_points\",12,e[3].dims.length):void 0;re&&X.push(re);let ee=U.length,ne=M(\"output\",e[0].dataType,ee),ve=ye(e[0].dataType),Be=()=>{switch(h){case 1:return`\n let a_data0 = vec4<${ve}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]);\n let a_data1 = vec4<${ve}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return`\n let a_data0 = vec4<${ve}>(sub_a[word_offset], sub_a[word_offset + 1]);\n let a_data1 = vec4<${ve}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return`\n let a_data0 = sub_a[word_offset];\n let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${h}-component is not supported.`)}};return`\n var sub_a: array<${W.type.value}, ${S}>;\n var inter_results: array, ${x}>;\n ${q.declareVariables(...X,ne)}\n ${q.mainStart([$,x,1])}\n let output_indices = ${ne.offsetToIndices(`workgroup_index * ${x}`)};\n let col = output_indices[2];\n let row = output_indices[1];\n let batch = output_indices[0];\n let n_blocks_per_col = uniforms.b_shape[1];\n let num_tiles = (n_blocks_per_col - 1) / ${T} + 1;\n\n // Loop over shared dimension.\n for (var tile: u32 = 0; tile < num_tiles; tile += 1) {\n let a_col_start = tile * ${S};\n // load one tile A data into shared memory.\n for (var a_offset = local_idx; a_offset < ${S}; a_offset += ${g})\n {\n let a_col = a_col_start + a_offset;\n if (a_col < uniforms.a_shape[2])\n {\n sub_a[a_offset] = ${W.getByIndices(`${W.type.indices}(batch, row, a_col)`)};\n } else {\n sub_a[a_offset] = ${W.type.value}(0);\n }\n }\n workgroupBarrier();\n\n // each thread process one block\n let b_row = col + local_id.y;\n let block = tile * ${T} + local_id.x;\n ${re?`\n let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2;\n let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u);\n let zero_point_word_index = zero_point_byte_count >> 0x2u;\n let zero_point_byte_offset = zero_point_byte_count & 0x3u;\n let zero_point_nibble_offset: u32 = block & 0x1u;\n let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n let zero_point_word = ${re.getByOffset(\"zero_point_word_index\")} >> zero_point_bits_offset;\n let zero_point = ${ve}((zero_point_word) & 0xFu);`:`\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${ve}(8);`}\n let scale = ${se.getByOffset(\"b_row * n_blocks_per_col + block\")};\n let b_data = ${Y.getByIndices(`${Y.type.indices}(b_row, block, 0)`)};\n var word_offset = local_id.x * ${t.blockSize/h};\n for (var i: u32 = 0; i < ${_}; i++) {\n ${Be()}\n let b_value = ${_===1?\"b_data\":\"b_data[i]\"};\n let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu);\n let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu);\n let b_quantized_values = mat2x4<${ve}>(${Array.from({length:4},($e,de)=>`${ve}(b_value_lower[${de}]), ${ve}(b_value_upper[${de}])`).join(\", \")});\n let b_dequantized_values = (b_quantized_values - mat2x4<${ve}>(${Array(8).fill(\"zero_point\").join(\",\")})) * scale;\n inter_results[local_id.y][local_id.x] += ${Array.from({length:2},($e,de)=>`${`dot(a_data${de}, b_dequantized_values[${de}])`}`).join(\" + \")};\n word_offset += ${8/h};\n }\n workgroupBarrier();\n }\n\n if (local_idx < ${x}) {\n var output_value: ${ne.type.value} = ${ne.type.value}(0);\n for (var b = 0u; b < ${$}; b++) {\n output_value += inter_results[local_idx][b];\n }\n if (col + local_idx < uniforms.output_shape[2])\n {\n ${ne.setByIndices(`${ne.type.indices}(batch, row, col + local_idx)`,\"output_value\")}\n }\n }\n }`};return{name:\"BlockwiseMatMulNBits32\",shaderCache:{hint:`${t.blockSize};${h};${_};${$};${x}`,inputDependencies:Array(e.length).fill(\"rank\")},getRunData:()=>({outputs:[{dims:y,dataType:u}],dispatchGroup:{x:C},programUniforms:A}),getShaderSource:G}},Yl=(e,t)=>{ah(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor(\"intel\")&&e.adapterInfo.isArchitecture(\"gen-12lp\")?e.compute(uh(e.inputs,t)):e.compute(sh(e.inputs,t))},Zl=e=>J(e)});var lh,dh,ch,ph,mh,fh,hh,gh,Xl,Jl=R(()=>{\"use strict\";te();oe();ae();lh=e=>{if(!e||e.length<1)throw new Error(\"Too few inputs\");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error(\"Input type must be float or float16.\");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error(\"The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].\")}},dh=(e,t,r)=>{let n=\"\";for(let o=t-1;o>=0;--o)n+=`\n k = i32(${e.indicesGet(\"indices\",o)}) - ${F(\"uniforms.pads\",o,r)};\n if (k < 0) {\n break;\n }\n if (k >= i32(${F(\"uniforms.x_shape\",o,t)})) {\n break;\n }\n offset += k * i32(${F(\"uniforms.x_strides\",o,t)});\n `;return`\n value = ${e.type.value}(uniforms.constant_value);\n for (var i = 0; i < 1; i++) {\n var offset = 0;\n var k = 0;\n ${n}\n value = x[offset];\n }\n `},ch=(e,t,r)=>{let n=\"\";for(let o=t-1;o>=0;--o)n+=`\n k = i32(${e.indicesGet(\"indices\",o)}) - ${F(\"uniforms.pads\",o,r)};\n if (k < 0) {\n k = -k;\n }\n {\n let _2n_1 = 2 * (i32(${F(\"uniforms.x_shape\",o,t)}) - 1);\n k = k % _2n_1;\n if(k >= i32(${F(\"uniforms.x_shape\",o,t)})) {\n k = _2n_1 - k;\n }\n }\n offset += k * i32(${F(\"uniforms.x_strides\",o,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${n}\n value = x[offset];\n `},ph=(e,t,r)=>{let n=\"\";for(let o=t-1;o>=0;--o)n+=`\n k = i32(${e.indicesGet(\"indices\",o)}) - ${F(\"uniforms.pads\",o,r)};\n if (k < 0) {\n k = 0;\n }\n if (k >= i32(${F(\"uniforms.x_shape\",o,t)})) {\n k = i32(${F(\"uniforms.x_shape\",o,t)}) - 1;\n }\n offset += k * i32(${F(\"uniforms.x_strides\",o,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${n}\n value = x[offset];\n `},mh=(e,t,r)=>{let n=\"\";for(let o=t-1;o>=0;--o)n+=`\n k = i32(${e.indicesGet(\"indices\",o)}) - ${F(\"uniforms.pads\",o,r)};\n if (k < 0) {\n k += i32(${F(\"uniforms.x_shape\",o,t)}]);\n }\n if (k >= i32(${F(\"uniforms.x_shape\",o,t)})) {\n k -= i32(${F(\"uniforms.x_shape\",o,t)});\n }\n offset += k * i32(${F(\"uniforms.x_strides\",o,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${n}\n value = x[offset];\n `},fh=(e,t,r)=>{switch(r.mode){case 0:return dh(e,t,r.pads.length);case 1:return ch(e,t,r.pads.length);case 2:return ph(e,t,r.pads.length);case 3:return mh(e,t,r.pads.length);default:throw new Error(\"Invalid mode\")}},hh=(e,t)=>{let r=k.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,o=k.size(r),i=[{type:12,data:o},{type:6,data:t.pads}],a=e.length>=3&&e[2].data;t.mode===0&&i.push({type:a?e[2].dataType:1,data:t.value}),i.push(...N(e[0].dims,r));let l=[\"rank\"],d=p=>{let m=M(\"output\",e[0].dataType,r.length),u=E(\"x\",e[0].dataType,n.length),h=u.type.value,_=fh(m,n.length,t),y=[{name:\"output_size\",type:\"u32\"},{name:\"pads\",type:\"i32\",length:t.pads.length}];return t.mode===0&&y.push({name:\"constant_value\",type:a?h:\"f32\"}),`\n ${p.registerUniforms(y).declareVariables(u,m)}\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n\n let indices = ${m.offsetToIndices(\"global_idx\")};\n\n var value = ${h}(0);\n ${_}\n output[global_idx] = value;\n }`};return{name:\"Pad\",shaderCache:{hint:`${t.mode}${a}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k.size(r)/64)},programUniforms:i}),getShaderSource:d}},gh=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,i=new Int32Array(2*o).fill(0);if(e.length>=4){let l=e[3].getBigInt64Array();for(let d=0;di[Number(d)]=Number(l));let a=[];return i.forEach(l=>a.push(l)),{mode:t.mode,value:n,pads:a}}else return t},Xl=(e,t)=>{lh(e.inputs);let r=gh(e.inputs,t);e.compute(hh(e.inputs,r),{inputs:[0]})}});var on,ed,td,rd,nd,bh,yh,od,id,ad,sd,ud,ld,dd,cd,pd,md,fd,hd,gd=R(()=>{\"use strict\";We();te();oe();ae();on=e=>{if(we.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error(\"Pool ops requires 1 input.\")},ed=(e,t,r)=>{let n=t.format===\"NHWC\",o=e.dims.slice();n&&o.splice(1,0,o.pop());let i=Object.hasOwnProperty.call(t,\"dilations\"),a=t.kernelShape.slice(),l=t.strides.slice(),d=i?t.dilations.slice():[],p=t.pads.slice();It.adjustPoolAttributes(r,o,a,l,d,p);let m=It.computePoolOutputShape(r,o,l,d,a,p,t.autoPad),u=Object.assign({},t);i?Object.assign(u,{kernelShape:a,strides:l,pads:p,dilations:d,cacheKey:t.cacheKey}):Object.assign(u,{kernelShape:a,strides:l,pads:p,cacheKey:t.cacheKey});let h=m.slice();return h.push(h.splice(1,1)[0]),[u,n?h:m]},td=(e,t)=>{let r=t.format===\"NHWC\",n=k.size(e),o=k.size(t.kernelShape),i=[{type:12,data:n},{type:12,data:o}],a=[{name:\"outputSize\",type:\"u32\"},{name:\"kernelSize\",type:\"u32\"}];if(t.kernelShape.length<=2){let l=t.kernelShape[t.kernelShape.length-1],d=t.strides[t.strides.length-1],p=t.pads[t.pads.length/2-1],m=t.pads[t.pads.length-1],u=!!(p+m);i.push({type:12,data:l},{type:12,data:d},{type:12,data:p},{type:12,data:m}),a.push({name:\"kw\",type:\"u32\"},{name:\"sw\",type:\"u32\"},{name:\"pwStart\",type:\"u32\"},{name:\"pwEnd\",type:\"u32\"});let h=!1;if(t.kernelShape.length===2){let _=t.kernelShape[t.kernelShape.length-2],y=t.strides[t.strides.length-2],g=t.pads[t.pads.length/2-2],x=t.pads[t.pads.length-2];h=!!(g+x),i.push({type:12,data:_},{type:12,data:y},{type:12,data:g},{type:12,data:x}),a.push({name:\"kh\",type:\"u32\"},{name:\"sh\",type:\"u32\"},{name:\"phStart\",type:\"u32\"},{name:\"phEnd\",type:\"u32\"})}return[i,a,!0,u,h]}else{if(r)throw new Error(\"Pooling with kernelShape.length > 2 is not supported for NHWC format.\");let l=k.computeStrides(t.kernelShape);i.push({type:12,data:l},{type:12,data:t.pads},{type:12,data:t.strides}),a.push({name:\"kernelStrides\",type:\"u32\",length:l.length},{name:\"pads\",type:\"u32\",length:t.pads.length},{name:\"strides\",type:\"u32\",length:t.strides.length});let d=t.pads.reduce((p,m)=>p+m);return[i,a,!!d,!1,!1]}},rd=(e,t,r,n,o,i,a,l,d,p,m,u)=>{let h=o.format===\"NHWC\",_=t.type.value,y=M(\"output\",t.type.tensor,n);if(o.kernelShape.length<=2){let g=\"\",x=\"\",$=\"\",v=r-(h?2:1);if(m?g=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i;\n if (xIndices[${v}] < 0 || xIndices[${v}]\n >= uniforms.x_shape[${v}]) {\n pad++;\n continue;\n }\n let x_val = x[${t.indicesToOffset(\"xIndices\")}];\n ${i}\n }`:g=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i;\n let x_val = x[${t.indicesToOffset(\"xIndices\")}];\n ${i}\n }`,o.kernelShape.length===2){let T=r-(h?3:2);u?x=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j;\n if (xIndices[${T}] < 0 || xIndices[${T}] >= uniforms.x_shape[${T}]) {\n pad += i32(uniforms.kw);\n continue;\n }\n `:x=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j;\n `,$=`\n }\n `}return`\n ${e.registerUniforms(d).declareVariables(t,y)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n\n let indices = ${y.offsetToIndices(\"global_idx\")};\n var xIndices = ${y.offsetToIndices(\"global_idx\")};\n\n var value = ${_}(${l});\n var pad = 0;\n ${x}\n ${g}\n ${$}\n ${a}\n\n output[global_idx] = value;\n }`}else{if(h)throw new Error(\"Pooling with kernelShape.length > 2 is not supported for NHWC format.\");let g=o.kernelShape.length,x=o.pads.length,$=\"\";return p?$=`\n if (xIndices[j] >= uniforms.x_shape[j]) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n let x_val = x[${t.indicesToOffset(\"xIndices\")}];\n ${i}\n }`:$=`\n }\n let x_val = x[${t.indicesToOffset(\"xIndices\")}];\n ${i}\n `,`\n ${e.registerUniforms(d).declareVariables(t,y)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n let indices = ${y.offsetToIndices(\"global_idx\")};\n var xIndices = ${y.offsetToIndices(\"global_idx\")};\n\n var offsets: array;\n\n var value = ${_}(${l});\n var pad = 0;\n var isPad = false;\n\n for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {\n var offset = i;\n for (var j = 0u; j < ${g-1}u; j++) {\n offsets[j] = offset / ${F(\"uniforms.kernelStrides\",\"j\",g)};\n offset -= offsets[j] * ${F(\"uniforms.kernelStrides\",\"j\",g)};\n }\n offsets[${g-1}] = offset;\n\n isPad = false;\n for (var j = ${r-g}u; j < ${r}u; j++) {\n xIndices[j] = indices[j] * ${F(\"uniforms.strides\",`j - ${r-g}u`,g)}\n + offsets[j - ${r-g}u] - ${F(\"uniforms.pads\",\"j - 2u\",x)};\n ${$}\n }\n ${a}\n\n output[global_idx] = value;\n }`}},nd=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,bh=e=>`${nd(e)};${e.countIncludePad}`,yh=e=>`${nd(e)};${e.storageOrder};${e.dilations}`,od=e=>({format:e.format,autoPad:[\"NOTSET\",\"VALID\",\"SAME_UPPER\",\"SAME_LOWER\"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),id=(e,t,r,n)=>{let[o,i]=ed(t,n,r),a=E(\"x\",t.dataType,t.dims.length),l=a.type.value,d=\"value += x_val;\",p=\"\";o.countIncludePad?p+=`value /= ${l}(uniforms.kernelSize);`:p+=`value /= ${l}(i32(uniforms.kernelSize) - pad);`;let[m,u,h,_,y]=td(i,o);m.push(...N(t.dims,i));let g=[\"rank\"];return{name:e,shaderCache:{hint:`${n.cacheKey};${h};${_};${y}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(k.size(i)/64)},programUniforms:m}),getShaderSource:x=>rd(x,a,t.dims.length,i.length,o,d,p,0,u,h,_,y)}},ad=e=>{let t=e.count_include_pad!==0,r=od(e);if(r.ceilMode!==0)throw new Error(\"using ceil() in shape computation is not yet supported for AveragePool\");let n={countIncludePad:t,...r,cacheKey:\"\"};return{...n,cacheKey:bh(n)}},sd=(e,t)=>{on(e.inputs),e.compute(id(\"AveragePool\",e.inputs[0],!1,t))},ud={autoPad:\"\",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},ld=e=>{let t=e.format;return{format:t,...ud,cacheKey:t}},dd=(e,t)=>{on(e.inputs),e.compute(id(\"GlobalAveragePool\",e.inputs[0],!0,t))},cd=(e,t,r,n)=>{let[o,i]=ed(t,n,r),a=`\n value = max(x_val, value);\n `,l=\"\",d=E(\"x\",t.dataType,t.dims.length),p=[\"rank\"],[m,u,h,_,y]=td(i,o);return m.push(...N(t.dims,i)),{name:e,shaderCache:{hint:`${n.cacheKey};${h};${_};${y}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(k.size(i)/64)},programUniforms:m}),getShaderSource:g=>rd(g,d,t.dims.length,i.length,o,a,l,t.dataType===10?-65504:-1e5,u,h,_,y)}},pd=(e,t)=>{on(e.inputs),e.compute(cd(\"MaxPool\",e.inputs[0],!1,t))},md=e=>{let t=e.storage_order,r=e.dilations,n=od(e);if(t!==0)throw new Error(\"column major storage order is not yet supported for MaxPool\");if(n.ceilMode!==0)throw new Error(\"using ceil() in shape computation is not yet supported for MaxPool\");let o={storageOrder:t,dilations:r,...n,cacheKey:\"\"};return{...o,cacheKey:yh(o)}},fd=e=>{let t=e.format;return{format:t,...ud,cacheKey:t}},hd=(e,t)=>{on(e.inputs),e.compute(cd(\"GlobalMaxPool\",e.inputs[0],!0,t))}});var wh,vh,bd,yd,_d=R(()=>{\"use strict\";te();oe();Se();ae();wh=(e,t)=>{if(e.length<2||e.length>3)throw new Error(\"DequantizeLinear requires 2 or 3 inputs.\");if(e.length===3&&e[1].dims===e[2].dims)throw new Error(\"x-scale and x-zero-point must have the same shape.\");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error(\"x and x-zero-point must have the same data type.\");if(e[0].dataType===6&&e.length>2)throw new Error(\"In the case of dequantizing int32 there is no zero point.\");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error(\"scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.\");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error(\"x and x-zero-point must have the same data type.\");if(e[1].dims.length!==e[2].dims.length)throw new Error(\"scale and zero-point inputs must have the same rank.\");if(!e[1].dims.map((r,n)=>r===e[2].dims[n]).reduce((r,n)=>r&&n,!0))throw new Error(\"scale and zero-point inputs must have the same shape.\")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error(\"blockSize must be set only for block quantization.\");if(!e[1].dims.map((o,i)=>i===t.axis||o===e[0].dims[i]).reduce((o,i)=>o&&i,!0))throw new Error(\"For block qunatization, scale input shape to match the input shape except for the axis\");if(e[1].dims.length!==e[0].dims.length)throw new Error(\"For block qunatization the scale input rank must be the same as the x rank.\");let r=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(n-1)-1))throw new Error(\"blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].\")}},vh=(e,t)=>{let r=k.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,o=n===3,i=e[0].dims,a=e[1].dataType,l=k.size(i),d=n===3||n===2,p=d?[Math.ceil(k.size(e[0].dims)/4)]:e[0].dims,m=e[1].dims,u=e.length>2?e[2]:void 0,h=u?d?[Math.ceil(k.size(u.dims)/4)]:u.dims:void 0,_=m.length===0||m.length===1&&m[0]===1,y=_===!1&&m.length===1,g=me(l),x=_&&(!d||g===4),$=x?g:1,v=x&&!d?g:1,S=E(\"input\",d?12:n,p.length,v),T=E(\"scale\",a,m.length),C=u?E(\"zero_point\",d?12:n,h.length):void 0,A=M(\"output\",a,i.length,$),P=[S,T];C&&P.push(C);let O=[p,m];u&&O.push(h);let U=[{type:12,data:l/$},{type:12,data:r},{type:12,data:t.blockSize},...N(...O,i)],G=q=>{let K=[{name:\"output_size\",type:\"u32\"},{name:\"axis\",type:\"u32\"},{name:\"block_size\",type:\"u32\"}];return`\n ${q.registerUniforms(K).declareVariables(...P,A)}\n ${q.mainStart()}\n ${q.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let output_indices = ${A.offsetToIndices(\"global_idx\")};\n\n // Set input x\n ${(()=>d?`\n let input = ${S.getByOffset(\"global_idx / 4\")};\n let x_vec = ${o?\"unpack4xI8(input)\":\"unpack4xU8(input)\"};\n let x_value = ${$===1?\"x_vec[global_idx % 4]\":\"x_vec\"};`:`let x_value = ${S.getByOffset(\"global_idx\")};`)()};\n\n // Set scale input\n ${(()=>_?`let scale_value= ${T.getByOffset(\"0\")}`:y?`\n let scale_index = ${A.indicesGet(\"output_indices\",\"uniforms.axis\")};\n let scale_value= ${T.getByOffset(\"scale_index\")};`:`\n var scale_indices: ${T.type.indices} = output_indices;\n let index = ${T.indicesGet(\"scale_indices\",\"uniforms.axis\")} / uniforms.block_size;\n ${T.indicesSet(\"scale_indices\",\"uniforms.axis\",\"index\")};\n let scale_value= ${T.getByIndices(\"scale_indices\")};`)()};\n\n // Set zero-point input\n ${(()=>C?_?d?`\n let zero_point_input = ${C.getByOffset(\"0\")};\n let zero_point_vec = ${o?\"unpack4xI8(zero_point_input)\":\"unpack4xU8(zero_point_input)\"};\n let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${C.getByOffset(\"0\")}`:y?d?`\n let zero_point_index = ${A.indicesGet(\"output_indices\",\"uniforms.axis\")};\n let zero_point_input = ${C.getByOffset(\"zero_point_index / 4\")};\n let zero_point_vec = ${o?\"unpack4xI8(zero_point_input)\":\"unpack4xU8(zero_point_input)\"};\n let zero_point_value = zero_point_vec[zero_point_index % 4]`:`\n let zero_point_index = ${A.indicesGet(\"output_indices\",\"uniforms.axis\")};\n let zero_point_value = ${C.getByOffset(\"zero_point_index\")};`:d?`\n let zero_point_offset = ${T.indicesToOffset(\"scale_indices\")};\n let zero_point_input = ${C.getByOffset(\"zero_point_offset / 4\")};\n let zero_point_vec = ${o?\"unpack4xI8(zero_point_input)\":\"unpack4xU8(zero_point_input)\"};\n let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${C.getByIndices(\"scale_indices\")};`:`let zero_point_value = ${d?o?\"i32\":\"u32\":S.type.value}(0);`)()};\n // Compute and write output\n ${A.setByOffset(\"global_idx\",`${A.type.value}(x_value - zero_point_value) * scale_value`)};\n }`};return{name:\"DequantizeLinear\",shaderCache:{hint:t.cacheKey,inputDependencies:C?[\"rank\",\"rank\",\"rank\"]:[\"rank\",\"rank\"]},getShaderSource:G,getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:Math.ceil(l/$/64),y:1,z:1},programUniforms:U})}},bd=(e,t)=>{wh(e.inputs,t),e.compute(vh(e.inputs,t))},yd=e=>J({axis:e.axis,blockSize:e.blockSize})});var $h,xh,wd,vd=R(()=>{\"use strict\";We();te();ae();$h=(e,t,r)=>{let n=e===t,o=et&&r>0;if(n||o||i)throw new Error(\"Range these inputs' contents are invalid.\")},xh=(e,t,r,n)=>{let o=Math.abs(Math.ceil((t-e)/r)),i=[o],a=o,l=[{type:12,data:a},{type:n,data:e},{type:n,data:r},...N(i)],d=p=>{let m=M(\"output\",n,i.length),u=m.type.value,h=[{name:\"outputSize\",type:\"u32\"},{name:\"start\",type:u},{name:\"delta\",type:u}];return`\n ${p.registerUniforms(h).declareVariables(m)}\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n output[global_idx] = uniforms.start + ${u}(global_idx) * uniforms.delta;\n }`};return{name:\"Range\",shaderCache:{hint:`${n}`},getShaderSource:d,getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l})}},wd=e=>{let t=0,r=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),we.webgpu.validateInputContent&&$h(t,r,n),e.compute(xh(t,r,n,e.inputs[0].dataType),{inputs:[]})}});var Sh,Th,$d,xd,Sd=R(()=>{\"use strict\";te();oe();Se();ae();Sh=(e,t,r,n)=>{if(e!==\"none\"&&n!==\"i32\"&&n!==\"u32\"&&n!==\"f32\")throw new Error(`Input ${n} is not supported with reduction ${e}.`);let o=`{\n var oldValue = 0;\n loop {\n let newValueF32 =`,i=`;\n let newValue = bitcast(newValueF32);\n let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue);\n if res.exchanged {\n break;\n }\n oldValue = res.old_value;\n }\n }`;switch(e){case\"none\":return`${t}=${r};`;case\"add\":return n===\"i32\"||n===\"u32\"?`atomicAdd(&${t}, bitcast<${n}>(${r}));`:`\n ${o}bitcast<${n}>(oldValue) + (${r})${i}`;case\"max\":return n===\"i32\"||n===\"u32\"?`atomicMax(&${t}, bitcast<${n}>(${r}));`:`\n ${o}max(bitcast(oldValue), (${r}))${i}`;case\"min\":return n===\"i32\"||n===\"u32\"?`atomicMin(&${t}, bitcast<${n}>(${r}));`:`${o}min(bitcast<${n}>(oldValue), (${r}))${i}`;case\"mul\":return`${o}(bitcast<${n}>(oldValue) * (${r}))${i}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Th=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r,i=1,a=Math.ceil(k.size(n)/i),l=n[n.length-1],d=k.sizeFromDimension(r,l),p=[{type:12,data:a},{type:12,data:l},{type:12,data:d},...N(e[1].dims,e[2].dims,o)],m=u=>{let h=E(\"indices\",e[1].dataType,e[1].dims.length),_=E(\"updates\",e[2].dataType,e[2].dims.length,i),y=t.reduction!==\"none\"&&t.reduction!==\"\"?es(\"output\",e[0].dataType,o.length):M(\"output\",e[0].dataType,o.length,i);return`\n ${u.registerUniform(\"output_size\",\"u32\").registerUniform(\"last_index_dimension\",\"u32\").registerUniform(\"num_updates_elements\",\"u32\").declareVariables(h,_,y)}\n ${u.mainStart()}\n ${u.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n var data_offset = 0u;\n let indices_start = uniforms.last_index_dimension * global_idx;\n let indices_end = indices_start + uniforms.last_index_dimension;\n for (var i = indices_start; i < indices_end; i++) {\n var index = i32(indices[i].x);\n ${e[0].dims.length===1?`\n let element_count_dim = uniforms.output_strides;\n let dim_value = uniforms.output_shape;`:`\n let element_count_dim = uniforms.output_strides[i - indices_start];\n let dim_value = uniforms.output_shape[i - indices_start + uniforms.last_index_dimension];`}\n if (index >= 0) {\n if (index >= i32(dim_value)) {\n index = i32(dim_value - 1);\n }\n } else {\n if (index < -i32(dim_value)) {\n index = 0;\n } else {\n index += i32(dim_value);\n }\n }\n data_offset += u32((u32(index) * element_count_dim));\n }\n\n for (var i = 0u; i < uniforms.num_updates_elements; i++) {\n let value = updates[uniforms.num_updates_elements * global_idx + i];\n ${Sh(t.reduction,\"output[data_offset + i]\",\"value\",y.type.value)}\n }\n\n }`};return{name:\"ScatterND\",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:[\"rank\",\"rank\"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p}),getShaderSource:m}},$d=e=>J({reduction:e.reduction}),xd=(e,t)=>{e.compute(Th(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}});var Ih,Ch,Ah,kh,Eh,Ph,zh,Oh,Bh,Dh,Mh,Td,Rh,Uh,Nh,Vh,Wh,Id,Cd,Ad=R(()=>{\"use strict\";te();oe();Se();ae();Ih=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error(\"Resize requires scales input values to be positive\")})),e.length>0){if(t.mode===\"linear\"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and\n one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode===\"cubic\"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error(\"Resize requires scales input size to be 2 or 4 for cubic mode\")}},Ch=(e,t,r)=>{t.every(o=>o>=0&&o{throw new Error(\"Resize requires axes input values to be positive and less than rank\")}));let n=new Array(r).fill(1);return t.forEach((o,i)=>n[o]=e[i]),n},Ah=(e,t,r,n,o,i)=>{let[a,l,d]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],p=e[0].dims.length;if(a>0&&e.length>a&&e[a].dims.length>0)e[a].getFloat32Array().forEach(m=>i.push(m));else if(t.coordinateTransformMode===\"tf_crop_and_resize\")throw new Error(\"Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize\");if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0){if(e[l].getFloat32Array().forEach(m=>n.push(m)),n.length!==0&&n.length!==p&&r>=18&&n.length!==t.axes.length)throw new Error(\"Resize requires scales input size to be same as input rank or axes size for opset 18 and up\");Ih(n,t),t.axes.length>0&&Ch(n,t.axes,p).forEach((m,u)=>n[u]=m)}if(d>0&&e.length>d&&e[d].dims.length===1&&e[d].dims[0]>0&&(e[d].getBigInt64Array().forEach(m=>o.push(Number(m))),o.length!==0&&o.length!==p&&r>=18&&o.length!==t.axes.length))throw new Error(\"Resize requires sizes input size to be same as input rank or axes size for opset 18 and up\");if(t.axes.length>0){if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires \"scales\" input size to be of axes rank when axes attributes is specified');if(o.length!==0&&o.length!==t.axes.length)throw new Error('Resize requires \"sizes\" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<\"u\"&&typeof o<\"u\"&&n.length>0&&o.length>p)throw new Error(\"Resize requires only of scales or sizes to be specified\")},kh=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,\n lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case\"asymmetric\":return`return ${t}(xResized) / ${t}(xScale);`;case\"pytorch_half_pixel\":return`if (lengthResized > 1) {\n return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;\n } else {\n return 0.0;\n }`;case\"tf_half_pixel_for_nn\":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case\"align_corners\":return`if (lengthResized == 1) {\n return 0.0;\n } else {\n // The whole part and the fractional part are calculated separately due to inaccuracy of floating\n // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an\n // offset-by-one error later in floor().\n let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1));\n let fract =\n ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1);\n return whole + fract;\n }`;case\"tf_crop_and_resize\":return`if (lengthResized > 1) {\n return ${t}(roiStart) * ${t}(lengthOriginal - 1) +\n (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /\n ${t}(lengthResized - 1);\n } else {\n return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);\n }`;case\"half_pixel_symmetric\":return`const outputWidth = ${t}xScale * ${t}(lengthResized);\n const adjustment = ${t}(lengthResized) / outputWidth;\n const center = ${t}(lengthOriginal) / 2;\n const offset = center * (1 - adjustment);\n return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case\"half_pixel\":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+\"}\",Eh=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case\"round_prefer_ceil\":return\"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }\";case\"floor\":return\"return floor(xOriginal);\";case\"ceil\":return\"return ceil(xOriginal);\";case\"round_prefer_floor\":return\"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }\";case\"simple\":default:if(t<11)return\"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }\";throw new Error(`Nearest mode ${e} is not supported`)}})()+\"}\",Ph=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),o=e.length===0?n:e.slice();return t.length>0?(t.forEach((i,a)=>{n[i]=o[a],n[a+r]=o[t.length+a]}),n):o},zh=(e,t,r,n)=>{let o=[];if(r.length>0)if(n.length>0){if(e.forEach(i=>o.push(i)),Math.max(...n)>e.length)throw new Error(\"axes is out of bound\");n.forEach((i,a)=>o[i]=r[a])}else r.forEach(i=>o.push(i));else{if(t.length===0)throw new Error(\"Resize requires either scales or sizes.\");o=e.map((i,a)=>Math.round(i*t[a]))}return o},Oh=(e,t,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case\"not_larger\":return r.axes.length>0?Math.min(...r.axes.map(i=>t[i]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case\"not_smaller\":return r.axes.length>0?Math.max(...r.axes.map(i=>t[i]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let o=e.slice();return r.axes.length>0?(r.axes.forEach(i=>t[i]=n),r.axes.forEach(i=>o[i]=Math.round(e[i]*t[i]))):(t.fill(n,0,t.length),o.forEach((i,a)=>o[a]=Math.round(i*t[a]))),o},Bh=(e,t,r,n,o)=>`\n fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> {\n var original_indices: array<${e.type.value}, ${r.length}>;\n for (var i:u32 = 0; i < ${r.length}; i++) {\n var output_index = ${e.indicesGet(\"output_indices\",\"i\")};\n var scale = ${F(\"uniforms.scales\",\"i\",n)};\n var roi_low = ${F(\"uniforms.roi\",\"i\",o)};\n var roi_hi = ${F(\"uniforms.roi\",`i + ${t.length}`,o)};\n if (scale == 1.0) {\n original_indices[i] = ${e.type.value}(output_index);\n } else {\n var input_shape_i = ${F(\"uniforms.input_shape\",\"i\",t.length)};\n var output_shape_i = ${F(\"uniforms.output_shape\",\"i\",r.length)};\n original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n }\n }\n return original_indices;\n }`,Dh=(e,t,r,n,o,i,a)=>`\n fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n for (var i:u32 = 0; i < ${n.length}; i++) {\n var output_index = ${t.indicesGet(\"output_indices\",\"i\")};\n var input_index: u32;\n var scale = ${F(\"uniforms.scales\",\"i\",o)};\n if (scale == 1.0) {\n input_index = output_index;\n } else {\n var roi_low = ${F(\"uniforms.roi\",\"i\",i)};\n var roi_hi = ${F(\"uniforms.roi\",`i + ${r.length}`,i)};\n var input_shape_i = ${F(\"uniforms.input_shape\",\"i\",r.length)};\n var output_shape_i = ${F(\"uniforms.output_shape\",\"i\",n.length)};\n var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n if (!${a} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {\n if (original_idx < 0) {\n input_index = 0;\n } else if (original_idx > ${t.type.value}(input_shape_i - 1)) {\n input_index = input_shape_i - 1;\n } else {\n input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));\n }\n } else {\n input_index = u32(original_idx);\n }\n }\n ${e.indicesSet(\"input_indices\",\"i\",\" input_index\")}\n }\n return input_indices;\n }`,Mh=(e,t)=>`\n fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {\n for (var i:u32 = 0; i < ${t.length}; i++) {\n var input_index = ${e.indicesGet(\"input_indices\",\"i\")};\n if (input_index < 0 || input_index >= ${F(\"uniforms.input_shape\",\"i\",t.length)}) {\n return false;\n }\n }\n return true;\n }`,Td=(e,t,r,n)=>e.rank>n?`\n ${e.indicesSet(\"input_indices\",t,\"channel\")};\n ${e.indicesSet(\"input_indices\",r,\"batch\")};\n`:\"\",Rh=(e,t,r,n,o)=>{let[a,l,d,p]=r.length===2?[-1,0,1,-1]:[0,2,3,1],m=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${m} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet(\"input_indices\",l,`max(0, min(row, ${r[l]} - 1))`)};\n ${e.indicesSet(\"input_indices\",d,`max(0, min(col, ${r[d]} - 1))`)};\n ${Td(e,p,a,2)}\n return ${e.getByIndices(\"input_indices\")};\n }\n\n fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${m} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var row:${m} = originalIndices[${l}];\n var col:${m} = originalIndices[${d}];\n ${n?`if (row < 0 || row > (${r[l]} - 1) || col < 0 || col > (${r[d]} - 1)) {\n return ${o};\n }`:\"\"};\n row = max(0, min(row, ${r[l]} - 1));\n col = max(0, min(col, ${r[d]} - 1));\n var row1: u32 = u32(row);\n var col1: u32 = u32(col);\n var row2: u32 = u32(row + 1);\n var col2: u32 = u32(col + 1);\n var channel: u32 = ${r.length>2?`u32(originalIndices[${p}])`:\"0\"};\n var batch: u32 = ${r.length>2?`u32(originalIndices[${a}])`:\"0\"};\n var x11: ${m} = getInputValue(batch, channel, row1, col1);\n var x12: ${m} = getInputValue(batch, channel, row1, col2);\n var x21: ${m} = getInputValue(batch, channel, row2, col1);\n var x22: ${m} = getInputValue(batch, channel, row2, col2);\n var dx1: ${m} = abs(row - ${m}(row1));\n var dx2: ${m} = abs(${m}(row2) - row);\n var dy1: ${m} = abs(col - ${m}(col1));\n var dy2: ${m} = abs(${m}(col2) - col);\n if (row1 == row2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (col1 == col2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);\n }`},Uh=(e,t,r,n,o,i,a,l,d,p)=>{let m=r.length===2,u=!0,[h,_]=m?[0,1]:u?[2,3]:[1,2],y=e.type.value,g=x=>{let $=x===h?\"row\":\"col\";return`\n fn ${$}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${y} {\n var output_index = ${t.indicesGet(\"output_indices\",x)};\n var originalIdx: ${y} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[x]},\n ${n[x]}, ${r[x]}, ${i[x]}, ${i[x]} + ${r.length});\n var fractOriginalIdx: ${y} = originalIdx - floor(originalIdx);\n var coefs = getCubicInterpolationCoefs(fractOriginalIdx);\n\n if (${l} && (originalIdx < 0 || originalIdx > (${r[x]} - 1))) {\n return ${d};\n }\n var data: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0);\n for (var i: i32 = -1; i < 3; i++) {\n var ${$}: ${y} = originalIdx + ${y}(i);\n if (${$} < 0 || ${$} >= ${r[x]}) {\n ${(()=>p?`coefs[i + 1] = 0.0;\n continue;`:l?`return ${d};`:`${$} = max(0, min(${$}, ${r[x]} - 1));`)()};\n }\n var input_indices_copy: ${e.type.indices} = input_indices;\n ${e.indicesSet(\"input_indices_copy\",x,`u32(${$})`)};\n data[i + 1] = ${x===h?e.getByIndices(\"input_indices_copy\"):\"rowCubicInterpolation(input_indices_copy, output_indices)\"};\n }\n return cubicInterpolation1D(data, coefs);\n }`};return`\n ${g(h)};\n ${g(_)};\n fn getCubicInterpolationCoefs(s: ${y}) -> array<${y}, 4> {\n var absS = abs(s);\n var coeffs: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0);\n var oneMinusAbsS: ${y} = 1.0 - absS;\n var twoMinusAbsS: ${y} = 2.0 - absS;\n var onePlusAbsS: ${y} = 1.0 + absS;\n coeffs[0] = ((${a} * onePlusAbsS - 5 * ${a}) * onePlusAbsS + 8 * ${a}) * onePlusAbsS - 4 * ${a};\n coeffs[1] = ((${a} + 2) * absS - (${a} + 3)) * absS * absS + 1;\n coeffs[2] = ((${a} + 2) * oneMinusAbsS - (${a} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;\n coeffs[3] = ((${a} * twoMinusAbsS - 5 * ${a}) * twoMinusAbsS + 8 * ${a}) * twoMinusAbsS - 4 * ${a};\n return coeffs;\n }\n\n fn cubicInterpolation1D(x: array<${y}, 4>, coefs: array<${y}, 4>) -> ${y} {\n var coefsSum: ${y} = coefs[0] + coefs[1] + coefs[2] + coefs[3];\n return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;\n }\n\n fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${y} {\n var input_indices: ${e.type.indices} = output_indices;\n return colCubicInterpolation(input_indices, output_indices);\n }\n `},Nh=(e,t,r,n,o)=>{let[a,l,d,p,m]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],u=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${u} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet(\"input_indices\",l,`max(0, min(depth, ${r[l]} - 1))`)};\n ${e.indicesSet(\"input_indices\",d,`max(0, min(height, ${r[d]} - 1))`)};\n ${e.indicesSet(\"input_indices\",p,`max(0, min(width, ${r[p]} - 1))`)};\n ${Td(e,m,a,3)}\n return ${e.getByIndices(\"input_indices\")};\n }\n\n fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${u} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var depth:${u} = originalIndices[${l}];\n var height:${u} = originalIndices[${d}];\n var width:${u} = originalIndices[${p}];\n ${n?`if (depth < 0 || depth > (${r[l]} - 1) || height < 0 || height > (${r[d]} - 1) || width < 0 || (width > ${r[p]} - 1)) {\n return ${o};\n }`:\"\"};\n\n depth = max(0, min(depth, ${r[l]} - 1));\n height = max(0, min(height, ${r[d]} - 1));\n width = max(0, min(width, ${r[p]} - 1));\n var depth1: u32 = u32(depth);\n var height1: u32 = u32(height);\n var width1: u32 = u32(width);\n var depth2: u32 = u32(depth + 1);\n var height2: u32 = u32(height + 1);\n var width2: u32 = u32(width + 1);\n var channel: u32 = ${r.length>3?`u32(originalIndices[${m}])`:\"0\"};\n var batch: u32 = ${r.length>3?`u32(originalIndices[${a}])`:\"0\"};\n\n var x111: ${u} = getInputValue(batch, channel, depth1, height1, width1);\n var x112: ${u} = getInputValue(batch, channel, depth1, height1, width2);\n var x121: ${u} = getInputValue(batch, channel, depth1, height2, width1);\n var x122: ${u} = getInputValue(batch, channel, depth1, height2, width2);\n var x211: ${u} = getInputValue(batch, channel, depth2, height1, width1);\n var x212: ${u} = getInputValue(batch, channel, depth2, height1, width2);\n var x221: ${u} = getInputValue(batch, channel, depth2, height2, width1);\n var x222: ${u} = getInputValue(batch, channel, depth2, height2, width2);\n var dx1: ${u} = abs(depth - ${u}(depth1));\n var dx2: ${u} = abs(${u}(depth2) - depth);\n var dy1: ${u} = abs(height - ${u}(height1));\n var dy2: ${u} = abs(${u}(height2) - height);\n var dz1: ${u} = abs(width - ${u}(width1));\n var dz2: ${u} = abs(${u}(width2) - width);\n if (depth1 == depth2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (height1 == height2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n if (width1 == width2) {\n dz1 = 0.5;\n dz2 = 0.5;\n }\n return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +\n x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);\n }`},Vh=(e,t,r,n,o,i)=>{let a=e.dims,l=Ph(i,t.axes,a.length),d=zh(a,n,o,t.axes),p=n.slice();n.length===0&&(p=a.map((v,S)=>v===0?1:d[S]/v),t.keepAspectRatioPolicy!==\"stretch\"&&(d=Oh(a,p,t)));let m=M(\"output\",e.dataType,d.length),u=E(\"input\",e.dataType,a.length),h=k.size(d),_=a.length===d.length&&a.every((v,S)=>v===d[S]),y=t.coordinateTransformMode===\"tf_crop_and_resize\",g=t.extrapolationValue,x=u.type.value,$=v=>`\n ${_?\"\":`\n ${kh(t.coordinateTransformMode,x)};\n ${(()=>{switch(t.mode){case\"nearest\":return`\n ${Mh(u,a)};\n ${Eh(t.nearestMode,r,x)};\n ${Dh(u,m,a,d,p.length,l.length,y)};\n `;case\"linear\":return`\n ${Bh(m,a,d,p.length,l.length)};\n ${(()=>{if(a.length===2||a.length===4)return`${Rh(u,m,a,y,g)}`;if(a.length===3||a.length===5)return`${Nh(u,m,a,y,g)}`;throw Error(\"Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.\")})()};\n `;case\"cubic\":return`\n ${(()=>{if(a.length===2||a.length===4)return`${Uh(u,m,a,d,p,l,t.cubicCoeffA,y,t.extrapolationValue,t.excludeOutside)}`;throw Error(\"Cubic mode only supports input dims 2 and 4 are supported in linear mode.\")})()};\n `;default:throw Error(\"Invalid resize mode\")}})()};\n `}\n ${v.registerUniform(\"output_size\",\"u32\").registerUniform(\"scales\",\"f32\",p.length).registerUniform(\"roi\",\"f32\",l.length).declareVariables(u,m)}\n ${v.mainStart()}\n ${v.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n ${_?\"output[global_idx] = input[global_idx];\":`\n let output_indices = ${m.offsetToIndices(\"global_idx\")};\n var input_indices: ${u.type.indices};\n ${(()=>{switch(t.mode){case\"nearest\":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);\n if (checkInputIndices(input_indices)) {\n output[global_idx] = ${u.getByIndices(\"input_indices\")};\n } else {\n output[global_idx] = ${t.extrapolationValue};\n }`;case\"linear\":return`output[global_idx] = ${a.length===2||a.length===4?\"bilinearInterpolation\":\"trilinearInterpolation\"}(output_indices);`;case\"cubic\":return\"output[global_idx] = bicubicInterpolation(output_indices);\";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};\n`}\n }`;return{name:\"Resize\",shaderCache:{hint:`${t.cacheKey}|${r}|${p.length>0?p:\"\"}|${o.length>0?o:\"\"}|${l.length>0?l:\"\"}|${_}|${a}`,inputDependencies:[\"rank\"]},getShaderSource:$,getRunData:()=>({outputs:[{dims:d,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:[{type:12,data:h},{type:1,data:p},{type:1,data:l},...N(a,d)]})}},Wh=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Id=(e,t)=>{let r=[],n=[],o=[],i=Wh(e);if(t.antialias!==0)throw Error(\"Only default value (0) for Antialias attribute is supported\");Ah(e.inputs,t,i,r,n,o),e.compute(Vh(e.inputs[0],t,i,r,n,o),{inputs:[0]})},Cd=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,o=e.cubicCoeffA,i=e.excludeOutside!==0,a=e.extrapolationValue,l=e.keepAspectRatioPolicy,d=e.mode,p=e.nearestMode===\"\"?\"simple\":e.nearestMode;return J({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:o,excludeOutside:i,extrapolationValue:a,keepAspectRatioPolicy:l,mode:d,nearestMode:p})}});var Lh,Gh,kd,Ed=R(()=>{\"use strict\";te();oe();Se();ae();Lh=(e,t)=>{let[r,n,o,i]=e,{numHeads:a,rotaryEmbeddingDim:l}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!k.areEqual(n.dims,[])&&!k.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(!k.areEqual(o.dims,i.dims))throw new Error(\"Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape\");if(l>0&&a===0)throw new Error(\"num_heads must be provided if rotary_embedding_dim is specified\");let d=r.dims[0],p=r.dims[r.dims.length-2],m=o.dims[0],u=k.sizeFromDimension(r.dims,1)/p,h=l===0?o.dims[1]*2:u/a;if(l>h)throw new Error(\"rotary_embedding_dim must be less than or equal to head_size\");if(n.dims.length===2){if(d!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(p!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(h/2!==o.dims[1]&&l/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(p>m)throw new Error(\"Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported\")},Gh=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:o,scale:i}=t,a=e[0].dims[0],l=k.sizeFromDimension(e[0].dims,1),d=e[0].dims[e[0].dims.length-2],p=l/d,m=e[2].dims[1],u=o===0?m*2:p/n,h=new Array(a,d,p/u,u-m),_=k.computeStrides(h),y=[{type:1,data:i},{type:12,data:h},{type:12,data:_},...e[0].dims.length===3?new Array({type:12,data:[l,p,u,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[l,u,d*u,1]}):[],...N(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],g=x=>{let $=E(\"input\",e[0].dataType,e[0].dims.length),v=E(\"position_ids\",e[1].dataType,e[1].dims.length),S=E(\"cos_cache\",e[2].dataType,e[2].dims.length),T=E(\"sin_cache\",e[3].dataType,e[3].dims.length),C=M(\"output\",e[0].dataType,e[0].dims.length);return x.registerUniforms([{name:\"scale\",type:\"f32\"},{name:\"global_shape\",type:\"u32\",length:h.length},{name:\"global_strides\",type:\"u32\",length:_.length},{name:\"input_output_strides\",type:\"u32\",length:_.length}]),`\n ${x.declareVariables($,v,S,T,C)}\n\n ${x.mainStart(Ct)}\n let half_rotary_emb_dim = uniforms.${S.name}_shape[1];\n let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;\n let size = uniforms.global_shape[0] * uniforms.global_strides[0];\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(\"size\")}\n\n if (bsnh[3] < half_rotary_emb_dim) {\n let position_ids_idx =\n ${v.broadcastedIndicesToOffset(\"bsnh.xy\",M(\"\",v.type.tensor,2))};\n let position_id =\n u32(${v.getByOffset(\"position_ids_idx\")}) + select(0, bsnh[1], position_ids_idx == 0);\n let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r});\n let j = i + select(half_rotary_emb_dim, 1, ${r});\n let re = ${$.getByOffset(\"i\")} * ${S.get(\"position_id\",\"bsnh[3]\")} -\n ${$.getByOffset(\"j\")} * ${T.get(\"position_id\",\"bsnh[3]\")};\n ${C.setByOffset(\"i\",\"re\")}\n let im = ${$.getByOffset(\"i\")} * ${T.get(\"position_id\",\"bsnh[3]\")} +\n ${$.getByOffset(\"j\")} * ${S.get(\"position_id\",\"bsnh[3]\")};\n ${C.setByOffset(\"j\",\"im\")}\n } else {\n let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;\n ${C.setByOffset(\"k\",$.getByOffset(\"k\"))}\n }\n }`};return{name:\"RotaryEmbedding\",shaderCache:{hint:J({interleaved:r}).cacheKey,inputDependencies:[\"rank\",\"rank\",\"rank\",\"rank\"]},getShaderSource:g,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k.size(h)/Ct)},programUniforms:y})}},kd=(e,t)=>{Lh(e.inputs,t),e.compute(Gh(e.inputs,t))}});var Hh,Fh,Pd,zd=R(()=>{\"use strict\";te();oe();ae();Hh=e=>{if(!e||e.length<3)throw new Error(\"layerNorm requires at least 3 inputs.\");let t=e[0],r=e[1],n=e[2];if(t.dataType!==r.dataType||t.dataType!==n.dataType)throw new Error(\"All inputs must have the same data type\");if(t.dims.length!==3&&t.dims.length!==2)throw new Error(\"Input must be 2D or 3D\");if(r.dims.length!==3&&r.dims.length!==2)throw new Error(\"Skip must be 2D or 3D\");let o=t.dims[t.dims.length-1],i=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==o)throw new Error(\"Skip must have the same hidden size as input\");if(r.dims[r.dims.length-2]!==i)throw new Error(\"Skip must have the same sequence length as input\");if(n.dims.length!==1)throw new Error(\"Gamma must be 1D\");if(n.dims[n.dims.length-1]!==o)throw new Error(\"Gamma must have the same hidden size as input\");if(e.length>3){let a=e[3];if(a.dims.length!==1)throw new Error(\"Beta must be 1D\");if(a.dims[a.dims.length-1]!==o)throw new Error(\"Beta must have the same hidden size as input\")}if(e.length>4){let a=e[4];if(a.dims.length!==1)throw new Error(\"Bias must be 1D\");if(a.dims[a.dims.length-1]!==o)throw new Error(\"Bias must have the same hidden size as input\")}},Fh=(e,t,r,n)=>{let o=t.simplified,i=e[0].dims,a=k.size(i),l=i,d=a,p=i.slice(-1)[0],m=n?i.slice(0,-1).concat(1):[],u=!o&&e.length>3,h=e.length>4,_=n&&r>1,y=n&&r>2,g=r>3,x=64,$=me(p),v=[{type:12,data:d},{type:12,data:$},{type:12,data:p},{type:1,data:t.epsilon}],S=C=>{let A=[{name:\"output_size\",type:\"u32\"},{name:\"components\",type:\"u32\"},{name:\"hidden_size\",type:\"u32\"},{name:\"epsilon\",type:\"f32\"}],P=[E(\"x\",e[0].dataType,e[0].dims,$),E(\"skip\",e[1].dataType,e[1].dims,$),E(\"gamma\",e[2].dataType,e[2].dims,$)];u&&P.push(E(\"beta\",e[3].dataType,e[3].dims,$)),h&&P.push(E(\"bias\",e[4].dataType,e[4].dims,$)),P.push(M(\"output\",e[0].dataType,l,$)),_&&P.push(M(\"mean_output\",1,m)),y&&P.push(M(\"inv_std_output\",1,m)),g&&P.push(M(\"input_skip_bias_sum\",e[0].dataType,l,$));let O=ye(e[0].dataType),U=ye(1,$);return`\n\n ${C.registerUniforms(A).declareVariables(...P)}\n var sum_shared : array<${U}, ${x}>;\n var sum_squared_shared : array<${U}, ${x}>;\n\n ${C.mainStart([x,1,1])}\n let ix = local_id.x;\n let iy = global_id.x / ${x};\n\n let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;\n var stride = hidden_size_vectorized / ${x};\n let offset = ix * stride + iy * hidden_size_vectorized;\n let offset1d = stride * ix;\n if (ix == ${x-1}) {\n stride = hidden_size_vectorized - stride * ix;\n }\n for (var i: u32 = 0; i < stride; i++) {\n let skip_value = skip[offset + i];\n let bias_value = ${h?\"bias[offset1d + i]\":O+\"(0.0)\"};\n let input_value = x[offset + i];\n let value = input_value + skip_value + bias_value;\n ${g?\"input_skip_bias_sum[offset + i] = value;\":\"\"}\n output[offset + i] = value;\n let f32_value = ${At(O,$,\"value\")};\n sum_shared[ix] += f32_value;\n sum_squared_shared[ix] += f32_value * f32_value;\n }\n workgroupBarrier();\n\n var reduce_size : u32 = ${x};\n for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) {\n reduce_size = curr_size + (reduce_size & 1);\n if (ix < curr_size) {\n sum_shared[ix] += sum_shared[ix + reduce_size];\n sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size];\n }\n workgroupBarrier();\n }\n\n let sum = sum_shared[0];\n let square_sum = sum_squared_shared[0];\n let mean = ${He(\"sum\",$)} / f32(uniforms.hidden_size);\n let inv_std_dev = inverseSqrt(${He(\"square_sum\",$)} / f32(uniforms.hidden_size) ${o?\"\":\"- mean * mean\"} + uniforms.epsilon);\n ${_?\"mean_output[global_idx] = mean;\":\"\"}\n ${y?\"inv_std_output[global_idx] = inv_std_dev;\":\"\"}\n\n for (var i: u32 = 0; i < stride; i++) {\n output[offset + i] = (output[offset + i] ${o?\"\":`- ${O}(mean)`}) *\n ${O}(inv_std_dev) * gamma[offset1d + i]\n ${u?\"+ beta[offset1d + i]\":\"\"};\n }\n }`},T=[{dims:l,dataType:e[0].dataType}];return r>1&&T.push({dims:m,dataType:1}),r>2&&T.push({dims:m,dataType:1}),r>3&&T.push({dims:i,dataType:e[0].dataType}),{name:\"SkipLayerNormalization\",shaderCache:{hint:`${$};${_};${y};${g}`,inputDependencies:e.map((C,A)=>\"type\")},getShaderSource:S,getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(d/p)},programUniforms:v})}},Pd=(e,t)=>{Hh(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(Fh(e.inputs,t,e.outputCount,!1),{outputs:n})}});var qh,an,jh,Od,Kh,Yh,Bd,Dd,Md=R(()=>{\"use strict\";te();oe();Se();ae();qh=(e,t)=>{if(!e||e.length<1)throw new Error(\"too few inputs\");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error(\"axes, starts and ends must have the same length\")}else if(t.starts.length!==t.ends.length)throw new Error(\"starts and ends must have the same length\");e.slice(1).forEach((r,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},an=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>r.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>r.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},jh=(e,t)=>{if(e.length>1){let r=an(e,1),n=an(e,2),o=an(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),J({starts:r,ends:n,axes:o})}else return t},Od=(e,t,r,n,o)=>{let i=e;return e<0&&(i+=r[n[t]]),o[t]<0?Math.max(0,Math.min(i,r[n[t]]-1)):Math.max(0,Math.min(i,r[n[t]]))},Kh=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n var carry = 0u;\n for (var i = ${r.length}; i >= 0; i--) {\n let input_shape_i = ${F(\"uniforms.input_shape\",\"i\",r.length)};\n let steps_i = ${F(\"uniforms.steps\",\"i\",r.length)};\n let signs_i = ${F(\"uniforms.signs\",\"i\",r.length)};\n let starts_i = ${F(\"uniforms.starts\",\"i\",r.length)};\n var output_index = ${t.indicesGet(\"output_indices\",\"i\")};\n var input_index = output_index * steps_i + starts_i + carry;\n carry = input_index / input_shape_i;\n input_index = input_index % input_shape_i;\n if (signs_i < 0) {\n input_index = input_shape_i - input_index - 1u + starts_i;\n }\n ${e.indicesSet(\"input_indices\",\"i\",\"input_index\")};\n }\n return input_indices;\n }`,Yh=(e,t)=>{let r=e[0].dims,n=k.size(r),o=t.axes.length>0?k.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],i=an(e,4);i.forEach($=>$!==0||(()=>{throw new Error(\"step cannot be 0\")})),i.length===0&&(i=Array(o.length).fill(1));let a=t.starts.map(($,v)=>Od($,v,r,o,i)),l=t.ends.map(($,v)=>Od($,v,r,o,i));if(o.length!==a.length||o.length!==l.length)throw new Error(\"start, ends and axes should have the same number of elements\");if(o.length!==r.length)for(let $=0;$Math.sign($));i.forEach(($,v,S)=>{if($<0){let T=(l[v]-a[v])/$,C=a[v],A=C+T*i[v];a[v]=A,l[v]=C,S[v]=-$}});let p=r.slice(0);o.forEach(($,v)=>{p[$]=Math.ceil((l[$]-a[$])/i[$])});let m={dims:p,dataType:e[0].dataType},u=M(\"output\",e[0].dataType,p.length),h=E(\"input\",e[0].dataType,e[0].dims.length),_=k.size(p),y=[{name:\"outputSize\",type:\"u32\"},{name:\"starts\",type:\"u32\",length:a.length},{name:\"signs\",type:\"i32\",length:d.length},{name:\"steps\",type:\"u32\",length:i.length}],g=[{type:12,data:_},{type:12,data:a},{type:6,data:d},{type:12,data:i},...N(e[0].dims,p)],x=$=>`\n ${$.registerUniforms(y).declareVariables(h,u)}\n ${Kh(h,u,r)}\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.outputSize\")}\n let output_indices = ${u.offsetToIndices(\"global_idx\")};\n let input_indices = calculateInputIndices(output_indices);\n ${u.setByOffset(\"global_idx\",h.getByIndices(\"input_indices\"))}\n }`;return{name:\"Slice\",shaderCache:{hint:`${d.length}_${a.length}_${i.length}`,inputDependencies:[\"rank\"]},getShaderSource:x,getRunData:()=>({outputs:[m],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:g})}},Bd=(e,t)=>{qh(e.inputs,t);let r=jh(e.inputs,t);e.compute(Yh(e.inputs,r),{inputs:[0]})},Dd=e=>{let t=e.starts,r=e.ends,n=e.axes;return J({starts:t,ends:r,axes:n})}});var Zh,Qh,Rd,Ud,Nd=R(()=>{\"use strict\";te();oe();Se();ut();ae();Zh=e=>{if(!e||e.length!==1)throw new Error(\"Softmax op requires 1 input.\")},Qh=(e,t)=>{let r=e.inputs[0],n=r.dims,o=k.size(n),i=n.length,a=k.normalizeAxis(t.axis,i),l=aO),p[a]=i-1,p[i-1]=a,d=e.compute(Ee(r,p),{inputs:[r],outputs:[-1]})[0]):d=r;let m=d.dims,u=m[i-1],h=o/u,_=me(u),y=u/_,g=64;h===1&&(g=256);let x=(P,O)=>O===4?`max(max(${P}.x, ${P}.y), max(${P}.z, ${P}.w))`:O===2?`max(${P}.x, ${P}.y)`:O===3?`max(max(${P}.x, ${P}.y), ${P}.z)`:P,$=E(\"x\",d.dataType,d.dims,_),v=M(\"result\",d.dataType,d.dims,_),S=$.type.value,T=ye(d.dataType)===\"f32\"?`var threadMax = ${S}(-3.402823e+38f);`:`var threadMax = ${S}(-65504.0h);`,C=P=>`\n var rowMaxShared : ${S};\n var rowSumShared : ${S};\n var threadShared : array<${S}, ${g}>;\n\n fn getValue(row: i32, col: i32, row_stride: i32) -> ${S} {\n let index = row * row_stride + col;\n return x[index];\n }\n\n fn setValue(row: i32, col: i32, row_stride: i32, value: ${S}) {\n let index = row * row_stride + col;\n result[index] = value;\n }\n ${P.registerUniform(\"packedCols\",\"i32\").declareVariables($,v)}\n ${P.mainStart(g)}\n let gindex = i32(global_idx);\n let lindex = i32(local_idx);\n const wg = ${g};\n let row = gindex / wg;\n let cols = uniforms.packedCols;\n let row_stride : i32 = uniforms.packedCols;\n\n // find the rows max\n ${T}\n for (var col = lindex; col < cols; col += wg) {\n let value = getValue(row, col, row_stride);\n threadMax = max(threadMax, value);\n }\n if (lindex < cols) {\n threadShared[lindex] = threadMax;\n }\n workgroupBarrier();\n\n var reduceSize = min(cols, wg);\n for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {\n reduceSize = currSize + (reduceSize & 1);\n if (lindex < currSize) {\n threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowMaxShared = ${S}(${x(\"threadShared[0]\",_)});\n }\n workgroupBarrier();\n\n // find the rows sum\n var threadSum = ${S}(0.0);\n for (var col = lindex; col < cols; col += wg) {\n let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);\n threadSum += subExp;\n }\n threadShared[lindex] = threadSum;\n workgroupBarrier();\n\n for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {\n if (lindex < currSize) {\n threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowSumShared = ${S}(${He(\"threadShared[0]\",_)});\n }\n workgroupBarrier();\n\n // calculate final value for each element in the row\n for (var col = lindex; col < cols; col += wg) {\n let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;\n setValue(row, col, row_stride, value);\n }\n }`,A=e.compute({name:\"Softmax\",shaderCache:{hint:`${_};${g}`,inputDependencies:[\"type\"]},getRunData:()=>({outputs:[{dims:m,dataType:d.dataType}],dispatchGroup:{x:h},programUniforms:[{type:6,data:y}]}),getShaderSource:C},{inputs:[d],outputs:[l?-1:0]})[0];l&&e.compute(Ee(A,p),{inputs:[A]})},Rd=(e,t)=>{Zh(e.inputs),Qh(e,t)},Ud=e=>J({axis:e.axis})});var Vd,Xh,Jh,eg,Wd,Ld=R(()=>{\"use strict\";te();oe();ae();Vd=e=>Array.from(e.getBigInt64Array(),Number),Xh=e=>{if(!e||e.length!==2)throw new Error(\"Tile requires 2 inputs.\");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error(\"Tile only support float, float16, int32, and uint32 data types\");if(e[1].dataType!==7)throw new Error(\"Tile `repeats` input should be of int64 data type\");if(e[1].dims.length!==1)throw new Error(\"Tile `repeats` input should be 1-D\");if(Vd(e[1]).length!==e[0].dims.length)throw new Error(\"Tile `repeats` input should have same number of elements as rank of input data tensor\")},Jh=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??Vd(e[1]),o=Jh(r,n),i=k.size(o),a=e[0].dataType,l=E(\"input\",a,r.length),d=M(\"output\",a,o.length),p=m=>`\n const inputShape = ${l.indices(...r)};\n ${m.registerUniform(\"output_size\",\"u32\").declareVariables(l,d)}\n ${m.mainStart()}\n ${m.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.output_size\")}\n let output_indices = ${d.offsetToIndices(\"global_idx\")};\n var input_indices: ${l.type.indices};\n for (var i = 0; i < ${r.length}; i++) {\n let input_dim_i = ${l.indicesGet(\"uniforms.input_shape\",\"i\")};\n let input_dim_value = ${d.indicesGet(\"output_indices\",\"i\")} % input_dim_i;\n\n ${l.indicesSet(\"input_indices\",\"i\",\"input_dim_value\")}\n }\n ${d.setByOffset(\"global_idx\",l.getByIndices(\"input_indices\"))}\n }`;return{name:\"Tile\",shaderCache:{hint:`${n}`,inputDependencies:[\"rank\"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...N(e[0].dims,o)]}),getShaderSource:p}},Wd=e=>{Xh(e.inputs),e.compute(eg(e.inputs),{inputs:[0]})}});var tg,rg,Gd,Hd=R(()=>{\"use strict\";te();oe();ae();tg=(e,t,r,n,o)=>{let i=M(\"output_data\",o,r.length,4),a=E(\"a_data\",t[1].dataType,t[1].dims.length,4),l=E(\"b_data\",t[2].dataType,t[2].dims.length,4),d=E(\"c_data\",t[0].dataType,t[0].dims.length,4),p,m=(u,h,_)=>`select(${h}, ${u}, ${_})`;if(!n)p=i.setByOffset(\"global_idx\",m(a.getByOffset(\"global_idx\"),l.getByOffset(\"global_idx\"),d.getByOffset(\"global_idx\")));else{let u=(h,_,y=\"\")=>{let g=`a_data[index_a${_}][component_a${_}]`,x=`b_data[index_b${_}][component_b${_}]`,$=`bool(c_data[index_c${_}] & (0xffu << (component_c${_} * 8)))`;return`\n let output_indices${_} = ${i.offsetToIndices(`global_idx * 4u + ${_}u`)};\n let offset_a${_} = ${a.broadcastedIndicesToOffset(`output_indices${_}`,i)};\n let offset_b${_} = ${l.broadcastedIndicesToOffset(`output_indices${_}`,i)};\n let offset_c${_} = ${d.broadcastedIndicesToOffset(`output_indices${_}`,i)};\n let index_a${_} = offset_a${_} / 4u;\n let index_b${_} = offset_b${_} / 4u;\n let index_c${_} = offset_c${_} / 4u;\n let component_a${_} = offset_a${_} % 4u;\n let component_b${_} = offset_b${_} % 4u;\n let component_c${_} = offset_c${_} % 4u;\n ${h}[${_}] = ${y}(${m(g,x,$)});\n `};o===9?p=`\n var data = vec4(0);\n ${u(\"data\",0,\"u32\")}\n ${u(\"data\",1,\"u32\")}\n ${u(\"data\",2,\"u32\")}\n ${u(\"data\",3,\"u32\")}\n output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:p=`\n ${u(\"output_data[global_idx]\",0)}\n ${u(\"output_data[global_idx]\",1)}\n ${u(\"output_data[global_idx]\",2)}\n ${u(\"output_data[global_idx]\",3)}\n `}return`\n ${e.registerUniform(\"vec_size\",\"u32\").declareVariables(d,a,l,i)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(\"uniforms.vec_size\")}\n ${p}\n }`},rg=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,o=e[1].dataType,i=!(k.areEqual(t,r)&&k.areEqual(r,n)),a=t,l=k.size(t);if(i){let p=et.calcShape(et.calcShape(t,r,!1),n,!1);if(!p)throw new Error(\"Can't perform where op on the given tensors\");a=p,l=k.size(a)}let d=Math.ceil(l/4);return{name:\"Where\",shaderCache:{inputDependencies:[\"rank\",\"rank\",\"rank\"]},getShaderSource:p=>tg(p,e,a,i,o),getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:Math.ceil(l/64/4)},programUniforms:[{type:12,data:d},...N(n,t,r,a)]})}},Gd=e=>{e.compute(rg(e.inputs))}});var Fd,qd=R(()=>{\"use strict\";ks();Kr();zs();Bs();_u();Eu();Ou();Yu();rl();il();ul();ml();gl();yl();vl();Sl();Cl();El();Ol();Wl();Hl();ql();Kl();Ql();To();Jl();gd();_d();vd();Sd();qr();Ad();Ed();zd();Md();Nd();Co();Ld();ut();Zr();Hd();Fd=new Map([[\"Abs\",[Ds]],[\"Acos\",[Ms]],[\"Acosh\",[Rs]],[\"Add\",[wu]],[\"ArgMax\",[As,po]],[\"ArgMin\",[Cs,po]],[\"Asin\",[Us]],[\"Asinh\",[Ns]],[\"Atan\",[Vs]],[\"Atanh\",[Ws]],[\"Attention\",[Es]],[\"AveragePool\",[sd,ad]],[\"BatchNormalization\",[Ps]],[\"BiasAdd\",[Os]],[\"BiasSplitGelu\",[yu]],[\"Cast\",[Gs,Ls]],[\"Ceil\",[Fs]],[\"Clip\",[Hs]],[\"Concat\",[Pu,zu]],[\"Conv\",[vo,wo]],[\"ConvTranspose\",[tl,Ju]],[\"Cos\",[qs]],[\"Cosh\",[js]],[\"CumSum\",[nl,ol]],[\"DepthToSpace\",[al,sl]],[\"DequantizeLinear\",[bd,yd]],[\"Div\",[vu]],[\"Einsum\",[cl,pl]],[\"Elu\",[Ks,Jt]],[\"Equal\",[$u]],[\"Erf\",[Ys]],[\"Exp\",[Zs]],[\"Expand\",[hl]],[\"FastGelu\",[bl]],[\"Floor\",[Qs]],[\"FusedConv\",[vo,wo]],[\"Gather\",[wl,_l]],[\"GatherElements\",[Il,Tl]],[\"GatherBlockQuantized\",[$l,xl]],[\"Gelu\",[Xs]],[\"Gemm\",[kl,Al]],[\"GlobalAveragePool\",[dd,ld]],[\"GlobalMaxPool\",[hd,fd]],[\"Greater\",[Iu]],[\"GreaterOrEqual\",[Au]],[\"GridSample\",[Pl,zl]],[\"GroupQueryAttention\",[Vl]],[\"HardSigmoid\",[au,iu]],[\"InstanceNormalization\",[Gl]],[\"LayerNormalization\",[Fl]],[\"LeakyRelu\",[Js,Jt]],[\"Less\",[Cu]],[\"LessOrEqual\",[ku]],[\"Log\",[hu]],[\"MatMul\",[jl]],[\"MatMulNBits\",[Yl,Zl]],[\"MaxPool\",[pd,md]],[\"Mul\",[xu]],[\"MultiHeadAttention\",[Ml,Dl]],[\"Neg\",[tu]],[\"Not\",[eu]],[\"Pad\",[Xl]],[\"Pow\",[Su]],[\"QuickGelu\",[gu,Jt]],[\"Range\",[wd]],[\"Reciprocal\",[ru]],[\"ReduceMin\",[vs]],[\"ReduceMean\",[gs]],[\"ReduceMax\",[ws]],[\"ReduceSum\",[xs]],[\"ReduceProd\",[$s]],[\"ReduceL1\",[bs]],[\"ReduceL2\",[ys]],[\"ReduceLogSum\",[Ts]],[\"ReduceLogSumExp\",[_s]],[\"ReduceSumSquare\",[Ss]],[\"Relu\",[nu]],[\"Resize\",[Id,Cd]],[\"RotaryEmbedding\",[kd]],[\"ScatterND\",[xd,$d]],[\"Sigmoid\",[ou]],[\"Sin\",[su]],[\"Sinh\",[uu]],[\"Slice\",[Bd,Dd]],[\"SkipLayerNormalization\",[Pd]],[\"Split\",[Rl,Ul]],[\"Sqrt\",[lu]],[\"Softmax\",[Rd,Ud]],[\"Sub\",[Tu]],[\"Tan\",[du]],[\"Tanh\",[pu]],[\"ThresholdedRelu\",[fu,Jt]],[\"Tile\",[Wd]],[\"Transpose\",[ns,os]],[\"Where\",[Gd]]])});var sn,jd=R(()=>{\"use strict\";We();Je();ae();sn=class{constructor(t){this.backend=t;this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,r){this.repo.set(t,r)}run(t,r,n,o,i){Ue(t.programInfo.name);let a=this.backend.device,l=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let d=[];for(let m of r)d.push({binding:d.length,resource:{buffer:m.buffer}});for(let m of n)d.push({binding:d.length,resource:{buffer:m.buffer}});i&&d.push({binding:d.length,resource:i});let p=a.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:d,label:t.programInfo.name});if(this.backend.sessionStatus===\"capturing\"){let m={kernelId:this.backend.currentKernelId,computePipeline:t.computePipeline,bindGroup:p,dispatchGroup:o};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(m)}l.setPipeline(t.computePipeline),l.setBindGroup(0,p),l.dispatchWorkgroups(...o),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType===\"at-passes\")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),De(t.programInfo.name)}dispose(){}build(t,r){Ue(t.name);let n=this.backend.device,o=[];[{feature:\"shader-f16\",extension:\"f16\"},{feature:\"subgroups\",extension:\"subgroups\"},{feature:\"subgroups-f16\",extension:\"subgroups_f16\"}].forEach(u=>{n.features.has(u.feature)&&o.push(`enable ${u.extension};`)});let a=ts(r,this.backend.device.limits),l=t.getShaderSource(a),d=`${o.join(`\n`)}\n${a.additionalImplementations}\n${l}`,p=n.createShaderModule({code:d,label:t.name});ue(\"verbose\",()=>`[WebGPU] ${t.name} shader code: ${d}`);let m=n.createComputePipeline({compute:{module:p,entryPoint:\"main\"},layout:\"auto\",label:t.name});return De(t.name),{programInfo:t,computePipeline:m,uniformVariablesInfo:a.variablesInfo}}normalizeDispatchGroupSize(t){let r=typeof t==\"number\"?t:t.x,n=typeof t==\"number\"?1:t.y||1,o=typeof t==\"number\"?1:t.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=i&&n<=i&&o<=i)return[r,n,o];let a=r*n*o,l=Math.ceil(Math.sqrt(a));if(l>i){if(l=Math.ceil(Math.cbrt(a)),l>i)throw new Error(\"Total dispatch size exceeds WebGPU maximum.\");return[l,l,l]}else return[l,l,1]}}});var ng,og,Ao,ko,un,Kd=R(()=>{\"use strict\";We();te();Je();eo();Qa();qd();jd();ng=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let n=0;n{let n=e.name;return e.shaderCache?.hint&&(n+=\"[\"+e.shaderCache.hint+\"]\"),n+=\":\"+r+`:${ng(t,e.shaderCache?.inputDependencies??new Array(t.length).fill(\"dims\"))}`,n},Ao=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},ko=class{constructor(t){this.subgroupsSupported=t.features.has(\"subgroups\"),this.subgroupsF16Supported=t.features.has(\"subgroups\");let r=t.limits;!this.subgroupsSupported||!r.minSubgroupSize||!r.maxSubgroupSize?this.subgroupSizeRange=void 0:this.subgroupSizeRange=[r.minSubgroupSize,r.maxSubgroupSize]}},un=class{constructor(){this.currentSessionId=null;this.currentKernelId=null;this.commandEncoder=null;this.computePassEncoder=null;this.maxDispatchNumber=16;this.pendingDispatchNumber=0;this.pendingKernels=[];this.pendingQueries=new Map;this.sessionStatus=\"default\";this.capturedCommandList=new Map;this.capturedPendingKernels=new Map;this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error(\"currentKernelCustomData(): currentKernelId is null. (should not happen)\");let t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,r){this.env=t;let n=[],o={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},i=a=>r.features.has(a)&&n.push(a)&&!0;i(\"chromium-experimental-timestamp-query-inside-passes\")||i(\"timestamp-query\"),i(\"shader-f16\"),i(\"subgroups\")&&i(\"subgroups-f16\"),this.device=await r.requestDevice(o),this.deviceInfo=new ko(this.device),this.adapterInfo=new Ao(r.info||await r.requestAdapterInfo()),this.gpuDataManager=Za(this),this.programManager=new sn(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Vr(t.logLevel,!!t.debug),this.device.onuncapturederror=a=>{a.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${a.error.message}`)},Object.defineProperty(this.env.webgpu,\"device\",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,\"adapter\",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<\"u\"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t=this.getCommandEncoder(),r={};this.queryType===\"at-passes\"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ue(),this.endComputePass();let t;this.queryType!==\"none\"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),t=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(t,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,t,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!==\"none\"&&t.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(t.getMappedRange()),n=this.pendingQueries.get(t);for(let o=0;o\"u\"&&(this.queryTimeBase=_);let g=Number(_-this.queryTimeBase),x=Number(y-this.queryTimeBase);if(!Number.isSafeInteger(g)||!Number.isSafeInteger(x))throw new RangeError(\"incorrect timestamp range\");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:u.map($=>({dims:$.dims,dataType:gt($.dataType)})),outputsMetadata:h.map($=>({dims:$.dims,dataType:gt($.dataType)})),kernelId:a,kernelType:d,kernelName:p,programName:m,startTime:g,endTime:x});else{let $=\"\";u.forEach((S,T)=>{$+=`input[${T}]: [${S.dims}] | ${gt(S.dataType)}, `});let v=\"\";h.forEach((S,T)=>{v+=`output[${T}]: [${S.dims}] | ${gt(S.dataType)}, `}),console.log(`[profiling] kernel \"${a}|${d}|${p}|${m}\" ${$}${v}execution time: ${x-g} ns`)}xr(\"GPU\",`${m}::${_}::${y}`)}t.unmap(),this.pendingQueries.delete(t)}),De()}run(t,r,n,o,i,a){Ue(t.name);let l=[];for(let S=0;ST):n;if(u.length!==d.length)throw new Error(`Output size ${u.length} must be equal to ${d.length}.`);let h=[],_=[];for(let S=0;S=a)throw new Error(`Invalid output index: ${u[S]}`);if(u[S]===-3)continue;let T=u[S]===-1,C=u[S]===-2,A=T||C?i(d[S].dataType,d[S].dims):o(u[S],d[S].dataType,d[S].dims);if(h.push(A),A.data===0)continue;let P=this.gpuDataManager.get(A.data);if(!P)throw new Error(`no GPU data for output: ${A.data}`);if(T&&this.temporaryData.push(P),C){let O=this.kernelPersistentData.get(this.currentKernelId);O||(O=[],this.kernelPersistentData.set(this.currentKernelId,O)),O.push(P)}_.push(P)}if(l.length!==r.length||_.length!==h.length){if(_.length===0)return De(t.name),h;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let y;if(m){let S=0,T=[];m.forEach(O=>{let U=typeof O.data==\"number\"?[O.data]:O.data;if(U.length===0)return;let G=O.type===10?2:4,q,K;O.type===10?(K=U.length>4?16:U.length>2?8:U.length*G,q=U.length>4?16:G*U.length):(K=U.length<=2?U.length*G:16,q=16),S=Math.ceil(S/K)*K,T.push(S);let W=O.type===10?8:4;S+=U.length>4?Math.ceil(U.length/W)*q:U.length*G});let C=16;S=Math.ceil(S/C)*C;let A=new ArrayBuffer(S);m.forEach((O,U)=>{let G=T[U],q=typeof O.data==\"number\"?[O.data]:O.data;if(O.type===6)new Int32Array(A,G,q.length).set(q);else if(O.type===12)new Uint32Array(A,G,q.length).set(q);else if(O.type===10)new Uint16Array(A,G,q.length).set(q);else if(O.type===1)new Float32Array(A,G,q.length).set(q);else throw new Error(`Unsupported uniform type: ${gt(O.type)}`)});let P=this.gpuDataManager.create(S,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(P.buffer,0,A,0,S),this.gpuDataManager.release(P.id),y={offset:0,size:S,buffer:P.buffer}}let g=this.programManager.normalizeDispatchGroupSize(p),x=g[1]===1&&g[2]===1,$=og(t,r,x),v=this.programManager.getArtifact($);if(v||(v=this.programManager.build(t,g),this.programManager.setArtifact($,v),ue(\"info\",()=>`[artifact] key: ${$}, programName: ${t.name}`)),m&&v.uniformVariablesInfo){if(m.length!==v.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${v.uniformVariablesInfo.length}, got ${m.length} in program \"${v.programInfo.name}\".`);for(let S=0;S`[ProgramManager] run \"${t.name}\" (key=${$}) with ${g[0]}x${g[1]}x${g[2]}`),this.queryType!==\"none\"||this.sessionStatus===\"capturing\"){let S={kernelId:this.currentKernelId,programName:v.programInfo.name,inputTensorViews:r,outputTensorViews:h};this.pendingKernels.push(S),this.sessionStatus===\"capturing\"&&this.capturedPendingKernels.get(this.currentSessionId).push(S)}return this.programManager.run(v,l,_,g,y),De(t.name),h}upload(t,r){this.gpuDataManager.upload(t,r)}memcpy(t,r){this.gpuDataManager.memcpy(t,r)}async download(t,r){await this.gpuDataManager.download(t,r)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,r,n,o){let i=Fd.get(t);if(!i)throw new Error(`kernel not implemented: ${t}`);let a={kernelType:t,kernelName:o,kernelEntry:i[0],attributes:[i[1],n]};this.kernels.set(r,a)}releaseKernel(t){let r=this.kernelPersistentData.get(t);if(r){for(let n of r)this.gpuDataManager.release(n.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,r,n){let o=this.kernels.get(t);if(!o)throw new Error(`kernel not created: ${t}`);let i=o.kernelType,a=o.kernelName,l=o.kernelEntry,d=o.attributes;if(this.currentKernelId!==null)throw new Error(`kernel \"[${i}] ${a}\" is not allowed to be called recursively`);this.currentKernelId=t,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),ue(\"info\",()=>`[WebGPU] Start to run kernel \"[${i}] ${a}\"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope(\"validation\"),l(r,d[1]),0}catch(m){return n.push(Promise.resolve(`[WebGPU] Kernel \"[${i}] ${a}\" failed. ${m}`)),1}finally{p&&n.push(this.device.popErrorScope().then(m=>m?`GPU validation error for kernel \"[${i}] ${a}\": ${m.message}`:null));for(let m of this.temporaryData)this.gpuDataManager.release(m.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,r,n,o){let i=this.sessionExternalDataMapping.get(t);i||(i=new Map,this.sessionExternalDataMapping.set(t,i));let a=i.get(r),l=this.gpuDataManager.registerExternalBuffer(n,o,a);return i.set(r,[l,n]),l}unregisterBuffers(t){let r=this.sessionExternalDataMapping.get(t);r&&(r.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[0])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let r=this.gpuDataManager.get(t);if(!r)throw new Error(`no GPU data for buffer: ${t}`);return r.buffer}createDownloader(t,r,n){return async()=>{let o=await oo(this,t,r);return Wr(o.buffer,n)}}writeTimestamp(t){this.queryType===\"inside-passes\"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}setQueryType(){this.queryType=\"none\",(this.env.webgpu.profiling?.mode===\"default\"||(typeof this.env.trace>\"u\"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has(\"chromium-experimental-timestamp-query-inside-passes\")?this.queryType=\"inside-passes\":this.device.features.has(\"timestamp-query\")&&(this.queryType=\"at-passes\"),this.queryType!==\"none\"&&typeof this.querySet>\"u\"&&(this.querySet=this.device.createQuerySet({type:\"timestamp\",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){ue(\"info\",\"captureBegin\"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus=\"capturing\"}captureEnd(){ue(\"info\",\"captureEnd\"),this.flush(),this.sessionStatus=\"default\"}replay(){ue(\"info\",\"replay\"),this.sessionStatus=\"replaying\";let t=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),n=t.length;this.pendingKernels=[];for(let o=0;o=this.maxDispatchNumber||this.queryType===\"at-passes\")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus=\"default\"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}});var ig,Yd,ag,Zd,ln,dn,Eo,Qd,Xd=R(()=>{\"use strict\";Je();ig=1,Yd=()=>ig++,ag=new Map([[\"float32\",32],[\"float16\",16],[\"int32\",32],[\"uint32\",32],[\"int64\",64],[\"uint64\",64],[\"int8\",8],[\"uint8\",8],[\"int4\",4],[\"uint4\",4]]),Zd=(e,t)=>{let r=ag.get(e);if(!r)throw new Error(\"Unsupported data type.\");return Math.ceil(t.reduce((n,o)=>n*o)*r/8)},ln=class{constructor(t){this.sessionId=t.sessionId,this.mlContext=t.context,this.mlTensor=t.tensor,this.dataType=t.dataType,this.tensorShape=t.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Zd(this.dataType,this.tensorShape)}destroy(){ue(\"verbose\",()=>\"[WebNN] TensorWrapper.destroy\"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t){return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}sameTypeAndShape(t,r){return this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((n,o)=>n===r[o])}},dn=class{constructor(t,r){this.tensorManager=t;this.wrapper=r}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(t,r,n){if(this.wrapper){if(this.wrapper.sameTypeAndShape(t,r))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==Zd(t,r))throw new Error(\"Unable to copy data to tensor with different size.\");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let o=typeof MLTensorUsage>\"u\"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,r,o,!0,!0),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(t){if(this.wrapper)if(t.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else ue(\"verbose\",()=>\"Data size does not match tensor size. Releasing tensor.\"),this.releaseTensor();this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(t){if(this.activeUpload)if(t){t instanceof ArrayBuffer?new Uint8Array(t).set(this.activeUpload):new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.wrapper)throw new Error(\"Tensor has not been created.\");return t?this.wrapper.read(t):this.wrapper.read()}},Eo=class{constructor(t){this.backend=t;this.tensorTrackersById=new Map;this.freeTensors=[];this.externalTensors=new Set}reserveTensorId(){let t=Yd();return this.tensorTrackersById.set(t,new dn(this)),t}releaseTensorId(t){let r=this.tensorTrackersById.get(t);r&&(this.tensorTrackersById.delete(t),r.tensorWrapper&&this.releaseTensor(r.tensorWrapper))}async ensureTensor(t,r,n,o){ue(\"verbose\",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${n}, copyOld: ${o}}`);let i=this.tensorTrackersById.get(t);if(!i)throw new Error(\"Tensor not found.\");return i.ensureTensor(r,n,o)}upload(t,r){let n=this.tensorTrackersById.get(t);if(!n)throw new Error(\"Tensor not found.\");n.upload(r)}async download(t,r){ue(\"verbose\",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${r?.byteLength}}`);let n=this.tensorTrackersById.get(t);if(!n)throw new Error(\"Tensor not found.\");return n.download(r)}releaseTensorsForSession(t){for(let r of this.freeTensors)r.sessionId===t&&r.destroy();this.freeTensors=this.freeTensors.filter(r=>r.sessionId!==t)}registerTensor(t,r,n,o){let i=Yd(),a=new ln({sessionId:this.backend.currentSessionId,context:t,tensor:r,dataType:n,shape:o});return this.tensorTrackersById.set(i,new dn(this,a)),this.externalTensors.add(a),i}async getCachedTensor(t,r,n,o,i){let a=this.backend.currentSessionId;for(let[p,m]of this.freeTensors.entries())if(m.sameTypeAndShape(t,r)){ue(\"verbose\",()=>`[WebNN] Reusing tensor {dataType: ${t}, shape: ${r}}`);let u=this.freeTensors.splice(p,1)[0];return u.sessionId=a,u}let l=this.backend.currentContext;ue(\"verbose\",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, shape: ${r}}`);let d=await l.createTensor({dataType:t,shape:r,dimensions:r,usage:n,writable:o,readable:i});return new ln({sessionId:a,context:l,tensor:d,dataType:t,shape:r})}releaseTensor(t){this.externalTensors.has(t)&&this.externalTensors.delete(t),this.freeTensors.push(t)}},Qd=(...e)=>new Eo(...e)});var Jd,sg,cn,ec=R(()=>{\"use strict\";te();ht();eo();Xd();Je();Jd=new Map([[1,\"float32\"],[10,\"float16\"],[6,\"int32\"],[12,\"uint32\"],[7,\"int64\"],[13,\"uint64\"],[22,\"int4\"],[21,\"uint4\"],[3,\"int8\"],[2,\"uint8\"],[9,\"uint8\"]]),sg=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.length===n.length&&r.every((o,i)=>o===n[i]&&e[o]===t[o])},cn=class{constructor(t){this.tensorManager=Qd(this);this.mlContextBySessionId=new Map;this.sessionIdsByMLContext=new Map;this.mlContextCache=[];Vr(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error(\"No active session\");return this.activeSessionId}onRunStart(t){this.activeSessionId=t}async createMLContext(t){if(t instanceof GPUDevice){let n=this.mlContextCache.findIndex(o=>o.gpuDevice===t);if(n!==-1)return this.mlContextCache[n].mlContext;{let o=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:o}),o}}else if(t===void 0){let n=this.mlContextCache.findIndex(o=>o.options===void 0&&o.gpuDevice===void 0);if(n!==-1)return this.mlContextCache[n].mlContext;{let o=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:o}),o}}let r=this.mlContextCache.findIndex(n=>sg(n.options,t));if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:n}),n}}get currentContext(){let t=this.getMLContext(this.currentSessionId);if(!t)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return t}registerMLContext(t,r){this.mlContextBySessionId.set(t,r);let n=this.sessionIdsByMLContext.get(r);n||(n=new Set,this.sessionIdsByMLContext.set(r,n)),n.add(t)}onReleaseSession(t){let r=this.mlContextBySessionId.get(t);if(!r)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t);let n=this.sessionIdsByMLContext.get(r);if(n.delete(t),n.size===0){this.sessionIdsByMLContext.delete(r);let o=this.mlContextCache.findIndex(i=>i.mlContext===r);o!==-1&&this.mlContextCache.splice(o,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){ue(\"verbose\",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,r,n,o){let i=Jd.get(r);if(!i)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(t,i,n,o)}uploadTensor(t,r){if(!Ce().shouldTransferToMLTensor)throw new Error(\"Trying to upload to a MLTensor while shouldTransferToMLTensor is false\");ue(\"verbose\",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${r.byteLength}}`),this.tensorManager.upload(t,r)}async downloadTensor(t,r){return this.tensorManager.download(t,r)}createMLTensorDownloader(t,r){return async()=>{let n=await this.tensorManager.download(t);return Wr(n,r)}}registerMLTensor(t,r,n){let o=Jd.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);let i=this.tensorManager.registerTensor(this.currentContext,t,o,n);return ue(\"verbose\",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${o}, dimensions: ${n}} -> {tensorId: ${i}}`),i}registerMLConstant(t,r,n,o,i,a){if(!a)throw new Error(\"External mounted files are not available.\");let l=t;t.startsWith(\"./\")&&(l=t.substring(2));let d=a.get(l);if(!d)throw new Error(`File with name ${l} not found in preloaded files.`);if(r+n>d.byteLength)throw new Error(\"Out of bounds: data offset and length exceed the external file data size.\");let p=d.slice(r,r+n).buffer,m;switch(i.dataType){case\"float32\":m=new Float32Array(p);break;case\"float16\":m=new Uint16Array(p);break;case\"int32\":m=new Int32Array(p);break;case\"uint32\":m=new Uint32Array(p);break;case\"int64\":m=new BigInt64Array(p);break;case\"uint64\":m=new BigUint64Array(p);break;case\"int8\":m=new Int8Array(p);break;case\"int4\":case\"uint4\":case\"uint8\":m=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return ue(\"verbose\",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`),o.constant(i,m)}flush(){}}});var tc={};Ft(tc,{init:()=>ug});var nr,Po,ug,rc=R(()=>{\"use strict\";te();Kd();Je();oe();ec();nr=class e{constructor(t,r,n,o){this.module=t;this.dataType=r;this.data=n;this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error(\"Invalid data type\");let t=k.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error(\"Invalid data type\");let t=k.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error(\"Invalid data type\");let t=k.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error(\"Invalid data type\");let t=k.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(k.size(t)!==k.size(this.dims))throw new Error(\"Invalid new shape\");return new e(this.module,this.dataType,this.data,t)}},Po=class{constructor(t,r,n){this.module=t;this.backend=r;this.customDataOffset=0;this.customDataSize=0;this.adapterInfo=r.adapterInfo,this.deviceInfo=r.deviceInfo;let o=t.PTR_SIZE,i=n/t.PTR_SIZE,a=o===4?\"i32\":\"i64\";this.opKernelContext=Number(t.getValue(o*i++,a));let l=Number(t.getValue(o*i++,a));this.outputCount=Number(t.getValue(o*i++,a)),this.customDataOffset=Number(t.getValue(o*i++,\"*\")),this.customDataSize=Number(t.getValue(o*i++,a));let d=[];for(let p=0;ptypeof l==\"number\"?this.inputs[l]:l)??this.inputs,o=r?.outputs??[],i=(l,d,p)=>new nr(this.module,d,this.output(l,p),p),a=(l,d)=>{let p=Tt(l,d);if(!p)throw new Error(`Unsupported data type: ${l}`);let m=p>0?this.backend.gpuDataManager.create(p).id:0;return new nr(this.module,l,m,d)};return this.backend.run(t,n,o,i,a,this.outputCount)}output(t,r){let n=this.module.stackSave();try{let o=this.module.PTR_SIZE,i=o===4?\"i32\":\"i64\",a=this.module.stackAlloc((1+r.length)*o);this.module.setValue(a,r.length,i);for(let l=0;l{let o=t.jsepInit;if(!o)throw new Error(\"Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.\");if(e===\"webgpu\"){let i=new un;await i.initialize(r,n),o(\"webgpu\",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,d,p=!1)=>{if(p)ue(\"verbose\",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(d)}`),i.memcpy(Number(a),Number(l));else{ue(\"verbose\",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(d)}`);let m=t.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(d));i.upload(Number(l),m)}},async(a,l,d)=>{ue(\"verbose\",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${d}`),await i.download(Number(a),()=>t.HEAPU8.subarray(Number(l)>>>0,Number(l+d)>>>0))},(a,l,d)=>i.createKernel(a,Number(l),d,t.UTF8ToString(t._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,d,p)=>{ue(\"verbose\",()=>`[WebGPU] jsepRun: sessionHandle=${d}, kernel=${a}, contextDataOffset=${l}`);let m=new Po(t,i,Number(l));return i.computeKernel(Number(a),m,p)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let i=new cn(r);o(\"webnn\",[i,()=>i.reserveTensorId(),a=>i.releaseTensorId(a),async(a,l,d,p)=>i.ensureTensor(a,l,d,p),(a,l)=>{i.uploadTensor(a,l)},async(a,l)=>i.downloadTensor(a,l)])}}});var lg,Ar,kr,kt,dg,Kt,Er,Pr,nc,zr,Or,Br,Kn=R(()=>{\"use strict\";La();Ha();te();ht();Mr();Jn();lg=(e,t)=>{Ce()._OrtInit(e,t)!==0&&pe(\"Can't initialize onnxruntime.\")},Ar=async e=>{lg(e.wasm.numThreads,Qt(e.logLevel))},kr=async(e,t)=>{{let r=(rc(),br(tc)).init;if(t===\"webgpu\"){if(typeof navigator>\"u\"||!navigator.gpu)throw new Error(\"WebGPU is not supported in current environment\");let n=e.webgpu.adapter;if(n){if(typeof n.limits!=\"object\"||typeof n.features!=\"object\"||typeof n.requestDevice!=\"function\")throw new Error(\"Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.\")}else{let o=e.webgpu.powerPreference;if(o!==void 0&&o!==\"low-power\"&&o!==\"high-performance\")throw new Error(`Invalid powerPreference setting: \"${o}\"`);let i=e.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!=\"boolean\")throw new Error(`Invalid forceFallbackAdapter setting: \"${i}\"`);if(n=await navigator.gpu.requestAdapter({powerPreference:o,forceFallbackAdapter:i}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag \"--enable-unsafe-webgpu\" if you are using Chrome.')}await r(\"webgpu\",Ce(),e,n)}if(t===\"webnn\"){if(typeof navigator>\"u\"||!navigator.ml)throw new Error(\"WebNN is not supported in current environment\");await r(\"webnn\",Ce(),e)}}},kt=new Map,dg=e=>{let t=Ce(),r=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,o,o+n)!==0&&pe(\"Can't get session input/output count.\");let a=n===4?\"i32\":\"i64\";return[Number(t.getValue(o,a)),Number(t.getValue(o+n,a))]}finally{t.stackRestore(r)}},Kt=e=>{let t=Ce(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},Er=async(e,t)=>{let r,n,o=Ce();Array.isArray(e)?[r,n]=e:e.buffer===o.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=Kt(e);let i=0,a=0,l=0,d=[],p=[],m=[];try{if([a,d]=Ga(t),t?.externalData&&o.mountExternalData){let v=[];for(let S of t.externalData){let T=typeof S==\"string\"?S:S.path;v.push(Xt(typeof S==\"string\"?S:S.data).then(C=>{o.mountExternalData(T,C)}))}await Promise.all(v)}for(let v of t?.executionProviders??[])if((typeof v==\"string\"?v:v.name)===\"webnn\"){if(o.shouldTransferToMLTensor=!1,typeof v!=\"string\"){let T=v,C=T?.context,A=T?.gpuDevice,P=T?.deviceType,O=T?.powerPreference;C?o.currentContext=C:A?o.currentContext=await o.jsepCreateMLContext(A):o.currentContext=await o.jsepCreateMLContext({deviceType:P,powerPreference:O})}else o.currentContext=await o.jsepCreateMLContext();break}i=await o._OrtCreateSession(r,n,a),i===0&&pe(\"Can't create a session.\"),o.jsepOnCreateSession?.(),o.currentContext&&(o.jsepRegisterMLContext(i,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[u,h]=dg(i),_=!!t?.enableGraphCapture,y=[],g=[],x=[];for(let v=0;vv===\"gpu-buffer\"||v===\"ml-tensor\")&&(l=o._OrtCreateBinding(i),l===0&&pe(\"Can't create IO binding.\"),$={handle:l,outputPreferredLocations:x,outputPreferredLocationsEncoded:x.map(v=>Xn(v))}),kt.set(i,[i,p,m,$,_,!1]),[i,y,g]}catch(u){throw p.forEach(h=>o._OrtFree(h)),m.forEach(h=>o._OrtFree(h)),l!==0&&o._OrtReleaseBinding(l)!==0&&pe(\"Can't release IO binding.\"),i!==0&&o._OrtReleaseSession(i)!==0&&pe(\"Can't release session.\"),u}finally{o._free(r),a!==0&&o._OrtReleaseSessionOptions(a)!==0&&pe(\"Can't release session options.\"),d.forEach(u=>o._free(u)),o.unmountExternalData?.()}},Pr=e=>{let t=Ce(),r=kt.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,o,i,a,l]=r;a&&(l&&t._OrtClearBoundOutputs(a.handle)!==0&&pe(\"Can't clear bound outputs.\"),t._OrtReleaseBinding(a.handle)!==0&&pe(\"Can't release IO binding.\")),t.jsepOnReleaseSession?.(e),o.forEach(d=>t._OrtFree(d)),i.forEach(d=>t._OrtFree(d)),t._OrtReleaseSession(n)!==0&&pe(\"Can't release session.\"),kt.delete(e)},nc=(e,t,r,n,o,i=!1)=>{if(!e){t.push(0);return}let a=Ce(),l=a.PTR_SIZE,d=e[0],p=e[1],m=e[3],u,h;if(d===\"string\"&&(m===\"gpu-buffer\"||m===\"ml-tensor\"))throw new Error(\"String tensor is not supported on GPU.\");if(i&&m!==\"gpu-buffer\")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(m===\"gpu-buffer\"){let g=e[2].gpuBuffer;h=Tt(Zt(d),p);let x=a.jsepRegisterBuffer;if(!x)throw new Error('Tensor location \"gpu-buffer\" is not supported without using WebGPU.');u=x(n,o,g,h)}else if(m===\"ml-tensor\"){let g=e[2].mlTensor;h=Tt(Zt(d),p);let x=a.jsepRegisterMLTensor;if(!x)throw new Error('Tensor location \"ml-tensor\" is not supported without using WebNN.');u=x(g,Zt(d),p)}else{let g=e[2];if(Array.isArray(g)){h=l*g.length,u=a._malloc(h),r.push(u);for(let x=0;xa.setValue(y+$*l,x,l===4?\"i32\":\"i64\"));let g=a._OrtCreateTensor(Zt(d),u,h,y,p.length,Xn(m));g===0&&pe(`Can't create tensor for input/output. session=${n}, index=${o}.`),t.push(g)}finally{a.stackRestore(_)}},zr=async(e,t,r,n,o,i)=>{let a=Ce(),l=a.PTR_SIZE,d=kt.get(e);if(!d)throw new Error(`cannot run inference. invalid session id: ${e}`);let p=d[0],m=d[1],u=d[2],h=d[3],_=d[4],y=d[5],g=t.length,x=n.length,$=0,v=[],S=[],T=[],C=[],A=a.stackSave(),P=a.stackAlloc(g*l),O=a.stackAlloc(g*l),U=a.stackAlloc(x*l),G=a.stackAlloc(x*l);try{a.jsepOnRunStart?.(p),[$,v]=Wa(i);for(let W=0;W_e*be,1);ee=gt($e);let Ge=h?.outputPreferredLocations[n[W]];if(ee===\"string\"){if(Ge===\"gpu-buffer\"||Ge===\"ml-tensor\")throw new Error(\"String tensor is not supported on GPU.\");let _e=[];for(let be=0;be0){let _e=a.jsepGetBuffer;if(!_e)throw new Error('preferredLocation \"gpu-buffer\" is not supported without using WebGPU.');let be=_e(ne),Ke=Tt($e,he);if(Ke===void 0||!Ur(ee))throw new Error(`Unsupported data type: ${ee}`);re=!0,K.push([ee,j,{gpuBuffer:be,download:a.jsepCreateDownloader(be,Ke,ee),dispose:()=>{a._OrtReleaseTensor(Y)!==0&&pe(\"Can't release tensor.\")}},\"gpu-buffer\"])}else if(Ge===\"ml-tensor\"&&he>0){let _e=a.jsepEnsureTensor;if(!_e)throw new Error('preferredLocation \"ml-tensor\" is not supported without using WebNN.');if(Tt($e,he)===void 0||!Nr(ee))throw new Error(`Unsupported data type: ${ee}`);let Ke=await _e(ne,$e,j,!1);re=!0,K.push([ee,j,{mlTensor:Ke,download:a.jsepCreateMLTensorDownloader(ne,ee),dispose:()=>{a.jsepReleaseTensorId(ne),a._OrtReleaseTensor(Y)}},\"ml-tensor\"])}else{let _e=Rr(ee),be=new _e(he);new Uint8Array(be.buffer,be.byteOffset,be.byteLength).set(a.HEAPU8.subarray(ne,ne+be.byteLength)),K.push([ee,j,be,\"cpu\"])}}finally{a.stackRestore(se),ee===\"string\"&&ne&&a._free(ne),re||a._OrtReleaseTensor(Y)}}return h&&!_&&(a._OrtClearBoundOutputs(h.handle)!==0&&pe(\"Can't clear bound outputs.\"),kt.set(e,[p,m,u,h,_,!1])),K}finally{a.stackRestore(A),S.forEach(q=>a._OrtReleaseTensor(q)),T.forEach(q=>a._OrtReleaseTensor(q)),C.forEach(q=>a._free(q)),$!==0&&a._OrtReleaseRunOptions($),v.forEach(q=>a._free(q))}},Or=e=>{let t=Ce(),r=kt.get(e);if(!r)throw new Error(\"invalid session id\");let n=r[0],o=t._OrtEndProfiling(n);o===0&&pe(\"Can't get an profile file name.\"),t._OrtFree(o)},Br=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&\"buffer\"in n&&t.push(n.buffer)}return t}});var Et,Le,or,mn,fn,pn,zo,Oo,Vt,Wt,pg,oc,ic,ac,sc,uc,lc,dc,Bo=R(()=>{\"use strict\";We();Kn();ht();jt();Et=()=>!!we.wasm.proxy&&typeof document<\"u\",or=!1,mn=!1,fn=!1,Oo=new Map,Vt=(e,t)=>{let r=Oo.get(e);r?r.push(t):Oo.set(e,[t])},Wt=()=>{if(or||!mn||fn||!Le)throw new Error(\"worker not ready\")},pg=e=>{switch(e.data.type){case\"init-wasm\":or=!1,e.data.err?(fn=!0,zo[1](e.data.err)):(mn=!0,zo[0]()),pn&&(URL.revokeObjectURL(pn),pn=void 0);break;case\"init-ep\":case\"copy-from\":case\"create\":case\"release\":case\"run\":case\"end-profiling\":{let t=Oo.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},oc=async()=>{if(!mn){if(or)throw new Error(\"multiple calls to 'initWasm()' detected.\");if(fn)throw new Error(\"previous call to 'initWasm()' failed.\");if(or=!0,Et())return new Promise((e,t)=>{Le?.terminate(),Ua().then(([r,n])=>{try{Le=n,Le.onerror=i=>t(i),Le.onmessage=pg,zo=[e,t];let o={type:\"init-wasm\",in:we};Le.postMessage(o),pn=r}catch(o){t(o)}},t)});try{await Cr(we.wasm),await Ar(we),mn=!0}catch(e){throw fn=!0,e}finally{or=!1}}},ic=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Vt(\"init-ep\",[t,r]);let n={type:\"init-ep\",in:{epName:e,env:we}};Le.postMessage(n)});await kr(we,e)},ac=async e=>Et()?(Wt(),new Promise((t,r)=>{Vt(\"copy-from\",[t,r]);let n={type:\"copy-from\",in:{buffer:e}};Le.postMessage(n,[e.buffer])})):Kt(e),sc=async(e,t)=>{if(Et()){if(t?.preferredOutputLocation)throw new Error('session option \"preferredOutputLocation\" is not supported for proxy.');return Wt(),new Promise((r,n)=>{Vt(\"create\",[r,n]);let o={type:\"create\",in:{model:e,options:{...t}}},i=[];e instanceof Uint8Array&&i.push(e.buffer),Le.postMessage(o,i)})}else return Er(e,t)},uc=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Vt(\"release\",[t,r]);let n={type:\"release\",in:e};Le.postMessage(n)});Pr(e)},lc=async(e,t,r,n,o,i)=>{if(Et()){if(r.some(a=>a[3]!==\"cpu\"))throw new Error(\"input tensor on GPU is not supported for proxy.\");if(o.some(a=>a))throw new Error(\"pre-allocated output tensor is not supported for proxy.\");return Wt(),new Promise((a,l)=>{Vt(\"run\",[a,l]);let d=r,p={type:\"run\",in:{sessionId:e,inputIndices:t,inputs:d,outputIndices:n,options:i}};Le.postMessage(p,Br(d))})}else return zr(e,t,r,n,o,i)},dc=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Vt(\"end-profiling\",[t,r]);let n={type:\"end-profiling\",in:e};Le.postMessage(n)});Or(e)}});var cc,mg,hn,pc=R(()=>{\"use strict\";We();Bo();te();Ir();Jn();cc=(e,t)=>{switch(e.location){case\"cpu\":return[e.type,e.dims,e.data,\"cpu\"];case\"gpu-buffer\":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},\"gpu-buffer\"];case\"ml-tensor\":return[e.type,e.dims,{mlTensor:e.mlTensor},\"ml-tensor\"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},mg=e=>{switch(e[3]){case\"cpu\":return new Oe(e[0],e[2],e[1]);case\"gpu-buffer\":{let t=e[0];if(!Ur(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:o}=e[2];return Oe.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:o})}case\"ml-tensor\":{let t=e[0];if(!Nr(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:o}=e[2];return Oe.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},hn=class{async fetchModelAndCopyToWasmMemory(t){return ac(await Xt(t))}async loadModel(t,r){Ue();let n;typeof t==\"string\"?!1?n=await Xt(t):n=await this.fetchModelAndCopyToWasmMemory(t):n=t,[this.sessionId,this.inputNames,this.outputNames]=await sc(n,r),De()}async dispose(){return uc(this.sessionId)}async run(t,r,n){Ue();let o=[],i=[];Object.entries(t).forEach(h=>{let _=h[0],y=h[1],g=this.inputNames.indexOf(_);if(g===-1)throw new Error(`invalid input '${_}'`);o.push(y),i.push(g)});let a=[],l=[];Object.entries(r).forEach(h=>{let _=h[0],y=h[1],g=this.outputNames.indexOf(_);if(g===-1)throw new Error(`invalid output '${_}'`);a.push(y),l.push(g)});let d=o.map((h,_)=>cc(h,()=>`input \"${this.inputNames[i[_]]}\"`)),p=a.map((h,_)=>h?cc(h,()=>`output \"${this.outputNames[l[_]]}\"`):null),m=await lc(this.sessionId,i,d,l,p,n),u={};for(let h=0;hgn,initializeFlags:()=>mc,wasmBackend:()=>fg});var mc,gn,fg,hc=R(()=>{\"use strict\";We();Bo();pc();jt();mc=()=>{if((typeof we.wasm.initTimeout!=\"number\"||we.wasm.initTimeout<0)&&(we.wasm.initTimeout=0),we.wasm.simd===!1&&console.warn('Deprecated property \"env.wasm.simd\" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof we.wasm.proxy!=\"boolean\"&&(we.wasm.proxy=!1),typeof we.wasm.trace!=\"boolean\"&&(we.wasm.trace=!1),typeof we.wasm.numThreads!=\"number\"||!Number.isInteger(we.wasm.numThreads)||we.wasm.numThreads<=0)if(typeof self<\"u\"&&!self.crossOriginIsolated)we.wasm.numThreads=1;else{let e=typeof navigator>\"u\"?Gn(\"node:os\").cpus().length:navigator.hardwareConcurrency;we.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},gn=class{async init(t){mc(),await oc(),await ic(t)}async createInferenceSessionHandler(t,r){let n=new hn;return await n.loadModel(t,r),Promise.resolve(n)}},fg=new gn});We();We();We();var ka=\"1.21.0-dev.20241122-a2ba3cb547\";var bS=jn;{let e=(hc(),br(fc)).wasmBackend;xt(\"webgpu\",e,5),xt(\"webnn\",e,5),xt(\"cpu\",e,10),xt(\"wasm\",e,10)}Object.defineProperty(we.versions,\"web\",{value:ka,enumerable:!0});export{Np as InferenceSession,xr as TRACE,Ue as TRACE_FUNC_BEGIN,De as TRACE_FUNC_END,Oe as Tensor,Wp as TrainingSession,bS as default,we as env,xt as registerBackend};\n/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n//# sourceMappingURL=ort.webgpu.bundle.min.mjs.map\n","/**\n * @file Handler file for choosing the correct version of ONNX Runtime, based on the environment.\n * Ideally, we could import the `onnxruntime-web` and `onnxruntime-node` packages only when needed,\n * but dynamic imports don't seem to work with the current webpack version and/or configuration.\n * This is possibly due to the experimental nature of top-level await statements.\n * So, we just import both packages, and use the appropriate one based on the environment:\n * - When running in node, we use `onnxruntime-node`.\n * - When running in the browser, we use `onnxruntime-web` (`onnxruntime-node` is not bundled).\n * \n * This module is not directly exported, but can be accessed through the environment variables:\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * console.log(env.backends.onnx);\n * ```\n * \n * @module backends/onnx\n */\n\nimport { env, apis } from '../env.js';\n\n// NOTE: Import order matters here. We need to import `onnxruntime-node` before `onnxruntime-web`.\n// In either case, we select the default export if it exists, otherwise we use the named export.\nimport * as ONNX_NODE from 'onnxruntime-node';\n\n// Use subpath-imports to ensure Node.js and browser interoperability.\n// See package.json and https://nodejs.org/api/packages.html#subpath-imports\n// for more information.\n// @ts-ignore\nimport * as ONNX_WEB from '#onnxruntime-webgpu';\n\nexport { Tensor } from 'onnxruntime-common';\n\n/**\n * @typedef {import('onnxruntime-common').InferenceSession.ExecutionProviderConfig} ONNXExecutionProviders\n */\n\n/** @type {Record} */\nconst DEVICE_TO_EXECUTION_PROVIDER_MAPPING = Object.freeze({\n auto: null, // Auto-detect based on device and environment\n gpu: null, // Auto-detect GPU\n cpu: 'cpu', // CPU\n wasm: 'wasm', // WebAssembly\n webgpu: 'webgpu', // WebGPU\n cuda: 'cuda', // CUDA\n dml: 'dml', // DirectML\n\n webnn: { name: 'webnn', deviceType: 'cpu' }, // WebNN (default)\n 'webnn-npu': { name: 'webnn', deviceType: 'npu' }, // WebNN NPU\n 'webnn-gpu': { name: 'webnn', deviceType: 'gpu' }, // WebNN GPU\n 'webnn-cpu': { name: 'webnn', deviceType: 'cpu' }, // WebNN CPU\n});\n\n/** \n * The list of supported devices, sorted by priority/performance.\n * @type {import(\"../utils/devices.js\").DeviceType[]}\n */\nconst supportedDevices = [];\n\n/** @type {ONNXExecutionProviders[]} */\nlet defaultDevices;\nlet ONNX;\nconst ORT_SYMBOL = Symbol.for('onnxruntime');\n\nif (ORT_SYMBOL in globalThis) {\n // If the JS runtime exposes their own ONNX runtime, use it\n ONNX = globalThis[ORT_SYMBOL];\n\n} else if (apis.IS_NODE_ENV) {\n ONNX = ONNX_NODE.default ?? ONNX_NODE;\n\n // Updated as of ONNX Runtime 1.18.0\n // The following table lists the supported versions of ONNX Runtime Node.js binding provided with pre-built binaries.\n // | EPs/Platforms | Windows x64 | Windows arm64 | Linux x64 | Linux arm64 | MacOS x64 | MacOS arm64 |\n // | ------------- | ----------- | ------------- | ----------------- | ----------- | --------- | ----------- |\n // | CPU | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |\n // | DirectML | ✔️ | ✔️ | ❌ | ❌ | ❌ | ❌ |\n // | CUDA | ❌ | ❌ | ✔️ (CUDA v11.8) | ❌ | ❌ | ❌ |\n switch (process.platform) {\n case 'win32': // Windows x64 and Windows arm64\n supportedDevices.push('dml');\n break;\n case 'linux': // Linux x64 and Linux arm64\n if (process.arch === 'x64') {\n supportedDevices.push('cuda');\n }\n break;\n case 'darwin': // MacOS x64 and MacOS arm64\n break;\n }\n\n supportedDevices.push('cpu');\n defaultDevices = ['cpu'];\n} else {\n ONNX = ONNX_WEB;\n\n if (apis.IS_WEBNN_AVAILABLE) {\n // TODO: Only push supported providers (depending on available hardware)\n supportedDevices.push('webnn-npu', 'webnn-gpu', 'webnn-cpu', 'webnn');\n }\n\n if (apis.IS_WEBGPU_AVAILABLE) {\n supportedDevices.push('webgpu');\n }\n\n supportedDevices.push('wasm');\n defaultDevices = ['wasm'];\n}\n\n// @ts-ignore\nconst InferenceSession = ONNX.InferenceSession;\n\n/**\n * Map a device to the execution providers to use for the given device.\n * @param {import(\"../utils/devices.js\").DeviceType|\"auto\"|null} [device=null] (Optional) The device to run the inference on.\n * @returns {ONNXExecutionProviders[]} The execution providers to use for the given device.\n */\nexport function deviceToExecutionProviders(device = null) {\n // Use the default execution providers if the user hasn't specified anything\n if (!device) return defaultDevices;\n\n // Handle overloaded cases\n switch (device) {\n case \"auto\":\n return supportedDevices;\n case \"gpu\":\n return supportedDevices.filter(x =>\n [\"webgpu\", \"cuda\", \"dml\", \"webnn-gpu\"].includes(x),\n );\n }\n\n if (supportedDevices.includes(device)) {\n return [DEVICE_TO_EXECUTION_PROVIDER_MAPPING[device] ?? device];\n }\n\n throw new Error(`Unsupported device: \"${device}\". Should be one of: ${supportedDevices.join(', ')}.`)\n}\n\n\n/**\n * To prevent multiple calls to `initWasm()`, we store the first call in a Promise\n * that is resolved when the first InferenceSession is created. Subsequent calls\n * will wait for this Promise to resolve before creating their own InferenceSession.\n * @type {Promise|null}\n */\nlet wasmInitPromise = null;\n\n/**\n * Create an ONNX inference session.\n * @param {Uint8Array} buffer The ONNX model buffer.\n * @param {import('onnxruntime-common').InferenceSession.SessionOptions} session_options ONNX inference session options.\n * @param {Object} session_config ONNX inference session configuration.\n * @returns {Promise} The ONNX inference session.\n */\nexport async function createInferenceSession(buffer, session_options, session_config) {\n if (wasmInitPromise) {\n // A previous session has already initialized the WASM runtime\n // so we wait for it to resolve before creating this new session.\n await wasmInitPromise;\n }\n\n const sessionPromise = InferenceSession.create(buffer, session_options);\n wasmInitPromise ??= sessionPromise;\n const session = await sessionPromise;\n session.config = session_config;\n return session;\n}\n\n/**\n * Check if an object is an ONNX tensor.\n * @param {any} x The object to check\n * @returns {boolean} Whether the object is an ONNX tensor.\n */\nexport function isONNXTensor(x) {\n return x instanceof ONNX.Tensor;\n}\n\n/** @type {import('onnxruntime-common').Env} */\n// @ts-ignore\nconst ONNX_ENV = ONNX?.env;\nif (ONNX_ENV?.wasm) {\n // Initialize wasm backend with suitable default settings.\n\n // (Optional) Set path to wasm files. This is needed when running in a web worker.\n // https://onnxruntime.ai/docs/api/js/interfaces/Env.WebAssemblyFlags.html#wasmPaths\n // We use remote wasm files by default to make it easier for newer users.\n // In practice, users should probably self-host the necessary .wasm files.\n ONNX_ENV.wasm.wasmPaths = `https://cdn.jsdelivr.net/npm/@huggingface/transformers@${env.version}/dist/`;\n\n // TODO: Add support for loading WASM files from cached buffer when we upgrade to onnxruntime-web@1.19.0\n // https://github.com/microsoft/onnxruntime/pull/21534\n\n // Users may wish to proxy the WASM backend to prevent the UI from freezing,\n // However, this is not necessary when using WebGPU, so we default to false.\n ONNX_ENV.wasm.proxy = false;\n\n // https://developer.mozilla.org/en-US/docs/Web/API/crossOriginIsolated\n if (typeof crossOriginIsolated === 'undefined' || !crossOriginIsolated) {\n ONNX_ENV.wasm.numThreads = 1;\n }\n}\n\nif (ONNX_ENV?.webgpu) {\n ONNX_ENV.webgpu.powerPreference = 'high-performance';\n}\n\n/**\n * Check if ONNX's WASM backend is being proxied.\n * @returns {boolean} Whether ONNX's WASM backend is being proxied.\n */\nexport function isONNXProxy() {\n // TODO: Update this when allowing non-WASM backends.\n return ONNX_ENV?.wasm?.proxy;\n}\n\n// Expose ONNX environment variables to `env.backends.onnx`\nenv.backends.onnx = ONNX_ENV;\n","\n/**\n * @file Helper module for using model configs. For more information, see the corresponding\n * [Python documentation](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoConfig).\n * \n * **Example:** Load an `AutoConfig`.\n * \n * ```javascript\n * import { AutoConfig } from '@huggingface/transformers';\n * const config = await AutoConfig.from_pretrained('bert-base-uncased');\n * console.log(config);\n * // PretrainedConfig {\n * // \"model_type\": \"bert\",\n * // \"is_encoder_decoder\": false,\n * // \"architectures\": [\n * // \"BertForMaskedLM\"\n * // ],\n * // \"vocab_size\": 30522\n * // \"num_attention_heads\": 12,\n * // \"num_hidden_layers\": 12,\n * // \"hidden_size\": 768,\n * // \"max_position_embeddings\": 512,\n * // ...\n * // }\n * ```\n * \n * @module configs\n */\n\nimport { pick } from './utils/core.js';\nimport {\n getModelJSON,\n} from './utils/hub.js';\n\n/**\n * @typedef {import('./utils/hub.js').PretrainedOptions} PretrainedOptions\n */\n\n\n/**\n * Loads a config from the specified path.\n * @param {string} pretrained_model_name_or_path The path to the config directory.\n * @param {PretrainedOptions} options Additional options for loading the config.\n * @returns {Promise} A promise that resolves with information about the loaded config.\n */\nasync function loadConfig(pretrained_model_name_or_path, options) {\n return await getModelJSON(pretrained_model_name_or_path, 'config.json', true, options);\n}\n\n/**\n * \n * @param {PretrainedConfig} config \n * @returns {Object} The normalized configuration.\n */\nfunction getNormalizedConfig(config) {\n const mapping = {};\n\n let init_normalized_config = {};\n switch (config.model_type) {\n // Sub-configs\n case 'llava':\n case 'paligemma':\n case 'florence2':\n init_normalized_config = getNormalizedConfig(config.text_config);\n break;\n case 'moondream1':\n init_normalized_config = getNormalizedConfig(config.phi_config);\n break;\n case 'musicgen':\n init_normalized_config = getNormalizedConfig(config.decoder);\n break;\n\n // Decoder-only models\n case 'gpt2':\n case 'gptj':\n case 'jais':\n case 'codegen':\n case 'gpt_bigcode':\n mapping['num_heads'] = 'n_head';\n mapping['num_layers'] = 'n_layer';\n mapping['hidden_size'] = 'n_embd';\n break;\n case 'gpt_neox':\n case 'stablelm':\n case 'opt':\n case 'phi':\n case 'phi3':\n case 'falcon':\n mapping['num_heads'] = 'num_attention_heads';\n mapping['num_layers'] = 'num_hidden_layers';\n mapping['hidden_size'] = 'hidden_size';\n break;\n case 'llama':\n case 'granite':\n case 'cohere':\n case 'mistral':\n case 'starcoder2':\n case 'qwen2':\n mapping['num_heads'] = 'num_key_value_heads';\n mapping['num_layers'] = 'num_hidden_layers';\n mapping['hidden_size'] = 'hidden_size';\n mapping['num_attention_heads'] = 'num_attention_heads';\n break;\n case 'gemma':\n case 'gemma2':\n mapping['num_heads'] = 'num_key_value_heads';\n mapping['num_layers'] = 'num_hidden_layers';\n mapping['dim_kv'] = 'head_dim';\n break;\n case 'openelm':\n mapping['num_heads'] = 'num_kv_heads';\n mapping['num_layers'] = 'num_transformer_layers';\n mapping['dim_kv'] = 'head_dim';\n break;\n case 'gpt_neo':\n case 'donut-swin':\n mapping['num_heads'] = 'num_heads';\n mapping['num_layers'] = 'num_layers';\n mapping['hidden_size'] = 'hidden_size';\n break;\n case 'bloom':\n mapping['num_heads'] = 'n_head';\n mapping['num_layers'] = 'n_layer';\n mapping['hidden_size'] = 'hidden_size';\n break;\n case 'mpt':\n mapping['num_heads'] = 'n_heads';\n mapping['num_layers'] = 'n_layers';\n mapping['hidden_size'] = 'd_model';\n break;\n\n // Encoder-decoder models\n case 't5':\n case 'mt5':\n case 'longt5':\n mapping['num_decoder_layers'] = 'num_decoder_layers';\n mapping['num_decoder_heads'] = 'num_heads';\n mapping['decoder_dim_kv'] = 'd_kv';\n mapping['num_encoder_layers'] = 'num_layers';\n mapping['num_encoder_heads'] = 'num_heads';\n mapping['encoder_dim_kv'] = 'd_kv';\n break;\n case 'bart':\n case 'mbart':\n case 'marian':\n case 'whisper':\n case 'm2m_100':\n case 'blenderbot':\n case 'blenderbot-small':\n case 'florence2_language':\n mapping['num_decoder_layers'] = 'decoder_layers';\n mapping['num_decoder_heads'] = 'decoder_attention_heads';\n mapping['decoder_hidden_size'] = 'd_model';\n mapping['num_encoder_layers'] = 'encoder_layers';\n mapping['num_encoder_heads'] = 'encoder_attention_heads';\n mapping['encoder_hidden_size'] = 'd_model';\n break;\n case 'speecht5':\n mapping['num_decoder_layers'] = 'decoder_layers';\n mapping['num_decoder_heads'] = 'decoder_attention_heads';\n mapping['decoder_hidden_size'] = 'hidden_size';\n mapping['num_encoder_layers'] = 'encoder_layers';\n mapping['num_encoder_heads'] = 'encoder_attention_heads';\n mapping['encoder_hidden_size'] = 'hidden_size';\n break;\n case 'trocr':\n mapping['num_encoder_layers'] = mapping['num_decoder_layers'] = 'decoder_layers';\n mapping['num_encoder_heads'] = mapping['num_decoder_heads'] = 'decoder_attention_heads';\n mapping['encoder_hidden_size'] = mapping['decoder_hidden_size'] = 'd_model';\n break;\n case 'musicgen_decoder':\n mapping['num_encoder_layers'] = mapping['num_decoder_layers'] = 'num_hidden_layers';\n mapping['num_encoder_heads'] = mapping['num_decoder_heads'] = 'num_attention_heads';\n mapping['encoder_hidden_size'] = mapping['decoder_hidden_size'] = 'hidden_size';\n break;\n\n case 'vision-encoder-decoder':\n const decoderConfig = getNormalizedConfig(config.decoder);\n\n const add_encoder_pkv = 'num_decoder_layers' in decoderConfig;\n const result = pick(config, ['model_type', 'is_encoder_decoder']);\n if (add_encoder_pkv) {\n // Decoder is part of an encoder-decoder model\n result.num_decoder_layers = decoderConfig.num_decoder_layers;\n result.num_decoder_heads = decoderConfig.num_decoder_heads;\n result.decoder_hidden_size = decoderConfig.decoder_hidden_size;\n\n result.num_encoder_layers = decoderConfig.num_encoder_layers;\n result.num_encoder_heads = decoderConfig.num_encoder_heads;\n result.encoder_hidden_size = decoderConfig.encoder_hidden_size;\n } else {\n // Decoder is a decoder-only model\n result.num_layers = decoderConfig.num_layers;\n result.num_heads = decoderConfig.num_heads;\n result.hidden_size = decoderConfig.hidden_size;\n }\n return result;\n\n }\n\n // NOTE: If `num_attention_heads` is not set, it is assumed to be equal to `num_heads`\n const normalized_config = {\n ...init_normalized_config,\n ...pick(config, ['model_type', 'multi_query', 'is_encoder_decoder']),\n };\n for (const key in mapping) {\n normalized_config[key] = config[mapping[key]];\n }\n return normalized_config;\n}\n\n/**\n * \n * @param {PretrainedConfig} config \n * @returns {Record}\n */\nexport function getKeyValueShapes(config, {\n prefix = 'past_key_values',\n} = {}) {\n /** @type {Record} */\n const decoderFeeds = {};\n const normalized_config = config.normalized_config;\n\n // TODO support batches (i.e., batch_size > 1)\n const batch_size = 1;\n\n if (normalized_config.is_encoder_decoder && (\n 'num_encoder_heads' in normalized_config && 'num_decoder_heads' in normalized_config\n )) {\n const encoder_dim_kv = normalized_config.encoder_dim_kv ?? (\n normalized_config.encoder_hidden_size / normalized_config.num_encoder_heads\n );\n const decoder_dim_kv = normalized_config.decoder_dim_kv ?? (\n normalized_config.decoder_hidden_size / normalized_config.num_decoder_heads\n );\n\n const encoder_dims = [batch_size, normalized_config.num_encoder_heads, 0, encoder_dim_kv];\n const decoder_dims = [batch_size, normalized_config.num_decoder_heads, 0, decoder_dim_kv];\n for (let i = 0; i < normalized_config.num_decoder_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.encoder.key`] = encoder_dims;\n decoderFeeds[`${prefix}.${i}.encoder.value`] = encoder_dims;\n decoderFeeds[`${prefix}.${i}.decoder.key`] = decoder_dims;\n decoderFeeds[`${prefix}.${i}.decoder.value`] = decoder_dims;\n }\n } else { // Decoders\n const num_heads = normalized_config.num_heads;\n const num_layers = normalized_config.num_layers;\n const dim_kv = normalized_config.dim_kv ?? (\n normalized_config.hidden_size /\n (normalized_config.num_attention_heads ?? num_heads)\n );\n\n if (normalized_config.model_type === 'falcon') {\n // NOTE: Custom implementation for Falcon\n const dims = [batch_size * num_heads, 0, dim_kv]\n for (let i = 0; i < num_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.key`] = dims;\n decoderFeeds[`${prefix}.${i}.value`] = dims;\n }\n } else if (normalized_config.multi_query) { // e.g., for `gpt_bigcode`\n const dims = [batch_size * num_heads, 0, 2 * dim_kv]\n\n for (let i = 0; i < num_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.key_value`] = dims;\n }\n } else if (normalized_config.model_type === 'bloom') {\n // NOTE: Custom implementation for Bloom\n\n const keyDims = [batch_size * num_heads, dim_kv, 0] // [batch_size x num_heads,64,past_sequence_length]\n const valueDims = [batch_size * num_heads, 0, dim_kv] // [batch_size x num_heads,past_sequence_length,64]\n for (let i = 0; i < num_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.key`] = keyDims;\n decoderFeeds[`${prefix}.${i}.value`] = valueDims;\n }\n } else if (normalized_config.model_type === 'openelm') {\n for (let i = 0; i < num_layers; ++i) {\n const dims = [batch_size, num_heads[i], 0, dim_kv]\n\n decoderFeeds[`${prefix}.${i}.key`] = dims;\n decoderFeeds[`${prefix}.${i}.value`] = dims;\n }\n } else { // Decoder-only\n const dims = [batch_size, num_heads, 0, dim_kv]\n for (let i = 0; i < num_layers; ++i) {\n decoderFeeds[`${prefix}.${i}.key`] = dims;\n decoderFeeds[`${prefix}.${i}.value`] = dims;\n }\n }\n }\n\n return decoderFeeds;\n}\n/**\n * Base class for all configuration classes. For more information, see the corresponding\n * [Python documentation](https://huggingface.co/docs/transformers/main/en/main_classes/configuration#transformers.PretrainedConfig).\n */\nexport class PretrainedConfig {\n // NOTE: Typo in original\n\n /** @type {string|null} */\n model_type = null;\n\n /** @type {boolean} */\n is_encoder_decoder = false;\n\n /** @type {number} */\n max_position_embeddings;\n\n /** @type {TransformersJSConfig} */\n 'transformers.js_config';\n\n /**\n * Create a new PreTrainedTokenizer instance.\n * @param {Object} configJSON The JSON of the config.\n */\n constructor(configJSON) {\n Object.assign(this, configJSON);\n this.normalized_config = getNormalizedConfig(this);\n }\n\n /**\n * Loads a pre-trained config from the given `pretrained_model_name_or_path`. \n * \n * @param {string} pretrained_model_name_or_path The path to the pre-trained config.\n * @param {PretrainedOptions} options Additional options for loading the config.\n * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.\n * \n * @returns {Promise} A new instance of the `PretrainedConfig` class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n } = {}) {\n if (config && !(config instanceof PretrainedConfig)) {\n config = new PretrainedConfig(config);\n }\n\n const data = config ?? await loadConfig(pretrained_model_name_or_path, {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n })\n return new this(data);\n }\n}\n\n/**\n * Helper class which is used to instantiate pretrained configs with the `from_pretrained` function.\n * \n * @example\n * const config = await AutoConfig.from_pretrained('Xenova/bert-base-uncased'); \n */\nexport class AutoConfig {\n /** @type {typeof PretrainedConfig.from_pretrained} */\n static async from_pretrained(...args) {\n return PretrainedConfig.from_pretrained(...args);\n }\n}\n\n/**\n * Transformers.js-specific configuration, possibly present in config.json under the key `transformers.js_config`.\n * @typedef {Object} TransformersJSConfig\n * @property {import('./utils/tensor.js').DataType|Record} [kv_cache_dtype] The data type of the key-value cache.\n * @property {Record} [free_dimension_overrides] Override the free dimensions of the model.\n * See https://onnxruntime.ai/docs/tutorials/web/env-flags-and-session-options.html#freedimensionoverrides\n * for more information.\n * @property {import('./utils/devices.js').DeviceType} [device] The default device to use for the model.\n * @property {import('./utils/dtypes.js').DataType} [dtype] The default data type to use for the model.\n * @property {boolean|Record} [use_external_data_format=false] Whether to load the model using the external data format (used for models >= 2GB in size).\n */\n","/**\n * @file Module used to configure Transformers.js.\n * \n * **Example:** Disable remote models.\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * env.allowRemoteModels = false;\n * ```\n * \n * **Example:** Set local model path.\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * env.localModelPath = '/path/to/local/models/';\n * ```\n * \n * **Example:** Set cache directory.\n * ```javascript\n * import { env } from '@huggingface/transformers';\n * env.cacheDir = '/path/to/cache/directory/';\n * ```\n * \n * @module env\n */\n\nimport fs from 'fs';\nimport path from 'path';\nimport url from 'url';\n\nconst VERSION = '3.0.0';\n\n// Check if various APIs are available (depends on environment)\nconst IS_BROWSER_ENV = typeof self !== 'undefined';\nconst IS_WEBWORKER_ENV = IS_BROWSER_ENV && self.constructor.name === 'DedicatedWorkerGlobalScope';\nconst IS_WEB_CACHE_AVAILABLE = IS_BROWSER_ENV && 'caches' in self;\nconst IS_WEBGPU_AVAILABLE = typeof navigator !== 'undefined' && 'gpu' in navigator;\nconst IS_WEBNN_AVAILABLE = typeof navigator !== 'undefined' && 'ml' in navigator;\n\nconst IS_PROCESS_AVAILABLE = typeof process !== 'undefined';\nconst IS_NODE_ENV = IS_PROCESS_AVAILABLE && process?.release?.name === 'node';\nconst IS_FS_AVAILABLE = !isEmpty(fs);\nconst IS_PATH_AVAILABLE = !isEmpty(path);\n\n/**\n * A read-only object containing information about the APIs available in the current environment.\n */\nexport const apis = Object.freeze({\n /** Whether we are running in a browser environment */\n IS_BROWSER_ENV,\n\n /** Whether we are running in a web worker environment */\n IS_WEBWORKER_ENV,\n\n /** Whether the Cache API is available */\n IS_WEB_CACHE_AVAILABLE,\n\n /** Whether the WebGPU API is available */\n IS_WEBGPU_AVAILABLE,\n\n /** Whether the WebNN API is available */\n IS_WEBNN_AVAILABLE,\n\n /** Whether the Node.js process API is available */\n IS_PROCESS_AVAILABLE,\n\n /** Whether we are running in a Node.js environment */\n IS_NODE_ENV,\n\n /** Whether the filesystem API is available */\n IS_FS_AVAILABLE,\n\n /** Whether the path API is available */\n IS_PATH_AVAILABLE,\n});\n\nconst RUNNING_LOCALLY = IS_FS_AVAILABLE && IS_PATH_AVAILABLE;\nconst dirname__ = RUNNING_LOCALLY\n ? path.dirname(path.dirname(url.fileURLToPath(import.meta.url)))\n : './';\n\n// Only used for environments with access to file system\nconst DEFAULT_CACHE_DIR = RUNNING_LOCALLY\n ? path.join(dirname__, '/.cache/')\n : null;\n\n// Set local model path, based on available APIs\nconst DEFAULT_LOCAL_MODEL_PATH = '/models/';\nconst localModelPath = RUNNING_LOCALLY\n ? path.join(dirname__, DEFAULT_LOCAL_MODEL_PATH)\n : DEFAULT_LOCAL_MODEL_PATH;\n\n/**\n * Global variable given visible to users to control execution. This provides users a simple way to configure Transformers.js.\n * @typedef {Object} TransformersEnvironment\n * @property {string} version This version of Transformers.js.\n * @property {{onnx: Partial}} backends Expose environment variables of different backends,\n * allowing users to set these variables if they want to.\n * @property {boolean} allowRemoteModels Whether to allow loading of remote files, defaults to `true`.\n * If set to `false`, it will have the same effect as setting `local_files_only=true` when loading pipelines, models, tokenizers, processors, etc.\n * @property {string} remoteHost Host URL to load models from. Defaults to the Hugging Face Hub.\n * @property {string} remotePathTemplate Path template to fill in and append to `remoteHost` when loading models.\n * @property {boolean} allowLocalModels Whether to allow loading of local files, defaults to `false` if running in-browser, and `true` otherwise.\n * If set to `false`, it will skip the local file check and try to load the model from the remote host.\n * @property {string} localModelPath Path to load local models from. Defaults to `/models/`.\n * @property {boolean} useFS Whether to use the file system to load files. By default, it is `true` if available.\n * @property {boolean} useBrowserCache Whether to use Cache API to cache models. By default, it is `true` if available.\n * @property {boolean} useFSCache Whether to use the file system to cache files. By default, it is `true` if available.\n * @property {string} cacheDir The directory to use for caching files with the file system. By default, it is `./.cache`.\n * @property {boolean} useCustomCache Whether to use a custom cache system (defined by `customCache`), defaults to `false`.\n * @property {Object} customCache The custom cache to use. Defaults to `null`. Note: this must be an object which\n * implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache\n */\n\n/** @type {TransformersEnvironment} */\nexport const env = {\n version: VERSION,\n\n /////////////////// Backends settings ///////////////////\n // NOTE: These will be populated later by the backends themselves.\n backends: {\n // onnxruntime-web/onnxruntime-node\n onnx: {},\n },\n\n /////////////////// Model settings ///////////////////\n allowRemoteModels: true,\n remoteHost: 'https://huggingface.co/',\n remotePathTemplate: '{model}/resolve/{revision}/',\n\n allowLocalModels: !IS_BROWSER_ENV,\n localModelPath: localModelPath,\n useFS: IS_FS_AVAILABLE,\n\n /////////////////// Cache settings ///////////////////\n useBrowserCache: IS_WEB_CACHE_AVAILABLE,\n\n useFSCache: IS_FS_AVAILABLE,\n cacheDir: DEFAULT_CACHE_DIR,\n\n useCustomCache: false,\n customCache: null,\n //////////////////////////////////////////////////////\n}\n\n\n/**\n * @param {Object} obj\n * @private\n */\nfunction isEmpty(obj) {\n return Object.keys(obj).length === 0;\n}\n\n","\n/**\n * @module generation/configuration_utils\n */\n\nimport { pick } from \"../utils/core.js\";\n\n/**\n * Class that holds a configuration for a generation task.\n */\nexport class GenerationConfig {\n // Parameters that control the length of the output\n /**\n * The maximum length the generated tokens can have.\n * Corresponds to the length of the input prompt + `max_new_tokens`.\n * Its effect is overridden by `max_new_tokens`, if also set.\n * @type {number}\n * @default 20\n */\n max_length = 20;\n\n /**\n * The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt.\n * @type {number}\n * @default null\n */\n max_new_tokens = null;\n\n /**\n * The minimum length of the sequence to be generated.\n * Corresponds to the length of the input prompt + `min_new_tokens`.\n * Its effect is overridden by `min_new_tokens`, if also set.\n * @type {number}\n * @default 0\n */\n min_length = 0;\n\n /**\n * The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt.\n * @type {number}\n * @default null\n */\n min_new_tokens = null;\n\n /**\n * Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:\n * - `true`, where the generation stops as soon as there are `num_beams` complete candidates;\n * - `false`, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates;\n * - `\"never\"`, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm).\n * @type {boolean|\"never\"}\n * @default false\n */\n early_stopping = false;\n\n /**\n * The maximum amount of time you allow the computation to run for in seconds.\n * Generation will still finish the current pass after allocated time has been passed.\n * @type {number}\n * @default null\n */\n max_time = null;\n\n // Parameters that control the generation strategy used\n /**\n * Whether or not to use sampling; use greedy decoding otherwise.\n * @type {boolean}\n * @default false\n */\n do_sample = false;\n\n /**\n * Number of beams for beam search. 1 means no beam search.\n * @type {number}\n * @default 1\n */\n num_beams = 1;\n\n /**\n * Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams.\n * See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.\n * @type {number}\n * @default 1\n */\n num_beam_groups = 1;\n\n /**\n * The values balance the model confidence and the degeneration penalty in contrastive search decoding.\n * @type {number}\n * @default null\n */\n penalty_alpha = null;\n\n /**\n * Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding.\n * @type {boolean}\n * @default true\n */\n use_cache = true;\n\n // Parameters for manipulation of the model output logits\n /**\n * The value used to modulate the next token probabilities.\n * @type {number}\n * @default 1.0\n */\n temperature = 1.0;\n\n /**\n * The number of highest probability vocabulary tokens to keep for top-k-filtering.\n * @type {number}\n * @default 50\n */\n top_k = 50;\n\n /**\n * If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation.\n * @type {number}\n * @default 1.0\n */\n top_p = 1.0;\n\n /**\n * Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated.\n * If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to `typical_p` or higher are kept for generation.\n * See [this paper](https://arxiv.org/pdf/2202.00666.pdf) for more details.\n * @type {number}\n * @default 1.0\n */\n typical_p = 1.0;\n\n /**\n * If set to float strictly between 0 and 1, only tokens with a conditional probability greater than `epsilon_cutoff` will be sampled.\n * In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model.\n * See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.\n * @type {number}\n * @default 0.0\n */\n epsilon_cutoff = 0.0;\n\n /**\n * Eta sampling is a hybrid of locally typical sampling and epsilon sampling.\n * If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`.\n * The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model.\n * See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.\n * @type {number}\n * @default 0.0\n */\n eta_cutoff = 0.0;\n\n /**\n * This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time.\n * Note that `diversity_penalty` is only effective if `group beam search` is enabled.\n * @type {number}\n * @default 0.0\n */\n diversity_penalty = 0.0;\n\n /**\n * The parameter for repetition penalty. 1.0 means no penalty.\n * See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.\n * @type {number}\n * @default 1.0\n */\n repetition_penalty = 1.0;\n\n /**\n * The paramater for encoder_repetition_penalty.\n * An exponential penalty on sequences that are not in the original input.\n * 1.0 means no penalty.\n * @type {number}\n * @default 1.0\n */\n encoder_repetition_penalty = 1.0;\n\n /**\n * Exponential penalty to the length that is used with beam-based generation.\n * It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence.\n * Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences.\n * @type {number}\n * @default 1.0\n */\n length_penalty = 1.0;\n\n /**\n * If set to int > 0, all ngrams of that size can only occur once.\n * @type {number}\n * @default 0\n */\n no_repeat_ngram_size = 0;\n\n /**\n * List of token ids that are not allowed to be generated.\n * In order to get the token ids of the words that should not appear in the generated text, use\n * `tokenizer(bad_words, { add_prefix_space: true, add_special_tokens: false }).input_ids`.\n * @type {number[][]}\n * @default null\n */\n bad_words_ids = null;\n\n /**\n * List of token ids that must be generated.\n * If given a `number[][]`, this is treated as a simple list of words that must be included, the opposite to `bad_words_ids`.\n * If given `number[][][]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one can allow different forms of each word.\n * @type {number[][]|number[][][]}\n * @default null\n */\n force_words_ids = null;\n\n /**\n * Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones).\n * It's highly recommended to set this flag to `true` as the search algorithms suppose the score logits are normalized but some logit processors or warpers break the normalization.\n * @type {boolean}\n * @default false\n */\n renormalize_logits = false;\n\n /**\n * Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by `Constraint` objects, in the most sensible way possible.\n * @type {Object[]}\n * @default null\n */\n constraints = null;\n\n /**\n * The id of the token to force as the first generated token after the `decoder_start_token_id`.\n * Useful for multilingual models like mBART where the first generated token needs to be the target language token.\n * @type {number}\n * @default null\n */\n forced_bos_token_id = null;\n\n /**\n * The id of the token to force as the last generated token when `max_length` is reached.\n * Optionally, use a list to set multiple *end-of-sequence* tokens.\n * @type {number|number[]}\n * @default null\n */\n forced_eos_token_id = null;\n\n /**\n * Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash. Note that using `remove_invalid_values` can slow down generation.\n * @type {boolean}\n */\n remove_invalid_values = false;\n\n /**\n * This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been generated.\n * The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty starts and `decay_factor` represents the factor of exponential decay.\n * @type {[number, number]}\n * @default null\n */\n exponential_decay_length_penalty = null;\n\n /**\n * A list of tokens that will be suppressed at generation.\n * The `SuppressTokens` logit processor will set their log probs to `-inf` so that they are not sampled.\n * @type {number[]}\n * @default null\n */\n suppress_tokens = null;\n\n /**\n * A list of tokens that will be suppressed at the beginning of the generation.\n * The `SuppressBeginTokens` logit processor will set their log probs to `-inf` so that they are not sampled.\n * @type {number[]}\n * @default null\n */\n begin_suppress_tokens = null;\n\n /**\n * A list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling.\n * For example, `[[1, 123]]` means the second generated token will always be a token of index 123.\n * @type {[number, number][]}\n * @default null\n */\n forced_decoder_ids = null;\n\n /**\n * The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.\n * Higher guidance scale encourages the model to generate samples that are more closely linked to the input\n * prompt, usually at the expense of poorer quality.\n * @type {number}\n * @default null\n */\n guidance_scale = null;\n\n // Parameters that define the output variables of `generate`\n /**\n * The number of independently computed returned sequences for each element in the batch.\n * @type {number}\n * @default 1\n */\n num_return_sequences = 1;\n\n /**\n * Whether or not to return the attentions tensors of all attention layers.\n * See `attentions` under returned tensors for more details.\n * @type {boolean}\n * @default false\n */\n output_attentions = false;\n\n /**\n * Whether or not to return the hidden states of all layers.\n * See `hidden_states` under returned tensors for more details.\n * @type {boolean}\n * @default false\n */\n output_hidden_states = false;\n\n /**\n * Whether or not to return the prediction scores.\n * See `scores` under returned tensors for more details.\n * @type {boolean}\n * @default false\n */\n output_scores = false;\n\n /**\n * Whether or not to return a `ModelOutput` instead of a plain tuple.\n * @type {boolean}\n * @default false\n */\n return_dict_in_generate = false;\n\n // Special tokens that can be used at generation time\n /**\n * The id of the *padding* token.\n * @type {number}\n * @default null\n */\n pad_token_id = null;\n\n /**\n * The id of the *beginning-of-sequence* token.\n * @type {number}\n * @default null\n */\n bos_token_id = null;\n\n /**\n * The id of the *end-of-sequence* token.\n * Optionally, use a list to set multiple *end-of-sequence* tokens.\n * @type {number|number[]}\n * @default null\n */\n eos_token_id = null;\n\n // Generation parameters exclusive to encoder-decoder models\n /**\n * If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`.\n * @type {number}\n * @default 0\n */\n encoder_no_repeat_ngram_size = 0;\n\n /**\n * If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token.\n * @type {number}\n * @default null\n */\n decoder_start_token_id = null;\n\n // Wild card\n /**\n * Additional generation kwargs will be forwarded to the `generate` function of the model.\n * Kwargs that are not present in `generate`'s signature will be used in the model forward pass.\n * @type {Object}\n * @default {}\n */\n generation_kwargs = {};\n\n /**\n * \n * @param {GenerationConfig|import('../configs.js').PretrainedConfig} config \n */\n constructor(config) {\n Object.assign(this, pick(config, Object.getOwnPropertyNames(this)));\n }\n}\n\n","\n/**\n * @module generation/logits_process\n */\n\nimport { Callable } from \"../utils/generic.js\";\nimport { Tensor } from \"../utils/tensor.js\";\n\nimport { max, log_softmax } from \"../utils/maths.js\";\n\n/**\n * Abstract base class for all logit processors that can be applied during generation.\n */\nexport class LogitsProcessor extends Callable {\n /**\n * Apply the processor to the input logits.\n *\n * @abstract\n * @param {bigint[][]} input_ids The input ids.\n * @param {Tensor} logits The logits to process.\n * @throws {Error} Throws an error if `_call` is not implemented in the subclass.\n */\n _call(input_ids, logits) {\n throw Error(\"`_call` should be implemented in a subclass\")\n }\n}\n\n\n/**\n * Abstract base class for all logit warpers that can be applied during generation with multinomial sampling.\n */\nexport class LogitsWarper extends Callable {\n /**\n * Apply the processor to the input logits.\n *\n * @abstract\n * @param {bigint[][]} input_ids The input ids.\n * @param {Tensor} logits The logits to process.\n * @throws {Error} Throws an error if `_call` is not implemented in the subclass.\n */\n _call(input_ids, logits) {\n throw Error(\"`_call` should be implemented in a subclass\")\n }\n}\n\n\n/**\n * A class representing a list of logits processors. A logits processor is a function that modifies the logits\n * output of a language model. This class provides methods for adding new processors and applying all processors to a\n * batch of logits.\n */\nexport class LogitsProcessorList extends Callable {\n /**\n * Constructs a new instance of `LogitsProcessorList`.\n */\n constructor() {\n super();\n this.processors = [];\n }\n\n /**\n * Adds a new logits processor to the list.\n *\n * @param {LogitsProcessor} item The logits processor function to add.\n */\n push(item) {\n this.processors.push(item);\n }\n\n /**\n * Adds multiple logits processors to the list.\n *\n * @param {LogitsProcessor[]} items The logits processor functions to add.\n */\n extend(items) {\n this.processors.push(...items);\n }\n\n /**\n * Applies all logits processors in the list to a batch of logits, modifying them in-place.\n *\n * @param {bigint[][]} input_ids The input IDs for the language model.\n * @param {Tensor} logits\n */\n _call(input_ids, logits) {\n let toReturn = logits;\n // NOTE: Most processors modify logits inplace\n for (const processor of this.processors) {\n toReturn = processor(input_ids, toReturn);\n }\n return toReturn;\n }\n\n [Symbol.iterator]() {\n return this.processors.values();\n }\n}\n\n// DEPRECATED: https://github.com/huggingface/transformers/pull/29485\n// /**\n// * A logits processor that forces a specific token to be generated by the decoder.\n// */\n// export class ForceTokensLogitsProcessor extends LogitsProcessor {\n// /**\n// * Constructs a new instance of `ForceTokensLogitsProcessor`.\n// * \n// * @param {[number, number][]} forced_decoder_ids The ids of tokens that should be forced.\n// */\n// constructor(forced_decoder_ids) {\n// super();\n// // TODO: convert to `new Map(forced_decoder_ids)`\n// this.force_token_map = Object.fromEntries(forced_decoder_ids ?? []);\n// }\n\n// /**\n// * Apply the processor to the input logits.\n// *\n// * @param {bigint[][]} input_ids The input ids.\n// * @param {Tensor} logits The logits to process.\n// * @returns {Tensor} The processed logits.\n// */\n// _call(input_ids, logits) {\n// console.log('this.force_token_map', this.force_token_map)\n// console.log('call ForceTokensLogitsProcessor', input_ids, logits)\n// console.log('input_ids.length', input_ids.length)\n// let map = this.force_token_map[input_ids.length];\n// if (map) { // There exists a mapping\n// logits.data.fill(-Infinity)\n// logits.data[map] = 0;\n// }\n// console.log('map', map)\n// // throw Error(\"Not implemented\")\n// return logits;\n// }\n// }\n\n/**\n * A LogitsProcessor that forces a BOS token at the beginning of the generated sequence.\n */\nexport class ForcedBOSTokenLogitsProcessor extends LogitsProcessor {\n /**\n * Create a ForcedBOSTokenLogitsProcessor.\n * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced.\n */\n constructor(bos_token_id) {\n super();\n this.bos_token_id = bos_token_id;\n }\n\n /**\n * Apply the BOS token forcing to the logits.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The logits with BOS token forcing.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n if (input_ids[i].length === 1) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n batch_logits_data.fill(-Infinity);\n batch_logits_data[this.bos_token_id] = 0;\n }\n }\n return logits;\n }\n}\n\n/**\n * A logits processor that enforces the specified token as the last generated token when `max_length` is reached.\n */\nexport class ForcedEOSTokenLogitsProcessor extends LogitsProcessor {\n /**\n * Create a ForcedEOSTokenLogitsProcessor.\n * @param {number} max_length The maximum length of the sequence to be generated.\n * @param {number|number[]} eos_token_id The id(s) of the *end-of-sequence* token.\n */\n constructor(max_length, eos_token_id) {\n super();\n this.max_length = max_length;\n this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];\n }\n\n /**\n * Apply the processor to input_ids and logits.\n * \n * @param {bigint[][]} input_ids The input ids.\n * @param {Tensor} logits The logits tensor.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n if (input_ids[i].length === this.max_length - 1) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n batch_logits_data.fill(-Infinity);\n for (const eos_token of this.eos_token_id) {\n batch_logits_data[eos_token] = 0;\n }\n }\n }\n return logits;\n }\n}\n\n/**\n * A LogitsProcessor that suppresses a list of tokens as soon as the `generate` function starts\n * generating using `begin_index` tokens. This should ensure that the tokens defined by\n * `begin_suppress_tokens` at not sampled at the begining of the generation.\n */\nexport class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor {\n /**\n * Create a SuppressTokensAtBeginLogitsProcessor.\n * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress.\n * @param {number} begin_index The number of tokens to generate before suppressing tokens.\n */\n constructor(begin_suppress_tokens, begin_index) {\n super();\n this.begin_suppress_tokens = begin_suppress_tokens;\n this.begin_index = begin_index;\n }\n\n /**\n * Apply the BOS token forcing to the logits.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The logits with BOS token forcing.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n if (input_ids[i].length === this.begin_index) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n for (const token_id of this.begin_suppress_tokens) {\n batch_logits_data[token_id] = -Infinity;\n }\n }\n }\n return logits;\n }\n}\n\n/**\n * A LogitsProcessor that handles adding timestamps to generated text.\n */\nexport class WhisperTimeStampLogitsProcessor extends LogitsProcessor {\n /**\n * Constructs a new WhisperTimeStampLogitsProcessor.\n * @param {import('../models/whisper/generation_whisper.js').WhisperGenerationConfig} generate_config The config object passed to the `generate()` method of a transformer model.\n * @param {number[]} init_tokens The initial tokens of the input sequence.\n */\n constructor(generate_config, init_tokens) {\n super();\n this.eos_token_id =\n Array.isArray(generate_config.eos_token_id)\n ? generate_config.eos_token_id[0]\n : generate_config.eos_token_id;\n\n this.no_timestamps_token_id = generate_config.no_timestamps_token_id;\n this.timestamp_begin = this.no_timestamps_token_id + 1;\n\n this.begin_index = init_tokens.length;\n if (init_tokens.at(-1) === this.no_timestamps_token_id) {\n this.begin_index -= 1;\n }\n this.max_initial_timestamp_index = generate_config.max_initial_timestamp_index;\n }\n\n /**\n * Modify the logits to handle timestamp tokens.\n * @param {bigint[][]} input_ids The input sequence of tokens.\n * @param {Tensor} logits The logits output by the model.\n * @returns {Tensor} The modified logits.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n\n // suppress <|notimestamps|> which is handled by without_timestamps\n batch_logits_data[this.no_timestamps_token_id] = -Infinity;\n\n if (input_ids[i].length === this.begin_index - 1) {\n batch_logits_data.fill(-Infinity);\n batch_logits_data[this.timestamp_begin] = 0;\n continue;\n }\n\n // timestamps have to appear in pairs, except directly before eos_token; mask logits accordingly\n const seq = input_ids[i].slice(this.begin_index);\n const last_was_timestamp = seq.length >= 1 && seq[seq.length - 1] >= this.timestamp_begin;\n const penultimate_was_timestamp = seq.length < 2 || seq[seq.length - 2] >= this.timestamp_begin;\n\n if (last_was_timestamp) {\n if (penultimate_was_timestamp) { // has to be non-timestamp\n batch_logits_data.subarray(this.timestamp_begin).fill(-Infinity);\n } else { // cannot be normal text tokens\n batch_logits_data.subarray(0, this.eos_token_id).fill(-Infinity);\n }\n }\n\n // apply the `max_initial_timestamp` option\n if (input_ids[i].length === this.begin_index && this.max_initial_timestamp_index !== null) {\n const last_allowed = this.timestamp_begin + this.max_initial_timestamp_index;\n batch_logits_data.subarray(last_allowed + 1).fill(-Infinity);\n }\n\n // if sum of probability over timestamps is above any other token, sample timestamp\n const logprobs = log_softmax(batch_logits_data);\n const timestamp_logprob = Math.log(logprobs.subarray(this.timestamp_begin).map(Math.exp).reduce((a, b) => a + b));\n const max_text_token_logprob = max(logprobs.subarray(0, this.timestamp_begin))[0];\n\n if (timestamp_logprob > max_text_token_logprob) {\n batch_logits_data.subarray(0, this.timestamp_begin).fill(-Infinity);\n }\n }\n\n return logits;\n }\n}\n\n/**\n * A logits processor that disallows ngrams of a certain size to be repeated.\n */\nexport class NoRepeatNGramLogitsProcessor extends LogitsProcessor {\n /**\n * Create a NoRepeatNGramLogitsProcessor.\n * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once.\n */\n constructor(no_repeat_ngram_size) {\n super();\n this.no_repeat_ngram_size = no_repeat_ngram_size;\n }\n\n /**\n * Generate n-grams from a sequence of token ids.\n * @param {bigint[]} prevInputIds List of previous input ids\n * @returns {Map} Map of generated n-grams\n */\n getNgrams(prevInputIds) {\n const curLen = prevInputIds.length;\n\n /**@type {number[][]} */\n const ngrams = [];\n for (let j = 0; j < curLen + 1 - this.no_repeat_ngram_size; ++j) {\n const ngram = [];\n for (let k = 0; k < this.no_repeat_ngram_size; ++k) {\n ngram.push(prevInputIds[j + k]);\n }\n ngrams.push(ngram.map(Number));\n }\n\n /** @type {Map} */\n const generatedNgram = new Map();\n for (const ngram of ngrams) {\n const prevNgram = ngram.slice(0, ngram.length - 1);\n const prevNgramKey = JSON.stringify(prevNgram);\n const prevNgramValue = generatedNgram.get(prevNgramKey) ?? [];\n prevNgramValue.push(ngram[ngram.length - 1]);\n generatedNgram.set(prevNgramKey, prevNgramValue);\n }\n return generatedNgram;\n }\n\n /**\n * Generate n-grams from a sequence of token ids.\n * @param {Map} bannedNgrams Map of banned n-grams\n * @param {bigint[]} prevInputIds List of previous input ids\n * @returns {number[]} Map of generated n-grams\n */\n getGeneratedNgrams(bannedNgrams, prevInputIds) {\n const ngramIdx = prevInputIds.slice(prevInputIds.length + 1 - this.no_repeat_ngram_size, prevInputIds.length);\n const banned = bannedNgrams.get(JSON.stringify(ngramIdx.map(Number))) ?? [];\n return banned;\n }\n\n /**\n * Calculate banned n-gram tokens\n * @param {bigint[]} prevInputIds List of previous input ids\n * @returns {number[]} Map of generated n-grams\n */\n calcBannedNgramTokens(prevInputIds) {\n const bannedTokens = [];\n if (prevInputIds.length + 1 < this.no_repeat_ngram_size) {\n // return no banned tokens if we haven't generated no_repeat_ngram_size tokens yet\n return bannedTokens;\n\n } else {\n const generatedNgrams = this.getNgrams(prevInputIds);\n const bannedTokens = this.getGeneratedNgrams(generatedNgrams, prevInputIds);\n return bannedTokens;\n }\n }\n\n /**\n * Apply the no-repeat-ngram processor to the logits.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The logits with no-repeat-ngram processing.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n const bannedTokens = this.calcBannedNgramTokens(input_ids[i]);\n for (const token of bannedTokens) {\n batch_logits_data[token] = -Infinity;\n }\n }\n return logits;\n }\n}\n\n/**\n * A logits processor that penalises repeated output tokens.\n */\nexport class RepetitionPenaltyLogitsProcessor extends LogitsProcessor {\n /**\n * Create a RepetitionPenaltyLogitsProcessor.\n * @param {number} penalty The penalty to apply for repeated tokens.\n */\n constructor(penalty) {\n super();\n this.penalty = penalty;\n }\n\n /**\n * Apply the repetition penalty to the logits.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The logits with repetition penalty processing.\n */\n _call(input_ids, logits) {\n // Modify the logits corresponding to each element in `input_ids`.\n // As a consequence, the logits corresponding to tokens that appear\n // many times in the output will be penalised more.\n\n for (let i = 0; i < input_ids.length; ++i) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n for (const input_id of input_ids[i]) {\n const token = Number(input_id);\n if (batch_logits_data[token] < 0) {\n batch_logits_data[token] *= this.penalty;\n } else {\n batch_logits_data[token] /= this.penalty;\n }\n }\n }\n\n return logits\n }\n}\n\n/**\n * A logits processor that enforces a minimum number of tokens.\n */\nexport class MinLengthLogitsProcessor extends LogitsProcessor {\n /**\n * Create a MinLengthLogitsProcessor.\n * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity.\n * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.\n */\n constructor(min_length, eos_token_id) {\n super();\n this.min_length = min_length;\n this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];\n }\n\n /**\n * Apply logit processor.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n if (input_ids[i].length < this.min_length) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n\n for (const eos_token of this.eos_token_id) {\n batch_logits_data[eos_token] = -Infinity;\n }\n }\n }\n\n return logits\n }\n}\n\n/**\n * A logits processor that enforces a minimum number of new tokens.\n */\nexport class MinNewTokensLengthLogitsProcessor extends LogitsProcessor {\n /**\n * Create a MinNewTokensLengthLogitsProcessor.\n * @param {number} prompt_length_to_skip The input tokens length.\n * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity.\n * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.\n */\n constructor(prompt_length_to_skip, min_new_tokens, eos_token_id) {\n super();\n this.prompt_length_to_skip = prompt_length_to_skip;\n this.min_new_tokens = min_new_tokens;\n this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];\n }\n\n /**\n * Apply logit processor.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n const new_tokens_length = input_ids[i].length - this.prompt_length_to_skip;\n if (new_tokens_length < this.min_new_tokens) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n\n for (const eos_token of this.eos_token_id) {\n batch_logits_data[eos_token] = -Infinity;\n }\n }\n }\n return logits\n }\n}\n\nexport class NoBadWordsLogitsProcessor extends LogitsProcessor {\n /**\n * Create a `NoBadWordsLogitsProcessor`.\n * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated.\n * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.\n */\n constructor(bad_words_ids, eos_token_id) {\n super();\n this.bad_words_ids = bad_words_ids;\n this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];\n }\n\n /**\n * Apply logit processor.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n for (let i = 0; i < input_ids.length; ++i) {\n const batch_logits_data = /** @type {Float32Array} */(logits[i].data);\n const ids = input_ids[i];\n for (const bad_word_ids of this.bad_words_ids) {\n // Whether to modify the logits of the last token in the bad word id sequence\n let mark = true;\n\n // For each bad word in the list, if the current sequence of input ids ends with this sequence (excluding the last),\n // then we set the logits of the last bad word id to -Infinity.\n for (let j = 1; j <= bad_word_ids.length - 1 && bad_word_ids.length < ids.length; ++j) {\n\n // NOTE: We use != instead of !== to compare bigint and number\n // @ts-ignore\n if (bad_word_ids.at(-j - 1) != ids.at(-j)) {\n // We have found a mismatch\n mark = false;\n break;\n }\n }\n if (mark) {\n batch_logits_data[bad_word_ids.at(-1)] = -Infinity;\n }\n }\n }\n return logits\n }\n}\n\n/**\n * [`LogitsProcessor`] for classifier free guidance (CFG). The scores are split over the batch dimension,\n * where the first half correspond to the conditional logits (predicted from the input prompt) and the second half\n * correspond to the unconditional logits (predicted from an empty or 'null' prompt). The processor computes a\n * weighted average across the conditional and unconditional logits, parameterised by the `guidance_scale`.\n * \n * See [the paper](https://arxiv.org/abs/2306.05284) for more information.\n */\nexport class ClassifierFreeGuidanceLogitsProcessor extends LogitsProcessor {\n\n /**\n * Create a `ClassifierFreeGuidanceLogitsProcessor`.\n * @param {number} guidance_scale The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`.\n * Higher guidance scale encourages the model to generate samples that are more closely linked to the input\n * prompt, usually at the expense of poorer quality.\n */\n constructor(guidance_scale) {\n super();\n if (guidance_scale <= 1) {\n throw new Error(\n `Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${guidance_scale}.`\n )\n }\n this.guidance_scale = guidance_scale;\n }\n\n /**\n * Apply logit processor.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n if (logits.dims[0] !== 2 * input_ids.length) {\n throw new Error(\n `Logits should have twice the batch size of the input ids, the first half of batches corresponding to ` +\n `the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got ` +\n `batch size ${logits.dims[0]} for the logits and ${input_ids.length} for the input ids.`\n )\n }\n\n const unguided_bsz = input_ids.length;\n const cond_logits = logits.slice([0, unguided_bsz], null);\n const uncond_logits = logits.slice([unguided_bsz, logits.dims[0]], null);\n\n // Merge into uncond_logits (to save memory). This is equivalent to the following:\n // scores = uncond_logits + (cond_logits - uncond_logits) * guidance_scale\n for (let i = 0; i < uncond_logits.data.length; ++i) {\n uncond_logits.data[i] += (cond_logits.data[i] - uncond_logits.data[i]) * this.guidance_scale;\n }\n\n return uncond_logits;\n }\n}\n\n/**\n * [`LogitsWarper`] for temperature (exponential scaling output probability distribution), which effectively means\n * that it can control the randomness of the predicted tokens. Often used together with [`TopPLogitsWarper`] and [`TopKLogitsWarper`].\n */\nexport class TemperatureLogitsWarper extends LogitsWarper {\n /**\n * Create a `TemperatureLogitsWarper`.\n * @param {number} temperature Strictly positive float value used to modulate the logits distribution.\n * A value smaller than `1` decreases randomness (and vice versa), with `0` being equivalent to shifting\n * all probability mass to the most likely token.\n */\n constructor(temperature) {\n super();\n\n if (typeof temperature !== 'number' || temperature <= 0) {\n let errorMessage =\n `\\`temperature\\` (=${temperature}) must be a strictly positive float, otherwise your next token scores will be invalid.`;\n\n if (temperature === 0) {\n errorMessage += \" If you're looking for greedy decoding strategies, set `do_sample=false`.\"\n }\n }\n this.temperature = temperature;\n }\n\n /**\n * Apply logit warper.\n * @param {bigint[][]} input_ids The input IDs.\n * @param {Tensor} logits The logits.\n * @returns {Object} The processed logits.\n */\n _call(input_ids, logits) {\n const batch_logits_data = /** @type {Float32Array} */(logits.data);\n for (let i = 0; i < batch_logits_data.length; ++i) {\n batch_logits_data[i] /= this.temperature;\n }\n return logits;\n }\n}\n\n/**\n * [`LogitsWarper`] that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off.\n * Often used together with [`TemperatureLogitsWarper`] and [`TopKLogitsWarper`].\n */\nexport class TopPLogitsWarper extends LogitsWarper {\n /**\n * Create a `TopPLogitsWarper`.\n * @param {number} top_p If set to < 1, only the smallest set of most probable tokens with\n * probabilities that add up to `top_p` or higher are kept for generation.\n * @param {Object} options Additional options for the top-p sampling.\n * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value.\n * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered.\n */\n constructor(top_p, {\n filter_value = -Infinity,\n min_tokens_to_keep = 1,\n } = {}) {\n super();\n if (top_p < 0 || top_p > 1.0) {\n throw new Error(`\\`top_p\\` must be a float > 0 and < 1, but is ${top_p}`)\n }\n if (!Number.isInteger(min_tokens_to_keep) || min_tokens_to_keep < 1) {\n throw new Error(`\\`min_tokens_to_keep\\` must be a positive integer, but is ${min_tokens_to_keep}`)\n }\n\n this.top_p = top_p\n this.filter_value = filter_value\n this.min_tokens_to_keep = min_tokens_to_keep\n }\n}\n\n/**\n * [`LogitsWarper`] that performs top-k, i.e. restricting to the k highest probability elements.\n * Often used together with [`TemperatureLogitsWarper`] and [`TopPLogitsWarper`].\n */\nexport class TopKLogitsWarper extends LogitsWarper {\n /**\n * Create a `TopKLogitsWarper`.\n * @param {number} top_k If set to > 0, only the top `top_k` tokens are kept for generation.\n * @param {Object} options Additional options for the top-k sampling.\n * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value.\n * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered.\n */\n constructor(top_k, {\n filter_value = -Infinity,\n min_tokens_to_keep = 1,\n } = {}) {\n super();\n if (!Number.isInteger(top_k) || top_k < 0) {\n throw new Error(`\\`top_k\\` must be a positive integer, but is ${top_k}`)\n }\n\n this.top_k = Math.max(top_k, min_tokens_to_keep)\n this.filter_value = filter_value\n }\n}","\n/**\n * @module generation/logits_sampler\n */\n\nimport { Callable } from \"../utils/generic.js\";\nimport { Tensor, topk } from \"../utils/tensor.js\";\n\nimport {\n max,\n softmax,\n} from '../utils/maths.js';\nimport { GenerationConfig } from '../generation/configuration_utils.js';\n\n/**\n * Sampler is a base class for all sampling methods used for text generation.\n */\nexport class LogitsSampler extends Callable {\n /**\n * Creates a new Sampler object with the specified generation config.\n * @param {GenerationConfig} generation_config The generation config.\n */\n constructor(generation_config) {\n super();\n this.generation_config = generation_config;\n }\n\n /**\n * Executes the sampler, using the specified logits.\n * @param {Tensor} logits\n * @returns {Promise<[bigint, number][]>}\n */\n async _call(logits) {\n // Sample from logits, of dims [batch, sequence_length, vocab_size].\n // If index is specified, sample from [batch, index, vocab_size].\n return this.sample(logits);\n }\n\n /**\n * Abstract method for sampling the logits.\n * @param {Tensor} logits\n * @throws {Error} If not implemented in subclass.\n * @returns {Promise<[bigint, number][]>}\n */\n async sample(logits) {\n throw Error(\"sample should be implemented in subclasses.\")\n }\n\n /**\n * Returns the specified logits as an array, with temperature applied.\n * @param {Tensor} logits\n * @param {number} index\n * @returns {Float32Array}\n */\n getLogits(logits, index) {\n let vocabSize = logits.dims.at(-1);\n\n let logs = /** @type {Float32Array} */(logits.data);\n\n if (index === -1) {\n logs = logs.slice(-vocabSize);\n } else {\n let startIndex = index * vocabSize;\n logs = logs.slice(startIndex, startIndex + vocabSize);\n }\n return logs;\n }\n\n /**\n * Selects an item randomly based on the specified probabilities.\n * @param {import(\"../transformers.js\").DataArray} probabilities An array of probabilities to use for selection.\n * @returns {number} The index of the selected item.\n */\n randomSelect(probabilities) {\n // Return index of chosen item\n let sumProbabilities = 0;\n for (let i = 0; i < probabilities.length; ++i) {\n sumProbabilities += probabilities[i];\n }\n\n let r = Math.random() * sumProbabilities;\n for (let i = 0; i < probabilities.length; ++i) {\n r -= probabilities[i];\n if (r <= 0) {\n return i;\n }\n }\n return 0; // return first (most probable) as a fallback\n }\n\n /**\n * Returns a Sampler object based on the specified options.\n * @param {GenerationConfig} generation_config An object containing options for the sampler.\n * @returns {LogitsSampler} A Sampler object.\n */\n static getSampler(generation_config) {\n // - *greedy decoding*: `num_beams=1` and `do_sample=False`\n // - *contrastive search*: `penalty_alpha>0` and `top_k>1`\n // - *multinomial sampling*: `num_beams=1` and `do_sample=True`\n // - *beam-search decoding*: `num_beams>1` and `do_sample=False`\n // - *beam-search multinomial sampling*: `num_beams>1` and `do_sample=True`\n // - *diverse beam-search decoding*: `num_beams>1` and `num_beam_groups>1`\n // - *constrained beam-search decoding*: `constraints!=None` or `force_words_ids!=None`\n\n // NOTE: beam search is implemented directly into the generation function\n if (generation_config.do_sample) {\n return new MultinomialSampler(generation_config);\n\n } else if (generation_config.num_beams > 1) {\n return new BeamSearchSampler(generation_config);\n\n } else {\n if (generation_config.num_return_sequences > 1) {\n throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${generation_config.num_return_sequences}.`)\n }\n return new GreedySampler(generation_config);\n }\n }\n}\n\n/**\n * Class representing a Greedy Sampler.\n */\nclass GreedySampler extends LogitsSampler {\n /**\n * Sample the maximum probability of a given logits tensor.\n * @param {Tensor} logits\n * @returns {Promise<[bigint, number][]>} An array with a single tuple, containing the index of the maximum value and a meaningless score (since this is a greedy search).\n */\n async sample(logits) {\n // NOTE: no need to do log_softmax here since we only take the maximum\n const argmax = max(logits.data)[1];\n\n // Note: score is meaningless in this context, since we are performing\n // greedy search (p = 1 => log(p) = 0)\n return [\n [BigInt(argmax), 0]\n ];\n }\n}\n\n/**\n * Class representing a MultinomialSampler.\n */\nclass MultinomialSampler extends LogitsSampler {\n\n /**\n * Sample from the logits.\n * @param {Tensor} logits\n * @returns {Promise<[bigint, number][]>}\n */\n async sample(logits) {\n let k = logits.dims.at(-1); // defaults to vocab size\n if (this.generation_config.top_k > 0) {\n k = Math.min(this.generation_config.top_k, k);\n }\n\n // Get top k tokens\n const [v, i] = await topk(logits, k);\n\n // Compute softmax over logits\n const probabilities = softmax(/** @type {Float32Array} */(v.data));\n\n return Array.from({ length: this.generation_config.num_beams }, () => {\n const sampledIndex = this.randomSelect(probabilities);\n return [\n i.data[sampledIndex], // token id\n Math.log(probabilities[sampledIndex]), // score\n ];\n });\n }\n}\n\n\n/**\n * Class representing a BeamSearchSampler.\n */\nclass BeamSearchSampler extends LogitsSampler {\n\n /**\n * Sample from the logits.\n * @param {Tensor} logits\n * @returns {Promise<[bigint, number][]>}\n */\n async sample(logits) {\n let k = logits.dims.at(-1); // defaults to vocab size\n if (this.generation_config.top_k > 0) {\n k = Math.min(this.generation_config.top_k, k);\n }\n\n // Get top k tokens\n const [v, i] = await topk(logits, k);\n\n // Compute softmax over logits\n const probabilities = softmax(/** @type {Float32Array} */(v.data));\n\n return Array.from({ length: this.generation_config.num_beams }, (_, x) => {\n return [\n i.data[x], // token id\n Math.log(probabilities[x]), // score\n ];\n });\n }\n}\n","\n/**\n * @module generation/stopping_criteria\n */\n\nimport { Callable } from \"../utils/generic.js\";\n\n// NOTE:\n// Stopping Criteria returns a list of `batch_size` booleans, indicating whether each sequence in the batch should be stopped.\n\n/**\n * Abstract base class for all stopping criteria that can be applied during generation.\n */\nexport class StoppingCriteria extends Callable {\n /**\n * \n * @param {number[][]} input_ids (`number[][]` of shape `(batch_size, sequence_length)`):\n * Indices of input sequence tokens in the vocabulary.\n * @param {number[][]} scores scores (`number[][]` of shape `(batch_size, config.vocab_size)`):\n * Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax\n * or scores for each vocabulary token after SoftMax.\n * @returns {boolean[]} A list of booleans indicating whether each sequence should be stopped.\n */\n _call(input_ids, scores) {\n throw Error(\"StoppingCriteria needs to be subclassed\");\n }\n}\n/**\n */\nexport class StoppingCriteriaList extends Callable {\n /**\n * Constructs a new instance of `StoppingCriteriaList`.\n */\n constructor() {\n super();\n this.criteria = [];\n }\n\n /**\n * Adds a new stopping criterion to the list.\n *\n * @param {StoppingCriteria} item The stopping criterion to add.\n */\n push(item) {\n this.criteria.push(item);\n }\n\n /**\n * Adds multiple stopping criteria to the list.\n *\n * @param {StoppingCriteria|StoppingCriteriaList|StoppingCriteria[]} items The stopping criteria to add.\n */\n extend(items) {\n if (items instanceof StoppingCriteriaList) {\n items = items.criteria;\n } else if (items instanceof StoppingCriteria) {\n items = [items];\n }\n this.criteria.push(...items);\n }\n\n _call(input_ids, scores) {\n const is_done = new Array(input_ids.length).fill(false);\n for (const criterion of this.criteria) {\n const criterion_done = criterion(input_ids, scores);\n for (let i = 0; i < is_done.length; ++i) {\n is_done[i] ||= criterion_done[i];\n }\n }\n return is_done;\n }\n\n [Symbol.iterator]() {\n return this.criteria.values();\n }\n}\n\n/**\n * This class can be used to stop generation whenever the full generated number of tokens exceeds `max_length`.\n * Keep in mind for decoder-only type of transformers, this will include the initial prompted tokens.\n */\nexport class MaxLengthCriteria extends StoppingCriteria {\n\n /**\n * \n * @param {number} max_length The maximum length that the output sequence can have in number of tokens.\n * @param {number} [max_position_embeddings=null] The maximum model length, as defined by the model's `config.max_position_embeddings` attribute.\n */\n constructor(max_length, max_position_embeddings = null) {\n super();\n this.max_length = max_length;\n this.max_position_embeddings = max_position_embeddings;\n }\n\n _call(input_ids) {\n return input_ids.map(ids => ids.length >= this.max_length);\n }\n}\n\n// TODO: add MaxTimeCriteria\n\n/**\n * This class can be used to stop generation whenever the \"end-of-sequence\" token is generated.\n * By default, it uses the `model.generation_config.eos_token_id`.\n */\nexport class EosTokenCriteria extends StoppingCriteria {\n\n /**\n * \n * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token.\n * Optionally, use a list to set multiple *end-of-sequence* tokens.\n */\n constructor(eos_token_id) {\n super();\n if (!Array.isArray(eos_token_id)) {\n eos_token_id = [eos_token_id];\n }\n this.eos_token_id = eos_token_id;\n }\n\n /**\n * \n * @param {number[][]} input_ids \n * @param {number[][]} scores \n * @returns {boolean[]}\n */\n _call(input_ids, scores) {\n return input_ids.map(ids => {\n const last = ids.at(-1);\n // NOTE: We use == instead of === to allow for number/bigint comparison\n return this.eos_token_id.some(eos_id => last == eos_id);\n });\n }\n}\n\n/**\n * This class can be used to stop generation whenever the user interrupts the process.\n */\nexport class InterruptableStoppingCriteria extends StoppingCriteria {\n constructor() {\n super();\n this.interrupted = false;\n }\n\n interrupt() {\n this.interrupted = true;\n }\n\n reset() {\n this.interrupted = false;\n }\n\n _call(input_ids, scores) {\n return new Array(input_ids.length).fill(this.interrupted);\n }\n}\n","\n/**\n * @module generation/streamers\n */\n\nimport { mergeArrays } from '../utils/core.js';\nimport { is_chinese_char } from '../tokenizers.js';\nimport { apis } from '../env.js';\n\nexport class BaseStreamer {\n /**\n * Function that is called by `.generate()` to push new tokens\n * @param {bigint[][]} value \n */\n put(value) {\n throw Error('Not implemented');\n }\n\n /**\n * Function that is called by `.generate()` to signal the end of generation\n */\n end() {\n throw Error('Not implemented');\n }\n}\n\nconst stdout_write = apis.IS_PROCESS_AVAILABLE\n ? x => process.stdout.write(x)\n : x => console.log(x);\n\n/**\n * Simple text streamer that prints the token(s) to stdout as soon as entire words are formed.\n */\nexport class TextStreamer extends BaseStreamer {\n /**\n * \n * @param {import('../tokenizers.js').PreTrainedTokenizer} tokenizer \n */\n constructor(tokenizer, {\n skip_prompt = false,\n callback_function = null,\n token_callback_function = null,\n decode_kwargs = {},\n ...kwargs\n } = {}) {\n super();\n this.tokenizer = tokenizer;\n this.skip_prompt = skip_prompt;\n this.callback_function = callback_function ?? stdout_write;\n this.token_callback_function = token_callback_function;\n this.decode_kwargs = { ...decode_kwargs, ...kwargs };\n\n // variables used in the streaming process\n this.token_cache = [];\n this.print_len = 0;\n this.next_tokens_are_prompt = true;\n }\n\n /**\n * Receives tokens, decodes them, and prints them to stdout as soon as they form entire words.\n * @param {bigint[][]} value \n */\n put(value) {\n if (value.length > 1) {\n throw Error('TextStreamer only supports batch size of 1');\n }\n\n if (this.skip_prompt && this.next_tokens_are_prompt) {\n this.next_tokens_are_prompt = false;\n return;\n }\n\n const tokens = value[0];\n this.token_callback_function?.(tokens)\n\n // Add the new token to the cache and decodes the entire thing.\n this.token_cache = mergeArrays(this.token_cache, tokens);\n const text = this.tokenizer.decode(this.token_cache, this.decode_kwargs);\n\n let printable_text;\n if (text.endsWith('\\n')) {\n // After the symbol for a new line, we flush the cache.\n printable_text = text.slice(this.print_len);\n this.token_cache = [];\n this.print_len = 0;\n } else if (text.length > 0 && is_chinese_char(text.charCodeAt(text.length - 1))) {\n // If the last token is a CJK character, we print the characters.\n printable_text = text.slice(this.print_len);\n this.print_len += printable_text.length;\n } else {\n // Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words,\n // which may change with the subsequent token -- there are probably smarter ways to do this!)\n printable_text = text.slice(this.print_len, text.lastIndexOf(' ') + 1);\n this.print_len += printable_text.length;\n }\n\n this.on_finalized_text(printable_text, false);\n }\n\n /**\n * Flushes any remaining cache and prints a newline to stdout.\n */\n end() {\n let printable_text;\n if (this.token_cache.length > 0) {\n const text = this.tokenizer.decode(this.token_cache, this.decode_kwargs);\n printable_text = text.slice(this.print_len);\n this.token_cache = [];\n this.print_len = 0;\n } else {\n printable_text = '';\n }\n this.next_tokens_are_prompt = true;\n this.on_finalized_text(printable_text, true);\n }\n\n /**\n * Prints the new text to stdout. If the stream is ending, also prints a newline.\n * @param {string} text \n * @param {boolean} stream_end \n */\n on_finalized_text(text, stream_end) {\n if (text.length > 0) {\n this.callback_function?.(text);\n }\n if (stream_end && this.callback_function === stdout_write && apis.IS_PROCESS_AVAILABLE) {\n this.callback_function?.('\\n');\n }\n }\n}\n\n/**\n * Utility class to handle streaming of tokens generated by whisper speech-to-text models.\n * Callback functions are invoked when each of the following events occur:\n * - A new chunk starts (on_chunk_start)\n * - A new token is generated (callback_function)\n * - A chunk ends (on_chunk_end)\n * - The stream is finalized (on_finalize)\n */\nexport class WhisperTextStreamer extends TextStreamer {\n /**\n * @param {import('../tokenizers.js').WhisperTokenizer} tokenizer\n * @param {Object} options\n * @param {boolean} [options.skip_prompt=false] Whether to skip the prompt tokens\n * @param {function(string): void} [options.callback_function=null] Function to call when a piece of text is ready to display\n * @param {function(string): void} [options.token_callback_function=null] Function to call when a new token is generated\n * @param {function(number): void} [options.on_chunk_start=null] Function to call when a new chunk starts\n * @param {function(number): void} [options.on_chunk_end=null] Function to call when a chunk ends\n * @param {function(): void} [options.on_finalize=null] Function to call when the stream is finalized\n * @param {number} [options.time_precision=0.02] Precision of the timestamps\n * @param {boolean} [options.skip_special_tokens=true] Whether to skip special tokens when decoding\n * @param {Object} [options.decode_kwargs={}] Additional keyword arguments to pass to the tokenizer's decode method\n */\n constructor(tokenizer, {\n skip_prompt = false,\n callback_function = null,\n token_callback_function = null,\n on_chunk_start = null,\n on_chunk_end = null,\n on_finalize = null,\n time_precision = 0.02,\n skip_special_tokens = true,\n decode_kwargs = {},\n } = {}) {\n super(tokenizer, {\n skip_prompt,\n callback_function,\n token_callback_function,\n decode_kwargs: { skip_special_tokens, ...decode_kwargs },\n });\n this.timestamp_begin = tokenizer.timestamp_begin;\n\n this.on_chunk_start = on_chunk_start;\n this.on_chunk_end = on_chunk_end;\n this.on_finalize = on_finalize;\n\n this.time_precision = time_precision;\n\n this.waiting_for_timestamp = false;\n }\n\n /**\n * @param {bigint[][]} value \n */\n put(value) {\n if (value.length > 1) {\n throw Error('WhisperTextStreamer only supports batch size of 1');\n }\n const tokens = value[0];\n\n // Check if the token is a timestamp\n if (tokens.length === 1) {\n const offset = Number(tokens[0]) - this.timestamp_begin;\n if (offset >= 0) {\n const time = offset * this.time_precision;\n if (this.waiting_for_timestamp) {\n this.on_chunk_end?.(time);\n } else {\n this.on_chunk_start?.(time);\n }\n this.waiting_for_timestamp = !this.waiting_for_timestamp; // Toggle\n value = [[]]; // Skip timestamp\n }\n }\n return super.put(value);\n }\n\n end() {\n super.end();\n this.on_finalize?.();\n }\n}\n","\n/**\n * @file Definitions of all models available in Transformers.js.\n * \n * **Example:** Load and run an `AutoModel`.\n * \n * ```javascript\n * import { AutoModel, AutoTokenizer } from '@huggingface/transformers';\n * \n * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');\n * let model = await AutoModel.from_pretrained('Xenova/bert-base-uncased');\n * \n * let inputs = await tokenizer('I love transformers!');\n * let { logits } = await model(inputs);\n * // Tensor {\n * // data: Float32Array(183132) [-7.117443084716797, -7.107812881469727, -7.092104911804199, ...]\n * // dims: (3) [1, 6, 30522],\n * // type: \"float32\",\n * // size: 183132,\n * // }\n * ```\n * \n * We also provide other `AutoModel`s (listed below), which you can use in the same way as the Python library. For example:\n * \n * **Example:** Load and run an `AutoModelForSeq2SeqLM`.\n * ```javascript\n * import { AutoModelForSeq2SeqLM, AutoTokenizer } from '@huggingface/transformers';\n * \n * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/t5-small');\n * let model = await AutoModelForSeq2SeqLM.from_pretrained('Xenova/t5-small');\n * \n * let { input_ids } = await tokenizer('translate English to German: I love transformers!');\n * let outputs = await model.generate(input_ids);\n * let decoded = tokenizer.decode(outputs[0], { skip_special_tokens: true });\n * // 'Ich liebe Transformatoren!'\n * ```\n * \n * @module models\n */\n\nimport {\n AutoConfig,\n getKeyValueShapes,\n} from './configs.js';\n\nimport {\n deviceToExecutionProviders,\n createInferenceSession,\n isONNXTensor,\n isONNXProxy,\n} from './backends/onnx.js';\nimport {\n DATA_TYPES,\n DEFAULT_DEVICE_DTYPE_MAPPING,\n DEFAULT_DTYPE_SUFFIX_MAPPING,\n isWebGpuFp16Supported,\n} from './utils/dtypes.js';\n\nimport {\n Callable,\n} from './utils/generic.js';\n\nimport {\n isIntegralNumber,\n mergeArrays,\n pick,\n} from './utils/core.js';\n\nimport {\n getModelFile,\n getModelJSON,\n} from './utils/hub.js';\n\nimport {\n GITHUB_ISSUE_URL,\n} from './utils/constants.js';\n\nimport {\n LogitsProcessorList,\n ForcedBOSTokenLogitsProcessor,\n ForcedEOSTokenLogitsProcessor,\n SuppressTokensAtBeginLogitsProcessor,\n WhisperTimeStampLogitsProcessor,\n NoRepeatNGramLogitsProcessor,\n RepetitionPenaltyLogitsProcessor,\n NoBadWordsLogitsProcessor,\n MinLengthLogitsProcessor,\n MinNewTokensLengthLogitsProcessor,\n\n TemperatureLogitsWarper,\n TopKLogitsWarper,\n TopPLogitsWarper,\n ClassifierFreeGuidanceLogitsProcessor,\n} from './generation/logits_process.js';\n\nimport {\n GenerationConfig,\n} from './generation/configuration_utils.js';\n\nimport {\n cat,\n full_like,\n mean,\n ones,\n ones_like,\n stack,\n std_mean,\n Tensor,\n zeros_like,\n} from './utils/tensor.js';\n\nimport { dynamic_time_warping, medianFilter } from './utils/maths.js';\nimport { EosTokenCriteria, MaxLengthCriteria, StoppingCriteriaList } from './generation/stopping_criteria.js';\nimport { LogitsSampler } from './generation/logits_sampler.js';\nimport { apis } from './env.js';\n\nimport { WhisperGenerationConfig } from './models/whisper/generation_whisper.js';\nimport { whisper_language_to_code } from './models/whisper/common_whisper.js';\n\n//////////////////////////////////////////////////\n// Model types: used internally\nconst MODEL_TYPES = {\n EncoderOnly: 0,\n EncoderDecoder: 1,\n Seq2Seq: 2,\n Vision2Seq: 3,\n DecoderOnly: 4,\n MaskGeneration: 5,\n ImageTextToText: 6,\n Musicgen: 7,\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Helper functions\n\n// NOTE: These will be populated fully later\nconst MODEL_TYPE_MAPPING = new Map();\nconst MODEL_NAME_TO_CLASS_MAPPING = new Map();\nconst MODEL_CLASS_TO_NAME_MAPPING = new Map();\n\n\n/**\n * Constructs an InferenceSession using a model file located at the specified path.\n * @param {string} pretrained_model_name_or_path The path to the directory containing the model file.\n * @param {string} fileName The name of the model file.\n * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the model.\n * @returns {Promise<{buffer: Uint8Array, session_options: Object, session_config: Object}>} A Promise that resolves to the data needed to create an InferenceSession object.\n * @private\n */\nasync function getSession(pretrained_model_name_or_path, fileName, options) {\n const custom_config = options.config?.['transformers.js_config'] ?? {};\n let device = options.device ?? custom_config.device;\n if (device && typeof device !== 'string') {\n if (device.hasOwnProperty(fileName)) {\n device = device[fileName];\n } else {\n console.warn(`device not specified for \"${fileName}\". Using the default device.`);\n device = null;\n }\n }\n\n // If the device is not specified, we use the default (supported) execution providers.\n const selectedDevice = /** @type {import(\"./utils/devices.js\").DeviceType} */(\n device ?? (apis.IS_NODE_ENV ? 'cpu' : 'wasm')\n );\n const executionProviders = deviceToExecutionProviders(selectedDevice);\n\n // If options.dtype is specified, we use it to choose the suffix for the model file.\n // Otherwise, we use the default dtype for the device.\n let dtype = options.dtype ?? custom_config.dtype;\n if (typeof dtype !== 'string') {\n if (dtype && dtype.hasOwnProperty(fileName)) {\n dtype = dtype[fileName];\n } else {\n dtype = DEFAULT_DEVICE_DTYPE_MAPPING[selectedDevice] ?? DATA_TYPES.fp32;\n console.warn(`dtype not specified for \"${fileName}\". Using the default dtype (${dtype}) for this device (${selectedDevice}).`);\n }\n }\n\n const selectedDtype = /** @type {import(\"./utils/dtypes.js\").DataType} */(dtype);\n\n if (!DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(selectedDtype)) {\n throw new Error(`Invalid dtype: ${selectedDtype}. Should be one of: ${Object.keys(DATA_TYPES).join(', ')}`);\n } else if (selectedDtype === DATA_TYPES.fp16 && selectedDevice === 'webgpu' && !(await isWebGpuFp16Supported())) {\n throw new Error(`The device (${selectedDevice}) does not support fp16.`);\n }\n\n // Only valid for models with a decoder\n const kv_cache_dtype = custom_config.kv_cache_dtype\n ? (typeof custom_config.kv_cache_dtype === 'string'\n ? custom_config.kv_cache_dtype\n : custom_config.kv_cache_dtype[selectedDtype] ?? 'float32')\n : undefined;\n\n if (kv_cache_dtype && !['float32', 'float16'].includes(kv_cache_dtype)) {\n throw new Error(`Invalid kv_cache_dtype: ${kv_cache_dtype}. Should be one of: float32, float16`);\n }\n\n const session_config = {\n dtype: selectedDtype,\n kv_cache_dtype,\n }\n\n // Construct the model file name\n const suffix = DEFAULT_DTYPE_SUFFIX_MAPPING[selectedDtype];\n const modelFileName = `${options.subfolder ?? ''}/${fileName}${suffix}.onnx`;\n\n const session_options = { ...options.session_options };\n\n // Overwrite `executionProviders` if not specified\n session_options.executionProviders ??= executionProviders;\n\n // Overwrite `freeDimensionOverrides` if specified in config and not set in session options\n const free_dimension_overrides = custom_config.free_dimension_overrides;\n if (free_dimension_overrides) {\n session_options.freeDimensionOverrides ??= free_dimension_overrides;\n } else if (selectedDevice.startsWith('webnn') && !session_options.freeDimensionOverrides) {\n console.warn(\n 'WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within \"transformers.js_config\". ' +\n 'When `free_dimension_overrides` is not set, you may experience significant performance degradation.'\n );\n }\n\n const bufferPromise = getModelFile(pretrained_model_name_or_path, modelFileName, true, options);\n\n // handle onnx external data files\n const use_external_data_format = options.use_external_data_format ?? custom_config.use_external_data_format;\n /** @type {Promise<{path: string, data: Uint8Array}>[]} */\n let externalDataPromises = [];\n if (use_external_data_format && (\n use_external_data_format === true ||\n (\n typeof use_external_data_format === 'object' &&\n use_external_data_format.hasOwnProperty(fileName) &&\n use_external_data_format[fileName] === true\n )\n )) {\n if (apis.IS_NODE_ENV) {\n throw new Error('External data format is not yet supported in Node.js');\n }\n const path = `${fileName}${suffix}.onnx_data`;\n const fullPath = `${options.subfolder ?? ''}/${path}`;\n externalDataPromises.push(new Promise(async (resolve, reject) => {\n const data = await getModelFile(pretrained_model_name_or_path, fullPath, true, options);\n resolve({ path, data })\n }));\n\n } else if (session_options.externalData !== undefined) {\n externalDataPromises = session_options.externalData.map(async (ext) => {\n // if the external data is a string, fetch the file and replace the string with its content\n if (typeof ext.data === \"string\") {\n const ext_buffer = await getModelFile(pretrained_model_name_or_path, ext.data, true, options);\n return { ...ext, data: ext_buffer };\n }\n return ext;\n });\n }\n\n if (externalDataPromises.length > 0) {\n session_options.externalData = await Promise.all(externalDataPromises);\n }\n\n if (selectedDevice === 'webgpu') {\n const shapes = getKeyValueShapes(options.config, {\n prefix: 'present',\n });\n if (Object.keys(shapes).length > 0 && !isONNXProxy()) {\n // Only set preferredOutputLocation if shapes are present and we aren't proxying ONNX\n /** @type {Record} */\n const preferredOutputLocation = {};\n for (const key in shapes) {\n preferredOutputLocation[key] = 'gpu-buffer';\n }\n session_options.preferredOutputLocation = preferredOutputLocation;\n }\n }\n\n const buffer = await bufferPromise;\n\n return { buffer, session_options, session_config };\n}\n\n/**\n * Helper function to create multiple InferenceSession objects.\n * \n * @param {string} pretrained_model_name_or_path The path to the directory containing the model file.\n * @param {Record} names The names of the model files to load.\n * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the model.\n * @returns {Promise>} A Promise that resolves to a dictionary of InferenceSession objects.\n * @private\n */\nasync function constructSessions(pretrained_model_name_or_path, names, options) {\n return Object.fromEntries(await Promise.all(\n Object.keys(names).map(async (name) => {\n const { buffer, session_options, session_config } = await getSession(pretrained_model_name_or_path, names[name], options);\n const session = await createInferenceSession(buffer, session_options, session_config);\n return [name, session];\n })\n ));\n}\n\n/**\n * Helper function to load multiple optional configuration files\n * @param {string} pretrained_model_name_or_path The path to the directory containing the config file.\n * @param {Record} names The names of the config files to load.\n * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the configs.\n * @returns {Promise>} A Promise that resolves to a dictionary of configuration objects.\n * @private\n */\nasync function getOptionalConfigs(pretrained_model_name_or_path, names, options) {\n return Object.fromEntries(await Promise.all(\n Object.keys(names).map(async (name) => {\n const config = await getModelJSON(pretrained_model_name_or_path, names[name], false, options);\n return [name, config];\n })\n ));\n}\n\n/**\n * Validate model inputs\n * @param {Object} session The InferenceSession object that will be run.\n * @param {Object} inputs The inputs to check.\n * @returns {Record} The checked inputs.\n * @throws {Error} If any inputs are missing.\n * @private\n */\nfunction validateInputs(session, inputs) {\n /**\n * NOTE: Create either a shallow or deep copy based on `onnx.wasm.proxy`\n * @type {Record}\n */\n const checkedInputs = Object.create(null);\n const missingInputs = [];\n for (const inputName of session.inputNames) {\n const tensor = inputs[inputName];\n // Rare case where one of the model's input names corresponds to a built-in\n // object name (e.g., toString), which would cause a simple (!tensor) check to fail,\n // because it's not undefined but a function.\n if (!(tensor instanceof Tensor)) {\n missingInputs.push(inputName);\n continue;\n }\n // NOTE: When `env.wasm.proxy is true` the tensor is moved across the Worker\n // boundary, transferring ownership to the worker and invalidating the tensor.\n // So, in this case, we simply sacrifice a clone for it.\n checkedInputs[inputName] = isONNXProxy() ? tensor.clone() : tensor;\n }\n if (missingInputs.length > 0) {\n throw new Error(\n `An error occurred during model execution: \"Missing the following inputs: ${missingInputs.join(', ')}.`);\n }\n\n const numInputsProvided = Object.keys(inputs).length;\n const numInputsNeeded = session.inputNames.length;\n if (numInputsProvided > numInputsNeeded) {\n // No missing inputs, but too many inputs were provided.\n // Warn the user and ignore the extra inputs.\n let ignored = Object.keys(inputs).filter(inputName => !session.inputNames.includes(inputName));\n console.warn(`WARNING: Too many inputs were provided (${numInputsProvided} > ${numInputsNeeded}). The following inputs will be ignored: \"${ignored.join(', ')}\".`);\n }\n\n return checkedInputs;\n}\n\nconst getQueryValue = (name) => {\n const urlParams = new URLSearchParams(window.location.search);\n return urlParams.get(name);\n};\n\nlet runs = 1;\n\nlet perf = {\n warmup: 0,\n inference: [],\n throughput: 0\n};\n\nexport function getPerf() {\n return perf;\n}\n\n/**\n * Executes an InferenceSession using the specified inputs.\n * NOTE: `inputs` must contain at least the input names of the model.\n * - If additional inputs are passed, they will be ignored.\n * - If inputs are missing, an error will be thrown.\n * \n * @param {Object} session The InferenceSession object to run.\n * @param {Object} inputs An object that maps input names to input tensors.\n * @returns {Promise} A Promise that resolves to an object that maps output names to output tensors.\n * @private\n */\nasync function sessionRun(session, inputs) {\n perf = {\n warmup: 0,\n inference: [],\n throughput: 0\n };\n const checkedInputs = validateInputs(session, inputs);\n try {\n // pass the original ort tensor\n const ortFeed = Object.fromEntries(Object.entries(checkedInputs).map(([k, v]) => [k, v.ort_tensor]));\n let output;\n let numOfWarmups = 1;\n // let numOfRuns = 100;\n console.log(`-- number of test runs --`);\n if (getQueryValue(\"run\")) {\n runs = parseInt(getQueryValue(\"run\"));\n } else {\n runs = 1;\n }\n console.log(runs);\n let start = performance.now();\n let loopStart;\n let current;\n let arrayInference = [];\n for(let i=0; i < numOfWarmups + runs; i++) {\n loopStart = performance.now();\n output = await session.run(ortFeed);\n current = performance.now() - loopStart;\n if(i==0) {\n perf.warmup = current;\n } else {\n arrayInference.push(current);\n }\n console.log(`Session run time: ${current}ms`);\n }\n perf.inference = arrayInference;\n perf.throughput = parseFloat((1000.00 / ((performance.now() - start) / (numOfWarmups + runs))).toFixed(2));\n output = replaceTensors(output);\n return output;\n } catch (e) {\n // This usually occurs when the inputs are of the wrong type.\n console.error(`An error occurred during model execution: \"${e}\".`);\n console.error('Inputs given to model:', checkedInputs);\n throw e;\n }\n}\n\n/**\n * Replaces ONNX Tensor objects with custom Tensor objects to support additional functions.\n * @param {Object} obj The object to replace tensor objects in.\n * @returns {Object} The object with tensor objects replaced by custom Tensor objects.\n * @private\n */\nfunction replaceTensors(obj) {\n for (let prop in obj) {\n if (isONNXTensor(obj[prop])) {\n obj[prop] = new Tensor(obj[prop]);\n } else if (typeof obj[prop] === 'object') {\n replaceTensors(obj[prop]);\n }\n }\n return obj;\n}\n\n\n/**\n * Converts an array or Tensor of integers to an int64 Tensor.\n * @param {Array|Tensor} items The input integers to be converted.\n * @returns {Tensor} The int64 Tensor with the converted values.\n * @throws {Error} If the input array is empty or the input is a batched Tensor and not all sequences have the same length.\n * @private\n */\nfunction toI64Tensor(items) {\n if (items instanceof Tensor) {\n return items;\n }\n // items is an array\n if (items.length === 0) {\n throw Error(\"items must be non-empty\");\n }\n\n if (Array.isArray(items[0])) {\n // batched\n if (items.some(x => x.length !== items[0].length)) {\n throw Error(\"Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.\")\n }\n\n return new Tensor('int64',\n BigInt64Array.from(items.flat().map(x => BigInt(x))),\n [items.length, items[0].length]\n );\n } else {\n //flat\n return new Tensor('int64',\n BigInt64Array.from(items.map(x => BigInt(x))),\n [1, items.length]\n );\n }\n}\n\n/**\n * Creates a boolean tensor with a single value.\n * @param {boolean} value The value of the tensor.\n * @returns {Tensor} The boolean tensor.\n * @private\n */\nfunction boolTensor(value) {\n return new Tensor('bool', [value], [1]);\n}\n\n// JS doesn't support mixins, so we define some reused functions here, and allow \"this\" to be passed in\n/**\n * Perform forward pass on the seq2seq model (both encoder and decoder).\n * @param {Object} self The seq2seq model object.\n * @param {Object} model_inputs The input object for the model containing encoder and decoder inputs.\n * @returns {Promise} Promise that resolves with the output of the seq2seq model.\n * @private\n */\nasync function seq2seqForward(self, model_inputs) {\n let { encoder_outputs, input_ids, decoder_input_ids, ...other_decoder_inputs } = model_inputs;\n // Encode if needed\n if (!encoder_outputs) {\n const encoder_inputs = pick(model_inputs, self.sessions['model'].inputNames);\n // Encoder outputs are not given, so we must compute them.\n encoder_outputs = (await encoderForward(self, encoder_inputs)).last_hidden_state;\n }\n\n other_decoder_inputs.input_ids = decoder_input_ids;\n other_decoder_inputs.encoder_hidden_states = encoder_outputs;\n\n if (self.sessions['decoder_model_merged'].inputNames.includes('encoder_attention_mask')) {\n other_decoder_inputs.encoder_attention_mask = model_inputs.attention_mask\n }\n\n const decoderResults = await decoderForward(self, other_decoder_inputs, true);\n\n return decoderResults;\n}\n\n/**\n * Forward pass of an encoder model.\n * @param {Object} self The encoder model.\n * @param {Object} model_inputs The input data to be used for the forward pass.\n * @returns {Promise} The model's outputs.\n * @private\n */\nasync function encoderForward(self, model_inputs) {\n const session = self.sessions['model'];\n const encoderFeeds = pick(model_inputs, session.inputNames);\n\n if (session.inputNames.includes('inputs_embeds') && !encoderFeeds.inputs_embeds) {\n if (!model_inputs.input_ids) {\n throw new Error('Both `input_ids` and `inputs_embeds` are missing in the model inputs.');\n }\n encoderFeeds.inputs_embeds = await self.encode_text({ input_ids: model_inputs.input_ids });\n }\n if (session.inputNames.includes('token_type_ids') && !encoderFeeds.token_type_ids) {\n // Assign default `token_type_ids` (all zeroes) to the `encoderFeeds` if the model expects it,\n // but they weren't created by the tokenizer.\n encoderFeeds.token_type_ids = new Tensor(\n 'int64',\n new BigInt64Array(encoderFeeds.input_ids.data.length),\n encoderFeeds.input_ids.dims\n )\n }\n return await sessionRun(session, encoderFeeds);\n}\n\n/**\n * Forward pass of a decoder model.\n * @param {Object} self The decoder model.\n * @param {Object} model_inputs The input data to be used for the forward pass.\n * @returns {Promise} The logits and past key values.\n * @private\n */\nasync function decoderForward(self, model_inputs, is_encoder_decoder = false) {\n\n const session = self.sessions[\n is_encoder_decoder ? 'decoder_model_merged' : 'model'\n ]\n\n const { past_key_values, ...new_model_inputs } = model_inputs;\n\n if (session.inputNames.includes('use_cache_branch')) {\n new_model_inputs.use_cache_branch = boolTensor(!!past_key_values);\n }\n if (session.inputNames.includes('position_ids') && new_model_inputs.attention_mask && !new_model_inputs.position_ids) {\n new_model_inputs.position_ids = createPositionIds(new_model_inputs, past_key_values);\n }\n\n // Unpack the `past_key_values` object into model inputs\n self.addPastKeyValues(new_model_inputs, past_key_values);\n\n // Select only the inputs that are needed for the current session\n const fixed = pick(new_model_inputs, session.inputNames);\n return await sessionRun(session, fixed);\n}\n\n\n/**\n * Forward pass of an image-text-to-text model.\n * @param {Object} self The image-text-to-text model model.\n * @param {Object} model_inputs The input data to be used for the forward pass.\n * @param {Tensor} [model_inputs.input_ids=null]\n * @param {Tensor} [model_inputs.attention_mask=null]\n * @param {Tensor} [model_inputs.pixel_values=null]\n * @param {Tensor} [model_inputs.position_ids=null]\n * @param {Tensor} [model_inputs.inputs_embeds=null]\n * @param {Tensor} [model_inputs.past_key_values=null]\n * @param {Object} [model_inputs.generation_config=null]\n * @param {Object} [model_inputs.logits_processor=null]\n * @returns {Promise} The model's output tensor\n * @private\n */\nasync function imageTextToTextForward(self, {\n // Produced by the tokenizer/processor:\n input_ids = null,\n attention_mask = null,\n pixel_values = null,\n\n // Used during generation:\n position_ids = null,\n inputs_embeds = null,\n past_key_values = null,\n\n // Generic generation parameters\n generation_config = null,\n logits_processor = null,\n\n // TODO: needed?\n ...kwargs\n}) {\n\n if (!inputs_embeds) {\n // 1. Extract the input embeddings\n inputs_embeds = await self.encode_text({ input_ids });\n\n // 2. Possibly, merge text and images\n if (pixel_values && input_ids.dims[1] !== 1) {\n const image_features = await self.encode_image({ pixel_values });\n\n ({ inputs_embeds, attention_mask } = self._merge_input_ids_with_image_features({\n image_features,\n inputs_embeds,\n input_ids,\n attention_mask,\n }));\n\n } else if (past_key_values && pixel_values && input_ids.dims[1] === 1) {\n // This is the case when we are generating with cache\n const target_length = input_ids.dims[1]; // always 1\n const past_length = Object.values(past_key_values)[0].dims.at(-2);\n\n attention_mask = cat([\n ones([input_ids.dims[0], past_length]),\n attention_mask.slice(null, [attention_mask.dims[1] - target_length, attention_mask.dims[1]]),\n ], 1);\n }\n }\n\n const outputs = await decoderForward(self, {\n inputs_embeds,\n past_key_values,\n attention_mask,\n position_ids,\n generation_config,\n logits_processor,\n }, true);\n return outputs;\n}\n\nfunction createPositionIds(model_inputs, past_key_values = null) {\n // If the model supports providing position_ids, we create position_ids on the fly for batch generation,\n // by computing the cumulative sum of the attention mask along the sequence length dimension.\n // \n // Equivalent to:\n // position_ids = attention_mask.long().cumsum(-1) - 1\n // position_ids.masked_fill_(attention_mask == 0, 1)\n // if past_key_values:\n // position_ids = position_ids[:, -input_ids.shape[1] :]\n const { input_ids, inputs_embeds, attention_mask } = model_inputs;\n const [bz, seq_len] = attention_mask.dims;\n\n const data = new BigInt64Array(attention_mask.data.length);\n for (let i = 0; i < bz; ++i) {\n const start = i * seq_len;\n let sum = BigInt(0);\n for (let j = 0; j < seq_len; ++j) {\n const index = start + j;\n if (attention_mask.data[index] === 0n) {\n data[index] = BigInt(1);\n } else { // === 1n\n data[index] = sum;\n sum += attention_mask.data[index];\n }\n }\n }\n\n let position_ids = new Tensor('int64', data, attention_mask.dims);\n if (past_key_values) {\n const offset = -(input_ids ?? inputs_embeds).dims.at(1);\n position_ids = position_ids.slice(null, [offset, null]);\n }\n return position_ids;\n}\n\nfunction decoder_prepare_inputs_for_generation(self, input_ids, model_inputs, generation_config) {\n if (model_inputs.past_key_values) {\n const past_length = Object.values(model_inputs.past_key_values)[0].dims.at(-2);\n const { input_ids, attention_mask } = model_inputs;\n\n // Keep only the unprocessed tokens:\n // 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where\n // some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as\n // input)\n if (attention_mask && attention_mask.dims[1] > input_ids.dims[1]) {\n // NOTE: not needed since we only pass the generated tokens to the next forward pass\n // const offset = -(attention_mask.dims[1] - past_length);\n // model_inputs.input_ids = input_ids.slice(null, [offset, null]);\n }\n // 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens.\n // We can discard input_ids based on the past_length.\n else if (past_length < input_ids.dims[1]) {\n // NOTE: Required for phi models.\n // See https://github.com/huggingface/transformers/issues/30809#issuecomment-2111918479 for more information.\n model_inputs.input_ids = input_ids.slice(null, [past_length, null]);\n }\n // 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.\n else {\n if (\n // NOTE: Only used by VLMs (!= so that null matches undefined)\n self.config.image_token_index != null &&\n // Equivalent to `self.config.image_token_index in input_ids` (== so that int matches bigint)\n input_ids.data.some(x => x == self.config.image_token_index)\n ) {\n // TODO: Support multiple image tokens\n const num_image_tokens = self.config.num_image_tokens;\n if (!num_image_tokens) {\n throw new Error('`num_image_tokens` is missing in the model configuration.');\n }\n\n const num_new_tokens = input_ids.dims[1] - (past_length - num_image_tokens);\n model_inputs.input_ids = input_ids.slice(null, [-num_new_tokens, null]);\n\n // TODO: The attention mask should be formed from the attention mask passed in model_inputs\n model_inputs.attention_mask = ones([1, past_length + num_new_tokens]);\n }\n }\n }\n\n return model_inputs;\n}\n\nfunction encoder_decoder_prepare_inputs_for_generation(self, input_ids, model_inputs, generation_config) {\n if (model_inputs.past_key_values) {\n input_ids = input_ids.map(x => [x.at(-1)]);\n }\n\n return {\n ...model_inputs,\n decoder_input_ids: toI64Tensor(input_ids),\n };\n}\n\nfunction image_text_to_text_prepare_inputs_for_generation(self, ...args) {\n if (self.config.is_encoder_decoder) {\n return encoder_decoder_prepare_inputs_for_generation(self, ...args);\n } else {\n return decoder_prepare_inputs_for_generation(self, ...args);\n }\n}\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n/**\n * A base class for pre-trained models that provides the model configuration and an ONNX session.\n */\nexport class PreTrainedModel extends Callable {\n main_input_name = 'input_ids';\n forward_params = ['input_ids', 'attention_mask'];\n /**\n * Creates a new instance of the `PreTrainedModel` class.\n * @param {import('./configs.js').PretrainedConfig} config The model configuration.\n * @param {Record} sessions The inference sessions for the model.\n * @param {Record} configs Additional configuration files (e.g., generation_config.json).\n */\n constructor(config, sessions, configs) {\n super();\n\n this.config = config;\n this.sessions = sessions;\n this.configs = configs;\n\n const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);\n const modelType = MODEL_TYPE_MAPPING.get(modelName);\n\n this.can_generate = false;\n this._forward = null;\n\n this._prepare_inputs_for_generation = null;\n switch (modelType) {\n case MODEL_TYPES.DecoderOnly:\n this.can_generate = true;\n this._forward = decoderForward;\n this._prepare_inputs_for_generation = decoder_prepare_inputs_for_generation;\n break;\n case MODEL_TYPES.Seq2Seq:\n case MODEL_TYPES.Vision2Seq:\n case MODEL_TYPES.Musicgen:\n this.can_generate = true;\n\n this._forward = seq2seqForward;\n this._prepare_inputs_for_generation = encoder_decoder_prepare_inputs_for_generation;\n break;\n\n case MODEL_TYPES.EncoderDecoder:\n this._forward = seq2seqForward;\n break;\n case MODEL_TYPES.ImageTextToText:\n this.can_generate = true;\n this._forward = imageTextToTextForward;\n this._prepare_inputs_for_generation = image_text_to_text_prepare_inputs_for_generation;\n break;\n\n default:\n // should be MODEL_TYPES.EncoderOnly\n this._forward = encoderForward;\n break;\n }\n\n if (this.can_generate) {\n this.forward_params.push('past_key_values');\n }\n\n /** @type {import('./configs.js').TransformersJSConfig} */\n this.custom_config = this.config['transformers.js_config'] ?? {};\n }\n\n /**\n * Disposes of all the ONNX sessions that were created during inference.\n * @returns {Promise} An array of promises, one for each ONNX session that is being disposed.\n * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n */\n async dispose() {\n const promises = [];\n for (const session of Object.values(this.sessions)) {\n if (session?.handler?.dispose) {\n promises.push(session.handler.dispose())\n }\n }\n return await Promise.all(promises);\n }\n\n /**\n * Instantiate one of the model classes of the library from a pretrained model.\n * \n * The model class to instantiate is selected based on the `model_type` property of the config object\n * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)\n * \n * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:\n * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.\n * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a\n * user or organization name, like `dbmdz/bert-base-german-cased`.\n * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`.\n * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the model.\n * \n * @returns {Promise} A new instance of the `PreTrainedModel` class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n model_file_name = null,\n subfolder = 'onnx',\n device = null,\n dtype = null,\n use_external_data_format = null,\n session_options = {},\n } = {}) {\n\n let options = {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n model_file_name,\n subfolder,\n device,\n dtype,\n use_external_data_format,\n session_options,\n }\n\n const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this);\n const modelType = MODEL_TYPE_MAPPING.get(modelName);\n\n config = options.config = await AutoConfig.from_pretrained(pretrained_model_name_or_path, options);\n\n let info;\n if (modelType === MODEL_TYPES.DecoderOnly) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: options.model_file_name ?? 'model',\n }, options),\n getOptionalConfigs(pretrained_model_name_or_path, {\n generation_config: 'generation_config.json',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: 'encoder_model',\n decoder_model_merged: 'decoder_model_merged',\n }, options),\n getOptionalConfigs(pretrained_model_name_or_path, {\n generation_config: 'generation_config.json',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.MaskGeneration) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: 'vision_encoder',\n prompt_encoder_mask_decoder: 'prompt_encoder_mask_decoder',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.EncoderDecoder) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: 'encoder_model',\n decoder_model_merged: 'decoder_model_merged',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.ImageTextToText) {\n const sessions = {\n embed_tokens: 'embed_tokens',\n vision_encoder: 'vision_encoder',\n decoder_model_merged: 'decoder_model_merged',\n }\n if (config.is_encoder_decoder) {\n sessions['model'] = 'encoder_model';\n }\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, sessions, options),\n getOptionalConfigs(pretrained_model_name_or_path, {\n generation_config: 'generation_config.json',\n }, options),\n ]);\n\n } else if (modelType === MODEL_TYPES.Musicgen) {\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: 'text_encoder',\n decoder_model_merged: 'decoder_model_merged',\n encodec_decode: 'encodec_decode',\n }, options),\n getOptionalConfigs(pretrained_model_name_or_path, {\n generation_config: 'generation_config.json',\n }, options),\n ]);\n\n } else { // should be MODEL_TYPES.EncoderOnly\n if (modelType !== MODEL_TYPES.EncoderOnly) {\n console.warn(`Model type for '${modelName ?? config?.model_type}' not found, assuming encoder-only architecture. Please report this at ${GITHUB_ISSUE_URL}.`)\n }\n info = await Promise.all([\n constructSessions(pretrained_model_name_or_path, {\n model: options.model_file_name ?? 'model',\n }, options),\n ]);\n }\n\n // @ts-ignore\n return new this(config, ...info);\n }\n\n /**\n * Runs the model with the provided inputs\n * @param {Object} model_inputs Object containing input tensors\n * @returns {Promise} Object containing output tensors\n */\n async _call(model_inputs) {\n return await this.forward(model_inputs);\n }\n\n /**\n * Forward method for a pretrained model. If not overridden by a subclass, the correct forward method\n * will be chosen based on the model type.\n * @param {Object} model_inputs The input data to the model in the format specified in the ONNX model.\n * @returns {Promise} The output data from the model in the format specified in the ONNX model.\n * @throws {Error} This method must be implemented in subclasses.\n */\n async forward(model_inputs) {\n return await this._forward(this, model_inputs);\n }\n\n /**\n * Get the model's generation config, if it exists.\n * @returns {GenerationConfig|null} The model's generation config if it exists, otherwise `null`.\n */\n get generation_config() {\n return this.configs?.generation_config ?? null;\n }\n\n /**\n * This function returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsWarper`]\n * instances used for multinomial sampling.\n * @param {GenerationConfig} generation_config The generation config.\n * @returns {LogitsProcessorList} generation_config \n */\n _get_logits_warper(generation_config) {\n\n // instantiate warpers list\n const warpers = new LogitsProcessorList();\n\n if (generation_config.temperature !== null && generation_config.temperature !== 1.0) {\n warpers.push(new TemperatureLogitsWarper(generation_config.temperature));\n }\n if (generation_config.top_k !== null && generation_config.top_k !== 0) {\n // TODO: add min_tokens_to_keep\n warpers.push(new TopKLogitsWarper(generation_config.top_k));\n }\n if (generation_config.top_p !== null && generation_config.top_p < 1.0) {\n // TODO: add min_tokens_to_keep\n warpers.push(new TopPLogitsWarper(generation_config.top_p));\n }\n\n return warpers;\n }\n\n /**\n * @param {GenerationConfig} generation_config \n * @param {number} input_ids_seq_length The starting sequence length for the input ids.\n * @returns {LogitsProcessorList}\n * @private\n */\n _get_logits_processor(\n generation_config,\n input_ids_seq_length,\n // encoder_input_ids, TODO\n // prefix_allowed_tokens_fn, TODO\n logits_processor = null\n ) {\n const processors = new LogitsProcessorList();\n\n // if (generation_config.diversity_penalty !== null && generation_config.diversity_penalty > 0.0) {\n // processors.push(new HammingDiversityLogitsProcessor(\n // generation_config.diversity_penalty,\n // generation_config.num_beams,\n // generation_config.num_beam_groups\n // ));\n // }\n\n // if (generation_config.encoder_repetition_penalty !== null && generation_config.encoder_repetition_penalty !== 1.0) {\n // processors.push(new EncoderRepetitionPenaltyLogitsProcessor(\n // generation_config.encoder_repetition_penalty,\n // encoder_input_ids\n // ));\n // }\n\n if (generation_config.repetition_penalty !== null && generation_config.repetition_penalty !== 1.0) {\n processors.push(new RepetitionPenaltyLogitsProcessor(generation_config.repetition_penalty));\n }\n\n if (generation_config.no_repeat_ngram_size !== null && generation_config.no_repeat_ngram_size > 0) {\n processors.push(new NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size));\n }\n\n // if (generation_config.encoder_no_repeat_ngram_size !== null && generation_config.encoder_no_repeat_ngram_size > 0) {\n // if (this.config.is_encoder_decoder) {\n // processors.push(new EncoderNoRepeatNGramLogitsProcessor(\n // generation_config.encoder_no_repeat_ngram_size,\n // encoder_input_ids\n // ));\n // } else {\n // throw new Error(\"It's impossible to use `encoder_no_repeat_ngram_size` with decoder-only architecture\");\n // }\n // }\n\n if (generation_config.bad_words_ids !== null) {\n processors.push(new NoBadWordsLogitsProcessor(generation_config.bad_words_ids, generation_config.eos_token_id));\n }\n\n if (generation_config.min_length !== null && generation_config.eos_token_id !== null && generation_config.min_length > 0) {\n processors.push(new MinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id));\n }\n\n if (generation_config.min_new_tokens !== null && generation_config.eos_token_id !== null && generation_config.min_new_tokens > 0) {\n processors.push(new MinNewTokensLengthLogitsProcessor(\n input_ids_seq_length,\n generation_config.min_new_tokens,\n generation_config.eos_token_id\n ));\n }\n\n // if (prefix_allowed_tokens_fn !== null) {\n // processors.push(new PrefixConstrainedLogitsProcessor(\n // prefix_allowed_tokens_fn,\n // generation_config.num_beams / generation_config.num_beam_groups\n // ));\n // }\n\n\n if (generation_config.forced_bos_token_id !== null) {\n processors.push(new ForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id));\n }\n\n if (generation_config.forced_eos_token_id !== null) {\n processors.push(new ForcedEOSTokenLogitsProcessor(\n generation_config.max_length,\n generation_config.forced_eos_token_id\n ));\n }\n\n // if (generation_config.remove_invalid_values === true) {\n // processors.push(new InfNanRemoveLogitsProcessor());\n // }\n\n // if (generation_config.exponential_decay_length_penalty !== null) {\n // processors.push(new ExponentialDecayLengthPenalty(\n // generation_config.exponential_decay_length_penalty,\n // generation_config.eos_token_id,\n // input_ids_seq_length\n // ));\n // }\n\n // if (generation_config.suppress_tokens !== null) {\n // processors.push(new SuppressTokensLogitsProcessor(generation_config.suppress_tokens));\n // }\n\n if (generation_config.begin_suppress_tokens !== null) {\n const begin_index = (input_ids_seq_length > 1 || generation_config.forced_bos_token_id === null)\n ? input_ids_seq_length\n : input_ids_seq_length + 1;\n\n processors.push(new SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index));\n }\n\n // DEPRECATED: https://github.com/huggingface/transformers/pull/29485\n // if (generation_config.forced_decoder_ids !== null) {\n // processors.push(new ForceTokensLogitsProcessor(generation_config.forced_decoder_ids));\n // }\n\n\n // 8. prepare batched CFG externally\n if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) {\n processors.push(new ClassifierFreeGuidanceLogitsProcessor(generation_config.guidance_scale));\n }\n\n if (logits_processor !== null) {\n processors.extend(logits_processor)\n }\n\n // `LogitNormalization` should always be the last logit processor, when present\n // if (generation_config.renormalize_logits === true) {\n // processors.push(new LogitNormalization());\n // }\n\n return processors;\n }\n\n /**\n * This function merges multiple generation configs together to form a final generation config to be used by the model for text generation.\n * It first creates an empty `GenerationConfig` object, then it applies the model's own `generation_config` property to it. Finally, if a `generation_config` object was passed in the arguments, it overwrites the corresponding properties in the final config with those of the passed config object.\n * @param {GenerationConfig|null} generation_config A `GenerationConfig` object containing generation parameters.\n * @param {Object} kwargs Additional generation parameters to be used in place of those in the `generation_config` object.\n * @returns {GenerationConfig} The final generation config object to be used by the model for text generation.\n */\n _prepare_generation_config(generation_config, kwargs, cls = GenerationConfig) {\n // Create empty generation config (contains defaults)\n // We pass `this.config` so that if `eos_token_id` or `bos_token_id` exist in the model's config, we will use them\n const config = { ...this.config };\n for (const key of [\"decoder\", \"generator\", \"text_config\"]) {\n // Special case: some models have generation attributes set in the decoder.\n // Use them if still unset in the generation config.\n if (key in config) {\n Object.assign(config, config[key]);\n }\n }\n\n const gen_config = new cls(config);\n\n // Apply model's generation config, if it exists\n Object.assign(gen_config, this.generation_config ?? {});\n\n // Next, use any generation config specified by the user\n // when calling `generate`\n if (generation_config) {\n Object.assign(gen_config, generation_config);\n }\n\n // Finally, if any kwargs were passed, use them to overwrite\n if (kwargs) {\n Object.assign(gen_config, pick(kwargs, Object.getOwnPropertyNames(gen_config)));\n }\n\n return gen_config;\n }\n\n /**\n * \n * @param {GenerationConfig} generation_config \n * @param {StoppingCriteriaList} [stopping_criteria=null] \n */\n _get_stopping_criteria(generation_config, stopping_criteria = null) {\n const criteria = new StoppingCriteriaList();\n\n if (generation_config.max_length !== null) {\n criteria.push(new MaxLengthCriteria(\n generation_config.max_length,\n this.config.max_position_embeddings ?? null,\n ));\n }\n // if (generation_config.max_time !== null) {\n // criteria.push(new MaxTimeCriteria(generation_config.max_time));\n // }\n if (generation_config.eos_token_id !== null) {\n criteria.push(new EosTokenCriteria(generation_config.eos_token_id));\n }\n\n if (stopping_criteria) {\n criteria.extend(stopping_criteria);\n }\n return criteria;\n\n }\n\n /**\n * Confirms that the model class is compatible with generation.\n * If not, raises an exception that points to the right class to use.\n */\n _validate_model_class() {\n if (!this.can_generate) {\n const generate_compatible_mappings = [\n MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,\n // MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING, // TODO\n MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,\n MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,\n MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES,\n ];\n\n const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);\n\n const generate_compatible_classes = new Set();\n const modelType = this.config.model_type;\n for (const model_mapping of generate_compatible_mappings) {\n const supported_models = model_mapping.get(modelType);\n if (supported_models) {\n generate_compatible_classes.add(supported_models[0]);\n }\n }\n\n let errorMessage = `The current model class (${modelName}) is not compatible with \\`.generate()\\`, as it doesn't have a language model head.`\n if (generate_compatible_classes.size > 0) {\n errorMessage += ` Please use the following class instead: ${[...generate_compatible_classes].join(', ')}`;\n }\n throw Error(errorMessage);\n }\n }\n\n prepare_inputs_for_generation(...args) {\n return this._prepare_inputs_for_generation(this, ...args);\n }\n\n /**\n * \n * @param {Object} inputs\n * @param {bigint[][]} inputs.generated_input_ids\n * @param {Object} inputs.outputs\n * @param {Object} inputs.model_inputs\n * @param {boolean} inputs.is_encoder_decoder\n * @returns {Object} The updated model inputs for the next generation iteration.\n */\n _update_model_kwargs_for_generation({ generated_input_ids, outputs, model_inputs, is_encoder_decoder }) {\n // update past_key_values\n model_inputs['past_key_values'] = this.getPastKeyValues(outputs, model_inputs.past_key_values);\n\n // update inputs for next run\n model_inputs['input_ids'] = new Tensor('int64', generated_input_ids.flat(), [generated_input_ids.length, 1]);\n\n if (!is_encoder_decoder) {\n // update attention mask\n model_inputs.attention_mask = cat(\n [\n model_inputs.attention_mask,\n ones([model_inputs.attention_mask.dims[0], 1]),\n ], 1\n );\n } else if ('decoder_attention_mask' in model_inputs) {\n // TODO: update decoder attention mask if the model requires it\n }\n\n // force recreate position_ids in next iteration\n model_inputs['position_ids'] = null;\n\n return model_inputs;\n }\n\n /**\n * This function extracts the model-specific `inputs` for generation.\n * @param {Object} params\n * @param {Tensor} [params.inputs=null]\n * @param {number} [params.bos_token_id=null]\n * @param {Record} [params.model_kwargs]\n * @returns {{inputs_tensor: Tensor, model_inputs: Record, model_input_name: string}} The model-specific inputs for generation.\n */\n _prepare_model_inputs({ inputs, bos_token_id, model_kwargs }) {\n const model_inputs = pick(model_kwargs, this.forward_params);\n const input_name = this.main_input_name;\n if (input_name in model_inputs) {\n if (inputs) {\n throw new Error(\n \"`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. \" +\n \"Make sure to either pass {inputs} or {input_name}=...\"\n );\n }\n } else {\n model_inputs[input_name] = inputs;\n }\n\n const inputs_tensor = model_inputs[input_name];\n\n return { inputs_tensor, model_inputs, model_input_name: input_name };\n }\n\n async _prepare_encoder_decoder_kwargs_for_generation({ inputs_tensor, model_inputs, model_input_name, generation_config }) {\n if (\n this.sessions['model'].inputNames.includes('inputs_embeds')\n && !model_inputs.inputs_embeds\n && '_prepare_inputs_embeds' in this\n ) {\n // Encoder expects `inputs_embeds` instead of `input_ids`\n const { input_ids, pixel_values, attention_mask, ...kwargs } = model_inputs;\n // @ts-ignore\n const prepared_inputs = await this._prepare_inputs_embeds(model_inputs);\n model_inputs = {\n ...kwargs,\n ...pick(prepared_inputs, ['inputs_embeds', 'attention_mask']),\n };\n }\n let { last_hidden_state } = await encoderForward(this, model_inputs);\n\n // for classifier free guidance we need to add a 'null' input to our encoder hidden states\n if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) {\n\n last_hidden_state = cat([\n last_hidden_state,\n full_like(last_hidden_state, 0.0),\n ], 0);\n\n if ('attention_mask' in model_inputs) {\n model_inputs['attention_mask'] = cat([\n model_inputs['attention_mask'],\n zeros_like(model_inputs['attention_mask']),\n ], 0);\n }\n\n } else if (model_inputs.decoder_input_ids) {\n // Ensure that the encoder outputs have the same batch size as the decoder inputs,\n // allowing for more efficient batched generation for single inputs\n const decoder_input_ids_batch_size = toI64Tensor(model_inputs.decoder_input_ids).dims[0];\n if (decoder_input_ids_batch_size !== last_hidden_state.dims[0]) {\n if (last_hidden_state.dims[0] !== 1) {\n throw new Error(\n `The encoder outputs have a different batch size (${last_hidden_state.dims[0]}) than the decoder inputs (${decoder_input_ids_batch_size}).`\n )\n }\n last_hidden_state = cat(Array.from({ length: decoder_input_ids_batch_size }, () => last_hidden_state), 0);\n }\n }\n model_inputs['encoder_outputs'] = last_hidden_state;\n\n return model_inputs;\n }\n\n /**\n * Prepares `decoder_input_ids` for generation with encoder-decoder models\n * @param {*} param0 \n */\n _prepare_decoder_input_ids_for_generation({ batch_size, model_input_name, model_kwargs, decoder_start_token_id, bos_token_id, generation_config }) {\n let { decoder_input_ids, ...model_inputs } = model_kwargs;\n\n // Prepare input ids if the user has not defined `decoder_input_ids` manually.\n if (!decoder_input_ids) {\n decoder_start_token_id ??= bos_token_id;\n\n if (this.config.model_type === 'musicgen') {\n // Custom logic (TODO: move to Musicgen class)\n decoder_input_ids = Array.from({\n length: batch_size * this.config.decoder.num_codebooks\n }, () => [decoder_start_token_id]);\n\n } else if (Array.isArray(decoder_start_token_id)) {\n if (decoder_start_token_id.length !== batch_size) {\n throw new Error(\n `\\`decoder_start_token_id\\` expcted to have length ${batch_size} but got ${decoder_start_token_id.length}`\n )\n }\n decoder_input_ids = decoder_start_token_id;\n } else {\n decoder_input_ids = Array.from({\n length: batch_size,\n }, () => [decoder_start_token_id]);\n }\n } else if (!Array.isArray(decoder_input_ids[0])) {\n // Correct batch size\n decoder_input_ids = Array.from({\n length: batch_size,\n }, () => decoder_input_ids);\n }\n\n decoder_input_ids = toI64Tensor(decoder_input_ids);\n model_kwargs['decoder_attention_mask'] = ones_like(decoder_input_ids);\n\n return { input_ids: decoder_input_ids, model_inputs };\n }\n\n /**\n * Generates sequences of token ids for models with a language modeling head.\n * @param {import('./generation/parameters.js').GenerationFunctionParameters} options\n * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores.\n */\n async generate({\n inputs = null,\n generation_config = null,\n logits_processor = null,\n stopping_criteria = null,\n streamer = null,\n\n // inputs_attention_mask = null,\n ...kwargs\n }) {\n this._validate_model_class();\n\n // Update generation config with defaults and kwargs\n generation_config = this._prepare_generation_config(generation_config, kwargs);\n\n // 3. Define model inputs\n let { inputs_tensor, model_inputs, model_input_name } = this._prepare_model_inputs({\n inputs,\n model_kwargs: kwargs,\n });\n\n const is_encoder_decoder = this.config.is_encoder_decoder;\n\n // 4. Define other model kwargs\n if (!is_encoder_decoder) {\n // decoder-only models should use left-padding for generation\n } else if (!('encoder_outputs' in model_inputs)) {\n // if model is encoder decoder encoder_outputs are created\n // and added to `model_kwargs`\n model_inputs = await this._prepare_encoder_decoder_kwargs_for_generation(\n { inputs_tensor, model_inputs, model_input_name, generation_config }\n )\n }\n\n // 5. Prepare `input_ids` which will be used for auto-regressive generation\n // TODO: Update to align with HF transformers' implementation\n let input_ids;\n if (is_encoder_decoder) {\n // Generating from the encoder outputs\n ({ input_ids, model_inputs } = this._prepare_decoder_input_ids_for_generation({\n batch_size: model_inputs[model_input_name].dims.at(0),\n model_input_name,\n model_kwargs: model_inputs,\n decoder_start_token_id: generation_config.decoder_start_token_id,\n bos_token_id: generation_config.bos_token_id,\n generation_config,\n }));\n } else {\n input_ids = model_inputs[model_input_name]\n }\n\n // 6. Prepare `max_length` depending on other stopping criteria.\n let input_ids_length = input_ids.dims.at(-1);\n\n if (generation_config.max_new_tokens !== null) {\n generation_config.max_length = input_ids_length + generation_config.max_new_tokens;\n }\n\n // input_ids_length = model_inputs[model_input_name].dims.at(1);\n // // inputs instanceof Tensor ? : inputs.length;\n\n // // decoder-only\n // if (input_ids_length === 0) {\n // throw Error(\"Must supply a non-empty array of input token ids.\")\n // }\n\n // let decoder_input_ids =\n // generation_config.decoder_input_ids\n // ?? generation_config.decoder_start_token_id\n // ?? generation_config.bos_token_id\n // ?? generation_config.eos_token_id;\n\n // Update logits processor\n // 8. prepare distribution pre_processing samplers\n const prepared_logits_processor = this._get_logits_processor(\n generation_config,\n input_ids_length,\n logits_processor,\n )\n\n // 9. prepare stopping criteria\n const prepared_stopping_criteria = this._get_stopping_criteria(\n generation_config, stopping_criteria\n )\n\n // /** @type {number[]} */\n // let eos_token_ids = generation_config.eos_token_id;\n // if (eos_token_ids !== null && !Array.isArray(eos_token_ids)) {\n // eos_token_ids = [eos_token_ids];\n // }\n\n const numInputs = model_inputs[model_input_name].dims.at(0);\n\n // TODO:\n // done is a list of booleans to keep track of which inputs are done\n // const done = new Array(numInputs).fill(false);\n // For efficiency purposes, we remove completed rows from model_inputs\n // when the beam is complete, and we keep track of the row index\n // const rowIndexToBatchIndex = new Map();\n\n const sampler = LogitsSampler.getSampler(generation_config);\n\n // TODO make > numInputs\n const scores = new Array(numInputs).fill(0);\n /** @type {bigint[][]} */\n const all_input_ids = input_ids.tolist();\n if (streamer) {\n streamer.put(all_input_ids);\n }\n // const all_generated_input_ids = Array.from({ length: numInputs }, () => []);\n\n // NOTE: For now, we don't support spawning new beams\n // TODO: when we do, we simply copy past key values and accumulate into single large tensor\n\n ////////////////////////////////////////////////////\n // Generic search which handles 4 generation modes:\n // - GenerationMode.GREEDY_SEARCH\n // - GenerationMode.SAMPLE\n // - GenerationMode.BEAM_SEARCH\n // - GenerationMode.BEAM_SAMPLE\n ////////////////////////////////////////////////////\n let outputs;\n let attentions = {};\n while (true) {\n // prepare model inputs\n model_inputs = this.prepare_inputs_for_generation(all_input_ids, model_inputs, generation_config);\n outputs = await this.forward(model_inputs);\n\n if (generation_config.output_attentions && generation_config.return_dict_in_generate) {\n // Get attentions if they are present\n const token_attentions = this.getAttentions(outputs);\n for (const key in token_attentions) {\n if (!(key in attentions)) {\n attentions[key] = [];\n }\n attentions[key].push(token_attentions[key]);\n }\n }\n\n // Logits are of the form [batch_size, out_seq_length, vocab_size]\n // In most cases, this will be [batch_size, 1, vocab_size]\n // So, we select the last token's logits:\n // (equivalent to `logits = outputs.logits[:, -1, :]`)\n const logits = outputs.logits.slice(null, -1, null);\n\n const next_tokens_scores = prepared_logits_processor(all_input_ids, logits);\n\n /** @type {[bigint][]} */\n const generated_input_ids = [];\n // const new_kv_cache = [];// NOTE: Only used for beam search when concatenating new kv\n // Loop over each batch\n for (let batch_idx = 0; batch_idx < next_tokens_scores.dims.at(0); ++batch_idx) {\n const logs = next_tokens_scores[batch_idx];\n\n const sampledTokens = await sampler(logs);\n for (const [newTokenId, logProb] of sampledTokens) {\n const bigint = BigInt(newTokenId);\n // TODO: If branching, use previous beam as a starting point\n // update generated ids, model inputs, and length for next step\n scores[batch_idx] += logProb;\n all_input_ids[batch_idx].push(bigint);\n generated_input_ids.push([bigint]);\n\n // TODO: Support beam search\n break;\n }\n }\n if (streamer) {\n streamer.put(generated_input_ids);\n }\n\n const stop = prepared_stopping_criteria(all_input_ids);\n if (stop.every(x => x)) {\n break;\n }\n\n model_inputs = this._update_model_kwargs_for_generation({\n generated_input_ids, outputs, model_inputs, is_encoder_decoder,\n });\n }\n\n if (streamer) {\n streamer.end();\n }\n\n // Retrieve and dispose all final past key values (including encoder attentions)\n const past_key_values = this.getPastKeyValues(outputs, model_inputs.past_key_values, true);\n\n // TODO: ensure all_input_ids is padded correctly...\n const sequences = new Tensor('int64', all_input_ids.flat(), [all_input_ids.length, all_input_ids[0].length]);\n\n if (generation_config.return_dict_in_generate) {\n return {\n sequences,\n past_key_values,\n ...attentions,\n // TODO:\n // scores,\n // logits,\n }\n } else {\n // Dispose all remaining tensors\n for (const tensor of Object.values(outputs)) {\n if (tensor.location === 'gpu-buffer') {\n tensor.dispose();\n }\n }\n return sequences;\n }\n }\n\n /**\n * Returns an object containing past key values from the given decoder results object.\n *\n * @param {Object} decoderResults The decoder results object.\n * @param {Object} pastKeyValues The previous past key values.\n * @returns {Object} An object containing past key values.\n */\n getPastKeyValues(decoderResults, pastKeyValues, disposeEncoderPKVs = false) {\n const pkvs = Object.create(null);\n\n for (const name in decoderResults) {\n if (name.startsWith('present')) {\n const newName = name.replace('present', 'past_key_values');\n const is_encoder_pkv = name.includes('encoder');\n if (is_encoder_pkv && pastKeyValues) {\n // Optimization introduced by optimum to reuse past key values.\n // So, we just replace the constant outputs (`decoderResults[name]`) with the previous past key values.\n // https://github.com/huggingface/optimum/blob/0bf2c05fb7e1182b52d21b703cfc95fd9e4ea3dc/optimum/onnxruntime/base.py#L677-L704\n pkvs[newName] = pastKeyValues[newName];\n } else { // decoder or using first encoder PKVs\n pkvs[newName] = decoderResults[name];\n }\n\n if (pastKeyValues && (!is_encoder_pkv || disposeEncoderPKVs)) {\n // - Always dispose decoder PKVs\n // - Only dispose encoder past key values when requested (after generation)\n const t = pastKeyValues[newName];\n if (t.location === 'gpu-buffer') {\n t.dispose();\n }\n }\n }\n }\n return pkvs;\n }\n\n /**\n * Returns an object containing attentions from the given model output object.\n *\n * @param {Object} model_output The output of the model.\n * @returns {{cross_attentions?: Tensor[]}} An object containing attentions.\n */\n getAttentions(model_output) {\n const attentions = {};\n\n for (const attnName of ['cross_attentions', 'encoder_attentions', 'decoder_attentions']) {\n for (const name in model_output) {\n if (name.startsWith(attnName)) {\n if (!(attnName in attentions)) {\n attentions[attnName] = [];\n }\n attentions[attnName].push(model_output[name]);\n }\n }\n }\n return attentions;\n }\n\n /**\n * Adds past key values to the decoder feeds object. If pastKeyValues is null, creates new tensors for past key values.\n *\n * @param {Object} decoderFeeds The decoder feeds object to add past key values to.\n * @param {Object} pastKeyValues An object containing past key values.\n */\n addPastKeyValues(decoderFeeds, pastKeyValues) {\n if (pastKeyValues) {\n Object.assign(decoderFeeds, pastKeyValues)\n } else {\n const session = this.sessions['decoder_model_merged'] ?? this.sessions['model'];\n const dtype = session?.config?.kv_cache_dtype ?? 'float32';\n const empty = (dtype === 'float16') ? new Uint16Array() : [];\n\n const shapes = getKeyValueShapes(this.config);\n\n for (const name in shapes) {\n decoderFeeds[name] = new Tensor(dtype, empty, shapes[name]);\n }\n }\n }\n\n async encode_image({ pixel_values }) {\n // image_inputs === { pixel_values }\n const features = (await sessionRun(this.sessions['vision_encoder'], { pixel_values })).image_features;\n if (!this.config.num_image_tokens) {\n console.warn(\n 'The number of image tokens was not set in the model configuration. ' +\n `Setting it to the number of features detected by the vision encoder (${features.dims[1]}).`\n )\n this.config.num_image_tokens = features.dims[1];\n }\n return features;\n }\n\n async encode_text({ input_ids }) {\n // text_inputs === { input_ids, attention_mask }\n return (await sessionRun(this.sessions['embed_tokens'], { input_ids })).inputs_embeds;\n }\n}\n\n//////////////////////////////////////////////////\n// Base model output class\nexport class ModelOutput { }\n\n/**\n * Base class for model's outputs, with potential hidden states and attentions.\n */\nexport class BaseModelOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.last_hidden_state Sequence of hidden-states at the output of the last layer of the model.\n * @param {Tensor} [output.hidden_states] Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.\n * @param {Tensor} [output.attentions] Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n */\n constructor({ last_hidden_state, hidden_states = null, attentions = null }) {\n super();\n this.last_hidden_state = last_hidden_state;\n this.hidden_states = hidden_states;\n this.attentions = attentions;\n }\n}\n//////////////////////////////////////////////////\n// Bert models\nexport class BertPreTrainedModel extends PreTrainedModel { }\nexport class BertModel extends BertPreTrainedModel { }\n\n/**\n * BertForMaskedLM is a class representing a BERT model for masked language modeling.\n */\nexport class BertForMaskedLM extends BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * BertForSequenceClassification is a class representing a BERT model for sequence classification.\n */\nexport class BertForSequenceClassification extends BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * BertForTokenClassification is a class representing a BERT model for token classification.\n */\nexport class BertForTokenClassification extends BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * BertForQuestionAnswering is a class representing a BERT model for question answering.\n */\nexport class BertForQuestionAnswering extends BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// NomicBert models\nexport class NomicBertPreTrainedModel extends PreTrainedModel { }\nexport class NomicBertModel extends NomicBertPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// RoFormer models\nexport class RoFormerPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare RoFormer Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class RoFormerModel extends RoFormerPreTrainedModel { }\n\n/**\n * RoFormer Model with a `language modeling` head on top.\n */\nexport class RoFormerForMaskedLM extends RoFormerPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RoFormer Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class RoFormerForSequenceClassification extends RoFormerPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RoFormer Model with a token classification head on top (a linear layer on top of the hidden-states output)\n * e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class RoFormerForTokenClassification extends RoFormerPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RoFormer Model with a span classification head on top for extractive question-answering tasks like SQuAD\n * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n */\nexport class RoFormerForQuestionAnswering extends RoFormerPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n// TODO: Add RoFormerForCausalLM and RoFormerForMultipleChoice\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// ConvBert models\nexport class ConvBertPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ConvBERT Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class ConvBertModel extends ConvBertPreTrainedModel { }\n\n/**\n * ConvBERT Model with a language modeling head on top.\n */\nexport class ConvBertForMaskedLM extends ConvBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ConvBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class ConvBertForSequenceClassification extends ConvBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ConvBERT Model with a token classification head on top (a linear layer on top of the hidden-states output)\n * e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class ConvBertForTokenClassification extends ConvBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ConvBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD\n * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`)\n */\nexport class ConvBertForQuestionAnswering extends ConvBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Electra models\nexport class ElectraPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Electra Model transformer outputting raw hidden-states without any specific head on top.\n * Identical to the BERT model except that it uses an additional linear layer between the embedding\n * layer and the encoder if the hidden size and embedding size are different.\n */\nexport class ElectraModel extends ElectraPreTrainedModel { }\n// TODO add ElectraForPreTraining\n/**\n * Electra model with a language modeling head on top.\n */\nexport class ElectraForMaskedLM extends ElectraPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ELECTRA Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class ElectraForSequenceClassification extends ElectraPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * Electra model with a token classification head on top.\n */\nexport class ElectraForTokenClassification extends ElectraPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * LECTRA Model with a span classification head on top for extractive question-answering tasks like SQuAD\n * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n */\nexport class ElectraForQuestionAnswering extends ElectraPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// CamemBERT models\nexport class CamembertPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare CamemBERT Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class CamembertModel extends CamembertPreTrainedModel { }\n\n/**\n * CamemBERT Model with a `language modeling` head on top.\n */\nexport class CamembertForMaskedLM extends CamembertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * CamemBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.\n */\nexport class CamembertForSequenceClassification extends CamembertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * CamemBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class CamembertForTokenClassification extends CamembertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * CamemBERT Model with a span classification head on top for extractive question-answering tasks\n */\nexport class CamembertForQuestionAnswering extends CamembertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// DeBERTa models\nexport class DebertaPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare DeBERTa Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class DebertaModel extends DebertaPreTrainedModel { }\n\n/**\n * DeBERTa Model with a `language modeling` head on top.\n */\nexport class DebertaForMaskedLM extends DebertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class DebertaForSequenceClassification extends DebertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class DebertaForTokenClassification extends DebertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear\n * layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n */\nexport class DebertaForQuestionAnswering extends DebertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// DeBERTa-v2 models\nexport class DebertaV2PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare DeBERTa-V2 Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class DebertaV2Model extends DebertaV2PreTrainedModel { }\n\n/**\n * DeBERTa-V2 Model with a `language modeling` head on top.\n */\nexport class DebertaV2ForMaskedLM extends DebertaV2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa-V2 Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class DebertaV2ForSequenceClassification extends DebertaV2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa-V2 Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class DebertaV2ForTokenClassification extends DebertaV2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DeBERTa-V2 Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear\n * layers on top of the hidden-states output to compute `span start logits` and `span end logits`).\n */\nexport class DebertaV2ForQuestionAnswering extends DebertaV2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// DistilBert models\nexport class DistilBertPreTrainedModel extends PreTrainedModel { }\nexport class DistilBertModel extends DistilBertPreTrainedModel { }\n\n/**\n * DistilBertForSequenceClassification is a class representing a DistilBERT model for sequence classification.\n */\nexport class DistilBertForSequenceClassification extends DistilBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DistilBertForTokenClassification is a class representing a DistilBERT model for token classification.\n */\nexport class DistilBertForTokenClassification extends DistilBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n\n/**\n * DistilBertForQuestionAnswering is a class representing a DistilBERT model for question answering.\n */\nexport class DistilBertForQuestionAnswering extends DistilBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * DistilBertForMaskedLM is a class representing a DistilBERT model for masking task.\n */\nexport class DistilBertForMaskedLM extends DistilBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// ESM models\nexport class EsmPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ESM Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class EsmModel extends EsmPreTrainedModel { }\n\n/**\n * ESM Model with a `language modeling` head on top.\n */\nexport class EsmForMaskedLM extends EsmPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ESM Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class EsmForSequenceClassification extends EsmPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * ESM Model with a token classification head on top (a linear layer on top of the hidden-states output)\n * e.g. for Named-Entity-Recognition (NER) tasks.\n */\nexport class EsmForTokenClassification extends EsmPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// MobileBert models\nexport class MobileBertPreTrainedModel extends PreTrainedModel { }\nexport class MobileBertModel extends MobileBertPreTrainedModel { }\n\n/**\n * MobileBertForMaskedLM is a class representing a MobileBERT model for masking task.\n */\nexport class MobileBertForMaskedLM extends MobileBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class MobileBertForSequenceClassification extends MobileBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MobileBert Model with a span classification head on top for extractive question-answering tasks\n */\nexport class MobileBertForQuestionAnswering extends MobileBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MPNet models\nexport class MPNetPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MPNet Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class MPNetModel extends MPNetPreTrainedModel { }\n\n/**\n * MPNetForMaskedLM is a class representing a MPNet model for masked language modeling.\n */\nexport class MPNetForMaskedLM extends MPNetPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for masked language modeling.\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MPNetForSequenceClassification is a class representing a MPNet model for sequence classification.\n */\nexport class MPNetForSequenceClassification extends MPNetPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MPNetForTokenClassification is a class representing a MPNet model for token classification.\n */\nexport class MPNetForTokenClassification extends MPNetPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * MPNetForQuestionAnswering is a class representing a MPNet model for question answering.\n */\nexport class MPNetForQuestionAnswering extends MPNetPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for question answering.\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// SqueezeBert models\nexport class SqueezeBertPreTrainedModel extends PreTrainedModel { }\nexport class SqueezeBertModel extends SqueezeBertPreTrainedModel { }\nexport class SqueezeBertForMaskedLM extends SqueezeBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\nexport class SqueezeBertForSequenceClassification extends SqueezeBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\nexport class SqueezeBertForQuestionAnswering extends SqueezeBertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Albert models\nexport class AlbertPreTrainedModel extends PreTrainedModel { }\nexport class AlbertModel extends AlbertPreTrainedModel { }\nexport class AlbertForSequenceClassification extends AlbertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\nexport class AlbertForQuestionAnswering extends AlbertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\nexport class AlbertForMaskedLM extends AlbertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// T5 models\nexport class T5PreTrainedModel extends PreTrainedModel {\n forward_params = [\n 'input_ids',\n 'attention_mask',\n 'encoder_outputs',\n 'decoder_input_ids',\n 'decoder_attention_mask',\n 'past_key_values',\n ];\n};\n\nexport class T5Model extends T5PreTrainedModel { }\n\n/**\n * T5Model is a class representing a T5 model for conditional generation.\n */\nexport class T5ForConditionalGeneration extends T5PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// LONGT5 models\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class LongT5PreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare LONGT5 Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class LongT5Model extends LongT5PreTrainedModel { }\n\n/**\n * LONGT5 Model with a `language modeling` head on top.\n */\nexport class LongT5ForConditionalGeneration extends LongT5PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// MT5 models\nexport class MT5PreTrainedModel extends PreTrainedModel { };\n\nexport class MT5Model extends MT5PreTrainedModel { }\n\n/**\n * A class representing a conditional sequence-to-sequence model based on the MT5 architecture.\n */\nexport class MT5ForConditionalGeneration extends MT5PreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Bart models\nexport class BartPretrainedModel extends PreTrainedModel { };\n\n/**\n * The bare BART Model outputting raw hidden-states without any specific head on top.\n */\nexport class BartModel extends BartPretrainedModel { }\n\n/**\n * The BART Model with a language modeling head. Can be used for summarization.\n */\nexport class BartForConditionalGeneration extends BartPretrainedModel { }\n\n/**\n * Bart model with a sequence classification/head on top (a linear layer on top of the pooled output)\n */\nexport class BartForSequenceClassification extends BartPretrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MBart models\nexport class MBartPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare MBART Model outputting raw hidden-states without any specific head on top.\n */\nexport class MBartModel extends MBartPreTrainedModel { }\n\n/**\n * The MBART Model with a language modeling head. Can be used for summarization, after fine-tuning the pretrained models.\n */\nexport class MBartForConditionalGeneration extends MBartPreTrainedModel { }\n\n/**\n * MBart model with a sequence classification/head on top (a linear layer on top of the pooled output).\n */\nexport class MBartForSequenceClassification extends MBartPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n\nexport class MBartForCausalLM extends MBartPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Blenderbot models\nexport class BlenderbotPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare Blenderbot Model outputting raw hidden-states without any specific head on top.\n */\nexport class BlenderbotModel extends BlenderbotPreTrainedModel { }\n\n/**\n * The Blenderbot Model with a language modeling head. Can be used for summarization.\n */\nexport class BlenderbotForConditionalGeneration extends BlenderbotPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Blenderbot models\nexport class BlenderbotSmallPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare BlenderbotSmall Model outputting raw hidden-states without any specific head on top.\n */\nexport class BlenderbotSmallModel extends BlenderbotSmallPreTrainedModel { }\n\n/**\n * The BlenderbotSmall Model with a language modeling head. Can be used for summarization.\n */\nexport class BlenderbotSmallForConditionalGeneration extends BlenderbotSmallPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Roberta models\nexport class RobertaPreTrainedModel extends PreTrainedModel { }\nexport class RobertaModel extends RobertaPreTrainedModel { }\n\n/**\n * RobertaForMaskedLM class for performing masked language modeling on Roberta models.\n */\nexport class RobertaForMaskedLM extends RobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RobertaForSequenceClassification class for performing sequence classification on Roberta models.\n */\nexport class RobertaForSequenceClassification extends RobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RobertaForTokenClassification class for performing token classification on Roberta models.\n */\nexport class RobertaForTokenClassification extends RobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * RobertaForQuestionAnswering class for performing question answering on Roberta models.\n */\nexport class RobertaForQuestionAnswering extends RobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// XLM models\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class XLMPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare XLM Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class XLMModel extends XLMPreTrainedModel { }\n\n/**\n * The XLM Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class XLMWithLMHeadModel extends XLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLM Model with a sequence classification/regression head on top (a linear layer on top of the pooled output)\n */\nexport class XLMForSequenceClassification extends XLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLM Model with a token classification head on top (a linear layer on top of the hidden-states output)\n */\nexport class XLMForTokenClassification extends XLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLM Model with a span classification head on top for extractive question-answering tasks\n */\nexport class XLMForQuestionAnswering extends XLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// XLMRoberta models\nexport class XLMRobertaPreTrainedModel extends PreTrainedModel { }\nexport class XLMRobertaModel extends XLMRobertaPreTrainedModel { }\n\n/**\n * XLMRobertaForMaskedLM class for performing masked language modeling on XLMRoberta models.\n */\nexport class XLMRobertaForMaskedLM extends XLMRobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new MaskedLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLMRobertaForSequenceClassification class for performing sequence classification on XLMRoberta models.\n */\nexport class XLMRobertaForSequenceClassification extends XLMRobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLMRobertaForTokenClassification class for performing token classification on XLMRoberta models.\n */\nexport class XLMRobertaForTokenClassification extends XLMRobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for token classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * XLMRobertaForQuestionAnswering class for performing question answering on XLMRoberta models.\n */\nexport class XLMRobertaForQuestionAnswering extends XLMRobertaPreTrainedModel {\n /**\n * Calls the model on new inputs.\n *\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} returned object\n */\n async _call(model_inputs) {\n return new QuestionAnsweringModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Audio Spectrogram Transformer (AST) models\nexport class ASTPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare AST Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class ASTModel extends ASTPreTrainedModel { }\n\n/**\n * Audio Spectrogram Transformer model with an audio classification head on top\n * (a linear layer on top of the pooled output) e.g. for datasets like AudioSet, Speech Commands v2.\n */\nexport class ASTForAudioClassification extends ASTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Whisper models\nexport class WhisperPreTrainedModel extends PreTrainedModel {\n\n requires_attention_mask = false;\n main_input_name = 'input_features';\n forward_params = [\n 'input_features',\n 'attention_mask',\n 'decoder_input_ids',\n 'decoder_attention_mask',\n 'past_key_values',\n ];\n};\n\n/**\n * WhisperModel class for training Whisper models without a language model head.\n */\nexport class WhisperModel extends WhisperPreTrainedModel { }\n\n\n/**\n * WhisperForConditionalGeneration class for generating conditional outputs from Whisper models.\n */\nexport class WhisperForConditionalGeneration extends WhisperPreTrainedModel {\n\n _prepare_generation_config(generation_config, kwargs) {\n return /** @type {WhisperGenerationConfig} */ (super._prepare_generation_config(generation_config, kwargs, WhisperGenerationConfig));\n }\n\n /**\n * \n * @param {WhisperGenerationConfig} generation_config \n */\n _retrieve_init_tokens(generation_config) {\n // prefix tokens are of the form: \n // - Multilingual: <|startoftranscript|> <|lang_id|> <|task|> [<|notimestamps|>]\n // - English-only: <|startoftranscript|> [<|notimestamps|>]\n\n // 1. Handle <|startoftranscript|> token\n const init_tokens = [generation_config.decoder_start_token_id];\n\n // 2. Handle <|lang_id|> and <|task> tokens\n let language = generation_config.language;\n const task = generation_config.task;\n if (generation_config.is_multilingual) {\n if (!language) {\n // TODO: Implement language detection\n console.warn('No language specified - defaulting to English (en).');\n language = 'en';\n }\n\n // Add language token\n const language_code = whisper_language_to_code(language);\n const language_token = `<|${language_code}|>`;\n init_tokens.push(generation_config.lang_to_id[language_token])\n\n // Add task token\n // NOTE: Defaults to 'transcribe' if no task is specified\n init_tokens.push(generation_config.task_to_id[task ?? 'transcribe']);\n\n } else if (language || task) {\n throw new Error(\n \"Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.\"\n )\n }\n\n // 3. Handle <|notimestamps|> token\n if (\n !generation_config.return_timestamps\n && generation_config.no_timestamps_token_id\n && init_tokens.at(-1) !== generation_config.no_timestamps_token_id\n ) {\n init_tokens.push(generation_config.no_timestamps_token_id);\n } else if (\n generation_config.return_timestamps\n &&\n init_tokens.at(-1) === generation_config.no_timestamps_token_id\n ) {\n console.warn(\"<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`.\");\n init_tokens.pop();\n }\n\n // let's make sure we don't pass `null` tokens as prompt tokens\n return init_tokens.filter(token => token != null);\n }\n\n /**\n * Transcribes or translates log-mel input features to a sequence of auto-regressively generated token ids.\n * @param {import('./models/whisper/generation_whisper.js').WhisperGenerationFunctionParameters} options\n * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores.\n */\n async generate({\n inputs = null,\n generation_config = null,\n logits_processor = null,\n stopping_criteria = null,\n\n // Whisper-specific options (passed to kwargs)\n // prompt_ids = null,\n // language = null,\n // task = null,\n\n ...kwargs\n }) {\n generation_config = this._prepare_generation_config(generation_config, kwargs);\n\n const init_tokens = kwargs.decoder_input_ids ?? this._retrieve_init_tokens(generation_config);\n\n if (generation_config.return_timestamps) {\n logits_processor ??= new LogitsProcessorList();\n logits_processor.push(\n new WhisperTimeStampLogitsProcessor(generation_config, init_tokens)\n );\n }\n\n if (generation_config.begin_suppress_tokens) {\n logits_processor ??= new LogitsProcessorList();\n logits_processor.push(\n new SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, init_tokens.length)\n );\n }\n\n if (generation_config.return_token_timestamps) {\n if (!generation_config.alignment_heads) {\n throw new Error(\n \"Model generation config has no `alignment_heads`, token-level timestamps not available. \" +\n \"See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.\"\n )\n }\n\n if (generation_config.task === 'translate') {\n console.warn(\"Token-level timestamps may not be reliable for task 'translate'.\")\n }\n\n generation_config.output_attentions = true;\n generation_config.return_dict_in_generate = true;\n }\n\n const outputs = await super.generate({\n inputs,\n generation_config,\n logits_processor,\n decoder_input_ids: init_tokens,\n ...kwargs\n });\n\n if (generation_config.return_token_timestamps) {\n outputs[\"token_timestamps\"] = this._extract_token_timestamps(\n outputs,\n generation_config.alignment_heads,\n generation_config.num_frames,\n );\n }\n\n return outputs;\n }\n\n /**\n * Calculates token-level timestamps using the encoder-decoder cross-attentions and\n * dynamic time-warping (DTW) to map each output token to a position in the input audio.\n * If `num_frames` is specified, the encoder-decoder cross-attentions will be cropped before applying DTW.\n * @param {Object} generate_outputs Outputs generated by the model\n * @param {Tensor[][]} generate_outputs.cross_attentions The cross attentions output by the model\n * @param {Tensor} generate_outputs.sequences The sequences output by the model\n * @param {number[][]} alignment_heads Alignment heads of the model\n * @param {number} [num_frames=null] Number of frames in the input audio.\n * @param {number} [time_precision=0.02] Precision of the timestamps in seconds\n * @returns {Tensor} tensor containing the timestamps in seconds for each predicted token\n */\n _extract_token_timestamps(generate_outputs, alignment_heads, num_frames = null, time_precision = 0.02) {\n if (!generate_outputs.cross_attentions) {\n throw new Error(\n \"Model outputs must contain cross attentions to extract timestamps. \" +\n \"This is most likely because the model was not exported with `output_attentions=True`.\"\n )\n }\n if (num_frames == null) {\n console.warn(\n \"`num_frames` has not been set, meaning the entire audio will be analyzed. \" +\n \"This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).\"\n );\n }\n\n let median_filter_width = this.config.median_filter_width;\n if (median_filter_width === undefined) {\n console.warn(\"Model config has no `median_filter_width`, using default value of 7.\")\n median_filter_width = 7;\n }\n\n // TODO: Improve batch processing\n const batch = generate_outputs.cross_attentions;\n // Create a list with `decoder_layers` elements, each a tensor of shape\n // (batch size, attention_heads, output length, input length).\n const cross_attentions = Array.from({ length: this.config.decoder_layers },\n // Concatenate the cross attentions for each layer across sequence length dimension.\n (_, i) => cat(batch.map(x => x[i]), 2)\n );\n\n const weights = stack(alignment_heads.map(([l, h]) => {\n if (l >= cross_attentions.length) {\n throw new Error(`Layer index ${l} is out of bounds for cross attentions (length ${cross_attentions.length}).`)\n }\n return num_frames\n ? cross_attentions[l].slice(null, h, null, [0, num_frames])\n : cross_attentions[l].slice(null, h);\n })).transpose(1, 0, 2, 3);\n\n const [std, calculatedMean] = std_mean(weights, -2, 0, true);\n\n // Normalize and smoothen the weights.\n const smoothedWeights = weights.clone(); // [1, 8, seqLength, 1500]\n\n for (let a = 0; a < smoothedWeights.dims[0]; ++a) {\n const aTensor = smoothedWeights[a]; // [8, seqLength, 1500]\n\n for (let b = 0; b < aTensor.dims[0]; ++b) {\n const bTensor = aTensor[b]; // [seqLength, 1500]\n\n const stdTensorData = std[a][b][0].data; // [1500]\n const meanTensorData = calculatedMean[a][b][0].data; // [1500]\n\n for (let c = 0; c < bTensor.dims[0]; ++c) {\n\n let cTensorData = bTensor[c].data; // [1500]\n for (let d = 0; d < cTensorData.length; ++d) {\n cTensorData[d] = (cTensorData[d] - meanTensorData[d]) / stdTensorData[d]\n }\n\n // Apply median filter.\n cTensorData.set(medianFilter(cTensorData, median_filter_width))\n }\n }\n }\n\n // Average the different cross-attention heads.\n const batchedMatrices = [mean(smoothedWeights, 1)];\n\n const timestampsShape = generate_outputs.sequences.dims;\n\n const timestamps = new Tensor(\n 'float32',\n new Float32Array(timestampsShape[0] * timestampsShape[1]),\n timestampsShape\n );\n\n // Perform dynamic time warping on each element of the batch.\n for (let batch_idx = 0; batch_idx < timestampsShape[0]; ++batch_idx) {\n // NOTE: Since we run only one batch at a time, we can squeeze to get the same dimensions\n // as the python implementation\n const matrix = batchedMatrices[batch_idx].neg().squeeze_(0);\n const [text_indices, time_indices] = dynamic_time_warping(matrix.tolist());\n\n const diffs = Array.from({ length: text_indices.length - 1 }, (v, i) => text_indices[i + 1] - text_indices[i]);\n const jumps = mergeArrays([1], diffs).map(x => !!x); // convert to boolean\n\n const jump_times = [];\n for (let i = 0; i < jumps.length; ++i) {\n if (jumps[i]) {\n // NOTE: No point in rounding here, since we set to Float32Array later\n jump_times.push(time_indices[i] * time_precision);\n }\n }\n timestamps[batch_idx].data.set(jump_times, 1)\n }\n\n return timestamps;\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n/**\n * Vision Encoder-Decoder model based on OpenAI's GPT architecture for image captioning and other vision tasks\n */\nexport class VisionEncoderDecoderModel extends PreTrainedModel {\n main_input_name = 'pixel_values';\n forward_params = [\n 'pixel_values',\n 'input_ids',\n 'encoder_hidden_states',\n 'past_key_values',\n ];\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// LLaVa Models\nexport class LlavaPreTrainedModel extends PreTrainedModel {\n forward_params = [\n 'input_ids',\n 'pixel_values',\n 'attention_mask',\n 'position_ids',\n 'past_key_values',\n ];\n}\n\n/**\n * The LLAVA model which consists of a vision backbone and a language model.\n */\nexport class LlavaForConditionalGeneration extends LlavaPreTrainedModel {\n\n _merge_input_ids_with_image_features({\n inputs_embeds,\n image_features,\n input_ids,\n attention_mask,\n }) {\n\n const image_token_index = this.config.image_token_index;\n\n const idsList = input_ids.tolist();\n\n // NOTE: we use .findIndex instead of .indexOf to perform weak comparison (==) between BigInt and Number\n const indexOfImage = idsList.map(x => x.findIndex(x => x == image_token_index));\n\n const noImages = indexOfImage.every(x => x === -1);\n const allImages = indexOfImage.every(x => x !== -1);\n if (!noImages && !allImages) {\n // Check for padding reasons\n throw new Error('Every input should contain either 0 or 1 image token.');\n }\n\n if (noImages) {\n return {\n inputs_embeds,\n attention_mask,\n }\n }\n\n const stacked = [];\n const stacked_attention_mask = [];\n for (let i = 0; i < indexOfImage.length; ++i) {\n const index = indexOfImage[i];\n\n const e = inputs_embeds[i];\n const im = image_features[i];\n const am = attention_mask[i];\n stacked.push(\n cat([\n e.slice([0, index]),\n im,\n e.slice([index + 1, e.dims[0]]),\n ], 0)\n );\n\n stacked_attention_mask.push(\n cat([\n am.slice([0, index]),\n ones([im.dims[0]]),\n am.slice([index + 1, am.dims[0]])\n ], 0)\n )\n }\n\n return {\n inputs_embeds: stack(stacked, 0),\n attention_mask: stack(stacked_attention_mask, 0),\n }\n }\n}\n//////////////////////////////////////////////////\n\nexport class Moondream1ForConditionalGeneration extends LlavaForConditionalGeneration { } // NOTE: extends LlavaForConditionalGeneration\n\nexport class Florence2PreTrainedModel extends PreTrainedModel {\n forward_params = [\n // Encoder inputs\n 'input_ids',\n 'inputs_embeds',\n 'attention_mask',\n 'pixel_values',\n\n // Decoder inputs\n 'encoder_outputs',\n 'decoder_input_ids',\n 'decoder_inputs_embeds',\n 'decoder_attention_mask',\n 'past_key_values',\n ];\n main_input_name = 'inputs_embeds';\n}\n\nexport class Florence2ForConditionalGeneration extends Florence2PreTrainedModel {\n\n _merge_input_ids_with_image_features({\n inputs_embeds,\n image_features,\n input_ids,\n attention_mask,\n }) {\n return {\n inputs_embeds: cat([\n image_features, // image embeds\n inputs_embeds, // task prefix embeds\n ], 1),\n attention_mask: cat([\n ones(image_features.dims.slice(0, 2)), // image attention mask\n attention_mask, // task prefix attention mask\n ], 1),\n }\n }\n\n async _prepare_inputs_embeds({ input_ids, pixel_values, inputs_embeds, attention_mask }) {\n if (!input_ids && !pixel_values) {\n throw new Error('Either `input_ids` or `pixel_values` should be provided.');\n }\n\n // 1. Possibly, extract the input embeddings\n let text_features, image_features;\n if (input_ids) {\n text_features = await this.encode_text({ input_ids });\n }\n if (pixel_values) {\n image_features = await this.encode_image({ pixel_values });\n }\n\n // 2. Possibly, merge text and images\n if (text_features && image_features) {\n ({ inputs_embeds, attention_mask } = this._merge_input_ids_with_image_features({\n inputs_embeds: text_features,\n image_features,\n input_ids,\n attention_mask,\n }));\n } else {\n inputs_embeds = text_features || image_features;\n }\n\n return { inputs_embeds, attention_mask };\n }\n\n async forward({\n input_ids,\n pixel_values,\n attention_mask,\n decoder_input_ids,\n decoder_attention_mask,\n encoder_outputs,\n past_key_values,\n\n inputs_embeds,\n decoder_inputs_embeds,\n }) {\n if (!inputs_embeds) {\n ({ inputs_embeds, attention_mask } = await this._prepare_inputs_embeds({ input_ids, pixel_values, inputs_embeds, attention_mask }));\n }\n\n if (!encoder_outputs) {\n // Must compute encoder outputs\n let { last_hidden_state } = await encoderForward(this, { inputs_embeds, attention_mask });\n encoder_outputs = last_hidden_state;\n }\n\n if (!decoder_inputs_embeds) {\n if (!decoder_input_ids) {\n throw new Error('Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.');\n }\n decoder_inputs_embeds = await this.encode_text({ input_ids: decoder_input_ids });\n }\n\n const decoderFeeds = {\n inputs_embeds: decoder_inputs_embeds,\n attention_mask: decoder_attention_mask,\n encoder_attention_mask: attention_mask,\n encoder_hidden_states: encoder_outputs,\n past_key_values,\n };\n const decoder_outputs = await decoderForward(this, decoderFeeds, true);\n return decoder_outputs;\n }\n}\nexport class CLIPPreTrainedModel extends PreTrainedModel { }\n\n/**\n * CLIP Text and Vision Model with a projection layers on top\n * \n * **Example:** Perform zero-shot image classification with a `CLIPModel`.\n * \n * ```javascript\n * import { AutoTokenizer, AutoProcessor, CLIPModel, RawImage } from '@huggingface/transformers';\n * \n * // Load tokenizer, processor, and model\n * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/clip-vit-base-patch16');\n * let processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16');\n * let model = await CLIPModel.from_pretrained('Xenova/clip-vit-base-patch16');\n * \n * // Run tokenization\n * let texts = ['a photo of a car', 'a photo of a football match']\n * let text_inputs = tokenizer(texts, { padding: true, truncation: true });\n * \n * // Read image and run processor\n * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * let image_inputs = await processor(image);\n * \n * // Run model with both text and pixel inputs\n * let output = await model({ ...text_inputs, ...image_inputs });\n * // {\n * // logits_per_image: Tensor {\n * // dims: [ 1, 2 ],\n * // data: Float32Array(2) [ 18.579734802246094, 24.31830596923828 ],\n * // },\n * // logits_per_text: Tensor {\n * // dims: [ 2, 1 ],\n * // data: Float32Array(2) [ 18.579734802246094, 24.31830596923828 ],\n * // },\n * // text_embeds: Tensor {\n * // dims: [ 2, 512 ],\n * // data: Float32Array(1024) [ ... ],\n * // },\n * // image_embeds: Tensor {\n * // dims: [ 1, 512 ],\n * // data: Float32Array(512) [ ... ],\n * // }\n * // }\n * ```\n */\nexport class CLIPModel extends CLIPPreTrainedModel { }\n\n/**\n * The text model from CLIP without any head or projection on top.\n */\nexport class CLIPTextModel extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'text_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * CLIP Text Model with a projection layer on top (a linear layer on top of the pooled output)\n * \n * **Example:** Compute text embeddings with `CLIPTextModelWithProjection`.\n * \n * ```javascript\n * import { AutoTokenizer, CLIPTextModelWithProjection } from '@huggingface/transformers';\n * \n * // Load tokenizer and text model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clip-vit-base-patch16');\n * const text_model = await CLIPTextModelWithProjection.from_pretrained('Xenova/clip-vit-base-patch16');\n * \n * // Run tokenization\n * let texts = ['a photo of a car', 'a photo of a football match'];\n * let text_inputs = tokenizer(texts, { padding: true, truncation: true });\n * \n * // Compute embeddings\n * const { text_embeds } = await text_model(text_inputs);\n * // Tensor {\n * // dims: [ 2, 512 ],\n * // type: 'float32',\n * // data: Float32Array(1024) [ ... ],\n * // size: 1024\n * // }\n * ```\n */\nexport class CLIPTextModelWithProjection extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'text_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * The vision model from CLIP without any head or projection on top.\n */\nexport class CLIPVisionModel extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'vision_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * CLIP Vision Model with a projection layer on top (a linear layer on top of the pooled output)\n * \n * **Example:** Compute vision embeddings with `CLIPVisionModelWithProjection`.\n * \n * ```javascript\n * import { AutoProcessor, CLIPVisionModelWithProjection, RawImage} from '@huggingface/transformers';\n * \n * // Load processor and vision model\n * const processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16');\n * const vision_model = await CLIPVisionModelWithProjection.from_pretrained('Xenova/clip-vit-base-patch16');\n * \n * // Read image and run processor\n * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * let image_inputs = await processor(image);\n * \n * // Compute embeddings\n * const { image_embeds } = await vision_model(image_inputs);\n * // Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [ ... ],\n * // size: 512\n * // }\n * ```\n */\nexport class CLIPVisionModelWithProjection extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'vision_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// SigLIP models\nexport class SiglipPreTrainedModel extends PreTrainedModel { }\n\n/**\n * SigLIP Text and Vision Model with a projection layers on top\n * \n * **Example:** Perform zero-shot image classification with a `SiglipModel`.\n * \n * ```javascript\n * import { AutoTokenizer, AutoProcessor, SiglipModel, RawImage } from '@huggingface/transformers';\n * \n * // Load tokenizer, processor, and model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/siglip-base-patch16-224');\n * const processor = await AutoProcessor.from_pretrained('Xenova/siglip-base-patch16-224');\n * const model = await SiglipModel.from_pretrained('Xenova/siglip-base-patch16-224');\n * \n * // Run tokenization\n * const texts = ['a photo of 2 cats', 'a photo of 2 dogs'];\n * const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true });\n * \n * // Read image and run processor\n * const image = await RawImage.read('http://images.cocodataset.org/val2017/000000039769.jpg');\n * const image_inputs = await processor(image);\n * \n * // Run model with both text and pixel inputs\n * const output = await model({ ...text_inputs, ...image_inputs });\n * // {\n * // logits_per_image: Tensor {\n * // dims: [ 1, 2 ],\n * // data: Float32Array(2) [ -1.6019744873046875, -10.720091819763184 ],\n * // },\n * // logits_per_text: Tensor {\n * // dims: [ 2, 1 ],\n * // data: Float32Array(2) [ -1.6019744873046875, -10.720091819763184 ],\n * // },\n * // text_embeds: Tensor {\n * // dims: [ 2, 768 ],\n * // data: Float32Array(1536) [ ... ],\n * // },\n * // image_embeds: Tensor {\n * // dims: [ 1, 768 ],\n * // data: Float32Array(768) [ ... ],\n * // }\n * // }\n * ```\n */\nexport class SiglipModel extends SiglipPreTrainedModel { }\n\n/**\n * The text model from SigLIP without any head or projection on top.\n * \n * **Example:** Compute text embeddings with `SiglipTextModel`.\n * \n * ```javascript\n * import { AutoTokenizer, SiglipTextModel } from '@huggingface/transformers';\n * \n * // Load tokenizer and text model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/siglip-base-patch16-224');\n * const text_model = await SiglipTextModel.from_pretrained('Xenova/siglip-base-patch16-224');\n * \n * // Run tokenization\n * const texts = ['a photo of 2 cats', 'a photo of 2 dogs'];\n * const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true });\n * \n * // Compute embeddings\n * const { pooler_output } = await text_model(text_inputs);\n * // Tensor {\n * // dims: [ 2, 768 ],\n * // type: 'float32',\n * // data: Float32Array(1536) [ ... ],\n * // size: 1536\n * // }\n * ```\n */\nexport class SiglipTextModel extends SiglipPreTrainedModel {\n\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'text_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * The vision model from SigLIP without any head or projection on top.\n * \n * **Example:** Compute vision embeddings with `SiglipVisionModel`.\n * \n * ```javascript\n * import { AutoProcessor, SiglipVisionModel, RawImage} from '@huggingface/transformers';\n * \n * // Load processor and vision model\n * const processor = await AutoProcessor.from_pretrained('Xenova/siglip-base-patch16-224');\n * const vision_model = await SiglipVisionModel.from_pretrained('Xenova/siglip-base-patch16-224');\n * \n * // Read image and run processor\n * const image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * const image_inputs = await processor(image);\n * \n * // Compute embeddings\n * const { pooler_output } = await vision_model(image_inputs);\n * // Tensor {\n * // dims: [ 1, 768 ],\n * // type: 'float32',\n * // data: Float32Array(768) [ ... ],\n * // size: 768\n * // }\n * ```\n */\nexport class SiglipVisionModel extends CLIPPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'vision_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n//////////////////////////////////////////////////\n// ChineseCLIP models\nexport class ChineseCLIPPreTrainedModel extends PreTrainedModel { }\n\nexport class ChineseCLIPModel extends ChineseCLIPPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// CLIPSeg models\nexport class CLIPSegPreTrainedModel extends PreTrainedModel { }\n\nexport class CLIPSegModel extends CLIPSegPreTrainedModel { }\n\n/**\n * CLIPSeg model with a Transformer-based decoder on top for zero-shot and one-shot image segmentation.\n * \n * **Example:** Perform zero-shot image segmentation with a `CLIPSegForImageSegmentation` model.\n * \n * ```javascript\n * import { AutoTokenizer, AutoProcessor, CLIPSegForImageSegmentation, RawImage } from '@huggingface/transformers';\n * \n * // Load tokenizer, processor, and model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clipseg-rd64-refined');\n * const processor = await AutoProcessor.from_pretrained('Xenova/clipseg-rd64-refined');\n * const model = await CLIPSegForImageSegmentation.from_pretrained('Xenova/clipseg-rd64-refined');\n * \n * // Run tokenization\n * const texts = ['a glass', 'something to fill', 'wood', 'a jar'];\n * const text_inputs = tokenizer(texts, { padding: true, truncation: true });\n * \n * // Read image and run processor\n * const image = await RawImage.read('https://github.com/timojl/clipseg/blob/master/example_image.jpg?raw=true');\n * const image_inputs = await processor(image);\n * \n * // Run model with both text and pixel inputs\n * const { logits } = await model({ ...text_inputs, ...image_inputs });\n * // logits: Tensor {\n * // dims: [4, 352, 352],\n * // type: 'float32',\n * // data: Float32Array(495616) [ ... ],\n * // size: 495616\n * // }\n * ```\n * \n * You can visualize the predictions as follows:\n * ```javascript\n * const preds = logits\n * .unsqueeze_(1)\n * .sigmoid_()\n * .mul_(255)\n * .round_()\n * .to('uint8');\n * \n * for (let i = 0; i < preds.dims[0]; ++i) {\n * const img = RawImage.fromTensor(preds[i]);\n * img.save(`prediction_${i}.png`);\n * }\n * ```\n */\nexport class CLIPSegForImageSegmentation extends CLIPSegPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// GPT2 models\nexport class GPT2PreTrainedModel extends PreTrainedModel { }\n\nexport class GPT2Model extends GPT2PreTrainedModel { }\n\n/**\n * GPT-2 language model head on top of the GPT-2 base model. This model is suitable for text generation tasks.\n */\nexport class GPT2LMHeadModel extends GPT2PreTrainedModel { }\n// export class GPT2ForSequenceClassification extends GPT2PreTrainedModel {\n// TODO\n// }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// JAIS models\nexport class JAISPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare JAIS Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class JAISModel extends JAISPreTrainedModel { }\n\n/**\n * The JAIS Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class JAISLMHeadModel extends JAISPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// GPTNeo models\nexport class GPTNeoPreTrainedModel extends PreTrainedModel { }\nexport class GPTNeoModel extends GPTNeoPreTrainedModel { }\n\nexport class GPTNeoForCausalLM extends GPTNeoPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// GPTNeoX models\nexport class GPTNeoXPreTrainedModel extends PreTrainedModel { }\nexport class GPTNeoXModel extends GPTNeoXPreTrainedModel { }\n\nexport class GPTNeoXForCausalLM extends GPTNeoXPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// GPT-J models\nexport class GPTJPreTrainedModel extends PreTrainedModel { }\n\nexport class GPTJModel extends GPTJPreTrainedModel { }\n\nexport class GPTJForCausalLM extends GPTJPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// GPTBigCode models\nexport class GPTBigCodePreTrainedModel extends PreTrainedModel { }\n\nexport class GPTBigCodeModel extends GPTBigCodePreTrainedModel { }\n\nexport class GPTBigCodeForCausalLM extends GPTBigCodePreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// CodeGen models\nexport class CodeGenPreTrainedModel extends PreTrainedModel { }\n/**\n * CodeGenModel is a class representing a code generation model without a language model head.\n */\nexport class CodeGenModel extends CodeGenPreTrainedModel { }\n\n/**\n * CodeGenForCausalLM is a class that represents a code generation model based on the GPT-2 architecture. It extends the `CodeGenPreTrainedModel` class.\n */\nexport class CodeGenForCausalLM extends CodeGenPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// LLama models\n\n/**\n * The bare LLama Model outputting raw hidden-states without any specific head on top.\n */\nexport class LlamaPreTrainedModel extends PreTrainedModel { }\n/**\n * The bare LLaMA Model outputting raw hidden-states without any specific head on top.\n */\nexport class LlamaModel extends LlamaPreTrainedModel { }\n\nexport class LlamaForCausalLM extends LlamaPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Granite models\nexport class GranitePreTrainedModel extends PreTrainedModel { }\nexport class GraniteModel extends GranitePreTrainedModel { }\nexport class GraniteForCausalLM extends GranitePreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Cohere models\n\n/**\n * The bare Cohere Model outputting raw hidden-states without any specific head on top.\n */\nexport class CoherePreTrainedModel extends PreTrainedModel { }\nexport class CohereModel extends CoherePreTrainedModel { }\n\nexport class CohereForCausalLM extends CoherePreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Gemma models\n\n/**\n * The bare Gemma Model outputting raw hidden-states without any specific head on top.\n */\nexport class GemmaPreTrainedModel extends PreTrainedModel { }\n/**\n * The bare Gemma Model outputting raw hidden-states without any specific head on top.\n */\nexport class GemmaModel extends GemmaPreTrainedModel { }\n\nexport class GemmaForCausalLM extends GemmaPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Gemma2 models\n\n/**\n * The bare Gemma2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Gemma2PreTrainedModel extends PreTrainedModel { }\n/**\n * The bare Gemma2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Gemma2Model extends Gemma2PreTrainedModel { }\n\nexport class Gemma2ForCausalLM extends Gemma2PreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class OpenELMPreTrainedModel extends PreTrainedModel { }\nexport class OpenELMModel extends OpenELMPreTrainedModel { }\n\nexport class OpenELMForCausalLM extends OpenELMPreTrainedModel { }\n\n\n//////////////////////////////////////////////////\n// Qwen2 models\n\n/**\n * The bare Qwen2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Qwen2PreTrainedModel extends PreTrainedModel { }\n/**\n * The bare Qwen2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Qwen2Model extends Qwen2PreTrainedModel { }\n\nexport class Qwen2ForCausalLM extends Qwen2PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Phi models\nexport class PhiPreTrainedModel extends PreTrainedModel { }\n/**\n * The bare Phi Model outputting raw hidden-states without any specific head on top.\n */\nexport class PhiModel extends PhiPreTrainedModel { }\n\nexport class PhiForCausalLM extends PhiPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Phi3 models\nexport class Phi3PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Phi3 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Phi3Model extends Phi3PreTrainedModel { }\n\nexport class Phi3ForCausalLM extends Phi3PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Bloom models\n/**\n * The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class BloomPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Bloom Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class BloomModel extends BloomPreTrainedModel { }\n\n/**\n * The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class BloomForCausalLM extends BloomPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MPT models\nexport class MptPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Mpt Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class MptModel extends MptPreTrainedModel { }\n\n/**\n * The MPT Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class MptForCausalLM extends MptPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// OPT models\nexport class OPTPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare OPT Model outputting raw hidden-states without any specific head on top.\n */\nexport class OPTModel extends OPTPreTrainedModel { }\n\n/**\n * The OPT Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).\n */\nexport class OPTForCausalLM extends OPTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class ViTPreTrainedModel extends PreTrainedModel { }\nexport class ViTModel extends ViTPreTrainedModel { }\nexport class ViTForImageClassification extends ViTPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class PvtPreTrainedModel extends PreTrainedModel { }\nexport class PvtModel extends PvtPreTrainedModel { }\nexport class PvtForImageClassification extends PvtPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class ViTMAEPreTrainedModel extends PreTrainedModel { }\nexport class ViTMAEModel extends ViTMAEPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class ViTMSNPreTrainedModel extends PreTrainedModel { }\nexport class ViTMSNModel extends ViTMSNPreTrainedModel { }\nexport class ViTMSNForImageClassification extends ViTMSNPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class GroupViTPreTrainedModel extends PreTrainedModel { }\nexport class GroupViTModel extends GroupViTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class FastViTPreTrainedModel extends PreTrainedModel { }\nexport class FastViTModel extends FastViTPreTrainedModel { }\nexport class FastViTForImageClassification extends FastViTPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class VitMattePreTrainedModel extends PreTrainedModel { }\n\n/**\n * ViTMatte framework leveraging any vision backbone e.g. for ADE20k, CityScapes.\n * \n * **Example:** Perform image matting with a `VitMatteForImageMatting` model.\n * ```javascript\n * import { AutoProcessor, VitMatteForImageMatting, RawImage } from '@huggingface/transformers';\n * \n * // Load processor and model\n * const processor = await AutoProcessor.from_pretrained('Xenova/vitmatte-small-distinctions-646');\n * const model = await VitMatteForImageMatting.from_pretrained('Xenova/vitmatte-small-distinctions-646');\n * \n * // Load image and trimap\n * const image = await RawImage.fromURL('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/vitmatte_image.png');\n * const trimap = await RawImage.fromURL('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/vitmatte_trimap.png');\n * \n * // Prepare image + trimap for the model\n * const inputs = await processor(image, trimap);\n * \n * // Predict alpha matte\n * const { alphas } = await model(inputs);\n * // Tensor {\n * // dims: [ 1, 1, 640, 960 ],\n * // type: 'float32',\n * // size: 614400,\n * // data: Float32Array(614400) [ 0.9894027709960938, 0.9970508813858032, ... ]\n * // }\n * ```\n * \n * You can visualize the alpha matte as follows:\n * ```javascript\n * import { Tensor, cat } from '@huggingface/transformers';\n * \n * // Visualize predicted alpha matte\n * const imageTensor = image.toTensor();\n * \n * // Convert float (0-1) alpha matte to uint8 (0-255)\n * const alphaChannel = alphas\n * .squeeze(0)\n * .mul_(255)\n * .clamp_(0, 255)\n * .round_()\n * .to('uint8');\n * \n * // Concatenate original image with predicted alpha\n * const imageData = cat([imageTensor, alphaChannel], 0);\n * \n * // Save output image\n * const outputImage = RawImage.fromTensor(imageData);\n * outputImage.save('output.png');\n * ```\n */\nexport class VitMatteForImageMatting extends VitMattePreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new ImageMattingOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class MobileViTPreTrainedModel extends PreTrainedModel { }\nexport class MobileViTModel extends MobileViTPreTrainedModel { }\nexport class MobileViTForImageClassification extends MobileViTPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n// TODO: MobileViTForSemanticSegmentation\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class MobileViTV2PreTrainedModel extends PreTrainedModel { }\nexport class MobileViTV2Model extends MobileViTV2PreTrainedModel { }\nexport class MobileViTV2ForImageClassification extends MobileViTV2PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n// TODO: MobileViTV2ForSemanticSegmentation\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class OwlViTPreTrainedModel extends PreTrainedModel { }\nexport class OwlViTModel extends OwlViTPreTrainedModel { }\nexport class OwlViTForObjectDetection extends OwlViTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class Owlv2PreTrainedModel extends PreTrainedModel { }\nexport class Owlv2Model extends Owlv2PreTrainedModel { }\nexport class Owlv2ForObjectDetection extends Owlv2PreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Beit Models\nexport class BeitPreTrainedModel extends PreTrainedModel { }\nexport class BeitModel extends BeitPreTrainedModel { }\nexport class BeitForImageClassification extends BeitPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class DetrPreTrainedModel extends PreTrainedModel { }\nexport class DetrModel extends DetrPreTrainedModel { }\nexport class DetrForObjectDetection extends DetrPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new DetrObjectDetectionOutput(await super._call(model_inputs));\n }\n}\n\nexport class DetrForSegmentation extends DetrPreTrainedModel {\n /**\n * Runs the model with the provided inputs\n * @param {Object} model_inputs Model inputs\n * @returns {Promise} Object containing segmentation outputs\n */\n async _call(model_inputs) {\n return new DetrSegmentationOutput(await super._call(model_inputs));\n }\n}\n\nexport class DetrObjectDetectionOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification logits (including no-object) for all queries.\n * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).\n * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).\n */\n constructor({ logits, pred_boxes }) {\n super();\n this.logits = logits;\n this.pred_boxes = pred_boxes;\n }\n}\n\nexport class DetrSegmentationOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits The output logits of the model.\n * @param {Tensor} output.pred_boxes Predicted boxes.\n * @param {Tensor} output.pred_masks Predicted masks.\n */\n constructor({ logits, pred_boxes, pred_masks }) {\n super();\n this.logits = logits;\n this.pred_boxes = pred_boxes;\n this.pred_masks = pred_masks;\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class RTDetrPreTrainedModel extends PreTrainedModel { }\nexport class RTDetrModel extends RTDetrPreTrainedModel { }\nexport class RTDetrForObjectDetection extends RTDetrPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new RTDetrObjectDetectionOutput(await super._call(model_inputs));\n }\n}\n\nexport class RTDetrObjectDetectionOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification logits (including no-object) for all queries.\n * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).\n * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).\n */\n constructor({ logits, pred_boxes }) {\n super();\n this.logits = logits;\n this.pred_boxes = pred_boxes;\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class TableTransformerPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Table Transformer Model (consisting of a backbone and encoder-decoder Transformer)\n * outputting raw hidden-states without any specific head on top.\n */\nexport class TableTransformerModel extends TableTransformerPreTrainedModel { }\n\n/**\n * Table Transformer Model (consisting of a backbone and encoder-decoder Transformer)\n * with object detection heads on top, for tasks such as COCO detection.\n */\nexport class TableTransformerForObjectDetection extends TableTransformerPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new TableTransformerObjectDetectionOutput(await super._call(model_inputs));\n }\n}\nexport class TableTransformerObjectDetectionOutput extends DetrObjectDetectionOutput { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class DeiTPreTrainedModel extends PreTrainedModel { }\nexport class DeiTModel extends DeiTPreTrainedModel { }\nexport class DeiTForImageClassification extends DeiTPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class HieraPreTrainedModel extends PreTrainedModel { }\nexport class HieraModel extends HieraPreTrainedModel { }\nexport class HieraForImageClassification extends HieraPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class ResNetPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ResNet model outputting raw features without any specific head on top.\n */\nexport class ResNetModel extends ResNetPreTrainedModel { }\n\n/**\n * ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.\n */\nexport class ResNetForImageClassification extends ResNetPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class SwinPreTrainedModel extends PreTrainedModel { }\nexport class SwinModel extends SwinPreTrainedModel { }\nexport class SwinForImageClassification extends SwinPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class Swin2SRPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Swin2SR Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class Swin2SRModel extends Swin2SRPreTrainedModel { }\n\n/**\n * Swin2SR Model transformer with an upsampler head on top for image super resolution and restoration.\n * \n * **Example:** Super-resolution w/ `Xenova/swin2SR-classical-sr-x2-64`.\n * \n * ```javascript\n * import { AutoProcessor, Swin2SRForImageSuperResolution, RawImage } from '@huggingface/transformers';\n * \n * // Load processor and model\n * const model_id = 'Xenova/swin2SR-classical-sr-x2-64';\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * const model = await Swin2SRForImageSuperResolution.from_pretrained(model_id);\n * \n * // Prepare model inputs\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg';\n * const image = await RawImage.fromURL(url);\n * const inputs = await processor(image);\n * \n * // Run model\n * const outputs = await model(inputs);\n * \n * // Convert Tensor to RawImage\n * const output = outputs.reconstruction.squeeze().clamp_(0, 1).mul_(255).round_().to('uint8');\n * const outputImage = RawImage.fromTensor(output);\n * // RawImage {\n * // data: Uint8Array(786432) [ 41, 31, 24, ... ],\n * // width: 512,\n * // height: 512,\n * // channels: 3\n * // }\n * ```\n */\nexport class Swin2SRForImageSuperResolution extends Swin2SRPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class DPTPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare DPT Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class DPTModel extends DPTPreTrainedModel { }\n\n/**\n * DPT Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2.\n * \n * **Example:** Depth estimation w/ `Xenova/dpt-hybrid-midas`.\n * ```javascript\n * import { DPTForDepthEstimation, AutoProcessor, RawImage, interpolate, max } from '@huggingface/transformers';\n * \n * // Load model and processor\n * const model_id = 'Xenova/dpt-hybrid-midas';\n * const model = await DPTForDepthEstimation.from_pretrained(model_id);\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * \n * // Load image from URL\n * const url = 'http://images.cocodataset.org/val2017/000000039769.jpg';\n * const image = await RawImage.fromURL(url);\n * \n * // Prepare image for the model\n * const inputs = await processor(image);\n * \n * // Run model\n * const { predicted_depth } = await model(inputs);\n * \n * // Interpolate to original size\n * const prediction = interpolate(predicted_depth, image.size.reverse(), 'bilinear', false);\n * \n * // Visualize the prediction\n * const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8');\n * const depth = RawImage.fromTensor(formatted);\n * // RawImage {\n * // data: Uint8Array(307200) [ 85, 85, 84, ... ],\n * // width: 640,\n * // height: 480,\n * // channels: 1\n * // }\n * ```\n */\nexport class DPTForDepthEstimation extends DPTPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class DepthAnythingPreTrainedModel extends PreTrainedModel { }\n\n/**\n * Depth Anything Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2.\n */\nexport class DepthAnythingForDepthEstimation extends DepthAnythingPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class SapiensPreTrainedModel extends PreTrainedModel { }\nexport class SapiensForSemanticSegmentation extends SapiensPreTrainedModel { }\nexport class SapiensForDepthEstimation extends SapiensPreTrainedModel { }\nexport class SapiensForNormalEstimation extends SapiensPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class DepthProPreTrainedModel extends PreTrainedModel { }\nexport class DepthProForDepthEstimation extends DepthProPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class MaskFormerPreTrainedModel extends PreTrainedModel { }\nexport class MaskFormerModel extends MaskFormerPreTrainedModel { }\nexport class MaskFormerForInstanceSegmentation extends MaskFormerPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class GLPNPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare GLPN encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top.\n */\nexport class GLPNModel extends GLPNPreTrainedModel { }\n\n/**\n * GLPN Model transformer with a lightweight depth estimation head on top e.g. for KITTI, NYUv2.\n * \n * **Example:** Depth estimation w/ `Xenova/glpn-kitti`.\n * ```javascript\n * import { GLPNForDepthEstimation, AutoProcessor, RawImage, interpolate, max } from '@huggingface/transformers';\n * \n * // Load model and processor\n * const model_id = 'Xenova/glpn-kitti';\n * const model = await GLPNForDepthEstimation.from_pretrained(model_id);\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * \n * // Load image from URL\n * const url = 'http://images.cocodataset.org/val2017/000000039769.jpg';\n * const image = await RawImage.fromURL(url);\n * \n * // Prepare image for the model\n * const inputs = await processor(image);\n * \n * // Run model\n * const { predicted_depth } = await model(inputs);\n * \n * // Interpolate to original size\n * const prediction = interpolate(predicted_depth, image.size.reverse(), 'bilinear', false);\n * \n * // Visualize the prediction\n * const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8');\n * const depth = RawImage.fromTensor(formatted);\n * // RawImage {\n * // data: Uint8Array(307200) [ 207, 169, 154, ... ],\n * // width: 640,\n * // height: 480,\n * // channels: 1\n * // }\n * ```\n */\nexport class GLPNForDepthEstimation extends GLPNPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class DonutSwinPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Donut Swin Model transformer outputting raw hidden-states without any specific head on top.\n * \n * **Example:** Step-by-step Document Parsing.\n * \n * ```javascript\n * import { AutoProcessor, AutoTokenizer, AutoModelForVision2Seq, RawImage } from '@huggingface/transformers';\n * \n * // Choose model to use\n * const model_id = 'Xenova/donut-base-finetuned-cord-v2';\n * \n * // Prepare image inputs\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/receipt.png';\n * const image = await RawImage.read(url);\n * const image_inputs = await processor(image);\n * \n * // Prepare decoder inputs\n * const tokenizer = await AutoTokenizer.from_pretrained(model_id);\n * const task_prompt = '';\n * const decoder_input_ids = tokenizer(task_prompt, {\n * add_special_tokens: false,\n * }).input_ids;\n * \n * // Create the model\n * const model = await AutoModelForVision2Seq.from_pretrained(model_id);\n * \n * // Run inference\n * const output = await model.generate(image_inputs.pixel_values, {\n * decoder_input_ids,\n * max_length: model.config.decoder.max_position_embeddings,\n * });\n * \n * // Decode output\n * const decoded = tokenizer.batch_decode(output)[0];\n * // CINNAMON SUGAR 17,000 1 x 17,000 17,000 17,000 20,000 3,000\n * ```\n * \n * **Example:** Step-by-step Document Visual Question Answering (DocVQA)\n * \n * ```javascript\n * import { AutoProcessor, AutoTokenizer, AutoModelForVision2Seq, RawImage } from '@huggingface/transformers';\n * \n * // Choose model to use\n * const model_id = 'Xenova/donut-base-finetuned-docvqa';\n * \n * // Prepare image inputs\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/invoice.png';\n * const image = await RawImage.read(url);\n * const image_inputs = await processor(image);\n * \n * // Prepare decoder inputs\n * const tokenizer = await AutoTokenizer.from_pretrained(model_id);\n * const question = 'What is the invoice number?';\n * const task_prompt = `${question}`;\n * const decoder_input_ids = tokenizer(task_prompt, {\n * add_special_tokens: false,\n * }).input_ids;\n * \n * // Create the model\n * const model = await AutoModelForVision2Seq.from_pretrained(model_id);\n * \n * // Run inference\n * const output = await model.generate(image_inputs.pixel_values, {\n * decoder_input_ids,\n * max_length: model.config.decoder.max_position_embeddings,\n * });\n * \n * // Decode output\n * const decoded = tokenizer.batch_decode(output)[0];\n * // What is the invoice number? us-001\n * ```\n */\nexport class DonutSwinModel extends DonutSwinPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class ConvNextPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ConvNext model outputting raw features without any specific head on top.\n */\nexport class ConvNextModel extends ConvNextPreTrainedModel { }\n\n/**\n * ConvNext Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.\n */\nexport class ConvNextForImageClassification extends ConvNextPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class ConvNextV2PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare ConvNextV2 model outputting raw features without any specific head on top.\n */\nexport class ConvNextV2Model extends ConvNextV2PreTrainedModel { }\n\n/**\n * ConvNextV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet.\n */\nexport class ConvNextV2ForImageClassification extends ConvNextV2PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class Dinov2PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare DINOv2 Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class Dinov2Model extends Dinov2PreTrainedModel { }\n\n/**\n * Dinov2 Model transformer with an image classification head on top (a linear layer on top of the final hidden state of the [CLS] token) e.g. for ImageNet.\n */\nexport class Dinov2ForImageClassification extends Dinov2PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class YolosPreTrainedModel extends PreTrainedModel { }\nexport class YolosModel extends YolosPreTrainedModel { }\nexport class YolosForObjectDetection extends YolosPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new YolosObjectDetectionOutput(await super._call(model_inputs));\n }\n}\n\nexport class YolosObjectDetectionOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification logits (including no-object) for all queries.\n * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).\n * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).\n */\n constructor({ logits, pred_boxes }) {\n super();\n this.logits = logits;\n this.pred_boxes = pred_boxes;\n }\n}\n//////////////////////////////////////////////////\n\n\n\n\n//////////////////////////////////////////////////\nexport class SamPreTrainedModel extends PreTrainedModel { }\n\n/**\n * Segment Anything Model (SAM) for generating segmentation masks, given an input image\n * and optional 2D location and bounding boxes.\n * \n * **Example:** Perform mask generation w/ `Xenova/sam-vit-base`.\n * ```javascript\n * import { SamModel, AutoProcessor, RawImage } from '@huggingface/transformers';\n * \n * const model = await SamModel.from_pretrained('Xenova/sam-vit-base');\n * const processor = await AutoProcessor.from_pretrained('Xenova/sam-vit-base');\n * \n * const img_url = 'https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png';\n * const raw_image = await RawImage.read(img_url);\n * const input_points = [[[450, 600]]] // 2D localization of a window\n * \n * const inputs = await processor(raw_image, { input_points });\n * const outputs = await model(inputs);\n * \n * const masks = await processor.post_process_masks(outputs.pred_masks, inputs.original_sizes, inputs.reshaped_input_sizes);\n * // [\n * // Tensor {\n * // dims: [ 1, 3, 1764, 2646 ],\n * // type: 'bool',\n * // data: Uint8Array(14002632) [ ... ],\n * // size: 14002632\n * // }\n * // ]\n * const scores = outputs.iou_scores;\n * // Tensor {\n * // dims: [ 1, 1, 3 ],\n * // type: 'float32',\n * // data: Float32Array(3) [\n * // 0.8892380595207214,\n * // 0.9311248064041138,\n * // 0.983696699142456\n * // ],\n * // size: 3\n * // }\n * ```\n */\nexport class SamModel extends SamPreTrainedModel {\n\n /**\n * Compute image embeddings and positional image embeddings, given the pixel values of an image.\n * @param {Object} model_inputs Object containing the model inputs.\n * @param {Tensor} model_inputs.pixel_values Pixel values obtained using a `SamProcessor`.\n * @returns {Promise<{ image_embeddings: Tensor, image_positional_embeddings: Tensor }>} The image embeddings and positional image embeddings.\n */\n async get_image_embeddings({ pixel_values }) {\n // in:\n // - pixel_values: tensor.float32[batch_size,3,1024,1024]\n // \n // out:\n // - image_embeddings: tensor.float32[batch_size,256,64,64]\n // - image_positional_embeddings: tensor.float32[batch_size,256,64,64]\n return await encoderForward(this, { pixel_values })\n }\n\n /**\n * @typedef {Object} SamModelInputs Object containing the model inputs.\n * @property {Tensor} pixel_values Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`.\n * These can be obtained using a `SamProcessor`.\n * @property {Tensor} [input_points] Input 2D spatial points with shape `(batch_size, num_points, 2)`.\n * This is used by the prompt encoder to encode the prompt.\n * @property {Tensor} [input_labels] Input labels for the points, as a Tensor of shape `(batch_size, point_batch_size, num_points)`.\n * This is used by the prompt encoder to encode the prompt. There are 4 types of labels:\n * - `1`: the point is a point that contains the object of interest\n * - `0`: the point is a point that does not contain the object of interest\n * - `-1`: the point corresponds to the background\n * - `-10`: the point is a padding point, thus should be ignored by the prompt encoder\n * @property {Tensor} [input_boxes] Input bounding boxes with shape `(batch_size, num_boxes, 4)`.\n * @property {Tensor} [image_embeddings] Image embeddings used by the mask decoder.\n * @property {Tensor} [image_positional_embeddings] Image positional embeddings used by the mask decoder.\n */\n\n /**\n * @param {SamModelInputs} model_inputs Object containing the model inputs.\n * @returns {Promise} The output of the model.\n */\n async forward(model_inputs) {\n if (!model_inputs.image_embeddings || !model_inputs.image_positional_embeddings) {\n // Compute the image embeddings if they are missing\n model_inputs = {\n ...model_inputs,\n ...(await this.get_image_embeddings(model_inputs))\n }\n }\n\n if (!model_inputs.input_labels && model_inputs.input_points) {\n // Set default input labels if they are missing\n const shape = model_inputs.input_points.dims.slice(0, -1);\n const numElements = shape.reduce((a, b) => a * b, 1);\n model_inputs.input_labels = new Tensor(\n 'int64',\n new BigInt64Array(numElements).fill(1n),\n shape\n );\n }\n\n const decoder_inputs = {\n image_embeddings: model_inputs.image_embeddings,\n image_positional_embeddings: model_inputs.image_positional_embeddings,\n };\n if (model_inputs.input_points) {\n decoder_inputs.input_points = model_inputs.input_points;\n }\n if (model_inputs.input_labels) {\n decoder_inputs.input_labels = model_inputs.input_labels;\n }\n if (model_inputs.input_boxes) {\n decoder_inputs.input_boxes = model_inputs.input_boxes;\n }\n\n // Returns:\n // - iou_scores: tensor.float32[batch_size,point_batch_size,3]\n // - pred_masks: tensor.float32[batch_size,point_batch_size,3,256,256]\n return await sessionRun(this.sessions['prompt_encoder_mask_decoder'], decoder_inputs);\n }\n\n /**\n * Runs the model with the provided inputs\n * @param {Object} model_inputs Model inputs\n * @returns {Promise} Object containing segmentation outputs\n */\n async _call(model_inputs) {\n return new SamImageSegmentationOutput(await super._call(model_inputs));\n }\n}\n\n\n/**\n * Base class for Segment-Anything model's output.\n */\nexport class SamImageSegmentationOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.iou_scores The output logits of the model.\n * @param {Tensor} output.pred_masks Predicted boxes.\n */\n constructor({ iou_scores, pred_masks }) {\n super();\n this.iou_scores = iou_scores;\n this.pred_masks = pred_masks;\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// MarianMT models\nexport class MarianPreTrainedModel extends PreTrainedModel { };\n\nexport class MarianModel extends MarianPreTrainedModel { }\n\nexport class MarianMTModel extends MarianPreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// M2M100 models\nexport class M2M100PreTrainedModel extends PreTrainedModel { };\n\nexport class M2M100Model extends M2M100PreTrainedModel { }\n\nexport class M2M100ForConditionalGeneration extends M2M100PreTrainedModel { }\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Wav2Vec2 models\nexport class Wav2Vec2PreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare Wav2Vec2 Model transformer outputting raw hidden-states without any specific head on top.\n * \n * **Example:** Load and run a `Wav2Vec2Model` for feature extraction.\n * \n * ```javascript\n * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/mms-300m');\n * const audio = await read_audio('https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac', 16000);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const model = await AutoModel.from_pretrained('Xenova/mms-300m');\n * const output = await model(inputs);\n * // {\n * // last_hidden_state: Tensor {\n * // dims: [ 1, 1144, 1024 ],\n * // type: 'float32',\n * // data: Float32Array(1171456) [ ... ],\n * // size: 1171456\n * // }\n * // }\n * ```\n */\nexport class Wav2Vec2Model extends Wav2Vec2PreTrainedModel { }\n\nexport class Wav2Vec2ForCTC extends Wav2Vec2PreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\nexport class Wav2Vec2ForSequenceClassification extends Wav2Vec2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * Wav2Vec2 Model with a frame classification head on top for tasks like Speaker Diarization.\n */\nexport class Wav2Vec2ForAudioFrameClassification extends Wav2Vec2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// PyAnnote models\nexport class PyAnnotePreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare PyAnnote Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class PyAnnoteModel extends PyAnnotePreTrainedModel { }\n\n/**\n * PyAnnote Model with a frame classification head on top for tasks like Speaker Diarization.\n * \n * **Example:** Load and run a `PyAnnoteForAudioFrameClassification` for speaker diarization.\n * \n * ```javascript\n * import { AutoProcessor, AutoModelForAudioFrameClassification, read_audio } from '@huggingface/transformers';\n * \n * // Load model and processor\n * const model_id = 'onnx-community/pyannote-segmentation-3.0';\n * const model = await AutoModelForAudioFrameClassification.from_pretrained(model_id);\n * const processor = await AutoProcessor.from_pretrained(model_id);\n * \n * // Read and preprocess audio\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/mlk.wav';\n * const audio = await read_audio(url, processor.feature_extractor.config.sampling_rate);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const { logits } = await model(inputs);\n * // {\n * // logits: Tensor {\n * // dims: [ 1, 767, 7 ], // [batch_size, num_frames, num_classes]\n * // type: 'float32',\n * // data: Float32Array(5369) [ ... ],\n * // size: 5369\n * // }\n * // }\n * \n * const result = processor.post_process_speaker_diarization(logits, audio.length);\n * // [\n * // [\n * // { id: 0, start: 0, end: 1.0512535626298245, confidence: 0.8220156481664611 },\n * // { id: 2, start: 1.0512535626298245, end: 2.3398869619825127, confidence: 0.9008811707860472 },\n * // ...\n * // ]\n * // ]\n * \n * // Display result\n * console.table(result[0], ['start', 'end', 'id', 'confidence']);\n * // ┌─────────┬────────────────────┬────────────────────┬────┬─────────────────────┐\n * // │ (index) │ start │ end │ id │ confidence │\n * // ├─────────┼────────────────────┼────────────────────┼────┼─────────────────────┤\n * // │ 0 │ 0 │ 1.0512535626298245 │ 0 │ 0.8220156481664611 │\n * // │ 1 │ 1.0512535626298245 │ 2.3398869619825127 │ 2 │ 0.9008811707860472 │\n * // │ 2 │ 2.3398869619825127 │ 3.5946089560890773 │ 0 │ 0.7521651315796233 │\n * // │ 3 │ 3.5946089560890773 │ 4.578039708226655 │ 2 │ 0.8491978128022479 │\n * // │ 4 │ 4.578039708226655 │ 4.594995410849717 │ 0 │ 0.2935352600416393 │\n * // │ 5 │ 4.594995410849717 │ 6.121008646925269 │ 3 │ 0.6788051309866024 │\n * // │ 6 │ 6.121008646925269 │ 6.256654267909762 │ 0 │ 0.37125512393851134 │\n * // │ 7 │ 6.256654267909762 │ 8.630452635138397 │ 2 │ 0.7467035186353542 │\n * // │ 8 │ 8.630452635138397 │ 10.088643060721703 │ 0 │ 0.7689364814666032 │\n * // │ 9 │ 10.088643060721703 │ 12.58113134631177 │ 2 │ 0.9123324509131324 │\n * // │ 10 │ 12.58113134631177 │ 13.005023911888312 │ 0 │ 0.4828358177572041 │\n * // └─────────┴────────────────────┴────────────────────┴────┴─────────────────────┘\n * ```\n */\nexport class PyAnnoteForAudioFrameClassification extends PyAnnotePreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// WeSpeakerResNet models\nexport class WeSpeakerResNetPreTrainedModel extends PreTrainedModel { };\nexport class WeSpeakerResNetModel extends WeSpeakerResNetPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// UniSpeech models\nexport class UniSpeechPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare UniSpeech Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class UniSpeechModel extends UniSpeechPreTrainedModel { }\n\n/**\n * UniSpeech Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class UniSpeechForCTC extends UniSpeechPreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * UniSpeech Model with a sequence classification head on top (a linear layer over the pooled output).\n */\nexport class UniSpeechForSequenceClassification extends UniSpeechPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// UniSpeechSat models\nexport class UniSpeechSatPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare UniSpeechSat Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class UniSpeechSatModel extends UniSpeechSatPreTrainedModel { }\n\n/**\n * UniSpeechSat Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class UniSpeechSatForCTC extends UniSpeechSatPreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * UniSpeechSat Model with a sequence classification head on top (a linear layer over the pooled output).\n */\nexport class UniSpeechSatForSequenceClassification extends UniSpeechSatPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * UniSpeechSat Model with a frame classification head on top for tasks like Speaker Diarization.\n */\nexport class UniSpeechSatForAudioFrameClassification extends UniSpeechSatPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Wav2Vec2Bert models\nexport class Wav2Vec2BertPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare Wav2Vec2Bert Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class Wav2Vec2BertModel extends Wav2Vec2BertPreTrainedModel { }\n\n/**\n * Wav2Vec2Bert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class Wav2Vec2BertForCTC extends Wav2Vec2BertPreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_features Float values of input mel-spectrogram.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * Wav2Vec2Bert Model with a sequence classification head on top (a linear layer over the pooled output).\n */\nexport class Wav2Vec2BertForSequenceClassification extends Wav2Vec2BertPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Hubert models\nexport class HubertPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Hubert Model transformer outputting raw hidden-states without any specific head on top.\n * \n * **Example:** Load and run a `HubertModel` for feature extraction.\n * \n * ```javascript\n * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/hubert-base-ls960');\n * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav', 16000);\n * const inputs = await processor(audio);\n * \n * // Load and run model with inputs\n * const model = await AutoModel.from_pretrained('Xenova/hubert-base-ls960');\n * const output = await model(inputs);\n * // {\n * // last_hidden_state: Tensor {\n * // dims: [ 1, 549, 768 ],\n * // type: 'float32',\n * // data: Float32Array(421632) [0.0682469978928566, 0.08104046434164047, -0.4975186586380005, ...],\n * // size: 421632\n * // }\n * // }\n * ```\n */\nexport class HubertModel extends Wav2Vec2PreTrainedModel { }\n\n/**\n * Hubert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class HubertForCTC extends Wav2Vec2PreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * Hubert Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like SUPERB Keyword Spotting.\n */\nexport class HubertForSequenceClassification extends Wav2Vec2PreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// WavLM models\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class WavLMPreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare WavLM Model transformer outputting raw hidden-states without any specific head on top.\n * \n * **Example:** Load and run a `WavLMModel` for feature extraction.\n * \n * ```javascript\n * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base');\n * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav', 16000);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const model = await AutoModel.from_pretrained('Xenova/wavlm-base');\n * const output = await model(inputs);\n * // {\n * // last_hidden_state: Tensor {\n * // dims: [ 1, 549, 768 ],\n * // type: 'float32',\n * // data: Float32Array(421632) [-0.349443256855011, -0.39341306686401367, 0.022836603224277496, ...],\n * // size: 421632\n * // }\n * // }\n * ```\n */\nexport class WavLMModel extends WavLMPreTrainedModel { }\n\n/**\n * WavLM Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\n */\nexport class WavLMForCTC extends WavLMPreTrainedModel {\n /**\n * @param {Object} model_inputs\n * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.\n * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]\n */\n async _call(model_inputs) {\n return new CausalLMOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * WavLM Model with a sequence classification head on top (a linear layer over the pooled output).\n */\nexport class WavLMForSequenceClassification extends WavLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * WavLM Model with an XVector feature extraction head on top for tasks like Speaker Verification.\n * \n * **Example:** Extract speaker embeddings with `WavLMForXVector`.\n * ```javascript\n * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base-plus-sv');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const audio = await read_audio(url, 16000);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const model = await AutoModel.from_pretrained('Xenova/wavlm-base-plus-sv');\n * const outputs = await model(inputs);\n * // {\n * // logits: Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [0.5847219228744507, ...],\n * // size: 512\n * // },\n * // embeddings: Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [-0.09079201519489288, ...],\n * // size: 512\n * // }\n * // }\n * ```\n */\nexport class WavLMForXVector extends WavLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits and speaker embeddings.\n */\n async _call(model_inputs) {\n return new XVectorOutput(await super._call(model_inputs));\n }\n}\n\n/**\n * WavLM Model with a frame classification head on top for tasks like Speaker Diarization.\n * \n * **Example:** Perform speaker diarization with `WavLMForAudioFrameClassification`.\n * ```javascript\n * import { AutoProcessor, AutoModelForAudioFrameClassification, read_audio } from '@huggingface/transformers';\n * \n * // Read and preprocess audio\n * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base-plus-sd');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const audio = await read_audio(url, 16000);\n * const inputs = await processor(audio);\n * \n * // Run model with inputs\n * const model = await AutoModelForAudioFrameClassification.from_pretrained('Xenova/wavlm-base-plus-sd');\n * const { logits } = await model(inputs);\n * // {\n * // logits: Tensor {\n * // dims: [ 1, 549, 2 ], // [batch_size, num_frames, num_speakers]\n * // type: 'float32',\n * // data: Float32Array(1098) [-3.5301010608673096, ...],\n * // size: 1098\n * // }\n * // }\n * \n * const labels = logits[0].sigmoid().tolist().map(\n * frames => frames.map(speaker => speaker > 0.5 ? 1 : 0)\n * );\n * console.log(labels); // labels is a one-hot array of shape (num_frames, num_speakers)\n * // [\n * // [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],\n * // [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0],\n * // [0, 0], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1],\n * // ...\n * // ]\n * ```\n */\nexport class WavLMForAudioFrameClassification extends WavLMPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} An object containing the model's output logits for sequence classification.\n */\n async _call(model_inputs) {\n return new TokenClassifierOutput(await super._call(model_inputs));\n }\n}\n\n//////////////////////////////////////////////////\n// SpeechT5 models\n/**\n * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.\n */\nexport class SpeechT5PreTrainedModel extends PreTrainedModel { };\n\n/**\n * The bare SpeechT5 Encoder-Decoder Model outputting raw hidden-states without any specific pre- or post-nets.\n */\nexport class SpeechT5Model extends SpeechT5PreTrainedModel { };\n\n/**\n * SpeechT5 Model with a speech encoder and a text decoder.\n * \n * **Example:** Generate speech from text with `SpeechT5ForSpeechToText`.\n * ```javascript\n * import { AutoTokenizer, AutoProcessor, SpeechT5ForTextToSpeech, SpeechT5HifiGan, Tensor } from '@huggingface/transformers';\n * \n * // Load the tokenizer and processor\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/speecht5_tts');\n * const processor = await AutoProcessor.from_pretrained('Xenova/speecht5_tts');\n * \n * // Load the models\n * // NOTE: We use the full-precision versions as they are more accurate\n * const model = await SpeechT5ForTextToSpeech.from_pretrained('Xenova/speecht5_tts', { dtype: 'fp32' });\n * const vocoder = await SpeechT5HifiGan.from_pretrained('Xenova/speecht5_hifigan', { dtype: 'fp32' });\n * \n * // Load speaker embeddings from URL\n * const speaker_embeddings_data = new Float32Array(\n * await (await fetch('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin')).arrayBuffer()\n * );\n * const speaker_embeddings = new Tensor(\n * 'float32',\n * speaker_embeddings_data,\n * [1, speaker_embeddings_data.length]\n * )\n * \n * // Run tokenization\n * const { input_ids } = tokenizer('Hello, my dog is cute');\n * \n * // Generate waveform\n * const { waveform } = await model.generate_speech(input_ids, speaker_embeddings, { vocoder });\n * console.log(waveform)\n * // Tensor {\n * // dims: [ 26112 ],\n * // type: 'float32',\n * // size: 26112,\n * // data: Float32Array(26112) [ -0.00043630177970044315, -0.00018082228780258447, ... ],\n * // }\n * ```\n */\nexport class SpeechT5ForSpeechToText extends SpeechT5PreTrainedModel { }\n\n/**\n * SpeechT5 Model with a text encoder and a speech decoder.\n */\nexport class SpeechT5ForTextToSpeech extends SpeechT5PreTrainedModel {\n\n /**\n * @typedef {Object} SpeechOutput\n * @property {Tensor} [spectrogram] The predicted log-mel spectrogram of shape\n * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided\n * @property {Tensor} [waveform] The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided.\n * @property {Tensor} [cross_attentions] The outputs of the decoder's cross-attention layers of shape\n * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`.\n */\n\n /**\n * Converts a sequence of input tokens into a sequence of mel spectrograms, which are subsequently turned into a speech waveform using a vocoder.\n * @param {Tensor} input_values Indices of input sequence tokens in the vocabulary.\n * @param {Tensor} speaker_embeddings Tensor containing the speaker embeddings.\n * @param {Object} options Optional parameters for generating speech.\n * @param {number} [options.threshold=0.5] The generated sequence ends when the predicted stop token probability exceeds this value.\n * @param {number} [options.minlenratio=0.0] Used to calculate the minimum required length for the output sequence.\n * @param {number} [options.maxlenratio=20.0] Used to calculate the maximum allowed length for the output sequence.\n * @param {Object} [options.vocoder=null] The vocoder that converts the mel spectrogram into a speech waveform. If `null`, the output is the mel spectrogram.\n * @param {boolean} [options.output_cross_attentions=false] Whether or not to return the attentions tensors of the decoder's cross-attention layers.\n * @returns {Promise} A promise which resolves to an object containing the spectrogram, waveform, and cross-attention tensors.\n */\n async generate_speech(input_values, speaker_embeddings, {\n threshold = 0.5,\n minlenratio = 0.0,\n maxlenratio = 20.0,\n vocoder = null,\n // output_cross_attentions = false, // TODO add\n } = {}) {\n\n const model_inputs = {\n input_ids: input_values\n }\n\n const { encoder_outputs, encoder_attention_mask } = await encoderForward(this, model_inputs);\n\n const r = encoder_outputs.dims[1] / this.config.reduction_factor;\n const maxlen = Math.floor(r * maxlenratio);\n const minlen = Math.floor(r * minlenratio);\n\n const num_mel_bins = this.config.num_mel_bins;\n\n let spectrogramParts = [];\n let past_key_values = null;\n let decoder_outputs = null;\n let idx = 0;\n\n while (true) {\n ++idx;\n\n const use_cache_branch = boolTensor(!!decoder_outputs);\n let output_sequence;\n if (decoder_outputs) {\n output_sequence = decoder_outputs.output_sequence_out;\n } else {\n output_sequence = new Tensor(\n 'float32',\n new Float32Array(num_mel_bins),\n [1, 1, num_mel_bins],\n )\n }\n let decoderFeeds = {\n use_cache_branch,\n output_sequence,\n encoder_attention_mask: encoder_attention_mask,\n speaker_embeddings: speaker_embeddings,\n encoder_hidden_states: encoder_outputs,\n };\n\n this.addPastKeyValues(decoderFeeds, past_key_values);\n decoder_outputs = await sessionRun(this.sessions['decoder_model_merged'], decoderFeeds);\n past_key_values = this.getPastKeyValues(decoder_outputs, past_key_values);\n\n const { prob, spectrum } = decoder_outputs;\n spectrogramParts.push(spectrum);\n\n if (idx >= minlen && (\n // Finished when stop token or maximum length is reached.\n Array.from(prob.data).filter(p => p >= threshold).length > 0 || idx >= maxlen\n )) {\n break;\n }\n }\n\n const spectrogram = cat(spectrogramParts);\n const { waveform } = await sessionRun(vocoder.sessions['model'], { spectrogram });\n\n return {\n spectrogram,\n waveform,\n // cross_attentions: null, // TODO add\n }\n }\n}\n\n/**\n * HiFi-GAN vocoder.\n * \n * See [SpeechT5ForSpeechToText](./models#module_models.SpeechT5ForSpeechToText) for example usage.\n */\nexport class SpeechT5HifiGan extends PreTrainedModel {\n main_input_name = 'spectrogram';\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// TrOCR models\nexport class TrOCRPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The TrOCR Decoder with a language modeling head.\n */\nexport class TrOCRForCausalLM extends TrOCRPreTrainedModel { }\n\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Mistral models\n/**\n * The bare Mistral Model outputting raw hidden-states without any specific head on top.\n */\nexport class MistralPreTrainedModel extends PreTrainedModel { }\n\nexport class MistralModel extends MistralPreTrainedModel { }\n\nexport class MistralForCausalLM extends MistralPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Starcoder2 models\n/**\n * The bare Starcoder2 Model outputting raw hidden-states without any specific head on top.\n */\nexport class Starcoder2PreTrainedModel extends PreTrainedModel { }\n\nexport class Starcoder2Model extends Starcoder2PreTrainedModel { }\n\nexport class Starcoder2ForCausalLM extends Starcoder2PreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// Falcon models\n/**\n * The bare Falcon Model outputting raw hidden-states without any specific head on top.\n */\nexport class FalconPreTrainedModel extends PreTrainedModel { }\n\nexport class FalconModel extends FalconPreTrainedModel { }\n\nexport class FalconForCausalLM extends FalconPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// CLAP models\nexport class ClapPreTrainedModel extends PreTrainedModel { }\n\nexport class ClapModel extends ClapPreTrainedModel { }\n\n/**\n * CLAP Text Model with a projection layer on top (a linear layer on top of the pooled output).\n * \n * **Example:** Compute text embeddings with `ClapTextModelWithProjection`.\n * \n * ```javascript\n * import { AutoTokenizer, ClapTextModelWithProjection } from '@huggingface/transformers';\n * \n * // Load tokenizer and text model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clap-htsat-unfused');\n * const text_model = await ClapTextModelWithProjection.from_pretrained('Xenova/clap-htsat-unfused');\n * \n * // Run tokenization\n * const texts = ['a sound of a cat', 'a sound of a dog'];\n * const text_inputs = tokenizer(texts, { padding: true, truncation: true });\n * \n * // Compute embeddings\n * const { text_embeds } = await text_model(text_inputs);\n * // Tensor {\n * // dims: [ 2, 512 ],\n * // type: 'float32',\n * // data: Float32Array(1024) [ ... ],\n * // size: 1024\n * // }\n * ```\n */\nexport class ClapTextModelWithProjection extends ClapPreTrainedModel {\n\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'text_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n\n/**\n * CLAP Audio Model with a projection layer on top (a linear layer on top of the pooled output).\n * \n * **Example:** Compute audio embeddings with `ClapAudioModelWithProjection`.\n * \n * ```javascript\n * import { AutoProcessor, ClapAudioModelWithProjection, read_audio } from '@huggingface/transformers';\n * \n * // Load processor and audio model\n * const processor = await AutoProcessor.from_pretrained('Xenova/clap-htsat-unfused');\n * const audio_model = await ClapAudioModelWithProjection.from_pretrained('Xenova/clap-htsat-unfused');\n * \n * // Read audio and run processor\n * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cat_meow.wav');\n * const audio_inputs = await processor(audio);\n * \n * // Compute embeddings\n * const { audio_embeds } = await audio_model(audio_inputs);\n * // Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [ ... ],\n * // size: 512\n * // }\n * ```\n */\nexport class ClapAudioModelWithProjection extends ClapPreTrainedModel {\n /** @type {PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, options = {}) {\n // Update default model file name if not provided\n options.model_file_name ??= 'audio_model';\n return super.from_pretrained(pretrained_model_name_or_path, options);\n }\n}\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\n// VITS models\nexport class VitsPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The complete VITS model, for text-to-speech synthesis.\n * \n * **Example:** Generate speech from text with `VitsModel`.\n * ```javascript\n * import { AutoTokenizer, VitsModel } from '@huggingface/transformers';\n * \n * // Load the tokenizer and model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/mms-tts-eng');\n * const model = await VitsModel.from_pretrained('Xenova/mms-tts-eng');\n * \n * // Run tokenization\n * const inputs = tokenizer('I love transformers');\n * \n * // Generate waveform\n * const { waveform } = await model(inputs);\n * // Tensor {\n * // dims: [ 1, 35328 ],\n * // type: 'float32',\n * // data: Float32Array(35328) [ ... ],\n * // size: 35328,\n * // }\n * ```\n */\nexport class VitsModel extends VitsPreTrainedModel {\n /**\n * Calls the model on new inputs.\n * @param {Object} model_inputs The inputs to the model.\n * @returns {Promise} The outputs for the VITS model.\n */\n async _call(model_inputs) {\n return new VitsModelOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Segformer models\nexport class SegformerPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare SegFormer encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top.\n */\nexport class SegformerModel extends SegformerPreTrainedModel { }\n\n/**\n * SegFormer Model transformer with an image classification head on top (a linear layer on top of the final hidden states) e.g. for ImageNet.\n */\nexport class SegformerForImageClassification extends SegformerPreTrainedModel { }\n\n/**\n * SegFormer Model transformer with an all-MLP decode head on top e.g. for ADE20k, CityScapes.\n */\nexport class SegformerForSemanticSegmentation extends SegformerPreTrainedModel { }\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// StableLm models\nexport class StableLmPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare StableLm Model transformer outputting raw hidden-states without any specific head on top.\n */\nexport class StableLmModel extends StableLmPreTrainedModel { }\n\n/**\n * StableLm Model with a `language modeling` head on top for Causal Language Modeling (with past).\n */\nexport class StableLmForCausalLM extends StableLmPreTrainedModel { }\n//////////////////////////////////////////////////\n\n\n//////////////////////////////////////////////////\nexport class EfficientNetPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare EfficientNet model outputting raw features without any specific head on top.\n */\nexport class EfficientNetModel extends EfficientNetPreTrainedModel { }\n\n/**\n * EfficientNet Model with an image classification head on top (a linear layer on top of the pooled features).\n */\nexport class EfficientNetForImageClassification extends EfficientNetPreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Musicgen models\nexport class MusicgenPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare Musicgen decoder model outputting raw hidden-states without any specific head on top.\n */\nexport class MusicgenModel extends MusicgenPreTrainedModel { }\n\n/**\n * The MusicGen decoder model with a language modelling head on top.\n */\nexport class MusicgenForCausalLM extends MusicgenPreTrainedModel { }\n\n/**\n * The composite MusicGen model with a text encoder, audio encoder and Musicgen decoder,\n * for music generation tasks with one or both of text and audio prompts.\n * \n * **Example:** Generate music from text with `Xenova/musicgen-small`.\n * ```javascript\n * import { AutoTokenizer, MusicgenForConditionalGeneration } from '@huggingface/transformers';\n * \n * // Load tokenizer and model\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/musicgen-small');\n * const model = await MusicgenForConditionalGeneration.from_pretrained(\n * 'Xenova/musicgen-small', { dtype: 'fp32' }\n * );\n * \n * // Prepare text input\n * const prompt = '80s pop track with bassy drums and synth';\n * const inputs = tokenizer(prompt);\n * \n * // Generate audio\n * const audio_values = await model.generate({\n * ...inputs,\n * max_new_tokens: 512,\n * do_sample: true,\n * guidance_scale: 3,\n * });\n * \n * // (Optional) Write the output to a WAV file\n * import wavefile from 'wavefile';\n * import fs from 'fs';\n * \n * const wav = new wavefile.WaveFile();\n * wav.fromScratch(1, model.config.audio_encoder.sampling_rate, '32f', audio_values.data);\n * fs.writeFileSync('musicgen_out.wav', wav.toBuffer());\n * ```\n */\nexport class MusicgenForConditionalGeneration extends PreTrainedModel { // NOTE: not MusicgenPreTrainedModel\n forward_params = [\n 'input_ids',\n 'attention_mask',\n 'encoder_outputs',\n 'decoder_input_ids',\n 'decoder_attention_mask',\n 'past_key_values',\n ];\n\n /**\n * Apply the pattern mask to the final ids,\n * then revert the pattern delay mask by filtering the pad token id in a single step.\n * @param {Tensor} outputs The output tensor from the model.\n * @returns {Tensor} The filtered output tensor.\n */\n _apply_and_filter_by_delay_pattern_mask(outputs) {\n const [bs_x_codebooks, seqLength] = outputs.dims;\n const num_codebooks = this.config.decoder.num_codebooks;\n const upperBound = (seqLength - num_codebooks);\n\n let newDataSize = 0;\n for (let i = 0; i < outputs.size; ++i) {\n if (outputs.data[i] === this.config.decoder.pad_token_id) {\n continue;\n }\n\n const row = (i % seqLength);\n const col = Math.floor(i / seqLength) % num_codebooks;\n\n const diff = row - col;\n if (diff > 0 && diff <= upperBound) {\n outputs.data[newDataSize++] = outputs.data[i];\n }\n }\n\n const batch_size = Math.floor(bs_x_codebooks / num_codebooks);\n const inferred = newDataSize / (batch_size * num_codebooks);\n // TODO: assert `inferred` is an integer\n return new Tensor(\n outputs.type,\n outputs.data.slice(0, newDataSize),\n [batch_size, num_codebooks, inferred]\n );\n }\n\n\n prepare_inputs_for_generation(input_ids, model_inputs, generation_config) {\n // apply the delay pattern mask\n let clonedInputIds = structuredClone(input_ids);\n for (let i = 0; i < clonedInputIds.length; ++i) {\n for (let j = 0; j < clonedInputIds[i].length; ++j) {\n if ((i % this.config.decoder.num_codebooks) >= j) {\n clonedInputIds[i][j] = BigInt(this.config.decoder.pad_token_id);\n }\n }\n }\n // for classifier free guidance we need to replicate the decoder args across the batch dim\n // (we'll split these before sampling)\n if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) {\n // [batch, seqLength] -> [2 * batch, seqLength]\n clonedInputIds = clonedInputIds.concat(clonedInputIds);\n }\n\n const prepped = super.prepare_inputs_for_generation(clonedInputIds, model_inputs, generation_config);\n return prepped;\n }\n\n /**\n * Generates sequences of token ids for models with a language modeling head.\n * @param {import('./generation/parameters.js').GenerationFunctionParameters} options\n * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores.\n */\n async generate(options) {\n\n const output_ids = await super.generate(options);\n\n // apply the pattern mask to the final ids\n // tensor: int64[1,batch_size,4,chunk_length]\n const audio_codes = this._apply_and_filter_by_delay_pattern_mask(\n /** @type {Tensor} */(output_ids)\n ).unsqueeze_(0); // append the frame dimension back to the audio codes\n\n const { audio_values } = await sessionRun(this.sessions['encodec_decode'], { audio_codes })\n\n return audio_values;\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MobileNetV1 models\nexport class MobileNetV1PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.\n */\nexport class MobileNetV1Model extends MobileNetV1PreTrainedModel { }\n\n/**\n * MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features),\n * e.g. for ImageNet.\n */\nexport class MobileNetV1ForImageClassification extends MobileNetV1PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MobileNetV2 models\nexport class MobileNetV2PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MobileNetV2 model outputting raw hidden-states without any specific head on top.\n */\nexport class MobileNetV2Model extends MobileNetV2PreTrainedModel { }\n\n/**\n * MobileNetV2 model with an image classification head on top (a linear layer on top of the pooled features),\n * e.g. for ImageNet.\n */\nexport class MobileNetV2ForImageClassification extends MobileNetV2PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MobileNetV3 models\nexport class MobileNetV3PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MobileNetV3 model outputting raw hidden-states without any specific head on top.\n */\nexport class MobileNetV3Model extends MobileNetV3PreTrainedModel { }\n\n/**\n * MobileNetV3 model with an image classification head on top (a linear layer on top of the pooled features),\n * e.g. for ImageNet.\n */\nexport class MobileNetV3ForImageClassification extends MobileNetV3PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// MobileNetV4 models\nexport class MobileNetV4PreTrainedModel extends PreTrainedModel { }\n\n/**\n * The bare MobileNetV4 model outputting raw hidden-states without any specific head on top.\n */\nexport class MobileNetV4Model extends MobileNetV4PreTrainedModel { }\n\n/**\n * MobileNetV4 model with an image classification head on top (a linear layer on top of the pooled features),\n * e.g. for ImageNet.\n */\nexport class MobileNetV4ForImageClassification extends MobileNetV4PreTrainedModel {\n /**\n * @param {any} model_inputs\n */\n async _call(model_inputs) {\n return new SequenceClassifierOutput(await super._call(model_inputs));\n }\n}\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// Decision Transformer models\nexport class DecisionTransformerPreTrainedModel extends PreTrainedModel { }\n\n/**\n * The model builds upon the GPT2 architecture to perform autoregressive prediction of actions in an offline RL setting.\n * Refer to the paper for more details: https://arxiv.org/abs/2106.01345\n */\nexport class DecisionTransformerModel extends DecisionTransformerPreTrainedModel { }\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\n// AutoModels, used to simplify construction of PreTrainedModels\n// (uses config to instantiate correct class)\n\n/**\n * Base class of all AutoModels. Contains the `from_pretrained` function\n * which is used to instantiate pretrained models.\n */\nexport class PretrainedMixin {\n /**\n * Mapping from model type to model class.\n * @type {Map[]}\n */\n static MODEL_CLASS_MAPPINGS = null;\n\n /**\n * Whether to attempt to instantiate the base class (`PretrainedModel`) if \n * the model type is not found in the mapping.\n */\n static BASE_IF_FAIL = false;\n\n\n /** @type {typeof PreTrainedModel.from_pretrained} */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n model_file_name = null,\n subfolder = 'onnx',\n device = null,\n dtype = null,\n use_external_data_format = null,\n session_options = {},\n } = {}) {\n\n const options = {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n model_file_name,\n subfolder,\n device,\n dtype,\n use_external_data_format,\n session_options,\n }\n options.config = await AutoConfig.from_pretrained(pretrained_model_name_or_path, options);\n\n if (!this.MODEL_CLASS_MAPPINGS) {\n throw new Error(\"`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: \" + this.name);\n }\n\n for (const MODEL_CLASS_MAPPING of this.MODEL_CLASS_MAPPINGS) {\n const modelInfo = MODEL_CLASS_MAPPING.get(options.config.model_type);\n if (!modelInfo) {\n continue; // Item not found in this mapping\n }\n return await modelInfo[1].from_pretrained(pretrained_model_name_or_path, options);\n }\n\n if (this.BASE_IF_FAIL) {\n console.warn(`Unknown model class \"${options.config.model_type}\", attempting to construct from base class.`);\n return await PreTrainedModel.from_pretrained(pretrained_model_name_or_path, options);\n } else {\n throw Error(`Unsupported model type: ${options.config.model_type}`)\n }\n }\n}\n\nconst MODEL_MAPPING_NAMES_ENCODER_ONLY = new Map([\n ['bert', ['BertModel', BertModel]],\n ['nomic_bert', ['NomicBertModel', NomicBertModel]],\n ['roformer', ['RoFormerModel', RoFormerModel]],\n ['electra', ['ElectraModel', ElectraModel]],\n ['esm', ['EsmModel', EsmModel]],\n ['convbert', ['ConvBertModel', ConvBertModel]],\n ['camembert', ['CamembertModel', CamembertModel]],\n ['deberta', ['DebertaModel', DebertaModel]],\n ['deberta-v2', ['DebertaV2Model', DebertaV2Model]],\n ['mpnet', ['MPNetModel', MPNetModel]],\n ['albert', ['AlbertModel', AlbertModel]],\n ['distilbert', ['DistilBertModel', DistilBertModel]],\n ['roberta', ['RobertaModel', RobertaModel]],\n ['xlm', ['XLMModel', XLMModel]],\n ['xlm-roberta', ['XLMRobertaModel', XLMRobertaModel]],\n ['clap', ['ClapModel', ClapModel]],\n ['clip', ['CLIPModel', CLIPModel]],\n ['clipseg', ['CLIPSegModel', CLIPSegModel]],\n ['chinese_clip', ['ChineseCLIPModel', ChineseCLIPModel]],\n ['siglip', ['SiglipModel', SiglipModel]],\n ['mobilebert', ['MobileBertModel', MobileBertModel]],\n ['squeezebert', ['SqueezeBertModel', SqueezeBertModel]],\n ['wav2vec2', ['Wav2Vec2Model', Wav2Vec2Model]],\n ['wav2vec2-bert', ['Wav2Vec2BertModel', Wav2Vec2BertModel]],\n ['unispeech', ['UniSpeechModel', UniSpeechModel]],\n ['unispeech-sat', ['UniSpeechSatModel', UniSpeechSatModel]],\n ['hubert', ['HubertModel', HubertModel]],\n ['wavlm', ['WavLMModel', WavLMModel]],\n ['audio-spectrogram-transformer', ['ASTModel', ASTModel]],\n ['vits', ['VitsModel', VitsModel]],\n ['pyannote', ['PyAnnoteModel', PyAnnoteModel]],\n ['wespeaker-resnet', ['WeSpeakerResNetModel', WeSpeakerResNetModel]],\n\n ['detr', ['DetrModel', DetrModel]],\n ['rt_detr', ['RTDetrModel', RTDetrModel]],\n ['table-transformer', ['TableTransformerModel', TableTransformerModel]],\n ['vit', ['ViTModel', ViTModel]],\n ['pvt', ['PvtModel', PvtModel]],\n ['vit_msn', ['ViTMSNModel', ViTMSNModel]],\n ['vit_mae', ['ViTMAEModel', ViTMAEModel]],\n ['groupvit', ['GroupViTModel', GroupViTModel]],\n ['fastvit', ['FastViTModel', FastViTModel]],\n ['mobilevit', ['MobileViTModel', MobileViTModel]],\n ['mobilevitv2', ['MobileViTV2Model', MobileViTV2Model]],\n ['owlvit', ['OwlViTModel', OwlViTModel]],\n ['owlv2', ['Owlv2Model', Owlv2Model]],\n ['beit', ['BeitModel', BeitModel]],\n ['deit', ['DeiTModel', DeiTModel]],\n ['hiera', ['HieraModel', HieraModel]],\n ['convnext', ['ConvNextModel', ConvNextModel]],\n ['convnextv2', ['ConvNextV2Model', ConvNextV2Model]],\n ['dinov2', ['Dinov2Model', Dinov2Model]],\n ['resnet', ['ResNetModel', ResNetModel]],\n ['swin', ['SwinModel', SwinModel]],\n ['swin2sr', ['Swin2SRModel', Swin2SRModel]],\n ['donut-swin', ['DonutSwinModel', DonutSwinModel]],\n ['yolos', ['YolosModel', YolosModel]],\n ['dpt', ['DPTModel', DPTModel]],\n ['glpn', ['GLPNModel', GLPNModel]],\n\n ['hifigan', ['SpeechT5HifiGan', SpeechT5HifiGan]],\n ['efficientnet', ['EfficientNetModel', EfficientNetModel]],\n\n ['decision_transformer', ['DecisionTransformerModel', DecisionTransformerModel]],\n\n ['mobilenet_v1', ['MobileNetV1Model', MobileNetV1Model]],\n ['mobilenet_v2', ['MobileNetV2Model', MobileNetV2Model]],\n ['mobilenet_v3', ['MobileNetV3Model', MobileNetV3Model]],\n ['mobilenet_v4', ['MobileNetV4Model', MobileNetV4Model]],\n\n ['maskformer', ['MaskFormerModel', MaskFormerModel]],\n]);\n\nconst MODEL_MAPPING_NAMES_ENCODER_DECODER = new Map([\n ['t5', ['T5Model', T5Model]],\n ['longt5', ['LongT5Model', LongT5Model]],\n ['mt5', ['MT5Model', MT5Model]],\n ['bart', ['BartModel', BartModel]],\n ['mbart', ['MBartModel', MBartModel]],\n ['marian', ['MarianModel', MarianModel]],\n ['whisper', ['WhisperModel', WhisperModel]],\n ['m2m_100', ['M2M100Model', M2M100Model]],\n ['blenderbot', ['BlenderbotModel', BlenderbotModel]],\n ['blenderbot-small', ['BlenderbotSmallModel', BlenderbotSmallModel]],\n]);\n\n\nconst MODEL_MAPPING_NAMES_DECODER_ONLY = new Map([\n ['bloom', ['BloomModel', BloomModel]],\n ['jais', ['JAISModel', JAISModel]],\n ['gpt2', ['GPT2Model', GPT2Model]],\n ['gptj', ['GPTJModel', GPTJModel]],\n ['gpt_bigcode', ['GPTBigCodeModel', GPTBigCodeModel]],\n ['gpt_neo', ['GPTNeoModel', GPTNeoModel]],\n ['gpt_neox', ['GPTNeoXModel', GPTNeoXModel]],\n ['codegen', ['CodeGenModel', CodeGenModel]],\n ['llama', ['LlamaModel', LlamaModel]],\n ['granite', ['GraniteModel', GraniteModel]],\n ['cohere', ['CohereModel', CohereModel]],\n ['gemma', ['GemmaModel', GemmaModel]],\n ['gemma2', ['Gemma2Model', Gemma2Model]],\n ['openelm', ['OpenELMModel', OpenELMModel]],\n ['qwen2', ['Qwen2Model', Qwen2Model]],\n ['phi', ['PhiModel', PhiModel]],\n ['phi3', ['Phi3Model', Phi3Model]],\n ['mpt', ['MptModel', MptModel]],\n ['opt', ['OPTModel', OPTModel]],\n ['mistral', ['MistralModel', MistralModel]],\n ['starcoder2', ['Starcoder2Model', Starcoder2Model]],\n ['falcon', ['FalconModel', FalconModel]],\n ['stablelm', ['StableLmModel', StableLmModel]],\n]);\n\nconst MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = new Map([\n ['speecht5', ['SpeechT5ForSpeechToText', SpeechT5ForSpeechToText]],\n ['whisper', ['WhisperForConditionalGeneration', WhisperForConditionalGeneration]],\n]);\n\nconst MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES = new Map([\n ['speecht5', ['SpeechT5ForTextToSpeech', SpeechT5ForTextToSpeech]],\n]);\n\nconst MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES = new Map([\n ['vits', ['VitsModel', VitsModel]],\n ['musicgen', ['MusicgenForConditionalGeneration', MusicgenForConditionalGeneration]],\n]);\n\nconst MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['bert', ['BertForSequenceClassification', BertForSequenceClassification]],\n ['roformer', ['RoFormerForSequenceClassification', RoFormerForSequenceClassification]],\n ['electra', ['ElectraForSequenceClassification', ElectraForSequenceClassification]],\n ['esm', ['EsmForSequenceClassification', EsmForSequenceClassification]],\n ['convbert', ['ConvBertForSequenceClassification', ConvBertForSequenceClassification]],\n ['camembert', ['CamembertForSequenceClassification', CamembertForSequenceClassification]],\n ['deberta', ['DebertaForSequenceClassification', DebertaForSequenceClassification]],\n ['deberta-v2', ['DebertaV2ForSequenceClassification', DebertaV2ForSequenceClassification]],\n ['mpnet', ['MPNetForSequenceClassification', MPNetForSequenceClassification]],\n ['albert', ['AlbertForSequenceClassification', AlbertForSequenceClassification]],\n ['distilbert', ['DistilBertForSequenceClassification', DistilBertForSequenceClassification]],\n ['roberta', ['RobertaForSequenceClassification', RobertaForSequenceClassification]],\n ['xlm', ['XLMForSequenceClassification', XLMForSequenceClassification]],\n ['xlm-roberta', ['XLMRobertaForSequenceClassification', XLMRobertaForSequenceClassification]],\n ['bart', ['BartForSequenceClassification', BartForSequenceClassification]],\n ['mbart', ['MBartForSequenceClassification', MBartForSequenceClassification]],\n ['mobilebert', ['MobileBertForSequenceClassification', MobileBertForSequenceClassification]],\n ['squeezebert', ['SqueezeBertForSequenceClassification', SqueezeBertForSequenceClassification]],\n]);\n\nconst MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['bert', ['BertForTokenClassification', BertForTokenClassification]],\n ['roformer', ['RoFormerForTokenClassification', RoFormerForTokenClassification]],\n ['electra', ['ElectraForTokenClassification', ElectraForTokenClassification]],\n ['esm', ['EsmForTokenClassification', EsmForTokenClassification]],\n ['convbert', ['ConvBertForTokenClassification', ConvBertForTokenClassification]],\n ['camembert', ['CamembertForTokenClassification', CamembertForTokenClassification]],\n ['deberta', ['DebertaForTokenClassification', DebertaForTokenClassification]],\n ['deberta-v2', ['DebertaV2ForTokenClassification', DebertaV2ForTokenClassification]],\n ['mpnet', ['MPNetForTokenClassification', MPNetForTokenClassification]],\n ['distilbert', ['DistilBertForTokenClassification', DistilBertForTokenClassification]],\n ['roberta', ['RobertaForTokenClassification', RobertaForTokenClassification]],\n ['xlm', ['XLMForTokenClassification', XLMForTokenClassification]],\n ['xlm-roberta', ['XLMRobertaForTokenClassification', XLMRobertaForTokenClassification]],\n]);\n\nconst MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = new Map([\n ['t5', ['T5ForConditionalGeneration', T5ForConditionalGeneration]],\n ['longt5', ['LongT5ForConditionalGeneration', LongT5ForConditionalGeneration]],\n ['mt5', ['MT5ForConditionalGeneration', MT5ForConditionalGeneration]],\n ['bart', ['BartForConditionalGeneration', BartForConditionalGeneration]],\n ['mbart', ['MBartForConditionalGeneration', MBartForConditionalGeneration]],\n ['marian', ['MarianMTModel', MarianMTModel]],\n ['m2m_100', ['M2M100ForConditionalGeneration', M2M100ForConditionalGeneration]],\n ['blenderbot', ['BlenderbotForConditionalGeneration', BlenderbotForConditionalGeneration]],\n ['blenderbot-small', ['BlenderbotSmallForConditionalGeneration', BlenderbotSmallForConditionalGeneration]],\n]);\n\nconst MODEL_FOR_CAUSAL_LM_MAPPING_NAMES = new Map([\n ['bloom', ['BloomForCausalLM', BloomForCausalLM]],\n ['gpt2', ['GPT2LMHeadModel', GPT2LMHeadModel]],\n ['jais', ['JAISLMHeadModel', JAISLMHeadModel]],\n ['gptj', ['GPTJForCausalLM', GPTJForCausalLM]],\n ['gpt_bigcode', ['GPTBigCodeForCausalLM', GPTBigCodeForCausalLM]],\n ['gpt_neo', ['GPTNeoForCausalLM', GPTNeoForCausalLM]],\n ['gpt_neox', ['GPTNeoXForCausalLM', GPTNeoXForCausalLM]],\n ['codegen', ['CodeGenForCausalLM', CodeGenForCausalLM]],\n ['llama', ['LlamaForCausalLM', LlamaForCausalLM]],\n ['granite', ['GraniteForCausalLM', GraniteForCausalLM]],\n ['cohere', ['CohereForCausalLM', CohereForCausalLM]],\n ['gemma', ['GemmaForCausalLM', GemmaForCausalLM]],\n ['gemma2', ['Gemma2ForCausalLM', Gemma2ForCausalLM]],\n ['openelm', ['OpenELMForCausalLM', OpenELMForCausalLM]],\n ['qwen2', ['Qwen2ForCausalLM', Qwen2ForCausalLM]],\n ['phi', ['PhiForCausalLM', PhiForCausalLM]],\n ['phi3', ['Phi3ForCausalLM', Phi3ForCausalLM]],\n ['mpt', ['MptForCausalLM', MptForCausalLM]],\n ['opt', ['OPTForCausalLM', OPTForCausalLM]],\n ['mbart', ['MBartForCausalLM', MBartForCausalLM]],\n ['mistral', ['MistralForCausalLM', MistralForCausalLM]],\n ['starcoder2', ['Starcoder2ForCausalLM', Starcoder2ForCausalLM]],\n ['falcon', ['FalconForCausalLM', FalconForCausalLM]],\n ['trocr', ['TrOCRForCausalLM', TrOCRForCausalLM]],\n ['stablelm', ['StableLmForCausalLM', StableLmForCausalLM]],\n]);\n\nconst MODEL_FOR_MASKED_LM_MAPPING_NAMES = new Map([\n ['bert', ['BertForMaskedLM', BertForMaskedLM]],\n ['roformer', ['RoFormerForMaskedLM', RoFormerForMaskedLM]],\n ['electra', ['ElectraForMaskedLM', ElectraForMaskedLM]],\n ['esm', ['EsmForMaskedLM', EsmForMaskedLM]],\n ['convbert', ['ConvBertForMaskedLM', ConvBertForMaskedLM]],\n ['camembert', ['CamembertForMaskedLM', CamembertForMaskedLM]],\n ['deberta', ['DebertaForMaskedLM', DebertaForMaskedLM]],\n ['deberta-v2', ['DebertaV2ForMaskedLM', DebertaV2ForMaskedLM]],\n ['mpnet', ['MPNetForMaskedLM', MPNetForMaskedLM]],\n ['albert', ['AlbertForMaskedLM', AlbertForMaskedLM]],\n ['distilbert', ['DistilBertForMaskedLM', DistilBertForMaskedLM]],\n ['roberta', ['RobertaForMaskedLM', RobertaForMaskedLM]],\n ['xlm', ['XLMWithLMHeadModel', XLMWithLMHeadModel]],\n ['xlm-roberta', ['XLMRobertaForMaskedLM', XLMRobertaForMaskedLM]],\n ['mobilebert', ['MobileBertForMaskedLM', MobileBertForMaskedLM]],\n ['squeezebert', ['SqueezeBertForMaskedLM', SqueezeBertForMaskedLM]],\n]);\n\nconst MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = new Map([\n ['bert', ['BertForQuestionAnswering', BertForQuestionAnswering]],\n ['roformer', ['RoFormerForQuestionAnswering', RoFormerForQuestionAnswering]],\n ['electra', ['ElectraForQuestionAnswering', ElectraForQuestionAnswering]],\n ['convbert', ['ConvBertForQuestionAnswering', ConvBertForQuestionAnswering]],\n ['camembert', ['CamembertForQuestionAnswering', CamembertForQuestionAnswering]],\n ['deberta', ['DebertaForQuestionAnswering', DebertaForQuestionAnswering]],\n ['deberta-v2', ['DebertaV2ForQuestionAnswering', DebertaV2ForQuestionAnswering]],\n ['mpnet', ['MPNetForQuestionAnswering', MPNetForQuestionAnswering]],\n ['albert', ['AlbertForQuestionAnswering', AlbertForQuestionAnswering]],\n ['distilbert', ['DistilBertForQuestionAnswering', DistilBertForQuestionAnswering]],\n ['roberta', ['RobertaForQuestionAnswering', RobertaForQuestionAnswering]],\n ['xlm', ['XLMForQuestionAnswering', XLMForQuestionAnswering]],\n ['xlm-roberta', ['XLMRobertaForQuestionAnswering', XLMRobertaForQuestionAnswering]],\n ['mobilebert', ['MobileBertForQuestionAnswering', MobileBertForQuestionAnswering]],\n ['squeezebert', ['SqueezeBertForQuestionAnswering', SqueezeBertForQuestionAnswering]],\n]);\n\nconst MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = new Map([\n ['vision-encoder-decoder', ['VisionEncoderDecoderModel', VisionEncoderDecoderModel]],\n]);\n\nconst MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES = new Map([\n ['llava', ['LlavaForConditionalGeneration', LlavaForConditionalGeneration]],\n ['moondream1', ['Moondream1ForConditionalGeneration', Moondream1ForConditionalGeneration]],\n ['florence2', ['Florence2ForConditionalGeneration', Florence2ForConditionalGeneration]],\n]);\n\nconst MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES = new Map([\n ['vision-encoder-decoder', ['VisionEncoderDecoderModel', VisionEncoderDecoderModel]],\n]);\n\nconst MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['vit', ['ViTForImageClassification', ViTForImageClassification]],\n ['pvt', ['PvtForImageClassification', PvtForImageClassification]],\n ['vit_msn', ['ViTMSNForImageClassification', ViTMSNForImageClassification]],\n ['fastvit', ['FastViTForImageClassification', FastViTForImageClassification]],\n ['mobilevit', ['MobileViTForImageClassification', MobileViTForImageClassification]],\n ['mobilevitv2', ['MobileViTV2ForImageClassification', MobileViTV2ForImageClassification]],\n ['beit', ['BeitForImageClassification', BeitForImageClassification]],\n ['deit', ['DeiTForImageClassification', DeiTForImageClassification]],\n ['hiera', ['HieraForImageClassification', HieraForImageClassification]],\n ['convnext', ['ConvNextForImageClassification', ConvNextForImageClassification]],\n ['convnextv2', ['ConvNextV2ForImageClassification', ConvNextV2ForImageClassification]],\n ['dinov2', ['Dinov2ForImageClassification', Dinov2ForImageClassification]],\n ['resnet', ['ResNetForImageClassification', ResNetForImageClassification]],\n ['swin', ['SwinForImageClassification', SwinForImageClassification]],\n ['segformer', ['SegformerForImageClassification', SegformerForImageClassification]],\n ['efficientnet', ['EfficientNetForImageClassification', EfficientNetForImageClassification]],\n ['mobilenet_v1', ['MobileNetV1ForImageClassification', MobileNetV1ForImageClassification]],\n ['mobilenet_v2', ['MobileNetV2ForImageClassification', MobileNetV2ForImageClassification]],\n ['mobilenet_v3', ['MobileNetV3ForImageClassification', MobileNetV3ForImageClassification]],\n ['mobilenet_v4', ['MobileNetV4ForImageClassification', MobileNetV4ForImageClassification]],\n]);\n\nconst MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = new Map([\n ['detr', ['DetrForObjectDetection', DetrForObjectDetection]],\n ['rt_detr', ['RTDetrForObjectDetection', RTDetrForObjectDetection]],\n ['table-transformer', ['TableTransformerForObjectDetection', TableTransformerForObjectDetection]],\n ['yolos', ['YolosForObjectDetection', YolosForObjectDetection]],\n]);\n\nconst MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = new Map([\n ['owlvit', ['OwlViTForObjectDetection', OwlViTForObjectDetection]],\n ['owlv2', ['Owlv2ForObjectDetection', Owlv2ForObjectDetection]],\n]);\n\nconst MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = new Map([\n // TODO: Do not add new models here\n ['detr', ['DetrForSegmentation', DetrForSegmentation]],\n ['clipseg', ['CLIPSegForImageSegmentation', CLIPSegForImageSegmentation]],\n]);\n\nconst MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = new Map([\n ['segformer', ['SegformerForSemanticSegmentation', SegformerForSemanticSegmentation]],\n ['sapiens', ['SapiensForSemanticSegmentation', SapiensForSemanticSegmentation]],\n]);\n\nconst MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES = new Map([\n ['detr', ['DetrForSegmentation', DetrForSegmentation]],\n ['maskformer', ['MaskFormerForInstanceSegmentation', MaskFormerForInstanceSegmentation]],\n]);\n\nconst MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = new Map([\n ['sam', ['SamModel', SamModel]],\n]);\n\nconst MODEL_FOR_CTC_MAPPING_NAMES = new Map([\n ['wav2vec2', ['Wav2Vec2ForCTC', Wav2Vec2ForCTC]],\n ['wav2vec2-bert', ['Wav2Vec2BertForCTC', Wav2Vec2BertForCTC]],\n ['unispeech', ['UniSpeechForCTC', UniSpeechForCTC]],\n ['unispeech-sat', ['UniSpeechSatForCTC', UniSpeechSatForCTC]],\n ['wavlm', ['WavLMForCTC', WavLMForCTC]],\n ['hubert', ['HubertForCTC', HubertForCTC]],\n]);\n\nconst MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['wav2vec2', ['Wav2Vec2ForSequenceClassification', Wav2Vec2ForSequenceClassification]],\n ['wav2vec2-bert', ['Wav2Vec2BertForSequenceClassification', Wav2Vec2BertForSequenceClassification]],\n ['unispeech', ['UniSpeechForSequenceClassification', UniSpeechForSequenceClassification]],\n ['unispeech-sat', ['UniSpeechSatForSequenceClassification', UniSpeechSatForSequenceClassification]],\n ['wavlm', ['WavLMForSequenceClassification', WavLMForSequenceClassification]],\n ['hubert', ['HubertForSequenceClassification', HubertForSequenceClassification]],\n ['audio-spectrogram-transformer', ['ASTForAudioClassification', ASTForAudioClassification]],\n]);\n\nconst MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES = new Map([\n ['wavlm', ['WavLMForXVector', WavLMForXVector]],\n]);\n\nconst MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES = new Map([\n ['unispeech-sat', ['UniSpeechSatForAudioFrameClassification', UniSpeechSatForAudioFrameClassification]],\n ['wavlm', ['WavLMForAudioFrameClassification', WavLMForAudioFrameClassification]],\n ['wav2vec2', ['Wav2Vec2ForAudioFrameClassification', Wav2Vec2ForAudioFrameClassification]],\n ['pyannote', ['PyAnnoteForAudioFrameClassification', PyAnnoteForAudioFrameClassification]],\n]);\n\nconst MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES = new Map([\n ['vitmatte', ['VitMatteForImageMatting', VitMatteForImageMatting]],\n]);\n\nconst MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES = new Map([\n ['swin2sr', ['Swin2SRForImageSuperResolution', Swin2SRForImageSuperResolution]],\n])\n\nconst MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = new Map([\n ['dpt', ['DPTForDepthEstimation', DPTForDepthEstimation]],\n ['depth_anything', ['DepthAnythingForDepthEstimation', DepthAnythingForDepthEstimation]],\n ['glpn', ['GLPNForDepthEstimation', GLPNForDepthEstimation]],\n ['sapiens', ['SapiensForDepthEstimation', SapiensForDepthEstimation]],\n ['depth_pro', ['DepthProForDepthEstimation', DepthProForDepthEstimation]],\n])\n\nconst MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES = new Map([\n ['sapiens', ['SapiensForNormalEstimation', SapiensForNormalEstimation]],\n])\n\n// NOTE: This is custom to Transformers.js, and is necessary because certain models\n// (e.g., CLIP) are split into vision and text components\nconst MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES = new Map([\n ['clip', ['CLIPVisionModelWithProjection', CLIPVisionModelWithProjection]],\n ['siglip', ['SiglipVisionModel', SiglipVisionModel]],\n])\n\nconst MODEL_CLASS_TYPE_MAPPING = [\n [MODEL_MAPPING_NAMES_ENCODER_ONLY, MODEL_TYPES.EncoderOnly],\n [MODEL_MAPPING_NAMES_ENCODER_DECODER, MODEL_TYPES.EncoderDecoder],\n [MODEL_MAPPING_NAMES_DECODER_ONLY, MODEL_TYPES.DecoderOnly],\n [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],\n [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],\n [MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.DecoderOnly],\n [MODEL_FOR_MASKED_LM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Vision2Seq],\n [MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES, MODEL_TYPES.ImageTextToText],\n [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES, MODEL_TYPES.MaskGeneration],\n [MODEL_FOR_CTC_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],\n [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n\n // Custom:\n [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],\n];\n\nfor (const [mappings, type] of MODEL_CLASS_TYPE_MAPPING) {\n // @ts-ignore\n for (const [name, model] of mappings.values()) {\n MODEL_TYPE_MAPPING.set(name, type);\n MODEL_CLASS_TO_NAME_MAPPING.set(model, name);\n MODEL_NAME_TO_CLASS_MAPPING.set(name, model);\n }\n}\n\nconst CUSTOM_MAPPING = [\n // OVERRIDE:\n // TODO: Refactor to allow class to specify model\n ['MusicgenForConditionalGeneration', MusicgenForConditionalGeneration, MODEL_TYPES.Musicgen],\n\n ['CLIPTextModelWithProjection', CLIPTextModelWithProjection, MODEL_TYPES.EncoderOnly],\n ['SiglipTextModel', SiglipTextModel, MODEL_TYPES.EncoderOnly],\n ['ClapTextModelWithProjection', ClapTextModelWithProjection, MODEL_TYPES.EncoderOnly],\n ['ClapAudioModelWithProjection', ClapAudioModelWithProjection, MODEL_TYPES.EncoderOnly],\n]\nfor (const [name, model, type] of CUSTOM_MAPPING) {\n MODEL_TYPE_MAPPING.set(name, type);\n MODEL_CLASS_TO_NAME_MAPPING.set(model, name);\n MODEL_NAME_TO_CLASS_MAPPING.set(name, model);\n}\n\n\n/**\n * Helper class which is used to instantiate pretrained models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModel.from_pretrained('Xenova/bert-base-uncased');\n */\nexport class AutoModel extends PretrainedMixin {\n /** @type {Map[]} */\n // @ts-ignore\n static MODEL_CLASS_MAPPINGS = MODEL_CLASS_TYPE_MAPPING.map(x => x[0]);\n static BASE_IF_FAIL = true;\n}\n\n/**\n * Helper class which is used to instantiate pretrained sequence classification models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForSequenceClassification.from_pretrained('Xenova/distilbert-base-uncased-finetuned-sst-2-english');\n */\nexport class AutoModelForSequenceClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained token classification models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForTokenClassification.from_pretrained('Xenova/distilbert-base-multilingual-cased-ner-hrl');\n */\nexport class AutoModelForTokenClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained sequence-to-sequence models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForSeq2SeqLM.from_pretrained('Xenova/t5-small');\n */\nexport class AutoModelForSeq2SeqLM extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained sequence-to-sequence speech-to-text models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForSpeechSeq2Seq.from_pretrained('openai/whisper-tiny.en');\n */\nexport class AutoModelForSpeechSeq2Seq extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained sequence-to-sequence text-to-spectrogram models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForTextToSpectrogram.from_pretrained('microsoft/speecht5_tts');\n */\nexport class AutoModelForTextToSpectrogram extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained text-to-waveform models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForTextToSpectrogram.from_pretrained('facebook/mms-tts-eng');\n */\nexport class AutoModelForTextToWaveform extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained causal language models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForCausalLM.from_pretrained('Xenova/gpt2');\n */\nexport class AutoModelForCausalLM extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_CAUSAL_LM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained masked language models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForMaskedLM.from_pretrained('Xenova/bert-base-uncased');\n */\nexport class AutoModelForMaskedLM extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_MASKED_LM_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained question answering models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForQuestionAnswering.from_pretrained('Xenova/distilbert-base-cased-distilled-squad');\n */\nexport class AutoModelForQuestionAnswering extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained vision-to-sequence models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForVision2Seq.from_pretrained('Xenova/vit-gpt2-image-captioning');\n */\nexport class AutoModelForVision2Seq extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained image classification models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForImageClassification.from_pretrained('Xenova/vit-base-patch16-224');\n */\nexport class AutoModelForImageClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained image segmentation models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForImageSegmentation.from_pretrained('Xenova/detr-resnet-50-panoptic');\n */\nexport class AutoModelForImageSegmentation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained image segmentation models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForSemanticSegmentation.from_pretrained('nvidia/segformer-b3-finetuned-cityscapes-1024-1024');\n */\nexport class AutoModelForSemanticSegmentation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained universal image segmentation models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForUniversalSegmentation.from_pretrained('hf-internal-testing/tiny-random-MaskFormerForInstanceSegmentation');\n */\nexport class AutoModelForUniversalSegmentation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES];\n}\n\n/**\n * Helper class which is used to instantiate pretrained object detection models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForObjectDetection.from_pretrained('Xenova/detr-resnet-50');\n */\nexport class AutoModelForObjectDetection extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES];\n}\n\nexport class AutoModelForZeroShotObjectDetection extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES];\n}\n\n\n/**\n * Helper class which is used to instantiate pretrained mask generation models with the `from_pretrained` function.\n * The chosen model class is determined by the type specified in the model config.\n * \n * @example\n * let model = await AutoModelForMaskGeneration.from_pretrained('Xenova/sam-vit-base');\n */\nexport class AutoModelForMaskGeneration extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForCTC extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_CTC_MAPPING_NAMES];\n}\n\nexport class AutoModelForAudioClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForXVector extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES];\n}\n\nexport class AutoModelForAudioFrameClassification extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForDocumentQuestionAnswering extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES];\n}\n\nexport class AutoModelForImageMatting extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES];\n}\n\nexport class AutoModelForImageToImage extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES];\n}\n\nexport class AutoModelForDepthEstimation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForNormalEstimation extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES];\n}\n\nexport class AutoModelForImageFeatureExtraction extends PretrainedMixin {\n static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES];\n}\n\n//////////////////////////////////////////////////\n\n//////////////////////////////////////////////////\nexport class Seq2SeqLMOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits The output logits of the model.\n * @param {Tensor} output.past_key_values An tensor of key/value pairs that represent the previous state of the model.\n * @param {Tensor} output.encoder_outputs The output of the encoder in a sequence-to-sequence model.\n * @param {Tensor} [output.decoder_attentions] Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.\n * @param {Tensor} [output.cross_attentions] Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.\n */\n constructor({ logits, past_key_values, encoder_outputs, decoder_attentions = null, cross_attentions = null }) {\n super();\n this.logits = logits;\n this.past_key_values = past_key_values;\n this.encoder_outputs = encoder_outputs;\n this.decoder_attentions = decoder_attentions;\n this.cross_attentions = cross_attentions;\n }\n}\n\n/**\n * Base class for outputs of sentence classification models.\n */\nexport class SequenceClassifierOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits classification (or regression if config.num_labels==1) scores (before SoftMax).\n */\n constructor({ logits }) {\n super();\n this.logits = logits;\n }\n}\n\n/**\n * Base class for outputs of XVector models.\n */\nexport class XVectorOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification hidden states before AMSoftmax, of shape `(batch_size, config.xvector_output_dim)`.\n * @param {Tensor} output.embeddings Utterance embeddings used for vector similarity-based retrieval, of shape `(batch_size, config.xvector_output_dim)`.\n */\n constructor({ logits, embeddings }) {\n super();\n this.logits = logits;\n this.embeddings = embeddings;\n }\n}\n\n/**\n * Base class for outputs of token classification models.\n */\nexport class TokenClassifierOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Classification scores (before SoftMax).\n */\n constructor({ logits }) {\n super();\n this.logits = logits;\n }\n}\n\n/**\n * Base class for masked language models outputs.\n */\nexport class MaskedLMOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).\n */\n constructor({ logits }) {\n super();\n this.logits = logits;\n }\n}\n\n/**\n * Base class for outputs of question answering models.\n */\nexport class QuestionAnsweringModelOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.start_logits Span-start scores (before SoftMax).\n * @param {Tensor} output.end_logits Span-end scores (before SoftMax).\n */\n constructor({ start_logits, end_logits }) {\n super();\n this.start_logits = start_logits;\n this.end_logits = end_logits;\n }\n}\n\n\n/**\n * Base class for causal language model (or autoregressive) outputs.\n */\nexport class CausalLMOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax).\n */\n constructor({ logits }) {\n super();\n this.logits = logits;\n }\n}\n\n/**\n * Base class for causal language model (or autoregressive) outputs.\n */\nexport class CausalLMOutputWithPast extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax).\n * @param {Tensor} output.past_key_values Contains pre-computed hidden-states (key and values in the self-attention blocks)\n * that can be used (see `past_key_values` input) to speed up sequential decoding.\n */\n constructor({ logits, past_key_values }) {\n super();\n this.logits = logits;\n this.past_key_values = past_key_values;\n }\n}\n\nexport class ImageMattingOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.alphas Estimated alpha values, of shape `(batch_size, num_channels, height, width)`.\n */\n constructor({ alphas }) {\n super();\n this.alphas = alphas;\n }\n}\n\n/**\n * Describes the outputs for the VITS model.\n */\nexport class VitsModelOutput extends ModelOutput {\n /**\n * @param {Object} output The output of the model.\n * @param {Tensor} output.waveform The final audio waveform predicted by the model, of shape `(batch_size, sequence_length)`.\n * @param {Tensor} output.spectrogram The log-mel spectrogram predicted at the output of the flow model.\n * This spectrogram is passed to the Hi-Fi GAN decoder model to obtain the final audio waveform.\n */\n constructor({ waveform, spectrogram }) {\n super();\n this.waveform = waveform;\n this.spectrogram = spectrogram;\n }\n}\n","\n\nconst WHISPER_LANGUAGES = [\n [\"en\", \"english\"],\n [\"zh\", \"chinese\"],\n [\"de\", \"german\"],\n [\"es\", \"spanish\"],\n [\"ru\", \"russian\"],\n [\"ko\", \"korean\"],\n [\"fr\", \"french\"],\n [\"ja\", \"japanese\"],\n [\"pt\", \"portuguese\"],\n [\"tr\", \"turkish\"],\n [\"pl\", \"polish\"],\n [\"ca\", \"catalan\"],\n [\"nl\", \"dutch\"],\n [\"ar\", \"arabic\"],\n [\"sv\", \"swedish\"],\n [\"it\", \"italian\"],\n [\"id\", \"indonesian\"],\n [\"hi\", \"hindi\"],\n [\"fi\", \"finnish\"],\n [\"vi\", \"vietnamese\"],\n [\"he\", \"hebrew\"],\n [\"uk\", \"ukrainian\"],\n [\"el\", \"greek\"],\n [\"ms\", \"malay\"],\n [\"cs\", \"czech\"],\n [\"ro\", \"romanian\"],\n [\"da\", \"danish\"],\n [\"hu\", \"hungarian\"],\n [\"ta\", \"tamil\"],\n [\"no\", \"norwegian\"],\n [\"th\", \"thai\"],\n [\"ur\", \"urdu\"],\n [\"hr\", \"croatian\"],\n [\"bg\", \"bulgarian\"],\n [\"lt\", \"lithuanian\"],\n [\"la\", \"latin\"],\n [\"mi\", \"maori\"],\n [\"ml\", \"malayalam\"],\n [\"cy\", \"welsh\"],\n [\"sk\", \"slovak\"],\n [\"te\", \"telugu\"],\n [\"fa\", \"persian\"],\n [\"lv\", \"latvian\"],\n [\"bn\", \"bengali\"],\n [\"sr\", \"serbian\"],\n [\"az\", \"azerbaijani\"],\n [\"sl\", \"slovenian\"],\n [\"kn\", \"kannada\"],\n [\"et\", \"estonian\"],\n [\"mk\", \"macedonian\"],\n [\"br\", \"breton\"],\n [\"eu\", \"basque\"],\n [\"is\", \"icelandic\"],\n [\"hy\", \"armenian\"],\n [\"ne\", \"nepali\"],\n [\"mn\", \"mongolian\"],\n [\"bs\", \"bosnian\"],\n [\"kk\", \"kazakh\"],\n [\"sq\", \"albanian\"],\n [\"sw\", \"swahili\"],\n [\"gl\", \"galician\"],\n [\"mr\", \"marathi\"],\n [\"pa\", \"punjabi\"],\n [\"si\", \"sinhala\"],\n [\"km\", \"khmer\"],\n [\"sn\", \"shona\"],\n [\"yo\", \"yoruba\"],\n [\"so\", \"somali\"],\n [\"af\", \"afrikaans\"],\n [\"oc\", \"occitan\"],\n [\"ka\", \"georgian\"],\n [\"be\", \"belarusian\"],\n [\"tg\", \"tajik\"],\n [\"sd\", \"sindhi\"],\n [\"gu\", \"gujarati\"],\n [\"am\", \"amharic\"],\n [\"yi\", \"yiddish\"],\n [\"lo\", \"lao\"],\n [\"uz\", \"uzbek\"],\n [\"fo\", \"faroese\"],\n [\"ht\", \"haitian creole\"],\n [\"ps\", \"pashto\"],\n [\"tk\", \"turkmen\"],\n [\"nn\", \"nynorsk\"],\n [\"mt\", \"maltese\"],\n [\"sa\", \"sanskrit\"],\n [\"lb\", \"luxembourgish\"],\n [\"my\", \"myanmar\"],\n [\"bo\", \"tibetan\"],\n [\"tl\", \"tagalog\"],\n [\"mg\", \"malagasy\"],\n [\"as\", \"assamese\"],\n [\"tt\", \"tatar\"],\n [\"haw\", \"hawaiian\"],\n [\"ln\", \"lingala\"],\n [\"ha\", \"hausa\"],\n [\"ba\", \"bashkir\"],\n [\"jw\", \"javanese\"],\n [\"su\", \"sundanese\"],\n]\n\n// @ts-ignore\nexport const WHISPER_LANGUAGE_MAPPING = new Map(WHISPER_LANGUAGES);\n// @ts-ignore\nexport const WHISPER_TO_LANGUAGE_CODE_MAPPING = new Map([\n ...WHISPER_LANGUAGES.map(([k, v]) => [v, k]),\n ...[\n [\"burmese\", \"my\"],\n [\"valencian\", \"ca\"],\n [\"flemish\", \"nl\"],\n [\"haitian\", \"ht\"],\n [\"letzeburgesch\", \"lb\"],\n [\"pushto\", \"ps\"],\n [\"panjabi\", \"pa\"],\n [\"moldavian\", \"ro\"],\n [\"moldovan\", \"ro\"],\n [\"sinhalese\", \"si\"],\n [\"castilian\", \"es\"],\n ]\n]);\n\n/**\n * @param {string} language The language name or code\n * @returns {string} The language code\n */\nexport function whisper_language_to_code(language) {\n language = language.toLowerCase();\n\n // Map to code from user-friendly name (e.g., \"english\" -> \"en\")\n let language_code = WHISPER_TO_LANGUAGE_CODE_MAPPING.get(language);\n\n if (language_code === undefined) {\n // User provided something that is not a language name\n\n if (WHISPER_LANGUAGE_MAPPING.has(language)) {\n // User provided the language code directly (e.g., \"en\")\n language_code = language;\n\n } else {\n // User provided something that is not a language code or name\n const is_language_code = language.length === 2;\n const langs = is_language_code ? WHISPER_LANGUAGE_MAPPING.keys() : WHISPER_LANGUAGE_MAPPING.values();\n\n throw new Error(`Language \"${language}\" is not supported. Must be one of: ${JSON.stringify(langs)}`);\n }\n }\n return language_code;\n}\n","import { GenerationConfig } from \"../../generation/configuration_utils.js\";\n\nexport class WhisperGenerationConfig extends GenerationConfig {\n\n /**\n * Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`.\n * @type {boolean}\n */\n return_timestamps = null;\n\n /**\n * Whether to return token-level timestamps\n * with the text. This can be used with or without the `return_timestamps` option. To get word-level\n * timestamps, use the tokenizer to group the tokens into words.\n * @type {boolean}\n */\n return_token_timestamps = null;\n\n /**\n * The number of audio frames available in this chunk. This is only used generating word-level timestamps.\n * @type {number}\n */\n num_frames = null;\n\n /**\n * Alignment heads to predict word-level timestamps. This is a list of [layer, head] pairs that\n * select the cross-attention heads that are highly correlated to word-level timing.\n * @type {[number, number][]}\n */\n alignment_heads = null;\n\n /**\n * Task to use for generation, either \"translate\" or \"transcribe\".\n * @type {string}\n */\n task = null;\n\n /**\n * Language token to use for generation, can be either in the form of `<|en|>`, `en` or `english`.\n * You can find all the possible language tokens in the `model.generation_config.lang_to_id` dictionary.\n * @type {string}\n */\n language = null;\n\n /**\n * The id of the `\"<|notimestamps|>\"` token.\n * @type {number}\n */\n no_timestamps_token_id = null;\n\n /**\n * Rank-1 list of token IDs created by passing text to [`~WhisperProcessor.get_prompt_ids`] that is\n * provided as a prompt to each chunk. This can be used to provide or \"prompt-engineer\" a context for\n * transcription, e.g. custom vocabularies or proper nouns to make it more likely to predict those words\n * correctly. It cannot be used in conjunction with `decoder_start_token_id` as it overwrites this value.\n * @type {number[]}\n */\n prompt_ids = null;\n\n /**\n * Whether the model is multilingual or not.\n * @type {boolean}\n */\n is_multilingual = null;\n\n /**\n * (Optional) A mapping from language tokens to their corresponding IDs.\n * Only required if the model is multilingual.\n * @type {Record|null}\n */\n lang_to_id = null;\n\n /**\n * (Optional) A mapping from task tokens to their corresponding IDs.\n * @type {Record|null}\n */\n task_to_id = null;\n\n /**\n * Used to set the maximum value of the initial timestamp. This is used to prevent the model from\n * predicting timestamps that are too far in the future.\n * @type {number}\n */\n max_initial_timestamp_index = 1;\n}\n\n/**\n * @typedef {import('../../generation/parameters.js').GenerationFunctionParameters & {generation_config: WhisperGenerationConfig} & WhisperGenerationConfig} WhisperGenerationFunctionParameters\n */\n","import { createInferenceSession } from \"../backends/onnx.js\";\nimport { Tensor } from \"../utils/tensor.js\";\n\n/**\n * Asynchronously creates a wrapper function for running an ONNX inference session.\n *\n * @param {number[]} session_bytes The session data in bytes.\n * @param {import('onnxruntime-common').InferenceSession.SessionOptions} session_options The options for the ONNX session.\n * @template {string | [string] | string[]} T\n * @param {T} names The name(s) of the output tensor(s).\n * \n * @returns {Promise): Promise>}\n * The wrapper function for running the ONNX inference session.\n */\nconst wrap = async (session_bytes, session_options, names) => {\n const session = await createInferenceSession(\n new Uint8Array(session_bytes), session_options,\n );\n return /** @type {any} */(async (/** @type {Record} */ inputs) => {\n const ortFeed = Object.fromEntries(Object.entries(inputs).map(([k, v]) => [k, v.ort_tensor]));\n const outputs = await session.run(ortFeed);\n\n if (Array.isArray(names)) {\n return names.map((n) => new Tensor(outputs[n]));\n } else {\n return new Tensor(outputs[/** @type {string} */(names)]);\n }\n })\n}\n\n// In-memory registry of initialized ONNX operators\nexport class TensorOpRegistry {\n static session_options = {\n // TODO: Allow for multiple execution providers\n // executionProviders: ['webgpu'],\n };\n\n static get bilinear_interpolate_4d() {\n if (!this._bilinear_interpolate_4d) {\n this._bilinear_interpolate_4d = wrap(\n [8, 9, 18, 0, 58, 128, 1, 10, 40, 10, 1, 120, 10, 0, 10, 0, 10, 1, 115, 18, 1, 121, 34, 6, 82, 101, 115, 105, 122, 101, 42, 17, 10, 4, 109, 111, 100, 101, 34, 6, 108, 105, 110, 101, 97, 114, 160, 1, 3, 18, 1, 114, 90, 31, 10, 1, 120, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 90, 15, 10, 1, 115, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 4, 98, 31, 10, 1, 121, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 66, 2, 16, 20],\n this.session_options,\n 'y',\n );\n }\n return this._bilinear_interpolate_4d;\n }\n\n static get bicubic_interpolate_4d() {\n if (!this._bicubic_interpolate_4d) {\n this._bicubic_interpolate_4d = wrap(\n [8, 9, 18, 0, 58, 127, 10, 39, 10, 1, 120, 10, 0, 10, 0, 10, 1, 115, 18, 1, 121, 34, 6, 82, 101, 115, 105, 122, 101, 42, 16, 10, 4, 109, 111, 100, 101, 34, 5, 99, 117, 98, 105, 99, 160, 1, 3, 18, 1, 114, 90, 31, 10, 1, 120, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 90, 15, 10, 1, 115, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 4, 98, 31, 10, 1, 121, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 66, 2, 16, 20],\n this.session_options,\n 'y',\n );\n }\n return this._bicubic_interpolate_4d;\n }\n\n static get matmul() {\n if (!this._matmul) {\n this._matmul = wrap(\n [8, 9, 18, 0, 58, 55, 10, 17, 10, 1, 97, 10, 1, 98, 18, 1, 99, 34, 6, 77, 97, 116, 77, 117, 108, 18, 1, 114, 90, 9, 10, 1, 97, 18, 4, 10, 2, 8, 1, 90, 9, 10, 1, 98, 18, 4, 10, 2, 8, 1, 98, 9, 10, 1, 99, 18, 4, 10, 2, 8, 1, 66, 2, 16, 20],\n this.session_options,\n 'c',\n );\n }\n return this._matmul;\n }\n\n static get stft() {\n if (!this._stft) {\n this._stft = wrap(\n [8, 7, 18, 0, 58, 148, 1, 10, 38, 10, 1, 115, 10, 1, 106, 10, 1, 119, 10, 1, 108, 18, 1, 111, 34, 4, 83, 84, 70, 84, 42, 15, 10, 8, 111, 110, 101, 115, 105, 100, 101, 100, 24, 1, 160, 1, 2, 18, 1, 115, 90, 26, 10, 1, 115, 18, 21, 10, 19, 8, 1, 18, 15, 10, 3, 18, 1, 98, 10, 3, 18, 1, 115, 10, 3, 18, 1, 99, 90, 11, 10, 1, 106, 18, 6, 10, 4, 8, 7, 18, 0, 90, 16, 10, 1, 119, 18, 11, 10, 9, 8, 1, 18, 5, 10, 3, 18, 1, 119, 90, 11, 10, 1, 108, 18, 6, 10, 4, 8, 7, 18, 0, 98, 31, 10, 1, 111, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 102, 10, 3, 18, 1, 100, 10, 3, 18, 1, 99, 66, 2, 16, 17],\n this.session_options,\n 'o',\n )\n }\n return this._stft;\n }\n\n static get rfft() {\n if (!this._rfft) {\n this._rfft = wrap(\n [8, 9, 18, 0, 58, 97, 10, 33, 10, 1, 120, 10, 0, 10, 1, 97, 18, 1, 121, 34, 3, 68, 70, 84, 42, 15, 10, 8, 111, 110, 101, 115, 105, 100, 101, 100, 24, 1, 160, 1, 2, 18, 1, 100, 90, 21, 10, 1, 120, 18, 16, 10, 14, 8, 1, 18, 10, 10, 3, 18, 1, 115, 10, 3, 18, 1, 99, 90, 11, 10, 1, 97, 18, 6, 10, 4, 8, 7, 18, 0, 98, 21, 10, 1, 121, 18, 16, 10, 14, 8, 1, 18, 10, 10, 3, 18, 1, 115, 10, 3, 18, 1, 99, 66, 2, 16, 20],\n this.session_options,\n 'y',\n )\n }\n return this._rfft;\n }\n\n static get top_k() {\n if (!this._top_k) {\n this._top_k = wrap(\n [8, 10, 18, 0, 58, 73, 10, 18, 10, 1, 120, 10, 1, 107, 18, 1, 118, 18, 1, 105, 34, 4, 84, 111, 112, 75, 18, 1, 116, 90, 9, 10, 1, 120, 18, 4, 10, 2, 8, 1, 90, 15, 10, 1, 107, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 1, 98, 9, 10, 1, 118, 18, 4, 10, 2, 8, 1, 98, 9, 10, 1, 105, 18, 4, 10, 2, 8, 7, 66, 2, 16, 21],\n this.session_options,\n [ /* Values */ 'v', /* Indices */ 'i']\n )\n }\n return this._top_k;\n }\n}\n","/**\n * @file Pipelines provide a high-level, easy to use, API for running machine learning models.\n * \n * **Example:** Instantiate pipeline using the `pipeline` function.\n * ```javascript\n * import { pipeline } from '@huggingface/transformers';\n * \n * const classifier = await pipeline('sentiment-analysis');\n * const output = await classifier('I love transformers!');\n * // [{'label': 'POSITIVE', 'score': 0.999817686}]\n * ```\n * \n * @module pipelines\n */\n\nimport {\n AutoTokenizer,\n PreTrainedTokenizer,\n} from './tokenizers.js';\nimport {\n AutoModel,\n AutoModelForSequenceClassification,\n AutoModelForAudioClassification,\n AutoModelForTokenClassification,\n AutoModelForQuestionAnswering,\n AutoModelForMaskedLM,\n AutoModelForSeq2SeqLM,\n AutoModelForSpeechSeq2Seq,\n AutoModelForTextToWaveform,\n AutoModelForTextToSpectrogram,\n AutoModelForCTC,\n AutoModelForCausalLM,\n AutoModelForVision2Seq,\n AutoModelForImageClassification,\n AutoModelForImageSegmentation,\n AutoModelForSemanticSegmentation,\n AutoModelForUniversalSegmentation,\n AutoModelForObjectDetection,\n AutoModelForZeroShotObjectDetection,\n AutoModelForDocumentQuestionAnswering,\n AutoModelForImageToImage,\n AutoModelForDepthEstimation,\n AutoModelForImageFeatureExtraction,\n PreTrainedModel,\n} from './models.js';\nimport {\n AutoProcessor,\n Processor\n} from './processors.js';\n\nimport {\n Callable,\n} from './utils/generic.js';\n\nimport {\n dispatchCallback,\n pop,\n product,\n} from './utils/core.js';\nimport {\n softmax,\n max,\n round,\n} from './utils/maths.js';\nimport {\n read_audio\n} from './utils/audio.js';\nimport {\n Tensor,\n mean_pooling,\n interpolate,\n quantize_embeddings,\n topk,\n} from './utils/tensor.js';\nimport { RawImage } from './utils/image.js';\n\n\n/**\n * @typedef {string | RawImage | URL} ImageInput\n * @typedef {ImageInput|ImageInput[]} ImagePipelineInputs\n */\n\n/**\n * Prepare images for further tasks.\n * @param {ImagePipelineInputs} images images to prepare.\n * @returns {Promise} returns processed images.\n * @private\n */\nasync function prepareImages(images) {\n if (!Array.isArray(images)) {\n images = [images];\n }\n\n // Possibly convert any non-images to images\n return await Promise.all(images.map(x => RawImage.read(x)));\n}\n\n/**\n * @typedef {string | URL | Float32Array | Float64Array} AudioInput\n * @typedef {AudioInput|AudioInput[]} AudioPipelineInputs\n */\n\n/**\n * Prepare audios for further tasks.\n * @param {AudioPipelineInputs} audios audios to prepare.\n * @param {number} sampling_rate sampling rate of the audios.\n * @returns {Promise} The preprocessed audio data.\n * @private\n */\nasync function prepareAudios(audios, sampling_rate) {\n if (!Array.isArray(audios)) {\n audios = [audios];\n }\n\n return await Promise.all(audios.map(x => {\n if (typeof x === 'string' || x instanceof URL) {\n return read_audio(x, sampling_rate);\n } else if (x instanceof Float64Array) {\n return new Float32Array(x);\n }\n return x;\n }));\n}\n\n/**\n * @typedef {Object} BoundingBox\n * @property {number} xmin The minimum x coordinate of the bounding box.\n * @property {number} ymin The minimum y coordinate of the bounding box.\n * @property {number} xmax The maximum x coordinate of the bounding box.\n * @property {number} ymax The maximum y coordinate of the bounding box.\n */\n\n/**\n * Helper function to convert list [xmin, xmax, ymin, ymax] into object { \"xmin\": xmin, ... }\n * @param {number[]} box The bounding box as a list.\n * @param {boolean} asInteger Whether to cast to integers.\n * @returns {BoundingBox} The bounding box as an object.\n * @private\n */\nfunction get_bounding_box(box, asInteger) {\n if (asInteger) {\n box = box.map(x => x | 0);\n }\n const [xmin, ymin, xmax, ymax] = box;\n\n return { xmin, ymin, xmax, ymax };\n}\n\n\n/**\n * @callback DisposeType Disposes the item.\n * @returns {Promise} A promise that resolves when the item has been disposed.\n * \n * @typedef {Object} Disposable\n * @property {DisposeType} dispose A promise that resolves when the pipeline has been disposed.\n */\n\n/**\n * The Pipeline class is the class from which all pipelines inherit.\n * Refer to this class for methods shared across different pipelines.\n * @extends Callable\n */\nexport class Pipeline extends Callable {\n /**\n * Create a new Pipeline.\n * @param {Object} options An object containing the following properties:\n * @param {string} [options.task] The task of the pipeline. Useful for specifying subtasks.\n * @param {PreTrainedModel} [options.model] The model used by the pipeline.\n * @param {PreTrainedTokenizer} [options.tokenizer=null] The tokenizer used by the pipeline (if any).\n * @param {Processor} [options.processor=null] The processor used by the pipeline (if any).\n */\n constructor({ task, model, tokenizer = null, processor = null }) {\n super();\n this.task = task;\n this.model = model;\n this.tokenizer = tokenizer;\n this.processor = processor;\n }\n\n /** @type {DisposeType} */\n async dispose() {\n await this.model.dispose();\n }\n}\n\n/**\n * @typedef {Object} ModelTokenizerConstructorArgs\n * @property {string} task The task of the pipeline. Useful for specifying subtasks.\n * @property {PreTrainedModel} model The model used by the pipeline.\n * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline.\n * \n * @typedef {ModelTokenizerConstructorArgs} TextPipelineConstructorArgs An object used to instantiate a text-based pipeline.\n */\n\n/**\n * @typedef {Object} ModelProcessorConstructorArgs\n * @property {string} task The task of the pipeline. Useful for specifying subtasks.\n * @property {PreTrainedModel} model The model used by the pipeline.\n * @property {Processor} processor The processor used by the pipeline.\n * \n * @typedef {ModelProcessorConstructorArgs} AudioPipelineConstructorArgs An object used to instantiate an audio-based pipeline.\n * @typedef {ModelProcessorConstructorArgs} ImagePipelineConstructorArgs An object used to instantiate an image-based pipeline.\n */\n\n\n/**\n * @typedef {Object} ModelTokenizerProcessorConstructorArgs\n * @property {string} task The task of the pipeline. Useful for specifying subtasks.\n * @property {PreTrainedModel} model The model used by the pipeline.\n * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline.\n * @property {Processor} processor The processor used by the pipeline.\n * \n * @typedef {ModelTokenizerProcessorConstructorArgs} TextAudioPipelineConstructorArgs An object used to instantiate a text- and audio-based pipeline.\n * @typedef {ModelTokenizerProcessorConstructorArgs} TextImagePipelineConstructorArgs An object used to instantiate a text- and image-based pipeline.\n */\n\n/**\n * @typedef {Object} TextClassificationSingle\n * @property {string} label The label predicted.\n * @property {number} score The corresponding probability.\n * @typedef {TextClassificationSingle[]} TextClassificationOutput\n * \n * @typedef {Object} TextClassificationPipelineOptions Parameters specific to text classification pipelines.\n * @property {number} [top_k=1] The number of top predictions to be returned.\n * \n * @callback TextClassificationPipelineCallback Classify the text(s) given as inputs.\n * @param {string|string[]} texts The input text(s) to be classified.\n * @param {TextClassificationPipelineOptions} [options] The options to use for text classification.\n * @returns {Promise} An array or object containing the predicted labels and scores.\n * \n * @typedef {TextPipelineConstructorArgs & TextClassificationPipelineCallback & Disposable} TextClassificationPipelineType\n */\n\n/**\n * Text classification pipeline using any `ModelForSequenceClassification`.\n *\n * **Example:** Sentiment-analysis w/ `Xenova/distilbert-base-uncased-finetuned-sst-2-english`.\n * ```javascript\n * const classifier = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english');\n * const output = await classifier('I love transformers!');\n * // [{ label: 'POSITIVE', score: 0.999788761138916 }]\n * ```\n * \n * **Example:** Multilingual sentiment-analysis w/ `Xenova/bert-base-multilingual-uncased-sentiment` (and return top 5 classes).\n * ```javascript\n * const classifier = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment');\n * const output = await classifier('Le meilleur film de tous les temps.', { top_k: 5 });\n * // [\n * // { label: '5 stars', score: 0.9610759615898132 },\n * // { label: '4 stars', score: 0.03323351591825485 },\n * // { label: '3 stars', score: 0.0036155181005597115 },\n * // { label: '1 star', score: 0.0011325967498123646 },\n * // { label: '2 stars', score: 0.0009423971059732139 }\n * // ]\n * ```\n * \n * **Example:** Toxic comment classification w/ `Xenova/toxic-bert` (and return all classes).\n * ```javascript\n * const classifier = await pipeline('text-classification', 'Xenova/toxic-bert');\n * const output = await classifier('I hate you!', { top_k: null });\n * // [\n * // { label: 'toxic', score: 0.9593140482902527 },\n * // { label: 'insult', score: 0.16187334060668945 },\n * // { label: 'obscene', score: 0.03452680632472038 },\n * // { label: 'identity_hate', score: 0.0223250575363636 },\n * // { label: 'threat', score: 0.019197041168808937 },\n * // { label: 'severe_toxic', score: 0.005651099607348442 }\n * // ]\n * ```\n */\nexport class TextClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TextClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new TextClassificationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {TextClassificationPipelineCallback} */\n async _call(texts, {\n top_k = 1\n } = {}) {\n\n // Run tokenization\n const model_inputs = this.tokenizer(texts, {\n padding: true,\n truncation: true,\n });\n\n // Run model\n const outputs = await this.model(model_inputs)\n\n // TODO: Use softmax tensor function\n const function_to_apply =\n this.model.config.problem_type === 'multi_label_classification'\n ? batch => batch.sigmoid()\n : batch => new Tensor(\n 'float32',\n softmax(batch.data),\n batch.dims,\n ); // single_label_classification (default)\n\n const id2label = this.model.config.id2label;\n\n const toReturn = [];\n for (const batch of outputs.logits) {\n const output = function_to_apply(batch);\n\n const scores = await topk(output, top_k);\n\n const values = scores[0].tolist();\n const indices = scores[1].tolist();\n const vals = indices.map((x, i) => ({\n label: id2label ? id2label[x] : `LABEL_${x}`,\n score: values[i],\n }));\n if (top_k === 1) {\n toReturn.push(...vals);\n } else {\n toReturn.push(vals);\n }\n }\n\n return Array.isArray(texts) || top_k === 1 ? /** @type {TextClassificationOutput} */ (toReturn) : /** @type {TextClassificationOutput[]} */ (toReturn)[0];\n }\n}\n\n/**\n * @typedef {Object} TokenClassificationSingle\n * @property {string} word The token/word classified. This is obtained by decoding the selected tokens.\n * @property {number} score The corresponding probability for `entity`.\n * @property {string} entity The entity predicted for that token/word.\n * @property {number} index The index of the corresponding token in the sentence.\n * @property {number} [start] The index of the start of the corresponding entity in the sentence.\n * @property {number} [end] The index of the end of the corresponding entity in the sentence.\n * @typedef {TokenClassificationSingle[]} TokenClassificationOutput\n * \n * @typedef {Object} TokenClassificationPipelineOptions Parameters specific to token classification pipelines.\n * @property {string[]} [ignore_labels] A list of labels to ignore.\n * \n * @callback TokenClassificationPipelineCallback Classify each token of the text(s) given as inputs.\n * @param {string|string[]} texts One or several texts (or one list of texts) for token classification.\n * @param {TokenClassificationPipelineOptions} [options] The options to use for token classification.\n * @returns {Promise} The result.\n * \n * @typedef {TextPipelineConstructorArgs & TokenClassificationPipelineCallback & Disposable} TokenClassificationPipelineType\n */\n\n/**\n * Named Entity Recognition pipeline using any `ModelForTokenClassification`.\n * \n * **Example:** Perform named entity recognition with `Xenova/bert-base-NER`.\n * ```javascript\n * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER');\n * const output = await classifier('My name is Sarah and I live in London');\n * // [\n * // { entity: 'B-PER', score: 0.9980202913284302, index: 4, word: 'Sarah' },\n * // { entity: 'B-LOC', score: 0.9994474053382874, index: 9, word: 'London' }\n * // ]\n * ```\n * \n * **Example:** Perform named entity recognition with `Xenova/bert-base-NER` (and return all labels).\n * ```javascript\n * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER');\n * const output = await classifier('Sarah lives in the United States of America', { ignore_labels: [] });\n * // [\n * // { entity: 'B-PER', score: 0.9966587424278259, index: 1, word: 'Sarah' },\n * // { entity: 'O', score: 0.9987385869026184, index: 2, word: 'lives' },\n * // { entity: 'O', score: 0.9990072846412659, index: 3, word: 'in' },\n * // { entity: 'O', score: 0.9988298416137695, index: 4, word: 'the' },\n * // { entity: 'B-LOC', score: 0.9995510578155518, index: 5, word: 'United' },\n * // { entity: 'I-LOC', score: 0.9990395307540894, index: 6, word: 'States' },\n * // { entity: 'I-LOC', score: 0.9986724853515625, index: 7, word: 'of' },\n * // { entity: 'I-LOC', score: 0.9975294470787048, index: 8, word: 'America' }\n * // ]\n * ```\n */\nexport class TokenClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TokenClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new TokenClassificationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {TokenClassificationPipelineCallback} */\n async _call(texts, {\n ignore_labels = ['O'],\n } = {}) {\n\n const isBatched = Array.isArray(texts);\n\n // Run tokenization\n const model_inputs = this.tokenizer(isBatched ? texts : [texts], {\n padding: true,\n truncation: true,\n });\n\n // Run model\n const outputs = await this.model(model_inputs)\n\n const logits = outputs.logits;\n const id2label = this.model.config.id2label;\n\n const toReturn = [];\n for (let i = 0; i < logits.dims[0]; ++i) {\n const ids = model_inputs.input_ids[i];\n const batch = logits[i];\n\n // List of tokens that aren't ignored\n const tokens = [];\n for (let j = 0; j < batch.dims[0]; ++j) {\n const tokenData = batch[j];\n const topScoreIndex = max(tokenData.data)[1];\n\n const entity = id2label ? id2label[topScoreIndex] : `LABEL_${topScoreIndex}`;\n if (ignore_labels.includes(entity)) {\n // We predicted a token that should be ignored. So, we skip it.\n continue;\n }\n\n // TODO add option to keep special tokens?\n const word = this.tokenizer.decode([ids[j].item()], { skip_special_tokens: true });\n if (word === '') {\n // Was a special token. So, we skip it.\n continue;\n }\n\n const scores = softmax(tokenData.data);\n\n tokens.push({\n entity: entity,\n score: scores[topScoreIndex],\n index: j,\n word: word,\n\n // TODO: Add support for start and end\n // start: null,\n // end: null,\n });\n }\n toReturn.push(tokens);\n }\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} QuestionAnsweringOutput\n * @property {number} score The probability associated to the answer.\n * @property {number} [start] The character start index of the answer (in the tokenized version of the input).\n * @property {number} [end] The character end index of the answer (in the tokenized version of the input).\n * @property {string} answer The answer to the question.\n * \n * @typedef {Object} QuestionAnsweringPipelineOptions Parameters specific to question answering pipelines.\n * @property {number} [top_k=1] The number of top answer predictions to be returned.\n * \n * @callback QuestionAnsweringPipelineCallback Answer the question(s) given as inputs by using the context(s).\n * @param {string|string[]} question One or several question(s) (must be used in conjunction with the `context` argument).\n * @param {string|string[]} context One or several context(s) associated with the question(s) (must be used in conjunction with the `question` argument).\n * @param {QuestionAnsweringPipelineOptions} [options] The options to use for question answering.\n * @returns {Promise} An array or object containing the predicted answers and scores.\n * \n * @typedef {TextPipelineConstructorArgs & QuestionAnsweringPipelineCallback & Disposable} QuestionAnsweringPipelineType\n */\n\n/**\n * Question Answering pipeline using any `ModelForQuestionAnswering`.\n * \n * **Example:** Run question answering with `Xenova/distilbert-base-uncased-distilled-squad`.\n * ```javascript\n * const answerer = await pipeline('question-answering', 'Xenova/distilbert-base-uncased-distilled-squad');\n * const question = 'Who was Jim Henson?';\n * const context = 'Jim Henson was a nice puppet.';\n * const output = await answerer(question, context);\n * // {\n * // answer: \"a nice puppet\",\n * // score: 0.5768911502526741\n * // }\n * ```\n */\nexport class QuestionAnsweringPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => QuestionAnsweringPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new QuestionAnsweringPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {QuestionAnsweringPipelineCallback} */\n async _call(question, context, {\n top_k = 1\n } = {}) {\n\n // Run tokenization\n const inputs = this.tokenizer(question, {\n text_pair: context,\n padding: true,\n truncation: true,\n });\n\n const { start_logits, end_logits } = await this.model(inputs);\n const input_ids = inputs.input_ids.tolist();\n const attention_mask = inputs.attention_mask.tolist();\n\n // TODO: add support for `return_special_tokens_mask`\n const special_tokens = this.tokenizer.all_special_ids;\n\n /** @type {QuestionAnsweringOutput[]} */\n const toReturn = [];\n for (let j = 0; j < start_logits.dims[0]; ++j) {\n const ids = input_ids[j];\n const sepIndex = ids.findIndex(x =>\n // We use == to match bigint with number\n // @ts-ignore\n x == this.tokenizer.sep_token_id\n );\n\n\n const valid_mask = attention_mask[j].map((y, ix) => (\n y == 1\n && (\n ix === 0 // is cls_token\n || (\n ix > sepIndex\n && special_tokens.findIndex(x => x == ids[ix]) === -1 // token is not a special token (special_tokens_mask == 0)\n )\n )\n ));\n\n const start = start_logits[j].tolist();\n const end = end_logits[j].tolist();\n\n // Now, we mask out values that can't be in the answer\n // NOTE: We keep the cls_token unmasked (some models use it to indicate unanswerable questions)\n for (let i = 1; i < start.length; ++i) {\n if (\n attention_mask[j] == 0 // is part of padding\n || i <= sepIndex // is before the sep_token\n || special_tokens.findIndex(x => x == ids[i]) !== -1 // Is a special token\n ) {\n // Make sure non-context indexes in the tensor cannot contribute to the softmax\n start[i] = -Infinity;\n end[i] = -Infinity;\n }\n }\n\n // Normalize logits and spans to retrieve the answer\n const start_scores = softmax(start).map((x, i) => [x, i]);\n const end_scores = softmax(end).map((x, i) => [x, i]);\n\n // Mask CLS\n start_scores[0][0] = 0;\n end_scores[0][0] = 0;\n\n // Generate all valid spans and select best ones\n const options = product(start_scores, end_scores)\n .filter(x => x[0][1] <= x[1][1])\n .map(x => [x[0][1], x[1][1], x[0][0] * x[1][0]])\n .sort((a, b) => b[2] - a[2]);\n\n for (let k = 0; k < Math.min(options.length, top_k); ++k) {\n const [start, end, score] = options[k];\n\n const answer_tokens = ids.slice(start, end + 1)\n\n const answer = this.tokenizer.decode(answer_tokens, {\n skip_special_tokens: true,\n });\n\n // TODO add start and end?\n // NOTE: HF returns character index\n toReturn.push({\n answer, score\n });\n }\n }\n\n // Mimic HF's return type based on top_k\n return (top_k === 1) ? toReturn[0] : toReturn;\n }\n}\n\n\n/**\n * @typedef {Object} FillMaskSingle\n * @property {string} sequence The corresponding input with the mask token prediction.\n * @property {number} score The corresponding probability.\n * @property {number} token The predicted token id (to replace the masked one).\n * @property {string} token_str The predicted token (to replace the masked one).\n * @typedef {FillMaskSingle[]} FillMaskOutput\n * \n * @typedef {Object} FillMaskPipelineOptions Parameters specific to fill mask pipelines.\n * @property {number} [top_k=5] When passed, overrides the number of predictions to return.\n * \n * @callback FillMaskPipelineCallback Fill the masked token in the text(s) given as inputs.\n * @param {string|string[]} texts One or several texts (or one list of prompts) with masked tokens.\n * @param {FillMaskPipelineOptions} [options] The options to use for masked language modelling.\n * @returns {Promise} An array of objects containing the score, predicted token, predicted token string,\n * and the sequence with the predicted token filled in, or an array of such arrays (one for each input text).\n * If only one input text is given, the output will be an array of objects.\n * @throws {Error} When the mask token is not found in the input text.\n * \n * @typedef {TextPipelineConstructorArgs & FillMaskPipelineCallback & Disposable} FillMaskPipelineType\n */\n\n/**\n * Masked language modeling prediction pipeline using any `ModelWithLMHead`.\n * \n * **Example:** Perform masked language modelling (a.k.a. \"fill-mask\") with `Xenova/bert-base-uncased`.\n * ```javascript\n * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased');\n * const output = await unmasker('The goal of life is [MASK].');\n * // [\n * // { token_str: 'survival', score: 0.06137419492006302, token: 8115, sequence: 'The goal of life is survival.' },\n * // { token_str: 'love', score: 0.03902450203895569, token: 1567, sequence: 'The goal of life is love.' },\n * // { token_str: 'happiness', score: 0.03253183513879776, token: 9266, sequence: 'The goal of life is happiness.' },\n * // { token_str: 'freedom', score: 0.018736306577920914, token: 4438, sequence: 'The goal of life is freedom.' },\n * // { token_str: 'life', score: 0.01859794743359089, token: 1297, sequence: 'The goal of life is life.' }\n * // ]\n * ```\n * \n * **Example:** Perform masked language modelling (a.k.a. \"fill-mask\") with `Xenova/bert-base-cased` (and return top result).\n * ```javascript\n * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased');\n * const output = await unmasker('The Milky Way is a [MASK] galaxy.', { top_k: 1 });\n * // [{ token_str: 'spiral', score: 0.6299987435340881, token: 14061, sequence: 'The Milky Way is a spiral galaxy.' }]\n * ```\n */\nexport class FillMaskPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => FillMaskPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new FillMaskPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {FillMaskPipelineCallback} */\n async _call(texts, {\n top_k = 5\n } = {}) {\n\n // Run tokenization\n const model_inputs = this.tokenizer(texts, {\n padding: true,\n truncation: true,\n });\n\n // Run model\n const { logits } = await this.model(model_inputs)\n\n const toReturn = [];\n\n /** @type {bigint[][]} */\n const input_ids = model_inputs.input_ids.tolist();\n for (let i = 0; i < input_ids.length; ++i) {\n const ids = input_ids[i];\n const mask_token_index = ids.findIndex(x =>\n // We use == to match bigint with number\n // @ts-ignore\n x == this.tokenizer.mask_token_id\n );\n if (mask_token_index === -1) {\n throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`)\n }\n const itemLogits = logits[i][mask_token_index];\n\n const scores = await topk(new Tensor(\n 'float32',\n softmax(itemLogits.data),\n itemLogits.dims,\n ), top_k);\n const values = scores[0].tolist();\n const indices = scores[1].tolist();\n\n toReturn.push(indices.map((x, i) => {\n const sequence = ids.slice();\n sequence[mask_token_index] = x;\n\n return {\n score: values[i],\n token: Number(x),\n token_str: this.tokenizer.model.vocab[x],\n sequence: this.tokenizer.decode(sequence, { skip_special_tokens: true }),\n }\n }));\n }\n return Array.isArray(texts) ? toReturn : toReturn[0];\n }\n}\n\n\n/**\n * @typedef {Object} Text2TextGenerationSingle\n * @property {string} generated_text The generated text.\n * @typedef {Text2TextGenerationSingle[]} Text2TextGenerationOutput\n * \n * @callback Text2TextGenerationPipelineCallback Generate the output text(s) using text(s) given as inputs.\n * @param {string|string[]} texts Input text for the encoder.\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise}\n * \n * @typedef {TextPipelineConstructorArgs & Text2TextGenerationPipelineCallback & Disposable} Text2TextGenerationPipelineType\n */\n\n/**\n * Text2TextGenerationPipeline class for generating text using a model that performs text-to-text generation tasks.\n * \n * **Example:** Text-to-text generation w/ `Xenova/LaMini-Flan-T5-783M`.\n * ```javascript\n * const generator = await pipeline('text2text-generation', 'Xenova/LaMini-Flan-T5-783M');\n * const output = await generator('how can I become more healthy?', {\n * max_new_tokens: 100,\n * });\n * // [{ generated_text: \"To become more healthy, you can: 1. Eat a balanced diet with plenty of fruits, vegetables, whole grains, lean proteins, and healthy fats. 2. Stay hydrated by drinking plenty of water. 3. Get enough sleep and manage stress levels. 4. Avoid smoking and excessive alcohol consumption. 5. Regularly exercise and maintain a healthy weight. 6. Practice good hygiene and sanitation. 7. Seek medical attention if you experience any health issues.\" }]\n * ```\n */\nexport class Text2TextGenerationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => Text2TextGenerationPipelineType} */ (Pipeline)) {\n /** @type {'generated_text'} */\n _key = 'generated_text';\n\n /**\n * Create a new Text2TextGenerationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {Text2TextGenerationPipelineCallback} */\n async _call(texts, generate_kwargs = {}) {\n if (!Array.isArray(texts)) {\n texts = [texts];\n }\n\n\n // Add global prefix, if present\n if (this.model.config.prefix) {\n texts = texts.map(x => this.model.config.prefix + x)\n }\n\n // Handle task specific params:\n const task_specific_params = this.model.config.task_specific_params\n if (task_specific_params && task_specific_params[this.task]) {\n // Add prefixes, if present\n if (task_specific_params[this.task].prefix) {\n texts = texts.map(x => task_specific_params[this.task].prefix + x)\n }\n\n // TODO update generation config\n }\n\n const tokenizer = this.tokenizer;\n const tokenizer_options = {\n padding: true,\n truncation: true,\n }\n let inputs;\n if (this instanceof TranslationPipeline && '_build_translation_inputs' in tokenizer) {\n // TODO: move to Translation pipeline?\n // Currently put here to avoid code duplication\n // @ts-ignore\n inputs = tokenizer._build_translation_inputs(texts, tokenizer_options, generate_kwargs);\n\n } else {\n inputs = tokenizer(texts, tokenizer_options);\n }\n\n const outputTokenIds = await this.model.generate({ ...inputs, ...generate_kwargs });\n return tokenizer.batch_decode(/** @type {Tensor} */(outputTokenIds), {\n skip_special_tokens: true,\n }).map(text => ({ [this._key]: text }));\n }\n}\n\n\n/**\n * @typedef {Object} SummarizationSingle\n * @property {string} summary_text The summary text.\n * @typedef {SummarizationSingle[]} SummarizationOutput\n * \n * @callback SummarizationPipelineCallback Summarize the text(s) given as inputs.\n * @param {string|string[]} texts One or several articles (or one list of articles) to summarize.\n * @param {import('./generation/configuration_utils.js').GenerationConfig} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise}\n * \n * @typedef {TextPipelineConstructorArgs & SummarizationPipelineCallback & Disposable} SummarizationPipelineType\n */\n\n/**\n * A pipeline for summarization tasks, inheriting from Text2TextGenerationPipeline.\n * \n * **Example:** Summarization w/ `Xenova/distilbart-cnn-6-6`.\n * ```javascript\n * const generator = await pipeline('summarization', 'Xenova/distilbart-cnn-6-6');\n * const text = 'The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, ' +\n * 'and the tallest structure in Paris. Its base is square, measuring 125 metres (410 ft) on each side. ' +\n * 'During its construction, the Eiffel Tower surpassed the Washington Monument to become the tallest ' +\n * 'man-made structure in the world, a title it held for 41 years until the Chrysler Building in New ' +\n * 'York City was finished in 1930. It was the first structure to reach a height of 300 metres. Due to ' +\n * 'the addition of a broadcasting aerial at the top of the tower in 1957, it is now taller than the ' +\n * 'Chrysler Building by 5.2 metres (17 ft). Excluding transmitters, the Eiffel Tower is the second ' +\n * 'tallest free-standing structure in France after the Millau Viaduct.';\n * const output = await generator(text, {\n * max_new_tokens: 100,\n * });\n * // [{ summary_text: ' The Eiffel Tower is about the same height as an 81-storey building and the tallest structure in Paris. It is the second tallest free-standing structure in France after the Millau Viaduct.' }]\n * ```\n */\nexport class SummarizationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => SummarizationPipelineType} */ (/** @type {any} */ (Text2TextGenerationPipeline))) {\n /** @type {'summary_text'} */\n _key = 'summary_text';\n\n /**\n * Create a new SummarizationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n}\n\n\n/**\n * @typedef {Object} TranslationSingle\n * @property {string} translation_text The translated text.\n * @typedef {TranslationSingle[]} TranslationOutput\n * \n * @callback TranslationPipelineCallback Translate the text(s) given as inputs.\n * @param {string|string[]} texts Texts to be translated.\n * @param {import('./generation/configuration_utils.js').GenerationConfig} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise}\n * \n * @typedef {TextPipelineConstructorArgs & TranslationPipelineCallback & Disposable} TranslationPipelineType\n */\n\n/**\n * Translates text from one language to another.\n * \n * **Example:** Multilingual translation w/ `Xenova/nllb-200-distilled-600M`.\n * \n * See [here](https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200)\n * for the full list of languages and their corresponding codes.\n * \n * ```javascript\n * const translator = await pipeline('translation', 'Xenova/nllb-200-distilled-600M');\n * const output = await translator('जीवन एक चॉकलेट बॉक्स की तरह है।', {\n * src_lang: 'hin_Deva', // Hindi\n * tgt_lang: 'fra_Latn', // French\n * });\n * // [{ translation_text: 'La vie est comme une boîte à chocolat.' }]\n * ```\n * \n * **Example:** Multilingual translation w/ `Xenova/m2m100_418M`.\n * \n * See [here](https://huggingface.co/facebook/m2m100_418M#languages-covered)\n * for the full list of languages and their corresponding codes.\n * \n * ```javascript\n * const translator = await pipeline('translation', 'Xenova/m2m100_418M');\n * const output = await translator('生活就像一盒巧克力。', {\n * src_lang: 'zh', // Chinese\n * tgt_lang: 'en', // English\n * });\n * // [{ translation_text: 'Life is like a box of chocolate.' }]\n * ```\n * \n * **Example:** Multilingual translation w/ `Xenova/mbart-large-50-many-to-many-mmt`.\n * \n * See [here](https://huggingface.co/facebook/mbart-large-50-many-to-many-mmt#languages-covered)\n * for the full list of languages and their corresponding codes.\n * \n * ```javascript\n * const translator = await pipeline('translation', 'Xenova/mbart-large-50-many-to-many-mmt');\n * const output = await translator('संयुक्त राष्ट्र के प्रमुख का कहना है कि सीरिया में कोई सैन्य समाधान नहीं है', {\n * src_lang: 'hi_IN', // Hindi\n * tgt_lang: 'fr_XX', // French\n * });\n * // [{ translation_text: 'Le chef des Nations affirme qu 'il n 'y a military solution in Syria.' }]\n * ```\n */\nexport class TranslationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TranslationPipelineType} */ (/** @type {any} */ (Text2TextGenerationPipeline))) {\n /** @type {'translation_text'} */\n _key = 'translation_text';\n\n /**\n * Create a new TranslationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n}\n\nfunction isChat(x) {\n return Array.isArray(x) && x.every(x => 'role' in x && 'content' in x);\n}\n\n/**\n * @typedef {import('./tokenizers.js').Message[]} Chat\n * \n * @typedef {Object} TextGenerationSingle\n * @property {string|Chat} generated_text The generated text.\n * @typedef {TextGenerationSingle[]} TextGenerationOutput\n * \n * @typedef {Object} TextGenerationSpecificParams Parameters specific to text-generation pipelines.\n * @property {boolean} [add_special_tokens] Whether or not to add special tokens when tokenizing the sequences.\n * @property {boolean} [return_full_text=true] If set to `false` only added text is returned, otherwise the full text is returned.\n * @typedef {import('./generation/configuration_utils.js').GenerationConfig & TextGenerationSpecificParams} TextGenerationConfig\n * \n * @callback TextGenerationPipelineCallback Complete the prompt(s) given as inputs.\n * @param {string|string[]|Chat|Chat[]} texts One or several prompts (or one list of prompts) to complete.\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise} An array or object containing the generated texts.\n * \n * @typedef {TextPipelineConstructorArgs & TextGenerationPipelineCallback & Disposable} TextGenerationPipelineType\n */\n\n/**\n * Language generation pipeline using any `ModelWithLMHead` or `ModelForCausalLM`.\n * This pipeline predicts the words that will follow a specified text prompt.\n * NOTE: For the full list of generation parameters, see [`GenerationConfig`](./utils/generation#module_utils/generation.GenerationConfig).\n * \n * **Example:** Text generation with `Xenova/distilgpt2` (default settings).\n * ```javascript\n * const generator = await pipeline('text-generation', 'Xenova/distilgpt2');\n * const text = 'I enjoy walking with my cute dog,';\n * const output = await generator(text);\n * // [{ generated_text: \"I enjoy walking with my cute dog, and I love to play with the other dogs.\" }]\n * ```\n * \n * **Example:** Text generation with `Xenova/distilgpt2` (custom settings).\n * ```javascript\n * const generator = await pipeline('text-generation', 'Xenova/distilgpt2');\n * const text = 'Once upon a time, there was';\n * const output = await generator(text, {\n * temperature: 2,\n * max_new_tokens: 10,\n * repetition_penalty: 1.5,\n * no_repeat_ngram_size: 2,\n * num_beams: 2,\n * num_return_sequences: 2,\n * });\n * // [{\n * // \"generated_text\": \"Once upon a time, there was an abundance of information about the history and activities that\"\n * // }, {\n * // \"generated_text\": \"Once upon a time, there was an abundance of information about the most important and influential\"\n * // }]\n * ```\n * \n * **Example:** Run code generation with `Xenova/codegen-350M-mono`.\n * ```javascript\n * const generator = await pipeline('text-generation', 'Xenova/codegen-350M-mono');\n * const text = 'def fib(n):';\n * const output = await generator(text, {\n * max_new_tokens: 44,\n * });\n * // [{\n * // generated_text: 'def fib(n):\\n' +\n * // ' if n == 0:\\n' +\n * // ' return 0\\n' +\n * // ' elif n == 1:\\n' +\n * // ' return 1\\n' +\n * // ' else:\\n' +\n * // ' return fib(n-1) + fib(n-2)\\n'\n * // }]\n * ```\n */\nexport class TextGenerationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TextGenerationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new TextGenerationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {TextGenerationPipelineCallback} */\n async _call(texts, generate_kwargs = {}) {\n let isBatched = false;\n let isChatInput = false;\n\n // Normalize inputs\n /** @type {string[]} */\n let inputs;\n if (typeof texts === 'string') {\n inputs = texts = [texts];\n } else if (Array.isArray(texts) && texts.every(x => typeof x === 'string')) {\n isBatched = true;\n inputs = /** @type {string[]} */(texts);\n } else {\n if (isChat(texts)) {\n texts = [/** @type {Chat} */(texts)];\n } else if (Array.isArray(texts) && texts.every(isChat)) {\n isBatched = true;\n } else {\n throw new Error('Input must be a string, an array of strings, a Chat, or an array of Chats');\n }\n isChatInput = true;\n\n // If the input is a chat, we need to apply the chat template\n inputs = /** @type {string[]} */(/** @type {Chat[]} */ (texts).map(\n x => this.tokenizer.apply_chat_template(x, {\n tokenize: false,\n add_generation_prompt: true,\n })\n ));\n }\n\n // By default, do not add special tokens\n const add_special_tokens = generate_kwargs.add_special_tokens ?? false;\n\n // By default, return full text\n const return_full_text = isChatInput\n ? false\n : generate_kwargs.return_full_text ?? true;\n\n this.tokenizer.padding_side = 'left';\n const text_inputs = this.tokenizer(inputs, {\n add_special_tokens,\n padding: true,\n truncation: true,\n });\n\n const outputTokenIds = /** @type {Tensor} */(await this.model.generate({\n ...text_inputs,\n ...generate_kwargs\n }));\n\n const decoded = this.tokenizer.batch_decode(outputTokenIds, {\n skip_special_tokens: true,\n });\n\n let promptLengths;\n if (!return_full_text && text_inputs.input_ids.dims.at(-1) > 0) {\n promptLengths = this.tokenizer.batch_decode(text_inputs.input_ids, {\n skip_special_tokens: true,\n }).map(x => x.length);\n }\n\n /** @type {TextGenerationOutput[]} */\n const toReturn = Array.from({ length: texts.length }, _ => []);\n for (let i = 0; i < decoded.length; ++i) {\n const textIndex = Math.floor(i / outputTokenIds.dims[0] * texts.length);\n\n if (promptLengths) {\n // Trim the decoded text to only include the generated part\n decoded[i] = decoded[i].slice(promptLengths[textIndex]);\n }\n toReturn[textIndex].push({\n generated_text: isChatInput\n ? [\n ...((/** @type {Chat[]} */(texts)[textIndex])),\n { role: 'assistant', content: decoded[i] },\n ]\n : decoded[i]\n });\n }\n return (!isBatched && toReturn.length === 1) ? toReturn[0] : toReturn;\n }\n}\n\n/**\n * @typedef {Object} ZeroShotClassificationOutput\n * @property {string} sequence The sequence for which this is the output.\n * @property {string[]} labels The labels sorted by order of likelihood.\n * @property {number[]} scores The probabilities for each of the labels.\n * \n * @typedef {Object} ZeroShotClassificationPipelineOptions Parameters specific to zero-shot classification pipelines.\n * @property {string} [hypothesis_template=\"This example is {}.\"] The template used to turn each\n * candidate label into an NLI-style hypothesis. The candidate label will replace the {} placeholder.\n * @property {boolean} [multi_label=false] Whether or not multiple candidate labels can be true.\n * If `false`, the scores are normalized such that the sum of the label likelihoods for each sequence\n * is 1. If `true`, the labels are considered independent and probabilities are normalized for each\n * candidate by doing a softmax of the entailment score vs. the contradiction score.\n * \n * @callback ZeroShotClassificationPipelineCallback Classify the sequence(s) given as inputs.\n * @param {string|string[]} texts The sequence(s) to classify, will be truncated if the model input is too large.\n * @param {string|string[]} candidate_labels The set of possible class labels to classify each sequence into.\n * Can be a single label, a string of comma-separated labels, or a list of labels.\n * @param {ZeroShotClassificationPipelineOptions} [options] The options to use for zero-shot classification.\n * @returns {Promise} An array or object containing the predicted labels and scores.\n * \n * @typedef {TextPipelineConstructorArgs & ZeroShotClassificationPipelineCallback & Disposable} ZeroShotClassificationPipelineType\n */\n\n/**\n * NLI-based zero-shot classification pipeline using a `ModelForSequenceClassification`\n * trained on NLI (natural language inference) tasks. Equivalent of `text-classification`\n * pipelines, but these models don't require a hardcoded number of potential classes, they\n * can be chosen at runtime. It usually means it's slower but it is **much** more flexible.\n * \n * **Example:** Zero shot classification with `Xenova/mobilebert-uncased-mnli`.\n * ```javascript\n * const classifier = await pipeline('zero-shot-classification', 'Xenova/mobilebert-uncased-mnli');\n * const text = 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.';\n * const labels = [ 'mobile', 'billing', 'website', 'account access' ];\n * const output = await classifier(text, labels);\n * // {\n * // sequence: 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.',\n * // labels: [ 'mobile', 'website', 'billing', 'account access' ],\n * // scores: [ 0.5562091040482018, 0.1843621307860853, 0.13942646639336376, 0.12000229877234923 ]\n * // }\n * ```\n * \n * **Example:** Zero shot classification with `Xenova/nli-deberta-v3-xsmall` (multi-label).\n * ```javascript\n * const classifier = await pipeline('zero-shot-classification', 'Xenova/nli-deberta-v3-xsmall');\n * const text = 'I have a problem with my iphone that needs to be resolved asap!';\n * const labels = [ 'urgent', 'not urgent', 'phone', 'tablet', 'computer' ];\n * const output = await classifier(text, labels, { multi_label: true });\n * // {\n * // sequence: 'I have a problem with my iphone that needs to be resolved asap!',\n * // labels: [ 'urgent', 'phone', 'computer', 'tablet', 'not urgent' ],\n * // scores: [ 0.9958870956360275, 0.9923963400697035, 0.002333537946160235, 0.0015134138567598765, 0.0010699384208377163 ]\n * // }\n * ```\n */\nexport class ZeroShotClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => ZeroShotClassificationPipelineType} */ (Pipeline)) {\n /**\n * Create a new ZeroShotClassificationPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n\n // Use model config to get label2id mapping\n this.label2id = Object.fromEntries(\n Object.entries((/** @type {any} */(this).model).config.label2id).map(\n ([k, v]) => [k.toLowerCase(), v]\n )\n );\n\n this.entailment_id = this.label2id['entailment'];\n if (this.entailment_id === undefined) {\n console.warn(\"Could not find 'entailment' in label2id mapping. Using 2 as entailment_id.\");\n this.entailment_id = 2;\n }\n\n this.contradiction_id = this.label2id['contradiction'] ?? this.label2id['not_entailment'];\n if (this.contradiction_id === undefined) {\n console.warn(\"Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id.\");\n this.contradiction_id = 0;\n }\n }\n\n /** @type {ZeroShotClassificationPipelineCallback} */\n async _call(texts, candidate_labels, {\n hypothesis_template = \"This example is {}.\",\n multi_label = false,\n } = {}) {\n\n const isBatched = Array.isArray(texts);\n if (!isBatched) {\n texts = [/** @type {string} */ (texts)];\n }\n if (!Array.isArray(candidate_labels)) {\n candidate_labels = [candidate_labels];\n }\n\n // Insert labels into hypothesis template\n const hypotheses = candidate_labels.map(\n x => hypothesis_template.replace('{}', x)\n );\n\n // How to perform the softmax over the logits:\n // - true: softmax over the entailment vs. contradiction dim for each label independently\n // - false: softmax the \"entailment\" logits over all candidate labels\n const softmaxEach = multi_label || candidate_labels.length === 1;\n\n /** @type {ZeroShotClassificationOutput[]} */\n const toReturn = [];\n for (const premise of texts) {\n const entails_logits = [];\n\n for (const hypothesis of hypotheses) {\n const inputs = this.tokenizer(premise, {\n text_pair: hypothesis,\n padding: true,\n truncation: true,\n })\n const outputs = await this.model(inputs)\n\n if (softmaxEach) {\n entails_logits.push([\n outputs.logits.data[this.contradiction_id],\n outputs.logits.data[this.entailment_id]\n ])\n } else {\n entails_logits.push(outputs.logits.data[this.entailment_id])\n }\n }\n\n /** @type {number[]} */\n const scores = softmaxEach\n ? entails_logits.map(x => softmax(x)[1])\n : softmax(entails_logits);\n\n // Sort by scores (desc) and return scores with indices\n const scores_sorted = scores\n .map((x, i) => [x, i])\n .sort((a, b) => (b[0] - a[0]));\n\n toReturn.push({\n sequence: premise,\n labels: scores_sorted.map(x => candidate_labels[x[1]]),\n scores: scores_sorted.map(x => x[0]),\n });\n }\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} FeatureExtractionPipelineOptions Parameters specific to feature extraction pipelines.\n * @property {'none'|'mean'|'cls'} [pooling=\"none\"] The pooling method to use.\n * @property {boolean} [normalize=false] Whether or not to normalize the embeddings in the last dimension.\n * @property {boolean} [quantize=false] Whether or not to quantize the embeddings.\n * @property {'binary'|'ubinary'} [precision='binary'] The precision to use for quantization. \n * \n * @callback FeatureExtractionPipelineCallback Extract the features of the input(s).\n * @param {string|string[]} texts One or several texts (or one list of texts) to get the features of.\n * @param {FeatureExtractionPipelineOptions} [options] The options to use for feature extraction.\n * @returns {Promise} The features computed by the model.\n * \n * @typedef {TextPipelineConstructorArgs & FeatureExtractionPipelineCallback & Disposable} FeatureExtractionPipelineType\n */\n\n/**\n * Feature extraction pipeline using no model head. This pipeline extracts the hidden\n * states from the base transformer, which can be used as features in downstream tasks.\n * \n * **Example:** Run feature extraction with `bert-base-uncased` (without pooling/normalization).\n * ```javascript\n * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' });\n * const output = await extractor('This is a simple test.');\n * // Tensor {\n * // type: 'float32',\n * // data: Float32Array [0.05939924716949463, 0.021655935794115067, ...],\n * // dims: [1, 8, 768]\n * // }\n * ```\n * \n * **Example:** Run feature extraction with `bert-base-uncased` (with pooling/normalization).\n * ```javascript\n * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' });\n * const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true });\n * // Tensor {\n * // type: 'float32',\n * // data: Float32Array [0.03373778983950615, -0.010106077417731285, ...],\n * // dims: [1, 768]\n * // }\n * ```\n * \n * **Example:** Calculating embeddings with `sentence-transformers` models.\n * ```javascript\n * const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');\n * const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true });\n * // Tensor {\n * // type: 'float32',\n * // data: Float32Array [0.09094982594251633, -0.014774246141314507, ...],\n * // dims: [1, 384]\n * // }\n * ```\n * **Example:** Calculating binary embeddings with `sentence-transformers` models.\n * ```javascript\n * const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');\n * const output = await extractor('This is a simple test.', { pooling: 'mean', quantize: true, precision: 'binary' });\n * // Tensor {\n * // type: 'int8',\n * // data: Int8Array [49, 108, 24, ...],\n * // dims: [1, 48]\n * // }\n * ```\n */\nexport class FeatureExtractionPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => FeatureExtractionPipelineType} */ (Pipeline)) {\n /**\n * Create a new FeatureExtractionPipeline.\n * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {FeatureExtractionPipelineCallback} */\n async _call(texts, {\n pooling = /** @type {'none'} */('none'),\n normalize = false,\n quantize = false,\n precision = /** @type {'binary'} */('binary'),\n } = {}) {\n\n // Run tokenization\n const model_inputs = this.tokenizer(texts, {\n padding: true,\n truncation: true,\n });\n\n // Run model\n const outputs = await this.model(model_inputs)\n\n // TODO: Provide warning to the user that they might be using model which was not exported\n // specifically for feature extraction\n // console.log(this.model.config)\n // console.log(outputs)\n\n /** @type {Tensor} */\n let result = outputs.last_hidden_state ?? outputs.logits ?? outputs.token_embeddings;\n if (pooling === 'none') {\n // Skip pooling\n } else if (pooling === 'mean') {\n result = mean_pooling(result, model_inputs.attention_mask);\n } else if (pooling === 'cls') {\n result = result.slice(null, 0);\n } else {\n throw Error(`Pooling method '${pooling}' not supported.`);\n }\n\n if (normalize) {\n result = result.normalize(2, -1);\n }\n\n if (quantize) {\n result = quantize_embeddings(result, precision);\n }\n\n return result;\n }\n}\n\n\n/**\n * @typedef {Object} ImageFeatureExtractionPipelineOptions Parameters specific to image feature extraction pipelines.\n * @property {boolean} [pool=null] Whether or not to return the pooled output. If set to `false`, the model will return the raw hidden states.\n * \n * @callback ImageFeatureExtractionPipelineCallback Extract the features of the input(s).\n * @param {ImagePipelineInputs} images One or several images (or one list of images) to get the features of.\n * @param {ImageFeatureExtractionPipelineOptions} [options] The options to use for image feature extraction.\n * @returns {Promise} The image features computed by the model.\n * \n * @typedef {ImagePipelineConstructorArgs & ImageFeatureExtractionPipelineCallback & Disposable} ImageFeatureExtractionPipelineType\n */\n\n/**\n * Image feature extraction pipeline using no model head. This pipeline extracts the hidden\n * states from the base transformer, which can be used as features in downstream tasks.\n * \n * **Example:** Perform image feature extraction with `Xenova/vit-base-patch16-224-in21k`.\n * ```javascript\n * const image_feature_extractor = await pipeline('image-feature-extraction', 'Xenova/vit-base-patch16-224-in21k');\n * const url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png';\n * const features = await image_feature_extractor(url);\n * // Tensor {\n * // dims: [ 1, 197, 768 ],\n * // type: 'float32',\n * // data: Float32Array(151296) [ ... ],\n * // size: 151296\n * // }\n * ```\n * \n * **Example:** Compute image embeddings with `Xenova/clip-vit-base-patch32`.\n * ```javascript\n * const image_feature_extractor = await pipeline('image-feature-extraction', 'Xenova/clip-vit-base-patch32');\n * const url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png';\n * const features = await image_feature_extractor(url);\n * // Tensor {\n * // dims: [ 1, 512 ],\n * // type: 'float32',\n * // data: Float32Array(512) [ ... ],\n * // size: 512\n * // }\n * ```\n */\nexport class ImageFeatureExtractionPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageFeatureExtractionPipelineType} */ (Pipeline)) {\n /**\n * Create a new ImageFeatureExtractionPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ImageFeatureExtractionPipelineCallback} */\n async _call(images, {\n pool = null,\n } = {}) {\n\n const preparedImages = await prepareImages(images);\n const { pixel_values } = await this.processor(preparedImages);\n const outputs = await this.model({ pixel_values });\n\n /** @type {Tensor} */\n let result;\n if (pool) {\n if (!('pooler_output' in outputs)) {\n throw Error(`No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.`);\n }\n result = outputs.pooler_output;\n\n } else {\n result = outputs.last_hidden_state ?? outputs.logits ?? outputs.image_embeds;\n }\n return result;\n }\n}\n\n// TODO\n// export class SentenceSimilarityPipeline extends Pipeline {\n// }\n\n/**\n * @typedef {Object} AudioClassificationSingle\n * @property {string} label The label predicted.\n * @property {number} score The corresponding probability.\n * @typedef {AudioClassificationSingle[]} AudioClassificationOutput\n * \n * @typedef {Object} AudioClassificationPipelineOptions Parameters specific to audio classification pipelines.\n * @property {number} [top_k=5] The number of top labels that will be returned by the pipeline.\n * If the provided number is `null` or higher than the number of labels available in the model configuration,\n * it will default to the number of labels.\n * \n * @callback AudioClassificationPipelineCallback Classify the sequence(s) given as inputs.\n * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either:\n * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate\n * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API.\n * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`.\n * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).\n * @param {AudioClassificationPipelineOptions} [options] The options to use for audio classification.\n * @returns {Promise} An array or object containing the predicted labels and scores.\n * \n * @typedef {AudioPipelineConstructorArgs & AudioClassificationPipelineCallback & Disposable} AudioClassificationPipelineType\n */\n\n/**\n * Audio classification pipeline using any `AutoModelForAudioClassification`.\n * This pipeline predicts the class of a raw waveform or an audio file.\n * \n * **Example:** Perform audio classification with `Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech`.\n * ```javascript\n * const classifier = await pipeline('audio-classification', 'Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const output = await classifier(url);\n * // [\n * // { label: 'male', score: 0.9981542229652405 },\n * // { label: 'female', score: 0.001845747814513743 }\n * // ]\n * ```\n * \n * **Example:** Perform audio classification with `Xenova/ast-finetuned-audioset-10-10-0.4593` and return top 4 results.\n * ```javascript\n * const classifier = await pipeline('audio-classification', 'Xenova/ast-finetuned-audioset-10-10-0.4593');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cat_meow.wav';\n * const output = await classifier(url, { top_k: 4 });\n * // [\n * // { label: 'Meow', score: 0.5617874264717102 },\n * // { label: 'Cat', score: 0.22365376353263855 },\n * // { label: 'Domestic animals, pets', score: 0.1141069084405899 },\n * // { label: 'Animal', score: 0.08985692262649536 },\n * // ]\n * ```\n */\nexport class AudioClassificationPipeline extends (/** @type {new (options: AudioPipelineConstructorArgs) => AudioClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new AudioClassificationPipeline.\n * @param {AudioPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {AudioClassificationPipelineCallback} */\n async _call(audio, {\n top_k = 5\n } = {}) {\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n const preparedAudios = await prepareAudios(audio, sampling_rate);\n\n const id2label = this.model.config.id2label;\n\n const toReturn = [];\n for (const aud of preparedAudios) {\n const inputs = await this.processor(aud);\n const output = await this.model(inputs);\n const logits = output.logits[0];\n\n const scores = await topk(new Tensor(\n 'float32',\n softmax(logits.data),\n logits.dims,\n ), top_k);\n\n const values = scores[0].tolist();\n const indices = scores[1].tolist();\n\n const vals = indices.map((x, i) => ({\n label: /** @type {string} */ (id2label ? id2label[x] : `LABEL_${x}`),\n score: /** @type {number} */ (values[i]),\n }));\n\n toReturn.push(vals);\n };\n return Array.isArray(audio) ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} ZeroShotAudioClassificationOutput\n * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`.\n * @property {number} score The score attributed by the model for that label (between 0 and 1).\n * \n * @typedef {Object} ZeroShotAudioClassificationPipelineOptions Parameters specific to zero-shot audio classification pipelines.\n * @property {string} [hypothesis_template=\"This is a sound of {}.\"] The sentence used in conjunction with `candidate_labels`\n * to attempt the audio classification by replacing the placeholder with the candidate_labels.\n * Then likelihood is estimated by using `logits_per_audio`.\n * \n * @callback ZeroShotAudioClassificationPipelineCallback Classify the sequence(s) given as inputs.\n * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either:\n * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate\n * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API.\n * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`.\n * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).\n * @param {string[]} candidate_labels The candidate labels for this audio.\n * @param {ZeroShotAudioClassificationPipelineOptions} [options] The options to use for zero-shot audio classification.\n * @returns {Promise} An array of objects containing the predicted labels and scores.\n * \n * @typedef {TextAudioPipelineConstructorArgs & ZeroShotAudioClassificationPipelineCallback & Disposable} ZeroShotAudioClassificationPipelineType\n */\n\n/**\n * Zero shot audio classification pipeline using `ClapModel`. This pipeline predicts the class of an audio when you\n * provide an audio and a set of `candidate_labels`.\n * \n * **Example**: Perform zero-shot audio classification with `Xenova/clap-htsat-unfused`.\n * ```javascript\n * const classifier = await pipeline('zero-shot-audio-classification', 'Xenova/clap-htsat-unfused');\n * const audio = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/dog_barking.wav';\n * const candidate_labels = ['dog', 'vaccum cleaner'];\n * const scores = await classifier(audio, candidate_labels);\n * // [\n * // { score: 0.9993992447853088, label: 'dog' },\n * // { score: 0.0006007603369653225, label: 'vaccum cleaner' }\n * // ]\n * ```\n */\nexport class ZeroShotAudioClassificationPipeline extends (/** @type {new (options: TextAudioPipelineConstructorArgs) => ZeroShotAudioClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ZeroShotAudioClassificationPipeline.\n * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ZeroShotAudioClassificationPipelineCallback} */\n async _call(audio, candidate_labels, {\n hypothesis_template = \"This is a sound of {}.\"\n } = {}) {\n\n const single = !Array.isArray(audio);\n if (single) {\n audio = [/** @type {AudioInput} */ (audio)];\n }\n\n // Insert label into hypothesis template \n const texts = candidate_labels.map(\n x => hypothesis_template.replace('{}', x)\n );\n\n // Run tokenization\n const text_inputs = this.tokenizer(texts, {\n padding: true,\n truncation: true,\n });\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n const preparedAudios = await prepareAudios(audio, sampling_rate);\n\n const toReturn = [];\n for (const aud of preparedAudios) {\n const audio_inputs = await this.processor(aud);\n\n // Run model with both text and audio inputs\n const output = await this.model({ ...text_inputs, ...audio_inputs });\n\n // Compute softmax per audio\n const probs = softmax(output.logits_per_audio.data);\n\n toReturn.push([...probs].map((x, i) => ({\n score: x,\n label: candidate_labels[i]\n })));\n }\n return single ? toReturn[0] : toReturn;\n }\n}\n\n/**\n * @typedef {Object} Chunk\n * @property {[number, number]} timestamp The start and end timestamp of the chunk in seconds.\n * @property {string} text The recognized text.\n */\n\n/**\n * @typedef {Object} AutomaticSpeechRecognitionOutput\n * @property {string} text The recognized text.\n * @property {Chunk[]} [chunks] When using `return_timestamps`, the `chunks` will become a list\n * containing all the various text chunks identified by the model.\n * \n * @typedef {Object} AutomaticSpeechRecognitionSpecificParams Parameters specific to automatic-speech-recognition pipelines.\n * @property {boolean|'word'} [return_timestamps] Whether to return timestamps or not. Default is `false`.\n * @property {number} [chunk_length_s] The length of audio chunks to process in seconds. Default is 0 (no chunking).\n * @property {number} [stride_length_s] The length of overlap between consecutive audio chunks in seconds. If not provided, defaults to `chunk_length_s / 6`.\n * @property {boolean} [force_full_sequences] Whether to force outputting full sequences or not. Default is `false`.\n * @property {string} [language] The source language. Default is `null`, meaning it should be auto-detected. Use this to potentially improve performance if the source language is known.\n * @property {string} [task] The task to perform. Default is `null`, meaning it should be auto-detected.\n * @property {number} [num_frames] The number of frames in the input audio.\n * @typedef {import('./generation/configuration_utils.js').GenerationConfig & AutomaticSpeechRecognitionSpecificParams} AutomaticSpeechRecognitionConfig\n * \n * @callback AutomaticSpeechRecognitionPipelineCallback Transcribe the audio sequence(s) given as inputs to text.\n * @param {AudioPipelineInputs} audio The input audio file(s) to be transcribed. The input is either:\n * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate\n * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API.\n * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`.\n * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done).\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise} An object containing the transcription text and optionally timestamps if `return_timestamps` is `true`.\n * \n * @typedef {TextAudioPipelineConstructorArgs & AutomaticSpeechRecognitionPipelineCallback & Disposable} AutomaticSpeechRecognitionPipelineType\n */\n\n/**\n * Pipeline that aims at extracting spoken text contained within some audio.\n *\n * **Example:** Transcribe English.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const output = await transcriber(url);\n * // { text: \" And so my fellow Americans ask not what your country can do for you, ask what you can do for your country.\" }\n * ```\n * \n * **Example:** Transcribe English w/ timestamps.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const output = await transcriber(url, { return_timestamps: true });\n * // {\n * // text: \" And so my fellow Americans ask not what your country can do for you, ask what you can do for your country.\"\n * // chunks: [\n * // { timestamp: [0, 8], text: \" And so my fellow Americans ask not what your country can do for you\" }\n * // { timestamp: [8, 11], text: \" ask what you can do for your country.\" }\n * // ]\n * // }\n * ```\n * \n * **Example:** Transcribe English w/ word-level timestamps.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav';\n * const output = await transcriber(url, { return_timestamps: 'word' });\n * // {\n * // \"text\": \" And so my fellow Americans ask not what your country can do for you ask what you can do for your country.\",\n * // \"chunks\": [\n * // { \"text\": \" And\", \"timestamp\": [0, 0.78] },\n * // { \"text\": \" so\", \"timestamp\": [0.78, 1.06] },\n * // { \"text\": \" my\", \"timestamp\": [1.06, 1.46] },\n * // ...\n * // { \"text\": \" for\", \"timestamp\": [9.72, 9.92] },\n * // { \"text\": \" your\", \"timestamp\": [9.92, 10.22] },\n * // { \"text\": \" country.\", \"timestamp\": [10.22, 13.5] }\n * // ]\n * // }\n * ```\n * \n * **Example:** Transcribe French.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3';\n * const output = await transcriber(url, { language: 'french', task: 'transcribe' });\n * // { text: \" J'adore, j'aime, je n'aime pas, je déteste.\" }\n * ```\n * \n * **Example:** Translate French to English.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3';\n * const output = await transcriber(url, { language: 'french', task: 'translate' });\n * // { text: \" I love, I like, I don't like, I hate.\" }\n * ```\n * \n * **Example:** Transcribe/translate audio longer than 30 seconds.\n * ```javascript\n * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/ted_60.wav';\n * const output = await transcriber(url, { chunk_length_s: 30, stride_length_s: 5 });\n * // { text: \" So in college, I was a government major, which means [...] So I'd start off light and I'd bump it up\" }\n * ```\n */\nexport class AutomaticSpeechRecognitionPipeline extends (/** @type {new (options: TextAudioPipelineConstructorArgs) => AutomaticSpeechRecognitionPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new AutomaticSpeechRecognitionPipeline.\n * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {AutomaticSpeechRecognitionPipelineCallback} */\n async _call(audio, kwargs = {}) {\n switch (this.model.config.model_type) {\n case 'whisper':\n return this._call_whisper(audio, kwargs)\n case 'wav2vec2':\n case 'wav2vec2-bert':\n case 'unispeech':\n case 'unispeech-sat':\n case 'hubert':\n return this._call_wav2vec2(audio, kwargs)\n default:\n throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)\n }\n }\n\n /**\n * @type {AutomaticSpeechRecognitionPipelineCallback}\n * @private\n */\n async _call_wav2vec2(audio, kwargs) {\n // TODO use kwargs\n\n if (kwargs.language) {\n console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to \"English\".');\n }\n if (kwargs.task) {\n console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to \"transcribe\".');\n }\n\n const single = !Array.isArray(audio);\n if (single) {\n audio = [/** @type {AudioInput} */ (audio)];\n }\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n const preparedAudios = await prepareAudios(audio, sampling_rate);\n\n const toReturn = [];\n for (const aud of preparedAudios) {\n const inputs = await this.processor(aud);\n const output = await this.model(inputs);\n const logits = output.logits[0];\n\n const predicted_ids = [];\n for (const item of logits) {\n predicted_ids.push(max(item.data)[1])\n }\n const predicted_sentences = this.tokenizer.decode(predicted_ids)\n toReturn.push({ text: predicted_sentences })\n }\n return single ? toReturn[0] : toReturn;\n }\n\n /**\n * @type {AutomaticSpeechRecognitionPipelineCallback}\n * @private\n */\n async _call_whisper(audio, kwargs) {\n const return_timestamps = kwargs.return_timestamps ?? false;\n const chunk_length_s = kwargs.chunk_length_s ?? 0;\n const force_full_sequences = kwargs.force_full_sequences ?? false;\n let stride_length_s = kwargs.stride_length_s ?? null;\n\n const generation_config = { ...kwargs }\n\n if (return_timestamps === 'word') {\n generation_config['return_token_timestamps'] = true;\n generation_config['return_timestamps'] = false; // Do not predict timestamp tokens\n }\n\n const single = !Array.isArray(audio);\n if (single) {\n audio = [/** @type {AudioInput} */ (audio)];\n }\n\n const time_precision = this.processor.feature_extractor.config.chunk_length / this.model.config.max_source_positions;\n const hop_length = this.processor.feature_extractor.config.hop_length;\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n const preparedAudios = await prepareAudios(audio, sampling_rate);\n\n const toReturn = [];\n for (const aud of preparedAudios) {\n /** @type {{stride: number[], input_features: Tensor, is_last: boolean, tokens?: bigint[], token_timestamps?: number[]}[]} */\n let chunks = [];\n if (chunk_length_s > 0) {\n if (stride_length_s === null) {\n stride_length_s = chunk_length_s / 6;\n } else if (chunk_length_s <= stride_length_s) {\n throw Error(\"`chunk_length_s` must be larger than `stride_length_s`.\")\n }\n\n // TODO support different stride_length_s (for left and right)\n\n const window = sampling_rate * chunk_length_s;\n const stride = sampling_rate * stride_length_s;\n const jump = window - 2 * stride;\n let offset = 0;\n\n // Create subarrays of audio with overlaps\n while (true) {\n const offset_end = offset + window;\n const subarr = aud.subarray(offset, offset_end);\n const feature = await this.processor(subarr);\n\n const is_first = offset === 0;\n const is_last = offset_end >= aud.length;\n chunks.push({\n stride: [\n subarr.length,\n is_first ? 0 : stride,\n is_last ? 0 : stride\n ],\n input_features: feature.input_features,\n is_last,\n })\n if (is_last) break;\n offset += jump;\n }\n\n } else {\n chunks = [{\n stride: [aud.length, 0, 0],\n input_features: (await this.processor(aud)).input_features,\n is_last: true\n }]\n }\n\n // Generate for each set of input features\n for (const chunk of chunks) {\n generation_config.num_frames = Math.floor(chunk.stride[0] / hop_length);\n\n // NOTE: doing sequentially for now\n const data = await this.model.generate({\n inputs: chunk.input_features,\n ...generation_config\n });\n\n // TODO: Right now we only get top beam\n if (return_timestamps === 'word') {\n chunk.tokens = data.sequences.tolist()[0];\n chunk.token_timestamps = data.token_timestamps.tolist()[0].map(\n (/** @type {number} */ x) => round(x, 2)\n );\n\n } else {\n chunk.tokens = (/** @type {Tensor} */(data))[0].tolist();\n }\n\n // convert stride to seconds\n chunk.stride = chunk.stride.map(x => x / sampling_rate);\n }\n\n // Merge text chunks\n // @ts-ignore\n const [full_text, optional] = this.tokenizer._decode_asr(chunks, {\n time_precision, return_timestamps, force_full_sequences\n });\n\n toReturn.push({ text: full_text, ...optional })\n }\n return single ? toReturn[0] : toReturn;\n }\n}\n\n/**\n * @typedef {Object} ImageToTextSingle\n * @property {string} generated_text The generated text.\n * @typedef {ImageToTextSingle[]} ImageToTextOutput\n * \n * @callback ImageToTextPipelineCallback Assign labels to the image(s) passed as inputs.\n * @param {ImagePipelineInputs} texts The images to be captioned.\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise} An object (or array of objects) containing the generated text(s).\n * \n * @typedef {TextImagePipelineConstructorArgs & ImageToTextPipelineCallback & Disposable} ImageToTextPipelineType\n */\n\n/**\n * Image To Text pipeline using a `AutoModelForVision2Seq`. This pipeline predicts a caption for a given image.\n * \n * **Example:** Generate a caption for an image w/ `Xenova/vit-gpt2-image-captioning`.\n * ```javascript\n * const captioner = await pipeline('image-to-text', 'Xenova/vit-gpt2-image-captioning');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';\n * const output = await captioner(url);\n * // [{ generated_text: 'a cat laying on a couch with another cat' }]\n * ```\n * \n * **Example:** Optical Character Recognition (OCR) w/ `Xenova/trocr-small-handwritten`.\n * ```javascript\n * const captioner = await pipeline('image-to-text', 'Xenova/trocr-small-handwritten');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/handwriting.jpg';\n * const output = await captioner(url);\n * // [{ generated_text: 'Mr. Brown commented icily.' }]\n * ```\n */\nexport class ImageToTextPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ImageToTextPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ImageToTextPipeline.\n * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ImageToTextPipelineCallback} */\n async _call(images, generate_kwargs = {}) {\n\n const isBatched = Array.isArray(images);\n const preparedImages = await prepareImages(images);\n\n const { pixel_values } = await this.processor(preparedImages);\n\n const toReturn = [];\n for (const batch of pixel_values) {\n batch.dims = [1, ...batch.dims]\n const output = await this.model.generate({ inputs: batch, ...generate_kwargs });\n const decoded = this.tokenizer.batch_decode(/** @type {Tensor} */(output), {\n skip_special_tokens: true,\n }).map(x => ({ generated_text: x.trim() }))\n toReturn.push(decoded);\n }\n\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} ImageClassificationSingle\n * @property {string} label The label identified by the model.\n * @property {number} score The score attributed by the model for that label.\n * @typedef {ImageClassificationSingle[]} ImageClassificationOutput\n * \n * @typedef {Object} ImageClassificationPipelineOptions Parameters specific to image classification pipelines.\n * @property {number} [top_k=1] The number of top labels that will be returned by the pipeline. \n * \n * @callback ImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The input images(s) to be classified.\n * @param {ImageClassificationPipelineOptions} [options] The options to use for image classification.\n * @returns {Promise} An array or object containing the predicted labels and scores.\n * \n * @typedef {ImagePipelineConstructorArgs & ImageClassificationPipelineCallback & Disposable} ImageClassificationPipelineType\n */\n\n/**\n * Image classification pipeline using any `AutoModelForImageClassification`.\n * This pipeline predicts the class of an image.\n * \n * **Example:** Classify an image.\n * ```javascript\n * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';\n * const output = await classifier(url);\n * // [\n * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 },\n * // ]\n * ```\n * \n * **Example:** Classify an image and return top `n` classes.\n * ```javascript\n * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';\n * const output = await classifier(url, { top_k: 3 });\n * // [\n * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 },\n * // { label: 'tiger cat', score: 0.3634825646877289 },\n * // { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 },\n * // ]\n * ```\n * \n * **Example:** Classify an image and return all classes.\n * ```javascript\n * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';\n * const output = await classifier(url, { top_k: 0 });\n * // [\n * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 },\n * // { label: 'tiger cat', score: 0.3634825646877289 },\n * // { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 },\n * // { label: 'jaguar, panther, Panthera onca, Felis onca', score: 0.00035465499968267977 },\n * // ...\n * // ]\n * ```\n */\nexport class ImageClassificationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageClassificationPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ImageClassificationPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ImageClassificationPipelineCallback} */\n async _call(images, {\n top_k = 5\n } = {}) {\n\n const preparedImages = await prepareImages(images);\n\n const { pixel_values } = await this.processor(preparedImages);\n const output = await this.model({ pixel_values });\n\n const id2label = this.model.config.id2label;\n\n /** @type {ImageClassificationOutput[]} */\n const toReturn = [];\n for (const batch of output.logits) {\n const scores = await topk(new Tensor(\n 'float32',\n softmax(batch.data),\n batch.dims,\n ), top_k);\n\n const values = scores[0].tolist();\n const indices = scores[1].tolist();\n\n const vals = indices.map((x, i) => ({\n label: /** @type {string} */ (id2label ? id2label[x] : `LABEL_${x}`),\n score: /** @type {number} */ (values[i]),\n }));\n toReturn.push(vals);\n }\n\n return Array.isArray(images) ? toReturn : toReturn[0];\n }\n\n}\n\n/**\n * @typedef {Object} ImageSegmentationPipelineOutput\n * @property {string} label The label of the segment.\n * @property {number|null} score The score of the segment.\n * @property {RawImage} mask The mask of the segment.\n * \n * @typedef {Object} ImageSegmentationPipelineOptions Parameters specific to image segmentation pipelines.\n * @property {number} [threshold=0.5] Probability threshold to filter out predicted masks.\n * @property {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values.\n * @property {number} [overlap_mask_area_threshold=0.8] Mask overlap threshold to eliminate small, disconnected segments.\n * @property {null|string} [subtask=null] Segmentation task to be performed. One of [`panoptic`, `instance`, and `semantic`],\n * depending on model capabilities. If not set, the pipeline will attempt to resolve (in that order).\n * @property {number[]} [label_ids_to_fuse=null] List of label ids to fuse. If not set, do not fuse any labels.\n * @property {number[][]} [target_sizes=null] List of target sizes for the input images. If not set, use the original image sizes.\n * \n * @callback ImageSegmentationPipelineCallback Segment the input images.\n * @param {ImagePipelineInputs} images The input images.\n * @param {ImageSegmentationPipelineOptions} [options] The options to use for image segmentation.\n * @returns {Promise} The annotated segments.\n * \n * @typedef {ImagePipelineConstructorArgs & ImageSegmentationPipelineCallback & Disposable} ImageSegmentationPipelineType\n */\n\n/**\n * Image segmentation pipeline using any `AutoModelForXXXSegmentation`.\n * This pipeline predicts masks of objects and their classes.\n * \n * **Example:** Perform image segmentation with `Xenova/detr-resnet-50-panoptic`.\n * ```javascript\n * const segmenter = await pipeline('image-segmentation', 'Xenova/detr-resnet-50-panoptic');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';\n * const output = await segmenter(url);\n * // [\n * // { label: 'remote', score: 0.9984649419784546, mask: RawImage { ... } },\n * // { label: 'cat', score: 0.9994316101074219, mask: RawImage { ... } }\n * // ]\n * ```\n */\nexport class ImageSegmentationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageSegmentationPipelineType} */ (Pipeline)) {\n /**\n * Create a new ImageSegmentationPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n\n this.subtasks_mapping = {\n // Mapping of subtasks to their corresponding post-processing function names.\n panoptic: 'post_process_panoptic_segmentation',\n instance: 'post_process_instance_segmentation',\n semantic: 'post_process_semantic_segmentation'\n }\n }\n\n /** @type {ImageSegmentationPipelineCallback} */\n async _call(images, {\n threshold = 0.5,\n mask_threshold = 0.5,\n overlap_mask_area_threshold = 0.8,\n label_ids_to_fuse = null,\n target_sizes = null,\n subtask = null,\n } = {}) {\n const isBatched = Array.isArray(images);\n\n if (isBatched && images.length !== 1) {\n throw Error(\"Image segmentation pipeline currently only supports a batch size of 1.\");\n }\n\n const preparedImages = await prepareImages(images);\n const imageSizes = preparedImages.map(x => [x.height, x.width]);\n\n const { pixel_values, pixel_mask } = await this.processor(preparedImages);\n const output = await this.model({ pixel_values, pixel_mask });\n\n let fn = null;\n if (subtask !== null) {\n fn = this.subtasks_mapping[subtask];\n } else {\n for (let [task, func] of Object.entries(this.subtasks_mapping)) {\n if (func in this.processor.feature_extractor) {\n fn = this.processor.feature_extractor[func].bind(this.processor.feature_extractor);\n subtask = task;\n break;\n }\n }\n }\n\n const id2label = this.model.config.id2label;\n\n /** @type {ImageSegmentationPipelineOutput[]} */\n const annotation = [];\n if (subtask === 'panoptic' || subtask === 'instance') {\n const processed = fn(\n output,\n threshold,\n mask_threshold,\n overlap_mask_area_threshold,\n label_ids_to_fuse,\n target_sizes ?? imageSizes, // TODO FIX?\n )[0];\n\n const segmentation = processed.segmentation;\n\n for (const segment of processed.segments_info) {\n const maskData = new Uint8ClampedArray(segmentation.data.length);\n for (let i = 0; i < segmentation.data.length; ++i) {\n if (segmentation.data[i] === segment.id) {\n maskData[i] = 255;\n }\n }\n\n const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1)\n\n annotation.push({\n score: segment.score,\n label: id2label[segment.label_id],\n mask: mask\n })\n }\n\n } else if (subtask === 'semantic') {\n const { segmentation, labels } = fn(output, target_sizes ?? imageSizes)[0];\n\n for (const label of labels) {\n const maskData = new Uint8ClampedArray(segmentation.data.length);\n for (let i = 0; i < segmentation.data.length; ++i) {\n if (segmentation.data[i] === label) {\n maskData[i] = 255;\n }\n }\n\n const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1);\n\n annotation.push({\n score: null,\n label: id2label[label],\n mask: mask\n });\n }\n } else {\n throw Error(`Subtask ${subtask} not supported.`);\n }\n\n return annotation;\n }\n}\n\n/**\n * @typedef {Object} ZeroShotImageClassificationOutput\n * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`.\n * @property {number} score The score attributed by the model for that label (between 0 and 1).\n * \n * @typedef {Object} ZeroShotImageClassificationPipelineOptions Parameters specific to zero-shot image classification pipelines.\n * @property {string} [hypothesis_template=\"This is a photo of {}\"] The sentence used in conjunction with `candidate_labels`\n * to attempt the image classification by replacing the placeholder with the candidate_labels.\n * Then likelihood is estimated by using `logits_per_image`.\n * \n * @callback ZeroShotImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The input images.\n * @param {string[]} candidate_labels The candidate labels for this image.\n * @param {ZeroShotImageClassificationPipelineOptions} [options] The options to use for zero-shot image classification.\n * @returns {Promise} An array of objects containing the predicted labels and scores.\n * \n * @typedef {TextImagePipelineConstructorArgs & ZeroShotImageClassificationPipelineCallback & Disposable} ZeroShotImageClassificationPipelineType\n */\n\n/**\n * Zero shot image classification pipeline. This pipeline predicts the class of\n * an image when you provide an image and a set of `candidate_labels`.\n * \n * **Example:** Zero shot image classification w/ `Xenova/clip-vit-base-patch32`.\n * ```javascript\n * const classifier = await pipeline('zero-shot-image-classification', 'Xenova/clip-vit-base-patch32');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg';\n * const output = await classifier(url, ['tiger', 'horse', 'dog']);\n * // [\n * // { score: 0.9993917942047119, label: 'tiger' },\n * // { score: 0.0003519294841680676, label: 'horse' },\n * // { score: 0.0002562698791734874, label: 'dog' }\n * // ]\n * ```\n */\nexport class ZeroShotImageClassificationPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotImageClassificationPipelineType} */ (Pipeline)) {\n /**\n * Create a new ZeroShotImageClassificationPipeline.\n * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ZeroShotImageClassificationPipelineCallback} */\n async _call(images, candidate_labels, {\n hypothesis_template = \"This is a photo of {}\"\n } = {}) {\n\n const isBatched = Array.isArray(images);\n const preparedImages = await prepareImages(images);\n\n // Insert label into hypothesis template \n const texts = candidate_labels.map(\n x => hypothesis_template.replace('{}', x)\n );\n\n // Run tokenization\n const text_inputs = this.tokenizer(texts, {\n padding: this.model.config.model_type === 'siglip' ? 'max_length' : true,\n truncation: true,\n });\n\n // Run processor\n const { pixel_values } = await this.processor(preparedImages);\n\n // Run model with both text and pixel inputs\n const output = await this.model({ ...text_inputs, pixel_values });\n\n const function_to_apply =\n this.model.config.model_type === 'siglip'\n ? batch => batch.sigmoid().data\n : batch => softmax(batch.data);\n\n // Compare each image with each candidate label\n const toReturn = [];\n for (const batch of output.logits_per_image) {\n // Compute softmax per image\n const probs = function_to_apply(batch);\n\n const result = [...probs].map((x, i) => ({\n score: x,\n label: candidate_labels[i]\n }));\n result.sort((a, b) => b.score - a.score); // sort by score in descending order\n toReturn.push(result);\n }\n\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n\n/**\n * @typedef {Object} ObjectDetectionPipelineSingle\n * @property {string} label The class label identified by the model.\n * @property {number} score The score attributed by the model for that label.\n * @property {BoundingBox} box The bounding box of detected object in image's original size, or as a percentage if `percentage` is set to true.\n * @typedef {ObjectDetectionPipelineSingle[]} ObjectDetectionPipelineOutput\n * \n * @typedef {Object} ObjectDetectionPipelineOptions Parameters specific to object detection pipelines.\n * @property {number} [threshold=0.9] The threshold used to filter boxes by score.\n * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false).\n * \n * @callback ObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The input images.\n * @param {ObjectDetectionPipelineOptions} [options] The options to use for object detection.\n * @returns {Promise} A list of objects or a list of list of objects. \n * \n * @typedef {ImagePipelineConstructorArgs & ObjectDetectionPipelineCallback & Disposable} ObjectDetectionPipelineType\n */\n\n/**\n * Object detection pipeline using any `AutoModelForObjectDetection`.\n * This pipeline predicts bounding boxes of objects and their classes.\n * \n * **Example:** Run object-detection with `Xenova/detr-resnet-50`.\n * ```javascript\n * const detector = await pipeline('object-detection', 'Xenova/detr-resnet-50');\n * const img = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';\n * const output = await detector(img, { threshold: 0.9 });\n * // [{\n * // score: 0.9976370930671692,\n * // label: \"remote\",\n * // box: { xmin: 31, ymin: 68, xmax: 190, ymax: 118 }\n * // },\n * // ...\n * // {\n * // score: 0.9984092116355896,\n * // label: \"cat\",\n * // box: { xmin: 331, ymin: 19, xmax: 649, ymax: 371 }\n * // }]\n * ```\n */\nexport class ObjectDetectionPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ObjectDetectionPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ObjectDetectionPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ObjectDetectionPipelineCallback} */\n async _call(images, {\n threshold = 0.9,\n percentage = false,\n } = {}) {\n\n const isBatched = Array.isArray(images);\n\n if (isBatched && images.length !== 1) {\n throw Error(\"Object detection pipeline currently only supports a batch size of 1.\");\n }\n const preparedImages = await prepareImages(images);\n\n const imageSizes = percentage ? null : preparedImages.map(x => [x.height, x.width]);\n\n const { pixel_values, pixel_mask } = await this.processor(preparedImages);\n const output = await this.model({ pixel_values, pixel_mask });\n\n // @ts-ignore\n const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSizes);\n\n // Add labels\n const id2label = this.model.config.id2label;\n\n // Format output\n /** @type {ObjectDetectionPipelineOutput[]} */\n const result = processed.map(batch => (\n batch.boxes.map((box, i) => ({\n score: batch.scores[i],\n label: id2label[batch.classes[i]],\n box: get_bounding_box(box, !percentage),\n }))\n ))\n\n return isBatched ? result : result[0];\n }\n}\n\n\n/**\n * @typedef {Object} ZeroShotObjectDetectionOutput\n * @property {string} label Text query corresponding to the found object.\n * @property {number} score Score corresponding to the object (between 0 and 1).\n * @property {BoundingBox} box Bounding box of the detected object in image's original size, or as a percentage if `percentage` is set to true.\n * \n * @typedef {Object} ZeroShotObjectDetectionPipelineOptions Parameters specific to zero-shot object detection pipelines.\n * @property {number} [threshold=0.1] The probability necessary to make a prediction.\n * @property {number} [top_k=null] The number of top predictions that will be returned by the pipeline.\n * If the provided number is `null` or higher than the number of predictions available, it will default\n * to the number of predictions.\n * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false).\n * \n * @callback ZeroShotObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The input images.\n * @param {string[]} candidate_labels What the model should recognize in the image.\n * @param {ZeroShotObjectDetectionPipelineOptions} [options] The options to use for zero-shot object detection.\n * @returns {Promise} An array of objects containing the predicted labels, scores, and bounding boxes.\n * \n * @typedef {TextImagePipelineConstructorArgs & ZeroShotObjectDetectionPipelineCallback & Disposable} ZeroShotObjectDetectionPipelineType\n */\n\n/**\n * Zero-shot object detection pipeline. This pipeline predicts bounding boxes of\n * objects when you provide an image and a set of `candidate_labels`.\n * \n * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32`.\n * ```javascript\n * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/astronaut.png';\n * const candidate_labels = ['human face', 'rocket', 'helmet', 'american flag'];\n * const output = await detector(url, candidate_labels);\n * // [\n * // {\n * // score: 0.24392342567443848,\n * // label: 'human face',\n * // box: { xmin: 180, ymin: 67, xmax: 274, ymax: 175 }\n * // },\n * // {\n * // score: 0.15129457414150238,\n * // label: 'american flag',\n * // box: { xmin: 0, ymin: 4, xmax: 106, ymax: 513 }\n * // },\n * // {\n * // score: 0.13649864494800568,\n * // label: 'helmet',\n * // box: { xmin: 277, ymin: 337, xmax: 511, ymax: 511 }\n * // },\n * // {\n * // score: 0.10262022167444229,\n * // label: 'rocket',\n * // box: { xmin: 352, ymin: -1, xmax: 463, ymax: 287 }\n * // }\n * // ]\n * ```\n * \n * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32` (returning top 4 matches and setting a threshold).\n * ```javascript\n * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/beach.png';\n * const candidate_labels = ['hat', 'book', 'sunglasses', 'camera'];\n * const output = await detector(url, candidate_labels, { top_k: 4, threshold: 0.05 });\n * // [\n * // {\n * // score: 0.1606510728597641,\n * // label: 'sunglasses',\n * // box: { xmin: 347, ymin: 229, xmax: 429, ymax: 264 }\n * // },\n * // {\n * // score: 0.08935828506946564,\n * // label: 'hat',\n * // box: { xmin: 38, ymin: 174, xmax: 258, ymax: 364 }\n * // },\n * // {\n * // score: 0.08530698716640472,\n * // label: 'camera',\n * // box: { xmin: 187, ymin: 350, xmax: 260, ymax: 411 }\n * // },\n * // {\n * // score: 0.08349756896495819,\n * // label: 'book',\n * // box: { xmin: 261, ymin: 280, xmax: 494, ymax: 425 }\n * // }\n * // ]\n * ```\n */\nexport class ZeroShotObjectDetectionPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotObjectDetectionPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new ZeroShotObjectDetectionPipeline.\n * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ZeroShotObjectDetectionPipelineCallback} */\n async _call(images, candidate_labels, {\n threshold = 0.1,\n top_k = null,\n percentage = false,\n } = {}) {\n\n const isBatched = Array.isArray(images);\n const preparedImages = await prepareImages(images);\n\n // Run tokenization\n const text_inputs = this.tokenizer(candidate_labels, {\n padding: true,\n truncation: true,\n });\n\n // Run processor\n const model_inputs = await this.processor(preparedImages);\n\n // Since non-maximum suppression is performed for exporting, we need to\n // process each image separately. For more information, see:\n // https://github.com/huggingface/optimum/blob/e3b7efb1257c011db907ef40ab340e795cc5684c/optimum/exporters/onnx/model_configs.py#L1028-L1032\n const toReturn = [];\n for (let i = 0; i < preparedImages.length; ++i) {\n const image = preparedImages[i];\n const imageSize = percentage ? null : [[image.height, image.width]];\n const pixel_values = model_inputs.pixel_values[i].unsqueeze_(0);\n\n // Run model with both text and pixel inputs\n const output = await this.model({ ...text_inputs, pixel_values });\n\n // @ts-ignore\n const processed = this.processor.feature_extractor.post_process_object_detection(output, threshold, imageSize, true)[0];\n let result = processed.boxes.map((box, i) => ({\n score: processed.scores[i],\n label: candidate_labels[processed.classes[i]],\n box: get_bounding_box(box, !percentage),\n })).sort((a, b) => b.score - a.score);\n if (top_k !== null) {\n result = result.slice(0, top_k);\n }\n toReturn.push(result)\n }\n\n return isBatched ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} DocumentQuestionAnsweringSingle\n * @property {string} answer The generated text.\n * @typedef {DocumentQuestionAnsweringSingle[]} DocumentQuestionAnsweringOutput\n * \n * @callback DocumentQuestionAnsweringPipelineCallback Answer the question given as input by using the document.\n * @param {ImageInput} image The image of the document to use.\n * @param {string} question A question to ask of the document.\n * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model.\n * @returns {Promise} An object (or array of objects) containing the answer(s).\n * \n * @typedef {TextImagePipelineConstructorArgs & DocumentQuestionAnsweringPipelineCallback & Disposable} DocumentQuestionAnsweringPipelineType\n */\n\n/**\n * Document Question Answering pipeline using any `AutoModelForDocumentQuestionAnswering`.\n * The inputs/outputs are similar to the (extractive) question answering pipeline; however,\n * the pipeline takes an image (and optional OCR'd words/boxes) as input instead of text context.\n * \n * **Example:** Answer questions about a document with `Xenova/donut-base-finetuned-docvqa`.\n * ```javascript\n * const qa_pipeline = await pipeline('document-question-answering', 'Xenova/donut-base-finetuned-docvqa');\n * const image = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/invoice.png';\n * const question = 'What is the invoice number?';\n * const output = await qa_pipeline(image, question);\n * // [{ answer: 'us-001' }]\n * ```\n */\nexport class DocumentQuestionAnsweringPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => DocumentQuestionAnsweringPipelineType} */ (Pipeline)) {\n\n /**\n * Create a new DocumentQuestionAnsweringPipeline.\n * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {DocumentQuestionAnsweringPipelineCallback} */\n async _call(image, question, generate_kwargs = {}) {\n throw new Error('This pipeline is not yet supported in Transformers.js v3.'); // TODO: Remove when implemented\n\n // NOTE: For now, we only support a batch size of 1\n\n // Preprocess image\n const preparedImage = (await prepareImages(image))[0];\n const { pixel_values } = await this.processor(preparedImage);\n\n // Run tokenization\n const task_prompt = `${question}`;\n const decoder_input_ids = this.tokenizer(task_prompt, {\n add_special_tokens: false,\n padding: true,\n truncation: true,\n }).input_ids;\n\n // Run model\n const output = await this.model.generate({\n inputs: pixel_values,\n max_length: this.model.config.decoder.max_position_embeddings,\n decoder_input_ids,\n ...generate_kwargs,\n });\n\n // Decode output\n const decoded = this.tokenizer.batch_decode(/** @type {Tensor} */(output))[0];\n\n // Parse answer\n const match = decoded.match(/(.*?)<\\/s_answer>/);\n let answer = null;\n if (match && match.length >= 2) {\n answer = match[1].trim();\n }\n return [{ answer }];\n }\n}\n\n\n/**\n * @typedef {Object} VocoderOptions\n * @property {PreTrainedModel} [vocoder] The vocoder used by the pipeline (if the model uses one). If not provided, use the default HifiGan vocoder.\n * @typedef {TextAudioPipelineConstructorArgs & VocoderOptions} TextToAudioPipelineConstructorArgs\n */\n\n/**\n * @typedef {Object} TextToAudioOutput\n * @property {Float32Array} audio The generated audio waveform.\n * @property {number} sampling_rate The sampling rate of the generated audio waveform.\n * \n * @typedef {Object} TextToAudioPipelineOptions Parameters specific to text-to-audio pipelines.\n * @property {Tensor|Float32Array|string|URL} [speaker_embeddings=null] The speaker embeddings (if the model requires it).\n * \n * @callback TextToAudioPipelineCallback Generates speech/audio from the inputs.\n * @param {string|string[]} texts The text(s) to generate.\n * @param {TextToAudioPipelineOptions} options Parameters passed to the model generation/forward method.\n * @returns {Promise} An object containing the generated audio and sampling rate.\n * \n * @typedef {TextToAudioPipelineConstructorArgs & TextToAudioPipelineCallback & Disposable} TextToAudioPipelineType\n */\n\n/**\n * Text-to-audio generation pipeline using any `AutoModelForTextToWaveform` or `AutoModelForTextToSpectrogram`.\n * This pipeline generates an audio file from an input text and optional other conditional inputs.\n * \n * **Example:** Generate audio from text with `Xenova/speecht5_tts`.\n * ```javascript\n * const synthesizer = await pipeline('text-to-speech', 'Xenova/speecht5_tts', { quantized: false });\n * const speaker_embeddings = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin';\n * const out = await synthesizer('Hello, my dog is cute', { speaker_embeddings });\n * // {\n * // audio: Float32Array(26112) [-0.00005657337896991521, 0.00020583874720614403, ...],\n * // sampling_rate: 16000\n * // }\n * ```\n * \n * You can then save the audio to a .wav file with the `wavefile` package:\n * ```javascript\n * import wavefile from 'wavefile';\n * import fs from 'fs';\n * \n * const wav = new wavefile.WaveFile();\n * wav.fromScratch(1, out.sampling_rate, '32f', out.audio);\n * fs.writeFileSync('out.wav', wav.toBuffer());\n * ```\n * \n * **Example:** Multilingual speech generation with `Xenova/mms-tts-fra`. See [here](https://huggingface.co/models?pipeline_tag=text-to-speech&other=vits&sort=trending) for the full list of available languages (1107).\n * ```javascript\n * const synthesizer = await pipeline('text-to-speech', 'Xenova/mms-tts-fra');\n * const out = await synthesizer('Bonjour');\n * // {\n * // audio: Float32Array(23808) [-0.00037693005288019776, 0.0003325853613205254, ...],\n * // sampling_rate: 16000\n * // }\n * ```\n */\nexport class TextToAudioPipeline extends (/** @type {new (options: TextToAudioPipelineConstructorArgs) => TextToAudioPipelineType} */ (Pipeline)) {\n DEFAULT_VOCODER_ID = \"Xenova/speecht5_hifigan\"\n\n /**\n * Create a new TextToAudioPipeline.\n * @param {TextToAudioPipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n\n // TODO: Find a better way for `pipeline` to set the default vocoder\n this.vocoder = options.vocoder ?? null;\n }\n\n\n /** @type {TextToAudioPipelineCallback} */\n async _call(text_inputs, {\n speaker_embeddings = null,\n } = {}) {\n\n // If this.processor is not set, we are using a `AutoModelForTextToWaveform` model\n if (this.processor) {\n return this._call_text_to_spectrogram(text_inputs, { speaker_embeddings });\n } else {\n return this._call_text_to_waveform(text_inputs);\n }\n }\n\n async _call_text_to_waveform(text_inputs) {\n\n // Run tokenization\n const inputs = this.tokenizer(text_inputs, {\n padding: true,\n truncation: true,\n });\n\n // Generate waveform\n const { waveform } = await this.model(inputs);\n\n const sampling_rate = this.model.config.sampling_rate;\n return {\n audio: waveform.data,\n sampling_rate,\n }\n }\n\n async _call_text_to_spectrogram(text_inputs, { speaker_embeddings }) {\n\n // Load vocoder, if not provided\n if (!this.vocoder) {\n console.log('No vocoder specified, using default HifiGan vocoder.');\n this.vocoder = await AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID, { dtype: 'fp32' });\n }\n\n // Load speaker embeddings as Float32Array from path/URL\n if (typeof speaker_embeddings === 'string' || speaker_embeddings instanceof URL) {\n // Load from URL with fetch\n speaker_embeddings = new Float32Array(\n await (await fetch(speaker_embeddings)).arrayBuffer()\n );\n }\n\n if (speaker_embeddings instanceof Float32Array) {\n speaker_embeddings = new Tensor(\n 'float32',\n speaker_embeddings,\n [1, speaker_embeddings.length]\n )\n } else if (!(speaker_embeddings instanceof Tensor)) {\n throw new Error(\"Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.\")\n }\n\n // Run tokenization\n const { input_ids } = this.tokenizer(text_inputs, {\n padding: true,\n truncation: true,\n });\n\n // NOTE: At this point, we are guaranteed that `speaker_embeddings` is a `Tensor`\n // @ts-ignore\n const { waveform } = await this.model.generate_speech(input_ids, speaker_embeddings, { vocoder: this.vocoder });\n\n const sampling_rate = this.processor.feature_extractor.config.sampling_rate;\n return {\n audio: waveform.data,\n sampling_rate,\n }\n }\n}\n\n/**\n * @callback ImageToImagePipelineCallback Transform the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The images to transform.\n * @returns {Promise} The transformed image or list of images.\n * \n * @typedef {ImagePipelineConstructorArgs & ImageToImagePipelineCallback & Disposable} ImageToImagePipelineType\n */\n\n/**\n * Image to Image pipeline using any `AutoModelForImageToImage`. This pipeline generates an image based on a previous image input.\n * \n * **Example:** Super-resolution w/ `Xenova/swin2SR-classical-sr-x2-64`\n * ```javascript\n * const upscaler = await pipeline('image-to-image', 'Xenova/swin2SR-classical-sr-x2-64');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg';\n * const output = await upscaler(url);\n * // RawImage {\n * // data: Uint8Array(786432) [ 41, 31, 24, 43, ... ],\n * // width: 512,\n * // height: 512,\n * // channels: 3\n * // }\n * ```\n */\nexport class ImageToImagePipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageToImagePipelineType} */ (Pipeline)) {\n /**\n * Create a new ImageToImagePipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {ImageToImagePipelineCallback} */\n async _call(images) {\n\n const preparedImages = await prepareImages(images);\n const inputs = await this.processor(preparedImages);\n const outputs = await this.model(inputs);\n\n /** @type {RawImage[]} */\n const toReturn = [];\n for (const batch of outputs.reconstruction) {\n const output = batch.squeeze().clamp_(0, 1).mul_(255).round_().to('uint8');\n toReturn.push(RawImage.fromTensor(output));\n }\n\n return toReturn.length > 1 ? toReturn : toReturn[0];\n }\n}\n\n/**\n * @typedef {Object} DepthEstimationPipelineOutput\n * @property {Tensor} predicted_depth The raw depth map predicted by the model.\n * @property {RawImage} depth The processed depth map as an image (with the same size as the input image).\n * \n * @callback DepthEstimationPipelineCallback Predicts the depth for the image(s) passed as inputs.\n * @param {ImagePipelineInputs} images The images to compute depth for.\n * @returns {Promise} An image or a list of images containing result(s).\n * \n * @typedef {ImagePipelineConstructorArgs & DepthEstimationPipelineCallback & Disposable} DepthEstimationPipelineType\n */\n\n/**\n * Depth estimation pipeline using any `AutoModelForDepthEstimation`. This pipeline predicts the depth of an image.\n * \n * **Example:** Depth estimation w/ `Xenova/dpt-hybrid-midas`\n * ```javascript\n * const depth_estimator = await pipeline('depth-estimation', 'Xenova/dpt-hybrid-midas');\n * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';\n * const out = await depth_estimator(url);\n * // {\n * // predicted_depth: Tensor {\n * // dims: [ 384, 384 ],\n * // type: 'float32',\n * // data: Float32Array(147456) [ 542.859130859375, 545.2833862304688, 546.1649169921875, ... ],\n * // size: 147456\n * // },\n * // depth: RawImage {\n * // data: Uint8Array(307200) [ 86, 86, 86, ... ],\n * // width: 640,\n * // height: 480,\n * // channels: 1\n * // }\n * // }\n * ```\n */\nexport class DepthEstimationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => DepthEstimationPipelineType} */ (Pipeline)) {\n /**\n * Create a new DepthEstimationPipeline.\n * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline.\n */\n constructor(options) {\n super(options);\n }\n\n /** @type {DepthEstimationPipelineCallback} */\n async _call(images) {\n\n const preparedImages = await prepareImages(images);\n\n const inputs = await this.processor(preparedImages);\n const { predicted_depth } = await this.model(inputs);\n\n const toReturn = [];\n for (let i = 0; i < preparedImages.length; ++i) {\n const prediction = interpolate(predicted_depth[i], preparedImages[i].size.reverse(), 'bilinear', false);\n const formatted = prediction.mul_(255 / max(prediction.data)[0]).to('uint8');\n toReturn.push({\n predicted_depth: predicted_depth[i],\n depth: RawImage.fromTensor(formatted),\n });\n }\n\n return toReturn.length > 1 ? toReturn : toReturn[0];\n }\n}\n\nconst SUPPORTED_TASKS = Object.freeze({\n \"text-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TextClassificationPipeline,\n \"model\": AutoModelForSequenceClassification,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"distilbert-base-uncased-finetuned-sst-2-english\",\n \"model\": \"Xenova/distilbert-base-uncased-finetuned-sst-2-english\",\n },\n \"type\": \"text\",\n },\n \"token-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TokenClassificationPipeline,\n \"model\": AutoModelForTokenClassification,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"Davlan/bert-base-multilingual-cased-ner-hrl\",\n \"model\": \"Xenova/bert-base-multilingual-cased-ner-hrl\",\n },\n \"type\": \"text\",\n },\n \"question-answering\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": QuestionAnsweringPipeline,\n \"model\": AutoModelForQuestionAnswering,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"distilbert-base-cased-distilled-squad\",\n \"model\": \"Xenova/distilbert-base-cased-distilled-squad\",\n },\n \"type\": \"text\",\n },\n\n \"fill-mask\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": FillMaskPipeline,\n \"model\": AutoModelForMaskedLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"bert-base-uncased\",\n \"model\": \"Xenova/bert-base-uncased\",\n },\n \"type\": \"text\",\n },\n \"summarization\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": SummarizationPipeline,\n \"model\": AutoModelForSeq2SeqLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"sshleifer/distilbart-cnn-6-6\",\n \"model\": \"Xenova/distilbart-cnn-6-6\",\n },\n \"type\": \"text\",\n },\n \"translation\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TranslationPipeline,\n \"model\": AutoModelForSeq2SeqLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"t5-small\",\n \"model\": \"Xenova/t5-small\",\n },\n \"type\": \"text\",\n },\n \"text2text-generation\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": Text2TextGenerationPipeline,\n \"model\": AutoModelForSeq2SeqLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"google/flan-t5-small\",\n \"model\": \"Xenova/flan-t5-small\",\n },\n \"type\": \"text\",\n },\n \"text-generation\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TextGenerationPipeline,\n \"model\": AutoModelForCausalLM,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"gpt2\",\n \"model\": \"Xenova/gpt2\",\n },\n \"type\": \"text\",\n },\n \"zero-shot-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ZeroShotClassificationPipeline,\n \"model\": AutoModelForSequenceClassification,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"typeform/distilbert-base-uncased-mnli\",\n \"model\": \"Xenova/distilbert-base-uncased-mnli\",\n },\n \"type\": \"text\",\n },\n \"audio-classification\": {\n \"pipeline\": AudioClassificationPipeline,\n \"model\": AutoModelForAudioClassification,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"superb/wav2vec2-base-superb-ks\",\n \"model\": \"Xenova/wav2vec2-base-superb-ks\",\n },\n \"type\": \"audio\",\n },\n \"zero-shot-audio-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ZeroShotAudioClassificationPipeline,\n \"model\": AutoModel,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"laion/clap-htsat-fused\",\n \"model\": \"Xenova/clap-htsat-unfused\",\n },\n \"type\": \"multimodal\",\n },\n \"automatic-speech-recognition\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": AutomaticSpeechRecognitionPipeline,\n \"model\": [AutoModelForSpeechSeq2Seq, AutoModelForCTC],\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"openai/whisper-tiny.en\",\n \"model\": \"Xenova/whisper-tiny.en\",\n },\n \"type\": \"multimodal\",\n },\n \"text-to-audio\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": TextToAudioPipeline,\n \"model\": [AutoModelForTextToWaveform, AutoModelForTextToSpectrogram],\n \"processor\": [AutoProcessor, /* Some don't use a processor */ null],\n \"default\": {\n // TODO: replace with original\n // \"model\": \"microsoft/speecht5_tts\",\n \"model\": \"Xenova/speecht5_tts\",\n },\n \"type\": \"text\",\n },\n \"image-to-text\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ImageToTextPipeline,\n \"model\": AutoModelForVision2Seq,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"nlpconnect/vit-gpt2-image-captioning\",\n \"model\": \"Xenova/vit-gpt2-image-captioning\",\n },\n \"type\": \"multimodal\",\n },\n\n \"image-classification\": {\n // no tokenizer\n \"pipeline\": ImageClassificationPipeline,\n \"model\": AutoModelForImageClassification,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"google/vit-base-patch16-224\",\n \"model\": \"Xenova/vit-base-patch16-224\",\n },\n \"type\": \"multimodal\",\n },\n\n \"image-segmentation\": {\n // no tokenizer\n \"pipeline\": ImageSegmentationPipeline,\n \"model\": [AutoModelForImageSegmentation, AutoModelForSemanticSegmentation, AutoModelForUniversalSegmentation],\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"facebook/detr-resnet-50-panoptic\",\n \"model\": \"Xenova/detr-resnet-50-panoptic\",\n },\n \"type\": \"multimodal\",\n },\n\n \"zero-shot-image-classification\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ZeroShotImageClassificationPipeline,\n \"model\": AutoModel,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"openai/clip-vit-base-patch32\",\n \"model\": \"Xenova/clip-vit-base-patch32\",\n },\n \"type\": \"multimodal\",\n },\n\n \"object-detection\": {\n // no tokenizer\n \"pipeline\": ObjectDetectionPipeline,\n \"model\": AutoModelForObjectDetection,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"facebook/detr-resnet-50\",\n \"model\": \"Xenova/detr-resnet-50\",\n },\n \"type\": \"multimodal\",\n },\n \"zero-shot-object-detection\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": ZeroShotObjectDetectionPipeline,\n \"model\": AutoModelForZeroShotObjectDetection,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"google/owlvit-base-patch32\",\n \"model\": \"Xenova/owlvit-base-patch32\",\n },\n \"type\": \"multimodal\",\n },\n \"document-question-answering\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": DocumentQuestionAnsweringPipeline,\n \"model\": AutoModelForDocumentQuestionAnswering,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"naver-clova-ix/donut-base-finetuned-docvqa\",\n \"model\": \"Xenova/donut-base-finetuned-docvqa\",\n },\n \"type\": \"multimodal\",\n },\n \"image-to-image\": {\n // no tokenizer\n \"pipeline\": ImageToImagePipeline,\n \"model\": AutoModelForImageToImage,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"caidas/swin2SR-classical-sr-x2-64\",\n \"model\": \"Xenova/swin2SR-classical-sr-x2-64\",\n },\n \"type\": \"image\",\n },\n \"depth-estimation\": {\n // no tokenizer\n \"pipeline\": DepthEstimationPipeline,\n \"model\": AutoModelForDepthEstimation,\n \"processor\": AutoProcessor,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"Intel/dpt-large\",\n \"model\": \"Xenova/dpt-large\",\n },\n \"type\": \"image\",\n },\n\n // This task serves as a useful interface for dealing with sentence-transformers (https://huggingface.co/sentence-transformers).\n \"feature-extraction\": {\n \"tokenizer\": AutoTokenizer,\n \"pipeline\": FeatureExtractionPipeline,\n \"model\": AutoModel,\n \"default\": {\n // TODO: replace with original\n // \"model\": \"sentence-transformers/all-MiniLM-L6-v2\",\n \"model\": \"Xenova/all-MiniLM-L6-v2\",\n },\n \"type\": \"text\",\n },\n \"image-feature-extraction\": {\n \"processor\": AutoProcessor,\n \"pipeline\": ImageFeatureExtractionPipeline,\n \"model\": [AutoModelForImageFeatureExtraction, AutoModel],\n \"default\": {\n // TODO: replace with original\n // \"model\": \"google/vit-base-patch16-224\",\n \"model\": \"Xenova/vit-base-patch16-224-in21k\",\n },\n \"type\": \"image\",\n },\n})\n\n\n// TODO: Add types for TASK_ALIASES\nconst TASK_ALIASES = Object.freeze({\n \"sentiment-analysis\": \"text-classification\",\n \"ner\": \"token-classification\",\n // \"vqa\": \"visual-question-answering\", // TODO: Add\n \"asr\": \"automatic-speech-recognition\",\n \"text-to-speech\": \"text-to-audio\",\n\n // Add for backwards compatibility\n \"embeddings\": \"feature-extraction\",\n});\n\n/**\n * @typedef {keyof typeof SUPPORTED_TASKS} TaskType\n * @typedef {keyof typeof TASK_ALIASES} AliasType\n * @typedef {TaskType | AliasType} PipelineType All possible pipeline types.\n * @typedef {{[K in TaskType]: InstanceType}} SupportedTasks A mapping of pipeline names to their corresponding pipeline classes.\n * @typedef {{[K in AliasType]: InstanceType}} AliasTasks A mapping from pipeline aliases to their corresponding pipeline classes.\n * @typedef {SupportedTasks & AliasTasks} AllTasks A mapping from all pipeline names and aliases to their corresponding pipeline classes.\n */\n\n/**\n * Utility factory method to build a `Pipeline` object.\n * \n * @template {PipelineType} T The type of pipeline to return.\n * @param {T} task The task defining which pipeline will be returned. Currently accepted tasks are:\n * - `\"audio-classification\"`: will return a `AudioClassificationPipeline`.\n * - `\"automatic-speech-recognition\"`: will return a `AutomaticSpeechRecognitionPipeline`.\n * - `\"depth-estimation\"`: will return a `DepthEstimationPipeline`.\n * - `\"document-question-answering\"`: will return a `DocumentQuestionAnsweringPipeline`.\n * - `\"feature-extraction\"`: will return a `FeatureExtractionPipeline`.\n * - `\"fill-mask\"`: will return a `FillMaskPipeline`.\n * - `\"image-classification\"`: will return a `ImageClassificationPipeline`.\n * - `\"image-segmentation\"`: will return a `ImageSegmentationPipeline`.\n * - `\"image-to-text\"`: will return a `ImageToTextPipeline`.\n * - `\"object-detection\"`: will return a `ObjectDetectionPipeline`.\n * - `\"question-answering\"`: will return a `QuestionAnsweringPipeline`.\n * - `\"summarization\"`: will return a `SummarizationPipeline`.\n * - `\"text2text-generation\"`: will return a `Text2TextGenerationPipeline`.\n * - `\"text-classification\"` (alias \"sentiment-analysis\" available): will return a `TextClassificationPipeline`.\n * - `\"text-generation\"`: will return a `TextGenerationPipeline`.\n * - `\"token-classification\"` (alias \"ner\" available): will return a `TokenClassificationPipeline`.\n * - `\"translation\"`: will return a `TranslationPipeline`.\n * - `\"translation_xx_to_yy\"`: will return a `TranslationPipeline`.\n * - `\"zero-shot-classification\"`: will return a `ZeroShotClassificationPipeline`.\n * - `\"zero-shot-audio-classification\"`: will return a `ZeroShotAudioClassificationPipeline`.\n * - `\"zero-shot-image-classification\"`: will return a `ZeroShotImageClassificationPipeline`.\n * - `\"zero-shot-object-detection\"`: will return a `ZeroShotObjectDetectionPipeline`.\n * @param {string} [model=null] The name of the pre-trained model to use. If not specified, the default model for the task will be used.\n * @param {import('./utils/hub.js').PretrainedModelOptions} [options] Optional parameters for the pipeline.\n * @returns {Promise} A Pipeline object for the specified task.\n * @throws {Error} If an unsupported pipeline is requested.\n */\nexport async function pipeline(\n task,\n model = null,\n {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n device = null,\n dtype = null,\n model_file_name = null,\n session_options = {},\n } = {}\n) {\n // Helper method to construct pipeline\n\n // Apply aliases\n // @ts-ignore\n task = TASK_ALIASES[task] ?? task;\n\n // Get pipeline info\n const pipelineInfo = SUPPORTED_TASKS[task.split('_', 1)[0]];\n if (!pipelineInfo) {\n throw Error(`Unsupported pipeline: ${task}. Must be one of [${Object.keys(SUPPORTED_TASKS)}]`)\n }\n\n // Use model if specified, otherwise, use default\n if (!model) {\n model = pipelineInfo.default.model\n console.log(`No model specified. Using default model: \"${model}\".`);\n }\n\n const pretrainedOptions = {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n device,\n dtype,\n model_file_name,\n session_options,\n }\n\n const classes = new Map([\n ['tokenizer', pipelineInfo.tokenizer],\n ['model', pipelineInfo.model],\n ['processor', pipelineInfo.processor],\n ]);\n\n // Load model, tokenizer, and processor (if they exist)\n const results = await loadItems(classes, model, pretrainedOptions);\n results.task = task;\n\n dispatchCallback(progress_callback, {\n 'status': 'ready',\n 'task': task,\n 'model': model,\n });\n\n const pipelineClass = pipelineInfo.pipeline;\n return new pipelineClass(results);\n}\n\n\n/**\n * Helper function to get applicable model, tokenizer, or processor classes for a given model.\n * @param {Map} mapping The mapping of names to classes, arrays of classes, or null.\n * @param {string} model The name of the model to load.\n * @param {import('./utils/hub.js').PretrainedOptions} pretrainedOptions The options to pass to the `from_pretrained` method.\n * @private\n */\nasync function loadItems(mapping, model, pretrainedOptions) {\n\n const result = Object.create(null);\n\n /**@type {Promise[]} */\n const promises = [];\n for (const [name, cls] of mapping.entries()) {\n if (!cls) continue;\n\n /**@type {Promise} */\n let promise;\n if (Array.isArray(cls)) {\n promise = new Promise(async (resolve, reject) => {\n let e;\n for (const c of cls) {\n if (c === null) {\n // If null, we resolve it immediately, meaning the relevant\n // class was not found, but it is optional.\n resolve(null);\n return;\n }\n try {\n resolve(await c.from_pretrained(model, pretrainedOptions));\n return;\n } catch (err) {\n if (err.message?.includes('Unsupported model type')) {\n // If the error is due to an unsupported model type, we\n // save the error and try the next class.\n e = err;\n } else if (err.message?.includes('Could not locate file')) {\n e = err;\n } else {\n reject(err);\n return;\n }\n\n }\n }\n reject(e);\n })\n } else {\n promise = cls.from_pretrained(model, pretrainedOptions);\n }\n\n result[name] = promise;\n promises.push(promise);\n }\n\n // Wait for all promises to resolve (in parallel)\n await Promise.all(promises);\n\n // Then assign to result\n for (const [name, promise] of Object.entries(result)) {\n result[name] = await promise;\n }\n\n return result;\n}","\n/**\n * @file Processors are used to prepare non-textual inputs (e.g., image or audio) for a model.\n * \n * **Example:** Using a `WhisperProcessor` to prepare an audio input for a model.\n * ```javascript\n * import { AutoProcessor, read_audio } from '@huggingface/transformers';\n *\n * let processor = await AutoProcessor.from_pretrained('openai/whisper-tiny.en');\n * let audio = await read_audio('https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac', 16000);\n * let { input_features } = await processor(audio);\n * // Tensor {\n * // data: Float32Array(240000) [0.4752984642982483, 0.5597258806228638, 0.56434166431427, ...],\n * // dims: [1, 80, 3000],\n * // type: 'float32',\n * // size: 240000,\n * // }\n * ```\n * \n * @module processors\n */\nimport {\n Callable,\n} from './utils/generic.js';\n\nimport {\n calculateDimensions,\n calculateReflectOffset,\n} from './utils/core.js';\n\nimport {\n getModelJSON,\n} from './utils/hub.js';\n\nimport {\n min,\n max,\n softmax,\n bankers_round,\n} from './utils/maths.js';\n\n\nimport { Tensor, cat, interpolate, stack, interpolate_4d, full } from './utils/tensor.js';\n\nimport { RawImage } from './utils/image.js';\nimport {\n window_function,\n spectrogram,\n mel_filter_bank,\n} from './utils/audio.js';\n\n\n// Helper functions\n\n/**\n * Converts bounding boxes from center format to corners format.\n * \n * @param {number[]} arr The coordinate for the center of the box and its width, height dimensions (center_x, center_y, width, height)\n * @returns {number[]} The coodinates for the top-left and bottom-right corners of the box (top_left_x, top_left_y, bottom_right_x, bottom_right_y)\n */\nfunction center_to_corners_format([centerX, centerY, width, height]) {\n return [\n centerX - width / 2,\n centerY - height / 2,\n centerX + width / 2,\n centerY + height / 2\n ];\n}\n\n/**\n * Post-processes the outputs of the model (for object detection).\n * @param {Object} outputs The outputs of the model that must be post-processed\n * @param {Tensor} outputs.logits The logits\n * @param {Tensor} outputs.pred_boxes The predicted boxes.\n * @param {number} [threshold=0.5] The threshold to use for the scores.\n * @param {[number, number][]} [target_sizes=null] The sizes of the original images.\n * @param {boolean} [is_zero_shot=false] Whether zero-shot object detection was performed.\n * @return {Object[]} An array of objects containing the post-processed outputs.\n * @private\n */\nfunction post_process_object_detection(outputs, threshold = 0.5, target_sizes = null, is_zero_shot = false) {\n const out_logits = outputs.logits;\n const out_bbox = outputs.pred_boxes;\n const [batch_size, num_boxes, num_classes] = out_logits.dims;\n\n if (target_sizes !== null && target_sizes.length !== batch_size) {\n throw Error(\"Make sure that you pass in as many target sizes as the batch dimension of the logits\")\n }\n let toReturn = [];\n for (let i = 0; i < batch_size; ++i) {\n let target_size = target_sizes !== null ? target_sizes[i] : null;\n let info = {\n boxes: [],\n classes: [],\n scores: []\n }\n let logits = out_logits[i];\n let bbox = out_bbox[i];\n\n for (let j = 0; j < num_boxes; ++j) {\n let logit = logits[j];\n\n let indices = [];\n let probs;\n if (is_zero_shot) {\n // Get indices of classes with high enough probability\n probs = logit.sigmoid().data;\n for (let k = 0; k < probs.length; ++k) {\n if (probs[k] > threshold) {\n indices.push(k);\n }\n }\n\n } else {\n // Get most probable class\n let maxIndex = max(logit.data)[1];\n\n if (maxIndex === num_classes - 1) {\n // This is the background class, skip it\n continue;\n }\n // Compute softmax over classes\n probs = softmax(logit.data);\n\n if (probs[maxIndex] < threshold) {\n continue;\n }\n indices.push(maxIndex);\n }\n\n for (const index of indices) {\n\n // Some class has a high enough probability\n /** @type {number[]} */\n let box = bbox[j].data;\n\n // convert to [x0, y0, x1, y1] format\n box = center_to_corners_format(box)\n if (target_size !== null) {\n box = box.map((x, i) => x * target_size[(i + 1) % 2])\n }\n\n info.boxes.push(box);\n info.classes.push(index);\n info.scores.push(probs[index]);\n }\n }\n toReturn.push(info);\n }\n return toReturn;\n}\n\n\n/**\n * Post-processes the outputs of the model (for semantic segmentation).\n * @param {*} outputs Raw outputs of the model.\n * @param {[number, number][]} [target_sizes=null] List of tuples corresponding to the requested final size\n * (height, width) of each prediction. If unset, predictions will not be resized.\n * @returns {{segmentation: Tensor; labels: number[]}[]} The semantic segmentation maps.\n */\nfunction post_process_semantic_segmentation(outputs, target_sizes = null) {\n\n const logits = outputs.logits;\n const batch_size = logits.dims[0];\n\n if (target_sizes !== null && target_sizes.length !== batch_size) {\n throw Error(\"Make sure that you pass in as many target sizes as the batch dimension of the logits\")\n }\n\n const toReturn = [];\n for (let i = 0; i < batch_size; ++i) {\n const target_size = target_sizes !== null ? target_sizes[i] : null;\n\n let data = logits[i];\n\n // 1. If target_size is not null, we need to resize the masks to the target size\n if (target_size !== null) {\n // resize the masks to the target size\n data = interpolate(data, target_size, 'bilinear', false);\n }\n const [height, width] = target_size ?? data.dims.slice(-2);\n\n const segmentation = new Tensor(\n 'int32',\n new Int32Array(height * width),\n [height, width]\n );\n\n // Buffer to store current largest value\n const buffer = data[0].data;\n const segmentation_data = segmentation.data;\n for (let j = 1; j < data.dims[0]; ++j) {\n const row = data[j].data;\n for (let k = 0; k < row.length; ++k) {\n if (row[k] > buffer[k]) {\n buffer[k] = row[k];\n segmentation_data[k] = j;\n }\n }\n }\n\n // Store which objects have labels\n // This is much more efficient that creating a set of the final values\n const hasLabel = new Array(data.dims[0]);\n for (let j = 0; j < segmentation_data.length; ++j) {\n const index = segmentation_data[j];\n hasLabel[index] = index;\n }\n /** @type {number[]} The unique list of labels that were detected */\n const labels = hasLabel.filter(x => x !== undefined);\n\n toReturn.push({ segmentation, labels });\n }\n return toReturn;\n}\n\n\n/**\n * Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and `labels`.\n * @param {Tensor} class_logits The class logits.\n * @param {Tensor} mask_logits The mask logits.\n * @param {number} object_mask_threshold A number between 0 and 1 used to binarize the masks.\n * @param {number} num_labels The number of labels.\n * @returns {[Tensor[], number[], number[]]} The binarized masks, the scores, and the labels.\n * @private\n */\nfunction remove_low_and_no_objects(class_logits, mask_logits, object_mask_threshold, num_labels) {\n\n const mask_probs_item = [];\n const pred_scores_item = [];\n const pred_labels_item = [];\n\n for (let j = 0; j < class_logits.dims[0]; ++j) {\n const cls = class_logits[j];\n const mask = mask_logits[j];\n\n const pred_label = max(cls.data)[1];\n if (pred_label === num_labels) {\n // Is the background, so we ignore it\n continue;\n }\n\n const scores = softmax(cls.data);\n const pred_score = scores[pred_label];\n if (pred_score > object_mask_threshold) {\n mask_probs_item.push(mask);\n pred_scores_item.push(pred_score);\n pred_labels_item.push(pred_label);\n }\n }\n\n return [mask_probs_item, pred_scores_item, pred_labels_item];\n}\n\n/**\n * Checks whether the segment is valid or not.\n * @param {Int32Array} mask_labels Labels for each pixel in the mask.\n * @param {Tensor[]} mask_probs Probabilities for each pixel in the masks.\n * @param {number} k The class id of the segment.\n * @param {number} mask_threshold The mask threshold.\n * @param {number} overlap_mask_area_threshold The overlap mask area threshold.\n * @returns {[boolean, number[]]} Whether the segment is valid or not, and the indices of the valid labels.\n * @private\n */\nfunction check_segment_validity(\n mask_labels,\n mask_probs,\n k,\n mask_threshold = 0.5,\n overlap_mask_area_threshold = 0.8\n) {\n // mask_k is a 1D array of indices, indicating where the mask is equal to k\n const mask_k = [];\n let mask_k_area = 0;\n let original_area = 0;\n\n const mask_probs_k_data = mask_probs[k].data;\n\n // Compute the area of all the stuff in query k\n for (let i = 0; i < mask_labels.length; ++i) {\n if (mask_labels[i] === k) {\n mask_k.push(i);\n ++mask_k_area;\n }\n\n if (mask_probs_k_data[i] >= mask_threshold) {\n ++original_area;\n }\n }\n let mask_exists = mask_k_area > 0 && original_area > 0;\n\n // Eliminate disconnected tiny segments\n if (mask_exists) {\n // Perform additional check\n let area_ratio = mask_k_area / original_area;\n mask_exists = area_ratio > overlap_mask_area_threshold;\n }\n\n return [mask_exists, mask_k]\n}\n\n/**\n * Computes the segments.\n * @param {Tensor[]} mask_probs The mask probabilities.\n * @param {number[]} pred_scores The predicted scores.\n * @param {number[]} pred_labels The predicted labels.\n * @param {number} mask_threshold The mask threshold.\n * @param {number} overlap_mask_area_threshold The overlap mask area threshold.\n * @param {Set} label_ids_to_fuse The label ids to fuse.\n * @param {number[]} target_size The target size of the image.\n * @returns {[Tensor, Array<{id: number, label_id: number, score: number}>]} The computed segments.\n * @private\n */\nfunction compute_segments(\n mask_probs,\n pred_scores,\n pred_labels,\n mask_threshold,\n overlap_mask_area_threshold,\n label_ids_to_fuse = null,\n target_size = null,\n) {\n const [height, width] = target_size ?? mask_probs[0].dims;\n\n const segmentation = new Tensor(\n 'int32',\n new Int32Array(height * width),\n [height, width]\n );\n const segments = [];\n\n // 1. If target_size is not null, we need to resize the masks to the target size\n if (target_size !== null) {\n // resize the masks to the target size\n for (let i = 0; i < mask_probs.length; ++i) {\n mask_probs[i] = interpolate(mask_probs[i], target_size, 'bilinear', false);\n }\n }\n\n // 2. Weigh each mask by its prediction score\n // NOTE: `mask_probs` is updated in-place\n // \n // Temporary storage for the best label/scores for each pixel ([height, width]):\n const mask_labels = new Int32Array(mask_probs[0].data.length);\n const bestScores = new Float32Array(mask_probs[0].data.length);\n\n for (let i = 0; i < mask_probs.length; ++i) {\n let score = pred_scores[i];\n\n const mask_probs_i_data = mask_probs[i].data;\n\n for (let j = 0; j < mask_probs_i_data.length; ++j) {\n mask_probs_i_data[j] *= score\n if (mask_probs_i_data[j] > bestScores[j]) {\n mask_labels[j] = i;\n bestScores[j] = mask_probs_i_data[j];\n }\n }\n }\n\n let current_segment_id = 0;\n\n // let stuff_memory_list = {}\n const segmentation_data = segmentation.data;\n for (let k = 0; k < pred_labels.length; ++k) {\n const pred_class = pred_labels[k];\n\n // TODO add `should_fuse`\n // let should_fuse = pred_class in label_ids_to_fuse\n\n // Check if mask exists and large enough to be a segment\n const [mask_exists, mask_k] = check_segment_validity(\n mask_labels,\n mask_probs,\n k,\n mask_threshold,\n overlap_mask_area_threshold\n )\n\n if (!mask_exists) {\n // Nothing to see here\n continue;\n }\n\n // TODO\n // if (pred_class in stuff_memory_list) {\n // current_segment_id = stuff_memory_list[pred_class]\n // } else {\n // current_segment_id += 1;\n // }\n ++current_segment_id;\n\n\n // Add current object segment to final segmentation map\n for (const index of mask_k) {\n segmentation_data[index] = current_segment_id;\n }\n\n segments.push({\n id: current_segment_id,\n label_id: pred_class,\n // was_fused: should_fuse, TODO\n score: pred_scores[k],\n })\n\n // TODO\n // if(should_fuse){\n // stuff_memory_list[pred_class] = current_segment_id\n // }\n }\n\n return [segmentation, segments];\n}\n\n\n/**\n * Post-process the model output to generate the final panoptic segmentation.\n * @param {*} outputs The model output to post process\n * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks.\n * @param {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values.\n * @param {number} [overlap_mask_area_threshold=0.8] The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask.\n * @param {Set} [label_ids_to_fuse=null] The labels in this state will have all their instances be fused together.\n * @param {[number, number][]} [target_sizes=null] The target sizes to resize the masks to.\n * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>}\n */\nfunction post_process_panoptic_segmentation(\n outputs,\n threshold = 0.5,\n mask_threshold = 0.5,\n overlap_mask_area_threshold = 0.8,\n label_ids_to_fuse = null,\n target_sizes = null,\n) {\n if (label_ids_to_fuse === null) {\n console.warn(\"`label_ids_to_fuse` unset. No instance will be fused.\")\n label_ids_to_fuse = new Set();\n }\n\n const class_queries_logits = outputs.class_queries_logits ?? outputs.logits; // [batch_size, num_queries, num_classes+1]\n const masks_queries_logits = outputs.masks_queries_logits ?? outputs.pred_masks; // [batch_size, num_queries, height, width]\n\n const mask_probs = masks_queries_logits.sigmoid() // [batch_size, num_queries, height, width]\n\n let [batch_size, num_queries, num_labels] = class_queries_logits.dims;\n num_labels -= 1; // Remove last class (background)\n\n if (target_sizes !== null && target_sizes.length !== batch_size) {\n throw Error(\"Make sure that you pass in as many target sizes as the batch dimension of the logits\")\n }\n\n let toReturn = [];\n for (let i = 0; i < batch_size; ++i) {\n let target_size = target_sizes !== null ? target_sizes[i] : null;\n\n let class_logits = class_queries_logits[i];\n let mask_logits = mask_probs[i];\n\n let [mask_probs_item, pred_scores_item, pred_labels_item] = remove_low_and_no_objects(class_logits, mask_logits, threshold, num_labels);\n\n if (pred_labels_item.length === 0) {\n // No mask found\n let [height, width] = target_size ?? mask_logits.dims.slice(-2);\n\n let segmentation = new Tensor(\n 'int32',\n new Int32Array(height * width).fill(-1),\n [height, width]\n )\n toReturn.push({\n segmentation: segmentation,\n segments_info: []\n });\n continue;\n }\n\n\n // Get segmentation map and segment information of batch item\n let [segmentation, segments] = compute_segments(\n mask_probs_item,\n pred_scores_item,\n pred_labels_item,\n mask_threshold,\n overlap_mask_area_threshold,\n label_ids_to_fuse,\n target_size,\n )\n\n toReturn.push({\n segmentation: segmentation,\n segments_info: segments\n })\n }\n\n return toReturn;\n}\n\n\n/**\n * Post-processes the outputs of the model (for instance segmentation).\n * @param {*} outputs Raw outputs of the model.\n * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks.\n * @param {[number, number][]} [target_sizes=null] List of tuples corresponding to the requested final size\n * (height, width) of each prediction. If unset, predictions will not be resized.\n * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>}\n */\nfunction post_process_instance_segmentation(outputs, threshold = 0.5, target_sizes = null) {\n throw new Error('Not implemented yet');\n return [];\n}\n\n/**\n * Named tuple to indicate the order we are using is (height x width), even though\n * the Graphics’ industry standard is (width x height).\n * @typedef {[height: number, width: number]} HeightWidth\n */\n\n/**\n * Helper function to validate audio inputs.\n * @param {any} audio The audio data.\n * @param {string} feature_extractor The name of the feature extractor.\n * @private\n */\nfunction validate_audio_inputs(audio, feature_extractor) {\n if (!(audio instanceof Float32Array || audio instanceof Float64Array)) {\n throw new Error(\n `${feature_extractor} expects input to be a Float32Array or a Float64Array, but got ${audio?.constructor?.name ?? typeof audio} instead. ` +\n `If using the feature extractor directly, remember to use \\`read_audio(url, sampling_rate)\\` to obtain the raw audio data of the file/url.`\n )\n }\n}\n\n/**\n * Helper function to constrain a value to be a multiple of a number.\n * @param {number} val The value to constrain.\n * @param {number} multiple The number to constrain to.\n * @param {number} [minVal=0] The minimum value to constrain to.\n * @param {number} [maxVal=null] The maximum value to constrain to.\n * @returns {number} The constrained value.\n * @private\n */\nfunction constraint_to_multiple_of(val, multiple, minVal = 0, maxVal = null) {\n const a = val / multiple;\n let x = bankers_round(a) * multiple;\n\n if (maxVal !== null && x > maxVal) {\n x = Math.floor(a) * multiple;\n }\n\n if (x < minVal) {\n x = Math.ceil(a) * multiple;\n }\n\n return x;\n}\n\n/**\n * Rounds the height and width down to the closest multiple of size_divisibility\n * @param {[number, number]} size The size of the image\n * @param {number} divisor The divisor to use.\n * @returns {[number, number]} The rounded size.\n */\nfunction enforce_size_divisibility([width, height], divisor) {\n return [\n Math.max(Math.floor(width / divisor), 1) * divisor,\n Math.max(Math.floor(height / divisor), 1) * divisor\n ];\n}\n\n\n/**\n * Base class for feature extractors.\n *\n * @extends Callable\n */\nexport class FeatureExtractor extends Callable {\n /**\n * Constructs a new FeatureExtractor instance.\n *\n * @param {Object} config The configuration for the feature extractor.\n */\n constructor(config) {\n super();\n this.config = config\n }\n}\n\n/**\n * @typedef {object} ImageFeatureExtractorResult\n * @property {Tensor} pixel_values The pixel values of the batched preprocessed images.\n * @property {HeightWidth[]} original_sizes Array of two-dimensional tuples like [[480, 640]].\n * @property {HeightWidth[]} reshaped_input_sizes Array of two-dimensional tuples like [[1000, 1330]].\n */\n\n/**\n * Feature extractor for image models.\n *\n * @extends FeatureExtractor\n */\nexport class ImageFeatureExtractor extends FeatureExtractor {\n\n /**\n * Constructs a new ImageFeatureExtractor instance.\n *\n * @param {Object} config The configuration for the feature extractor.\n * @param {number[]} config.image_mean The mean values for image normalization.\n * @param {number[]} config.image_std The standard deviation values for image normalization.\n * @param {boolean} config.do_rescale Whether to rescale the image pixel values to the [0,1] range.\n * @param {number} config.rescale_factor The factor to use for rescaling the image pixel values.\n * @param {boolean} config.do_normalize Whether to normalize the image pixel values.\n * @param {boolean} config.do_resize Whether to resize the image.\n * @param {number} config.resample What method to use for resampling.\n * @param {number|Object} config.size The size to resize the image to.\n * @param {boolean} [config.do_flip_channel_order=false] Whether to flip the color channels from RGB to BGR.\n * Can be overridden by the `do_flip_channel_order` parameter in the `preprocess` method.\n */\n constructor(config) {\n super(config);\n\n this.image_mean = this.config.image_mean ?? this.config.mean;\n this.image_std = this.config.image_std ?? this.config.std;\n\n this.resample = this.config.resample ?? 2; // 2 => bilinear\n this.do_rescale = this.config.do_rescale ?? true;\n this.rescale_factor = this.config.rescale_factor ?? (1 / 255);\n this.do_normalize = this.config.do_normalize;\n\n this.do_resize = this.config.do_resize;\n this.do_thumbnail = this.config.do_thumbnail;\n this.size = this.config.size;\n this.size_divisibility = this.config.size_divisibility ?? this.config.size_divisor;\n\n this.do_center_crop = this.config.do_center_crop;\n this.crop_size = this.config.crop_size;\n this.do_convert_rgb = this.config.do_convert_rgb ?? true;\n this.do_crop_margin = this.config.do_crop_margin;\n\n this.pad_size = this.config.pad_size;\n this.do_pad = this.config.do_pad;\n\n if (this.do_pad && !this.pad_size && this.size && this.size.width !== undefined && this.size.height !== undefined) {\n // Should pad, but no pad size specified\n // We infer the pad size from the resize size\n this.pad_size = this.size\n }\n\n this.do_flip_channel_order = this.config.do_flip_channel_order ?? false;\n }\n\n /**\n * Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any\n * corresponding dimension of the specified size.\n * @param {RawImage} image The image to be resized.\n * @param {{height:number, width:number}} size The size `{\"height\": h, \"width\": w}` to resize the image to.\n * @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use.\n * @returns {Promise} The resized image.\n */\n async thumbnail(image, size, resample = 2) {\n const input_height = image.height;\n const input_width = image.width;\n\n const output_height = size.height;\n const output_width = size.width;\n\n // We always resize to the smallest of either the input or output size.\n let height = Math.min(input_height, output_height)\n let width = Math.min(input_width, output_width)\n\n if (height === input_height && width === input_width) {\n return image;\n }\n if (input_height > input_width) {\n width = Math.floor(input_width * height / input_height);\n } else if (input_width > input_height) {\n height = Math.floor(input_height * width / input_width);\n }\n return await image.resize(width, height, { resample });\n }\n\n\n /**\n * Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold).\n * @param {RawImage} image The image to be cropped.\n * @param {number} gray_threshold Value below which pixels are considered to be gray.\n * @returns {Promise} The cropped image.\n */\n async crop_margin(image, gray_threshold = 200) {\n\n const gray_image = image.clone().grayscale();\n\n const minValue = min(gray_image.data)[0];\n const maxValue = max(gray_image.data)[0];\n const diff = maxValue - minValue;\n\n if (diff === 0) {\n return image;\n }\n\n const threshold = gray_threshold / 255;\n\n let x_min = gray_image.width, y_min = gray_image.height, x_max = 0, y_max = 0;\n const gray_image_data = gray_image.data;\n for (let j = 0; j < gray_image.height; ++j) {\n const row = j * gray_image.width;\n for (let i = 0; i < gray_image.width; ++i) {\n if ((gray_image_data[row + i] - minValue) / diff < threshold) {\n // We have a non-zero pixel, so we update the min/max values accordingly\n x_min = Math.min(x_min, i);\n y_min = Math.min(y_min, j);\n x_max = Math.max(x_max, i);\n y_max = Math.max(y_max, j);\n }\n }\n }\n\n image = await image.crop([x_min, y_min, x_max, y_max]);\n return image;\n }\n\n /**\n * Pad the image by a certain amount.\n * @param {Float32Array} pixelData The pixel data to pad.\n * @param {number[]} imgDims The dimensions of the image (height, width, channels).\n * @param {{width:number; height:number}|number} padSize The dimensions of the padded image.\n * @param {Object} options The options for padding.\n * @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add.\n * @param {boolean} [options.center=false] Whether to center the image.\n * @param {number} [options.constant_values=0] The constant value to use for padding.\n * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions.\n */\n pad_image(pixelData, imgDims, padSize, {\n mode = 'constant',\n center = false,\n constant_values = 0,\n } = {}) {\n const [imageHeight, imageWidth, imageChannels] = imgDims;\n\n let paddedImageWidth, paddedImageHeight;\n if (typeof padSize === 'number') {\n paddedImageWidth = padSize;\n paddedImageHeight = padSize;\n } else {\n paddedImageWidth = padSize.width;\n paddedImageHeight = padSize.height;\n }\n\n // Only add padding if there is a difference in size\n if (paddedImageWidth !== imageWidth || paddedImageHeight !== imageHeight) {\n const paddedPixelData = new Float32Array(paddedImageWidth * paddedImageHeight * imageChannels);\n if (Array.isArray(constant_values)) {\n // Fill with constant values, cycling through the array\n for (let i = 0; i < paddedPixelData.length; ++i) {\n paddedPixelData[i] = constant_values[i % imageChannels];\n }\n } else if (constant_values !== 0) {\n paddedPixelData.fill(constant_values);\n }\n\n const [left, top] = center\n ? [Math.floor((paddedImageWidth - imageWidth) / 2), Math.floor((paddedImageHeight - imageHeight) / 2)]\n : [0, 0];\n\n // Copy the original image into the padded image\n for (let i = 0; i < imageHeight; ++i) {\n const a = (i + top) * paddedImageWidth;\n const b = i * imageWidth;\n for (let j = 0; j < imageWidth; ++j) {\n const c = (a + j + left) * imageChannels;\n const d = (b + j) * imageChannels;\n for (let k = 0; k < imageChannels; ++k) {\n paddedPixelData[c + k] = pixelData[d + k];\n }\n }\n }\n\n if (mode === 'symmetric') {\n if (center) {\n throw new Error('`center` padding is not supported when `mode` is set to `symmetric`.');\n // TODO: Implement this\n }\n const h1 = imageHeight - 1;\n const w1 = imageWidth - 1;\n for (let i = 0; i < paddedImageHeight; ++i) {\n const a = i * paddedImageWidth;\n const b = calculateReflectOffset(i, h1) * imageWidth;\n\n for (let j = 0; j < paddedImageWidth; ++j) {\n if (i < imageHeight && j < imageWidth) continue; // Do not overwrite original image\n const c = (a + j) * imageChannels;\n const d = (b + calculateReflectOffset(j, w1)) * imageChannels;\n\n // Copy channel-wise\n for (let k = 0; k < imageChannels; ++k) {\n paddedPixelData[c + k] = pixelData[d + k];\n }\n }\n }\n }\n\n\n // Update pixel data and image dimensions\n pixelData = paddedPixelData;\n imgDims = [paddedImageHeight, paddedImageWidth, imageChannels]\n }\n return [pixelData, imgDims];\n }\n\n /**\n * Rescale the image' pixel values by `this.rescale_factor`.\n * @param {Float32Array} pixelData The pixel data to rescale.\n * @returns {void}\n */\n rescale(pixelData) {\n for (let i = 0; i < pixelData.length; ++i) {\n pixelData[i] = this.rescale_factor * pixelData[i];\n }\n }\n\n /**\n * Find the target (width, height) dimension of the output image after\n * resizing given the input image and the desired size.\n * @param {RawImage} image The image to resize.\n * @param {any} size The size to use for resizing the image. \n * @returns {[number, number]} The target (width, height) dimension of the output image after resizing.\n */\n get_resize_output_image_size(image, size) {\n // `size` comes in many forms, so we need to handle them all here:\n // 1. `size` is an integer, in which case we resize the image to be a square \n\n const [srcWidth, srcHeight] = image.size;\n\n let shortest_edge;\n let longest_edge;\n\n if (this.do_thumbnail) {\n // NOTE: custom logic for `Donut` models\n const { height, width } = size;\n shortest_edge = Math.min(height, width)\n }\n // Support both formats for backwards compatibility\n else if (Number.isInteger(size)) {\n shortest_edge = size;\n longest_edge = this.config.max_size ?? shortest_edge;\n\n } else if (size !== undefined) {\n // Extract known properties from `size`\n shortest_edge = size.shortest_edge;\n longest_edge = size.longest_edge;\n }\n\n // If `longest_edge` and `shortest_edge` are set, maintain aspect ratio and resize to `shortest_edge`\n // while keeping the largest dimension <= `longest_edge`\n if (shortest_edge !== undefined || longest_edge !== undefined) {\n // http://opensourcehacker.com/2011/12/01/calculate-aspect-ratio-conserving-resize-for-images-in-javascript/\n // Try resize so that shortest edge is `shortest_edge` (target)\n const shortResizeFactor = shortest_edge === undefined\n ? 1 // If `shortest_edge` is not set, don't upscale\n : Math.max(shortest_edge / srcWidth, shortest_edge / srcHeight);\n\n const newWidth = srcWidth * shortResizeFactor;\n const newHeight = srcHeight * shortResizeFactor;\n\n // The new width and height might be greater than `longest_edge`, so\n // we downscale again to ensure the largest dimension is `longest_edge` \n const longResizeFactor = longest_edge === undefined\n ? 1 // If `longest_edge` is not set, don't downscale\n : Math.min(longest_edge / newWidth, longest_edge / newHeight);\n\n // To avoid certain floating point precision issues, we round to 2 decimal places\n let finalWidth = Math.floor(Number((newWidth * longResizeFactor).toFixed(2)));\n let finalHeight = Math.floor(Number((newHeight * longResizeFactor).toFixed(2)));\n\n if (this.size_divisibility !== undefined) {\n [finalWidth, finalHeight] = enforce_size_divisibility([finalWidth, finalHeight], this.size_divisibility)\n }\n return [finalWidth, finalHeight];\n\n } else if (size !== undefined && size.width !== undefined && size.height !== undefined) {\n // If `width` and `height` are set, resize to those dimensions\n\n let newWidth = size.width;\n let newHeight = size.height;\n\n // Custom for DPT models\n if (this.config.keep_aspect_ratio && this.config.ensure_multiple_of) {\n\n // determine new height and width\n let scale_height = newHeight / srcHeight;\n let scale_width = newWidth / srcWidth;\n\n // scale as little as possible\n if (Math.abs(1 - scale_width) < Math.abs(1 - scale_height)) {\n // fit width\n scale_height = scale_width;\n } else {\n // fit height\n scale_width = scale_height;\n }\n\n newHeight = constraint_to_multiple_of(scale_height * srcHeight, this.config.ensure_multiple_of);\n newWidth = constraint_to_multiple_of(scale_width * srcWidth, this.config.ensure_multiple_of);\n }\n\n return [newWidth, newHeight];\n\n } else if (this.size_divisibility !== undefined) {\n return enforce_size_divisibility([srcWidth, srcHeight], this.size_divisibility);\n } else {\n throw new Error(`Could not resize image due to unsupported \\`this.size\\` option in config: ${JSON.stringify(size)}`);\n }\n }\n\n /**\n * Resizes the image.\n * @param {RawImage} image The image to resize.\n * @returns {Promise} The resized image.\n */\n async resize(image) {\n const [newWidth, newHeight] = this.get_resize_output_image_size(image, this.size);\n return await image.resize(newWidth, newHeight, {\n resample: this.resample,\n });\n }\n\n /**\n * @typedef {object} PreprocessedImage\n * @property {HeightWidth} original_size The original size of the image.\n * @property {HeightWidth} reshaped_input_size The reshaped input size of the image.\n * @property {Tensor} pixel_values The pixel values of the preprocessed image.\n */\n\n /**\n * Preprocesses the given image.\n *\n * @param {RawImage} image The image to preprocess.\n * @param {Object} overrides The overrides for the preprocessing options.\n * @returns {Promise} The preprocessed image.\n */\n async preprocess(image, {\n do_normalize = null,\n do_pad = null,\n do_convert_rgb = null,\n do_convert_grayscale = null,\n do_flip_channel_order = null,\n } = {}) {\n if (this.do_crop_margin) {\n // NOTE: Specific to nougat processors. This is done before resizing,\n // and can be interpreted as a pre-preprocessing step.\n image = await this.crop_margin(image);\n }\n\n const [srcWidth, srcHeight] = image.size; // original image size\n\n // Convert image to RGB if specified in config.\n if (do_convert_rgb ?? this.do_convert_rgb) {\n image = image.rgb();\n } else if (do_convert_grayscale) {\n image = image.grayscale();\n }\n\n // TODO:\n // For efficiency reasons, it might be best to merge the resize and center crop operations into one.\n\n // Resize all images\n if (this.do_resize) {\n image = await this.resize(image);\n }\n\n // Resize the image using thumbnail method.\n if (this.do_thumbnail) {\n image = await this.thumbnail(image, this.size, this.resample);\n }\n\n if (this.do_center_crop) {\n\n let crop_width;\n let crop_height;\n if (Number.isInteger(this.crop_size)) {\n crop_width = this.crop_size;\n crop_height = this.crop_size;\n } else {\n crop_width = this.crop_size.width;\n crop_height = this.crop_size.height;\n }\n\n image = await image.center_crop(crop_width, crop_height);\n }\n\n /** @type {HeightWidth} */\n const reshaped_input_size = [image.height, image.width];\n\n // NOTE: All pixel-level manipulation (i.e., modifying `pixelData`)\n // occurs with data in the hwc format (height, width, channels), \n // to emulate the behavior of the original Python code (w/ numpy).\n let pixelData = Float32Array.from(image.data);\n let imgDims = [image.height, image.width, image.channels];\n\n if (this.do_rescale) {\n this.rescale(pixelData);\n }\n\n if (do_normalize ?? this.do_normalize) {\n let image_mean = this.image_mean;\n if (!Array.isArray(this.image_mean)) {\n image_mean = new Array(image.channels).fill(image_mean);\n }\n\n let image_std = this.image_std;\n if (!Array.isArray(this.image_std)) {\n image_std = new Array(image.channels).fill(image_mean);\n }\n\n if (image_mean.length !== image.channels || image_std.length !== image.channels) {\n throw new Error(`When set to arrays, the length of \\`image_mean\\` (${image_mean.length}) and \\`image_std\\` (${image_std.length}) must match the number of channels in the image (${image.channels}).`);\n }\n\n for (let i = 0; i < pixelData.length; i += image.channels) {\n for (let j = 0; j < image.channels; ++j) {\n pixelData[i + j] = (pixelData[i + j] - image_mean[j]) / image_std[j];\n }\n }\n }\n\n // do padding after rescaling/normalizing\n if (do_pad ?? this.do_pad) {\n if (this.pad_size) {\n const padded = this.pad_image(pixelData, [image.height, image.width, image.channels], this.pad_size);\n [pixelData, imgDims] = padded; // Update pixel data and image dimensions\n } else if (this.size_divisibility) {\n const [paddedWidth, paddedHeight] = enforce_size_divisibility([imgDims[1], imgDims[0]], this.size_divisibility);\n [pixelData, imgDims] = this.pad_image(pixelData, imgDims, { width: paddedWidth, height: paddedHeight });\n }\n }\n\n if (do_flip_channel_order ?? this.do_flip_channel_order) {\n if (imgDims[2] !== 3) {\n throw new Error('Flipping channel order is only supported for RGB images.');\n }\n // Convert RGB to BGR\n for (let i = 0; i < pixelData.length; i += 3) {\n const temp = pixelData[i];\n pixelData[i] = pixelData[i + 2];\n pixelData[i + 2] = temp;\n }\n }\n\n const pixel_values = new Tensor('float32', pixelData, imgDims)\n .permute(2, 0, 1); // convert to channel dimension format (hwc -> chw)\n\n return {\n original_size: [srcHeight, srcWidth],\n reshaped_input_size: reshaped_input_size,\n pixel_values,\n }\n }\n\n /**\n * Calls the feature extraction process on an array of images,\n * preprocesses each image, and concatenates the resulting\n * features into a single Tensor.\n * @param {RawImage[]} images The image(s) to extract features from.\n * @param {...any} args Additional arguments.\n * @returns {Promise} An object containing the concatenated pixel values (and other metadata) of the preprocessed images.\n */\n async _call(images, ...args) {\n if (!Array.isArray(images)) {\n images = [images];\n }\n /** @type {PreprocessedImage[]} */\n const imageData = await Promise.all(images.map(x => this.preprocess(x)));\n\n // Stack pixel values\n const pixel_values = stack(imageData.map(x => x.pixel_values), 0);\n\n return {\n pixel_values,\n\n // Original sizes of images\n original_sizes: imageData.map(x => x.original_size),\n\n // Reshaped sizes of images, before padding or cropping\n reshaped_input_sizes: imageData.map(x => x.reshaped_input_size),\n }\n }\n\n}\n\nexport class SapiensFeatureExtractor extends ImageFeatureExtractor {\n /** @type {typeof post_process_semantic_segmentation} */\n post_process_semantic_segmentation(...args) {\n return post_process_semantic_segmentation(...args);\n }\n}\nexport class SegformerFeatureExtractor extends ImageFeatureExtractor {\n /** @type {typeof post_process_semantic_segmentation} */\n post_process_semantic_segmentation(...args) {\n return post_process_semantic_segmentation(...args);\n }\n}\nexport class PvtImageProcessor extends ImageFeatureExtractor { }\nexport class DPTFeatureExtractor extends ImageFeatureExtractor { }\nexport class DPTImageProcessor extends DPTFeatureExtractor { } // NOTE: extends DPTFeatureExtractor\nexport class BitImageProcessor extends ImageFeatureExtractor { }\nexport class GLPNFeatureExtractor extends ImageFeatureExtractor { }\nexport class CLIPFeatureExtractor extends ImageFeatureExtractor { }\nexport class CLIPImageProcessor extends CLIPFeatureExtractor { } // NOTE: extends CLIPFeatureExtractor\nexport class ChineseCLIPFeatureExtractor extends ImageFeatureExtractor { }\nexport class SiglipImageProcessor extends ImageFeatureExtractor { }\nexport class ConvNextFeatureExtractor extends ImageFeatureExtractor {\n constructor(config) {\n super(config);\n\n /**\n * Percentage of the image to crop. Only has an effect if this.size < 384.\n */\n this.crop_pct = this.config.crop_pct ?? (224 / 256);\n }\n\n async resize(image) {\n const shortest_edge = this.size?.shortest_edge;\n if (shortest_edge === undefined) {\n throw new Error(`Size dictionary must contain 'shortest_edge' key.`);\n }\n\n if (shortest_edge < 384) {\n // maintain same ratio, resizing shortest edge to shortest_edge/crop_pct\n const resize_shortest_edge = Math.floor(shortest_edge / this.crop_pct);\n\n const [newWidth, newHeight] = this.get_resize_output_image_size(image, {\n shortest_edge: resize_shortest_edge,\n });\n\n image = await image.resize(newWidth, newHeight, {\n resample: this.resample,\n });\n\n // then crop to (shortest_edge, shortest_edge)\n image = await image.center_crop(shortest_edge, shortest_edge);\n } else {\n // warping (no cropping) when evaluated at 384 or larger\n image = await image.resize(shortest_edge, shortest_edge, {\n resample: this.resample,\n });\n }\n\n return image;\n }\n}\nexport class ConvNextImageProcessor extends ConvNextFeatureExtractor { } // NOTE extends ConvNextFeatureExtractor\nexport class ViTFeatureExtractor extends ImageFeatureExtractor { }\nexport class ViTImageProcessor extends ImageFeatureExtractor { }\n\nexport class EfficientNetImageProcessor extends ImageFeatureExtractor {\n constructor(config) {\n super(config);\n this.include_top = this.config.include_top ?? true;\n if (this.include_top) {\n this.image_std = this.image_std.map(x => x * x);\n }\n }\n}\n\nexport class MobileNetV1FeatureExtractor extends ImageFeatureExtractor { }\nexport class MobileNetV2FeatureExtractor extends ImageFeatureExtractor { }\nexport class MobileNetV3FeatureExtractor extends ImageFeatureExtractor { }\nexport class MobileNetV4FeatureExtractor extends ImageFeatureExtractor { }\n\nexport class MobileViTFeatureExtractor extends ImageFeatureExtractor { }\nexport class MobileViTImageProcessor extends MobileViTFeatureExtractor { } // NOTE extends MobileViTFeatureExtractor\nexport class OwlViTFeatureExtractor extends ImageFeatureExtractor {\n /** @type {typeof post_process_object_detection} */\n post_process_object_detection(...args) {\n return post_process_object_detection(...args);\n }\n}\nexport class Owlv2ImageProcessor extends OwlViTFeatureExtractor { } // NOTE extends OwlViTFeatureExtractor\n\nexport class RTDetrImageProcessor extends ImageFeatureExtractor {\n /** @type {typeof post_process_object_detection} */\n post_process_object_detection(...args) {\n return post_process_object_detection(...args);\n }\n}\n\nexport class DeiTFeatureExtractor extends ImageFeatureExtractor { }\nexport class BeitFeatureExtractor extends ImageFeatureExtractor { }\nexport class DonutFeatureExtractor extends ImageFeatureExtractor {\n pad_image(pixelData, imgDims, padSize, options = {}) {\n const [imageHeight, imageWidth, imageChannels] = imgDims;\n\n let image_mean = this.image_mean;\n if (!Array.isArray(this.image_mean)) {\n image_mean = new Array(imageChannels).fill(image_mean);\n }\n\n let image_std = this.image_std;\n if (!Array.isArray(image_std)) {\n image_std = new Array(imageChannels).fill(image_mean);\n }\n\n const constant_values = image_mean.map((x, i) => - x / image_std[i]);\n\n return super.pad_image(pixelData, imgDims, padSize, {\n center: true,\n\n // Since normalization is done after padding, we need to use certain constant values to ensure the same behaviour is observed.\n // For more information, see https://github.com/huggingface/transformers/blob/main/src/transformers/models/donut/image_processing_donut.py#L433-L451\n constant_values: constant_values,\n ...options,\n });\n }\n}\nexport class NougatImageProcessor extends DonutFeatureExtractor { } // NOTE extends DonutFeatureExtractor\n\n/**\n * @typedef {object} DetrFeatureExtractorResultProps\n * @property {Tensor} pixel_mask\n * @typedef {ImageFeatureExtractorResult & DetrFeatureExtractorResultProps} DetrFeatureExtractorResult\n */\n\n/**\n * Detr Feature Extractor.\n *\n * @extends ImageFeatureExtractor\n */\nexport class DetrFeatureExtractor extends ImageFeatureExtractor {\n /**\n * Calls the feature extraction process on an array of images, preprocesses\n * each image, and concatenates the resulting features into a single Tensor.\n * @param {RawImage[]} images The image(s) to extract features from.\n * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images.\n */\n async _call(images) {\n const result = await super._call(images);\n\n // TODO support differently-sized images, for now assume all images are the same size.\n // TODO support different mask sizes (not just 64x64)\n // Currently, just fill pixel mask with 1s\n const maskSize = [result.pixel_values.dims[0], 64, 64];\n const pixel_mask = full(maskSize, 1n);\n\n return { ...result, pixel_mask };\n }\n\n /** @type {typeof post_process_object_detection} */\n post_process_object_detection(...args) {\n return post_process_object_detection(...args);\n }\n\n /** @type {typeof post_process_panoptic_segmentation} */\n post_process_panoptic_segmentation(...args) {\n return post_process_panoptic_segmentation(...args);\n }\n\n post_process_instance_segmentation() {\n // TODO\n throw Error(\"Not implemented yet\");\n }\n}\n\nexport class MaskFormerFeatureExtractor extends ImageFeatureExtractor {\n\n /** @type {typeof post_process_panoptic_segmentation} */\n post_process_panoptic_segmentation(...args) {\n return post_process_panoptic_segmentation(...args);\n }\n\n post_process_instance_segmentation() {\n // TODO\n throw Error(\"Not implemented yet\");\n }\n}\n\n\nexport class YolosFeatureExtractor extends ImageFeatureExtractor {\n /** @type {typeof post_process_object_detection} */\n post_process_object_detection(...args) {\n return post_process_object_detection(...args);\n }\n}\n\n/**\n * @typedef {object} SamImageProcessorResult\n * @property {Tensor} pixel_values\n * @property {HeightWidth[]} original_sizes\n * @property {HeightWidth[]} reshaped_input_sizes\n * @property {Tensor} [input_points]\n * @property {Tensor} [input_labels]\n * @property {Tensor} [input_boxes]\n */\n\nexport class SamImageProcessor extends ImageFeatureExtractor {\n\n /**\n * \n * @param {any} input_points \n * @param {HeightWidth[]} original_sizes \n * @param {HeightWidth[]} reshaped_input_sizes \n * @returns {Tensor}\n */\n reshape_input_points(input_points, original_sizes, reshaped_input_sizes, is_bounding_box = false) {\n\n // Make deep copy to avoid altering user's input\n input_points = structuredClone(input_points);\n let shape = calculateDimensions(input_points);\n\n // TODO: add support for 2D input_points\n if (shape.length === 3) {\n // Correct user's input\n if (!is_bounding_box) {\n shape = [1, ...shape];\n }\n input_points = [input_points];\n } else if (shape.length !== 4) {\n throw Error(\"The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.\")\n }\n\n // Reshape input points\n for (let i = 0; i < input_points.length; ++i) { // batch_size\n let originalImageSize = original_sizes[i];\n let reshapedImageSize = reshaped_input_sizes[i];\n\n let resizeFactors = [\n reshapedImageSize[0] / originalImageSize[0],\n reshapedImageSize[1] / originalImageSize[1]\n ]\n\n for (let j = 0; j < input_points[i].length; ++j) { // point_batch_size\n for (let k = 0; k < input_points[i][j].length; ++k) { // nb_points_per_image\n for (let w = 0; w < input_points[i][j][k].length; ++w) { // 2 or 4\n input_points[i][j][k][w] *= resizeFactors[w % 2];\n }\n }\n }\n }\n\n return new Tensor(\n 'float32',\n Float32Array.from(input_points.flat(Infinity)),\n shape\n )\n\n }\n\n /**\n * \n * @param {any} input_labels \n * @param {Tensor} input_points \n * @returns {Tensor}\n */\n add_input_labels(input_labels, input_points) {\n let shape = calculateDimensions(input_labels);\n if (shape.length === 2) {\n // Correct user's input\n shape = [1, ...shape];\n input_labels = [input_labels];\n } else if (shape.length !== 3) {\n throw Error(\"The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.\")\n }\n\n if (shape.some((x, i) => x !== input_points.dims[i])) {\n throw Error(`The first ${shape.length} dimensions of 'input_points' and 'input_labels' must be the same.`)\n }\n return new Tensor(\n 'int64',\n input_labels.flat(Infinity).map(BigInt),\n shape,\n )\n }\n /**\n * @param {any[]} images The URL(s) of the image(s) to extract features from.\n * @param {Object} [options] Additional options for the processor.\n * @param {any} [options.input_points=null] A 3D or 4D array, representing the input points provided by the user.\n * - 3D: `[point_batch_size, nb_points_per_image, 2]`. In this case, `batch_size` is assumed to be 1.\n * - 4D: `[batch_size, point_batch_size, nb_points_per_image, 2]`.\n * @param {any} [options.input_labels=null] A 2D or 3D array, representing the input labels for the points, used by the prompt encoder to encode the prompt.\n * - 2D: `[point_batch_size, nb_points_per_image]`. In this case, `batch_size` is assumed to be 1.\n * - 3D: `[batch_size, point_batch_size, nb_points_per_image]`.\n * @param {number[][][]} [options.input_boxes=null] A 3D array of shape `(batch_size, num_boxes, 4)`, representing the input boxes provided by the user.\n * This is used by the prompt encoder to encode the prompt. Generally yields to much better generated masks.\n * The processor will generate a tensor, with each dimension corresponding respectively to the image batch size,\n * the number of boxes per image and the coordinates of the top left and botton right point of the box.\n * In the order (`x1`, `y1`, `x2`, `y2`):\n * - `x1`: the x coordinate of the top left point of the input box\n * - `y1`: the y coordinate of the top left point of the input box\n * - `x2`: the x coordinate of the bottom right point of the input box\n * - `y2`: the y coordinate of the bottom right point of the input box\n * @returns {Promise}\n */\n async _call(images, {\n input_points = null,\n input_labels = null,\n input_boxes = null\n } = {}) {\n // TODO allow user to use preprocessed images\n /** @type {SamImageProcessorResult} */\n const processed = await super._call(images);\n\n if (input_points) {\n processed.input_points = this.reshape_input_points(\n input_points, processed.original_sizes, processed.reshaped_input_sizes\n );\n }\n\n if (input_labels) {\n if (!processed.input_points) {\n throw Error(\"`input_points` must be provided if `input_labels` are provided.\")\n }\n processed.input_labels = this.add_input_labels(input_labels, processed.input_points);\n }\n\n if (input_boxes) {\n processed.input_boxes = this.reshape_input_points(\n input_boxes, processed.original_sizes, processed.reshaped_input_sizes, true,\n );\n }\n\n return processed;\n }\n\n /**\n * Remove padding and upscale masks to the original image size.\n * @param {Tensor} masks Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.\n * @param {[number, number][]} original_sizes The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format.\n * @param {[number, number][]} reshaped_input_sizes The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.\n * @param {Object} options Optional parameters for post-processing.\n * @param {number} [options.mask_threshold] The threshold to use for binarizing the masks.\n * @param {boolean} [options.binarize] Whether to binarize the masks.\n * @param {Object} [options.pad_size] The target size the images were padded to before being passed to the model. If `null`, the target size is assumed to be the processor's `pad_size`.\n * @param {number} [options.pad_size.height] The height the images were padded to.\n * @param {number} [options.pad_size.width] The width the images were padded to.\n * @returns {Promise} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size.\n */\n async post_process_masks(masks, original_sizes, reshaped_input_sizes, {\n mask_threshold = 0.0,\n binarize = true,\n pad_size = null,\n } = {}) {\n // masks: [1, 1, 3, 256, 256]\n\n const output_masks = [];\n\n pad_size = pad_size ?? this.pad_size;\n\n /** @type {[number, number]} */\n const target_image_size = [pad_size.height, pad_size.width];\n\n for (let i = 0; i < original_sizes.length; ++i) {\n const original_size = original_sizes[i];\n const reshaped_input_size = reshaped_input_sizes[i];\n\n // Upscale mask to padded size\n let interpolated_mask = (await interpolate_4d(\n masks[i],\n { mode: 'bilinear', size: target_image_size }\n ));\n\n // Crop mask\n interpolated_mask = interpolated_mask.slice(null, null, [0, reshaped_input_size[0]], [0, reshaped_input_size[1]]);\n\n // Downscale mask\n interpolated_mask = (await interpolate_4d(\n interpolated_mask,\n { mode: 'bilinear', size: original_size }\n ));\n\n if (binarize) {\n const data = interpolated_mask.data;\n const binarizedMaskData = new Uint8Array(data.length);\n for (let i = 0; i < data.length; ++i) {\n if (data[i] > mask_threshold) {\n binarizedMaskData[i] = 1;\n }\n }\n interpolated_mask = new Tensor(\n 'bool',\n binarizedMaskData,\n interpolated_mask.dims\n )\n }\n\n output_masks.push(interpolated_mask);\n }\n\n return output_masks;\n }\n\n /**\n * Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.\n * @param {RawImage} image Input original image\n * @param {number} target_size Target size of the resized image\n * @param {Object} options Options for generating crop boxes \n * @param {number} [options.crop_n_layers] If >0, mask prediction will be run again on crops of the image.\n * Sets the number of layers to run, where each layer has 2**i_layer number of image crops.\n * @param {number} [options.overlap_ratio] Sets the degree to which crops overlap. In the first crop layer,\n * crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap.\n * @param {number} [options.points_per_crop] Number of points to sample from each crop.\n * @param {number} [options.crop_n_points_downscale_factor] The number of points-per-side sampled in layer n is\n * scaled down by crop_n_points_downscale_factor**n.\n * @returns {Object} An object containing the crop boxes, number of points per crop, cropped images, and input labels.\n */\n generate_crop_boxes(image, target_size, {\n crop_n_layers = 0,\n overlap_ratio = 512 / 1500,\n points_per_crop = 32,\n crop_n_points_downscale_factor = 1,\n } = {}) {\n // TODO: Implement\n // return { crop_boxes, points_per_crop, cropped_images, input_labels }\n }\n}\n\nexport class Swin2SRImageProcessor extends ImageFeatureExtractor {\n pad_image(pixelData, imgDims, padSize, options = {}) {\n // NOTE: In this case, `padSize` represents the size of the sliding window for the local attention.\n // In other words, the image is padded so that its width and height are multiples of `padSize`.\n const [imageHeight, imageWidth, imageChannels] = imgDims;\n\n return super.pad_image(pixelData, imgDims, {\n // NOTE: For Swin2SR models, the original python implementation adds padding even when the image's width/height is already\n // a multiple of `pad_size`. However, this is most likely a bug (PR: https://github.com/mv-lab/swin2sr/pull/19).\n // For this reason, we only add padding when the image's width/height is not a multiple of `pad_size`.\n width: imageWidth + (padSize - imageWidth % padSize) % padSize,\n height: imageHeight + (padSize - imageHeight % padSize) % padSize,\n }, {\n mode: 'symmetric',\n center: false,\n constant_values: -1,\n ...options,\n })\n }\n}\n\nexport class VitMatteImageProcessor extends ImageFeatureExtractor {\n /**\n * Calls the feature extraction process on an array of images, preprocesses\n * each image, and concatenates the resulting features into a single Tensor.\n * @param {RawImage[]} images The image(s) to extract features from.\n * @param {RawImage[]} trimaps The trimaps(s) to extract features from.\n * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images.\n */\n async _call(images, trimaps) {\n if (!Array.isArray(images)) {\n images = [images];\n }\n if (!Array.isArray(trimaps)) {\n trimaps = [trimaps];\n }\n\n const imageData = await Promise.all(images.map(x => this.preprocess(x)));\n const trimapData = await Promise.all(trimaps.map(x => this.preprocess(x, {\n do_normalize: false,\n do_convert_rgb: false,\n do_convert_grayscale: true,\n })));\n\n\n // Stack pixel values\n const pixel_values = stack(imageData.map(\n // Concatenate images and trimaps\n (x, i) => cat([x.pixel_values, trimapData[i].pixel_values], 0)\n ), 0);\n\n return {\n pixel_values,\n\n // Original sizes of images\n original_sizes: imageData.map(x => x.original_size),\n\n // Reshaped sizes of images, before padding or cropping\n reshaped_input_sizes: imageData.map(x => x.reshaped_input_size),\n }\n }\n}\n\nexport class WhisperFeatureExtractor extends FeatureExtractor {\n\n constructor(config) {\n super(config);\n\n // Prefer given `mel_filters` from preprocessor_config.json, or calculate them if they don't exist.\n this.config.mel_filters ??= mel_filter_bank(\n Math.floor(1 + this.config.n_fft / 2), // num_frequency_bins\n this.config.feature_size, // num_mel_filters\n 0.0, // min_frequency\n 8000.0, // max_frequency\n this.config.sampling_rate, // sampling_rate\n \"slaney\", // norm\n \"slaney\", // mel_scale\n );\n\n this.window = window_function(this.config.n_fft, 'hann');\n }\n\n /**\n * Computes the log-Mel spectrogram of the provided audio waveform.\n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform) {\n const features = await spectrogram(\n waveform,\n this.window, // window\n this.config.n_fft, // frame_length\n this.config.hop_length, // hop_length\n {\n power: 2.0,\n mel_filters: this.config.mel_filters,\n log_mel: 'log10',\n\n // Custom\n max_num_frames: this.config.nb_max_frames, // 3000\n }\n )\n\n const data = features.data;\n const maxValue = max(data)[0];\n\n for (let i = 0; i < data.length; ++i) {\n data[i] = (Math.max(data[i], maxValue - 8.0) + 4.0) / 4.0;\n }\n\n return features;\n }\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'WhisperFeatureExtractor');\n\n let waveform;\n if (audio.length > this.config.n_samples) {\n console.warn(\n \"Attempting to extract features for audio longer than 30 seconds. \" +\n \"If using a pipeline to extract transcript from a long audio clip, \" +\n \"remember to specify `chunk_length_s` and/or `stride_length_s`.\"\n );\n waveform = audio.slice(0, this.config.n_samples);\n } else {\n // pad with zeros\n waveform = new Float32Array(this.config.n_samples);\n waveform.set(audio);\n }\n\n const features = await this._extract_fbank_features(waveform);\n\n return {\n input_features: features.unsqueeze_(0)\n };\n }\n}\n\nexport class Wav2Vec2FeatureExtractor extends FeatureExtractor {\n\n /**\n * @param {Float32Array} input_values \n * @returns {Float32Array} \n */\n _zero_mean_unit_var_norm(input_values) {\n // TODO support batch?\n const sum = input_values.reduce((a, b) => a + b, 0);\n const mean = sum / input_values.length;\n const variance = input_values.reduce((a, b) => a + (b - mean) ** 2, 0) / input_values.length;\n return input_values.map(x => (x - mean) / Math.sqrt(variance + 1e-7));\n }\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_values: Tensor; attention_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention mask as Tensors.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'Wav2Vec2FeatureExtractor');\n\n if (audio instanceof Float64Array) {\n audio = new Float32Array(audio);\n }\n\n let input_values = audio;\n\n // zero-mean and unit-variance normalization\n if (this.config.do_normalize) {\n input_values = this._zero_mean_unit_var_norm(input_values);\n }\n\n // TODO: allow user to pass in attention mask\n const shape = [1, input_values.length];\n return {\n input_values: new Tensor('float32', input_values, shape),\n attention_mask: new Tensor('int64', new BigInt64Array(input_values.length).fill(1n), shape)\n };\n }\n}\n\nexport class SeamlessM4TFeatureExtractor extends FeatureExtractor {\n\n constructor(config) {\n super(config);\n\n const sampling_rate = this.config.sampling_rate;\n const mel_filters = mel_filter_bank(\n 256, // num_frequency_bins\n this.config.num_mel_bins, // num_mel_filters\n 20, // min_frequency\n Math.floor(sampling_rate / 2), // max_frequency\n sampling_rate, // sampling_rate\n null, // norm\n \"kaldi\", // mel_scale\n true, // triangularize_in_mel_space\n );\n\n // Do padding:\n for (let i = 0; i < mel_filters.length; ++i) {\n mel_filters[i].push(0);\n }\n this.mel_filters = mel_filters;\n\n this.window = window_function(400, 'povey', {\n periodic: false,\n })\n }\n\n /**\n * Computes the log-Mel spectrogram of the provided audio waveform.\n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @param {number} max_length The maximum number of frames to return.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform, max_length) {\n // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`\n\n // Kaldi compliance: 16-bit signed integers\n // 32768 == 2 ** 15\n waveform = waveform.map((/** @type {number} */ x) => x * 32768)\n\n return spectrogram(\n waveform,\n this.window, // window\n 400, // frame_length\n 160, // hop_length\n {\n fft_length: 512,\n power: 2.0,\n center: false,\n preemphasis: 0.97,\n mel_filters: this.mel_filters,\n log_mel: 'log',\n mel_floor: 1.192092955078125e-07,\n remove_dc_offset: true,\n\n // Custom\n max_num_frames: max_length,\n transpose: true,\n }\n )\n }\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @param {Object} options Optional parameters for feature extraction.\n * @param {boolean} [options.padding=true] Whether to pad the sequence to a multiple of `pad_to_multiple_of`.\n * @param {number} [options.pad_to_multiple_of=2] The number to pad the sequence to a multiple of.\n * @param {boolean} [options.do_normalize_per_mel_bins=true] Whether or not to zero-mean unit-variance normalize the input per mel-channel.\n * @param {boolean} [options.return_attention_mask=true] Whether to return the attention mask.\n * @returns {Promise<{ input_features: Tensor, attention_mask?: Tensor }>} A Promise resolving to an object containing the extracted input features and attention masks as Tensors.\n */\n async _call(audio, {\n padding = true,\n pad_to_multiple_of = 2,\n do_normalize_per_mel_bins = true,\n return_attention_mask = true,\n } = {}) {\n validate_audio_inputs(audio, 'SeamlessM4TFeatureExtractor');\n\n let features = await this._extract_fbank_features(audio, this.config.max_length);\n\n if (do_normalize_per_mel_bins) {\n const [num_features, feature_size] = features.dims;\n const data = features.data;\n for (let i = 0; i < feature_size; ++i) {\n let sum = 0;\n for (let j = 0; j < num_features; ++j) {\n sum += data[j * feature_size + i];\n }\n\n const mean = sum / num_features;\n\n let variance = 0;\n for (let j = 0; j < num_features; ++j) {\n variance += (data[j * feature_size + i] - mean) ** 2;\n }\n variance /= num_features - 1; // NOTE: We use ddof=1\n\n const std = Math.sqrt(variance + 1e-7);\n for (let j = 0; j < num_features; ++j) {\n const index = j * feature_size + i;\n data[index] = (data[index] - mean) / std;\n }\n }\n }\n\n let padded_attention_mask;\n if (padding) {\n const [num_frames, num_channels] = features.dims;\n const data = /** @type {Float32Array} */(features.data);\n\n const pad_size = num_frames % pad_to_multiple_of;\n if (pad_size > 0) {\n const padded_data = new Float32Array(num_channels * (num_frames + pad_size));\n padded_data.set(data)\n padded_data.fill(this.config.padding_value, data.length)\n\n const numPaddedFrames = num_frames + pad_size;\n features = new Tensor(\n features.type,\n padded_data,\n [numPaddedFrames, num_channels],\n )\n\n if (return_attention_mask) {\n padded_attention_mask = new Tensor(\n 'int64',\n new BigInt64Array(numPaddedFrames),\n [1, numPaddedFrames],\n )\n padded_attention_mask.data.fill(1n, 0, num_frames);\n }\n }\n }\n\n const [num_frames, num_channels] = features.dims;\n\n const stride = this.config.stride;\n const remainder = num_frames % stride;\n if (remainder !== 0) {\n throw new Error(`The number of frames (${num_frames}) must be a multiple of the stride (${stride}).`)\n }\n\n const input_features = features.view(\n 1,\n Math.floor(num_frames / stride),\n num_channels * stride,\n );\n\n const result = { input_features }\n\n if (return_attention_mask) {\n const reshapedNumFrames = input_features.dims[1];\n\n const attention_mask_data = new BigInt64Array(reshapedNumFrames);\n\n if (padded_attention_mask) {\n const padded_attention_mask_data = padded_attention_mask.data;\n for (let i = 1, j = 0; i < num_frames; i += stride, ++j) {\n attention_mask_data[j] = padded_attention_mask_data[i];\n }\n } else {\n attention_mask_data.fill(1n);\n }\n result.attention_mask = new Tensor(\n 'int64',\n attention_mask_data,\n [1, reshapedNumFrames],\n );\n }\n\n return result;\n }\n}\n\nexport class ASTFeatureExtractor extends FeatureExtractor {\n\n\n constructor(config) {\n super(config);\n\n const sampling_rate = this.config.sampling_rate;\n const mel_filters = mel_filter_bank(\n 256, // num_frequency_bins\n this.config.num_mel_bins, // num_mel_filters\n 20, // min_frequency\n Math.floor(sampling_rate / 2), // max_frequency\n sampling_rate, // sampling_rate\n null, // norm\n \"kaldi\", // mel_scale\n true, // triangularize_in_mel_space\n );\n\n // Do padding:\n for (let i = 0; i < mel_filters.length; ++i) {\n mel_filters[i].push(0);\n }\n this.mel_filters = mel_filters;\n\n this.window = window_function(400, 'hann', {\n periodic: false,\n })\n\n this.mean = this.config.mean;\n this.std = this.config.std;\n }\n\n /**\n * Computes the log-Mel spectrogram of the provided audio waveform.\n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @param {number} max_length The maximum number of frames to return.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform, max_length) {\n // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`\n return spectrogram(\n waveform,\n this.window, // window\n 400, // frame_length\n 160, // hop_length\n {\n fft_length: 512,\n power: 2.0,\n center: false,\n preemphasis: 0.97,\n mel_filters: this.mel_filters,\n log_mel: 'log',\n mel_floor: 1.192092955078125e-07,\n remove_dc_offset: true,\n\n // Custom\n max_num_frames: max_length,\n transpose: true,\n }\n )\n }\n\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_values: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'ASTFeatureExtractor');\n\n const features = await this._extract_fbank_features(audio, this.config.max_length);\n if (this.config.do_normalize) {\n // Normalize the input audio spectrogram to have mean=0, std=0.5\n const denom = this.std * 2;\n const features_data = features.data;\n for (let i = 0; i < features_data.length; ++i) {\n features_data[i] = (features_data[i] - this.mean) / denom;\n }\n }\n\n return {\n input_values: features.unsqueeze_(0)\n };\n }\n}\n\nexport class ClapFeatureExtractor extends FeatureExtractor {\n\n constructor(config) {\n super(config);\n\n this.mel_filters = mel_filter_bank(\n this.config.nb_frequency_bins, // num_frequency_bins\n this.config.feature_size, // num_mel_filters\n this.config.frequency_min, // min_frequency\n this.config.frequency_max, // max_frequency\n this.config.sampling_rate, // sampling_rate\n null, // norm\n \"htk\", // mel_scale\n );\n\n this.mel_filters_slaney = mel_filter_bank(\n this.config.nb_frequency_bins, // num_frequency_bins\n this.config.feature_size, // num_mel_filters\n this.config.frequency_min, // min_frequency\n this.config.frequency_max, // max_frequency\n this.config.sampling_rate, // sampling_rate\n \"slaney\", // norm\n \"slaney\", // mel_scale\n );\n\n this.window = window_function(this.config.fft_window_size, 'hann')\n\n }\n\n\n /**\n * Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments.\n * \n * Four different path are possible:\n * - `truncation=\"fusion\"` and the length of the waveform is greater than the max length: the mel spectrogram\n * will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram\n * are then stacked together. They will later be used for `feature_fusion`.\n * - `truncation=\"rand_trunc\"` and the length of the waveform is smaller than the max length: the audio is\n * padded based on `padding`.\n * - `truncation=\"fusion\"` and the length of the waveform is smaller than the max length: the audio is padded\n * based on `padding`, and is repeated `4` times.\n * - `truncation=\"rand_trunc\"` and the length of the waveform is greater than the max length: the mel\n * spectrogram will be computed on a random crop of the waveform.\n * \n * @param {Float32Array|Float64Array} waveform The input waveform.\n * @param {number} max_length The maximum length of the waveform.\n * @param {string} truncation The truncation strategy to use.\n * @param {string} padding The padding strategy to use.\n * @returns {Promise} An object containing the mel spectrogram data as a Float32Array, its dimensions as an array of numbers, and a boolean indicating whether the waveform was longer than the max length.\n * @private\n */\n async _get_input_mel(waveform, max_length, truncation, padding) {\n\n /** @type {Tensor} */\n let input_mel;\n let longer = false;\n const diff = waveform.length - max_length;\n if (diff > 0) {\n if (truncation === 'rand_trunc') {\n longer = true;\n const idx = Math.floor(Math.random() * (diff + 1));\n waveform = waveform.subarray(idx, idx + max_length);\n\n input_mel = await this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples);\n } else {\n // TODO implement fusion strategy\n throw new Error(`Truncation strategy \"${truncation}\" not implemented`)\n }\n } else {\n if (diff < 0) {\n let padded = new Float64Array(max_length); // already padded with zeros\n padded.set(waveform);\n\n if (padding === 'repeat') {\n for (let i = waveform.length; i < max_length; i += waveform.length) {\n padded.set(waveform.subarray(0, Math.min(waveform.length, max_length - i)), i);\n }\n } else if (padding === 'repeatpad') {\n for (let i = waveform.length; i < -diff; i += waveform.length) {\n padded.set(waveform, i);\n }\n }\n waveform = padded;\n }\n\n if (truncation === 'fusion') {\n throw new Error(`Truncation strategy \"${truncation}\" not implemented`)\n }\n\n input_mel = await this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples);\n }\n\n return input_mel.unsqueeze_(0);\n }\n\n /**\n * Compute the log-mel spectrogram of the provided `waveform` using the Hann window.\n * In CLAP, two different filter banks are used depending on the truncation pattern:\n * - `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from\n * calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation`\n * is set to `\"fusion\"`.\n * - `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used\n * `librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original\n * implementation when the truncation mode is not `\"fusion\"`.\n * \n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @param {number[][]} mel_filters The mel filters to use.\n * @param {number} [max_length=null] The maximum number of frames to return.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform, mel_filters, max_length = null) {\n // NOTE: We don't pad/truncate since that is passed in as `max_num_frames`\n return spectrogram(\n waveform,\n this.window, // window\n this.config.fft_window_size, // frame_length\n this.config.hop_length, // hop_length\n {\n power: 2.0,\n mel_filters,\n log_mel: 'dB',\n\n // Custom\n max_num_frames: max_length,\n do_pad: false,\n transpose: true,\n }\n )\n }\n\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.\n */\n async _call(audio, {\n max_length = null,\n } = {}) {\n validate_audio_inputs(audio, 'ClapFeatureExtractor');\n\n // convert to mel spectrogram, truncate and pad if needed.\n const padded_inputs = await this._get_input_mel(\n audio,\n max_length ?? this.config.nb_max_samples,\n this.config.truncation,\n this.config.padding,\n );\n\n return {\n input_features: padded_inputs.unsqueeze_(0),\n }\n }\n}\n\n\nexport class PyAnnoteFeatureExtractor extends FeatureExtractor {\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_values: Tensor; }>} The extracted input features.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'PyAnnoteFeatureExtractor');\n\n if (audio instanceof Float64Array) {\n audio = new Float32Array(audio);\n }\n\n const shape = [\n 1, /* batch_size */\n 1, /* num_channels */\n audio.length, /* num_samples */\n ];\n return {\n input_values: new Tensor('float32', audio, shape),\n };\n }\n\n /**\n * NOTE: Can return fractional values. `Math.ceil` will ensure correct value.\n * @param {number} samples The number of frames in the audio.\n * @returns {number} The number of frames in the audio.\n */\n samples_to_frames(samples) {\n return ((samples - this.config.offset) / this.config.step);\n }\n\n /**\n * Post-processes the speaker diarization logits output by the model.\n * @param {Tensor} logits The speaker diarization logits output by the model.\n * @param {number} num_samples Number of samples in the input audio.\n * @returns {Array>} The post-processed speaker diarization results.\n */\n post_process_speaker_diarization(logits, num_samples) {\n const ratio = (\n num_samples / this.samples_to_frames(num_samples)\n ) / this.config.sampling_rate;\n\n const results = [];\n for (const scores of logits.tolist()) {\n const accumulated_segments = [];\n\n let current_speaker = -1;\n for (let i = 0; i < scores.length; ++i) {\n const probabilities = softmax(scores[i]);\n const [score, id] = max(probabilities);\n const [start, end] = [i, i + 1];\n\n if (id !== current_speaker) {\n // Speaker has changed\n current_speaker = id;\n accumulated_segments.push({ id, start, end, score });\n } else {\n // Continue the current segment\n accumulated_segments.at(-1).end = end;\n accumulated_segments.at(-1).score += score;\n }\n }\n\n results.push(accumulated_segments.map(\n // Convert frame-space to time-space\n // and compute the confidence\n ({ id, start, end, score }) => ({\n id,\n start: start * ratio,\n end: end * ratio,\n confidence: score / (end - start),\n })\n ));\n }\n return results;\n }\n\n}\n\nexport class WeSpeakerFeatureExtractor extends FeatureExtractor {\n\n constructor(config) {\n super(config);\n\n const sampling_rate = this.config.sampling_rate;\n const mel_filters = mel_filter_bank(\n 256, // num_frequency_bins\n this.config.num_mel_bins, // num_mel_filters\n 20, // min_frequency\n Math.floor(sampling_rate / 2), // max_frequency\n sampling_rate, // sampling_rate\n null, // norm\n \"kaldi\", // mel_scale\n true, // triangularize_in_mel_space\n );\n\n // Do padding:\n for (let i = 0; i < mel_filters.length; ++i) {\n mel_filters[i].push(0);\n }\n this.mel_filters = mel_filters;\n\n this.window = window_function(400, 'hamming', {\n periodic: false,\n })\n this.min_num_frames = this.config.min_num_frames;\n }\n\n /**\n * Computes the log-Mel spectrogram of the provided audio waveform.\n * @param {Float32Array|Float64Array} waveform The audio waveform to process.\n * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers.\n */\n async _extract_fbank_features(waveform) {\n // Kaldi compliance: 16-bit signed integers\n // 32768 == 2 ** 15\n waveform = waveform.map((/** @type {number} */ x) => x * 32768)\n\n return spectrogram(\n waveform,\n this.window, // window\n 400, // frame_length\n 160, // hop_length\n {\n fft_length: 512,\n power: 2.0,\n center: false,\n preemphasis: 0.97,\n mel_filters: this.mel_filters,\n log_mel: 'log',\n mel_floor: 1.192092955078125e-07,\n remove_dc_offset: true,\n\n // Custom\n transpose: true,\n min_num_frames: this.min_num_frames,\n }\n )\n }\n\n\n /**\n * Asynchronously extracts features from a given audio using the provided configuration.\n * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array.\n * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor.\n */\n async _call(audio) {\n validate_audio_inputs(audio, 'WeSpeakerFeatureExtractor');\n\n const features = (await this._extract_fbank_features(audio)).unsqueeze_(0);\n\n if (this.config.fbank_centering_span === null) {\n // center features with global average\n const meanData = /** @type {Float32Array} */ (features.mean(1).data);\n const featuresData = /** @type {Float32Array} */(features.data);\n const [batch_size, num_frames, feature_size] = features.dims;\n\n for (let i = 0; i < batch_size; ++i) {\n const offset1 = i * num_frames * feature_size;\n const offset2 = i * feature_size;\n for (let j = 0; j < num_frames; ++j) {\n const offset3 = offset1 + j * feature_size;\n for (let k = 0; k < feature_size; ++k) {\n featuresData[offset3 + k] -= meanData[offset2 + k];\n }\n }\n }\n }\n\n return {\n input_features: features\n };\n }\n}\n\nexport class SpeechT5FeatureExtractor extends FeatureExtractor { }\n\n/**\n * Represents a Processor that extracts features from an input.\n * @extends Callable\n */\nexport class Processor extends Callable {\n /**\n * Creates a new Processor with the given feature extractor.\n * @param {FeatureExtractor} feature_extractor The function used to extract features from the input.\n */\n constructor(feature_extractor) {\n super();\n this.feature_extractor = feature_extractor;\n // TODO use tokenizer here?\n }\n\n /**\n * Calls the feature_extractor function with the given input.\n * @param {any} input The input to extract features from.\n * @param {...any} args Additional arguments.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(input, ...args) {\n return await this.feature_extractor(input, ...args);\n }\n}\n\nexport class SamProcessor extends Processor {\n /**\n * @borrows SamImageProcessor#_call as _call\n */\n async _call(...args) {\n return await this.feature_extractor(...args);\n }\n\n /**\n * @borrows SamImageProcessor#post_process_masks as post_process_masks\n */\n post_process_masks(...args) {\n // @ts-ignore\n return this.feature_extractor.post_process_masks(...args);\n }\n /**\n * @borrows SamImageProcessor#reshape_input_points as reshape_input_points\n */\n reshape_input_points(...args) {\n // @ts-ignore\n return this.feature_extractor.reshape_input_points(...args);\n }\n}\n\n/**\n * Represents a WhisperProcessor that extracts features from an audio input.\n * @extends Processor\n */\nexport class WhisperProcessor extends Processor {\n /**\n * Calls the feature_extractor function with the given audio input.\n * @param {any} audio The audio input to extract features from.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(audio) {\n return await this.feature_extractor(audio)\n }\n}\n\n\nexport class Wav2Vec2ProcessorWithLM extends Processor {\n /**\n * Calls the feature_extractor function with the given audio input.\n * @param {any} audio The audio input to extract features from.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(audio) {\n return await this.feature_extractor(audio)\n }\n}\n\nexport class PyAnnoteProcessor extends Processor {\n /**\n * Calls the feature_extractor function with the given audio input.\n * @param {any} audio The audio input to extract features from.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(audio) {\n return await this.feature_extractor(audio)\n }\n\n post_process_speaker_diarization(...args) {\n // @ts-ignore\n return this.feature_extractor.post_process_speaker_diarization(...args);\n }\n\n}\n\nexport class SpeechT5Processor extends Processor {\n /**\n * Calls the feature_extractor function with the given input.\n * @param {any} input The input to extract features from.\n * @returns {Promise} A Promise that resolves with the extracted features.\n */\n async _call(input) {\n return await this.feature_extractor(input)\n }\n}\n\nexport class OwlViTProcessor extends Processor { }\n\nexport class Florence2Processor extends Processor {\n constructor(feature_extractor) {\n super(feature_extractor);\n\n const {\n tasks_answer_post_processing_type,\n task_prompts_without_inputs,\n task_prompts_with_input,\n } = feature_extractor.config;\n\n /** @type {Map} */\n this.tasks_answer_post_processing_type = new Map(Object.entries(tasks_answer_post_processing_type ?? {}));\n\n /** @type {Map} */\n this.task_prompts_without_inputs = new Map(Object.entries(task_prompts_without_inputs ?? {}));\n\n /** @type {Map} */\n this.task_prompts_with_input = new Map(Object.entries(task_prompts_with_input ?? {}));\n\n this.regexes = {\n quad_boxes: /(.+?)/gm,\n bboxes: /([^<]+)?/gm,\n }\n this.size_per_bin = 1000;\n }\n\n /**\n * Helper function to construct prompts from input texts\n * @param {string|string[]} text\n * @returns {string[]}\n */\n construct_prompts(text) {\n if (typeof text === 'string') {\n text = [text];\n }\n\n const prompts = [];\n for (const t of text) {\n // 1. fixed task prompts without additional inputs\n if (this.task_prompts_without_inputs.has(t)) {\n prompts.push(this.task_prompts_without_inputs.get(t));\n }\n // 2. task prompts with additional inputs \n else {\n for (const [task, prompt] of this.task_prompts_with_input) {\n if (t.includes(task)) {\n prompts.push(prompt.replaceAll('{input}', t).replaceAll(task, ''));\n break;\n }\n }\n\n // 3. default prompt\n if (prompts.length !== text.length) {\n prompts.push(t);\n }\n }\n }\n return prompts;\n }\n\n /**\n * Post-process the output of the model to each of the task outputs.\n * @param {string} text The text to post-process.\n * @param {string} task The task to post-process the text for.\n * @param {[number, number]} image_size The size of the image. height x width.\n */\n post_process_generation(text, task, image_size) {\n const task_answer_post_processing_type = this.tasks_answer_post_processing_type.get(task) ?? 'pure_text';\n\n // remove the special tokens\n text = text.replaceAll('', '').replaceAll('', '');\n\n let final_answer;\n switch (task_answer_post_processing_type) {\n case 'pure_text':\n final_answer = text;\n break;\n\n case 'description_with_bboxes':\n case 'bboxes':\n case 'phrase_grounding':\n case 'ocr':\n const key = task_answer_post_processing_type === 'ocr' ? 'quad_boxes' : 'bboxes';\n const matches = text.matchAll(this.regexes[key]);\n const labels = [];\n const items = [];\n for (const [_, label, ...locations] of matches) {\n // Push new label, or duplicate the last label\n labels.push(label ? label.trim() : labels.at(-1) ?? '');\n items.push(locations.map((x, i) =>\n // NOTE: Add 0.5 to use the center position of the bin as the coordinate.\n (Number(x) + 0.5) / this.size_per_bin * image_size[i % 2])\n );\n }\n final_answer = { labels, [key]: items };\n break;\n\n default:\n throw new Error(`Task \"${task}\" (of type \"${task_answer_post_processing_type}\") not yet implemented.`);\n }\n\n return { [task]: final_answer }\n }\n}\n\n//////////////////////////////////////////////////\n/**\n * Helper class which is used to instantiate pretrained processors with the `from_pretrained` function.\n * The chosen processor class is determined by the type specified in the processor config.\n * \n * **Example:** Load a processor using `from_pretrained`.\n * ```javascript\n * let processor = await AutoProcessor.from_pretrained('openai/whisper-tiny.en');\n * ```\n * \n * **Example:** Run an image through a processor.\n * ```javascript\n * let processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16');\n * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * let image_inputs = await processor(image);\n * // {\n * // \"pixel_values\": {\n * // \"dims\": [ 1, 3, 224, 224 ],\n * // \"type\": \"float32\",\n * // \"data\": Float32Array [ -1.558687686920166, -1.558687686920166, -1.5440893173217773, ... ],\n * // \"size\": 150528\n * // },\n * // \"original_sizes\": [\n * // [ 533, 800 ]\n * // ],\n * // \"reshaped_input_sizes\": [\n * // [ 224, 224 ]\n * // ]\n * // }\n * ```\n */\nexport class AutoProcessor {\n static FEATURE_EXTRACTOR_CLASS_MAPPING = {\n ImageFeatureExtractor,\n WhisperFeatureExtractor,\n ViTFeatureExtractor,\n MobileViTFeatureExtractor,\n MobileViTImageProcessor,\n MobileNetV1FeatureExtractor,\n MobileNetV2FeatureExtractor,\n MobileNetV3FeatureExtractor,\n MobileNetV4FeatureExtractor,\n OwlViTFeatureExtractor,\n Owlv2ImageProcessor,\n CLIPFeatureExtractor,\n CLIPImageProcessor,\n Florence2Processor,\n ChineseCLIPFeatureExtractor,\n SiglipImageProcessor,\n ConvNextFeatureExtractor,\n ConvNextImageProcessor,\n SegformerFeatureExtractor,\n SapiensFeatureExtractor,\n BitImageProcessor,\n DPTImageProcessor,\n DPTFeatureExtractor,\n PvtImageProcessor,\n GLPNFeatureExtractor,\n BeitFeatureExtractor,\n DeiTFeatureExtractor,\n DetrFeatureExtractor,\n RTDetrImageProcessor,\n MaskFormerFeatureExtractor,\n YolosFeatureExtractor,\n DonutFeatureExtractor,\n NougatImageProcessor,\n EfficientNetImageProcessor,\n\n ViTImageProcessor,\n VitMatteImageProcessor,\n SamImageProcessor,\n Swin2SRImageProcessor,\n Wav2Vec2FeatureExtractor,\n SeamlessM4TFeatureExtractor,\n SpeechT5FeatureExtractor,\n ASTFeatureExtractor,\n ClapFeatureExtractor,\n PyAnnoteFeatureExtractor,\n WeSpeakerFeatureExtractor,\n }\n\n static PROCESSOR_CLASS_MAPPING = {\n WhisperProcessor,\n Wav2Vec2ProcessorWithLM,\n PyAnnoteProcessor,\n SamProcessor,\n SpeechT5Processor,\n OwlViTProcessor,\n Florence2Processor,\n }\n\n /**\n * Instantiate one of the processor classes of the library from a pretrained model.\n * \n * The processor class to instantiate is selected based on the `feature_extractor_type` property of the config object\n * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)\n * \n * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:\n * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co.\n * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a\n * user or organization name, like `dbmdz/bert-base-german-cased`.\n * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`.\n * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the processor.\n * \n * @returns {Promise} A new instance of the Processor class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n } = {}) {\n\n let preprocessorConfig = config ?? await getModelJSON(pretrained_model_name_or_path, 'preprocessor_config.json', true, {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n })\n\n // Determine feature extractor class\n // TODO: Ensure backwards compatibility with old configs\n let key = preprocessorConfig.feature_extractor_type ?? preprocessorConfig.image_processor_type;\n let feature_extractor_class = this.FEATURE_EXTRACTOR_CLASS_MAPPING[key];\n\n if (!feature_extractor_class) {\n if (preprocessorConfig.size !== undefined) {\n // Assume ImageFeatureExtractor\n console.warn(`Feature extractor type \"${key}\" not found, assuming ImageFeatureExtractor due to size parameter in config.`);\n feature_extractor_class = ImageFeatureExtractor;\n } else {\n throw new Error(`Unknown Feature Extractor type: ${key}`);\n }\n }\n\n // If no associated processor class, use default\n let processor_class = this.PROCESSOR_CLASS_MAPPING[preprocessorConfig.processor_class] ?? Processor;\n\n // Instantiate processor and feature extractor\n let feature_extractor = new feature_extractor_class(preprocessorConfig);\n return new processor_class(feature_extractor);\n }\n}\n//////////////////////////////////////////////////\n\n","\n/**\n * @file Tokenizers are used to prepare textual inputs for a model.\n * \n * **Example:** Create an `AutoTokenizer` and use it to tokenize a sentence.\n * This will automatically detect the tokenizer type based on the tokenizer class defined in `tokenizer.json`.\n * ```javascript\n * import { AutoTokenizer } from '@huggingface/transformers';\n * \n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');\n * const { input_ids } = await tokenizer('I love transformers!');\n * // Tensor {\n * // data: BigInt64Array(6) [101n, 1045n, 2293n, 19081n, 999n, 102n],\n * // dims: [1, 6],\n * // type: 'int64',\n * // size: 6,\n * // }\n * ```\n * \n * @module tokenizers\n */\nimport {\n Callable,\n} from './utils/generic.js';\n\nimport {\n reverseDictionary,\n escapeRegExp,\n isIntegralNumber,\n mergeArrays,\n len,\n} from './utils/core.js';\n\nimport {\n getModelJSON,\n} from './utils/hub.js';\n\nimport { max, min, round } from './utils/maths.js';\nimport { Tensor } from './utils/tensor.js';\n\nimport {\n PriorityQueue,\n TokenLattice,\n CharTrie,\n} from './utils/data-structures.js';\n\nimport { Template } from '@huggingface/jinja';\n\nimport {\n WHISPER_LANGUAGE_MAPPING,\n whisper_language_to_code,\n} from './models/whisper/common_whisper.js';\nimport { GITHUB_ISSUE_URL } from './utils/constants.js';\n\n/**\n * @typedef {Object} TokenizerProperties Additional tokenizer-specific properties.\n * @property {boolean} [legacy=false] Whether or not the `legacy` behavior of the tokenizer should be used.\n * @typedef {import('./utils/hub.js').PretrainedOptions & TokenizerProperties} PretrainedTokenizerOptions\n */\n\n/**\n * Loads a tokenizer from the specified path.\n * @param {string} pretrained_model_name_or_path The path to the tokenizer directory.\n * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.\n * @returns {Promise} A promise that resolves with information about the loaded tokenizer.\n */\nasync function loadTokenizer(pretrained_model_name_or_path, options) {\n\n const info = await Promise.all([\n getModelJSON(pretrained_model_name_or_path, 'tokenizer.json', true, options),\n getModelJSON(pretrained_model_name_or_path, 'tokenizer_config.json', true, options),\n ])\n\n // Override legacy option if `options.legacy` is not null\n if (options.legacy !== null) {\n info[1].legacy = options.legacy;\n }\n return info;\n}\n\n\n/**\n * Helper function to split a string on a regex, but keep the delimiters.\n * This is required, because the JavaScript `.split()` method does not keep the delimiters,\n * and wrapping in a capturing group causes issues with existing capturing groups (due to nesting).\n * @param {string} text The text to split.\n * @param {RegExp} regex The regex to split on.\n * @returns {string[]} The split string.\n */\nfunction regexSplit(text, regex) {\n const result = [];\n let prev = 0;\n for (const match of text.matchAll(regex)) {\n const fullMatch = match[0];\n if (prev < match.index) {\n result.push(text.slice(prev, match.index));\n }\n if (fullMatch.length > 0) {\n result.push(fullMatch);\n }\n prev = match.index + fullMatch.length;\n }\n if (prev < text.length) {\n result.push(text.slice(prev));\n }\n return result;\n}\n\n\n/**\n * Helper method to construct a pattern from a config object.\n * @param {Object} pattern The pattern object.\n * @param {boolean} invert Whether to invert the pattern.\n * @returns {RegExp|null} The compiled pattern.\n */\nfunction createPattern(pattern, invert = true) {\n\n if (pattern.Regex !== undefined) {\n // In certain cases, the pattern may contain unnecessary escape sequences (e.g., \\# or \\& or \\~).\n // i.e., valid in Python (where the patterns are exported from) but invalid in JavaScript (where the patterns are parsed).\n // This isn't an issue when creating the regex w/o the 'u' flag, but it is when the 'u' flag is used.\n // For this reason, it is necessary to remove these backslashes before creating the regex.\n // See https://stackoverflow.com/a/63007777/13989043 for more information\n let regex = pattern.Regex.replace(/\\\\([#&~])/g, '$1'); // TODO: add more characters to this list if necessary\n\n // We also handle special cases where the regex contains invalid (non-JS compatible) syntax.\n for (const [key, value] of PROBLEMATIC_REGEX_MAP) {\n regex = regex.replaceAll(key, value);\n }\n\n return new RegExp(regex, 'gu');\n\n } else if (pattern.String !== undefined) {\n const escaped = escapeRegExp(pattern.String);\n // NOTE: if invert is true, we wrap the pattern in a group so that it is kept when performing .split()\n return new RegExp(invert ? escaped : `(${escaped})`, 'gu');\n\n } else {\n console.warn('Unknown pattern type:', pattern)\n return null;\n }\n}\n\n/**\n * Helper function to convert an Object to a Map\n * @param {Object} obj The object to convert.\n * @returns {Map} The map.\n */\nfunction objectToMap(obj) {\n return new Map(Object.entries(obj));\n}\n\n/**\n * Helper function to convert a tensor to a list before decoding.\n * @param {Tensor} tensor The tensor to convert.\n * @returns {number[]} The tensor as a list.\n */\nfunction prepareTensorForDecode(tensor) {\n const dims = tensor.dims;\n switch (dims.length) {\n case 1:\n return tensor.tolist();\n case 2:\n if (dims[0] !== 1) {\n throw new Error('Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.');\n }\n return tensor.tolist()[0];\n default:\n throw new Error(`Expected tensor to have 1-2 dimensions, got ${dims.length}.`)\n }\n}\n\n/**\n * Clean up a list of simple English tokenization artifacts like spaces before punctuations and abbreviated forms\n * @param {string} text The text to clean up.\n * @returns {string} The cleaned up text.\n */\nfunction clean_up_tokenization(text) {\n // Clean up a list of simple English tokenization artifacts\n // like spaces before punctuations and abbreviated forms\n return text.replace(/ \\./g, '.')\n .replace(/ \\?/g, '?')\n .replace(/ \\!/g, '!')\n .replace(/ ,/g, ',')\n .replace(/ \\' /g, \"'\")\n .replace(/ n\\'t/g, \"n't\")\n .replace(/ \\'m/g, \"'m\")\n .replace(/ \\'s/g, \"'s\")\n .replace(/ \\'ve/g, \"'ve\")\n .replace(/ \\'re/g, \"'re\");\n}\n\n/**\n * Helper function to remove accents from a string.\n * @param {string} text The text to remove accents from.\n * @returns {string} The text with accents removed.\n */\nfunction remove_accents(text) {\n return text.replace(/\\p{M}/gu, '');\n}\n\n/**\n * Helper function to lowercase a string and remove accents.\n * @param {string} text The text to lowercase and remove accents from.\n * @returns {string} The lowercased text with accents removed.\n */\nfunction lowercase_and_remove_accent(text) {\n return remove_accents(text.toLowerCase());\n}\n\n\n/**\n * Checks whether the given Unicode codepoint represents a CJK (Chinese, Japanese, or Korean) character.\n *\n * A \"chinese character\" is defined as anything in the CJK Unicode block:\n * https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)\n *\n * Note that the CJK Unicode block is NOT all Japanese and Korean characters, despite its name.\n * The modern Korean Hangul alphabet is a different block, as is Japanese Hiragana and Katakana.\n * Those alphabets are used to write space-separated words, so they are not treated specially\n * and are handled like all other languages.\n *\n * @param {number|bigint} cp The Unicode codepoint to check.\n * @returns {boolean} True if the codepoint represents a CJK character, false otherwise.\n */\nexport function is_chinese_char(cp) {\n return (\n (cp >= 0x4E00 && cp <= 0x9FFF)\n || (cp >= 0x3400 && cp <= 0x4DBF)\n || (cp >= 0x20000 && cp <= 0x2A6DF)\n || (cp >= 0x2A700 && cp <= 0x2B73F)\n || (cp >= 0x2B740 && cp <= 0x2B81F)\n || (cp >= 0x2B820 && cp <= 0x2CEAF)\n || (cp >= 0xF900 && cp <= 0xFAFF)\n || (cp >= 0x2F800 && cp <= 0x2FA1F)\n )\n}\n\n/**\n * Helper function to fuse consecutive unknown tokens.\n * @param {string[]} arr The list of input tokens\n * @param {Map} tokens_to_ids The mapping from tokens to token ids.\n * @param {number} unk_token_id The value to fuse on.\n * @private\n */\nfunction fuse_unk(arr, tokens_to_ids, unk_token_id) {\n const fused = [];\n let i = 0;\n while (i < arr.length) {\n fused.push(arr[i])\n if ((tokens_to_ids.get(arr[i]) ?? unk_token_id) !== unk_token_id) {\n ++i;\n continue;\n }\n\n while (++i < arr.length && (tokens_to_ids.get(arr[i]) ?? unk_token_id) === unk_token_id) {\n if (tokens_to_ids.get(fused.at(-1)) !== unk_token_id) {\n fused[fused.length - 1] += arr[i];\n }\n }\n }\n\n return fused;\n}\n\n/**\n * Split a string on whitespace.\n * @param {string} text The text to split.\n * @returns {string[]} The split string.\n */\nfunction whitespace_split(text) {\n return text.match(/\\S+/g) || [];\n}\n\nconst PUNCTUATION_REGEX = '\\\\p{P}\\\\u0021-\\\\u002F\\\\u003A-\\\\u0040\\\\u005B-\\\\u0060\\\\u007B-\\\\u007E';\nconst PUNCTUATION_ONLY_REGEX = new RegExp(`^[${PUNCTUATION_REGEX}]+$`, 'gu');\nconst BLOOM_SPLIT_CHARS = '.,!?\\u2026\\u3002\\uff0c\\u3001\\u0964\\u06d4\\u060c';\n\n// A mapping of regex patterns to their equivalent (but possibly longer) JS-compatible versions.\nconst PROBLEMATIC_REGEX_MAP = new Map([\n // This uses the case insensitive group modifier, which is not supported in JavaScript.\n // When parsing the regex, an \"Invalid group\" error is thrown.\n [\"(?i:'s|'t|'re|'ve|'m|'ll|'d)\", \"(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))\"],\n\n // Used to override the default (invalid) regex of the bloom pretokenizer.\n // For more information, see https://github.com/huggingface/transformers.js/issues/94\n [` ?[^(\\\\s|[${BLOOM_SPLIT_CHARS}])]+`, ` ?[^\\\\s${BLOOM_SPLIT_CHARS}]+`],\n])\n\n\n/**\n * Represent a token added by the user on top of the existing Model vocabulary.\n * AddedToken can be configured to specify the behavior they should have in various situations like:\n * - Whether they should only match single words\n * - Whether to include any whitespace on its left or right\n */\nclass AddedToken {\n /**\n * Creates a new instance of AddedToken.\n * @param {Object} config Added token configuration object.\n * @param {string} config.content The content of the added token.\n * @param {number} config.id The id of the added token.\n * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words.\n * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left.\n * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right.\n * @param {boolean} [config.normalized=false] Whether this token should be normalized.\n * @param {boolean} [config.special=false] Whether this token is special.\n */\n constructor(config) {\n this.content = config.content;\n this.id = config.id;\n this.single_word = config.single_word ?? false;\n this.lstrip = config.lstrip ?? false;\n this.rstrip = config.rstrip ?? false;\n this.special = config.special ?? false;\n this.normalized = config.normalized ?? null;\n }\n}\n\n/**\n * Abstract base class for tokenizer models.\n *\n * @extends Callable\n */\nexport class TokenizerModel extends Callable {\n /**\n * Creates a new instance of TokenizerModel.\n * @param {Object} config The configuration object for the TokenizerModel.\n */\n constructor(config) {\n super();\n this.config = config;\n\n /** @type {string[]} */\n this.vocab = [];\n\n /**\n * A mapping of tokens to ids.\n * @type {Map}\n */\n this.tokens_to_ids = new Map();\n\n this.unk_token_id = undefined;\n this.unk_token = undefined;\n this.end_of_word_suffix = undefined;\n\n /** @type {boolean} Whether to fuse unknown tokens when encoding. Defaults to false. */\n this.fuse_unk = this.config.fuse_unk ?? false;\n }\n\n /**\n * Instantiates a new TokenizerModel instance based on the configuration object provided.\n * @param {Object} config The configuration object for the TokenizerModel.\n * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor.\n * @returns {TokenizerModel} A new instance of a TokenizerModel.\n * @throws Will throw an error if the TokenizerModel type in the config is not recognized.\n */\n static fromConfig(config, ...args) {\n switch (config.type) {\n case 'WordPiece':\n return new WordPieceTokenizer(config);\n case 'Unigram':\n // @ts-ignore\n return new Unigram(config, ...args);\n case 'BPE':\n return new BPE(config);\n\n default:\n // Some tokenizers, like for google-t5/t5-small, do not have a `type` field.\n // In this case, we can infer the tokenizer type based on the structure of the `vocab` field.\n if (config.vocab) {\n if (Array.isArray(config.vocab)) {\n // config.vocab is of type `[string, number][]`\n // @ts-ignore\n return new Unigram(config, ...args);\n } else {\n // @ts-ignore\n return new LegacyTokenizerModel(config, ...args);\n }\n }\n throw new Error(`Unknown TokenizerModel type: ${config.type}`);\n }\n }\n\n /**\n * Internal function to call the TokenizerModel instance.\n * @param {string[]} tokens The tokens to encode.\n * @returns {string[]} The encoded tokens.\n */\n _call(tokens) {\n tokens = this.encode(tokens);\n if (this.fuse_unk) {\n // Fuse unknown tokens\n tokens = fuse_unk(tokens, this.tokens_to_ids, this.unk_token_id);\n }\n return tokens;\n }\n\n /**\n * Encodes a list of tokens into a list of token IDs.\n * @param {string[]} tokens The tokens to encode.\n * @returns {string[]} The encoded tokens.\n * @throws Will throw an error if not implemented in a subclass.\n */\n encode(tokens) {\n throw Error(\"encode should be implemented in subclass.\")\n }\n\n /**\n * Converts a list of tokens into a list of token IDs.\n * @param {string[]} tokens The tokens to convert.\n * @returns {number[]} The converted token IDs.\n */\n convert_tokens_to_ids(tokens) {\n return tokens.map(t => this.tokens_to_ids.get(t) ?? this.unk_token_id);\n }\n\n /**\n * Converts a list of token IDs into a list of tokens.\n * @param {number[]|bigint[]} ids The token IDs to convert.\n * @returns {string[]} The converted tokens.\n */\n convert_ids_to_tokens(ids) {\n return ids.map(i => this.vocab[i] ?? this.unk_token);\n }\n}\n\n/**\n * A subclass of TokenizerModel that uses WordPiece encoding to encode tokens.\n * @extends TokenizerModel\n */\nclass WordPieceTokenizer extends TokenizerModel {\n /**\n * @param {Object} config The configuration object.\n * @param {Object} config.vocab A mapping of tokens to ids.\n * @param {string} config.unk_token The unknown token string.\n * @param {string} config.continuing_subword_prefix The prefix to use for continuing subwords.\n * @param {number} [config.max_input_chars_per_word=100] The maximum number of characters per word.\n */\n constructor(config) {\n super(config);\n /**\n * A mapping of tokens to ids.\n * @type {Map}\n */\n this.tokens_to_ids = objectToMap(config.vocab);\n\n /**\n * The id of the unknown token.\n * @type {number}\n */\n this.unk_token_id = this.tokens_to_ids.get(config.unk_token);\n\n /**\n * The unknown token string.\n * @type {string}\n */\n this.unk_token = config.unk_token;\n\n /**\n * The maximum number of characters allowed per word.\n * @type {number}\n */\n this.max_input_chars_per_word = config.max_input_chars_per_word ?? 100;\n\n /**\n * An array of tokens.\n * @type {string[]}\n */\n this.vocab = new Array(this.tokens_to_ids.size);\n for (const [key, value] of this.tokens_to_ids) {\n this.vocab[value] = key;\n }\n }\n\n /**\n * Encodes an array of tokens using WordPiece encoding.\n * @param {string[]} tokens The tokens to encode.\n * @returns {string[]} An array of encoded tokens.\n */\n encode(tokens) {\n const outputTokens = [];\n for (const token of tokens) {\n const chars = [...token];\n if (chars.length > this.max_input_chars_per_word) {\n outputTokens.push(this.unk_token);\n continue;\n }\n\n let isUnknown = false;\n let start = 0;\n const subTokens = [];\n\n while (start < chars.length) {\n let end = chars.length;\n let currentSubstring = null;\n while (start < end) {\n let substr = chars.slice(start, end).join('');\n\n if (start > 0) {\n substr = this.config.continuing_subword_prefix + substr;\n }\n if (this.tokens_to_ids.has(substr)) {\n currentSubstring = substr;\n break;\n }\n\n --end;\n }\n if (currentSubstring === null) {\n isUnknown = true;\n break;\n }\n subTokens.push(currentSubstring);\n start = end;\n }\n if (isUnknown) {\n outputTokens.push(this.unk_token);\n } else {\n outputTokens.push(...subTokens);\n }\n }\n\n return outputTokens;\n }\n\n}\n\n/**\n * Class representing a Unigram tokenizer model.\n * @extends TokenizerModel\n */\nclass Unigram extends TokenizerModel {\n /**\n * Create a new Unigram tokenizer model.\n * @param {Object} config The configuration object for the Unigram model.\n * @param {number} config.unk_id The ID of the unknown token\n * @param {any[][]} config.vocab A 2D array representing a mapping of tokens to scores.\n * @param {Object} moreConfig Additional configuration object for the Unigram model.\n */\n constructor(config, moreConfig) {\n super(config);\n\n const vocabSize = config.vocab.length;\n this.vocab = new Array(vocabSize);\n this.scores = new Array(vocabSize);\n for (let i = 0; i < vocabSize; ++i) {\n const piece = config.vocab[i];\n this.vocab[i] = piece[0];\n this.scores[i] = piece[1];\n }\n\n this.unk_token_id = config.unk_id;\n this.unk_token = this.vocab[config.unk_id];\n\n this.tokens_to_ids = new Map(this.vocab.map((x, i) => [x, i]));\n this.bos_token = ' '; // beginning of a sentence token\n\n this.bos_token_id = this.tokens_to_ids.get(this.bos_token); // NOTE: may be undefined\n this.eos_token = moreConfig.eos_token;\n\n this.eos_token_id = this.tokens_to_ids.get(this.eos_token);\n this.unk_token = this.vocab[this.unk_token_id];\n\n this.minScore = min(this.scores)[0];\n\n this.unk_score = this.minScore - 10.0;\n this.scores[this.unk_token_id] = this.unk_score;\n\n this.trie = new CharTrie();\n this.trie.extend(this.vocab);\n\n // NOTE: `fuse_unk` is hardcoded to true for Unigram models\n // See: https://github.com/huggingface/tokenizers/blob/b58227c7f1ccf8b73ee2268354336da56d91e492/tokenizers/src/models/unigram/model.rs#L119\n this.fuse_unk = true;\n }\n\n /**\n * Populates lattice nodes.\n * @param {TokenLattice} lattice The token lattice to populate with nodes.\n */\n populateNodes(lattice) {\n const chars = lattice.chars;\n const mblen = 1;\n let beginPos = 0;\n while (beginPos < chars.length) {\n let hasSingleNode = false;\n\n const tokens = [];\n const sliced = chars.slice(beginPos).join('');\n const prefixedTokens = this.trie.commonPrefixSearch(sliced);\n for (const token of prefixedTokens) {\n tokens.push(token);\n const tokenId = this.tokens_to_ids.get(token);\n const tokenScore = this.scores[tokenId];\n const n = len(token);\n lattice.insert(beginPos, n, tokenScore, tokenId);\n if (!hasSingleNode && n === mblen) {\n hasSingleNode = true;\n }\n }\n if (!hasSingleNode) {\n lattice.insert(beginPos, mblen, this.unk_score, this.unk_token_id);\n }\n beginPos += mblen;\n }\n }\n\n /**\n * Encodes an array of tokens into an array of subtokens using the unigram model.\n *\n * @param {string} normalized The normalized string.\n * @returns {string[]} An array of subtokens obtained by encoding the input tokens using the unigram model.\n */\n tokenize(normalized) {\n const lattice = new TokenLattice(normalized, this.bos_token_id, this.eos_token_id);\n this.populateNodes(lattice);\n return lattice.tokens();\n }\n\n /**\n * Encodes an array of tokens using Unigram encoding.\n * @param {string[]} tokens The tokens to encode.\n * @returns {string[]} An array of encoded tokens.\n */\n encode(tokens) {\n const toReturn = [];\n for (const token of tokens) {\n const tokenized = this.tokenize(token);\n toReturn.push(...tokenized);\n }\n return toReturn;\n }\n\n}\n\n/**\n * Returns list of utf-8 byte and a mapping to unicode strings.\n * Specifically avoids mapping to whitespace/control characters the BPE code barfs on.\n * @returns {Object} Object with utf-8 byte keys and unicode string values.\n */\nconst BYTES_TO_UNICODE = (() => {\n // Returns list of utf-8 byte and a mapping to unicode strings.\n // We specifically avoids mapping to whitespace/control characters\n // the bpe code barfs on.\n\n const bs = [\n ...Array.from({ length: \"~\".charCodeAt(0) - \"!\".charCodeAt(0) + 1 }, (_, i) => i + \"!\".charCodeAt(0)),\n ...Array.from({ length: \"¬\".charCodeAt(0) - \"¡\".charCodeAt(0) + 1 }, (_, i) => i + \"¡\".charCodeAt(0)),\n ...Array.from({ length: \"ÿ\".charCodeAt(0) - \"®\".charCodeAt(0) + 1 }, (_, i) => i + \"®\".charCodeAt(0)),\n ];\n const cs = bs.slice();\n let n = 0;\n for (let b = 0; b < 256; ++b) {\n if (!bs.includes(b)) {\n bs.push(b);\n cs.push(256 + n);\n n += 1;\n }\n }\n const ccs = cs.map(n => String.fromCharCode(n));\n return Object.fromEntries(bs.map((b, i) => [b, ccs[i]]));\n})();\n\nconst UNICODE_TO_BYTES = reverseDictionary(BYTES_TO_UNICODE);\n\n\n/**\n * @typedef {Object} BPENode\n * @property {string} token The token associated with the node\n * @property {number} bias A positional bias for the node.\n * @property {number} [score] The score of the node.\n * @property {BPENode} [prev] The previous node in the linked list.\n * @property {BPENode} [next] The next node in the linked list.\n */\n\n/**\n * BPE class for encoding text into Byte-Pair-Encoding (BPE) tokens.\n * @extends TokenizerModel\n */\nclass BPE extends TokenizerModel {\n /**\n * Create a BPE instance.\n * @param {Object} config The configuration object for BPE.\n * @param {Object} config.vocab A mapping of tokens to ids.\n * @param {string[]|[string, string][]} config.merges An array of BPE merges as strings.\n * @param {string} config.unk_token The unknown token used for out of vocabulary words.\n * @param {string} config.end_of_word_suffix The suffix to place at the end of each word.\n * @param {string} [config.continuing_subword_suffix] The suffix to insert between words.\n * @param {boolean} [config.byte_fallback=false] Whether to use spm byte-fallback trick (defaults to False)\n * @param {boolean} [config.ignore_merges=false] Whether or not to match tokens with the vocab before using merges.\n */\n constructor(config) {\n super(config);\n\n /** @type {Map} */\n this.tokens_to_ids = objectToMap(config.vocab);\n\n this.unk_token_id = this.tokens_to_ids.get(config.unk_token);\n this.unk_token = config.unk_token;\n\n this.vocab = new Array(this.tokens_to_ids.size);\n for (const [key, value] of this.tokens_to_ids) {\n this.vocab[value] = key;\n }\n\n // Tokenizers >= 0.20.0 serializes BPE merges as a [string, string][] instead of a string[],\n // which resolves the ambiguity for merges containing spaces.\n const use_new_merge_format = Array.isArray(config.merges[0]);\n\n /** @type {[string, string][]} */\n this.merges = use_new_merge_format\n ? /** @type {[string, string][]} */(config.merges)\n : (/** @type {string[]} */(config.merges)).map(x => /** @type {[string, string]} */(x.split(' ', 2)));\n this.bpe_ranks = new Map(this.merges.map((x, i) => [JSON.stringify(x), i]));\n\n this.end_of_word_suffix = config.end_of_word_suffix;\n\n // NOTE: `continuing_subword_suffix` is custom (to support `BlenderbotSmallTokenizer`)\n this.continuing_subword_suffix = config.continuing_subword_suffix ?? null;\n\n this.byte_fallback = this.config.byte_fallback ?? false;\n\n if (this.byte_fallback) {\n this.text_encoder = new TextEncoder();\n }\n\n this.ignore_merges = this.config.ignore_merges ?? false;\n\n /** @type {Map} */\n this.cache = new Map();\n }\n\n /**\n * Apply Byte-Pair-Encoding (BPE) to a given token. Efficient heap-based priority\n * queue implementation adapted from https://github.com/belladoreai/llama-tokenizer-js.\n * @param {string} token The token to encode.\n * @returns {string[]} The BPE encoded tokens.\n */\n bpe(token) {\n if (token.length === 0) {\n return [];\n }\n\n const cached = this.cache.get(token);\n if (cached !== undefined) {\n return cached;\n }\n\n const word = Array.from(token);\n if (this.end_of_word_suffix) {\n word[word.length - 1] += this.end_of_word_suffix;\n }\n\n let result = [];\n if (word.length > 1) {\n // Create a priority queue to store the nodes that will be merged.\n // The comparator function compares the scores of the nodes.\n const queue = new PriorityQueue((a, b) => a.score < b.score);\n\n // Construct a doubly-linked list of nodes that will be inserted into the priority queue,\n // starting with the individual characters. We also populate each node with a positional\n // bias to break ties in the priority queue.\n let startingNode = {\n token: word[0],\n bias: 0,\n prev: null,\n next: null,\n }\n\n let previousNode = startingNode\n for (let i = 1; i < word.length; ++i) {\n const currentNode = {\n bias: i / word.length, // Add fractional component to break ties\n token: word[i],\n prev: previousNode,\n next: null,\n }\n previousNode.next = currentNode\n this._add_node(queue, previousNode)\n previousNode = currentNode\n }\n\n while (!queue.isEmpty()) {\n // Get the next node with the highest priority\n const node = queue.pop();\n\n // Check that this merge is still possible\n if (node.deleted || !node.next || node.next.deleted) continue;\n\n // Here, we mark the current node (left side of the merge) and the next node (right side of the merge) as deleted.\n // This is because they will both be replaced by a new node representing the merge result.\n node.deleted = true;\n node.next.deleted = true;\n\n // Next, we fix the node that comes before the current node (i.e., left side of the merge).\n if (node.prev) {\n\n // Make a shallow copy of the previous node\n const newPreviousNode = { ...node.prev };\n\n // Mark the old previous node as deleted. This avoids erroneous merges later,\n // because there may still be references to this node in the priority queue.\n node.prev.deleted = true;\n node.prev = newPreviousNode;\n\n // Update the reference of the previous node, by pointing its previous node to this new previous node.\n if (newPreviousNode.prev) {\n newPreviousNode.prev.next = newPreviousNode;\n } else {\n // If the previous of the previous node does not exist, it means that\n // `newPreviousNode` must be the new `startingNode`.\n startingNode = newPreviousNode;\n }\n }\n\n // Create a new node which represents the result of the merge.\n const merged = {\n token: node.token + node.next.token,\n bias: node.bias,\n prev: node.prev,\n next: node.next.next,\n }\n\n // We now consider where we can add the new merged node to the priority queue:\n // 1. prev <-> merged\n if (merged.prev) {\n merged.prev.next = merged;\n this._add_node(queue, merged.prev);\n } else {\n // If `merged.prev` does not exist, then `merged` must be the new `startingNode`.\n startingNode = merged;\n }\n\n // 2. merged <-> next\n if (merged.next) {\n merged.next.prev = merged;\n this._add_node(queue, merged);\n }\n }\n\n // Traverse the linked list, starting from the `startingNode`, and collect the tokens.\n for (let currentNode = startingNode; currentNode !== null; currentNode = currentNode.next) {\n result.push(currentNode.token);\n }\n } else {\n result = word;\n }\n\n // Possibly append suffix\n if (this.continuing_subword_suffix) {\n // Do not append suffix to the last token\n for (let i = 0; i < result.length - 1; ++i) {\n result[i] += this.continuing_subword_suffix;\n }\n }\n\n // Save the result to the cache\n this.cache.set(token, result);\n\n return result;\n }\n\n\n /**\n * Helper function to add a node to the priority queue.\n * @param {PriorityQueue} queue \n * @param {BPENode} node\n * @private\n */\n _add_node(queue, node) {\n // `score` is a measure of the merge priority: lower means higher priority\n // We use the BPE rank as a measure of priority (i.e., the local of the merge in the merges list)\n // We also add a fractional component to the score to break ties (with the earlier character having higher priority)\n const rank = this.bpe_ranks.get(JSON.stringify([node.token, node.next.token]));\n if (rank !== undefined) {\n node.score = rank + node.bias;\n queue.push(node);\n }\n }\n\n /**\n * Encodes the input sequence of tokens using the BPE algorithm and returns the resulting subword tokens.\n * @param {string[]} tokens The input sequence of tokens to encode.\n * @returns {string[]} The resulting subword tokens after applying the BPE algorithm to the input sequence of tokens.\n */\n encode(tokens) {\n const outputTokens = [];\n\n for (const token of tokens) {\n if (this.ignore_merges && this.tokens_to_ids.has(token)) {\n outputTokens.push(token);\n continue;\n }\n const bpe_token_list = this.bpe(token);\n\n for (const t of bpe_token_list) {\n if (this.tokens_to_ids.has(t)) {\n outputTokens.push(t);\n } else if (this.byte_fallback) {\n const byteTokens = Array.from(this.text_encoder.encode(t))\n .map(x => `<0x${x.toString(16).toUpperCase().padStart(2, '0')}>`);\n if (byteTokens.every(x => this.tokens_to_ids.has(x))) {\n // Ensure the byte tokens are actually in the vocabulary, otherwise\n // we fall back to the unknown token. For more information, see\n // https://github.com/huggingface/transformers/issues/28096.\n outputTokens.push(...byteTokens);\n } else {\n outputTokens.push(this.unk_token);\n }\n } else {\n outputTokens.push(this.unk_token);\n }\n }\n }\n\n return outputTokens;\n }\n\n}\n\n/**\n * Legacy tokenizer class for tokenizers with only a vocabulary.\n */\nclass LegacyTokenizerModel extends TokenizerModel {\n /**\n * Create a LegacyTokenizerModel instance.\n * @param {Object} config The configuration object for LegacyTokenizerModel.\n * @param {Object} config.vocab A (possibly nested) mapping of tokens to ids.\n * @param {Object} moreConfig Additional configuration object for the LegacyTokenizerModel model.\n */\n constructor(config, moreConfig) {\n super(config);\n\n /**@type {Map} */\n this.tokens_to_ids = objectToMap(\n moreConfig.target_lang\n ? config.vocab[moreConfig.target_lang]\n : config.vocab\n );\n\n this.bos_token = moreConfig.bos_token;\n this.bos_token_id = this.tokens_to_ids.get(this.bos_token);\n\n this.eos_token = moreConfig.eos_token;\n this.eos_token_id = this.tokens_to_ids.get(this.eos_token);\n\n this.pad_token = moreConfig.pad_token;\n this.pad_token_id = this.tokens_to_ids.get(this.pad_token);\n\n this.unk_token = moreConfig.unk_token;\n this.unk_token_id = this.tokens_to_ids.get(this.unk_token);\n\n this.vocab = new Array(this.tokens_to_ids.size);\n for (const [key, value] of this.tokens_to_ids) {\n this.vocab[value] = key;\n }\n }\n\n encode(tokens) {\n return tokens;\n }\n}\n\n\n/**\n * A base class for text normalization.\n * @abstract\n */\nclass Normalizer extends Callable {\n /**\n * @param {Object} config The configuration object for the normalizer.\n */\n constructor(config) {\n super();\n this.config = config;\n }\n\n /**\n * Factory method for creating normalizers from config objects.\n * @static\n * @param {Object} config The configuration object for the normalizer.\n * @returns {Normalizer} A Normalizer object.\n * @throws {Error} If an unknown Normalizer type is specified in the config.\n */\n static fromConfig(config) {\n if (config === null) return null;\n switch (config.type) {\n case 'BertNormalizer':\n return new BertNormalizer(config);\n case 'Precompiled':\n return new Precompiled(config);\n case 'Sequence':\n return new NormalizerSequence(config);\n case 'Replace':\n return new Replace(config);\n case 'NFC':\n return new NFC(config);\n case 'NFKC':\n return new NFKC(config);\n case 'NFKD':\n return new NFKD(config);\n case 'Strip':\n return new StripNormalizer(config);\n case 'StripAccents':\n return new StripAccents(config);\n case 'Lowercase':\n return new Lowercase(config);\n case 'Prepend':\n return new Prepend(config);\n default:\n throw new Error(`Unknown Normalizer type: ${config.type}`);\n }\n }\n\n /**\n * Normalize the input text.\n * @abstract\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n * @throws {Error} If this method is not implemented in a subclass.\n */\n normalize(text) {\n throw Error(\"normalize should be implemented in subclass.\")\n }\n\n /**\n * Alias for {@link Normalizer#normalize}.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n _call(text) {\n return this.normalize(text);\n }\n\n}\n\n/**\n * Replace normalizer that replaces occurrences of a pattern with a given string or regular expression.\n * @extends Normalizer\n */\nclass Replace extends Normalizer {\n /**\n * Normalize the input text by replacing the pattern with the content.\n * @param {string} text The input text to be normalized.\n * @returns {string} The normalized text after replacing the pattern with the content.\n */\n normalize(text) {\n const pattern = createPattern(this.config.pattern);\n return pattern === null\n ? text\n : text.replaceAll(pattern, this.config.content);\n }\n}\n\n/**\n * A normalizer that applies Unicode normalization form C (NFC) to the input text.\n * @extends Normalizer\n */\nclass NFC extends Normalizer {\n /**\n * Normalize the input text by applying Unicode normalization form C (NFC).\n * @param {string} text The input text to be normalized.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = text.normalize('NFC')\n return text;\n }\n}\n\n/**\n * NFKC Normalizer.\n * @extends Normalizer\n */\nclass NFKC extends Normalizer {\n /**\n * Normalize text using NFKC normalization.\n * @param {string} text The text to be normalized.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = text.normalize('NFKC')\n return text;\n }\n}\n/**\n * NFKD Normalizer.\n * @extends Normalizer\n */\nclass NFKD extends Normalizer {\n /**\n * Normalize text using NFKD normalization.\n * @param {string} text The text to be normalized.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = text.normalize('NFKD')\n return text;\n }\n}\n\n/**\n * A normalizer that strips leading and/or trailing whitespace from the input text.\n */\nclass StripNormalizer extends Normalizer {\n /**\n * Strip leading and/or trailing whitespace from the input text.\n * @param {string} text The input text.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n if (this.config.strip_left && this.config.strip_right) {\n // Fast path to avoid an extra trim call\n text = text.trim();\n } else {\n if (this.config.strip_left) {\n text = text.trimStart();\n }\n if (this.config.strip_right) {\n text = text.trimEnd();\n }\n }\n return text;\n }\n}\n\n/**\n * StripAccents normalizer removes all accents from the text.\n * @extends Normalizer\n */\nclass StripAccents extends Normalizer {\n /**\n * Remove all accents from the text.\n * @param {string} text The input text.\n * @returns {string} The normalized text without accents.\n */\n normalize(text) {\n text = remove_accents(text);\n return text;\n }\n}\n\n/**\n * A Normalizer that lowercases the input string.\n * @extends Normalizer\n */\nclass Lowercase extends Normalizer {\n /**\n * Lowercases the input string.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = text.toLowerCase();\n return text;\n }\n}\n\n/**\n * A Normalizer that prepends a string to the input string.\n * @extends Normalizer\n */\nclass Prepend extends Normalizer {\n /**\n * Prepends the input string.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n text = this.config.prepend + text;\n return text;\n }\n}\n\n/**\n * A Normalizer that applies a sequence of Normalizers.\n * @extends Normalizer\n */\nclass NormalizerSequence extends Normalizer {\n /**\n * Create a new instance of NormalizerSequence.\n * @param {Object} config The configuration object.\n * @param {Object[]} config.normalizers An array of Normalizer configuration objects.\n */\n constructor(config) {\n super(config);\n this.normalizers = config.normalizers.map(x => Normalizer.fromConfig(x));\n }\n /**\n * Apply a sequence of Normalizers to the input text.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n return this.normalizers.reduce((t, normalizer) => {\n return normalizer.normalize(t);\n }, text);\n }\n}\n\n/**\n * A class representing a normalizer used in BERT tokenization.\n * @extends Normalizer\n */\nclass BertNormalizer extends Normalizer {\n /**\n * Adds whitespace around any CJK (Chinese, Japanese, or Korean) character in the input text.\n *\n * @param {string} text The input text to tokenize.\n * @returns {string} The tokenized text with whitespace added around CJK characters.\n */\n _tokenize_chinese_chars(text) {\n /* Adds whitespace around any CJK character. */\n const output = [];\n for (let i = 0; i < text.length; ++i) {\n const char = text[i];\n const cp = char.charCodeAt(0);\n if (is_chinese_char(cp)) {\n output.push(\" \");\n output.push(char);\n output.push(\" \");\n } else {\n output.push(char);\n }\n }\n return output.join(\"\");\n }\n\n /**\n * Strips accents from the given text.\n * @param {string} text The text to strip accents from.\n * @returns {string} The text with accents removed.\n */\n stripAccents(text) {\n // \"Mark, Nonspacing\" (Mn)\n return text.normalize('NFD').replace(/\\p{Mn}/gu, '');\n }\n\n\n /**\n * Checks whether `char` is a control character.\n * @param {string} char The character to check.\n * @returns {boolean} Whether `char` is a control character.\n * @private\n */\n _is_control(char) {\n switch (char) {\n case '\\t':\n case '\\n':\n case '\\r':\n // These are technically control characters but we count them as whitespace characters.\n return false;\n\n default:\n // Check if unicode category starts with C:\n // Cc - Control\n // Cf - Format\n // Co - Private Use\n // Cs - Surrogate\n return /^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$/u.test(char);\n }\n }\n\n /**\n * Performs invalid character removal and whitespace cleanup on text.\n * @param {string} text The text to clean.\n * @returns {string} The cleaned text.\n * @private\n */\n _clean_text(text) {\n const output = [];\n for (const char of text) {\n const cp = char.charCodeAt(0);\n if (cp === 0 || cp === 0xFFFD || this._is_control(char)) {\n continue;\n }\n if (/^\\s$/.test(char)) { // is whitespace\n output.push(\" \");\n } else {\n output.push(char);\n }\n }\n return output.join(\"\");\n }\n /**\n * Normalizes the given text based on the configuration.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n if (this.config.clean_text) {\n text = this._clean_text(text);\n }\n\n if (this.config.handle_chinese_chars) {\n text = this._tokenize_chinese_chars(text);\n }\n\n if (this.config.lowercase) {\n text = text.toLowerCase();\n\n if (this.config.strip_accents !== false) {\n text = this.stripAccents(text);\n }\n } else if (this.config.strip_accents) {\n text = this.stripAccents(text);\n }\n\n return text;\n }\n}\n\n/**\n * A callable class representing a pre-tokenizer used in tokenization. Subclasses\n * should implement the `pre_tokenize_text` method to define the specific pre-tokenization logic.\n * @extends Callable\n */\nclass PreTokenizer extends Callable {\n /**\n * Factory method that returns an instance of a subclass of `PreTokenizer` based on the provided configuration.\n *\n * @static\n * @param {Object} config A configuration object for the pre-tokenizer.\n * @returns {PreTokenizer} An instance of a subclass of `PreTokenizer`.\n * @throws {Error} If the provided configuration object does not correspond to any known pre-tokenizer.\n */\n static fromConfig(config) {\n if (config === null) return null;\n\n switch (config.type) {\n case 'BertPreTokenizer':\n return new BertPreTokenizer(config);\n case 'Sequence':\n return new PreTokenizerSequence(config);\n case 'Whitespace':\n return new WhitespacePreTokenizer(config);\n case 'WhitespaceSplit':\n return new WhitespaceSplit(config);\n case 'Metaspace':\n return new MetaspacePreTokenizer(config);\n\n case 'ByteLevel':\n return new ByteLevelPreTokenizer(config);\n case 'Split':\n return new SplitPreTokenizer(config);\n case 'Punctuation':\n return new PunctuationPreTokenizer(config);\n case 'Digits':\n return new DigitsPreTokenizer(config);\n case 'Replace':\n return new ReplacePreTokenizer(config);\n default:\n throw new Error(`Unknown PreTokenizer type: ${config.type}`);\n }\n }\n\n /**\n * Method that should be implemented by subclasses to define the specific pre-tokenization logic.\n *\n * @abstract\n * @param {string} text The text to pre-tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} The pre-tokenized text.\n * @throws {Error} If the method is not implemented in the subclass.\n */\n pre_tokenize_text(text, options) {\n throw Error(\"pre_tokenize_text should be implemented in subclass.\")\n }\n\n /**\n * Tokenizes the given text into pre-tokens.\n * @param {string|string[]} text The text or array of texts to pre-tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of pre-tokens.\n */\n pre_tokenize(text, options) {\n return (Array.isArray(text)\n ? text.map(x => this.pre_tokenize_text(x, options))\n : this.pre_tokenize_text(text, options)\n ).flat();\n }\n\n /**\n * Alias for {@link PreTokenizer#pre_tokenize}.\n * @param {string|string[]} text The text or array of texts to pre-tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of pre-tokens.\n */\n _call(text, options) {\n return this.pre_tokenize(text, options);\n }\n}\n\n/**\n * @extends PreTokenizer\n */\nclass BertPreTokenizer extends PreTokenizer {\n /**\n * A PreTokenizer that splits text into wordpieces using a basic tokenization scheme\n * similar to that used in the original implementation of BERT.\n * \n * @param {Object} config The configuration object.\n */\n constructor(config) {\n super();\n // Construct a pattern which matches the rust implementation:\n // https://github.com/huggingface/tokenizers/blob/b4fcc9ce6e4ad5806e82826f816acfdfdc4fcc67/tokenizers/src/pre_tokenizers/bert.rs#L11\n // Equivalent to removing whitespace and splitting on punctuation (both \\p{P} and other ascii characters)\n this.pattern = new RegExp(`[^\\\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`, 'gu');\n }\n /**\n * Tokenizes a single text using the BERT pre-tokenization scheme.\n * \n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n return text.trim().match(this.pattern) || [];\n }\n}\n\n/**\n * A pre-tokenizer that splits text into Byte-Pair-Encoding (BPE) subwords.\n * @extends PreTokenizer\n */\nclass ByteLevelPreTokenizer extends PreTokenizer {\n /**\n * Creates a new instance of the `ByteLevelPreTokenizer` class.\n * @param {Object} config The configuration object.\n */\n constructor(config) {\n super();\n this.config = config;\n\n /**\n * @type {boolean} Whether to add a leading space to the first word.\n * This allows to treat the leading word just as any other word.\n */\n this.add_prefix_space = this.config.add_prefix_space;\n\n /**\n * @type {boolean} Whether the post processing step should trim offsets\n * to avoid including whitespaces.\n * @todo Use this in the pretokenization step.\n */\n this.trim_offsets = this.config.trim_offsets;\n\n /**\n * @type {boolean} Whether to use the standard GPT2 regex for whitespace splitting.\n * Set it to False if you want to use your own splitting. Defaults to true.\n */\n this.use_regex = this.config.use_regex ?? true;\n this.pattern = /'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+/gu;\n\n this.byte_encoder = BYTES_TO_UNICODE;\n this.text_encoder = new TextEncoder();\n }\n\n /**\n * Tokenizes a single piece of text using byte-level tokenization.\n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n // Add a leading space if the option is enabled\n if (this.add_prefix_space && !text.startsWith(' ')) {\n text = ' ' + text;\n }\n\n // Split on whitespace and punctuation\n const tokens = this.use_regex ? (text.match(this.pattern) || []) : [text];\n\n // Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)\n return tokens.map(\n token => Array.from(this.text_encoder.encode(token), byte => this.byte_encoder[byte]).join('')\n );\n }\n}\n\n/**\n * @typedef {'removed'|'isolated'|'mergedWithPrevious'|'mergedWithNext'|'contiguous'} SplitDelimiterBehavior\n */\n\n/**\n * Splits text using a given pattern.\n * @extends PreTokenizer\n */\nclass SplitPreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration options for the pre-tokenizer.\n * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.\n * @param {string|undefined} config.pattern.String The string to use for splitting. Only defined if the pattern is a string.\n * @param {string|undefined} config.pattern.Regex The regex to use for splitting. Only defined if the pattern is a regex.\n * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.\n * @param {boolean} config.invert Whether to split (invert=false) or match (invert=true) the pattern.\n */\n constructor(config) {\n super();\n this.config = config;\n // TODO support all behaviours (config.behavior)\n\n this.pattern = createPattern(this.config.pattern, this.config.invert);\n }\n\n /**\n * Tokenizes text by splitting it using the given pattern.\n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n if (this.pattern === null) {\n return [];\n }\n\n if (this.config.invert) {\n return text.match(this.pattern) || [];\n } else {\n return regexSplit(text, this.pattern);\n }\n }\n}\n\n/**\n * Splits text based on punctuation.\n * @extends PreTokenizer\n */\nclass PunctuationPreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration options for the pre-tokenizer.\n * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting.\n */\n constructor(config) {\n super();\n this.config = config;\n this.pattern = new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`, 'gu');\n }\n\n /**\n * Tokenizes text by splitting it using the given pattern.\n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n return text.match(this.pattern) || [];\n }\n}\n\n\n/**\n * Splits text based on digits.\n * @extends PreTokenizer\n */\nclass DigitsPreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration options for the pre-tokenizer.\n * @param {boolean} config.individual_digits Whether to split on individual digits.\n */\n constructor(config) {\n super();\n this.config = config;\n\n // Construct a pattern which matches the rust implementation:\n const digit_pattern = `[^\\\\d]+|\\\\d${this.config.individual_digits ? '' : '+'}`;\n this.pattern = new RegExp(digit_pattern, 'gu');\n }\n\n /**\n * Tokenizes text by splitting it using the given pattern.\n * @param {string} text The text to tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens.\n */\n pre_tokenize_text(text, options) {\n return text.match(this.pattern) || [];\n }\n}\n\n/**\n * @typedef {Object} PostProcessedOutput\n * @property {string[]} tokens List of token produced by the post-processor.\n * @property {number[]} [token_type_ids] List of token type ids produced by the post-processor.\n */\n\n\n/**\n * @typedef {Object} EncodingSingle\n * @property {number[]} input_ids List of token ids to be fed to a model.\n * @property {number[]} attention_mask List of token type ids to be fed to a model\n * @property {number[]} [token_type_ids] List of indices specifying which tokens should be attended to by the model\n */\n\n\n/**\n * @extends Callable\n */\nclass PostProcessor extends Callable {\n\n /**\n * @param {Object} config The configuration for the post-processor.\n */\n constructor(config) {\n super();\n this.config = config;\n }\n\n /**\n * Factory method to create a PostProcessor object from a configuration object.\n *\n * @param {Object} config Configuration object representing a PostProcessor.\n * @returns {PostProcessor} A PostProcessor object created from the given configuration.\n * @throws {Error} If an unknown PostProcessor type is encountered.\n */\n static fromConfig(config) {\n if (config === null) return null;\n switch (config.type) {\n case 'TemplateProcessing':\n return new TemplateProcessing(config);\n\n case 'ByteLevel':\n return new ByteLevelPostProcessor(config);\n\n case 'RobertaProcessing':\n return new RobertaProcessing(config);\n case 'BertProcessing':\n return new BertProcessing(config);\n\n case 'Sequence':\n return new PostProcessorSequence(config);\n default:\n throw new Error(`Unknown PostProcessor type: ${config.type}`);\n }\n }\n\n /**\n * Method to be implemented in subclass to apply post-processing on the given tokens.\n *\n * @param {Array} tokens The input tokens to be post-processed.\n * @param {...*} args Additional arguments required by the post-processing logic.\n * @returns {PostProcessedOutput} The post-processed tokens.\n * @throws {Error} If the method is not implemented in subclass.\n */\n post_process(tokens, ...args) {\n throw Error(\"post_process should be implemented in subclass.\")\n }\n\n /**\n * Alias for {@link PostProcessor#post_process}.\n * @param {Array} tokens The text or array of texts to post-process.\n * @param {...*} args Additional arguments required by the post-processing logic.\n * @returns {PostProcessedOutput} The post-processed tokens.\n */\n _call(tokens, ...args) {\n return this.post_process(tokens, ...args);\n }\n}\n\n/**\n * A post-processor that adds special tokens to the beginning and end of the input.\n */\nclass BertProcessing extends PostProcessor {\n /**\n * @param {Object} config The configuration for the post-processor.\n * @param {string[]} config.cls The special tokens to add to the beginning of the input.\n * @param {string[]} config.sep The special tokens to add to the end of the input.\n */\n constructor(config) {\n super(config);\n // TODO use all of config: add_prefix_space, trim_offsets\n\n this.cls = config.cls[0];\n this.sep = config.sep[0];\n }\n\n /**\n * Adds the special tokens to the beginning and end of the input.\n * @param {string[]} tokens The input tokens.\n * @param {string[]} [tokens_pair=null] An optional second set of input tokens.\n * @returns {PostProcessedOutput} The post-processed tokens with the special tokens added to the beginning and end.\n */\n post_process(tokens, tokens_pair = null, {\n add_special_tokens = true,\n } = {}) {\n if (add_special_tokens) {\n tokens = mergeArrays([this.cls], tokens, [this.sep]);\n }\n\n let token_type_ids = new Array(tokens.length).fill(0);\n if (tokens_pair !== null) {\n // NOTE: It is intended to add 2 EOS tokens after the first set of tokens\n // https://github.com/huggingface/tokenizers/issues/983\n const middle = (add_special_tokens && this instanceof RobertaProcessing)\n ? [this.sep]\n : [];\n const after = add_special_tokens ? [this.sep] : [];\n\n tokens = mergeArrays(tokens, middle, tokens_pair, after);\n token_type_ids = mergeArrays(token_type_ids, new Array(tokens_pair.length + middle.length + after.length).fill(1));\n }\n return { tokens, token_type_ids };\n }\n}\nclass RobertaProcessing extends BertProcessing { } // NOTE: extends BertProcessing\n\n/**\n * Post processor that replaces special tokens in a template with actual tokens.\n * @extends PostProcessor\n */\nclass TemplateProcessing extends PostProcessor {\n /**\n * Creates a new instance of `TemplateProcessing`.\n * @param {Object} config The configuration options for the post processor.\n * @param {Array} config.single The template for a single sequence of tokens.\n * @param {Array} config.pair The template for a pair of sequences of tokens.\n */\n constructor(config) {\n super(config);\n\n this.single = config.single;\n this.pair = config.pair;\n }\n\n /**\n * Replaces special tokens in the template with actual tokens.\n * @param {string[]} tokens The list of tokens for the first sequence.\n * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).\n * @returns {PostProcessedOutput} An object containing the list of tokens with the special tokens replaced with actual tokens.\n */\n post_process(tokens, tokens_pair = null, {\n add_special_tokens = true,\n } = {}) {\n const type = tokens_pair === null ? this.single : this.pair\n\n let processedTokens = [];\n let types = [];\n for (const item of type) {\n if ('SpecialToken' in item) {\n if (add_special_tokens) {\n processedTokens.push(item.SpecialToken.id);\n types.push(item.SpecialToken.type_id);\n }\n } else if ('Sequence' in item) {\n if (item.Sequence.id === 'A') {\n processedTokens = mergeArrays(processedTokens, tokens);\n types = mergeArrays(types, new Array(tokens.length).fill(item.Sequence.type_id));\n\n } else if (item.Sequence.id === 'B') {\n processedTokens = mergeArrays(processedTokens, tokens_pair);\n types = mergeArrays(types, new Array(tokens_pair.length).fill(item.Sequence.type_id));\n }\n }\n }\n return { tokens: processedTokens, token_type_ids: types };\n }\n}\n\n/**\n * A PostProcessor that returns the given tokens as is.\n * @extends PostProcessor\n */\nclass ByteLevelPostProcessor extends PostProcessor {\n /**\n * Post process the given tokens.\n * @param {string[]} tokens The list of tokens for the first sequence.\n * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).\n * @returns {PostProcessedOutput} An object containing the post-processed tokens.\n */\n post_process(tokens, tokens_pair = null) {\n if (tokens_pair) {\n tokens = mergeArrays(tokens, tokens_pair);\n }\n return { tokens };\n }\n}\n\n\n/**\n * A post-processor that applies multiple post-processors in sequence.\n */\nclass PostProcessorSequence extends PostProcessor {\n\n /**\n * Creates a new instance of PostProcessorSequence.\n * @param {Object} config The configuration object.\n * @param {Object[]} config.processors The list of post-processors to apply.\n */\n constructor(config) {\n super(config);\n\n this.processors = config.processors.map(x => PostProcessor.fromConfig(x));\n }\n\n /**\n * Post process the given tokens.\n * @param {string[]} tokens The list of tokens for the first sequence.\n * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional).\n * @returns {PostProcessedOutput} An object containing the post-processed tokens.\n */\n post_process(tokens, tokens_pair = null, options = {}) {\n let token_type_ids;\n for (const processor of this.processors) {\n if (processor instanceof ByteLevelPostProcessor) {\n // Special case where we need to pass the tokens_pair to the post-processor\n const output = processor.post_process(tokens);\n tokens = output.tokens;\n if (tokens_pair) {\n const pair_output = processor.post_process(tokens_pair);\n tokens_pair = pair_output.tokens;\n }\n } else {\n const output = processor.post_process(tokens, tokens_pair, options);\n tokens = output.tokens;\n token_type_ids = output.token_type_ids;\n }\n }\n return { tokens, token_type_ids };\n }\n}\n\n/**\n * The base class for token decoders.\n * @extends Callable\n */\nclass Decoder extends Callable {\n\n /**\n * Creates an instance of `Decoder`.\n *\n * @param {Object} config The configuration object.\n */\n constructor(config) {\n super();\n this.config = config;\n\n /** @type {AddedToken[]} */\n this.added_tokens = [];\n this.end_of_word_suffix = null;\n this.trim_offsets = config.trim_offsets;\n }\n\n /**\n * Creates a decoder instance based on the provided configuration.\n *\n * @param {Object} config The configuration object.\n * @returns {Decoder} A decoder instance.\n * @throws {Error} If an unknown decoder type is provided.\n */\n static fromConfig(config) {\n if (config === null) return null;\n switch (config.type) {\n case 'WordPiece':\n return new WordPieceDecoder(config);\n case 'Metaspace':\n return new MetaspaceDecoder(config);\n case 'ByteLevel':\n return new ByteLevelDecoder(config);\n\n case 'Replace':\n return new ReplaceDecoder(config);\n case 'ByteFallback':\n return new ByteFallback(config);\n case 'Fuse':\n return new FuseDecoder(config);\n case 'Strip':\n return new StripDecoder(config);\n\n case 'Sequence':\n return new DecoderSequence(config);\n\n case 'CTC':\n return new CTCDecoder(config);\n case 'BPEDecoder':\n return new BPEDecoder(config);\n default:\n throw new Error(`Unknown Decoder type: ${config.type}`);\n }\n }\n\n /**\n * Calls the `decode` method.\n *\n * @param {string[]} tokens The list of tokens.\n * @returns {string} The decoded string.\n */\n _call(tokens) {\n return this.decode(tokens);\n }\n\n /**\n * Decodes a list of tokens.\n * @param {string[]} tokens The list of tokens.\n * @returns {string} The decoded string.\n */\n decode(tokens) {\n return this.decode_chain(tokens).join('');\n }\n\n /**\n * Apply the decoder to a list of tokens.\n * \n * @param {string[]} tokens The list of tokens.\n * @returns {string[]} The decoded list of tokens.\n * @throws {Error} If the `decode_chain` method is not implemented in the subclass.\n */\n decode_chain(tokens) {\n throw Error(\"`decode_chain` should be implemented in subclass.\")\n }\n\n}\n\nclass ReplaceDecoder extends Decoder {\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n const pattern = createPattern(this.config.pattern);\n return pattern === null\n ? tokens\n : tokens.map(token => token.replaceAll(pattern, this.config.content))\n }\n}\n\n\nclass ByteFallback extends Decoder {\n constructor(config) {\n super(config);\n\n this.text_decoder = new TextDecoder();\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n\n const new_tokens = [];\n let previous_byte_tokens = [];\n\n for (const token of tokens) {\n let bytes = null;\n if (token.length === 6 && token.startsWith('<0x') && token.endsWith('>')) {\n const byte = parseInt(token.slice(3, 5), 16);\n if (!isNaN(byte)) {\n bytes = byte;\n }\n }\n if (bytes !== null) {\n previous_byte_tokens.push(bytes);\n } else {\n if (previous_byte_tokens.length > 0) {\n const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));\n new_tokens.push(string);\n previous_byte_tokens = [];\n }\n new_tokens.push(token);\n }\n }\n if (previous_byte_tokens.length > 0) {\n const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens));\n new_tokens.push(string);\n previous_byte_tokens = [];\n }\n\n return new_tokens;\n }\n}\n\n/**\n * Fuse simply fuses all tokens into one big string.\n * It's usually the last decoding step anyway, but this decoder\n * exists incase some decoders need to happen after that step\n */\nclass FuseDecoder extends Decoder {\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return [tokens.join('')];\n }\n}\n\n\nclass StripDecoder extends Decoder {\n constructor(config) {\n super(config);\n\n this.content = this.config.content;\n this.start = this.config.start;\n this.stop = this.config.stop;\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return tokens.map(token => {\n let start_cut = 0;\n for (let i = 0; i < this.start; ++i) {\n if (token[i] === this.content) {\n start_cut = i + 1;\n continue;\n } else {\n break;\n }\n }\n\n let stop_cut = token.length;\n for (let i = 0; i < this.stop; ++i) {\n const index = token.length - i - 1;\n if (token[index] === this.content) {\n stop_cut = index;\n continue;\n } else {\n break;\n }\n }\n\n return token.slice(start_cut, stop_cut)\n });\n }\n}\n\n/**\n * A decoder that decodes a list of WordPiece tokens into a single string.\n * @extends Decoder\n */\nclass WordPieceDecoder extends Decoder {\n\n /**\n * Creates a new instance of WordPieceDecoder.\n * @param {Object} config The configuration object.\n * @param {string} config.prefix The prefix used for WordPiece encoding.\n * @param {boolean} config.cleanup Whether to cleanup the decoded string.\n */\n constructor(config) {\n super(config);\n this.cleanup = config.cleanup;\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return tokens.map((token, i) => {\n if (i !== 0) {\n if (token.startsWith(this.config.prefix)) {\n // NOTE: .replace() is intended; only replace first occurrence\n token = token.replace(this.config.prefix, '');\n } else {\n token = ' ' + token;\n }\n }\n if (this.cleanup) {\n token = clean_up_tokenization(token)\n }\n\n return token;\n });\n }\n}\n\n/**\n * Byte-level decoder for tokenization output. Inherits from the `Decoder` class.\n * @extends Decoder\n */\nclass ByteLevelDecoder extends Decoder {\n\n /**\n * Create a `ByteLevelDecoder` object.\n * @param {Object} config Configuration object.\n */\n constructor(config) {\n super(config);\n\n this.byte_decoder = UNICODE_TO_BYTES;\n this.text_decoder = new TextDecoder(\"utf-8\", {\n fatal: false,\n ignoreBOM: true,\n });\n\n this.end_of_word_suffix = null;\n }\n\n /**\n * Convert an array of tokens to string by decoding each byte.\n * @param {string[]} tokens Array of tokens to be decoded.\n * @returns {string} The decoded string.\n */\n convert_tokens_to_string(tokens) {\n const text = tokens.join('');\n const byteArray = new Uint8Array([...text].map(c => this.byte_decoder[c]));\n const decoded_text = this.text_decoder.decode(byteArray);\n return decoded_text;\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n // TODO move to base class (like HF)\n // tokens === filtered_tokens\n\n // To avoid mixing byte-level and unicode for byte-level BPT\n // we need to build string separately for added tokens and byte-level tokens\n // cf. https://github.com/huggingface/transformers/issues/1133\n const sub_texts = [];\n let current_sub_text = [];\n for (const token of tokens) {\n // tokens sent here are already filtered, so we don't need to do this\n // if (skip_special_tokens && this.all_special_ids.includes(token)) {\n // continue;\n // }\n\n if (this.added_tokens.find(x => x.content === token) !== undefined) {\n if (current_sub_text.length > 0) {\n sub_texts.push(this.convert_tokens_to_string(current_sub_text));\n current_sub_text = [];\n }\n sub_texts.push(token);\n } else {\n current_sub_text.push(token);\n }\n }\n if (current_sub_text.length > 0) {\n sub_texts.push(this.convert_tokens_to_string(current_sub_text));\n }\n\n // TODO add spaces_between_special_tokens and clean_up_tokenization_spaces options\n\n return sub_texts;\n }\n}\n\n/**\n * The CTC (Connectionist Temporal Classification) decoder.\n * See https://github.com/huggingface/tokenizers/blob/bb38f390a61883fc2f29d659af696f428d1cda6b/tokenizers/src/decoders/ctc.rs\n */\nclass CTCDecoder extends Decoder {\n\n constructor(config) {\n super(config);\n\n this.pad_token = this.config.pad_token;\n this.word_delimiter_token = this.config.word_delimiter_token;\n this.cleanup = this.config.cleanup;\n }\n /**\n * Converts a connectionist-temporal-classification (CTC) output tokens into a single string.\n * @param {string[]} tokens Array of tokens to be decoded.\n * @returns {string} The decoded string.\n */\n convert_tokens_to_string(tokens) {\n if (tokens.length === 0) return '';\n\n // group same tokens into non-repeating tokens in CTC style decoding\n const grouped_tokens = [tokens[0]];\n for (let i = 1; i < tokens.length; ++i) {\n if (tokens[i] !== grouped_tokens.at(-1)) {\n grouped_tokens.push(tokens[i]);\n }\n }\n\n // filter self.pad_token which is used as CTC-blank token\n const filtered_tokens = grouped_tokens.filter(token => token !== this.pad_token);\n\n let text = filtered_tokens.join('');\n if (this.cleanup) {\n // cleanup and replace delimiter token\n text = clean_up_tokenization(text)\n .replaceAll(this.word_delimiter_token, ' ')\n .trim();\n }\n return text;\n }\n\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return [this.convert_tokens_to_string(tokens)];\n }\n}\n\n/**\n * Apply a sequence of decoders.\n * @extends Decoder\n */\nclass DecoderSequence extends Decoder {\n\n /**\n * Creates a new instance of DecoderSequence.\n * @param {Object} config The configuration object.\n * @param {Object[]} config.decoders The list of decoders to apply.\n */\n constructor(config) {\n super(config);\n this.decoders = config.decoders.map(x => Decoder.fromConfig(x));\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n // Use reduce to apply each decoder to the tokens\n return this.decoders.reduce((toks, decoder) => {\n return decoder.decode_chain(toks);\n }, tokens);\n }\n\n}\n\nclass BPEDecoder extends Decoder {\n constructor(config) {\n super(config);\n\n this.suffix = this.config.suffix;\n }\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n return tokens.map((token, i) => {\n return token.replaceAll(this.suffix, (i === tokens.length - 1) ? '' : ' ')\n });\n }\n}\n\n// Custom decoder for VITS\nclass VitsDecoder extends Decoder {\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n let decoded = '';\n for (let i = 1; i < tokens.length; i += 2) {\n decoded += tokens[i];\n }\n return [decoded];\n }\n}\n\n\n/**\n * This PreTokenizer replaces spaces with the given replacement character, adds a prefix space if requested,\n * and returns a list of tokens.\n * @extends PreTokenizer\n */\nclass MetaspacePreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration object for the MetaspacePreTokenizer.\n * @param {boolean} config.add_prefix_space Whether to add a prefix space to the first token.\n * @param {string} config.replacement The character to replace spaces with.\n * @param {string} [config.str_rep=config.replacement] An optional string representation of the replacement character.\n * @param {'first'|'never'|'always'} [config.prepend_scheme='always'] The metaspace prepending scheme.\n */\n constructor(config) {\n super();\n\n this.addPrefixSpace = config.add_prefix_space;\n this.replacement = config.replacement;\n this.strRep = config.str_rep || this.replacement;\n this.prepend_scheme = config.prepend_scheme ?? 'always';\n }\n\n /**\n * This method takes a string, replaces spaces with the replacement character,\n * adds a prefix space if requested, and returns a new list of tokens.\n * @param {string} text The text to pre-tokenize.\n * @param {Object} [options] The options for the pre-tokenization.\n * @param {number} [options.section_index] The index of the section to pre-tokenize.\n * @returns {string[]} A new list of pre-tokenized tokens.\n */\n pre_tokenize_text(text, {\n section_index = undefined,\n } = {}) {\n\n let normalized = text.replaceAll(' ', this.strRep);\n\n if (\n // We add a prefix space if:\n // (1) The addPrefixSpace option is enabled and the normalized\n // token does not already start with the replacement character.\n (this.addPrefixSpace && !normalized.startsWith(this.replacement))\n\n // and (2) either:\n // (a) prepend_scheme is 'always'\n // (b) prepend_scheme is 'first' and this is the first section\n && (\n this.prepend_scheme === 'always' ||\n (this.prepend_scheme === 'first' && section_index === 0)\n )\n ) {\n normalized = this.strRep + normalized;\n }\n return [normalized];\n }\n}\n\n/**\n * MetaspaceDecoder class extends the Decoder class and decodes Metaspace tokenization.\n * @extends Decoder\n */\nclass MetaspaceDecoder extends Decoder {\n /**\n * Constructs a new MetaspaceDecoder object.\n * @param {Object} config The configuration object for the MetaspaceDecoder.\n * @param {boolean} config.add_prefix_space Whether to add a prefix space to the decoded string.\n * @param {string} config.replacement The string to replace spaces with.\n */\n constructor(config) {\n super(config);\n\n this.addPrefixSpace = config.add_prefix_space;\n this.replacement = config.replacement;\n }\n\n /** @type {Decoder['decode_chain']} */\n decode_chain(tokens) {\n const result = [];\n for (let i = 0; i < tokens.length; ++i) {\n let normalized = tokens[i].replaceAll(this.replacement, ' ');\n if (this.addPrefixSpace && i == 0 && normalized.startsWith(' ')) {\n normalized = normalized.substring(1);\n }\n result.push(normalized);\n }\n return result;\n }\n}\n\n/**\n * A normalizer that applies a precompiled charsmap.\n * This is useful for applying complex normalizations in C++ and exposing them to JavaScript.\n * @extends Normalizer\n * @param {Object} config The configuration object for the Precompiled normalizer.\n * @param {Object} config.precompiled_charsmap The precompiled charsmap object.\n */\nclass Precompiled extends Normalizer {\n /**\n * Create a new instance of Precompiled normalizer.\n * @param {Object} config The configuration object.\n * @param {any} config.precompiled_charsmap Precompiled chars mapping.\n */\n constructor(config) {\n super(config);\n this.charsmap = config.precompiled_charsmap;\n }\n\n /**\n * Normalizes the given text by applying the precompiled charsmap.\n * @param {string} text The text to normalize.\n * @returns {string} The normalized text.\n */\n normalize(text) {\n // As stated in the sentencepiece normalization docs (https://github.com/google/sentencepiece/blob/master/doc/normalization.md#use-pre-defined-normalization-rule),\n // there are 5 pre-defined normalization rules:\n // 1. nmt_nfkc: NFKC normalization with some additional normalization around spaces. (default)\n // 2. nfkc: original NFKC normalization.\n // 3. nmt_nfkc_cf: nmt_nfkc + Unicode case folding (mostly lower casing)\n // 4. nfkc_cf: nfkc + Unicode case folding.\n // 5. identity: no normalization\n // \n // For now, we only implement the default (nmt_nfkc).\n // See https://raw.githubusercontent.com/google/sentencepiece/master/data/nmt_nfkc.tsv for the full list of rules.\n // TODO: detect when a different `this.charsmap` is used.\n\n text = text.replace(/[\\u0001-\\u0008\\u000B\\u000E-\\u001F\\u007F\\u008F\\u009F]/gm, ''); // Remove control characters\n text = text.replace(/[\\u0009\\u000A\\u000C\\u000D\\u00A0\\u1680\\u2000-\\u200F\\u2028\\u2029\\u202F\\u205F\\u2581\\u3000\\uFEFF\\uFFFD]/gm, '\\u0020'); // Replace certain characters with a space\n\n if (text.includes('\\uFF5E')) {\n // To match the sentencepiece implementation 100%, we must handle a very strange edge-case.\n // For some reason, the \"Fullwidth Tilde\" character (\\uFF5E) should not be converted to the standard Tilde character (\\u007E).\n // However, NFKC normalization does do this conversion. As a result, we split the string on the Fullwidth Tilde character,\n // perform NFKC normalization on each substring, and then join them back together with the Fullwidth Tilde character.\n const parts = text.split('\\uFF5E');\n text = parts.map(part => part.normalize('NFKC')).join('\\uFF5E');\n } else {\n text = text.normalize('NFKC');\n }\n\n return text;\n }\n}\n\n/**\n * A pre-tokenizer that applies a sequence of pre-tokenizers to the input text.\n * @extends PreTokenizer\n */\nclass PreTokenizerSequence extends PreTokenizer {\n /**\n * Creates an instance of PreTokenizerSequence.\n * @param {Object} config The configuration object for the pre-tokenizer sequence.\n * @param {Object[]} config.pretokenizers An array of pre-tokenizer configurations.\n */\n constructor(config) {\n super();\n this.tokenizers = config.pretokenizers.map(x => PreTokenizer.fromConfig(x));\n }\n\n /**\n * Applies each pre-tokenizer in the sequence to the input text in turn.\n * @param {string} text The text to pre-tokenize.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} The pre-tokenized text.\n */\n pre_tokenize_text(text, options) {\n // Use reduce to apply each tokenizer to the text\n return this.tokenizers.reduce((preTokenizedText, tokenizer) => {\n return tokenizer.pre_tokenize(preTokenizedText, options);\n }, [text]);\n }\n}\n\n/**\n * Splits on word boundaries (using the following regular expression: `\\w+|[^\\w\\s]+`).\n */\nclass WhitespacePreTokenizer extends PreTokenizer {\n /**\n * Creates an instance of WhitespacePreTokenizer.\n * @param {Object} config The configuration object for the pre-tokenizer.\n */\n constructor(config) {\n super();\n }\n /**\n * Pre-tokenizes the input text by splitting it on word boundaries.\n * @param {string} text The text to be pre-tokenized.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.\n */\n pre_tokenize_text(text, options) {\n return text.match(/\\w+|[^\\w\\s]+/g) || [];\n }\n}\n\n/**\n * Splits a string of text by whitespace characters into individual tokens.\n * @extends PreTokenizer\n */\nclass WhitespaceSplit extends PreTokenizer {\n /**\n * Creates an instance of WhitespaceSplit.\n * @param {Object} config The configuration object for the pre-tokenizer.\n */\n constructor(config) {\n super();\n }\n /**\n * Pre-tokenizes the input text by splitting it on whitespace characters.\n * @param {string} text The text to be pre-tokenized.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens produced by splitting the input text on whitespace.\n */\n pre_tokenize_text(text, options) {\n return whitespace_split(text);\n }\n}\n\n// NOTE: `ReplacePreTokenizer` is custom (to support `BlenderbotSmallTokenizer`)\nclass ReplacePreTokenizer extends PreTokenizer {\n /**\n * @param {Object} config The configuration options for the pre-tokenizer.\n * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object.\n * @param {string} config.content What to replace the pattern with.\n */\n constructor(config) {\n super();\n this.config = config;\n this.pattern = createPattern(this.config.pattern);\n this.content = this.config.content;\n }\n\n /**\n * Pre-tokenizes the input text by replacing certain characters.\n * @param {string} text The text to be pre-tokenized.\n * @param {Object} [options] Additional options for the pre-tokenization logic.\n * @returns {string[]} An array of tokens produced by replacing certain characters.\n */\n pre_tokenize_text(text, options) {\n if (this.pattern === null) {\n return [text];\n }\n return [text.replaceAll(this.pattern, this.config.content)];\n }\n}\n\nconst SPECIAL_TOKEN_ATTRIBUTES = [\n 'bos_token',\n 'eos_token',\n 'unk_token',\n 'sep_token',\n 'pad_token',\n 'cls_token',\n 'mask_token',\n // additional_special_tokens (TODO)\n]\n\n/**\n * \n * Helper function for padding values of an object, which are each arrays.\n * NOTE: No additional checks are made here for validity of arguments.\n * @param {Record} item The input object.\n * @param {number} length The length to pad to.\n * @param {(key: string) => any} value_fn Determine the value to fill the array, based on its key.\n * @param {string} side Which side to pad the array.\n * @private\n */\nfunction padHelper(item, length, value_fn, side) {\n for (const key of Object.keys(item)) {\n const diff = length - item[key].length;\n const value = value_fn(key);\n\n const padData = new Array(diff).fill(value);\n item[key] = side === 'right'\n ? mergeArrays(item[key], padData)\n : mergeArrays(padData, item[key]);\n }\n}\n\n/**\n * Helper function for truncating values of an object, which are each arrays.\n * NOTE: No additional checks are made here for validity of arguments.\n * @param {Record} item The input object.\n * @param {number} length The length to truncate to.\n * @private\n */\nfunction truncateHelper(item, length) {\n // Setting .length to a lower value truncates the array in-place:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length\n for (const key of Object.keys(item)) {\n item[key].length = length;\n }\n}\n\n\n/**\n * @typedef {Object} Message\n * @property {string} role The role of the message (e.g., \"user\" or \"assistant\" or \"system\").\n * @property {string} content The content of the message.\n */\n\nexport class PreTrainedTokenizer extends Callable {\n return_token_type_ids = false;\n\n padding_side = 'right';\n /**\n * Create a new PreTrainedTokenizer instance.\n * @param {Object} tokenizerJSON The JSON of the tokenizer.\n * @param {Object} tokenizerConfig The config of the tokenizer.\n */\n constructor(tokenizerJSON, tokenizerConfig) {\n super();\n\n this._tokenizer_config = tokenizerConfig;\n\n // Construct parts of the tokenizer from the JSON\n this.normalizer = Normalizer.fromConfig(tokenizerJSON.normalizer);\n this.pre_tokenizer = PreTokenizer.fromConfig(tokenizerJSON.pre_tokenizer);\n this.model = TokenizerModel.fromConfig(tokenizerJSON.model, tokenizerConfig);\n this.post_processor = PostProcessor.fromConfig(tokenizerJSON.post_processor);\n this.decoder = Decoder.fromConfig(tokenizerJSON.decoder);\n\n // Add added_tokens to model\n this.special_tokens = [];\n this.all_special_ids = [];\n\n /** @type {AddedToken[]} */\n this.added_tokens = [];\n for (const addedToken of tokenizerJSON.added_tokens) {\n const token = new AddedToken(addedToken);\n this.added_tokens.push(token);\n\n this.model.tokens_to_ids.set(token.content, token.id);\n this.model.vocab[token.id] = token.content;\n\n if (token.special) {\n this.special_tokens.push(token.content);\n this.all_special_ids.push(token.id);\n }\n }\n\n // Update additional_special_tokens\n this.additional_special_tokens = tokenizerConfig.additional_special_tokens ?? [];\n this.special_tokens.push(...this.additional_special_tokens);\n this.special_tokens = [...new Set(this.special_tokens)]; // Remove duplicates\n\n if (this.decoder) {\n // Slight hack, but it prevents code duplication:\n this.decoder.added_tokens = this.added_tokens;\n\n // Another slight hack to add `end_of_word_suffix` (if present) to the decoder\n // This is needed for cases where BPE model and ByteLevel decoder are used\n // For more information, see https://github.com/huggingface/transformers.js/issues/74\n // TODO: save this to the decoder when exporting?\n this.decoder.end_of_word_suffix = this.model.end_of_word_suffix;\n }\n\n this.added_tokens_regex = this.added_tokens.length > 0 ? new RegExp(\n this.added_tokens.slice()\n // Sort by length (desc) to avoid early partial matches\n .sort((a, b) => b.content.length - a.content.length)\n .map(x => `${x.lstrip ? '\\\\s*' : ''}(${escapeRegExp(x.content)})${x.rstrip ? '\\\\s*' : ''}`)\n .join('|')\n ) : null;\n\n // Set mask token if present (otherwise will be undefined, which is fine)\n this.mask_token = this.getToken('mask_token');\n this.mask_token_id = this.model.tokens_to_ids.get(this.mask_token);\n\n this.pad_token = this.getToken('pad_token', 'eos_token');\n this.pad_token_id = this.model.tokens_to_ids.get(this.pad_token);\n\n this.sep_token = this.getToken('sep_token');\n this.sep_token_id = this.model.tokens_to_ids.get(this.sep_token);\n\n this.unk_token = this.getToken('unk_token');\n this.unk_token_id = this.model.tokens_to_ids.get(this.unk_token);\n\n this.model_max_length = tokenizerConfig.model_max_length;\n\n /** @type {boolean} Whether or not to strip the text when tokenizing (removing excess spaces before and after the string). */\n this.remove_space = tokenizerConfig.remove_space;\n\n this.clean_up_tokenization_spaces = tokenizerConfig.clean_up_tokenization_spaces ?? true;\n this.do_lowercase_and_remove_accent = tokenizerConfig.do_lowercase_and_remove_accent ?? false;\n\n if (tokenizerConfig.padding_side) {\n this.padding_side = tokenizerConfig.padding_side;\n }\n\n this.legacy = false;\n\n this.chat_template = tokenizerConfig.chat_template ?? null;\n if (Array.isArray(this.chat_template)) {\n // Chat templates are stored as lists of dicts with fixed key names,\n // we reconstruct that into a single dict while loading them.\n const chat_template = Object.create(null);\n for (const { name, template } of this.chat_template) {\n if (typeof name !== 'string' || typeof template !== 'string') {\n throw new Error('Chat template must be a list of objects with \"name\" and \"template\" properties');\n }\n chat_template[name] = template;\n }\n this.chat_template = chat_template;\n }\n this._compiled_template_cache = new Map();\n }\n\n /**\n * Returns the value of the first matching key in the tokenizer config object.\n * @param {...string} keys One or more keys to search for in the tokenizer config object.\n * @returns {string|null} The value associated with the first matching key, or null if no match is found.\n * @throws {Error} If an object is found for a matching key and its __type property is not \"AddedToken\".\n * @private\n */\n getToken(...keys) {\n for (const key of keys) {\n const item = this._tokenizer_config[key];\n\n if (!item) continue;\n\n if (typeof item === 'object') {\n if (item.__type === 'AddedToken') {\n return item.content;\n } else {\n throw Error(`Unknown token: ${item}`);\n }\n } else {\n return item;\n }\n }\n return null;\n }\n\n /**\n * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`. \n * \n * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer.\n * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.\n * \n * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`.\n * @returns {Promise} A new instance of the `PreTrainedTokenizer` class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n legacy = null,\n } = {}) {\n\n const info = await loadTokenizer(pretrained_model_name_or_path, {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n legacy,\n })\n\n // @ts-ignore\n return new this(...info);\n }\n\n /**\n * @typedef {number[]|number[][]|Tensor} BatchEncodingItem\n * \n * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function.\n * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model.\n * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model.\n * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model.\n */\n\n /**\n * Encode/tokenize the given text(s).\n * @param {string|string[]} text The text to tokenize.\n * @param {Object} options An optional object containing the following properties:\n * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text.\n * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences.\n * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.\n * @param {boolean} [options.truncation=null] Whether to truncate the input sequences.\n * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length.\n * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays.\n * @param {boolean} [options.return_token_type_ids=null] Whether to return the token type ids.\n * @returns {BatchEncoding} Object to be passed to the model.\n */\n _call(\n // Required positional arguments\n text,\n\n // Optional keyword arguments\n {\n text_pair = null,\n add_special_tokens = true,\n padding = false,\n truncation = null,\n max_length = null,\n return_tensor = true, // Different to HF\n return_token_type_ids = null,\n } = {},\n ) {\n\n const isBatched = Array.isArray(text);\n\n /** @type {EncodingSingle[]} */\n let encodedTokens;\n\n if (isBatched) {\n if (text.length === 0) {\n throw Error('text array must be non-empty')\n }\n\n if (text_pair !== null) {\n if (!Array.isArray(text_pair)) {\n throw Error('text_pair must also be an array')\n\n } else if (text.length !== text_pair.length) {\n throw Error('text and text_pair must have the same length')\n }\n\n encodedTokens = text.map(\n (t, i) => this._encode_plus(t, { text_pair: text_pair[i], add_special_tokens, return_token_type_ids })\n )\n\n } else {\n encodedTokens = text.map(x => this._encode_plus(x, { add_special_tokens, return_token_type_ids }));\n }\n\n } else {\n if (text === null || text === undefined) {\n throw Error('text may not be null or undefined')\n }\n\n if (Array.isArray(text_pair)) {\n throw Error('When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).')\n }\n\n // For single input, we just wrap in an array, and then unwrap later.\n encodedTokens = [this._encode_plus(text, { text_pair, add_special_tokens, return_token_type_ids })];\n }\n // At this point, tokens is batched: [batch_size, tokens]\n // However, array may be jagged. So, we pad to max_length\n\n if (max_length === null) {\n if (padding === 'max_length') {\n max_length = this.model_max_length;\n } else {\n // Calculate max length from sequences\n max_length = max(encodedTokens.map(x => x.input_ids.length))[0];\n }\n } else {\n if (!truncation) {\n console.warn(`Truncation was not explicitly activated but \\`max_length\\` is provided a specific value, please use \\`truncation=true\\` to explicitly truncate examples to max length.`)\n }\n }\n\n // Ensure it is less than model max length\n max_length = Math.min(max_length, this.model_max_length ?? Infinity);\n\n if (padding || truncation) {\n\n // Perform padding and/or truncation\n for (let i = 0; i < encodedTokens.length; ++i) {\n if (encodedTokens[i].input_ids.length === max_length) {\n continue;\n\n } else if (encodedTokens[i].input_ids.length > max_length) {\n // possibly truncate\n if (truncation) {\n truncateHelper(encodedTokens[i], max_length);\n }\n\n } else { // t.length < max_length\n // possibly pad\n if (padding) {\n padHelper(\n encodedTokens[i],\n max_length,\n key => key === 'input_ids' ? this.pad_token_id : 0,\n this.padding_side\n );\n }\n }\n }\n }\n\n const result = {};\n\n if (return_tensor) {\n if (!(padding && truncation)) {\n // Not, guaranteed that all items have same length, so\n // we perform additional check\n\n if (\n encodedTokens.some(x => {\n for (const key of Object.keys(x)) {\n if (x[key].length !== encodedTokens[0][key]?.length) {\n return true;\n }\n }\n return false;\n })\n ) {\n throw Error(\n \"Unable to create tensor, you should probably activate truncation and/or padding \" +\n \"with 'padding=true' and 'truncation=true' to have batched tensors with the same length.\"\n )\n }\n }\n\n // Now we actually convert to tensor\n // NOTE: In the same way as the python library, we return a batched tensor, regardless of\n // whether we have a single input or multiple inputs.\n const dims = [encodedTokens.length, encodedTokens[0].input_ids.length];\n\n for (const key of Object.keys(encodedTokens[0])) {\n result[key] = new Tensor('int64',\n BigInt64Array.from(encodedTokens.flatMap(x => x[key]).map(BigInt)),\n dims\n );\n }\n\n } else {\n for (const key of Object.keys(encodedTokens[0])) {\n result[key] = encodedTokens.map(x => x[key]);\n }\n\n // If not returning a tensor, we match the input type\n if (!isBatched) {\n // Input was not batched, so we unwrap\n for (const key of Object.keys(result)) {\n result[key] = result[key][0];\n }\n }\n }\n\n return /** @type {BatchEncoding} */(result);\n }\n\n /**\n * Encodes a single text using the preprocessor pipeline of the tokenizer.\n *\n * @param {string|null} text The text to encode.\n * @returns {string[]|null} The encoded tokens.\n */\n _encode_text(text) {\n if (text === null) return null;\n\n // Actual function which does encoding, for a single text\n // First, we take care of special tokens. Needed to avoid issues arising from\n // normalization and/or pretokenization (which may not preserve special tokens)\n const sections = this.added_tokens_regex ? text.split(this.added_tokens_regex).filter(x => x) : [text];\n\n const tokens = sections.map((x, section_index) => {\n const addedToken = this.added_tokens.find(t => t.content === x);\n if (addedToken !== undefined) {\n // Ignore added tokens\n return x\n } else {\n if (this.remove_space === true) {\n x = x.trim().split(/\\s+/).join(' ');\n }\n if (this.do_lowercase_and_remove_accent) {\n x = lowercase_and_remove_accent(x);\n }\n\n if (this.normalizer !== null) {\n x = this.normalizer(x);\n }\n\n // If, after normalization, this section is empty (e.g., trimming whitespace),\n // we return an empty array\n if (x.length === 0) {\n return [];\n }\n\n const sectionTokens = (this.pre_tokenizer !== null) ? this.pre_tokenizer(x, {\n section_index,\n }) : [x];\n\n const tokens = this.model(sectionTokens);\n\n return tokens;\n }\n }).flat();\n\n return tokens;\n }\n\n /**\n * Encodes a single text or a pair of texts using the model's tokenizer.\n *\n * @param {string} text The text to encode.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.text_pair=null] The optional second text to encode.\n * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.\n * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids.\n * @returns {EncodingSingle} An object containing the encoded text.\n * @private\n */\n _encode_plus(text, {\n text_pair = null,\n add_special_tokens = true,\n return_token_type_ids = null,\n } = {}) {\n\n const { tokens, token_type_ids } = this._tokenize_helper(text, { pair: text_pair, add_special_tokens });\n\n const input_ids = this.model.convert_tokens_to_ids(tokens);\n\n const result = {\n input_ids,\n attention_mask: new Array(input_ids.length).fill(1),\n }\n if ((return_token_type_ids ?? this.return_token_type_ids) && token_type_ids) {\n result.token_type_ids = token_type_ids;\n }\n return result;\n }\n\n /**\n * Internal helper function to tokenize a text, and optionally a pair of texts.\n * @param {string} text The text to tokenize.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.pair=null] The optional second text to tokenize.\n * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model.\n * @returns {{tokens: string[], token_type_ids?: number[]}} An object containing the tokens and optionally the token type IDs.\n */\n _tokenize_helper(text, {\n pair = null,\n add_special_tokens = false,\n } = {}) {\n const tokens = this._encode_text(text);\n const tokens2 = this._encode_text(pair);\n\n return this.post_processor\n ? this.post_processor(tokens, tokens2, { add_special_tokens })\n : { tokens: mergeArrays(tokens ?? [], tokens2 ?? []) };\n }\n\n /**\n * Converts a string into a sequence of tokens.\n * @param {string} text The sequence to be encoded.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.pair] A second sequence to be encoded with the first.\n * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model.\n * @returns {string[]} The list of tokens.\n */\n tokenize(text, {\n pair = null,\n add_special_tokens = false,\n } = {}) {\n return this._tokenize_helper(text, { pair, add_special_tokens }).tokens;\n }\n\n /**\n * Encodes a single text or a pair of texts using the model's tokenizer.\n *\n * @param {string} text The text to encode.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.text_pair=null] The optional second text to encode.\n * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model.\n * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids.\n * @returns {number[]} An array of token IDs representing the encoded text(s).\n */\n encode(text, {\n text_pair = null,\n add_special_tokens = true,\n return_token_type_ids = null,\n } = {}) {\n return this._encode_plus(text, {\n text_pair,\n add_special_tokens,\n return_token_type_ids,\n }).input_ids;\n }\n\n /**\n * Decode a batch of tokenized sequences.\n * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences.\n * @param {Object} decode_args (Optional) Object with decoding arguments.\n * @returns {string[]} List of decoded sequences.\n */\n batch_decode(batch, decode_args = {}) {\n if (batch instanceof Tensor) {\n batch = batch.tolist();\n }\n return batch.map(x => this.decode(x, decode_args));\n }\n\n /**\n * Decodes a sequence of token IDs back to a string.\n *\n * @param {number[]|bigint[]|Tensor} token_ids List/Tensor of token IDs to decode.\n * @param {Object} [decode_args={}]\n * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string.\n * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuations and abbreviated forms are removed.\n *\n * @returns {string} The decoded string.\n * @throws {Error} If `token_ids` is not a non-empty array of integers.\n */\n decode(\n token_ids,\n decode_args = {},\n ) {\n if (token_ids instanceof Tensor) {\n token_ids = prepareTensorForDecode(token_ids);\n }\n\n if (!Array.isArray(token_ids) || token_ids.length === 0 || !isIntegralNumber(token_ids[0])) {\n throw Error(\"token_ids must be a non-empty array of integers.\");\n }\n\n return this.decode_single(token_ids, decode_args)\n }\n\n /**\n * Decode a single list of token ids to a string.\n * @param {number[]|bigint[]} token_ids List of token ids to decode\n * @param {Object} decode_args Optional arguments for decoding\n * @param {boolean} [decode_args.skip_special_tokens=false] Whether to skip special tokens during decoding\n * @param {boolean} [decode_args.clean_up_tokenization_spaces=null] Whether to clean up tokenization spaces during decoding.\n * If null, the value is set to `this.decoder.cleanup` if it exists, falling back to `this.clean_up_tokenization_spaces` if it exists, falling back to `true`.\n * @returns {string} The decoded string\n */\n decode_single(\n token_ids,\n {\n skip_special_tokens = false,\n clean_up_tokenization_spaces = null,\n }\n ) {\n let tokens = this.model.convert_ids_to_tokens(token_ids);\n if (skip_special_tokens) {\n tokens = tokens.filter(x => !this.special_tokens.includes(x));\n }\n\n // If `this.decoder` is null, we just join tokens with a space:\n // https://github.com/huggingface/tokenizers/blob/8edec536a737cb04494b454805be16c020abb14f/tokenizers/src/tokenizer/mod.rs#L835\n /** @type {string} */\n let decoded = this.decoder ? this.decoder(tokens) : tokens.join(' ');\n\n // Slight hack, but prevents having to pass `skip_special_tokens` to\n // each call to `decode`, which would lead to code duplication.\n if (this.decoder && this.decoder.end_of_word_suffix) {\n decoded = decoded.replaceAll(this.decoder.end_of_word_suffix, ' ');\n if (skip_special_tokens) {\n decoded = decoded.trim();\n }\n }\n\n if (clean_up_tokenization_spaces ?? this.clean_up_tokenization_spaces) {\n decoded = clean_up_tokenization(decoded);\n }\n\n return decoded;\n }\n\n /**\n * Retrieve the chat template string used for tokenizing chat messages. This template is used\n * internally by the `apply_chat_template` method and can also be used externally to retrieve the model's chat\n * template for better generation tracking.\n * \n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.chat_template=null]\n * A Jinja template or the name of a template to use for this conversion.\n * It is usually not necessary to pass anything to this argument,\n * as the model's template will be used by default.\n * @param {Object[]} [options.tools=null]\n * A list of tools (callable functions) that will be accessible to the model. If the template does not\n * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema,\n * giving the name, description and argument types for the tool. See our\n * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use)\n * for more information.\n * @returns {string} The chat template string.\n */\n get_chat_template({\n chat_template = null,\n tools = null,\n } = {}) {\n\n // First, handle the cases when the model has a dict of multiple templates\n if (this.chat_template && typeof this.chat_template === 'object') {\n const template_dict = this.chat_template;\n\n if (chat_template !== null && Object.hasOwn(template_dict, chat_template)) {\n // The user can pass the name of a template to the chat template argument instead of an entire template\n chat_template = template_dict[chat_template];\n } else if (chat_template === null) {\n if (tools !== null && 'tool_use' in template_dict) {\n chat_template = template_dict['tool_use'];\n } else if ('default' in template_dict) {\n chat_template = template_dict['default'];\n } else {\n throw Error(\n `This model has multiple chat templates with no default specified! Please either pass a chat ` +\n `template or the name of the template you wish to use to the 'chat_template' argument. Available ` +\n `template names are ${Object.keys(template_dict).sort()}.`\n )\n }\n }\n } else if (chat_template === null) {\n // These are the cases when the model has a single template\n // priority: `chat_template` argument > `tokenizer.chat_template`\n if (this.chat_template) {\n chat_template = this.chat_template;\n } else {\n throw Error(\n \"Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template \" +\n \"argument was passed! For information about writing templates and setting the \" +\n \"tokenizer.chat_template attribute, please see the documentation at \" +\n \"https://huggingface.co/docs/transformers/main/en/chat_templating\"\n )\n }\n }\n return chat_template;\n }\n\n /**\n * Converts a list of message objects with `\"role\"` and `\"content\"` keys to a list of token\n * ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to\n * determine the format and control tokens to use when converting.\n * \n * See [here](https://huggingface.co/docs/transformers/chat_templating) for more information.\n * \n * **Example:** Applying a chat template to a conversation.\n * \n * ```javascript\n * import { AutoTokenizer } from \"@huggingface/transformers\";\n * \n * const tokenizer = await AutoTokenizer.from_pretrained(\"Xenova/mistral-tokenizer-v1\");\n * \n * const chat = [\n * { \"role\": \"user\", \"content\": \"Hello, how are you?\" },\n * { \"role\": \"assistant\", \"content\": \"I'm doing great. How can I help you today?\" },\n * { \"role\": \"user\", \"content\": \"I'd like to show off how chat templating works!\" },\n * ]\n * \n * const text = tokenizer.apply_chat_template(chat, { tokenize: false });\n * // \"[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today? [INST] I'd like to show off how chat templating works! [/INST]\"\n * \n * const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false });\n * // [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793]\n * ```\n * \n * @param {Message[]} conversation A list of message objects with `\"role\"` and `\"content\"` keys,\n * representing the chat history so far.\n * @param {Object} options An optional object containing the following properties:\n * @param {string} [options.chat_template=null] A Jinja template to use for this conversion. If\n * this is not passed, the model's chat template will be used instead.\n * @param {Object[]} [options.tools=null]\n * A list of tools (callable functions) that will be accessible to the model. If the template does not\n * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema,\n * giving the name, description and argument types for the tool. See our\n * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use)\n * for more information.\n * @param {Record[]} [options.documents=null]\n * A list of dicts representing documents that will be accessible to the model if it is performing RAG\n * (retrieval-augmented generation). If the template does not support RAG, this argument will have no\n * effect. We recommend that each document should be a dict containing \"title\" and \"text\" keys. Please\n * see the RAG section of the [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#arguments-for-RAG)\n * for examples of passing documents with chat templates.\n * @param {boolean} [options.add_generation_prompt=false] Whether to end the prompt with the token(s) that indicate\n * the start of an assistant message. This is useful when you want to generate a response from the model.\n * Note that this argument will be passed to the chat template, and so it must be supported in the\n * template for this argument to have any effect.\n * @param {boolean} [options.tokenize=true] Whether to tokenize the output. If false, the output will be a string.\n * @param {boolean} [options.padding=false] Whether to pad sequences to the maximum length. Has no effect if tokenize is false.\n * @param {boolean} [options.truncation=false] Whether to truncate sequences to the maximum length. Has no effect if tokenize is false.\n * @param {number} [options.max_length=null] Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is false.\n * If not specified, the tokenizer's `max_length` attribute will be used as a default.\n * @param {boolean} [options.return_tensor=true] Whether to return the output as a Tensor or an Array. Has no effect if tokenize is false.\n * @param {boolean} [options.return_dict=true] Whether to return a dictionary with named outputs. Has no effect if tokenize is false.\n * @param {Object} [options.tokenizer_kwargs={}] Additional options to pass to the tokenizer.\n * @returns {string | Tensor | number[]| number[][]|BatchEncoding} The tokenized output.\n */\n apply_chat_template(conversation, {\n tools = null,\n documents = null,\n chat_template = null,\n add_generation_prompt = false,\n tokenize = true,\n padding = false,\n truncation = false,\n max_length = null,\n return_tensor = true,\n return_dict = false,\n tokenizer_kwargs = {},\n ...kwargs\n } = {}) {\n\n chat_template = this.get_chat_template({ chat_template, tools });\n\n if (typeof chat_template !== 'string') {\n throw Error(`chat_template must be a string, but got ${typeof chat_template}`);\n }\n\n // Compilation function uses a cache to avoid recompiling the same template\n let compiledTemplate = this._compiled_template_cache.get(chat_template);\n if (compiledTemplate === undefined) {\n compiledTemplate = new Template(chat_template);\n this._compiled_template_cache.set(chat_template, compiledTemplate);\n }\n\n const special_tokens_map = Object.create(null);\n for (const key of SPECIAL_TOKEN_ATTRIBUTES) {\n const value = this.getToken(key);\n if (value) {\n special_tokens_map[key] = value;\n }\n }\n\n const rendered = compiledTemplate.render({\n messages: conversation,\n add_generation_prompt,\n tools,\n documents,\n ...special_tokens_map,\n ...kwargs,\n });\n\n if (tokenize) {\n const out = this._call(rendered, {\n add_special_tokens: false,\n padding,\n truncation,\n max_length,\n return_tensor,\n ...tokenizer_kwargs,\n });\n return return_dict ? out : out.input_ids;\n }\n\n return rendered;\n }\n}\n\n/**\n * BertTokenizer is a class used to tokenize text for BERT models.\n * @extends PreTrainedTokenizer\n */\nexport class BertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\n/**\n * Albert tokenizer\n * @extends PreTrainedTokenizer\n */\nexport class AlbertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class MobileBertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class SqueezeBertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class DebertaTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class DebertaV2Tokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class HerbertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class ConvBertTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class RoFormerTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\nexport class DistilBertTokenizer extends PreTrainedTokenizer { }\nexport class CamembertTokenizer extends PreTrainedTokenizer { }\nexport class XLMTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\\'s \"fast\" tokenizers library. Therefore, you may experience slightly inaccurate results.')\n }\n}\nexport class ElectraTokenizer extends PreTrainedTokenizer {\n return_token_type_ids = true;\n}\n\nexport class T5Tokenizer extends PreTrainedTokenizer { }\nexport class GPT2Tokenizer extends PreTrainedTokenizer { }\nexport class BartTokenizer extends PreTrainedTokenizer { }\nexport class MBartTokenizer extends PreTrainedTokenizer {\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.languageRegex = /^[a-z]{2}_[A-Z]{2}$/;\n this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x));\n this.lang_to_token = x => x; // Identity function\n }\n\n /**\n * Helper function to build translation inputs for an `MBartTokenizer`.\n * @param {string|string[]} raw_inputs The text to tokenize.\n * @param {Object} tokenizer_options Options to be sent to the tokenizer\n * @param {Object} generate_kwargs Generation options.\n * @returns {Object} Object to be passed to the model.\n */\n _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {\n return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);\n }\n}\nexport class MBart50Tokenizer extends MBartTokenizer { } // NOTE: extends MBartTokenizer\n\nexport class RobertaTokenizer extends PreTrainedTokenizer { }\n\nexport class BloomTokenizer extends PreTrainedTokenizer { }\n\nconst SPIECE_UNDERLINE = \"▁\";\n\nexport class LlamaTokenizer extends PreTrainedTokenizer {\n\n padding_side = 'left';\n\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.legacy = tokenizerConfig.legacy ?? true;\n if (!this.legacy) {\n // See https://github.com/huggingface/transformers/pull/24565 for more information\n this.normalizer = null;\n this.pre_tokenizer = new MetaspacePreTokenizer({\n replacement: SPIECE_UNDERLINE,\n add_prefix_space: true,\n prepend_scheme: \"first\",\n });\n }\n }\n\n /**\n * Helper function to handle legacy encoding of SPM tokenizers.\n * Adapted from https://github.com/huggingface/transformers/blob/e6dcf8abd6f65bb4b6dfc1831b20d9ba49ce00e2/src/transformers/models/t5/tokenization_t5.py#L374-L387\n * @param {string} text The text to encode.\n * @returns {string[]} The encoded tokens.\n */\n _encode_text(text) {\n if (text === null) return null;\n\n if (this.legacy || text.length === 0) {\n return super._encode_text(text);\n }\n\n let tokens = super._encode_text(SPIECE_UNDERLINE + text.replaceAll(SPIECE_UNDERLINE, \" \"));\n if (tokens.length > 1 && tokens[0] === SPIECE_UNDERLINE && this.special_tokens.includes(tokens[1])) {\n tokens = tokens.slice(1);\n }\n return tokens;\n }\n}\nexport class CodeLlamaTokenizer extends PreTrainedTokenizer { }\n\nexport class XLMRobertaTokenizer extends PreTrainedTokenizer { }\nexport class MPNetTokenizer extends PreTrainedTokenizer { }\n\nexport class FalconTokenizer extends PreTrainedTokenizer { }\n\nexport class GPTNeoXTokenizer extends PreTrainedTokenizer { }\n\nexport class EsmTokenizer extends PreTrainedTokenizer { }\n\nexport class Qwen2Tokenizer extends PreTrainedTokenizer { }\n\nexport class GemmaTokenizer extends PreTrainedTokenizer { }\n\nexport class Grok1Tokenizer extends PreTrainedTokenizer { }\n\n/**\n * Helper function to build translation inputs for an `NllbTokenizer` or `M2M100Tokenizer`.\n * @param {PreTrainedTokenizer} self The tokenizer instance.\n * @param {string|string[]} raw_inputs The text to tokenize.\n * @param {Object} tokenizer_options Options to be sent to the tokenizer\n * @param {Object} generate_kwargs Generation options.\n * @returns {Object} Object to be passed to the model.\n * @private\n */\nfunction _build_translation_inputs(self, raw_inputs, tokenizer_options, generate_kwargs) {\n if (!('language_codes' in self) || !Array.isArray(self.language_codes)) {\n throw new Error('Tokenizer must have `language_codes` attribute set and it should be an array of language ids.')\n }\n if (!('languageRegex' in self) || !(self.languageRegex instanceof RegExp)) {\n throw new Error('Tokenizer must have `languageRegex` attribute set and it should be a regular expression.')\n }\n if (!('lang_to_token' in self) || typeof self.lang_to_token !== 'function') {\n throw new Error('Tokenizer must have `lang_to_token` attribute set and it should be a function.')\n }\n const src_lang_token = generate_kwargs.src_lang;\n const tgt_lang_token = generate_kwargs.tgt_lang;\n\n // Check that the target language is valid:\n if (!self.language_codes.includes(tgt_lang_token)) {\n throw new Error(`Target language code \"${tgt_lang_token}\" is not valid. Must be one of: {${self.language_codes.join(', ')}}`);\n }\n\n // Allow `src_lang` to be optional. If not set, we'll use the tokenizer's default.\n if (src_lang_token !== undefined) {\n // Check that the source language is valid:\n if (!self.language_codes.includes(src_lang_token)) {\n throw new Error(`Source language code \"${src_lang_token}\" is not valid. Must be one of: {${self.language_codes.join(', ')}}`);\n }\n\n // In the same way as the Python library, we override the post-processor\n // to force the source language to be first:\n for (const item of self.post_processor.config.single) {\n if ('SpecialToken' in item && self.languageRegex.test(item.SpecialToken.id)) {\n item.SpecialToken.id = self.lang_to_token(src_lang_token);\n break;\n }\n }\n // TODO: Do the same for pair?\n }\n\n // Override the `forced_bos_token_id` to force the correct language\n generate_kwargs.forced_bos_token_id = self.model.convert_tokens_to_ids([self.lang_to_token(tgt_lang_token)])[0];\n\n return self._call(raw_inputs, tokenizer_options);\n}\n\n/**\n * The NllbTokenizer class is used to tokenize text for NLLB (\"No Language Left Behind\") models.\n * \n * No Language Left Behind (NLLB) is a first-of-its-kind, AI breakthrough project\n * that open-sources models capable of delivering high-quality translations directly\n * between any pair of 200+ languages — including low-resource languages like Asturian,\n * Luganda, Urdu and more. It aims to help people communicate with anyone, anywhere,\n * regardless of their language preferences. For more information, check out their\n * [paper](https://arxiv.org/abs/2207.04672).\n * \n * For a list of supported languages (along with their language codes),\n * @see {@link https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200}\n */\nexport class NllbTokenizer extends PreTrainedTokenizer {\n\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.languageRegex = /^[a-z]{3}_[A-Z][a-z]{3}$/;\n this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x));\n this.lang_to_token = x => x; // Identity function\n }\n\n /**\n * Helper function to build translation inputs for an `NllbTokenizer`.\n * @param {string|string[]} raw_inputs The text to tokenize.\n * @param {Object} tokenizer_options Options to be sent to the tokenizer\n * @param {Object} generate_kwargs Generation options.\n * @returns {Object} Object to be passed to the model.\n */\n _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {\n return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);\n }\n}\n\n/**\n * The M2M100Tokenizer class is used to tokenize text for M2M100 (\"Many-to-Many\") models.\n * \n * M2M100 is a multilingual encoder-decoder (seq-to-seq) model trained for Many-to-Many\n * multilingual translation. It was introduced in this [paper](https://arxiv.org/abs/2010.11125)\n * and first released in [this](https://github.com/pytorch/fairseq/tree/master/examples/m2m_100) repository.\n * \n * For a list of supported languages (along with their language codes),\n * @see {@link https://huggingface.co/facebook/m2m100_418M#languages-covered}\n */\nexport class M2M100Tokenizer extends PreTrainedTokenizer {\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.languageRegex = /^__[a-z]{2,3}__$/;\n this.language_codes = this.special_tokens\n .filter(x => this.languageRegex.test(x))\n .map(x => x.slice(2, -2));\n this.lang_to_token = x => `__${x}__`;\n }\n\n /**\n * Helper function to build translation inputs for an `M2M100Tokenizer`.\n * @param {string|string[]} raw_inputs The text to tokenize.\n * @param {Object} tokenizer_options Options to be sent to the tokenizer\n * @param {Object} generate_kwargs Generation options.\n * @returns {Object} Object to be passed to the model.\n */\n _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) {\n return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs);\n }\n}\n\n/**\n * WhisperTokenizer tokenizer\n * @extends PreTrainedTokenizer\n */\nexport class WhisperTokenizer extends PreTrainedTokenizer {\n\n get timestamp_begin() {\n return this.model.convert_tokens_to_ids([\"<|notimestamps|>\"])[0] + 1;\n }\n\n /**\n * Decodes automatic speech recognition (ASR) sequences.\n * @param {Array<{tokens: bigint[], token_timestamps?: number[], stride: number[]}>} sequences The sequences to decode.\n * @param {Object} options The options to use for decoding.\n * @returns {Array, text: string}>}>} The decoded sequences.\n */\n _decode_asr(sequences, {\n return_timestamps = false,\n return_language = false,\n time_precision = null,\n force_full_sequences = true\n } = {}) {\n // Set force_full_sequences=false if you want streaming\n // TODO add support for `return_language`\n\n // Internal method meant to only be used by asr pipeline.\n // Handles all the little quirks specific to whisper to handle\n // the various options not allowed in other seq2seq models\n\n // =========== Overview ============\n // - iterate over all outputs\n // - all tokens within output\n // - Each token can be\n // - language token\n // - special token\n // - timestamp token\n // - text token\n // - We accumulate the text tokens.\n // - We split on end timestamps\n // - Lots of complexity comes from stride and timestamps\n\n if (time_precision === null) {\n throw Error(\"Must specify time_precision\")\n }\n let last_language = null;\n\n const returnWordTimestamps = return_timestamps === \"word\";\n\n function new_chunk() {\n return { \"language\": last_language, \"timestamp\": [null, null], \"text\": \"\" };\n }\n\n // Welcome to the state machine!\n const chunks = [];\n let chunk = new_chunk();\n let time_offset = 0.0;\n const timestamp_begin = this.timestamp_begin;\n\n let previous_tokens = [];\n let previous_token_timestamps = [];\n\n let skip = false;\n let right_stride_start = null;\n\n\n const all_special_ids = new Set(this.all_special_ids);\n\n for (const output of sequences) {\n // NOTE: python version has batches, so it uses [0]\n const token_ids = output.tokens;\n const token_timestamps = returnWordTimestamps ? output.token_timestamps : null;\n\n // These keep track of timestamps within strides, which need\n // to be skipped and resolve all tokens in a single chunk.\n let last_timestamp = null;\n let first_timestamp = timestamp_begin;\n\n if (\"stride\" in output) {\n const [chunk_len, stride_left, stride_right] = output.stride;\n\n // Offset the timings to account for the other `model_outputs`.\n time_offset -= stride_left;\n right_stride_start = chunk_len - stride_right;\n\n // Keeping track of timestamps within strides\n // We're going to NOT split on those, and delay until we're\n // out of BOTH stride. Otherwise lots of issues occur and\n // corner cases\n if (stride_left) {\n first_timestamp = stride_left / time_precision + timestamp_begin;\n }\n\n if (stride_right) {\n for (let i = token_ids.length - 1; i >= 0; --i) {\n const token = Number(token_ids[i]);\n if (token >= timestamp_begin) {\n // There can be several token in the right stride\n // But the last one is ALWAYS going to be skipped\n if (last_timestamp !== null && (token - timestamp_begin) * time_precision < right_stride_start) {\n break;\n }\n last_timestamp = token;\n }\n }\n }\n }\n\n let current_tokens = [];\n let current_token_timestamps = [];\n\n // - all tokens within output\n for (let i = 0; i < token_ids.length; ++i) {\n const token = Number(token_ids[i]);\n // 4 possible states for each token\n // - 1/ Language code\n // - 2/ all other special tokens (which we ignore)\n // - 3/ Timestamp\n // - 4/ Regular text\n\n if (all_special_ids.has(token)) {\n const text = this.decode([token]);\n const language = WHISPER_LANGUAGE_MAPPING.get(text.slice(2, -2));\n\n if (language !== undefined) {\n // 1/ Indeed some language\n // TODO Handle when language is different from the previous\n // one, and we cannot use timestamped tokens to create chunks\n if (last_language !== null && language !== last_language && !return_timestamps) {\n previous_tokens.push(current_tokens);\n const resolved_tokens = this.findLongestCommonSequence(previous_tokens)[0];\n const resolved_text = this.decode(resolved_tokens);\n chunk.text = resolved_text;\n chunks.push(chunk);\n\n // Flush all our temporary context\n previous_tokens = [];\n current_tokens = [];\n chunk = new_chunk();\n }\n\n last_language = chunk.language = language;\n } else {\n // 2/ This is a regular special token, ignoring it\n }\n } else if (token >= timestamp_begin) {\n // 3/ Timestamp token\n const time = (token - timestamp_begin) * time_precision + time_offset;\n const rounded_time = round(time, 2);\n\n if (last_timestamp !== null && token >= last_timestamp) {\n // Whisper outputted a timestamp token, but it falls within\n // our stride, so we're going to skip it for the time being\n // and resolve this later\n // Skip is necessary because timestamp tokens always come\n // by pair, so we need to skip the next one too (which would mark the start of another chunk).\n skip = true;\n } else if (skip || (previous_tokens.length > 0 && token < first_timestamp)) {\n skip = false;\n } else if (chunk.timestamp[0] === null) {\n chunk.timestamp[0] = rounded_time;\n } else {\n // This is the end of the timestamp chunk\n if (rounded_time === chunk.timestamp[0]) {\n // This is a bug in timestamp token output\n // where we're taking the duplicate token\n // as a stop where it should be a start.\n // This is an issue in the underlying model output\n // Let's just skip it so it becomes de-factor a start agin\n } else {\n chunk.timestamp[1] = rounded_time;\n\n // Handling merges\n previous_tokens.push(current_tokens)\n\n if (returnWordTimestamps) {\n previous_token_timestamps.push(current_token_timestamps);\n }\n const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(\n previous_tokens, previous_token_timestamps\n )\n\n const resolved_text = this.decode(resolved_tokens)\n chunk.text = resolved_text\n\n if (returnWordTimestamps) {\n chunk.words = this.collateWordTimestamps(\n resolved_tokens, resolved_token_timestamps, last_language,\n )\n }\n\n chunks.push(chunk)\n\n // Flush all our temporary context\n previous_tokens = []\n current_tokens = []\n previous_token_timestamps = []\n current_token_timestamps = []\n chunk = new_chunk()\n }\n }\n\n } else {\n // 4/ Regular token\n // We just append to the list of all tokens so we can handle\n // merges later and decode into text.\n current_tokens.push(token)\n\n if (returnWordTimestamps) {\n let start_time = round(token_timestamps[i] + time_offset, 2);\n\n let end_time;\n if (i + 1 < token_timestamps.length) {\n end_time = round(token_timestamps[i + 1] + time_offset, 2);\n\n // Do not allow punctuation-only tokens to have a duration.\n // This prevents long pauses from messing up the timestamps.\n const decoded_text = this.decode([token]);\n if (PUNCTUATION_ONLY_REGEX.test(decoded_text)) {\n // Add `time_precision` to avoid overlapping timestamps\n end_time = round(Math.min(start_time + time_precision, end_time), 2);\n }\n } else {\n // should never happen\n end_time = null;\n }\n current_token_timestamps.push([start_time, end_time]);\n }\n\n }\n }\n\n if ('stride' in output) {\n const [chunk_len, stride_left, stride_right] = output.stride;\n time_offset += chunk_len - stride_right\n }\n\n // Leftover tokens\n if (current_tokens.length > 0) {\n previous_tokens.push(current_tokens)\n if (returnWordTimestamps) {\n previous_token_timestamps.push(current_token_timestamps);\n }\n } else if (previous_tokens.every(p => p.length === 0)) {\n // Flushing previous tokens (END)\"\n chunk = new_chunk()\n previous_tokens = []\n current_tokens = []\n previous_token_timestamps = [];\n current_token_timestamps = [];\n }\n\n }\n\n if (previous_tokens.length > 0) {\n if (force_full_sequences && return_timestamps) {\n // Last token should always be timestamps, so there shouldn't be\n // leftover\n throw new Error(\n \"Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. \" +\n \"Also make sure WhisperTimeStampLogitsProcessor was used during generation.\"\n );\n }\n\n // Happens when we don't use timestamps\n const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(previous_tokens, previous_token_timestamps);\n\n // Flushing previous tokens (FINAL)\n const resolved_text = this.decode(resolved_tokens);\n chunk.text = resolved_text;\n if (returnWordTimestamps) {\n chunk.words = this.collateWordTimestamps(\n resolved_tokens, resolved_token_timestamps, last_language,\n )\n }\n chunks.push(chunk);\n }\n\n let optional = Object.create(null);\n\n // Preparing and cleaning up the pipeline output\n const full_text = chunks.map(chunk => chunk.text).join('');\n if (return_timestamps || return_language) {\n for (let i = 0; i < chunks.length; ++i) {\n const chunk = chunks[i];\n if (!return_timestamps) {\n delete chunk[\"timestamp\"];\n }\n\n if (!return_language) {\n delete chunk[\"language\"];\n }\n }\n if (returnWordTimestamps) {\n const new_chunks = [];\n for (const chunk of chunks) {\n for (const word of chunk.words) {\n new_chunks.push(word);\n }\n }\n optional = { \"chunks\": new_chunks };\n } else {\n optional = { \"chunks\": chunks };\n }\n }\n return [full_text, optional];\n\n }\n\n /**\n * Finds the longest common sequence among the provided sequences.\n * @param {number[][]} sequences An array of sequences of token ids to compare.\n * @returns {number[][]} The longest common sequence found.\n * @throws {Error} If there is a bug within the function.\n * @private\n */\n findLongestCommonSequence(sequences, token_timestamp_sequences = null) {\n // It would be much harder to do O(n) because of fault tolerance.\n // We actually have a really good property which is that the total sequence\n // MUST be those subsequences in order.\n // If token_timestamp_sequences is provided, will split those sequences in\n // exactly the same way.\n let leftSequence = sequences[0];\n let leftLength = leftSequence.length;\n let totalSequence = [];\n\n const use_token_timestamp_sequences = Array.isArray(token_timestamp_sequences) && token_timestamp_sequences.length > 0;\n let total_token_timestamp_sequence = use_token_timestamp_sequences ? [] : null;\n let left_token_timestamp_sequence = use_token_timestamp_sequences ? token_timestamp_sequences[0] : null;\n for (let i = 1; i < sequences.length; ++i) {\n const rightSequence = sequences[i];\n let max = 0.0;\n let maxIndices = [leftLength, leftLength, 0, 0];\n // Here we're sliding matches\n // [a, b, c, d]\n // [c, d, f]\n // = [c] == [d]\n\n // [a, b, c, d]\n // [c, d, f]\n // = [c, d] == [c, d]\n\n\n // [a, b, c, d]\n // [c, d, f]\n\n // = [b, c, d] == [c, d, f]\n\n // [a, b, c, d]\n // [c, d, f]\n\n // [a, b, c] == [c, d, f]\n\n // [a, b, c, d]\n // [d, f]\n\n // [a, b] == [d, f]\n\n // [a, b, c, d]\n // [f]\n\n // [a] == [f]\n\n const rightLength = rightSequence.length;\n for (let j = 1; j < leftLength + rightLength; ++j) {\n // Slightly convoluted because we don't want out of bound indices\n // This will be necessary for a small conflict resolution optimization\n // later\n const leftStart = Math.max(0, leftLength - j);\n const leftStop = Math.min(leftLength, leftLength + rightLength - j);\n const left = leftSequence.slice(leftStart, leftStop);\n const rightStart = Math.max(0, j - leftLength);\n const rightStop = Math.min(rightLength, j);\n const right = rightSequence.slice(rightStart, rightStop);\n if (left.length !== right.length) {\n throw new Error(\"There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.\");\n }\n\n let matches;\n if (use_token_timestamp_sequences) {\n // Get length of longest subsequence of tokens that match\n // and have timestamps that are in order\n matches = left.filter((elem, idx) => (\n elem === right[idx]\n && left_token_timestamp_sequence[leftStart + idx] <= token_timestamp_sequences[i][rightStart + idx]\n )).length;\n } else {\n matches = left.filter((elem, idx) => elem === right[idx]).length;\n }\n\n // epsilon to favor long perfect matches\n const eps = j / 10000.0;\n const matching = matches / j + eps;\n if (matches > 1 && matching > max) {\n max = matching;\n maxIndices = [leftStart, leftStop, rightStart, rightStop];\n }\n }\n const [leftStart, leftStop, rightStart, rightStop] = maxIndices;\n const leftMid = Math.floor((leftStop + leftStart) / 2);\n const rightMid = Math.floor((rightStop + rightStart) / 2);\n totalSequence.push(...leftSequence.slice(0, leftMid));\n leftSequence = rightSequence.slice(rightMid);\n leftLength = leftSequence.length;\n\n if (use_token_timestamp_sequences) {\n total_token_timestamp_sequence.push(...left_token_timestamp_sequence.slice(0, leftMid));\n left_token_timestamp_sequence = token_timestamp_sequences[i].slice(rightMid);\n }\n }\n totalSequence.push(...leftSequence);\n\n if (use_token_timestamp_sequences) {\n total_token_timestamp_sequence.push(...left_token_timestamp_sequence);\n return [totalSequence, total_token_timestamp_sequence];\n } else {\n return [totalSequence, []];\n }\n }\n\n /** @private */\n collateWordTimestamps(tokens, token_timestamps, language) {\n\n const [words, _, token_indices] = this.combineTokensIntoWords(tokens, language);\n\n const timings = [];\n for (let i = 0; i < words.length; ++i) {\n const indices = token_indices[i];\n timings.push({\n text: words[i],\n timestamp: [\n token_timestamps[indices.at(0)][0],\n token_timestamps[indices.at(-1)][1],\n ],\n });\n }\n return timings;\n }\n\n /**\n * Groups tokens by word. Returns a tuple containing a list of strings with the words,\n * and a list of `token_id` sequences with the tokens making up each word.\n * @param {number[]} tokens \n * @param {string} [language] \n * @param {string} prepend_punctionations \n * @param {string} append_punctuations \n * \n * @private\n */\n combineTokensIntoWords(tokens, language, prepend_punctionations = \"\\\"'“¡¿([{-\", append_punctuations = \"\\\"'.。,,!!??::”)]}、\") {\n language = language ?? 'english';\n\n let words, word_tokens, token_indices;\n\n if ([\"chinese\", \"japanese\", \"thai\", \"lao\", \"myanmar\"].includes(language)) {\n // These languages don't typically use spaces.\n [words, word_tokens, token_indices] = this.splitTokensOnUnicode(tokens)\n } else {\n [words, word_tokens, token_indices] = this.splitTokensOnSpaces(tokens)\n }\n\n return this.mergePunctuations(words, word_tokens, token_indices, prepend_punctionations, append_punctuations);\n }\n\n /** @type {PreTrainedTokenizer['decode']} */\n decode(\n token_ids,\n decode_args,\n ) {\n let text;\n // @ts-ignore\n if (decode_args?.decode_with_timestamps) {\n if (token_ids instanceof Tensor) {\n token_ids = prepareTensorForDecode(token_ids);\n }\n text = this.decodeWithTimestamps(token_ids, decode_args);\n } else {\n text = super.decode(token_ids, decode_args);\n }\n // TODO: implement offsets\n // if (decode_args.output_offsets) {\n // let offsets = this.computeOffsets\n // }\n return text;\n }\n\n /**\n * @param {number[]|bigint[]} token_ids List of token IDs to decode.\n * @param {Object} decode_args Optional arguments for decoding\n * @private\n */\n decodeWithTimestamps(token_ids, decode_args) {\n const time_precision = decode_args?.time_precision ?? 0.02;\n\n const timestamp_begin = Array.from(this.all_special_ids).at(-1) + 1;\n /**@type {Array} */\n let outputs = [[]];\n for (let token of token_ids) {\n token = Number(token);\n if (token >= timestamp_begin) {\n const timestamp = ((token - timestamp_begin) * time_precision).toFixed(2);\n outputs.push(`<|${timestamp}|>`);\n outputs.push([]);\n } else {\n outputs[outputs.length - 1].push(token);\n }\n }\n outputs = outputs.map(\n s => typeof s === 'string' ? s : super.decode(s, decode_args)\n )\n\n return outputs.join('');\n }\n\n /**\n * Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points.\n * @param {number[]} tokens \n * @returns {*}\n * @private\n */\n splitTokensOnUnicode(tokens) {\n const decoded_full = this.decode(tokens, {\n // @ts-ignore\n decode_with_timestamps: true,\n });\n const replacement_char = '\\uFFFD';\n\n const words = []\n const word_tokens = []\n const token_indices = []\n let current_tokens = []\n let current_indices = []\n let unicode_offset = 0\n\n for (let token_idx = 0; token_idx < tokens.length; ++token_idx) {\n const token = tokens[token_idx];\n\n current_tokens.push(token);\n current_indices.push(token_idx);\n\n const decoded = this.decode(current_tokens, {\n // @ts-ignore\n decode_with_timestamps: true,\n });\n\n if (!decoded.includes(replacement_char) || decoded_full[unicode_offset + decoded.indexOf(replacement_char)] === replacement_char) {\n words.push(decoded)\n word_tokens.push(current_tokens)\n token_indices.push(current_indices)\n current_tokens = []\n current_indices = []\n unicode_offset += decoded.length;\n }\n\n }\n\n return [words, word_tokens, token_indices]\n }\n\n /**\n * Combine tokens into words by splitting at whitespace and punctuation tokens.\n * @param {number[]} tokens \n * @private\n */\n splitTokensOnSpaces(tokens) {\n\n const [subwords, subword_tokens_list, subword_indices_list] = this.splitTokensOnUnicode(tokens);\n\n const words = []\n const word_tokens = []\n const token_indices = []\n\n const punctuationRegex = new RegExp(`^[${PUNCTUATION_REGEX}]$`, 'gu');\n\n for (let i = 0; i < subwords.length; ++i) {\n\n const subword = subwords[i];\n const subword_tokens = subword_tokens_list[i];\n const subword_indices = subword_indices_list[i];\n\n // @ts-ignore\n const special = subword_tokens[0] >= this.model.tokens_to_ids.get('<|endoftext|>');\n const with_space = subword.startsWith(' ');\n const trimmed = subword.trim();\n const punctuation = punctuationRegex.test(trimmed);\n\n if (special || with_space || punctuation || words.length === 0) {\n words.push(subword);\n word_tokens.push(subword_tokens);\n token_indices.push(subword_indices);\n } else {\n const ix = words.length - 1;\n words[ix] += subword;\n word_tokens[ix].push(...subword_tokens);\n token_indices[ix].push(...subword_indices);\n }\n }\n\n return [words, word_tokens, token_indices];\n\n }\n\n /**\n * Merges punctuation tokens with neighboring words.\n * @param {string[]} words \n * @param {number[][]} tokens \n * @param {number[][]} indices \n * @param {string} prepended \n * @param {string} appended \n * @private\n */\n mergePunctuations(words, tokens, indices, prepended, appended) {\n\n const newWords = structuredClone(words);\n const newTokens = structuredClone(tokens);\n const newIndices = structuredClone(indices);\n\n\n // prepend punctuations\n let i = newWords.length - 2;\n let j = newWords.length - 1;\n\n while (i >= 0) {\n if (newWords[i].startsWith(' ') && prepended.includes(newWords[i].trim())) {\n newWords[j] = newWords[i] + newWords[j];\n newTokens[j] = mergeArrays(newTokens[i], newTokens[j]);\n newIndices[j] = mergeArrays(newIndices[i], newIndices[j]);\n newWords[i] = '';\n newTokens[i] = [];\n newIndices[i] = [];\n } else {\n j = i;\n }\n --i;\n }\n\n // append punctuations\n i = 0;\n j = 1;\n while (j < newWords.length) {\n if (!newWords[i].endsWith(' ') && appended.includes(newWords[j])) {\n newWords[i] += newWords[j];\n newTokens[i] = mergeArrays(newTokens[i], newTokens[j]);\n newIndices[i] = mergeArrays(newIndices[i], newIndices[j]);\n newWords[j] = '';\n newTokens[j] = [];\n newIndices[j] = [];\n } else {\n i = j;\n }\n ++j;\n }\n\n return [\n newWords.filter(x => x),\n newTokens.filter(x => x.length > 0),\n newIndices.filter(x => x.length > 0),\n ]\n }\n}\nexport class CodeGenTokenizer extends PreTrainedTokenizer { }\nexport class CLIPTokenizer extends PreTrainedTokenizer { }\nexport class SiglipTokenizer extends PreTrainedTokenizer { }\n\n/**\n * @todo This model is not yet supported by Hugging Face's \"fast\" tokenizers library (https://github.com/huggingface/tokenizers).\n * Therefore, this implementation (which is based on fast tokenizers) may produce slightly inaccurate results.\n */\nexport class MarianTokenizer extends PreTrainedTokenizer {\n /**\n * Create a new MarianTokenizer instance.\n * @param {Object} tokenizerJSON The JSON of the tokenizer.\n * @param {Object} tokenizerConfig The config of the tokenizer.\n */\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n this.languageRegex = /^(>>\\w+<<)\\s*/g;\n\n this.supported_language_codes = this.model.vocab.filter(\n x => this.languageRegex.test(x)\n );\n\n console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\\'s \"fast\" tokenizers library. Therefore, you may experience slightly inaccurate results.')\n }\n\n /**\n * Encodes a single text. Overriding this method is necessary since the language codes\n * must be removed before encoding with sentencepiece model.\n * @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213\n *\n * @param {string|null} text The text to encode.\n * @returns {Array} The encoded tokens.\n */\n _encode_text(text) {\n if (text === null) return null;\n\n // Check if text starts with language code:\n const [matchInfo, ...remainder] = text.trim().split(this.languageRegex);\n\n if (remainder.length === 0) {\n // No language code, encode normally\n return super._encode_text(matchInfo);\n\n } else if (remainder.length === 2) {\n // Text starts with language code, so we do not encode it with sentencepiece.\n const [language, text] = remainder;\n\n if (!this.supported_language_codes.includes(language)) {\n console.warn(`Unsupported language code \"${language}\" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`)\n }\n return mergeArrays([language], super._encode_text(text));\n }\n }\n\n}\n\nexport class Wav2Vec2CTCTokenizer extends PreTrainedTokenizer { }\n\nexport class BlenderbotTokenizer extends PreTrainedTokenizer { }\nexport class BlenderbotSmallTokenizer extends PreTrainedTokenizer { }\n\nexport class SpeechT5Tokenizer extends PreTrainedTokenizer { }\n\nexport class NougatTokenizer extends PreTrainedTokenizer { }\n\nexport class VitsTokenizer extends PreTrainedTokenizer {\n\n constructor(tokenizerJSON, tokenizerConfig) {\n super(tokenizerJSON, tokenizerConfig);\n\n // Custom decoder function\n this.decoder = new VitsDecoder({});\n }\n}\n\nexport class CohereTokenizer extends PreTrainedTokenizer { }\n\n/**\n * Helper class which is used to instantiate pretrained tokenizers with the `from_pretrained` function.\n * The chosen tokenizer class is determined by the type specified in the tokenizer config.\n * \n * @example\n * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased');\n */\nexport class AutoTokenizer {\n static TOKENIZER_CLASS_MAPPING = {\n T5Tokenizer,\n DistilBertTokenizer,\n CamembertTokenizer,\n DebertaTokenizer,\n DebertaV2Tokenizer,\n BertTokenizer,\n HerbertTokenizer,\n ConvBertTokenizer,\n RoFormerTokenizer,\n XLMTokenizer,\n ElectraTokenizer,\n MobileBertTokenizer,\n SqueezeBertTokenizer,\n AlbertTokenizer,\n GPT2Tokenizer,\n BartTokenizer,\n MBartTokenizer,\n MBart50Tokenizer,\n RobertaTokenizer,\n WhisperTokenizer,\n CodeGenTokenizer,\n CLIPTokenizer,\n SiglipTokenizer,\n MarianTokenizer,\n BloomTokenizer,\n NllbTokenizer,\n M2M100Tokenizer,\n LlamaTokenizer,\n CodeLlamaTokenizer,\n XLMRobertaTokenizer,\n MPNetTokenizer,\n FalconTokenizer,\n GPTNeoXTokenizer,\n EsmTokenizer,\n Wav2Vec2CTCTokenizer,\n BlenderbotTokenizer,\n BlenderbotSmallTokenizer,\n SpeechT5Tokenizer,\n NougatTokenizer,\n VitsTokenizer,\n Qwen2Tokenizer,\n GemmaTokenizer,\n Grok1Tokenizer,\n CohereTokenizer,\n\n // Base case:\n PreTrainedTokenizer,\n }\n\n\n /**\n * Instantiate one of the tokenizer classes of the library from a pretrained model.\n * \n * The tokenizer class to instantiate is selected based on the `tokenizer_class` property of the config object\n * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)\n * \n * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:\n * - A string, the *model id* of a pretrained tokenizer hosted inside a model repo on huggingface.co.\n * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a\n * user or organization name, like `dbmdz/bert-base-german-cased`.\n * - A path to a *directory* containing tokenizer files, e.g., `./my_model_directory/`.\n * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer.\n * \n * @returns {Promise} A new instance of the PreTrainedTokenizer class.\n */\n static async from_pretrained(pretrained_model_name_or_path, {\n progress_callback = null,\n config = null,\n cache_dir = null,\n local_files_only = false,\n revision = 'main',\n legacy = null,\n } = {}) {\n\n const [tokenizerJSON, tokenizerConfig] = await loadTokenizer(pretrained_model_name_or_path, {\n progress_callback,\n config,\n cache_dir,\n local_files_only,\n revision,\n legacy,\n })\n\n // Some tokenizers are saved with the \"Fast\" suffix, so we remove that if present.\n const tokenizerName = tokenizerConfig.tokenizer_class?.replace(/Fast$/, '') ?? 'PreTrainedTokenizer';\n\n let cls = this.TOKENIZER_CLASS_MAPPING[tokenizerName];\n if (!cls) {\n console.warn(`Unknown tokenizer class \"${tokenizerName}\", attempting to construct from base class.`);\n cls = PreTrainedTokenizer;\n }\n return new cls(tokenizerJSON, tokenizerConfig);\n }\n}\n","/**\n * @file Helper module for audio processing. \n * \n * These functions and classes are only used internally, \n * meaning an end-user shouldn't need to access anything here.\n * \n * @module utils/audio\n */\n\nimport {\n getFile,\n} from './hub.js';\nimport { FFT, max } from './maths.js';\nimport {\n calculateReflectOffset,\n} from './core.js';\nimport { Tensor, matmul } from './tensor.js';\n\n\n/**\n * Helper function to read audio from a path/URL.\n * @param {string|URL} url The path/URL to load the audio from.\n * @param {number} sampling_rate The sampling rate to use when decoding the audio.\n * @returns {Promise} The decoded audio as a `Float32Array`.\n */\nexport async function read_audio(url, sampling_rate) {\n if (typeof AudioContext === 'undefined') {\n // Running in node or an environment without AudioContext\n throw Error(\n \"Unable to load audio from path/URL since `AudioContext` is not available in your environment. \" +\n \"Instead, audio data should be passed directly to the pipeline/processor. \" +\n \"For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.\"\n )\n }\n\n const response = await (await getFile(url)).arrayBuffer();\n const audioCTX = new AudioContext({ sampleRate: sampling_rate });\n if (typeof sampling_rate === 'undefined') {\n console.warn(`No sampling rate provided, using default of ${audioCTX.sampleRate}Hz.`)\n }\n const decoded = await audioCTX.decodeAudioData(response);\n\n /** @type {Float32Array} */\n let audio;\n\n // We now replicate HuggingFace's `ffmpeg_read` method:\n if (decoded.numberOfChannels === 2) {\n // When downmixing a stereo audio file to mono using the -ac 1 option in FFmpeg,\n // the audio signal is summed across both channels to create a single mono channel.\n // However, if the audio is at full scale (i.e. the highest possible volume level),\n // the summing of the two channels can cause the audio signal to clip or distort.\n\n // To prevent this clipping, FFmpeg applies a scaling factor of 1/sqrt(2) (~ 0.707)\n // to the audio signal before summing the two channels. This scaling factor ensures\n // that the combined audio signal will not exceed the maximum possible level, even\n // if both channels are at full scale.\n\n // After applying this scaling factor, the audio signal from both channels is summed\n // to create a single mono channel. It's worth noting that this scaling factor is\n // only applied when downmixing stereo audio to mono using the -ac 1 option in FFmpeg.\n // If you're using a different downmixing method, or if you're not downmixing the\n // audio at all, this scaling factor may not be needed.\n const SCALING_FACTOR = Math.sqrt(2);\n\n const left = decoded.getChannelData(0);\n const right = decoded.getChannelData(1);\n\n audio = new Float32Array(left.length);\n for (let i = 0; i < decoded.length; ++i) {\n audio[i] = SCALING_FACTOR * (left[i] + right[i]) / 2;\n }\n\n } else {\n // If the audio is not stereo, we can just use the first channel:\n audio = decoded.getChannelData(0);\n }\n\n return audio;\n}\n\n/**\n * Helper function to generate windows that are special cases of the generalized cosine window.\n * See https://www.mathworks.com/help/signal/ug/generalized-cosine-windows.html for more information.\n * @param {number} M Number of points in the output window. If zero or less, an empty array is returned.\n * @param {number} a_0 Offset for the generalized cosine window.\n * @returns {Float64Array} The generated window.\n */\nfunction generalized_cosine_window(M, a_0) {\n if (M < 1) {\n return new Float64Array();\n }\n if (M === 1) {\n return new Float64Array([1]);\n }\n\n const a_1 = 1 - a_0;\n const factor = 2 * Math.PI / (M - 1);\n\n const cos_vals = new Float64Array(M);\n for (let i = 0; i < M; ++i) {\n cos_vals[i] = a_0 - a_1 * Math.cos(i * factor);\n }\n return cos_vals;\n}\n\n/**\n * Generates a Hanning window of length M.\n * See https://numpy.org/doc/stable/reference/generated/numpy.hanning.html for more information.\n *\n * @param {number} M The length of the Hanning window to generate.\n * @returns {Float64Array} The generated Hanning window.\n */\nexport function hanning(M) {\n return generalized_cosine_window(M, 0.5);\n}\n\n\n/**\n * Generates a Hamming window of length M.\n * See https://numpy.org/doc/stable/reference/generated/numpy.hamming.html for more information.\n *\n * @param {number} M The length of the Hamming window to generate.\n * @returns {Float64Array} The generated Hamming window.\n */\nexport function hamming(M) {\n return generalized_cosine_window(M, 0.54);\n}\n\n\nconst HERTZ_TO_MEL_MAPPING = {\n \"htk\": (/** @type {number} */ freq) => 2595.0 * Math.log10(1.0 + (freq / 700.0)),\n \"kaldi\": (/** @type {number} */ freq) => 1127.0 * Math.log(1.0 + (freq / 700.0)),\n \"slaney\": (/** @type {number} */ freq, min_log_hertz = 1000.0, min_log_mel = 15.0, logstep = 27.0 / Math.log(6.4)) =>\n freq >= min_log_hertz\n ? min_log_mel + Math.log(freq / min_log_hertz) * logstep\n : 3.0 * freq / 200.0,\n}\n\n/**\n * @template {Float32Array|Float64Array|number} T \n * @param {T} freq \n * @param {string} [mel_scale]\n * @returns {T}\n */\nfunction hertz_to_mel(freq, mel_scale = \"htk\") {\n const fn = HERTZ_TO_MEL_MAPPING[mel_scale];\n if (!fn) {\n throw new Error('mel_scale should be one of \"htk\", \"slaney\" or \"kaldi\".');\n }\n\n return typeof freq === 'number' ? fn(freq) : freq.map(x => fn(x));\n}\n\nconst MEL_TO_HERTZ_MAPPING = {\n \"htk\": (/** @type {number} */ mels) => 700.0 * (10.0 ** (mels / 2595.0) - 1.0),\n \"kaldi\": (/** @type {number} */ mels) => 700.0 * (Math.exp(mels / 1127.0) - 1.0),\n \"slaney\": (/** @type {number} */ mels, min_log_hertz = 1000.0, min_log_mel = 15.0, logstep = Math.log(6.4) / 27.0) => mels >= min_log_mel\n ? min_log_hertz * Math.exp(logstep * (mels - min_log_mel))\n : 200.0 * mels / 3.0,\n}\n\n/**\n * @template {Float32Array|Float64Array|number} T \n * @param {T} mels \n * @param {string} [mel_scale]\n * @returns {T}\n */\nfunction mel_to_hertz(mels, mel_scale = \"htk\") {\n const fn = MEL_TO_HERTZ_MAPPING[mel_scale];\n if (!fn) {\n throw new Error('mel_scale should be one of \"htk\", \"slaney\" or \"kaldi\".');\n }\n\n return typeof mels === 'number' ? fn(mels) : mels.map(x => fn(x));\n}\n\n/**\n* Creates a triangular filter bank.\n*\n* Adapted from torchaudio and librosa.\n*\n* @param {Float64Array} fft_freqs Discrete frequencies of the FFT bins in Hz, of shape `(num_frequency_bins,)`.\n* @param {Float64Array} filter_freqs Center frequencies of the triangular filters to create, in Hz, of shape `(num_mel_filters,)`.\n* @returns {number[][]} of shape `(num_frequency_bins, num_mel_filters)`.\n*/\nfunction _create_triangular_filter_bank(fft_freqs, filter_freqs) {\n const filter_diff = Float64Array.from(\n { length: filter_freqs.length - 1 },\n (_, i) => filter_freqs[i + 1] - filter_freqs[i]\n );\n\n const slopes = Array.from({\n length: fft_freqs.length\n }, () => new Array(filter_freqs.length));\n\n for (let j = 0; j < fft_freqs.length; ++j) {\n const slope = slopes[j];\n for (let i = 0; i < filter_freqs.length; ++i) {\n slope[i] = filter_freqs[i] - fft_freqs[j];\n }\n }\n\n const numFreqs = filter_freqs.length - 2;\n const ret = Array.from({ length: numFreqs }, () => new Array(fft_freqs.length));\n\n for (let j = 0; j < fft_freqs.length; ++j) { // 201\n const slope = slopes[j];\n for (let i = 0; i < numFreqs; ++i) { // 80\n const down = -slope[i] / filter_diff[i];\n const up = slope[i + 2] / filter_diff[i + 1];\n ret[i][j] = Math.max(0, Math.min(down, up));\n }\n }\n return ret;\n}\n\n/**\n * Return evenly spaced numbers over a specified interval.\n * @param {number} start The starting value of the sequence.\n * @param {number} end The end value of the sequence.\n * @param {number} num Number of samples to generate.\n * @returns `num` evenly spaced samples, calculated over the interval `[start, stop]`.\n */\nfunction linspace(start, end, num) {\n const step = (end - start) / (num - 1);\n return Float64Array.from({ length: num }, (_, i) => start + step * i);\n}\n\n/**\n * Creates a frequency bin conversion matrix used to obtain a mel spectrogram. This is called a *mel filter bank*, and\n * various implementation exist, which differ in the number of filters, the shape of the filters, the way the filters\n * are spaced, the bandwidth of the filters, and the manner in which the spectrum is warped. The goal of these\n * features is to approximate the non-linear human perception of the variation in pitch with respect to the frequency.\n * @param {number} num_frequency_bins Number of frequencies used to compute the spectrogram (should be the same as in `stft`).\n * @param {number} num_mel_filters Number of mel filters to generate.\n * @param {number} min_frequency Lowest frequency of interest in Hz.\n * @param {number} max_frequency Highest frequency of interest in Hz. This should not exceed `sampling_rate / 2`.\n * @param {number} sampling_rate Sample rate of the audio waveform.\n * @param {string} [norm] If `\"slaney\"`, divide the triangular mel weights by the width of the mel band (area normalization).\n * @param {string} [mel_scale] The mel frequency scale to use, `\"htk\"` or `\"slaney\"`.\n * @param {boolean} [triangularize_in_mel_space] If this option is enabled, the triangular filter is applied in mel space rather than frequency space.\n * This should be set to `true` in order to get the same results as `torchaudio` when computing mel filters.\n * @returns {number[][]} Triangular filter bank matrix, which is a 2D array of shape (`num_frequency_bins`, `num_mel_filters`).\n * This is a projection matrix to go from a spectrogram to a mel spectrogram.\n */\nexport function mel_filter_bank(\n num_frequency_bins,\n num_mel_filters,\n min_frequency,\n max_frequency,\n sampling_rate,\n norm = null,\n mel_scale = \"htk\",\n triangularize_in_mel_space = false,\n) {\n if (norm !== null && norm !== \"slaney\") {\n throw new Error('norm must be one of null or \"slaney\"');\n }\n\n const mel_min = hertz_to_mel(min_frequency, mel_scale);\n const mel_max = hertz_to_mel(max_frequency, mel_scale);\n const mel_freqs = linspace(mel_min, mel_max, num_mel_filters + 2);\n\n let filter_freqs = mel_to_hertz(mel_freqs, mel_scale);\n let fft_freqs; // frequencies of FFT bins in Hz\n\n if (triangularize_in_mel_space) {\n const fft_bin_width = sampling_rate / (num_frequency_bins * 2);\n fft_freqs = hertz_to_mel(Float64Array.from({ length: num_frequency_bins }, (_, i) => i * fft_bin_width), mel_scale);\n filter_freqs = mel_freqs;\n } else {\n fft_freqs = linspace(0, Math.floor(sampling_rate / 2), num_frequency_bins);\n }\n\n const mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs);\n\n if (norm !== null && norm === \"slaney\") {\n // Slaney-style mel is scaled to be approx constant energy per channel\n for (let i = 0; i < num_mel_filters; ++i) {\n const filter = mel_filters[i];\n const enorm = 2.0 / (filter_freqs[i + 2] - filter_freqs[i]);\n for (let j = 0; j < num_frequency_bins; ++j) {\n // Apply this enorm to all frequency bins\n filter[j] *= enorm;\n }\n }\n }\n\n // TODO warn if there is a zero row\n\n return mel_filters;\n\n}\n\n/**\n * @template {Float32Array|Float64Array} T\n * Pads an array with a reflected version of itself on both ends.\n * @param {T} array The array to pad.\n * @param {number} left The amount of padding to add to the left.\n * @param {number} right The amount of padding to add to the right.\n * @returns {T} The padded array.\n */\nfunction padReflect(array, left, right) {\n // @ts-ignore\n const padded = new array.constructor(array.length + left + right);\n const w = array.length - 1;\n\n for (let i = 0; i < array.length; ++i) {\n padded[left + i] = array[i];\n }\n\n for (let i = 1; i <= left; ++i) {\n padded[left - i] = array[calculateReflectOffset(i, w)];\n }\n\n for (let i = 1; i <= right; ++i) {\n padded[w + left + i] = array[calculateReflectOffset(w - i, w)];\n }\n\n return padded;\n}\n\n/**\n * Helper function to compute `amplitude_to_db` and `power_to_db`.\n * @template {Float32Array|Float64Array} T\n * @param {T} spectrogram \n * @param {number} factor \n * @param {number} reference \n * @param {number} min_value \n * @param {number} db_range \n * @returns {T}\n */\nfunction _db_conversion_helper(spectrogram, factor, reference, min_value, db_range) {\n if (reference <= 0) {\n throw new Error('reference must be greater than zero');\n }\n\n if (min_value <= 0) {\n throw new Error('min_value must be greater than zero');\n }\n\n reference = Math.max(min_value, reference);\n\n const logReference = Math.log10(reference);\n for (let i = 0; i < spectrogram.length; ++i) {\n spectrogram[i] = factor * Math.log10(Math.max(min_value, spectrogram[i]) - logReference)\n }\n\n if (db_range !== null) {\n if (db_range <= 0) {\n throw new Error('db_range must be greater than zero');\n }\n const maxValue = max(spectrogram)[0] - db_range;\n for (let i = 0; i < spectrogram.length; ++i) {\n spectrogram[i] = Math.max(spectrogram[i], maxValue);\n }\n }\n\n return spectrogram;\n}\n\n/**\n * Converts an amplitude spectrogram to the decibel scale. This computes `20 * log10(spectrogram / reference)`,\n * using basic logarithm properties for numerical stability. NOTE: Operates in-place.\n * \n * The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a\n * linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.\n * This means that large variations in energy may not sound all that different if the sound is loud to begin with.\n * This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.\n * \n * @template {Float32Array|Float64Array} T\n * @param {T} spectrogram The input amplitude (mel) spectrogram.\n * @param {number} [reference=1.0] Sets the input spectrogram value that corresponds to 0 dB.\n * For example, use `np.max(spectrogram)` to set the loudest part to 0 dB. Must be greater than zero.\n * @param {number} [min_value=1e-5] The spectrogram will be clipped to this minimum value before conversion to decibels,\n * to avoid taking `log(0)`. The default of `1e-5` corresponds to a minimum of -100 dB. Must be greater than zero.\n * @param {number} [db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the\n * difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero.\n * @returns {T} The modified spectrogram in decibels.\n */\nfunction amplitude_to_db(spectrogram, reference = 1.0, min_value = 1e-5, db_range = null) {\n return _db_conversion_helper(spectrogram, 20.0, reference, min_value, db_range);\n}\n\n/**\n * Converts a power spectrogram to the decibel scale. This computes `10 * log10(spectrogram / reference)`,\n * using basic logarithm properties for numerical stability. NOTE: Operates in-place.\n * \n * The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a\n * linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it.\n * This means that large variations in energy may not sound all that different if the sound is loud to begin with.\n * This compression operation makes the (mel) spectrogram features match more closely what humans actually hear.\n * \n * Based on the implementation of `librosa.power_to_db`.\n * \n * @template {Float32Array|Float64Array} T\n * @param {T} spectrogram The input power (mel) spectrogram. Note that a power spectrogram has the amplitudes squared!\n * @param {number} [reference=1.0] Sets the input spectrogram value that corresponds to 0 dB.\n * For example, use `np.max(spectrogram)` to set the loudest part to 0 dB. Must be greater than zero.\n * @param {number} [min_value=1e-10] The spectrogram will be clipped to this minimum value before conversion to decibels,\n * to avoid taking `log(0)`. The default of `1e-10` corresponds to a minimum of -100 dB. Must be greater than zero.\n * @param {number} [db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the\n * difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero.\n * @returns {T} The modified spectrogram in decibels.\n */\nfunction power_to_db(spectrogram, reference = 1.0, min_value = 1e-10, db_range = null) {\n return _db_conversion_helper(spectrogram, 10.0, reference, min_value, db_range);\n}\n\n/**\n * Calculates a spectrogram over one waveform using the Short-Time Fourier Transform.\n * \n * This function can create the following kinds of spectrograms:\n * - amplitude spectrogram (`power = 1.0`)\n * - power spectrogram (`power = 2.0`)\n * - complex-valued spectrogram (`power = None`)\n * - log spectrogram (use `log_mel` argument)\n * - mel spectrogram (provide `mel_filters`)\n * - log-mel spectrogram (provide `mel_filters` and `log_mel`)\n *\n * In this implementation, the window is assumed to be zero-padded to have the same size as the analysis frame.\n * A padded window can be obtained from `window_function()`. The FFT input buffer may be larger than the analysis frame, \n * typically the next power of two.\n * \n * @param {Float32Array|Float64Array} waveform The input waveform of shape `(length,)`. This must be a single real-valued, mono waveform.\n * @param {Float32Array|Float64Array} window The windowing function to apply of shape `(frame_length,)`, including zero-padding if necessary. The actual window length may be\n * shorter than `frame_length`, but we're assuming the array has already been zero-padded.\n * @param {number} frame_length The length of the analysis frames in samples (a.k.a., `fft_length`).\n * @param {number} hop_length The stride between successive analysis frames in samples.\n * @param {Object} options\n * @param {number} [options.fft_length=null] The size of the FFT buffer in samples. This determines how many frequency bins the spectrogram will have.\n * For optimal speed, this should be a power of two. If `null`, uses `frame_length`.\n * @param {number} [options.power=1.0] If 1.0, returns the amplitude spectrogram. If 2.0, returns the power spectrogram. If `null`, returns complex numbers.\n * @param {boolean} [options.center=true] Whether to pad the waveform so that frame `t` is centered around time `t * hop_length`. If `false`, frame\n * `t` will start at time `t * hop_length`.\n * @param {string} [options.pad_mode=\"reflect\"] Padding mode used when `center` is `true`. Possible values are: `\"constant\"` (pad with zeros),\n * `\"edge\"` (pad with edge values), `\"reflect\"` (pads with mirrored values).\n * @param {boolean} [options.onesided=true] If `true`, only computes the positive frequencies and returns a spectrogram containing `fft_length // 2 + 1`\n * frequency bins. If `false`, also computes the negative frequencies and returns `fft_length` frequency bins.\n * @param {number} [options.preemphasis=null] Coefficient for a low-pass filter that applies pre-emphasis before the DFT.\n * @param {number[][]} [options.mel_filters=null] The mel filter bank of shape `(num_freq_bins, num_mel_filters)`.\n * If supplied, applies this filter bank to create a mel spectrogram.\n * @param {number} [options.mel_floor=1e-10] Minimum value of mel frequency banks.\n * @param {string} [options.log_mel=null] How to convert the spectrogram to log scale. Possible options are:\n * `null` (don't convert), `\"log\"` (take the natural logarithm) `\"log10\"` (take the base-10 logarithm), `\"dB\"` (convert to decibels).\n * Can only be used when `power` is not `null`.\n * @param {number} [options.reference=1.0] Sets the input spectrogram value that corresponds to 0 dB. For example, use `max(spectrogram)[0]` to set\n * the loudest part to 0 dB. Must be greater than zero.\n * @param {number} [options.min_value=1e-10] The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking `log(0)`.\n * For a power spectrogram, the default of `1e-10` corresponds to a minimum of -100 dB. For an amplitude spectrogram, the value `1e-5` corresponds to -100 dB.\n * Must be greater than zero.\n * @param {number} [options.db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the\n * peak value and the smallest value will never be more than 80 dB. Must be greater than zero.\n * @param {boolean} [options.remove_dc_offset=null] Subtract mean from waveform on each frame, applied before pre-emphasis. This should be set to `true` in\n * order to get the same results as `torchaudio.compliance.kaldi.fbank` when computing mel filters.\n * @param {number} [options.max_num_frames=null] If provided, limits the number of frames to compute to this value.\n * @param {number} [options.min_num_frames=null] If provided, ensures the number of frames to compute is at least this value.\n * @param {boolean} [options.do_pad=true] If `true`, pads the output spectrogram to have `max_num_frames` frames.\n * @param {boolean} [options.transpose=false] If `true`, the returned spectrogram will have shape `(num_frames, num_frequency_bins/num_mel_filters)`. If `false`, the returned spectrogram will have shape `(num_frequency_bins/num_mel_filters, num_frames)`.\n * @returns {Promise} Spectrogram of shape `(num_frequency_bins, length)` (regular spectrogram) or shape `(num_mel_filters, length)` (mel spectrogram).\n */\nexport async function spectrogram(\n waveform,\n window,\n frame_length,\n hop_length,\n {\n fft_length = null,\n power = 1.0,\n center = true,\n pad_mode = \"reflect\",\n onesided = true,\n preemphasis = null,\n mel_filters = null,\n mel_floor = 1e-10,\n log_mel = null,\n reference = 1.0,\n min_value = 1e-10,\n db_range = null,\n remove_dc_offset = null,\n\n // Custom parameters for efficiency reasons\n min_num_frames = null,\n max_num_frames = null,\n do_pad = true,\n transpose = false,\n } = {}\n) {\n const window_length = window.length;\n if (fft_length === null) {\n fft_length = frame_length;\n }\n if (frame_length > fft_length) {\n throw Error(`frame_length (${frame_length}) may not be larger than fft_length (${fft_length})`)\n }\n\n if (window_length !== frame_length) {\n throw new Error(`Length of the window (${window_length}) must equal frame_length (${frame_length})`);\n }\n\n if (hop_length <= 0) {\n throw new Error(\"hop_length must be greater than zero\");\n }\n\n if (power === null && mel_filters !== null) {\n throw new Error(\n \"You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. \" +\n \"Specify `power` to fix this issue.\"\n );\n }\n\n if (center) {\n if (pad_mode !== 'reflect') {\n throw new Error(`pad_mode=\"${pad_mode}\" not implemented yet.`)\n }\n const half_window = Math.floor((fft_length - 1) / 2) + 1;\n waveform = padReflect(waveform, half_window, half_window);\n }\n\n // split waveform into frames of frame_length size\n let num_frames = Math.floor(1 + Math.floor((waveform.length - frame_length) / hop_length))\n if (min_num_frames !== null && num_frames < min_num_frames) {\n num_frames = min_num_frames\n }\n const num_frequency_bins = onesided ? Math.floor(fft_length / 2) + 1 : fft_length\n\n let d1 = num_frames;\n let d1Max = num_frames;\n\n // If maximum number of frames is provided, we must either pad or truncate\n if (max_num_frames !== null) {\n if (max_num_frames > num_frames) { // input is too short, so we pad\n if (do_pad) {\n d1Max = max_num_frames;\n }\n } else { // input is too long, so we truncate\n d1Max = d1 = max_num_frames;\n }\n }\n\n // Preallocate arrays to store output.\n const fft = new FFT(fft_length);\n const inputBuffer = new Float64Array(fft_length);\n const outputBuffer = new Float64Array(fft.outputBufferSize);\n const transposedMagnitudeData = new Float32Array(num_frequency_bins * d1Max);\n\n for (let i = 0; i < d1; ++i) {\n // Populate buffer with waveform data\n const offset = i * hop_length;\n const buffer_size = Math.min(waveform.length - offset, frame_length);\n if (buffer_size !== frame_length) {\n // The full buffer is not needed, so we need to reset it (avoid overflow from previous iterations)\n // NOTE: We don't need to reset the buffer if it's full since we overwrite the first\n // `frame_length` values and the rest (`fft_length - frame_length`) remains zero.\n inputBuffer.fill(0, 0, frame_length);\n }\n\n for (let j = 0; j < buffer_size; ++j) {\n inputBuffer[j] = waveform[offset + j];\n }\n\n if (remove_dc_offset) {\n let sum = 0;\n for (let j = 0; j < buffer_size; ++j) {\n sum += inputBuffer[j];\n }\n const mean = sum / buffer_size;\n for (let j = 0; j < buffer_size; ++j) {\n inputBuffer[j] -= mean;\n }\n }\n\n if (preemphasis !== null) {\n // Done in reverse to avoid copies and distructive modification\n for (let j = buffer_size - 1; j >= 1; --j) {\n inputBuffer[j] -= preemphasis * inputBuffer[j - 1];\n }\n inputBuffer[0] *= 1 - preemphasis;\n }\n\n // Apply window function\n for (let j = 0; j < window.length; ++j) {\n inputBuffer[j] *= window[j];\n }\n\n fft.realTransform(outputBuffer, inputBuffer);\n\n // compute magnitudes\n for (let j = 0; j < num_frequency_bins; ++j) {\n const j2 = j << 1;\n\n // NOTE: We transpose the data here to avoid doing it later\n transposedMagnitudeData[j * d1Max + i] = outputBuffer[j2] ** 2 + outputBuffer[j2 + 1] ** 2;\n }\n }\n\n if (power !== null && power !== 2) {\n // slight optimization to not sqrt\n const pow = 2 / power; // we use 2 since we already squared\n for (let i = 0; i < transposedMagnitudeData.length; ++i) {\n transposedMagnitudeData[i] **= pow;\n }\n }\n\n // TODO: What if `mel_filters` is null?\n const num_mel_filters = mel_filters.length;\n\n // Perform matrix muliplication:\n // mel_spec = mel_filters @ magnitudes.T\n // - mel_filters.shape=(80, 201)\n // - magnitudes.shape=(3000, 201) => magnitudes.T.shape=(201, 3000)\n // - mel_spec.shape=(80, 3000)\n let mel_spec = await matmul(\n // TODO: Make `mel_filters` a Tensor during initialization\n new Tensor('float32', mel_filters.flat(), [num_mel_filters, num_frequency_bins]),\n new Tensor('float32', transposedMagnitudeData, [num_frequency_bins, d1Max]),\n );\n if (transpose) {\n mel_spec = mel_spec.transpose(1, 0);\n }\n\n const mel_spec_data = /** @type {Float32Array} */(mel_spec.data);\n for (let i = 0; i < mel_spec_data.length; ++i) {\n mel_spec_data[i] = Math.max(mel_floor, mel_spec_data[i]);\n }\n\n if (power !== null && log_mel !== null) {\n const o = Math.min(mel_spec_data.length, d1 * num_mel_filters);\n // NOTE: operates in-place\n switch (log_mel) {\n case 'log':\n for (let i = 0; i < o; ++i) {\n mel_spec_data[i] = Math.log(mel_spec_data[i]);\n }\n break;\n case 'log10':\n for (let i = 0; i < o; ++i) {\n mel_spec_data[i] = Math.log10(mel_spec_data[i]);\n }\n break;\n case 'dB':\n if (power === 1.0) {\n amplitude_to_db(mel_spec_data, reference, min_value, db_range);\n } else if (power === 2.0) {\n power_to_db(mel_spec_data, reference, min_value, db_range);\n } else {\n throw new Error(`Cannot use log_mel option '${log_mel}' with power ${power}`)\n }\n break;\n default:\n throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${log_mel}'`);\n }\n }\n\n return mel_spec;\n}\n\n/**\n * Returns an array containing the specified window.\n * @param {number} window_length The length of the window in samples.\n * @param {string} name The name of the window function.\n * @param {Object} options Additional options.\n * @param {boolean} [options.periodic=true] Whether the window is periodic or symmetric.\n * @param {number} [options.frame_length=null] The length of the analysis frames in samples.\n * Provide a value for `frame_length` if the window is smaller than the frame length, so that it will be zero-padded.\n * @param {boolean} [options.center=true] Whether to center the window inside the FFT buffer. Only used when `frame_length` is provided.\n * @returns {Float64Array} The window of shape `(window_length,)` or `(frame_length,)`.\n */\nexport function window_function(window_length, name, {\n periodic = true,\n frame_length = null,\n center = true,\n} = {}) {\n const length = periodic ? window_length + 1 : window_length;\n let window;\n switch (name) {\n case 'boxcar':\n window = new Float64Array(length).fill(1.0);\n break;\n case 'hann':\n case 'hann_window':\n window = hanning(length);\n break;\n case 'hamming':\n window = hamming(length);\n break;\n case 'povey':\n window = hanning(length).map(x => Math.pow(x, 0.85));\n break;\n default:\n throw new Error(`Unknown window type ${name}.`);\n }\n if (periodic) {\n window = window.subarray(0, window_length);\n }\n if (frame_length === null) {\n return window;\n }\n if (window_length > frame_length) {\n throw new Error(`Length of the window (${window_length}) may not be larger than frame_length (${frame_length})`);\n }\n\n return window;\n}\n","\nexport const GITHUB_ISSUE_URL = 'https://github.com/huggingface/transformers.js/issues/new/choose';","\n/**\n * @file Core utility functions/classes for Transformers.js.\n * \n * These are only used internally, meaning an end-user shouldn't\n * need to access anything here.\n * \n * @module utils/core\n */\n\n/**\n * Helper function to dispatch progress callbacks.\n *\n * @param {Function} progress_callback The progress callback function to dispatch.\n * @param {any} data The data to pass to the progress callback function.\n * @returns {void}\n * @private\n */\nexport function dispatchCallback(progress_callback, data) {\n if (progress_callback) progress_callback(data);\n}\n\n/**\n * Reverses the keys and values of an object.\n *\n * @param {Object} data The object to reverse.\n * @returns {Object} The reversed object.\n * @see https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript\n */\nexport function reverseDictionary(data) {\n // https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript\n return Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key]));\n}\n\n/**\n * Escapes regular expression special characters from a string by replacing them with their escaped counterparts.\n *\n * @param {string} string The string to escape.\n * @returns {string} The escaped string.\n */\nexport function escapeRegExp(string) {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); // $& means the whole matched string\n}\n\n/**\n * Check if a value is a typed array.\n * @param {*} val The value to check.\n * @returns {boolean} True if the value is a `TypedArray`, false otherwise.\n * \n * Adapted from https://stackoverflow.com/a/71091338/13989043\n */\nexport function isTypedArray(val) {\n return val?.prototype?.__proto__?.constructor?.name === 'TypedArray';\n}\n\n\n/**\n * Check if a value is an integer.\n * @param {*} x The value to check.\n * @returns {boolean} True if the value is a string, false otherwise.\n */\nexport function isIntegralNumber(x) {\n return Number.isInteger(x) || typeof x === 'bigint'\n}\n\n/**\n * Calculates the dimensions of a nested array.\n *\n * @param {any[]} arr The nested array to calculate dimensions for.\n * @returns {number[]} An array containing the dimensions of the input array.\n */\nexport function calculateDimensions(arr) {\n const dimensions = [];\n let current = arr;\n while (Array.isArray(current)) {\n dimensions.push(current.length);\n current = current[0];\n }\n return dimensions;\n}\n\n/**\n * Replicate python's .pop() method for objects.\n * @param {Object} obj The object to pop from.\n * @param {string} key The key to pop.\n * @param {*} defaultValue The default value to return if the key does not exist.\n * @returns {*} The value of the popped key.\n * @throws {Error} If the key does not exist and no default value is provided.\n */\nexport function pop(obj, key, defaultValue = undefined) {\n const value = obj[key];\n if (value !== undefined) {\n delete obj[key];\n return value;\n }\n if (defaultValue === undefined) {\n throw Error(`Key ${key} does not exist in object.`)\n }\n return defaultValue;\n}\n\n/**\n * Efficiently merge arrays, creating a new copy.\n * Adapted from https://stackoverflow.com/a/6768642/13989043\n * @param {Array[]} arrs Arrays to merge.\n * @returns {Array} The merged array.\n */\nexport function mergeArrays(...arrs) {\n return Array.prototype.concat.apply([], arrs);\n}\n\n/**\n * Compute the Cartesian product of given arrays\n * @param {...Array} a Arrays to compute the product\n * @returns {Array} Returns the computed Cartesian product as an array\n * @private\n */\nexport function product(...a) {\n // Cartesian product of items\n // Adapted from https://stackoverflow.com/a/43053803\n return a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e])));\n}\n\n/**\n * Calculates the index offset for a given index and window size.\n * @param {number} i The index.\n * @param {number} w The window size.\n * @returns {number} The index offset.\n */\nexport function calculateReflectOffset(i, w) {\n return Math.abs((i + w) % (2 * w) - w);\n}\n\n/**\n * \n * @param {Object} o \n * @param {string[]} props \n * @returns {Object}\n */\nexport function pick(o, props) {\n return Object.assign(\n {},\n ...props.map((prop) => {\n if (o[prop] !== undefined) {\n return { [prop]: o[prop] };\n }\n })\n );\n}\n\n/**\n * Calculate the length of a string, taking multi-byte characters into account.\n * This mimics the behavior of Python's `len` function.\n * @param {string} s The string to calculate the length of. \n * @returns {number} The length of the string.\n */\nexport function len(s) {\n let length = 0;\n for (const c of s) ++length;\n return length;\n}\n","\n/**\n * @file Custom data structures.\n * \n * These are only used internally, meaning an end-user shouldn't\n * need to access anything here.\n * \n * @module utils/data-structures\n */\n\n\n/**\n * Efficient Heap-based Implementation of a Priority Queue.\n * It uses an array-based binary heap, where the root is at index `0`, and the\n * children of node `i` are located at indices `2i + 1` and `2i + 2`, respectively.\n * \n * Adapted from the following sources:\n * - https://stackoverflow.com/a/42919752/13989043 (original)\n * - https://github.com/belladoreai/llama-tokenizer-js (minor improvements)\n */\nexport class PriorityQueue {\n\n /**\n * Create a new PriorityQueue.\n * @param {function(any, any): boolean} comparator Comparator function to determine priority. Defaults to a MaxHeap.\n */\n constructor(comparator = (a, b) => a > b, maxSize = Infinity) {\n this._heap = [];\n this._comparator = comparator;\n this._maxSize = maxSize;\n }\n\n /**\n * The size of the queue\n */\n get size() {\n return this._heap.length;\n }\n\n /**\n * Check if the queue is empty.\n * @returns {boolean} `true` if the queue is empty, `false` otherwise.\n */\n isEmpty() {\n return this.size === 0;\n }\n\n /**\n * Return the element with the highest priority in the queue.\n * @returns {any} The highest priority element in the queue.\n */\n peek() {\n return this._heap[0];\n }\n\n /**\n * Add one or more elements to the queue.\n * @param {...any} values The values to push into the queue.\n * @returns {number} The new size of the queue.\n */\n push(...values) {\n return this.extend(values);\n }\n\n /**\n * Add multiple elements to the queue.\n * @param {any[]} values The values to push into the queue.\n * @returns {number} The new size of the queue.\n */\n extend(values) {\n for (const value of values) {\n if (this.size < this._maxSize) {\n this._heap.push(value);\n this._siftUp();\n } else {\n // Get index of value with the lowest priority\n const smallest = this._smallest();\n\n // If the new value has higher priority than the smallest value in the heap\n // then replace the smallest value with the new value and update the heap\n if (this._comparator(value, this._heap[smallest])) {\n this._heap[smallest] = value;\n this._siftUpFrom(smallest);\n }\n }\n }\n return this.size;\n }\n\n /**\n * Remove and return the element with the highest priority in the queue.\n * @returns {any} The element with the highest priority in the queue.\n */\n pop() {\n const poppedValue = this.peek();\n const bottom = this.size - 1;\n if (bottom > 0) {\n this._swap(0, bottom);\n }\n this._heap.pop();\n this._siftDown();\n return poppedValue;\n }\n\n /**\n * Replace the element with the highest priority in the queue with a new value.\n * @param {*} value The new value.\n * @returns {*} The replaced value.\n */\n replace(value) {\n const replacedValue = this.peek();\n this._heap[0] = value;\n this._siftDown();\n return replacedValue;\n }\n\n /**\n * Compute the index for the parent of the node at index `i`.\n * @param {number} i The index of the node to get the parent of.\n * @returns {number} The index of the parent node.\n * @private\n */\n _parent(i) {\n return ((i + 1) >>> 1) - 1;\n }\n\n /**\n * Compute the index for the left child of the node at index `i`.\n * @param {number} i The index of the node to get the left child of.\n * @returns {number} The index of the left child.\n * @private\n */\n _left(i) {\n return (i << 1) + 1;\n }\n\n /**\n * Compute the index for the right child of the node at index `i`.\n * @param {number} i The index of the node to get the right child of.\n * @returns {number} The index of the right child.\n * @private\n */\n _right(i) {\n return (i + 1) << 1;\n }\n\n /**\n * Check if the element at index `i` is greater than the element at index `j`.\n * @param {number} i The index of the first element to compare.\n * @param {number} j The index of the second element to compare.\n * @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.\n * @private\n */\n _greater(i, j) {\n return this._comparator(this._heap[i], this._heap[j]);\n }\n\n /**\n * Swap the elements at indices `i` and `j`.\n * @param {number} i The index of the first element to swap.\n * @param {number} j The index of the second element to swap.\n * @private\n */\n _swap(i, j) {\n const temp = this._heap[i];\n this._heap[i] = this._heap[j];\n this._heap[j] = temp;\n }\n\n /**\n * Maintain the heap property by updating positions in the heap,\n * starting at the last element and moving up the heap.\n * @private\n */\n _siftUp() {\n this._siftUpFrom(this.size - 1);\n }\n\n /**\n * Helper function to sift up from a given node.\n * @param {number} node The index of the node to start sifting up from.\n */\n _siftUpFrom(node) {\n while (node > 0 && this._greater(node, this._parent(node))) {\n this._swap(node, this._parent(node));\n node = this._parent(node);\n }\n }\n\n /**\n * Maintain the heap property by updating positions in the heap,\n * starting at the first element and moving down the heap.\n * @private\n */\n _siftDown() {\n let node = 0;\n while (\n (this._left(node) < this.size && this._greater(this._left(node), node)) ||\n (this._right(node) < this.size && this._greater(this._right(node), node))\n ) {\n const maxChild = (this._right(node) < this.size && this._greater(this._right(node), this._left(node)))\n ? this._right(node)\n : this._left(node);\n this._swap(node, maxChild);\n node = maxChild;\n }\n }\n\n /**\n * Get the index of the smallest element in the heap. Since we use an array-based heap,\n * the index can be computed without needing to traverse the heap.\n * @private\n */\n _smallest() {\n return (2 ** (Math.floor(Math.log2(this.size))) - 1);\n }\n}\n\n/**\n * A trie structure to efficiently store and search for strings.\n */\nexport class CharTrie {\n constructor() {\n this.root = CharTrieNode.default();\n }\n\n /**\n * Adds one or more `texts` to the trie.\n * @param {string[]} texts The strings to add to the trie.\n */\n extend(texts) {\n for (const text of texts) {\n this.push(text);\n }\n }\n\n /**\n * Adds text to the trie.\n * @param {string} text The string to add to the trie.\n */\n push(text) {\n let node = this.root;\n for (const ch of text) {\n let child = node.children.get(ch);\n if (child === undefined) {\n child = CharTrieNode.default();\n node.children.set(ch, child);\n }\n node = child;\n }\n node.isLeaf = true;\n }\n\n /**\n * Searches the trie for all strings with a common prefix of `text`.\n * @param {string} text The common prefix to search for.\n * @yields {string} Each string in the trie that has `text` as a prefix.\n */\n *commonPrefixSearch(text) {\n let node = this.root;\n if (node === undefined) return;\n\n let prefix = \"\";\n for (const ch of text) {\n prefix += ch;\n node = node.children.get(ch);\n if (node === undefined) return;\n if (node.isLeaf) {\n yield prefix;\n }\n }\n }\n}\n\n/**\n * Represents a node in a character trie.\n */\nclass CharTrieNode {\n /**\n * Create a new CharTrieNode.\n * @param {boolean} isLeaf Whether the node is a leaf node or not.\n * @param {Map} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.\n */\n constructor(isLeaf, children) {\n this.isLeaf = isLeaf;\n this.children = children;\n }\n\n /**\n * Returns a new `CharTrieNode` instance with default values.\n * @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map.\n */\n static default() {\n return new CharTrieNode(false, new Map());\n }\n}\n\n/**\n * A lattice data structure to be used for tokenization.\n */\nexport class TokenLattice {\n /**\n * Creates a new TokenLattice instance.\n *\n * @param {string} sentence The input sentence to be tokenized.\n * @param {number} bosTokenId The beginning-of-sequence token ID.\n * @param {number} eosTokenId The end-of-sequence token ID.\n */\n constructor(sentence, bosTokenId, eosTokenId) {\n this.chars = Array.from(sentence);\n this.len = this.chars.length;\n this.bosTokenId = bosTokenId;\n this.eosTokenId = eosTokenId;\n this.nodes = [];\n this.beginNodes = Array.from({ length: this.len + 1 }, () => []);\n this.endNodes = Array.from({ length: this.len + 1 }, () => []);\n\n const bos = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0.0);\n const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0.0);\n this.nodes.push(bos.clone());\n this.nodes.push(eos.clone());\n this.beginNodes[this.len].push(eos);\n this.endNodes[0].push(bos);\n }\n\n /**\n * Inserts a new token node into the token lattice.\n *\n * @param {number} pos The starting position of the token.\n * @param {number} length The length of the token.\n * @param {number} score The score of the token.\n * @param {number} tokenId The token ID of the token.\n */\n insert(pos, length, score, tokenId) {\n const nodeId = this.nodes.length;\n const node = new TokenLatticeNode(tokenId, nodeId, pos, length, score);\n this.beginNodes[pos].push(node);\n this.endNodes[pos + length].push(node);\n this.nodes.push(node);\n }\n\n /**\n * Implements the Viterbi algorithm to compute the most likely sequence of tokens.\n *\n * @returns {TokenLatticeNode[]} The most likely sequence of tokens.\n */\n viterbi() {\n const len = this.len;\n let pos = 0;\n while (pos <= len) {\n if (this.beginNodes[pos].length == 0) {\n return [];\n }\n for (let rnode of this.beginNodes[pos]) {\n rnode.prev = null;\n let bestScore = 0.0;\n let bestNode = null;\n for (let lnode of this.endNodes[pos]) {\n const score = lnode.backtraceScore + rnode.score;\n if (bestNode === null || score > bestScore) {\n bestNode = lnode.clone();\n bestScore = score;\n }\n }\n\n if (bestNode !== null) {\n rnode.prev = bestNode;\n rnode.backtraceScore = bestScore;\n } else {\n return [];\n }\n }\n ++pos;\n }\n\n const results = [];\n const root = this.beginNodes[len][0];\n const prev = root.prev;\n if (prev === null) {\n return [];\n }\n\n let node = prev.clone();\n while (node.prev !== null) {\n results.push(node.clone());\n const n = node.clone();\n node = n.prev.clone();\n }\n\n results.reverse();\n return results;\n }\n\n /**\n * @param {TokenLatticeNode} node\n * @returns {string} The array of nodes representing the most likely sequence of tokens.\n */\n piece(node) {\n return this.chars.slice(node.pos, node.pos + node.length).join('');\n }\n\n /**\n * @returns {string[]} The most likely sequence of tokens.\n */\n tokens() {\n const nodes = this.viterbi();\n return nodes.map(x => this.piece(x));\n }\n\n /**\n * @returns {number[]} The most likely sequence of token ids.\n */\n tokenIds() {\n const nodes = this.viterbi();\n return nodes.map(x => x.tokenId);\n }\n}\nclass TokenLatticeNode {\n /**\n * Represents a node in a token lattice for a given sentence.\n * @param {number} tokenId The ID of the token associated with this node.\n * @param {number} nodeId The ID of this node.\n * @param {number} pos The starting position of the token in the sentence.\n * @param {number} length The length of the token.\n * @param {number} score The score associated with the token.\n */\n constructor(tokenId, nodeId, pos, length, score) {\n this.tokenId = tokenId;\n this.nodeId = nodeId;\n this.pos = pos;\n this.length = length;\n this.score = score;\n this.prev = null;\n this.backtraceScore = 0.0;\n }\n\n /**\n * Returns a clone of this node.\n * @returns {TokenLatticeNode} A clone of this node.\n */\n clone() {\n const n = new TokenLatticeNode(this.tokenId, this.nodeId, this.pos, this.length, this.score);\n n.prev = this.prev;\n n.backtraceScore = this.backtraceScore;\n return n;\n }\n}\n","\n/**\n * The list of devices supported by Transformers.js\n */\nexport const DEVICE_TYPES = Object.freeze({\n auto: 'auto', // Auto-detect based on device and environment\n gpu: 'gpu', // Auto-detect GPU\n cpu: 'cpu', // CPU\n wasm: 'wasm', // WebAssembly\n webgpu: 'webgpu', // WebGPU\n cuda: 'cuda', // CUDA\n dml: 'dml', // DirectML\n\n webnn: 'webnn', // WebNN (default)\n 'webnn-npu': 'webnn-npu', // WebNN NPU\n 'webnn-gpu': 'webnn-gpu', // WebNN GPU\n 'webnn-cpu': 'webnn-cpu', // WebNN CPU\n});\n\n/**\n * @typedef {keyof typeof DEVICE_TYPES} DeviceType\n */\n","import { apis } from \"../env.js\";\n\nimport { DEVICE_TYPES } from \"./devices.js\";\n\n// TODO: Use the adapter from `env.backends.onnx.webgpu.adapter` to check for `shader-f16` support,\n// when available in https://github.com/microsoft/onnxruntime/pull/19940.\n// For more information, see https://github.com/microsoft/onnxruntime/pull/19857#issuecomment-1999984753\n\n/**\n * Checks if WebGPU fp16 support is available in the current environment.\n */\nexport const isWebGpuFp16Supported = (function () {\n /** @type {boolean} */\n let cachedResult;\n\n return async function () {\n if (cachedResult === undefined) {\n if (!apis.IS_WEBGPU_AVAILABLE) {\n cachedResult = false;\n } else {\n try {\n const adapter = await navigator.gpu.requestAdapter();\n cachedResult = adapter.features.has('shader-f16');\n } catch (e) {\n cachedResult = false;\n }\n }\n }\n return cachedResult;\n };\n})();\n\nexport const DATA_TYPES = Object.freeze({\n fp32: 'fp32',\n fp16: 'fp16',\n q8: 'q8',\n int8: 'int8',\n uint8: 'uint8',\n q4: 'q4',\n bnb4: 'bnb4',\n q4f16: 'q4f16', // fp16 model with int4 block weight quantization\n});\n/** @typedef {keyof typeof DATA_TYPES} DataType */\n\nexport const DEFAULT_DEVICE_DTYPE_MAPPING = Object.freeze({\n // NOTE: If not specified, will default to fp32\n [DEVICE_TYPES.wasm]: DATA_TYPES.q8,\n});\n\n/** @type {Record} */\nexport const DEFAULT_DTYPE_SUFFIX_MAPPING = Object.freeze({\n [DATA_TYPES.fp32]: '',\n [DATA_TYPES.fp16]: '_fp16',\n [DATA_TYPES.int8]: '_int8',\n [DATA_TYPES.uint8]: '_uint8',\n [DATA_TYPES.q8]: '_quantized',\n [DATA_TYPES.q4]: '_q4',\n [DATA_TYPES.q4f16]: '_q4f16',\n [DATA_TYPES.bnb4]: '_bnb4',\n});\n","\n/**\n * A base class for creating callable objects.\n * See [here](https://stackoverflow.com/q/76073890) for more information.\n * \n * @type {new () => {(...args: any[]): any, _call(...args: any[]): any}}\n */\nexport const Callable = /** @type {any} */ (class {\n /**\n * Creates a new instance of the Callable class.\n */\n constructor() {\n /**\n * Creates a closure that delegates to a private method '_call' with the given arguments.\n * @type {any}\n * @param {...any} args Zero or more arguments to pass to the '_call' method.\n * @returns {*} The result of calling the '_call' method.\n */\n let closure = function (...args) {\n return closure._call(...args)\n }\n return Object.setPrototypeOf(closure, new.target.prototype)\n }\n\n /**\n * This method should be implemented in subclasses to provide the\n * functionality of the callable object.\n *\n * @param {any[]} args\n * @throws {Error} If the subclass does not implement the `_call` method.\n */\n _call(...args) {\n throw Error('Must implement _call method in subclass')\n }\n});\n","\n/**\n * @file Utility functions to interact with the Hugging Face Hub (https://huggingface.co/models)\n * \n * @module utils/hub\n */\n\nimport fs from 'fs';\nimport path from 'path';\n\nimport { env } from '../env.js';\nimport { dispatchCallback } from './core.js';\n\n/**\n * @typedef {Object} PretrainedOptions Options for loading a pretrained model. \n * @property {function} [progress_callback=null] If specified, this function will be called during model construction, to provide the user with progress updates.\n * @property {import('../configs.js').PretrainedConfig} [config=null] Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when:\n * - The model is a model provided by the library (loaded with the *model id* string of a pretrained model).\n * - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a configuration JSON file named *config.json* is found in the directory.\n * @property {string} [cache_dir=null] Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.\n * @property {boolean} [local_files_only=false] Whether or not to only look at local files (e.g., not try downloading the model).\n * @property {string} [revision='main'] The specific model version to use. It can be a branch name, a tag name, or a commit id,\n * since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git.\n * NOTE: This setting is ignored for local requests.\n */\n\n/**\n * @typedef {Object} ModelSpecificPretrainedOptions Options for loading a pretrained model.\n * @property {string} [subfolder='onnx'] In case the relevant files are located inside a subfolder of the model repo on huggingface.co,\n * you can specify the folder name here.\n * @property {string} [model_file_name=null] If specified, load the model with this name (excluding the .onnx suffix). Currently only valid for encoder- or decoder-only models.\n * @property {import(\"./devices.js\").DeviceType|Record} [device=null] The device to run the model on. If not specified, the device will be chosen from the environment settings.\n * @property {import(\"./dtypes.js\").DataType|Record} [dtype=null] The data type to use for the model. If not specified, the data type will be chosen from the environment settings.\n * @property {boolean|Record} [use_external_data_format=false] Whether to load the model using the external data format (used for models >= 2GB in size).\n * @property {import('onnxruntime-common').InferenceSession.SessionOptions} [session_options] (Optional) User-specified session options passed to the runtime. If not provided, suitable defaults will be chosen.\n */\n\n/**\n * @typedef {PretrainedOptions & ModelSpecificPretrainedOptions} PretrainedModelOptions Options for loading a pretrained model.\n */\n\n/**\n * Mapping from file extensions to MIME types.\n */\nconst CONTENT_TYPE_MAP = {\n 'txt': 'text/plain',\n 'html': 'text/html',\n 'css': 'text/css',\n 'js': 'text/javascript',\n 'json': 'application/json',\n 'png': 'image/png',\n 'jpg': 'image/jpeg',\n 'jpeg': 'image/jpeg',\n 'gif': 'image/gif',\n}\nclass FileResponse {\n\n /**\n * Creates a new `FileResponse` object.\n * @param {string|URL} filePath\n */\n constructor(filePath) {\n this.filePath = filePath;\n this.headers = new Headers();\n\n this.exists = fs.existsSync(filePath);\n if (this.exists) {\n this.status = 200;\n this.statusText = 'OK';\n\n let stats = fs.statSync(filePath);\n this.headers.set('content-length', stats.size.toString());\n\n this.updateContentType();\n\n let self = this;\n this.body = new ReadableStream({\n start(controller) {\n self.arrayBuffer().then(buffer => {\n controller.enqueue(new Uint8Array(buffer));\n controller.close();\n })\n }\n });\n } else {\n this.status = 404;\n this.statusText = 'Not Found';\n this.body = null;\n }\n }\n\n /**\n * Updates the 'content-type' header property of the response based on the extension of\n * the file specified by the filePath property of the current object.\n * @returns {void}\n */\n updateContentType() {\n // Set content-type header based on file extension\n const extension = this.filePath.toString().split('.').pop().toLowerCase();\n this.headers.set('content-type', CONTENT_TYPE_MAP[extension] ?? 'application/octet-stream');\n }\n\n /**\n * Clone the current FileResponse object.\n * @returns {FileResponse} A new FileResponse object with the same properties as the current object.\n */\n clone() {\n let response = new FileResponse(this.filePath);\n response.exists = this.exists;\n response.status = this.status;\n response.statusText = this.statusText;\n response.headers = new Headers(this.headers);\n return response;\n }\n\n /**\n * Reads the contents of the file specified by the filePath property and returns a Promise that\n * resolves with an ArrayBuffer containing the file's contents.\n * @returns {Promise} A Promise that resolves with an ArrayBuffer containing the file's contents.\n * @throws {Error} If the file cannot be read.\n */\n async arrayBuffer() {\n const data = await fs.promises.readFile(this.filePath);\n return data.buffer;\n }\n\n /**\n * Reads the contents of the file specified by the filePath property and returns a Promise that\n * resolves with a Blob containing the file's contents.\n * @returns {Promise} A Promise that resolves with a Blob containing the file's contents.\n * @throws {Error} If the file cannot be read.\n */\n async blob() {\n const data = await fs.promises.readFile(this.filePath);\n return new Blob([data], { type: this.headers.get('content-type') });\n }\n\n /**\n * Reads the contents of the file specified by the filePath property and returns a Promise that\n * resolves with a string containing the file's contents.\n * @returns {Promise} A Promise that resolves with a string containing the file's contents.\n * @throws {Error} If the file cannot be read.\n */\n async text() {\n const data = await fs.promises.readFile(this.filePath, 'utf8');\n return data;\n }\n\n /**\n * Reads the contents of the file specified by the filePath property and returns a Promise that\n * resolves with a parsed JavaScript object containing the file's contents.\n * \n * @returns {Promise} A Promise that resolves with a parsed JavaScript object containing the file's contents.\n * @throws {Error} If the file cannot be read.\n */\n async json() {\n return JSON.parse(await this.text());\n }\n}\n\n/**\n * Determines whether the given string is a valid URL.\n * @param {string|URL} string The string to test for validity as an URL.\n * @param {string[]} [protocols=null] A list of valid protocols. If specified, the protocol must be in this list.\n * @param {string[]} [validHosts=null] A list of valid hostnames. If specified, the URL's hostname must be in this list.\n * @returns {boolean} True if the string is a valid URL, false otherwise.\n */\nfunction isValidUrl(string, protocols = null, validHosts = null) {\n let url;\n try {\n url = new URL(string);\n } catch (_) {\n return false;\n }\n if (protocols && !protocols.includes(url.protocol)) {\n return false;\n }\n if (validHosts && !validHosts.includes(url.hostname)) {\n return false;\n }\n return true;\n}\n\n/**\n * Helper function to get a file, using either the Fetch API or FileSystem API.\n *\n * @param {URL|string} urlOrPath The URL/path of the file to get.\n * @returns {Promise} A promise that resolves to a FileResponse object (if the file is retrieved using the FileSystem API), or a Response object (if the file is retrieved using the Fetch API).\n */\nexport async function getFile(urlOrPath) {\n\n if (env.useFS && !isValidUrl(urlOrPath, ['http:', 'https:', 'blob:'])) {\n return new FileResponse(urlOrPath);\n\n } else if (typeof process !== 'undefined' && process?.release?.name === 'node') {\n const IS_CI = !!process.env?.TESTING_REMOTELY;\n const version = env.version;\n\n const headers = new Headers();\n headers.set('User-Agent', `transformers.js/${version}; is_ci/${IS_CI};`);\n\n // Check whether we are making a request to the Hugging Face Hub.\n const isHFURL = isValidUrl(urlOrPath, ['http:', 'https:'], ['huggingface.co', 'hf.co']);\n if (isHFURL) {\n // If an access token is present in the environment variables,\n // we add it to the request headers.\n // NOTE: We keep `HF_ACCESS_TOKEN` for backwards compatibility (as a fallback).\n const token = process.env?.HF_TOKEN ?? process.env?.HF_ACCESS_TOKEN;\n if (token) {\n headers.set('Authorization', `Bearer ${token}`);\n }\n }\n return fetch(urlOrPath, { headers });\n } else {\n // Running in a browser-environment, so we use default headers\n // NOTE: We do not allow passing authorization headers in the browser,\n // since this would require exposing the token to the client.\n return fetch(urlOrPath);\n }\n}\n\nconst ERROR_MAPPING = {\n // 4xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses)\n 400: 'Bad request error occurred while trying to load file',\n 401: 'Unauthorized access to file',\n 403: 'Forbidden access to file',\n 404: 'Could not locate file',\n 408: 'Request timeout error occurred while trying to load file',\n\n // 5xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses)\n 500: 'Internal server error error occurred while trying to load file',\n 502: 'Bad gateway error occurred while trying to load file',\n 503: 'Service unavailable error occurred while trying to load file',\n 504: 'Gateway timeout error occurred while trying to load file',\n}\n/**\n * Helper method to handle fatal errors that occur while trying to load a file from the Hugging Face Hub.\n * @param {number} status The HTTP status code of the error.\n * @param {string} remoteURL The URL of the file that could not be loaded.\n * @param {boolean} fatal Whether to raise an error if the file could not be loaded.\n * @returns {null} Returns `null` if `fatal = true`.\n * @throws {Error} If `fatal = false`.\n */\nfunction handleError(status, remoteURL, fatal) {\n if (!fatal) {\n // File was not loaded correctly, but it is optional.\n // TODO in future, cache the response?\n return null;\n }\n\n const message = ERROR_MAPPING[status] ?? `Error (${status}) occurred while trying to load file`;\n throw Error(`${message}: \"${remoteURL}\".`);\n}\n\nclass FileCache {\n /**\n * Instantiate a `FileCache` object.\n * @param {string} path \n */\n constructor(path) {\n this.path = path;\n }\n\n /**\n * Checks whether the given request is in the cache.\n * @param {string} request \n * @returns {Promise}\n */\n async match(request) {\n\n let filePath = path.join(this.path, request);\n let file = new FileResponse(filePath);\n\n if (file.exists) {\n return file;\n } else {\n return undefined;\n }\n }\n\n /**\n * Adds the given response to the cache.\n * @param {string} request \n * @param {Response|FileResponse} response \n * @returns {Promise}\n */\n async put(request, response) {\n const buffer = Buffer.from(await response.arrayBuffer());\n\n let outputPath = path.join(this.path, request);\n\n try {\n await fs.promises.mkdir(path.dirname(outputPath), { recursive: true });\n await fs.promises.writeFile(outputPath, buffer);\n\n } catch (err) {\n console.warn('An error occurred while writing the file to cache:', err)\n }\n }\n\n // TODO add the rest?\n // addAll(requests: RequestInfo[]): Promise;\n // delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise;\n // keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>;\n // match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise;\n // matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>;\n}\n\n/**\n * \n * @param {FileCache|Cache} cache The cache to search\n * @param {string[]} names The names of the item to search for\n * @returns {Promise} The item from the cache, or undefined if not found.\n */\nasync function tryCache(cache, ...names) {\n for (let name of names) {\n try {\n let result = await cache.match(name);\n if (result) return result;\n } catch (e) {\n continue;\n }\n }\n return undefined;\n}\n\n/**\n * \n * Retrieves a file from either a remote URL using the Fetch API or from the local file system using the FileSystem API.\n * If the filesystem is available and `env.useCache = true`, the file will be downloaded and cached.\n * \n * @param {string} path_or_repo_id This can be either:\n * - a string, the *model id* of a model repo on huggingface.co.\n * - a path to a *directory* potentially containing the file.\n * @param {string} filename The name of the file to locate in `path_or_repo`.\n * @param {boolean} [fatal=true] Whether to throw an error if the file is not found.\n * @param {PretrainedOptions} [options] An object containing optional parameters.\n * \n * @throws Will throw an error if the file is not found and `fatal` is true.\n * @returns {Promise} A Promise that resolves with the file content as a buffer.\n */\nexport async function getModelFile(path_or_repo_id, filename, fatal = true, options = {}) {\n\n if (!env.allowLocalModels) {\n // User has disabled local models, so we just make sure other settings are correct.\n\n if (options.local_files_only) {\n throw Error(\"Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).\")\n } else if (!env.allowRemoteModels) {\n throw Error(\"Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.\")\n }\n }\n\n // Initiate file retrieval\n dispatchCallback(options.progress_callback, {\n status: 'initiate',\n name: path_or_repo_id,\n file: filename\n })\n\n // First, check if the a caching backend is available\n // If no caching mechanism available, will download the file every time\n let cache;\n if (!cache && env.useBrowserCache) {\n if (typeof caches === 'undefined') {\n throw Error('Browser cache is not available in this environment.')\n }\n try {\n // In some cases, the browser cache may be visible, but not accessible due to security restrictions.\n // For example, when running an application in an iframe, if a user attempts to load the page in\n // incognito mode, the following error is thrown: `DOMException: Failed to execute 'open' on 'CacheStorage':\n // An attempt was made to break through the security policy of the user agent.`\n // So, instead of crashing, we just ignore the error and continue without using the cache.\n cache = await caches.open('transformers-cache');\n } catch (e) {\n console.warn('An error occurred while opening the browser cache:', e);\n }\n }\n\n if (!cache && env.useFSCache) {\n // TODO throw error if not available\n\n // If `cache_dir` is not specified, use the default cache directory\n cache = new FileCache(options.cache_dir ?? env.cacheDir);\n }\n\n if (!cache && env.useCustomCache) {\n // Allow the user to specify a custom cache system.\n if (!env.customCache) {\n throw Error('`env.useCustomCache=true`, but `env.customCache` is not defined.')\n }\n\n // Check that the required methods are defined:\n if (!env.customCache.match || !env.customCache.put) {\n throw new Error(\n \"`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. \" +\n \"For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache\"\n )\n }\n cache = env.customCache;\n }\n\n const revision = options.revision ?? 'main';\n\n let requestURL = pathJoin(path_or_repo_id, filename);\n let localPath = pathJoin(env.localModelPath, requestURL);\n\n let remoteURL = pathJoin(\n env.remoteHost,\n env.remotePathTemplate\n .replaceAll('{model}', path_or_repo_id)\n .replaceAll('{revision}', encodeURIComponent(revision)),\n filename\n );\n\n // Choose cache key for filesystem cache\n // When using the main revision (default), we use the request URL as the cache key.\n // If a specific revision is requested, we account for this in the cache key.\n let fsCacheKey = revision === 'main' ? requestURL : pathJoin(path_or_repo_id, revision, filename);\n\n /** @type {string} */\n let cacheKey;\n let proposedCacheKey = cache instanceof FileCache ? fsCacheKey : remoteURL;\n\n // Whether to cache the final response in the end.\n let toCacheResponse = false;\n\n /** @type {Response|FileResponse|undefined} */\n let response;\n\n if (cache) {\n // A caching system is available, so we try to get the file from it.\n // 1. We first try to get from cache using the local path. In some environments (like deno),\n // non-URL cache keys are not allowed. In these cases, `response` will be undefined.\n // 2. If no response is found, we try to get from cache using the remote URL or file system cache.\n response = await tryCache(cache, localPath, proposedCacheKey);\n }\n\n const cacheHit = response !== undefined;\n\n if (response === undefined) {\n // Caching not available, or file is not cached, so we perform the request\n\n if (env.allowLocalModels) {\n // Accessing local models is enabled, so we try to get the file locally.\n // If request is a valid HTTP URL, we skip the local file check. Otherwise, we try to get the file locally.\n const isURL = isValidUrl(requestURL, ['http:', 'https:']);\n if (!isURL) {\n try {\n response = await getFile(localPath);\n cacheKey = localPath; // Update the cache key to be the local path\n } catch (e) {\n // Something went wrong while trying to get the file locally.\n // NOTE: error handling is done in the next step (since `response` will be undefined)\n console.warn(`Unable to load from local path \"${localPath}\": \"${e}\"`);\n }\n } else if (options.local_files_only) {\n throw new Error(`\\`local_files_only=true\\`, but attempted to load a remote file from: ${requestURL}.`);\n } else if (!env.allowRemoteModels) {\n throw new Error(`\\`env.allowRemoteModels=false\\`, but attempted to load a remote file from: ${requestURL}.`);\n }\n }\n\n if (response === undefined || response.status === 404) {\n // File not found locally. This means either:\n // - The user has disabled local file access (`env.allowLocalModels=false`)\n // - the path is a valid HTTP url (`response === undefined`)\n // - the path is not a valid HTTP url and the file is not present on the file system or local server (`response.status === 404`)\n\n if (options.local_files_only || !env.allowRemoteModels) {\n // User requested local files only, but the file is not found locally.\n if (fatal) {\n throw Error(`\\`local_files_only=true\\` or \\`env.allowRemoteModels=false\\` and file was not found locally at \"${localPath}\".`);\n } else {\n // File not found, but this file is optional.\n // TODO in future, cache the response?\n return null;\n }\n }\n\n // File not found locally, so we try to download it from the remote server\n response = await getFile(remoteURL);\n\n if (response.status !== 200) {\n return handleError(response.status, remoteURL, fatal);\n }\n\n // Success! We use the proposed cache key from earlier\n cacheKey = proposedCacheKey;\n }\n\n // Only cache the response if:\n toCacheResponse =\n cache // 1. A caching system is available\n && typeof Response !== 'undefined' // 2. `Response` is defined (i.e., we are in a browser-like environment)\n && response instanceof Response // 3. result is a `Response` object (i.e., not a `FileResponse`)\n && response.status === 200 // 4. request was successful (status code 200)\n }\n\n // Start downloading\n dispatchCallback(options.progress_callback, {\n status: 'download',\n name: path_or_repo_id,\n file: filename\n })\n\n const progressInfo = {\n status: 'progress',\n name: path_or_repo_id,\n file: filename\n }\n\n /** @type {Uint8Array} */\n let buffer;\n\n if (!options.progress_callback) {\n // If no progress callback is specified, we can use the `.arrayBuffer()`\n // method to read the response.\n buffer = new Uint8Array(await response.arrayBuffer());\n\n } else if (\n cacheHit // The item is being read from the cache\n &&\n typeof navigator !== 'undefined' && /firefox/i.test(navigator.userAgent) // We are in Firefox\n ) {\n // Due to bug in Firefox, we cannot display progress when loading from cache.\n // Fortunately, since this should be instantaneous, this should not impact users too much.\n buffer = new Uint8Array(await response.arrayBuffer());\n\n // For completeness, we still fire the final progress callback\n dispatchCallback(options.progress_callback, {\n ...progressInfo,\n progress: 100,\n loaded: buffer.length,\n total: buffer.length,\n })\n } else {\n buffer = await readResponse(response, data => {\n dispatchCallback(options.progress_callback, {\n ...progressInfo,\n ...data,\n })\n })\n }\n\n if (\n // Only cache web responses\n // i.e., do not cache FileResponses (prevents duplication)\n toCacheResponse && cacheKey\n &&\n // Check again whether request is in cache. If not, we add the response to the cache\n (await cache.match(cacheKey) === undefined)\n ) {\n // NOTE: We use `new Response(buffer, ...)` instead of `response.clone()` to handle LFS files\n await cache.put(cacheKey, new Response(buffer, {\n headers: response.headers\n }))\n .catch(err => {\n // Do not crash if unable to add to cache (e.g., QuotaExceededError).\n // Rather, log a warning and proceed with execution.\n console.warn(`Unable to add response to browser cache: ${err}.`);\n });\n\n }\n\n dispatchCallback(options.progress_callback, {\n status: 'done',\n name: path_or_repo_id,\n file: filename\n });\n\n return buffer;\n}\n\n/**\n * Fetches a JSON file from a given path and file name.\n *\n * @param {string} modelPath The path to the directory containing the file.\n * @param {string} fileName The name of the file to fetch.\n * @param {boolean} [fatal=true] Whether to throw an error if the file is not found.\n * @param {PretrainedOptions} [options] An object containing optional parameters.\n * @returns {Promise} The JSON data parsed into a JavaScript object.\n * @throws Will throw an error if the file is not found and `fatal` is true.\n */\nexport async function getModelJSON(modelPath, fileName, fatal = true, options = {}) {\n let buffer = await getModelFile(modelPath, fileName, fatal, options);\n if (buffer === null) {\n // Return empty object\n return {}\n }\n\n let decoder = new TextDecoder('utf-8');\n let jsonData = decoder.decode(buffer);\n\n return JSON.parse(jsonData);\n}\n\n/**\n * Read and track progress when reading a Response object\n *\n * @param {any} response The Response object to read\n * @param {function} progress_callback The function to call with progress updates\n * @returns {Promise} A Promise that resolves with the Uint8Array buffer\n */\nasync function readResponse(response, progress_callback) {\n\n const contentLength = response.headers.get('Content-Length');\n if (contentLength === null) {\n console.warn('Unable to determine content-length from response headers. Will expand buffer when needed.')\n }\n let total = parseInt(contentLength ?? '0');\n let buffer = new Uint8Array(total);\n let loaded = 0;\n\n const reader = response.body.getReader();\n async function read() {\n const { done, value } = await reader.read();\n if (done) return;\n\n let newLoaded = loaded + value.length;\n if (newLoaded > total) {\n total = newLoaded;\n\n // Adding the new data will overflow buffer.\n // In this case, we extend the buffer\n let newBuffer = new Uint8Array(total);\n\n // copy contents\n newBuffer.set(buffer);\n\n buffer = newBuffer;\n }\n buffer.set(value, loaded)\n loaded = newLoaded;\n\n const progress = (loaded / total) * 100;\n\n // Call your function here\n progress_callback({\n progress: progress,\n loaded: loaded,\n total: total,\n })\n\n return read();\n }\n\n // Actually read\n await read();\n\n return buffer;\n}\n\n/**\n * Joins multiple parts of a path into a single path, while handling leading and trailing slashes.\n *\n * @param {...string} parts Multiple parts of a path.\n * @returns {string} A string representing the joined path.\n */\nfunction pathJoin(...parts) {\n // https://stackoverflow.com/a/55142565\n parts = parts.map((part, index) => {\n if (index) {\n part = part.replace(new RegExp('^/'), '');\n }\n if (index !== parts.length - 1) {\n part = part.replace(new RegExp('/$'), '');\n }\n return part;\n })\n return parts.join('/');\n}\n","\n/**\n * @file Helper module for image processing. \n * \n * These functions and classes are only used internally, \n * meaning an end-user shouldn't need to access anything here.\n * \n * @module utils/image\n */\n\nimport { getFile } from './hub.js';\nimport { env } from '../env.js';\nimport { Tensor } from './tensor.js';\n\n// Will be empty (or not used) if running in browser or web-worker\nimport sharp from 'sharp';\n\nconst BROWSER_ENV = typeof self !== 'undefined';\nconst WEBWORKER_ENV = BROWSER_ENV && self.constructor.name === 'DedicatedWorkerGlobalScope';\n\nlet createCanvasFunction;\nlet ImageDataClass;\nlet loadImageFunction;\nif (BROWSER_ENV) {\n // Running in browser or web-worker\n createCanvasFunction = (/** @type {number} */ width, /** @type {number} */ height) => {\n if (!self.OffscreenCanvas) {\n throw new Error('OffscreenCanvas not supported by this browser.');\n }\n return new self.OffscreenCanvas(width, height)\n };\n loadImageFunction = self.createImageBitmap;\n ImageDataClass = self.ImageData;\n\n} else if (sharp) {\n // Running in Node.js, electron, or other non-browser environment\n\n loadImageFunction = async (/**@type {sharp.Sharp}*/img) => {\n const metadata = await img.metadata();\n const rawChannels = metadata.channels;\n\n const { data, info } = await img.rotate().raw().toBuffer({ resolveWithObject: true });\n\n const newImage = new RawImage(new Uint8ClampedArray(data), info.width, info.height, info.channels);\n if (rawChannels !== undefined && rawChannels !== info.channels) {\n // Make sure the new image has the same number of channels as the input image.\n // This is necessary for grayscale images.\n newImage.convert(rawChannels);\n }\n return newImage;\n }\n\n} else {\n throw new Error('Unable to load image processing library.');\n}\n\n\n// Defined here: https://github.com/python-pillow/Pillow/blob/a405e8406b83f8bfb8916e93971edc7407b8b1ff/src/libImaging/Imaging.h#L262-L268\nconst RESAMPLING_MAPPING = {\n 0: 'nearest',\n 1: 'lanczos',\n 2: 'bilinear',\n 3: 'bicubic',\n 4: 'box',\n 5: 'hamming',\n}\n\n/**\n * Mapping from file extensions to MIME types.\n */\nconst CONTENT_TYPE_MAP = new Map([\n ['png', 'image/png'],\n ['jpg', 'image/jpeg'],\n ['jpeg', 'image/jpeg'],\n ['gif', 'image/gif'],\n]);\n\nexport class RawImage {\n\n /**\n * Create a new `RawImage` object.\n * @param {Uint8ClampedArray|Uint8Array} data The pixel data.\n * @param {number} width The width of the image.\n * @param {number} height The height of the image.\n * @param {1|2|3|4} channels The number of channels.\n */\n constructor(data, width, height, channels) {\n this.data = data;\n this.width = width;\n this.height = height;\n this.channels = channels;\n }\n\n /** \n * Returns the size of the image (width, height).\n * @returns {[number, number]} The size of the image (width, height).\n */\n get size() {\n return [this.width, this.height];\n }\n\n /**\n * Helper method for reading an image from a variety of input types.\n * @param {RawImage|string|URL} input \n * @returns The image object.\n * \n * **Example:** Read image from a URL.\n * ```javascript\n * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');\n * // RawImage {\n * // \"data\": Uint8ClampedArray [ 25, 25, 25, 19, 19, 19, ... ],\n * // \"width\": 800,\n * // \"height\": 533,\n * // \"channels\": 3\n * // }\n * ```\n */\n static async read(input) {\n if (input instanceof RawImage) {\n return input;\n } else if (typeof input === 'string' || input instanceof URL) {\n return await this.fromURL(input);\n } else {\n throw new Error(`Unsupported input type: ${typeof input}`);\n }\n }\n\n /**\n * Read an image from a canvas.\n * @param {HTMLCanvasElement|OffscreenCanvas} canvas The canvas to read the image from.\n * @returns {RawImage} The image object.\n */\n static fromCanvas(canvas) {\n if (!BROWSER_ENV) {\n throw new Error('fromCanvas() is only supported in browser environments.')\n }\n\n const ctx = canvas.getContext('2d');\n const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;\n return new RawImage(data, canvas.width, canvas.height, 4);\n }\n\n /**\n * Read an image from a URL or file path.\n * @param {string|URL} url The URL or file path to read the image from.\n * @returns {Promise} The image object.\n */\n static async fromURL(url) {\n const response = await getFile(url);\n if (response.status !== 200) {\n throw new Error(`Unable to read image from \"${url}\" (${response.status} ${response.statusText})`);\n }\n const blob = await response.blob();\n return this.fromBlob(blob);\n }\n\n /**\n * Helper method to create a new Image from a blob.\n * @param {Blob} blob The blob to read the image from.\n * @returns {Promise} The image object.\n */\n static async fromBlob(blob) {\n if (BROWSER_ENV) {\n // Running in environment with canvas\n const img = await loadImageFunction(blob);\n\n const ctx = createCanvasFunction(img.width, img.height).getContext('2d');\n\n // Draw image to context\n ctx.drawImage(img, 0, 0);\n\n return new this(ctx.getImageData(0, 0, img.width, img.height).data, img.width, img.height, 4);\n\n } else {\n // Use sharp.js to read (and possible resize) the image.\n const img = sharp(await blob.arrayBuffer());\n\n return await loadImageFunction(img);\n }\n }\n\n /**\n * Helper method to create a new Image from a tensor\n * @param {Tensor} tensor \n */\n static fromTensor(tensor, channel_format = 'CHW') {\n if (tensor.dims.length !== 3) {\n throw new Error(`Tensor should have 3 dimensions, but has ${tensor.dims.length} dimensions.`);\n }\n\n if (channel_format === 'CHW') {\n tensor = tensor.transpose(1, 2, 0);\n } else if (channel_format === 'HWC') {\n // Do nothing\n } else {\n throw new Error(`Unsupported channel format: ${channel_format}`);\n }\n if (!(tensor.data instanceof Uint8ClampedArray || tensor.data instanceof Uint8Array)) {\n throw new Error(`Unsupported tensor type: ${tensor.type}`);\n }\n switch (tensor.dims[2]) {\n case 1:\n case 2:\n case 3:\n case 4:\n return new RawImage(tensor.data, tensor.dims[1], tensor.dims[0], tensor.dims[2]);\n default:\n throw new Error(`Unsupported number of channels: ${tensor.dims[2]}`);\n }\n }\n\n /**\n * Convert the image to grayscale format.\n * @returns {RawImage} `this` to support chaining.\n */\n grayscale() {\n if (this.channels === 1) {\n return this;\n }\n\n const newData = new Uint8ClampedArray(this.width * this.height * 1);\n switch (this.channels) {\n case 3: // rgb to grayscale\n case 4: // rgba to grayscale\n for (let i = 0, offset = 0; i < this.data.length; i += this.channels) {\n const red = this.data[i];\n const green = this.data[i + 1];\n const blue = this.data[i + 2];\n\n newData[offset++] = Math.round(0.2989 * red + 0.5870 * green + 0.1140 * blue);\n }\n break;\n default:\n throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);\n }\n return this._update(newData, this.width, this.height, 1);\n }\n\n /**\n * Convert the image to RGB format.\n * @returns {RawImage} `this` to support chaining.\n */\n rgb() {\n if (this.channels === 3) {\n return this;\n }\n\n const newData = new Uint8ClampedArray(this.width * this.height * 3);\n\n switch (this.channels) {\n case 1: // grayscale to rgb\n for (let i = 0, offset = 0; i < this.data.length; ++i) {\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i];\n }\n break;\n case 4: // rgba to rgb\n for (let i = 0, offset = 0; i < this.data.length; i += 4) {\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i + 1];\n newData[offset++] = this.data[i + 2];\n }\n break;\n default:\n throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);\n }\n return this._update(newData, this.width, this.height, 3);\n\n }\n\n /**\n * Convert the image to RGBA format.\n * @returns {RawImage} `this` to support chaining.\n */\n rgba() {\n if (this.channels === 4) {\n return this;\n }\n\n const newData = new Uint8ClampedArray(this.width * this.height * 4);\n\n switch (this.channels) {\n case 1: // grayscale to rgba\n for (let i = 0, offset = 0; i < this.data.length; ++i) {\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i];\n newData[offset++] = 255;\n }\n break;\n case 3: // rgb to rgba\n for (let i = 0, offset = 0; i < this.data.length; i += 3) {\n newData[offset++] = this.data[i];\n newData[offset++] = this.data[i + 1];\n newData[offset++] = this.data[i + 2];\n newData[offset++] = 255;\n }\n break;\n default:\n throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);\n }\n\n return this._update(newData, this.width, this.height, 4);\n }\n\n /**\n * Resize the image to the given dimensions. This method uses the canvas API to perform the resizing.\n * @param {number} width The width of the new image.\n * @param {number} height The height of the new image.\n * @param {Object} options Additional options for resizing.\n * @param {0|1|2|3|4|5|string} [options.resample] The resampling method to use.\n * @returns {Promise} `this` to support chaining.\n */\n async resize(width, height, {\n resample = 2,\n } = {}) {\n\n // Ensure resample method is a string\n let resampleMethod = RESAMPLING_MAPPING[resample] ?? resample;\n\n if (BROWSER_ENV) {\n // TODO use `resample` in browser environment\n\n // Store number of channels before resizing\n const numChannels = this.channels;\n\n // Create canvas object for this image\n const canvas = this.toCanvas();\n\n // Actually perform resizing using the canvas API\n const ctx = createCanvasFunction(width, height).getContext('2d');\n\n // Draw image to context, resizing in the process\n ctx.drawImage(canvas, 0, 0, width, height);\n\n // Create image from the resized data\n const resizedImage = new RawImage(ctx.getImageData(0, 0, width, height).data, width, height, 4);\n\n // Convert back so that image has the same number of channels as before\n return resizedImage.convert(numChannels);\n\n } else {\n // Create sharp image from raw data, and resize\n let img = this.toSharp();\n\n switch (resampleMethod) {\n case 'box':\n case 'hamming':\n if (resampleMethod === 'box' || resampleMethod === 'hamming') {\n console.warn(`Resampling method ${resampleMethod} is not yet supported. Using bilinear instead.`);\n resampleMethod = 'bilinear';\n }\n\n case 'nearest':\n case 'bilinear':\n case 'bicubic':\n // Perform resizing using affine transform. \n // This matches how the python Pillow library does it.\n img = img.affine([width / this.width, 0, 0, height / this.height], {\n interpolator: resampleMethod\n });\n break;\n\n case 'lanczos':\n // https://github.com/python-pillow/Pillow/discussions/5519\n // https://github.com/lovell/sharp/blob/main/docs/api-resize.md\n img = img.resize({\n width, height,\n fit: 'fill',\n kernel: 'lanczos3', // PIL Lanczos uses a kernel size of 3 \n });\n break;\n\n default:\n throw new Error(`Resampling method ${resampleMethod} is not supported.`);\n }\n\n return await loadImageFunction(img);\n }\n\n }\n\n async pad([left, right, top, bottom]) {\n left = Math.max(left, 0);\n right = Math.max(right, 0);\n top = Math.max(top, 0);\n bottom = Math.max(bottom, 0);\n\n if (left === 0 && right === 0 && top === 0 && bottom === 0) {\n // No padding needed\n return this;\n }\n\n if (BROWSER_ENV) {\n // Store number of channels before padding\n const numChannels = this.channels;\n\n // Create canvas object for this image\n const canvas = this.toCanvas();\n\n const newWidth = this.width + left + right;\n const newHeight = this.height + top + bottom;\n\n // Create a new canvas of the desired size.\n const ctx = createCanvasFunction(newWidth, newHeight).getContext('2d');\n\n // Draw image to context, padding in the process\n ctx.drawImage(canvas,\n 0, 0, this.width, this.height,\n left, top, newWidth, newHeight\n );\n\n // Create image from the padded data\n const paddedImage = new RawImage(\n ctx.getImageData(0, 0, newWidth, newHeight).data,\n newWidth, newHeight, 4);\n\n // Convert back so that image has the same number of channels as before\n return paddedImage.convert(numChannels);\n\n } else {\n const img = this.toSharp().extend({ left, right, top, bottom });\n return await loadImageFunction(img);\n }\n }\n\n async crop([x_min, y_min, x_max, y_max]) {\n // Ensure crop bounds are within the image\n x_min = Math.max(x_min, 0);\n y_min = Math.max(y_min, 0);\n x_max = Math.min(x_max, this.width - 1);\n y_max = Math.min(y_max, this.height - 1);\n\n // Do nothing if the crop is the entire image\n if (x_min === 0 && y_min === 0 && x_max === this.width - 1 && y_max === this.height - 1) {\n return this;\n }\n\n const crop_width = x_max - x_min + 1;\n const crop_height = y_max - y_min + 1;\n\n if (BROWSER_ENV) {\n // Store number of channels before resizing\n const numChannels = this.channels;\n\n // Create canvas object for this image\n const canvas = this.toCanvas();\n\n // Create a new canvas of the desired size. This is needed since if the \n // image is too small, we need to pad it with black pixels.\n const ctx = createCanvasFunction(crop_width, crop_height).getContext('2d');\n\n // Draw image to context, cropping in the process\n ctx.drawImage(canvas,\n x_min, y_min, crop_width, crop_height,\n 0, 0, crop_width, crop_height\n );\n\n // Create image from the resized data\n const resizedImage = new RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4);\n\n // Convert back so that image has the same number of channels as before\n return resizedImage.convert(numChannels);\n\n } else {\n // Create sharp image from raw data\n const img = this.toSharp().extract({\n left: x_min,\n top: y_min,\n width: crop_width,\n height: crop_height,\n });\n\n return await loadImageFunction(img);\n }\n\n }\n\n async center_crop(crop_width, crop_height) {\n // If the image is already the desired size, return it\n if (this.width === crop_width && this.height === crop_height) {\n return this;\n }\n\n // Determine bounds of the image in the new canvas\n const width_offset = (this.width - crop_width) / 2;\n const height_offset = (this.height - crop_height) / 2;\n\n\n if (BROWSER_ENV) {\n // Store number of channels before resizing\n const numChannels = this.channels;\n\n // Create canvas object for this image\n const canvas = this.toCanvas();\n\n // Create a new canvas of the desired size. This is needed since if the \n // image is too small, we need to pad it with black pixels.\n const ctx = createCanvasFunction(crop_width, crop_height).getContext('2d');\n\n let sourceX = 0;\n let sourceY = 0;\n let destX = 0;\n let destY = 0;\n\n if (width_offset >= 0) {\n sourceX = width_offset;\n } else {\n destX = -width_offset;\n }\n\n if (height_offset >= 0) {\n sourceY = height_offset;\n } else {\n destY = -height_offset;\n }\n\n // Draw image to context, cropping in the process\n ctx.drawImage(canvas,\n sourceX, sourceY, crop_width, crop_height,\n destX, destY, crop_width, crop_height\n );\n\n // Create image from the resized data\n const resizedImage = new RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4);\n\n // Convert back so that image has the same number of channels as before\n return resizedImage.convert(numChannels);\n\n } else {\n // Create sharp image from raw data\n let img = this.toSharp();\n\n if (width_offset >= 0 && height_offset >= 0) {\n // Cropped image lies entirely within the original image\n img = img.extract({\n left: Math.floor(width_offset),\n top: Math.floor(height_offset),\n width: crop_width,\n height: crop_height,\n })\n } else if (width_offset <= 0 && height_offset <= 0) {\n // Cropped image lies entirely outside the original image,\n // so we add padding\n const top = Math.floor(-height_offset);\n const left = Math.floor(-width_offset);\n img = img.extend({\n top: top,\n left: left,\n\n // Ensures the resulting image has the desired dimensions\n right: crop_width - this.width - left,\n bottom: crop_height - this.height - top,\n });\n } else {\n // Cropped image lies partially outside the original image.\n // We first pad, then crop.\n\n let y_padding = [0, 0];\n let y_extract = 0;\n if (height_offset < 0) {\n y_padding[0] = Math.floor(-height_offset);\n y_padding[1] = crop_height - this.height - y_padding[0];\n } else {\n y_extract = Math.floor(height_offset);\n }\n\n let x_padding = [0, 0];\n let x_extract = 0;\n if (width_offset < 0) {\n x_padding[0] = Math.floor(-width_offset);\n x_padding[1] = crop_width - this.width - x_padding[0];\n } else {\n x_extract = Math.floor(width_offset);\n }\n\n img = img.extend({\n top: y_padding[0],\n bottom: y_padding[1],\n left: x_padding[0],\n right: x_padding[1],\n }).extract({\n left: x_extract,\n top: y_extract,\n width: crop_width,\n height: crop_height,\n })\n }\n\n return await loadImageFunction(img);\n }\n }\n\n async toBlob(type = 'image/png', quality = 1) {\n if (!BROWSER_ENV) {\n throw new Error('toBlob() is only supported in browser environments.')\n }\n\n const canvas = this.toCanvas();\n return await canvas.convertToBlob({ type, quality });\n }\n\n toTensor(channel_format = 'CHW') {\n let tensor = new Tensor(\n 'uint8',\n new Uint8Array(this.data),\n [this.height, this.width, this.channels]\n );\n\n if (channel_format === 'HWC') {\n // Do nothing\n } else if (channel_format === 'CHW') { // hwc -> chw\n tensor = tensor.permute(2, 0, 1);\n } else {\n throw new Error(`Unsupported channel format: ${channel_format}`);\n }\n return tensor;\n }\n\n toCanvas() {\n if (!BROWSER_ENV) {\n throw new Error('toCanvas() is only supported in browser environments.')\n }\n\n // Clone, and convert data to RGBA before drawing to canvas.\n // This is because the canvas API only supports RGBA\n const cloned = this.clone().rgba();\n\n // Create canvas object for the cloned image\n const clonedCanvas = createCanvasFunction(cloned.width, cloned.height);\n\n // Draw image to context\n const data = new ImageDataClass(cloned.data, cloned.width, cloned.height);\n clonedCanvas.getContext('2d').putImageData(data, 0, 0);\n\n return clonedCanvas;\n }\n\n /**\n * Helper method to update the image data.\n * @param {Uint8ClampedArray} data The new image data.\n * @param {number} width The new width of the image.\n * @param {number} height The new height of the image.\n * @param {1|2|3|4|null} [channels] The new number of channels of the image.\n * @private\n */\n _update(data, width, height, channels = null) {\n this.data = data;\n this.width = width;\n this.height = height;\n if (channels !== null) {\n this.channels = channels;\n }\n return this;\n }\n\n /**\n * Clone the image\n * @returns {RawImage} The cloned image\n */\n clone() {\n return new RawImage(this.data.slice(), this.width, this.height, this.channels);\n }\n\n /**\n * Helper method for converting image to have a certain number of channels\n * @param {number} numChannels The number of channels. Must be 1, 3, or 4.\n * @returns {RawImage} `this` to support chaining.\n */\n convert(numChannels) {\n if (this.channels === numChannels) return this; // Already correct number of channels\n\n switch (numChannels) {\n case 1:\n this.grayscale();\n break;\n case 3:\n this.rgb();\n break;\n case 4:\n this.rgba();\n break;\n default:\n throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`);\n }\n return this;\n }\n\n /**\n * Save the image to the given path.\n * @param {string} path The path to save the image to.\n */\n async save(path) {\n\n if (BROWSER_ENV) {\n if (WEBWORKER_ENV) {\n throw new Error('Unable to save an image from a Web Worker.')\n }\n\n const extension = path.split('.').pop().toLowerCase();\n const mime = CONTENT_TYPE_MAP.get(extension) ?? 'image/png';\n\n // Convert image to Blob\n const blob = await this.toBlob(mime);\n\n // Convert the canvas content to a data URL\n const dataURL = URL.createObjectURL(blob);\n\n // Create an anchor element with the data URL as the href attribute\n const downloadLink = document.createElement('a');\n downloadLink.href = dataURL;\n\n // Set the download attribute to specify the desired filename for the downloaded image\n downloadLink.download = path;\n\n // Trigger the download\n downloadLink.click();\n\n // Clean up: remove the anchor element from the DOM\n downloadLink.remove();\n\n } else if (!env.useFS) {\n throw new Error('Unable to save the image because filesystem is disabled in this environment.')\n\n } else {\n const img = this.toSharp();\n return await img.toFile(path);\n }\n }\n\n toSharp() {\n if (BROWSER_ENV) {\n throw new Error('toSharp() is only supported in server-side environments.')\n }\n\n return sharp(this.data, {\n raw: {\n width: this.width,\n height: this.height,\n channels: this.channels\n }\n });\n }\n}","\n/**\n * @file Helper module for mathematical processing. \n * \n * These functions and classes are only used internally, \n * meaning an end-user shouldn't need to access anything here.\n * \n * @module utils/maths\n */\n\n/**\n * @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array} TypedArray\n * @typedef {BigInt64Array | BigUint64Array} BigTypedArray\n * @typedef {TypedArray | BigTypedArray} AnyTypedArray\n */\n\n/**\n * @param {TypedArray} input\n */\nexport function interpolate_data(input, [in_channels, in_height, in_width], [out_height, out_width], mode = 'bilinear', align_corners = false) {\n // TODO use mode and align_corners\n\n // Output image dimensions\n const x_scale = out_width / in_width;\n const y_scale = out_height / in_height;\n\n // Output image\n // @ts-ignore\n const out_img = new input.constructor(out_height * out_width * in_channels);\n\n // Pre-calculate strides\n const inStride = in_height * in_width;\n const outStride = out_height * out_width;\n\n for (let i = 0; i < out_height; ++i) {\n for (let j = 0; j < out_width; ++j) {\n // Calculate output offset\n const outOffset = i * out_width + j;\n\n // Calculate input pixel coordinates\n const x = (j + 0.5) / x_scale - 0.5;\n const y = (i + 0.5) / y_scale - 0.5;\n\n // Calculate the four nearest input pixels\n // We also check if the input pixel coordinates are within the image bounds\n let x1 = Math.floor(x);\n let y1 = Math.floor(y);\n const x2 = Math.min(x1 + 1, in_width - 1);\n const y2 = Math.min(y1 + 1, in_height - 1);\n\n x1 = Math.max(x1, 0);\n y1 = Math.max(y1, 0);\n\n\n // Calculate the fractional distances between the input pixel and the four nearest pixels\n const s = x - x1;\n const t = y - y1;\n\n // Perform bilinear interpolation\n const w1 = (1 - s) * (1 - t);\n const w2 = s * (1 - t);\n const w3 = (1 - s) * t;\n const w4 = s * t;\n\n // Calculate the four nearest input pixel indices\n const yStride = y1 * in_width;\n const xStride = y2 * in_width;\n const idx1 = yStride + x1;\n const idx2 = yStride + x2;\n const idx3 = xStride + x1;\n const idx4 = xStride + x2;\n\n for (let k = 0; k < in_channels; ++k) {\n // Calculate channel offset\n const cOffset = k * inStride;\n\n out_img[k * outStride + outOffset] =\n w1 * input[cOffset + idx1] +\n w2 * input[cOffset + idx2] +\n w3 * input[cOffset + idx3] +\n w4 * input[cOffset + idx4];\n }\n }\n }\n\n return out_img;\n}\n\n\n/**\n * Helper method to permute a `AnyTypedArray` directly\n * @template {AnyTypedArray} T \n * @param {T} array \n * @param {number[]} dims \n * @param {number[]} axes \n * @returns {[T, number[]]} The permuted array and the new shape.\n */\nexport function permute_data(array, dims, axes) {\n // Calculate the new shape of the permuted array\n // and the stride of the original array\n const shape = new Array(axes.length);\n const stride = new Array(axes.length);\n\n for (let i = axes.length - 1, s = 1; i >= 0; --i) {\n stride[i] = s;\n shape[i] = dims[axes[i]];\n s *= shape[i];\n }\n\n // Precompute inverse mapping of stride\n const invStride = axes.map((_, i) => stride[axes.indexOf(i)]);\n\n // Create the permuted array with the new shape\n // @ts-ignore\n const permutedData = new array.constructor(array.length);\n\n // Permute the original array to the new array\n for (let i = 0; i < array.length; ++i) {\n let newIndex = 0;\n for (let j = dims.length - 1, k = i; j >= 0; --j) {\n newIndex += (k % dims[j]) * invStride[j];\n k = Math.floor(k / dims[j]);\n }\n permutedData[newIndex] = array[i];\n }\n\n return [permutedData, shape];\n}\n\n\n/**\n * Compute the softmax of an array of numbers.\n * @template {TypedArray|number[]} T\n * @param {T} arr The array of numbers to compute the softmax of.\n * @returns {T} The softmax array.\n */\nexport function softmax(arr) {\n // Compute the maximum value in the array\n const maxVal = max(arr)[0];\n\n // Compute the exponentials of the array values\n const exps = arr.map(x => Math.exp(x - maxVal));\n\n // Compute the sum of the exponentials\n // @ts-ignore\n const sumExps = exps.reduce((acc, val) => acc + val, 0);\n\n // Compute the softmax values\n const softmaxArr = exps.map(x => x / sumExps);\n\n return /** @type {T} */(softmaxArr);\n}\n\n/**\n * Calculates the logarithm of the softmax function for the input array.\n * @template {TypedArray|number[]} T\n * @param {T} arr The input array to calculate the log_softmax function for.\n * @returns {T} The resulting log_softmax array.\n */\nexport function log_softmax(arr) {\n // Compute the maximum value in the array\n const maxVal = max(arr)[0];\n\n // Compute the sum of the exponentials\n let sumExps = 0;\n for(let i = 0; i < arr.length; ++i) {\n sumExps += Math.exp(arr[i] - maxVal);\n }\n\n // Compute the log of the sum\n const logSum = Math.log(sumExps);\n\n // Compute the softmax values\n const logSoftmaxArr = arr.map(x => x - maxVal - logSum);\n\n return /** @type {T} */(logSoftmaxArr);\n}\n\n/**\n * Calculates the dot product of two arrays.\n * @param {number[]} arr1 The first array.\n * @param {number[]} arr2 The second array.\n * @returns {number} The dot product of arr1 and arr2.\n */\nexport function dot(arr1, arr2) {\n let result = 0;\n for (let i = 0; i < arr1.length; ++i) {\n result += arr1[i] * arr2[i];\n }\n return result;\n}\n\n/**\n * Computes the cosine similarity between two arrays.\n *\n * @param {number[]} arr1 The first array.\n * @param {number[]} arr2 The second array.\n * @returns {number} The cosine similarity between the two arrays.\n */\nexport function cos_sim(arr1, arr2) {\n // Calculate dot product of the two arrays\n const dotProduct = dot(arr1, arr2);\n\n // Calculate the magnitude of the first array\n const magnitudeA = magnitude(arr1);\n\n // Calculate the magnitude of the second array\n const magnitudeB = magnitude(arr2);\n\n // Calculate the cosine similarity\n const cosineSimilarity = dotProduct / (magnitudeA * magnitudeB);\n\n return cosineSimilarity;\n}\n\n/**\n * Calculates the magnitude of a given array.\n * @param {number[]} arr The array to calculate the magnitude of.\n * @returns {number} The magnitude of the array.\n */\nexport function magnitude(arr) {\n return Math.sqrt(arr.reduce((acc, val) => acc + val * val, 0));\n}\n\n\n/**\n * Returns the value and index of the minimum element in an array.\n * @param {number[]|TypedArray} arr array of numbers.\n * @returns {[number, number]} the value and index of the minimum element, of the form: [valueOfMin, indexOfMin]\n * @throws {Error} If array is empty.\n */\nexport function min(arr) {\n if (arr.length === 0) throw Error('Array must not be empty');\n let min = arr[0];\n let indexOfMin = 0;\n for (let i = 1; i < arr.length; ++i) {\n if (arr[i] < min) {\n min = arr[i];\n indexOfMin = i;\n }\n }\n return [min, indexOfMin];\n}\n\n\n/**\n * Returns the value and index of the maximum element in an array.\n * @param {number[]|AnyTypedArray} arr array of numbers.\n * @returns {[number, number]} the value and index of the maximum element, of the form: [valueOfMax, indexOfMax]\n * @throws {Error} If array is empty.\n */\nexport function max(arr) {\n if (arr.length === 0) throw Error('Array must not be empty');\n let max = arr[0];\n let indexOfMax = 0;\n for (let i = 1; i < arr.length; ++i) {\n if (arr[i] > max) {\n max = arr[i];\n indexOfMax = i;\n }\n }\n return [Number(max), indexOfMax];\n}\n\nfunction isPowerOfTwo(number) {\n // Check if the number is greater than 0 and has only one bit set to 1\n return (number > 0) && ((number & (number - 1)) === 0);\n}\n\n/**\n * Implementation of Radix-4 FFT.\n * \n * P2FFT class provides functionality for performing Fast Fourier Transform on arrays\n * which are a power of two in length.\n * Code adapted from https://www.npmjs.com/package/fft.js\n */\nclass P2FFT {\n /**\n * @param {number} size The size of the input array. Must be a power of two larger than 1.\n * @throws {Error} FFT size must be a power of two larger than 1.\n */\n constructor(size) {\n this.size = size | 0; // convert to a 32-bit signed integer\n if (this.size <= 1 || !isPowerOfTwo(this.size))\n throw new Error('FFT size must be a power of two larger than 1');\n\n this._csize = size << 1;\n\n this.table = new Float64Array(this.size * 2);\n for (let i = 0; i < this.table.length; i += 2) {\n const angle = Math.PI * i / this.size;\n this.table[i] = Math.cos(angle);\n this.table[i + 1] = -Math.sin(angle);\n }\n\n // Find size's power of two\n let power = 0;\n for (let t = 1; this.size > t; t <<= 1)\n ++power;\n\n // Calculate initial step's width:\n // * If we are full radix-4, it is 2x smaller to give inital len=8\n // * Otherwise it is the same as `power` to give len=4\n this._width = power % 2 === 0 ? power - 1 : power;\n\n // Pre-compute bit-reversal patterns\n this._bitrev = new Int32Array(1 << this._width);\n for (let j = 0; j < this._bitrev.length; ++j) {\n this._bitrev[j] = 0;\n for (let shift = 0; shift < this._width; shift += 2) {\n const revShift = this._width - shift - 2;\n this._bitrev[j] |= ((j >>> shift) & 3) << revShift;\n }\n }\n }\n\n /**\n * Create a complex number array with size `2 * size`\n *\n * @returns {Float64Array} A complex number array with size `2 * size`\n */\n createComplexArray() {\n return new Float64Array(this._csize);\n }\n\n /**\n * Converts a complex number representation stored in a Float64Array to an array of real numbers.\n * \n * @param {Float64Array} complex The complex number representation to be converted.\n * @param {number[]} [storage] An optional array to store the result in.\n * @returns {number[]} An array of real numbers representing the input complex number representation.\n */\n fromComplexArray(complex, storage) {\n const res = storage || new Array(complex.length >>> 1);\n for (let i = 0; i < complex.length; i += 2)\n res[i >>> 1] = complex[i];\n return res;\n }\n\n /**\n * Convert a real-valued input array to a complex-valued output array.\n * @param {Float64Array} input The real-valued input array.\n * @param {Float64Array} [storage] Optional buffer to store the output array.\n * @returns {Float64Array} The complex-valued output array.\n */\n toComplexArray(input, storage) {\n const res = storage || this.createComplexArray();\n for (let i = 0; i < res.length; i += 2) {\n res[i] = input[i >>> 1];\n res[i + 1] = 0;\n }\n return res;\n }\n\n /**\n * Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer.\n * \n * @param {Float64Array} out The output buffer to store the result.\n * @param {Float64Array} data The input data to transform.\n * \n * @throws {Error} Input and output buffers must be different.\n * \n * @returns {void}\n */\n transform(out, data) {\n if (out === data)\n throw new Error('Input and output buffers must be different');\n\n this._transform4(out, data, 1 /* DONE */);\n }\n\n /**\n * Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer.\n * The input buffer must contain real values only, while the output buffer will contain complex values. The input and\n * output buffers must be different.\n *\n * @param {Float64Array} out The output buffer.\n * @param {Float64Array} data The input buffer containing real values.\n *\n * @throws {Error} If the input and output buffers are the same.\n */\n realTransform(out, data) {\n if (out === data)\n throw new Error('Input and output buffers must be different');\n\n this._realTransform4(out, data, 1 /* DONE */);\n }\n\n /**\n * Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`.\n * The `out` array must be a different buffer than the `data` array. The `out` array will contain the\n * result of the transformation. The `data` array will not be modified.\n * \n * @param {Float64Array} out The output buffer for the transformed data.\n * @param {Float64Array} data The input data to transform.\n * @throws {Error} If `out` and `data` refer to the same buffer.\n * @returns {void}\n */\n inverseTransform(out, data) {\n if (out === data)\n throw new Error('Input and output buffers must be different');\n\n this._transform4(out, data, -1 /* DONE */);\n for (let i = 0; i < out.length; ++i)\n out[i] /= this.size;\n }\n\n /**\n * Performs a radix-4 implementation of a discrete Fourier transform on a given set of data.\n *\n * @param {Float64Array} out The output buffer for the transformed data.\n * @param {Float64Array} data The input buffer of data to be transformed.\n * @param {number} inv A scaling factor to apply to the transform.\n * @returns {void}\n */\n _transform4(out, data, inv) {\n // radix-4 implementation\n\n const size = this._csize;\n\n // Initial step (permute and transform)\n const width = this._width;\n let step = 1 << width;\n let len = (size / step) << 1;\n\n let outOff;\n let t;\n const bitrev = this._bitrev;\n if (len === 4) {\n for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n const off = bitrev[t];\n this._singleTransform2(data, out, outOff, off, step);\n }\n } else {\n // len === 8\n for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n const off = bitrev[t];\n this._singleTransform4(data, out, outOff, off, step, inv);\n }\n }\n\n // Loop through steps in decreasing order\n const table = this.table;\n for (step >>= 2; step >= 2; step >>= 2) {\n len = (size / step) << 1;\n const quarterLen = len >>> 2;\n\n // Loop through offsets in the data\n for (outOff = 0; outOff < size; outOff += len) {\n // Full case\n const limit = outOff + quarterLen - 1;\n for (let i = outOff, k = 0; i < limit; i += 2, k += step) {\n const A = i;\n const B = A + quarterLen;\n const C = B + quarterLen;\n const D = C + quarterLen;\n\n // Original values\n const Ar = out[A];\n const Ai = out[A + 1];\n const Br = out[B];\n const Bi = out[B + 1];\n const Cr = out[C];\n const Ci = out[C + 1];\n const Dr = out[D];\n const Di = out[D + 1];\n\n const tableBr = table[k];\n const tableBi = inv * table[k + 1];\n const MBr = Br * tableBr - Bi * tableBi;\n const MBi = Br * tableBi + Bi * tableBr;\n\n const tableCr = table[2 * k];\n const tableCi = inv * table[2 * k + 1];\n const MCr = Cr * tableCr - Ci * tableCi;\n const MCi = Cr * tableCi + Ci * tableCr;\n\n const tableDr = table[3 * k];\n const tableDi = inv * table[3 * k + 1];\n const MDr = Dr * tableDr - Di * tableDi;\n const MDi = Dr * tableDi + Di * tableDr;\n\n // Pre-Final values\n const T0r = Ar + MCr;\n const T0i = Ai + MCi;\n const T1r = Ar - MCr;\n const T1i = Ai - MCi;\n const T2r = MBr + MDr;\n const T2i = MBi + MDi;\n const T3r = inv * (MBr - MDr);\n const T3i = inv * (MBi - MDi);\n\n // Final values\n out[A] = T0r + T2r;\n out[A + 1] = T0i + T2i;\n out[B] = T1r + T3i;\n out[B + 1] = T1i - T3r;\n out[C] = T0r - T2r;\n out[C + 1] = T0i - T2i;\n out[D] = T1r - T3i;\n out[D + 1] = T1i + T3r;\n }\n }\n }\n }\n\n /**\n * Performs a radix-2 implementation of a discrete Fourier transform on a given set of data.\n *\n * @param {Float64Array} data The input buffer of data to be transformed.\n * @param {Float64Array} out The output buffer for the transformed data.\n * @param {number} outOff The offset at which to write the output data.\n * @param {number} off The offset at which to begin reading the input data.\n * @param {number} step The step size for indexing the input data.\n * @returns {void}\n */\n _singleTransform2(data, out, outOff, off, step) {\n // radix-2 implementation\n // NOTE: Only called for len=4\n\n const evenR = data[off];\n const evenI = data[off + 1];\n const oddR = data[off + step];\n const oddI = data[off + step + 1];\n\n out[outOff] = evenR + oddR;\n out[outOff + 1] = evenI + oddI;\n out[outOff + 2] = evenR - oddR;\n out[outOff + 3] = evenI - oddI;\n }\n\n /**\n * Performs radix-4 transformation on input data of length 8\n *\n * @param {Float64Array} data Input data array of length 8\n * @param {Float64Array} out Output data array of length 8\n * @param {number} outOff Index of output array to start writing from\n * @param {number} off Index of input array to start reading from\n * @param {number} step Step size between elements in input array\n * @param {number} inv Scaling factor for inverse transform\n * \n * @returns {void}\n */\n _singleTransform4(data, out, outOff, off, step, inv) {\n // radix-4\n // NOTE: Only called for len=8\n const step2 = step * 2;\n const step3 = step * 3;\n\n // Original values\n const Ar = data[off];\n const Ai = data[off + 1];\n const Br = data[off + step];\n const Bi = data[off + step + 1];\n const Cr = data[off + step2];\n const Ci = data[off + step2 + 1];\n const Dr = data[off + step3];\n const Di = data[off + step3 + 1];\n\n // Pre-Final values\n const T0r = Ar + Cr;\n const T0i = Ai + Ci;\n const T1r = Ar - Cr;\n const T1i = Ai - Ci;\n const T2r = Br + Dr;\n const T2i = Bi + Di;\n const T3r = inv * (Br - Dr);\n const T3i = inv * (Bi - Di);\n\n // Final values\n out[outOff] = T0r + T2r;\n out[outOff + 1] = T0i + T2i;\n out[outOff + 2] = T1r + T3i;\n out[outOff + 3] = T1i - T3r;\n out[outOff + 4] = T0r - T2r;\n out[outOff + 5] = T0i - T2i;\n out[outOff + 6] = T1r - T3i;\n out[outOff + 7] = T1i + T3r;\n }\n\n /**\n * Real input radix-4 implementation\n * @param {Float64Array} out Output array for the transformed data\n * @param {Float64Array} data Input array of real data to be transformed\n * @param {number} inv The scale factor used to normalize the inverse transform\n */\n _realTransform4(out, data, inv) {\n // Real input radix-4 implementation\n const size = this._csize;\n\n // Initial step (permute and transform)\n const width = this._width;\n let step = 1 << width;\n let len = (size / step) << 1;\n\n let outOff;\n let t;\n const bitrev = this._bitrev;\n if (len === 4) {\n for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n const off = bitrev[t];\n this._singleRealTransform2(data, out, outOff, off >>> 1, step >>> 1);\n }\n } else {\n // len === 8\n for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) {\n const off = bitrev[t];\n this._singleRealTransform4(data, out, outOff, off >>> 1, step >>> 1, inv);\n }\n }\n\n // Loop through steps in decreasing order\n const table = this.table;\n for (step >>= 2; step >= 2; step >>= 2) {\n len = (size / step) << 1;\n const halfLen = len >>> 1;\n const quarterLen = halfLen >>> 1;\n const hquarterLen = quarterLen >>> 1;\n\n // Loop through offsets in the data\n for (outOff = 0; outOff < size; outOff += len) {\n for (let i = 0, k = 0; i <= hquarterLen; i += 2, k += step) {\n const A = outOff + i;\n const B = A + quarterLen;\n const C = B + quarterLen;\n const D = C + quarterLen;\n\n // Original values\n const Ar = out[A];\n const Ai = out[A + 1];\n const Br = out[B];\n const Bi = out[B + 1];\n const Cr = out[C];\n const Ci = out[C + 1];\n const Dr = out[D];\n const Di = out[D + 1];\n\n // Middle values\n const MAr = Ar;\n const MAi = Ai;\n\n const tableBr = table[k];\n const tableBi = inv * table[k + 1];\n const MBr = Br * tableBr - Bi * tableBi;\n const MBi = Br * tableBi + Bi * tableBr;\n\n const tableCr = table[2 * k];\n const tableCi = inv * table[2 * k + 1];\n const MCr = Cr * tableCr - Ci * tableCi;\n const MCi = Cr * tableCi + Ci * tableCr;\n\n const tableDr = table[3 * k];\n const tableDi = inv * table[3 * k + 1];\n const MDr = Dr * tableDr - Di * tableDi;\n const MDi = Dr * tableDi + Di * tableDr;\n\n // Pre-Final values\n const T0r = MAr + MCr;\n const T0i = MAi + MCi;\n const T1r = MAr - MCr;\n const T1i = MAi - MCi;\n const T2r = MBr + MDr;\n const T2i = MBi + MDi;\n const T3r = inv * (MBr - MDr);\n const T3i = inv * (MBi - MDi);\n\n // Final values\n out[A] = T0r + T2r;\n out[A + 1] = T0i + T2i;\n out[B] = T1r + T3i;\n out[B + 1] = T1i - T3r;\n\n // Output final middle point\n if (i === 0) {\n out[C] = T0r - T2r;\n out[C + 1] = T0i - T2i;\n continue;\n }\n\n // Do not overwrite ourselves\n if (i === hquarterLen)\n continue;\n\n const SA = outOff + quarterLen - i;\n const SB = outOff + halfLen - i;\n\n out[SA] = T1r - inv * T3i;\n out[SA + 1] = -T1i - inv * T3r;\n out[SB] = T0r - inv * T2r;\n out[SB + 1] = -T0i + inv * T2i;\n }\n }\n }\n\n // Complete the spectrum by adding its mirrored negative frequency components.\n const half = size >>> 1;\n for (let i = 2; i < half; i += 2) {\n out[size - i] = out[i];\n out[size - i + 1] = -out[i + 1];\n }\n }\n\n /**\n * Performs a single real input radix-2 transformation on the provided data\n * \n * @param {Float64Array} data The input data array\n * @param {Float64Array} out The output data array\n * @param {number} outOff The output offset\n * @param {number} off The input offset\n * @param {number} step The step\n * \n * @returns {void}\n */\n _singleRealTransform2(data, out, outOff, off, step) {\n // radix-2 implementation\n // NOTE: Only called for len=4\n\n const evenR = data[off];\n const oddR = data[off + step];\n\n out[outOff] = evenR + oddR;\n out[outOff + 1] = 0;\n out[outOff + 2] = evenR - oddR;\n out[outOff + 3] = 0;\n }\n\n /**\n * Computes a single real-valued transform using radix-4 algorithm.\n * This method is only called for len=8.\n *\n * @param {Float64Array} data The input data array.\n * @param {Float64Array} out The output data array.\n * @param {number} outOff The offset into the output array.\n * @param {number} off The offset into the input array.\n * @param {number} step The step size for the input array.\n * @param {number} inv The value of inverse.\n */\n _singleRealTransform4(data, out, outOff, off, step, inv) {\n // radix-4\n // NOTE: Only called for len=8\n const step2 = step * 2;\n const step3 = step * 3;\n\n // Original values\n const Ar = data[off];\n const Br = data[off + step];\n const Cr = data[off + step2];\n const Dr = data[off + step3];\n\n // Pre-Final values\n const T0r = Ar + Cr;\n const T1r = Ar - Cr;\n const T2r = Br + Dr;\n const T3r = inv * (Br - Dr);\n\n // Final values\n out[outOff] = T0r + T2r;\n out[outOff + 1] = 0;\n out[outOff + 2] = T1r;\n out[outOff + 3] = -T3r;\n out[outOff + 4] = T0r - T2r;\n out[outOff + 5] = 0;\n out[outOff + 6] = T1r;\n out[outOff + 7] = T3r;\n }\n}\n\n/**\n * NP2FFT class provides functionality for performing Fast Fourier Transform on arrays\n * which are not a power of two in length. In such cases, the chirp-z transform is used.\n * \n * For more information, see: https://math.stackexchange.com/questions/77118/non-power-of-2-ffts/77156#77156\n */\nclass NP2FFT {\n\n /**\n * Constructs a new NP2FFT object.\n * @param {number} fft_length The length of the FFT\n */\n constructor(fft_length) {\n // Helper variables\n const a = 2 * (fft_length - 1);\n const b = 2 * (2 * fft_length - 1);\n const nextP2 = 2 ** (Math.ceil(Math.log2(b)))\n this.bufferSize = nextP2;\n this._a = a;\n\n // Define buffers\n // Compute chirp for transform\n const chirp = new Float64Array(b);\n const ichirp = new Float64Array(nextP2);\n this._chirpBuffer = new Float64Array(nextP2);\n this._buffer1 = new Float64Array(nextP2);\n this._buffer2 = new Float64Array(nextP2);\n this._outBuffer1 = new Float64Array(nextP2);\n this._outBuffer2 = new Float64Array(nextP2);\n\n // Compute complex exponentiation\n const theta = -2 * Math.PI / fft_length;\n const baseR = Math.cos(theta);\n const baseI = Math.sin(theta);\n\n // Precompute helper for chirp-z transform\n for (let i = 0; i < b >> 1; ++i) {\n // Compute complex power:\n const e = (i + 1 - fft_length) ** 2 / 2.0;\n\n // Compute the modulus and argument of the result\n const result_mod = Math.sqrt(baseR ** 2 + baseI ** 2) ** e;\n const result_arg = e * Math.atan2(baseI, baseR);\n\n // Convert the result back to rectangular form\n // and assign to chirp and ichirp\n const i2 = 2 * i;\n chirp[i2] = result_mod * Math.cos(result_arg);\n chirp[i2 + 1] = result_mod * Math.sin(result_arg);\n\n // conjugate\n ichirp[i2] = chirp[i2];\n ichirp[i2 + 1] = - chirp[i2 + 1];\n }\n this._slicedChirpBuffer = chirp.subarray(a, b);\n\n // create object to perform Fast Fourier Transforms\n // with `nextP2` complex numbers\n this._f = new P2FFT(nextP2 >> 1);\n this._f.transform(this._chirpBuffer, ichirp);\n }\n\n _transform(output, input, real) {\n const ib1 = this._buffer1;\n const ib2 = this._buffer2;\n const ob2 = this._outBuffer1;\n const ob3 = this._outBuffer2;\n const cb = this._chirpBuffer;\n const sb = this._slicedChirpBuffer;\n const a = this._a;\n\n if (real) {\n // Real multiplication\n for (let j = 0; j < sb.length; j += 2) {\n const j2 = j + 1\n const j3 = j >> 1;\n\n const a_real = input[j3];\n ib1[j] = a_real * sb[j];\n ib1[j2] = a_real * sb[j2];\n }\n } else {\n // Complex multiplication\n for (let j = 0; j < sb.length; j += 2) {\n const j2 = j + 1\n ib1[j] = input[j] * sb[j] - input[j2] * sb[j2];\n ib1[j2] = input[j] * sb[j2] + input[j2] * sb[j];\n }\n }\n this._f.transform(ob2, ib1);\n\n for (let j = 0; j < cb.length; j += 2) {\n const j2 = j + 1;\n\n ib2[j] = ob2[j] * cb[j] - ob2[j2] * cb[j2];\n ib2[j2] = ob2[j] * cb[j2] + ob2[j2] * cb[j];\n }\n this._f.inverseTransform(ob3, ib2);\n\n for (let j = 0; j < ob3.length; j += 2) {\n const a_real = ob3[j + a];\n const a_imag = ob3[j + a + 1];\n const b_real = sb[j];\n const b_imag = sb[j + 1];\n\n output[j] = a_real * b_real - a_imag * b_imag;\n output[j + 1] = a_real * b_imag + a_imag * b_real;\n }\n }\n\n transform(output, input) {\n this._transform(output, input, false);\n }\n\n realTransform(output, input) {\n this._transform(output, input, true);\n }\n}\n\nexport class FFT {\n constructor(fft_length) {\n this.fft_length = fft_length;\n this.isPowerOfTwo = isPowerOfTwo(fft_length);\n if (this.isPowerOfTwo) {\n this.fft = new P2FFT(fft_length);\n this.outputBufferSize = 2 * fft_length;\n } else {\n this.fft = new NP2FFT(fft_length);\n this.outputBufferSize = this.fft.bufferSize;\n }\n }\n\n realTransform(out, input) {\n this.fft.realTransform(out, input);\n }\n\n transform(out, input) {\n this.fft.transform(out, input);\n }\n}\n\n\n/**\n * Performs median filter on the provided data. Padding is done by mirroring the data.\n * @param {AnyTypedArray} data The input array\n * @param {number} windowSize The window size\n */\nexport function medianFilter(data, windowSize) {\n\n if (windowSize % 2 === 0 || windowSize <= 0) {\n throw new Error('Window size must be a positive odd number');\n }\n\n // @ts-ignore\n const outputArray = new data.constructor(data.length);\n\n // @ts-ignore\n const buffer = new data.constructor(windowSize); // Reusable array for storing values\n\n const halfWindowSize = Math.floor(windowSize / 2);\n\n for (let i = 0; i < data.length; ++i) {\n let valuesIndex = 0;\n\n for (let j = -halfWindowSize; j <= halfWindowSize; ++j) {\n let index = i + j;\n if (index < 0) {\n index = Math.abs(index);\n } else if (index >= data.length) {\n index = 2 * (data.length - 1) - index;\n }\n\n buffer[valuesIndex++] = data[index];\n }\n\n buffer.sort();\n outputArray[i] = buffer[halfWindowSize];\n }\n\n return outputArray;\n}\n\n/**\n * Helper function to round a number to a given number of decimals\n * @param {number} num The number to round\n * @param {number} decimals The number of decimals\n * @returns {number} The rounded number\n */\nexport function round(num, decimals) {\n const pow = Math.pow(10, decimals);\n return Math.round(num * pow) / pow;\n}\n\n/**\n * Helper function to round a number to the nearest integer, with ties rounded to the nearest even number.\n * Also known as \"bankers' rounding\". This is the default rounding mode in python. For example:\n * 1.5 rounds to 2 and 2.5 rounds to 2.\n * \n * @param {number} x The number to round\n * @returns {number} The rounded number\n */\nexport function bankers_round(x) {\n const r = Math.round(x);\n const br = Math.abs(x) % 1 === 0.5 ? (r % 2 === 0 ? r : r - 1) : r;\n return br;\n}\n\n\n/**\n * Measures similarity between two temporal sequences (e.g., input audio and output tokens\n * to generate token-level timestamps).\n * @param {number[][]} matrix \n * @returns {number[][]}\n */\nexport function dynamic_time_warping(matrix) {\n const output_length = matrix.length;\n const input_length = matrix[0].length;\n\n const outputShape = [output_length + 1, input_length + 1];\n\n const cost = Array.from(\n { length: outputShape[0] },\n () => Array(outputShape[1]).fill(Infinity)\n );\n cost[0][0] = 0;\n\n const trace = Array.from(\n { length: outputShape[0] },\n () => Array(outputShape[1]).fill(-1)\n );\n\n for (let j = 1; j < outputShape[1]; ++j) {\n for (let i = 1; i < outputShape[0]; ++i) {\n const c0 = cost[i - 1][j - 1];\n const c1 = cost[i - 1][j];\n const c2 = cost[i][j - 1];\n\n let c, t;\n if (c0 < c1 && c0 < c2) {\n c = c0;\n t = 0;\n } else if (c1 < c0 && c1 < c2) {\n c = c1;\n t = 1;\n } else {\n c = c2;\n t = 2;\n }\n cost[i][j] = matrix[i - 1][j - 1] + c;\n trace[i][j] = t;\n }\n }\n\n for (let i = 0; i < outputShape[1]; ++i) { // trace[0, :] = 2\n trace[0][i] = 2;\n }\n for (let i = 0; i < outputShape[0]; ++i) { // trace[:, 0] = 1\n trace[i][0] = 1;\n }\n\n // backtrace\n let i = output_length;\n let j = input_length;\n let text_indices = [];\n let time_indices = [];\n while (i > 0 || j > 0) {\n text_indices.push(i - 1);\n time_indices.push(j - 1);\n\n switch (trace[i][j]) {\n case 0:\n --i; --j;\n break;\n case 1:\n --i;\n break;\n case 2:\n --j;\n break;\n default:\n throw new Error(\n `Internal error in dynamic time warping. Unexpected trace[${i}, ${j}]. Please file a bug report.`\n )\n }\n }\n\n text_indices.reverse();\n time_indices.reverse();\n\n return [text_indices, time_indices];\n\n}\n","/**\n * @file Helper module for `Tensor` processing.\n *\n * These functions and classes are only used internally,\n * meaning an end-user shouldn't need to access anything here.\n *\n * @module utils/tensor\n */\n\nimport {\n interpolate_data,\n permute_data\n} from './maths.js';\n\nimport {\n Tensor as ONNXTensor, isONNXTensor,\n} from '../backends/onnx.js';\n\nimport { TensorOpRegistry } from '../ops/registry.js';\n\nconst DataTypeMap = Object.freeze({\n float32: Float32Array,\n float16: Uint16Array,\n float64: Float64Array,\n string: Array, // string[]\n int8: Int8Array,\n uint8: Uint8Array,\n int16: Int16Array,\n uint16: Uint16Array,\n int32: Int32Array,\n uint32: Uint32Array,\n int64: BigInt64Array,\n uint64: BigUint64Array,\n bool: Uint8Array,\n});\n\n/**\n * @typedef {keyof typeof DataTypeMap} DataType\n * @typedef {import('./maths.js').AnyTypedArray | any[]} DataArray\n */\n\n\nexport class Tensor {\n /** @type {number[]} Dimensions of the tensor. */\n get dims() {\n // @ts-ignore\n return this.ort_tensor.dims;\n }\n set dims(value) {\n // FIXME: ONNXTensor declares dims as readonly so one needs to use the constructor() if dims change.\n // @ts-ignore\n this.ort_tensor.dims = value;\n }\n\n /** @type {DataType} Type of the tensor. */\n get type() {\n return this.ort_tensor.type;\n };\n\n /** @type {DataArray} The data stored in the tensor. */\n get data() {\n return this.ort_tensor.data;\n }\n\n /** @type {number} The number of elements in the tensor. */\n get size() {\n return this.ort_tensor.size;\n };\n\n /** @type {string} The location of the tensor data. */\n get location() {\n return this.ort_tensor.location;\n };\n\n ort_tensor;\n\n /**\n * Create a new Tensor or copy an existing Tensor.\n * @param {[DataType, DataArray, number[]]|[ONNXTensor]} args\n */\n constructor(...args) {\n if (isONNXTensor(args[0])) {\n this.ort_tensor = /** @type {ONNXTensor} */ (args[0]);\n } else {\n // Create new tensor\n this.ort_tensor = new ONNXTensor(\n /** @type {DataType} */(args[0]),\n /** @type {Exclude} */(args[1]),\n args[2]\n );\n }\n\n return new Proxy(this, {\n get: (obj, key) => {\n if (typeof key === 'string') {\n let index = Number(key);\n if (Number.isInteger(index)) {\n // key is an integer (i.e., index)\n return obj._getitem(index);\n }\n }\n // @ts-ignore\n return obj[key];\n },\n set: (obj, key, value) => {\n // TODO allow setting of data\n\n // @ts-ignore\n return obj[key] = value;\n }\n });\n }\n\n dispose() {\n this.ort_tensor.dispose();\n // this.ort_tensor = undefined;\n }\n\n /**\n * Returns an iterator object for iterating over the tensor data in row-major order.\n * If the tensor has more than one dimension, the iterator will yield subarrays.\n * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order.\n */\n *[Symbol.iterator]() {\n const [iterLength, ...iterDims] = this.dims;\n\n if (iterDims.length > 0) {\n const iterSize = iterDims.reduce((a, b) => a * b);\n for (let i = 0; i < iterLength; ++i) {\n yield this._subarray(i, iterSize, iterDims);\n }\n } else {\n yield* this.data\n }\n\n }\n\n /**\n * Index into a Tensor object.\n * @param {number} index The index to access.\n * @returns {Tensor} The data at the specified index.\n */\n _getitem(index) {\n const [iterLength, ...iterDims] = this.dims;\n\n index = safeIndex(index, iterLength);\n\n if (iterDims.length > 0) {\n const iterSize = iterDims.reduce((a, b) => a * b);\n return this._subarray(index, iterSize, iterDims);\n } else {\n return new Tensor(this.type, [this.data[index]], iterDims);\n }\n }\n\n /**\n * @param {number|bigint} item The item to search for in the tensor\n * @returns {number} The index of the first occurrence of item in the tensor data.\n */\n indexOf(item) {\n const this_data = this.data;\n for (let index = 0; index < this_data.length; ++index) {\n // Note: == instead of === so we can match Ints with BigInts\n if (this_data[index] == item) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * @param {number} index\n * @param {number} iterSize\n * @param {any} iterDims\n * @returns {Tensor}\n */\n _subarray(index, iterSize, iterDims) {\n const o1 = index * iterSize;\n const o2 = (index + 1) * iterSize;\n\n // We use subarray if available (typed array), otherwise we use slice (normal array)\n const data =\n ('subarray' in this.data)\n ? this.data.subarray(o1, o2)\n : this.data.slice(o1, o2);\n return new Tensor(this.type, data, iterDims);\n }\n\n /**\n * Returns the value of this tensor as a standard JavaScript Number. This only works\n * for tensors with one element. For other cases, see `Tensor.tolist()`.\n * @returns {number|bigint} The value of this tensor as a standard JavaScript Number.\n * @throws {Error} If the tensor has more than one element.\n */\n item() {\n const this_data = this.data;\n if (this_data.length !== 1) {\n throw new Error(`a Tensor with ${this_data.length} elements cannot be converted to Scalar`);\n }\n return this_data[0];\n }\n\n /**\n * Convert tensor data to a n-dimensional JS list\n * @returns {Array}\n */\n tolist() {\n return reshape(this.data, this.dims)\n }\n\n /**\n * Return a new Tensor with the sigmoid function applied to each element.\n * @returns {Tensor} The tensor with the sigmoid function applied.\n */\n sigmoid() {\n return this.clone().sigmoid_();\n }\n\n /**\n * Applies the sigmoid function to the tensor in place.\n * @returns {Tensor} Returns `this`.\n */\n sigmoid_() {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = 1 / (1 + Math.exp(-this_data[i]));\n }\n return this;\n }\n\n /**\n * Return a new Tensor with a callback function applied to each element.\n * @param {Function} callback - The function to apply to each element. It should take three arguments:\n * the current element, its index, and the tensor's data array.\n * @returns {Tensor} A new Tensor with the callback function applied to each element.\n */\n map(callback) {\n return this.clone().map_(callback);\n }\n\n /**\n * Apply a callback function to each element of the tensor in place.\n * @param {Function} callback - The function to apply to each element. It should take three arguments:\n * the current element, its index, and the tensor's data array.\n * @returns {Tensor} Returns `this`.\n */\n map_(callback) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = callback(this_data[i], i, this_data);\n }\n return this;\n }\n\n /**\n * Return a new Tensor with every element multiplied by a constant.\n * @param {number} val The value to multiply by.\n * @returns {Tensor} The new tensor.\n */\n mul(val) {\n return this.clone().mul_(val);\n }\n\n /**\n * Multiply the tensor by a constant in place.\n * @param {number} val The value to multiply by.\n * @returns {Tensor} Returns `this`.\n */\n mul_(val) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] *= val;\n }\n return this;\n }\n\n /**\n * Return a new Tensor with every element divided by a constant.\n * @param {number} val The value to divide by.\n * @returns {Tensor} The new tensor.\n */\n div(val) {\n return this.clone().div_(val);\n }\n\n /**\n * Divide the tensor by a constant in place.\n * @param {number} val The value to divide by.\n * @returns {Tensor} Returns `this`.\n */\n div_(val) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] /= val;\n }\n return this;\n }\n\n /**\n * Return a new Tensor with every element added by a constant.\n * @param {number} val The value to add by.\n * @returns {Tensor} The new tensor.\n */\n add(val) {\n return this.clone().add_(val);\n }\n\n /**\n * Add the tensor by a constant in place.\n * @param {number} val The value to add by.\n * @returns {Tensor} Returns `this`.\n */\n add_(val) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] += val;\n }\n return this;\n }\n\n /**\n * Return a new Tensor with every element subtracted by a constant.\n * @param {number} val The value to subtract by.\n * @returns {Tensor} The new tensor.\n */\n sub(val) {\n return this.clone().sub_(val);\n }\n\n /**\n * Subtract the tensor by a constant in place.\n * @param {number} val The value to subtract by.\n * @returns {Tensor} Returns `this`.\n */\n sub_(val) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] -= val;\n }\n return this;\n }\n\n clone() {\n return new Tensor(this.type, this.data.slice(), this.dims.slice());\n }\n\n slice(...slices) {\n // This allows for slicing with ranges and numbers\n const newTensorDims = [];\n const newOffsets = [];\n\n // slices is an array of numbers or arrays of numbers\n // e.g., slices = [0, [1, 3], null, [0, 3]]\n for (let sliceIndex = 0; sliceIndex < this.dims.length; ++sliceIndex) {\n let slice = slices[sliceIndex];\n\n if (slice === null || slice === undefined) {\n // null or undefined means take the whole dimension\n newOffsets.push([0, this.dims[sliceIndex]]);\n newTensorDims.push(this.dims[sliceIndex]);\n\n } else if (typeof slice === 'number') {\n slice = safeIndex(slice, this.dims[sliceIndex], sliceIndex);\n\n // A number means take a single element\n newOffsets.push([slice, slice + 1]);\n\n } else if (Array.isArray(slice) && slice.length === 2) {\n // An array of length 2 means take a range of elements\n let [start, end] = slice;\n start = start === null\n ? 0\n : safeIndex(start, this.dims[sliceIndex], sliceIndex, false);\n end = end === null\n ? this.dims[sliceIndex]\n : safeIndex(end, this.dims[sliceIndex], sliceIndex, false);\n\n if (start > end) {\n throw new Error(`Invalid slice: ${slice}`);\n }\n\n const offsets = [\n Math.max(start, 0),\n Math.min(end, this.dims[sliceIndex])\n ];\n\n newOffsets.push(offsets);\n newTensorDims.push(offsets[1] - offsets[0]);\n\n } else {\n throw new Error(`Invalid slice: ${slice}`);\n }\n }\n\n const newDims = newOffsets.map(([start, end]) => end - start);\n const newBufferSize = newDims.reduce((a, b) => a * b);\n\n const this_data = this.data;\n // Allocate memory\n // @ts-ignore\n const data = new this_data.constructor(newBufferSize);\n\n // Precompute strides\n const stride = this.stride();\n\n for (let i = 0; i < newBufferSize; ++i) {\n let originalIndex = 0;\n for (let j = newDims.length - 1, num = i; j >= 0; --j) {\n const size = newDims[j];\n originalIndex += ((num % size) + newOffsets[j][0]) * stride[j];\n num = Math.floor(num / size);\n }\n data[i] = this_data[originalIndex];\n }\n return new Tensor(this.type, data, newTensorDims);\n\n }\n\n /**\n * Return a permuted version of this Tensor, according to the provided dimensions.\n * @param {...number} dims Dimensions to permute.\n * @returns {Tensor} The permuted tensor.\n */\n permute(...dims) {\n return permute(this, dims);\n }\n\n // TODO: implement transpose. For now (backwards compatibility), it's just an alias for permute()\n transpose(...dims) {\n return this.permute(...dims);\n }\n\n // TODO add .max() and .min() methods\n\n /**\n * Returns the sum of each row of the input tensor in the given dimension dim.\n *\n * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced.\n * @param {boolean} keepdim Whether the output tensor has `dim` retained or not.\n * @returns The summed tensor\n */\n sum(dim = null, keepdim = false) {\n return this.norm(1, dim, keepdim);\n }\n\n /**\n * Returns the matrix norm or vector norm of a given tensor.\n * @param {number|string} [p='fro'] The order of norm\n * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across.\n * If dim is None, the norm will be calculated across all dimensions of input.\n * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not.\n * @returns {Tensor} The norm of the tensor.\n */\n norm(p = 'fro', dim = null, keepdim = false) {\n if (p === 'fro') {\n // NOTE: Since we only support integer dims, Frobenius norm produces the same result as p=2.\n p = 2;\n } else if (typeof p === 'string') {\n throw Error(`Unsupported norm: ${p}`);\n }\n\n const this_data = this.data;\n\n if (dim === null) {\n // @ts-ignore\n let val = this_data.reduce((a, b) => a + (b ** p), 0) ** (1 / p);\n return new Tensor(this.type, [val], []);\n }\n\n // Negative indexing\n dim = safeIndex(dim, this.dims.length);\n\n // Calculate the shape of the resulting array after summation\n const resultDims = this.dims.slice(); // Copy the original dimensions\n resultDims[dim] = 1; // Remove the specified axis\n\n // Create a new array to store the accumulated values\n // @ts-ignore\n const result = new this_data.constructor(this_data.length / this.dims[dim]);\n\n // Iterate over the data array\n for (let i = 0; i < this_data.length; ++i) {\n\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = this.dims[j];\n if (j !== dim) {\n const index = num % size;\n resultIndex += index * resultMultiplier;\n resultMultiplier *= resultDims[j];\n }\n num = Math.floor(num / size);\n }\n\n // Accumulate the value at the current index\n result[resultIndex] += (this_data[i]) ** p;\n }\n\n if (p !== 1) {\n for (let i = 0; i < result.length; ++i) {\n result[i] = result[i] ** (1 / p);\n }\n }\n\n if (!keepdim) {\n resultDims.splice(dim, 1);\n }\n\n return new Tensor(this.type, result, resultDims);\n }\n\n /**\n * Performs `L_p` normalization of inputs over specified dimension. Operates in place.\n * @param {number} [p=2] The exponent value in the norm formulation\n * @param {number} [dim=1] The dimension to reduce\n * @returns {Tensor} `this` for operation chaining.\n */\n normalize_(p = 2.0, dim = 1) {\n dim = safeIndex(dim, this.dims.length);\n\n const norm = this.norm(p, dim, true);\n\n const this_data = this.data;\n const norm_data = norm.data;\n for (let i = 0; i < this_data.length; ++i) {\n\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = this.dims[j];\n if (j !== dim) {\n const index = num % size;\n resultIndex += index * resultMultiplier;\n resultMultiplier *= this.dims[j];\n }\n num = Math.floor(num / size);\n }\n\n // Divide by normalized value\n this_data[i] /= norm_data[resultIndex];\n }\n\n return this;\n }\n\n /**\n * Performs `L_p` normalization of inputs over specified dimension.\n * @param {number} [p=2] The exponent value in the norm formulation\n * @param {number} [dim=1] The dimension to reduce\n * @returns {Tensor} The normalized tensor.\n */\n normalize(p = 2.0, dim = 1) {\n return this.clone().normalize_(p, dim);\n }\n\n /**\n * Compute and return the stride of this tensor.\n * Stride is the jump necessary to go from one element to the next one in the specified dimension dim.\n * @returns {number[]} The stride of this tensor.\n */\n stride() {\n return dimsToStride(this.dims);\n }\n\n /**\n * Returns a tensor with all specified dimensions of input of size 1 removed.\n *\n * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other.\n * If you would like a copy, use `tensor.clone()` before squeezing.\n *\n * @param {number} [dim=null] If given, the input will be squeezed only in the specified dimensions.\n * @returns {Tensor} The squeezed tensor\n */\n squeeze(dim = null) {\n return new Tensor(\n this.type,\n this.data,\n calc_squeeze_dims(this.dims, dim)\n )\n }\n\n /**\n * In-place version of @see {@link Tensor.squeeze}\n */\n squeeze_(dim = null) {\n this.dims = calc_squeeze_dims(this.dims, dim);\n return this;\n }\n\n /**\n * Returns a new tensor with a dimension of size one inserted at the specified position.\n *\n * NOTE: The returned tensor shares the same underlying data with this tensor.\n *\n * @param {number} dim The index at which to insert the singleton dimension\n * @returns {Tensor} The unsqueezed tensor\n */\n unsqueeze(dim = null) {\n return new Tensor(\n this.type,\n this.data,\n calc_unsqueeze_dims(this.dims, dim)\n );\n }\n\n /**\n * In-place version of @see {@link Tensor.unsqueeze}\n */\n unsqueeze_(dim = null) {\n this.dims = calc_unsqueeze_dims(this.dims, dim);\n return this;\n }\n\n /**\n * In-place version of @see {@link Tensor.flatten}\n */\n flatten_(start_dim = 0, end_dim = -1) {\n // TODO validate inputs\n end_dim = (end_dim + this.dims.length) % this.dims.length;\n\n let dimsToKeepBefore = this.dims.slice(0, start_dim);\n let dimsToFlatten = this.dims.slice(start_dim, end_dim + 1);\n let dimsToKeepAfter = this.dims.slice(end_dim + 1);\n\n this.dims = [...dimsToKeepBefore, dimsToFlatten.reduce((a, b) => a * b, 1), ...dimsToKeepAfter]\n return this;\n }\n\n /**\n * Flattens input by reshaping it into a one-dimensional tensor.\n * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim`\n * and ending with `end_dim` are flattened. The order of elements in input is unchanged.\n * @param {number} start_dim the first dim to flatten\n * @param {number} end_dim the last dim to flatten\n * @returns {Tensor} The flattened tensor.\n */\n flatten(start_dim = 0, end_dim = -1) {\n return this.clone().flatten_(start_dim, end_dim);\n }\n\n /**\n * Returns a new tensor with the same data as the `self` tensor but of a different `shape`.\n * @param {...number} dims the desired size\n * @returns {Tensor} The tensor with the same data but different shape\n */\n view(...dims) {\n // TODO: validate dims\n let inferredIndex = -1;\n for (let i = 0; i < dims.length; ++i) {\n if (dims[i] === -1) {\n if (inferredIndex !== -1) {\n throw new Error(\"Only one dimension can be inferred\");\n }\n inferredIndex = i;\n }\n }\n\n const this_data = this.data;\n if (inferredIndex !== -1) {\n // Some dimension must be inferred\n const productOther = dims.reduce((product, curr, index) => {\n return index !== inferredIndex ? product * curr : product\n }, 1);\n\n dims[inferredIndex] = this_data.length / productOther;\n }\n return new Tensor(this.type, this_data, dims); // NOTE: uses same underlying storage\n }\n\n neg_() {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = -this_data[i];\n }\n return this;\n }\n neg() {\n return this.clone().neg_();\n }\n\n /**\n * In-place version of @see {@link Tensor.clamp}\n */\n clamp_(min, max) {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = Math.min(Math.max(this_data[i], min), max);\n }\n return this;\n }\n\n /**\n * Clamps all elements in input into the range [ min, max ]\n * @param {number} min lower-bound of the range to be clamped to\n * @param {number} max upper-bound of the range to be clamped to\n * @returns {Tensor} the output tensor.\n */\n clamp(min, max) {\n return this.clone().clamp_(min, max);\n }\n\n /**\n * In-place version of @see {@link Tensor.round}\n */\n round_() {\n const this_data = this.data;\n for (let i = 0; i < this_data.length; ++i) {\n this_data[i] = Math.round(this_data[i]);\n }\n return this;\n }\n\n /**\n * Rounds elements of input to the nearest integer.\n * @returns {Tensor} the output tensor.\n */\n round() {\n return this.clone().round_();\n }\n\n mean(dim = null, keepdim = false) {\n return mean(this, dim, keepdim);\n }\n\n /**\n * Performs Tensor dtype conversion.\n * @param {DataType} type The desired data type.\n * @returns {Tensor} The converted tensor.\n */\n to(type) {\n // If the self Tensor already has the correct dtype, then self is returned.\n if (this.type === type) return this;\n\n // Otherwise, the returned tensor is a copy of self with the desired dtype.\n if (!DataTypeMap.hasOwnProperty(type)) {\n throw new Error(`Unsupported type: ${type}`);\n }\n // @ts-ignore\n return new Tensor(type, DataTypeMap[type].from(this.data), this.dims);\n }\n}\n\n/**\n * This creates a nested array of a given type and depth (see examples).\n *\n * @example\n * NestArray; // string[]\n * @example\n * NestArray; // number[][]\n * @example\n * NestArray; // string[][][] etc.\n * @template T\n * @template {number} Depth\n * @template {never[]} [Acc=[]]\n * @typedef {Acc['length'] extends Depth ? T : NestArray} NestArray\n */\n\n/**\n * Reshapes a 1-dimensional array into an n-dimensional array, according to the provided dimensions.\n *\n * @example\n * reshape([10 ], [1 ]); // Type: number[] Value: [10]\n * reshape([1, 2, 3, 4 ], [2, 2 ]); // Type: number[][] Value: [[1, 2], [3, 4]]\n * reshape([1, 2, 3, 4, 5, 6, 7, 8], [2, 2, 2]); // Type: number[][][] Value: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]\n * reshape([1, 2, 3, 4, 5, 6, 7, 8], [4, 2 ]); // Type: number[][] Value: [[1, 2], [3, 4], [5, 6], [7, 8]]\n * @param {T[]|DataArray} data The input array to reshape.\n * @param {DIM} dimensions The target shape/dimensions.\n * @template T\n * @template {[number]|number[]} DIM\n * @returns {NestArray} The reshaped array.\n */\nfunction reshape(data, dimensions) {\n\n const totalElements = data.length;\n const dimensionSize = dimensions.reduce((a, b) => a * b);\n\n if (totalElements !== dimensionSize) {\n throw Error(`cannot reshape array of size ${totalElements} into shape (${dimensions})`);\n }\n\n /** @type {any} */\n let reshapedArray = data;\n\n for (let i = dimensions.length - 1; i >= 0; i--) {\n reshapedArray = reshapedArray.reduce((acc, val) => {\n let lastArray = acc[acc.length - 1];\n\n if (lastArray.length < dimensions[i]) {\n lastArray.push(val);\n } else {\n acc.push([val]);\n }\n\n return acc;\n }, [[]]);\n }\n\n return reshapedArray[0];\n}\n\n/**\n * Permutes a tensor according to the provided axes.\n * @param {any} tensor The input tensor to permute.\n * @param {Array} axes The axes to permute the tensor along.\n * @returns {Tensor} The permuted tensor.\n */\nexport function permute(tensor, axes) {\n const [permutedData, shape] = permute_data(tensor.data, tensor.dims, axes);\n return new Tensor(tensor.type, permutedData, shape);\n}\n\n\n/**\n * Interpolates an Tensor to the given size.\n * @param {Tensor} input The input tensor to interpolate. Data must be channel-first (i.e., [c, h, w])\n * @param {number[]} size The output size of the image\n * @param {string} mode The interpolation mode\n * @param {boolean} align_corners Whether to align corners.\n * @returns {Tensor} The interpolated tensor.\n */\nexport function interpolate(input, [out_height, out_width], mode = 'bilinear', align_corners = false) {\n\n // Input image dimensions\n const in_channels = input.dims.at(-3) ?? 1;\n const in_height = input.dims.at(-2);\n const in_width = input.dims.at(-1);\n\n let output = interpolate_data(\n /** @type {import('./maths.js').TypedArray}*/(input.data),\n [in_channels, in_height, in_width],\n [out_height, out_width],\n mode,\n align_corners\n );\n return new Tensor(input.type, output, [in_channels, out_height, out_width]);\n}\n\n\n/**\n * Down/up samples the input.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html.\n * @param {Tensor} input the input tensor\n * @param {Object} options the options for the interpolation\n * @param {[number, number]|[number, number, number]|[number, number, number, number]} [options.size=null] output spatial size.\n * @param {\"bilinear\"|\"bicubic\"} [options.mode='bilinear'] algorithm used for upsampling\n * @returns {Promise} The interpolated tensor.\n */\nexport async function interpolate_4d(input, {\n size = null,\n mode = 'bilinear',\n} = {}) {\n\n // Error checking\n if (input.dims.length !== 4) {\n throw new Error('`interpolate_4d` currently only supports 4D input.');\n }\n if (!size) {\n // TODO: support scale_factor\n throw new Error('`interpolate_4d` requires a `size` argument.');\n }\n\n // Fill in missing dimensions\n let targetDims;\n if (size.length === 2) {\n targetDims = [...input.dims.slice(0, 2), ...size];\n } else if (size.length === 3) {\n targetDims = [input.dims[0], ...size];\n } else if (size.length === 4) {\n targetDims = size;\n } else {\n throw new Error('`size` must be of length 2, 3, or 4.');\n }\n\n let op;\n if (mode === 'bilinear') {\n op = await TensorOpRegistry.bilinear_interpolate_4d;\n } else if (mode === 'bicubic') {\n op = await TensorOpRegistry.bicubic_interpolate_4d;\n } else {\n throw new Error(`Unsupported mode: ${mode}`);\n }\n\n const sizeTensor = new Tensor('int64', new BigInt64Array(targetDims.map(BigInt)), [targetDims.length]);\n return await op({ x: input, s: sizeTensor });\n}\n\n/**\n * Matrix product of two tensors.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.matmul.html\n * @param {Tensor} a the first tensor to be multiplied\n * @param {Tensor} b the second tensor to be multiplied\n * @returns {Promise} The matrix product of the two tensors.\n */\nexport async function matmul(a, b) {\n const op = await TensorOpRegistry.matmul;\n return await op({ a, b });\n}\n\n/**\n * Computes the one dimensional Fourier transform of real-valued input.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.fft.rfft.html\n * @param {Tensor} x the real input tensor\n * @param {Tensor} a The dimension along which to take the one dimensional real FFT.\n * @returns {Promise} the output tensor.\n */\nexport async function rfft(x, a) {\n const op = await TensorOpRegistry.rfft;\n return await op({ x, a });\n}\n\n\n/**\n * Returns the k largest elements of the given input tensor.\n * Inspired by https://pytorch.org/docs/stable/generated/torch.topk.html\n * @param {Tensor} x the input tensor\n * @param {number} k the k in \"top-k\"\n * @returns {Promise<[Tensor, Tensor]>} the output tuple of (Tensor, LongTensor) of top-k elements and their indices.\n */\nexport async function topk(x, k) {\n const op = await TensorOpRegistry.top_k;\n\n if (k === null) {\n k = x.dims.at(-1);\n } else {\n k = Math.min(k, x.dims.at(-1));\n }\n return await op({\n x,\n k: new Tensor(\n 'int64',\n [BigInt(k)],\n [1]\n )\n });\n}\n\n/**\n * Perform mean pooling of the last hidden state followed by a normalization step.\n * @param {Tensor} last_hidden_state Tensor of shape [batchSize, seqLength, embedDim]\n * @param {Tensor} attention_mask Tensor of shape [batchSize, seqLength]\n * @returns {Tensor} Returns a new Tensor of shape [batchSize, embedDim].\n */\nexport function mean_pooling(last_hidden_state, attention_mask) {\n // last_hidden_state: [batchSize, seqLength, embedDim]\n // attention_mask: [batchSize, seqLength]\n const lastHiddenStateData = last_hidden_state.data;\n const attentionMaskData = attention_mask.data;\n\n const shape = [last_hidden_state.dims[0], last_hidden_state.dims[2]];\n\n // @ts-ignore\n const returnedData = new lastHiddenStateData.constructor(shape[0] * shape[1]);\n const [batchSize, seqLength, embedDim] = last_hidden_state.dims;\n\n let outIndex = 0;\n for (let i = 0; i < batchSize; ++i) {\n const offset = i * embedDim * seqLength;\n\n for (let k = 0; k < embedDim; ++k) {\n let sum = 0;\n let count = 0;\n\n const attnMaskOffset = i * seqLength;\n const offset2 = offset + k;\n // Pool over all words in sequence\n for (let j = 0; j < seqLength; ++j) {\n // index into attention mask\n const attn = Number(attentionMaskData[attnMaskOffset + j]);\n\n count += attn;\n sum += lastHiddenStateData[offset2 + j * embedDim] * attn;\n }\n\n const avg = sum / count;\n returnedData[outIndex++] = avg;\n }\n }\n\n return new Tensor(\n last_hidden_state.type,\n returnedData,\n shape\n )\n}\n\n/**\n * Apply Layer Normalization for last certain number of dimensions.\n * @param {Tensor} input The input tensor\n * @param {number[]} normalized_shape input shape from an expected input of size\n * @param {Object} options The options for the layer normalization\n * @param {number} [options.eps=1e-5] A value added to the denominator for numerical stability.\n * @returns {Tensor} The normalized tensor.\n */\nexport function layer_norm(input, normalized_shape, {\n eps = 1e-5,\n} = {}) {\n if (input.dims.length !== 2) {\n throw new Error('`layer_norm` currently only supports 2D input.');\n }\n\n const [batchSize, featureDim] = input.dims;\n\n if (normalized_shape.length !== 1 && normalized_shape[0] !== featureDim) {\n throw new Error('`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.');\n }\n\n const [std, mean] = std_mean(input, 1, 0, true);\n const stdData = /** @type {Float32Array} */(std.data);\n const meanData = /** @type {Float32Array} */(mean.data);\n\n const inputData = /** @type {Float32Array} */(input.data);\n\n // @ts-ignore\n const returnedData = new inputData.constructor(inputData.length);\n\n for (let i = 0; i < batchSize; ++i) {\n const offset = i * featureDim;\n for (let j = 0; j < featureDim; ++j) {\n const offset2 = offset + j;\n returnedData[offset2] = (inputData[offset2] - meanData[i]) / (stdData[i] + eps);\n }\n }\n return new Tensor(input.type, returnedData, input.dims);\n}\n\n/**\n * Helper function to calculate new dimensions when performing a squeeze operation.\n * @param {number[]} dims The dimensions of the tensor.\n * @param {number|number[]|null} dim The dimension(s) to squeeze.\n * @returns {number[]} The new dimensions.\n * @private\n */\nfunction calc_squeeze_dims(dims, dim) {\n dims = dims.slice();\n if (dim === null) {\n dims = dims.filter((d) => d !== 1);\n } else if (typeof dim === 'number') {\n if (dims[dim] === 1) {\n dims.splice(dim, 1);\n }\n } else if (Array.isArray(dim)) {\n dims = dims.filter((x, i) => {\n return x !== 1 || !dim.includes(i);\n });\n }\n return dims;\n}\n\n/**\n * Helper function to calculate new dimensions when performing an unsqueeze operation.\n * @param {number[]} dims The dimensions of the tensor.\n * @param {number} dim The dimension to unsqueeze.\n * @returns {number[]} The new dimensions.\n * @private\n */\nfunction calc_unsqueeze_dims(dims, dim) {\n // Dimension out of range (e.g., \"expected to be in range of [-4, 3], but got 4\")\n // + 1 since we allow inserting at the end (i.e. dim = -1)\n dim = safeIndex(dim, dims.length + 1);\n dims = dims.slice();\n // Insert 1 into specified dimension\n dims.splice(dim, 0, 1);\n return dims;\n}\n\n/**\n * Safely calculate the index for an array of a given size, allowing negative indexing.\n * @param {number} index The index that will be used.\n * @param {number} size The size of the array.\n * @param {number} [dimension=null] The dimension that the index is for (optional).\n * @returns {number} The index, guaranteed to be non-negative and less than `arrayLength`.\n *\n * @throws {Error} If the index is out of range.\n * @private\n */\nfunction safeIndex(index, size, dimension = null, boundsCheck = true) {\n if (boundsCheck && (index < -size || index >= size)) {\n throw new Error(`IndexError: index ${index} is out of bounds for dimension${dimension === null ? '' : ' ' + dimension} with size ${size}`);\n }\n\n if (index < 0) {\n // Negative indexing, ensuring positive index\n index = ((index % size) + size) % size;\n }\n return index;\n}\n\n/**\n * Concatenates an array of tensors along a specified dimension.\n * @param {Tensor[]} tensors The array of tensors to concatenate.\n * @param {number} dim The dimension to concatenate along.\n * @returns {Tensor} The concatenated tensor.\n */\nexport function cat(tensors, dim = 0) {\n dim = safeIndex(dim, tensors[0].dims.length);\n\n // TODO do validation of shapes\n\n const resultDims = tensors[0].dims.slice();\n resultDims[dim] = tensors.reduce((a, b) => a + b.dims[dim], 0);\n\n // Create a new array to store the accumulated values\n const resultSize = resultDims.reduce((a, b) => a * b, 1);\n // @ts-ignore\n const result = new tensors[0].data.constructor(resultSize);\n\n // Create output tensor of same type as first\n const resultType = tensors[0].type;\n\n if (dim === 0) {\n // Handle special case for performance reasons\n\n let offset = 0;\n for (const tensor of tensors) {\n const tensorData = tensor.data;\n result.set(tensorData, offset);\n offset += tensorData.length;\n }\n\n } else {\n\n let currentDim = 0;\n\n for (let t = 0; t < tensors.length; ++t) {\n const { data, dims } = tensors[t];\n\n // Iterate over the data array\n for (let i = 0; i < data.length; ++i) {\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = dims[j];\n let index = num % size;\n if (j === dim) {\n index += currentDim;\n }\n resultIndex += index * resultMultiplier;\n resultMultiplier *= resultDims[j];\n num = Math.floor(num / size);\n }\n // Accumulate the value at the current index\n result[resultIndex] = data[i];\n }\n\n currentDim += dims[dim];\n }\n }\n return new Tensor(resultType, result, resultDims);\n}\n\n/**\n * Stack an array of tensors along a specified dimension.\n * @param {Tensor[]} tensors The array of tensors to stack.\n * @param {number} dim The dimension to stack along.\n * @returns {Tensor} The stacked tensor.\n */\nexport function stack(tensors, dim = 0) {\n // TODO do validation of shapes\n // NOTE: stack expects each tensor to be equal size\n return cat(tensors.map(t => t.unsqueeze(dim)), dim);\n}\n\n\n/**\n * Calculates the standard deviation and mean over the dimensions specified by dim. dim can be a single dimension or `null` to reduce over all dimensions.\n * @param {Tensor} input the input tenso\n * @param {number|null} dim the dimension to reduce. If None, all dimensions are reduced.\n * @param {number} correction difference between the sample size and sample degrees of freedom. Defaults to Bessel's correction, correction=1.\n * @param {boolean} keepdim whether the output tensor has dim retained or not.\n * @returns {Tensor[]} A tuple of (std, mean) tensors.\n */\nexport function std_mean(input, dim = null, correction = 1, keepdim = false) {\n const inputData = /** @type {Float32Array} */(input.data);\n const inputDims = input.dims;\n\n if (dim === null) {\n // None to reduce over all dimensions.\n const sum = inputData.reduce((a, b) => a + b, 0);\n const mean = sum / inputData.length;\n const std = Math.sqrt(inputData.reduce((a, b) => a + (b - mean) ** 2, 0) / (inputData.length - correction));\n\n const meanTensor = new Tensor(input.type, [mean], [/* scalar */]);\n const stdTensor = new Tensor(input.type, [std], [/* scalar */]);\n\n return [stdTensor, meanTensor];\n }\n\n // Negative indexing\n dim = safeIndex(dim, inputDims.length);\n\n const meanTensor = mean(input, dim, keepdim);\n const meanTensorData = meanTensor.data;\n\n // Calculate the shape of the resulting array after summation\n const resultDims = inputDims.slice(); // Copy the original dimensions\n resultDims[dim] = 1; // Remove the specified axis\n\n // Create a new array to store the accumulated values\n // @ts-ignore\n const result = new inputData.constructor(inputData.length / inputDims[dim]);\n\n // Iterate over the data array\n for (let i = 0; i < inputData.length; ++i) {\n\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = inputDims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = inputDims[j];\n if (j !== dim) {\n const index = num % size;\n resultIndex += index * resultMultiplier;\n resultMultiplier *= resultDims[j];\n }\n num = Math.floor(num / size);\n }\n\n // Accumulate the value at the current index\n result[resultIndex] += (inputData[i] - meanTensorData[resultIndex]) ** 2;\n }\n\n for (let i = 0; i < result.length; ++i) {\n result[i] = Math.sqrt(result[i] / (inputDims[dim] - correction));\n }\n\n if (!keepdim) {\n resultDims.splice(dim, 1);\n }\n\n const stdTensor = new Tensor(input.type, result, resultDims);\n\n return [stdTensor, meanTensor];\n}\n\n\n/**\n * Returns the mean value of each row of the input tensor in the given dimension dim.\n * @param {Tensor} input the input tensor.\n * @param {number|null} dim the dimension to reduce.\n * @param {boolean} keepdim whether the output tensor has dim retained or not.\n * @returns {Tensor} A new tensor with means taken along the specified dimension.\n */\nexport function mean(input, dim = null, keepdim = false) {\n const inputData = /** @type {Float32Array} */(input.data);\n\n if (dim === null) {\n // None to reduce over all dimensions.\n // @ts-ignore\n const val = inputData.reduce((a, b) => a + b, 0);\n return new Tensor(input.type, [val / inputData.length], [/* scalar */]);\n }\n const inputDims = input.dims;\n\n // Negative indexing\n dim = safeIndex(dim, inputDims.length);\n\n // Calculate the shape of the resulting array after summation\n const resultDims = inputDims.slice(); // Copy the original dimensions\n resultDims[dim] = 1; // Remove the specified axis\n\n // Create a new array to store the accumulated values\n // @ts-ignore\n const result = new inputData.constructor(inputData.length / inputDims[dim]);\n\n // Iterate over the data array\n for (let i = 0; i < inputData.length; ++i) {\n\n // Calculate the index in the resulting array\n let resultIndex = 0;\n\n for (let j = inputDims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) {\n const size = inputDims[j];\n if (j !== dim) {\n const index = num % size;\n resultIndex += index * resultMultiplier;\n resultMultiplier *= resultDims[j];\n }\n num = Math.floor(num / size);\n }\n\n // Accumulate the value at the current index\n result[resultIndex] += inputData[i];\n }\n\n if (inputDims[dim] !== 1) {\n for (let i = 0; i < result.length; ++i) {\n result[i] = result[i] / inputDims[dim];\n }\n }\n\n if (!keepdim) {\n resultDims.splice(dim, 1);\n }\n\n return new Tensor(input.type, result, resultDims);\n}\n\n\nfunction dimsToStride(dims) {\n const stride = new Array(dims.length);\n for (let i = dims.length - 1, s2 = 1; i >= 0; --i) {\n stride[i] = s2;\n s2 *= dims[i];\n }\n return stride;\n}\n\nfunction fullHelper(size, fill_value, dtype, cls) {\n const numElements = size.reduce((a, b) => a * b, 1);\n return new Tensor(\n dtype,\n new cls(numElements).fill(fill_value),\n size\n )\n}\n\n/**\n * Creates a tensor of size size filled with fill_value. The tensor's dtype is inferred from fill_value.\n * @param {number[]} size A sequence of integers defining the shape of the output tensor.\n * @param {number|bigint} fill_value The value to fill the output tensor with.\n * @returns {Tensor} The filled tensor.\n */\nexport function full(size, fill_value) {\n let dtype;\n let typedArrayCls;\n if (typeof fill_value === 'number') {\n dtype = 'float32';\n typedArrayCls = Float32Array;\n } else if (typeof fill_value === 'bigint') {\n dtype = 'int64';\n typedArrayCls = BigInt64Array;\n } else {\n // TODO: support other dtypes\n throw new Error(`Unsupported data type: ${typeof fill_value}`);\n }\n return fullHelper(size, fill_value, dtype, typedArrayCls);\n}\n\nexport function full_like(tensor, fill_value) {\n return full(tensor.dims, fill_value);\n}\n\n/**\n * Returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size.\n * @param {number[]} size A sequence of integers defining the shape of the output tensor.\n * @returns {Tensor} The ones tensor.\n */\nexport function ones(size) {\n return fullHelper(size, 1n, 'int64', BigInt64Array);\n}\n\n/**\n * Returns a tensor filled with the scalar value 1, with the same size as input.\n * @param {Tensor} tensor The size of input will determine size of the output tensor.\n * @returns {Tensor} The ones tensor.\n */\nexport function ones_like(tensor) {\n return ones(tensor.dims);\n}\n\n/**\n * Returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size.\n * @param {number[]} size A sequence of integers defining the shape of the output tensor.\n * @returns {Tensor} The zeros tensor.\n */\nexport function zeros(size) {\n return fullHelper(size, 0n, 'int64', BigInt64Array);\n}\n\n/**\n * Returns a tensor filled with the scalar value 0, with the same size as input.\n * @param {Tensor} tensor The size of input will determine size of the output tensor.\n * @returns {Tensor} The zeros tensor.\n */\nexport function zeros_like(tensor) {\n return zeros(tensor.dims);\n}\n\n/**\n * Quantizes the embeddings tensor to binary or unsigned binary precision.\n * @param {Tensor} tensor The tensor to quantize.\n * @param {'binary'|'ubinary'} precision The precision to use for quantization.\n * @returns {Tensor} The quantized tensor.\n */\nexport function quantize_embeddings(tensor, precision) {\n if (tensor.dims.length !== 2) {\n throw new Error(\"The tensor must have 2 dimensions\");\n }\n if (tensor.dims.at(-1) % 8 !== 0) {\n throw new Error(\"The last dimension of the tensor must be a multiple of 8\");\n }\n if (!['binary', 'ubinary'].includes(precision)) {\n throw new Error(\"The precision must be either 'binary' or 'ubinary'\");\n }\n\n const signed = precision === 'binary';\n const dtype = signed ? 'int8' : 'uint8';\n\n // Create a typed array to store the packed bits\n const cls = signed ? Int8Array : Uint8Array;\n const inputData = tensor.data;\n const outputData = new cls(inputData.length / 8);\n\n // Iterate over each number in the array\n for (let i = 0; i < inputData.length; ++i) {\n // Determine if the number is greater than 0\n const bit = inputData[i] > 0 ? 1 : 0;\n\n // Calculate the index in the typed array and the position within the byte\n const arrayIndex = Math.floor(i / 8);\n const bitPosition = i % 8;\n\n // Pack the bit into the typed array\n outputData[arrayIndex] |= bit << (7 - bitPosition);\n if (signed && bitPosition === 0) {\n outputData[arrayIndex] -= 128;\n }\n };\n\n return new Tensor(dtype, outputData, [tensor.dims[0], tensor.dims[1] / 8]);\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","var scriptUrl;\nif (typeof import.meta.url === \"string\") scriptUrl = import.meta.url\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl;","__webpack_require__.b = new URL(\"./\", import.meta.url);\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t\"transformers.min\": 0\n};\n\n// no install chunk\n\n// no chunk on demand loading\n\n// no prefetching\n\n// no preloaded\n\n// no external install chunk\n\n// no on chunks loaded"],"names":["leafPrototypes","getProto","TOKEN_TYPES","Object","freeze","Text","NumericLiteral","BooleanLiteral","StringLiteral","Identifier","Equals","OpenParen","CloseParen","OpenStatement","CloseStatement","OpenExpression","CloseExpression","OpenSquareBracket","CloseSquareBracket","OpenCurlyBracket","CloseCurlyBracket","Comma","Dot","Colon","Pipe","CallOperator","AdditiveBinaryOperator","MultiplicativeBinaryOperator","ComparisonBinaryOperator","UnaryOperator","Set","If","For","In","Is","NotIn","Else","EndIf","ElseIf","EndFor","And","Or","Not","Macro","EndMacro","KEYWORDS","set","for","in","is","if","else","endif","elif","endfor","and","or","not","macro","endmacro","true","false","True","False","Token","constructor","value","type","this","isWord","char","test","isInteger","ORDERED_MAPPING_TABLE","ESCAPE_CHARACTERS","Map","tokenize","source","options","tokens","src","template","endsWith","slice","replace","lstrip_blocks","trim_blocks","preprocess","cursorPosition","consumeWhile","predicate","str","length","SyntaxError","escaped","unescaped","get","main","lastTokenType","at","text","push","char2","lastTokenType2","num","token","word","hasOwn","pop","c","Statement","Program","body","super","alternate","loopvar","iterable","defaultBlock","SetStatement","assignee","name","args","Expression","MemberExpression","object","property","computed","CallExpression","callee","Literal","ArrayLiteral","TupleLiteral","ObjectLiteral","BinaryExpression","operator","left","right","FilterExpression","operand","filter","SelectExpression","TestExpression","negate","UnaryExpression","argument","SliceExpression","start","stop","step","KeywordArgumentExpression","key","parse","program","current","expect","error","prev","Error","parseAny","result","parseSetStatement","parseIfStatement","parsePrimaryExpression","parseArgs","parseMacroStatement","loopVariable","parseExpressionSequence","parseExpression","alternative","parseForStatement","parseJinjaStatement","parseJinjaExpression","types","some","i","every","primary","fn","expressions","isTuple","a","parseLogicalOrExpression","b","parseIfExpression","parseLogicalAndExpression","parseLogicalNegationExpression","arg","parseAdditiveExpression","parseComparisonExpression","parseMultiplicativeExpression","parseCallMemberExpression","member","parseMemberExpressionArgumentsList","parseMemberExpression","parseCallExpression","callExpression","parseArgumentsList","slices","isSlice","parseTestExpression","parseFilterExpression","toString","Number","toLowerCase","expression","values","range","array","direction","Math","sign","max","min","titleCase","toUpperCase","RuntimeValue","builtins","__bool__","BooleanValue","NumericValue","StringValue","FunctionValue","trim","ObjectValue","size","defaultValue","NullValue","ArrayValue","Array","from","entries","map","KeywordArgumentsValue","TupleValue","UndefinedValue","Environment","parent","variables","tests","declareVariable","convertToRuntimeValues","has","setVariable","resolve","lookupVariable","Interpreter","global","env","run","evaluate","evaluateBinaryExpression","node","environment","concat","find","x","includes","evaluateArguments","positionalArguments","keywordArguments","kwarg","evaluateFilterExpression","toJSON","reverse","sort","localeCompare","charAt","split","join","abs","filterName","kwargs","indent","attr","testName","testFunction","filtered","item","mapped","width","first","blank","lines","repeat","indented","evaluateTestExpression","evaluateUnaryExpression","evalProgram","evaluateBlock","statements","statement","lastEvaluated","evaluateIdentifier","evaluateCallExpression","expr","evaluateSliceExpression","evaluateMemberExpression","evaluateSet","rhs","variableName","JSON","stringify","evaluateIf","evaluateFor","scope","select","items","scopeUpdateFunctions","loopScope","scopeUpdateFunction","scope2","j","noIteration","loop","evaluateMacro","macroScope","nodeArg","passedArg","identifier","mapping","evaluatedKey","input","isArray","_scope","depth","currentDepth","indentValue","basePadding","childrenPadding","core","v","Template","parsed","render","backends","backendsSortedByPriority","registerBackend","backend","priority","init","createInferenceSessionHandler","TypeError","currentBackend","undefined","indexOf","splice","tryResolveAndInitializeBackend","async","backendName","backendInfo","initialized","aborted","isInitializing","initPromise","e","resolveBackendAndExecutionProviders","eps","executionProviders","backendHints","backendNames","errors","availableBackendNames","resolveResult","err","add","console","warn","filteredEps","Proxy","target","prop","Reflect","logLevelValue","wasm","webgl","webgpu","versions","common","version","logLevel","defineProperty","enumerable","InferenceSession","handler","feeds","arg1","arg2","TRACE_FUNC_BEGIN","fetches","Tensor","isFetchesEmpty","outputNames","RangeError","isFetches","arg1Keys","getOwnPropertyNames","inputNames","results","returnValue","hasOwnProperty","call","data","dims","TRACE_FUNC_END","release","dispose","create","arg0","arg3","filePathOrUint8Array","Uint8Array","ArrayBuffer","SharedArrayBuffer","buffer","byteOffset","byteLength","isSafeInteger","optionsWithValidatedEPs","startProfiling","endProfiling","tensorToDataURL","tensor","canvas","document","createElement","OffscreenCanvas","height","pixels2DContext","getContext","tensorLayout","inputformat","format","norm","normMean","normBias","mean","bias","stride","rTensorPointer","gTensorPointer","bTensorPointer","aTensorPointer","R","G","B","A","fillStyle","fillRect","toDataURL","tensorToImageData","image","channels","rImagePointer","gImagePointer","bImagePointer","aImagePointer","createImageData","bufferToTensor","outputformat","tensorFormat","float32Data","Float32Array","tensorFromImage","isHTMLImageEle","HTMLImageElement","isImageDataEle","ImageData","isImageBitmap","ImageBitmap","isString","bufferToTensorOptions","createCanvas","createCanvasContext","HTMLCanvasElement","resizedHeight","resizedWidth","drawImage","getImageData","Promise","reject","context","newImage","Image","crossOrigin","onload","img","tempCanvas","putImageData","tensorFromTexture","texture","download","location","tensorFromGpuBuffer","gpuBuffer","dataType","tensorFromPinnedBuffer","NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP","Int8Array","Uint16Array","Int16Array","Int32Array","Float64Array","Uint32Array","NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP","isTypedArrayChecked","checkTypedArray","isBigInt64ArrayAvailable","BigInt64Array","isBigUint64ArrayAvailable","BigUint64Array","isFloat16ArrayAvailable","Float16Array","dataLocation","expectedTypedArrayConstructor","cpuData","gpuTextureData","downloader","disposer","gpuBufferData","maybeDims","typedArrayConstructor","BigInt","firstElementType","mappedType","calculateSize","fromImage","fromTexture","fromGpuBuffer","fromPinnedBuffer","toImageData","ensureValid","getData","releaseData","isDownloading","reshape","tensorReshape","dim","TRACE","deviceType","label","trace","timeStamp","TRACE_FUNC","msg","extraMsg","stack","hasTraceFunc","TrainingSession","hasOptimizerModel","hasEvalModel","trainingInputNames","trainingOutputNames","evalInputNames","evalOutputNames","trainingOptions","sessionOptions","evalModel","optimizerModel","createTrainingSessionHandler","checkpointState","trainModel","typeNarrowingForRunStep","convertHandlerReturnTypeToMapOfTensors","lazyResetGrad","runTrainStep","runOptimizerStep","runEvalStep","getParametersSize","trainableOnly","loadParametersBuffer","paramsSize","getContiguousParameters","yr","$t","xt","Up","_r","ta","na","Re","we","ia","aa","Fn","ua","la","da","ca","pa","St","qt","fa","ha","ba","ya","ze","Oe","xr","wa","Ue","De","Sr","Np","Tr","Wp","Ln","Bp","getOwnPropertyDescriptor","Dp","Mp","prototype","Gn","require","apply","arguments","t","r","Ft","br","n","o","Rp","wr","d","p","l","ea","ra","Hn","oa","sa","m","u","h","_","y","g","$","S","T","C","ma","vr","mlTensor","ga","_a","mlTensorData","Uint8ClampedArray","ceil","fromMLTensor","$r","qn","va","$a","xa","Sa","Ta","Ia","Ca","Aa","jn","We","Ir","za","default","Lp","Ea","Pa","Oa","Kn","ht","jt","globalThis","self","onmessage","Cr","then","Ar","postMessage","epName","kr","Kt","out","model","Er","Pr","sessionId","inputIndices","inputs","outputIndices","zr","fill","Br","Worker","Dt","Da","Gp","Yn","Ba","Hp","Fp","qp","Ra","Ua","jp","Na","Zn","Qn","Dr","Va","Kp","Yp","Ce","Ae","Yt","pe","Wa","Zp","Qp","Xp","Jp","Ga","Zt","gt","Tt","Rr","Qt","Ur","Nr","Xn","Xt","em","tm","Fa","qa","Vr","rm","ue","Wr","ja","to","ro","nm","om","Ka","oo","no","Za","io","J","ao","et","k","It","Gr","Xa","Ja","Ct","uo","ye","ke","N","me","lo","At","He","F","Hr","E","M","es","Fr","so","ts","im","rs","am","sm","um","lm","Ee","ns","os","dm","cm","pm","mm","fm","hm","gm","bm","ym","_m","tt","as","ss","us","ls","ds","cs","ps","ms","fs","rt","wm","jr","co","nt","vm","$m","xm","Sm","Tm","Im","Cm","Am","km","Em","ot","gs","bs","ys","_s","ws","vs","$s","xs","Ss","Ts","Cs","As","po","Pm","mo","zm","Om","Bm","Rt","Dm","Es","Mm","Rm","Um","Ps","Nm","Vm","Os","Wm","fe","Ds","Ms","Rs","Us","Ns","Vs","Ws","Ls","Gs","Lm","Hs","Fs","qs","js","Jt","Ks","Yr","Ys","Zs","Qs","Xs","Js","eu","tu","ru","nu","ou","iu","au","su","uu","lu","du","cu","pu","fo","ho","mu","fu","hu","Gm","Hm","gu","Fm","qm","yu","jm","Km","it","wu","vu","$u","xu","Su","Tu","Iu","Cu","Au","ku","Zm","Qm","Xm","Jm","Pu","zu","Fe","qe","je","Qr","Pe","Bu","Du","er","Jr","ef","tf","go","Ru","rf","bo","nf","tr","of","Uu","af","Vu","rn","sf","Wu","uf","Lu","Gu","Fu","qu","lf","yo","df","_o","wo","Ku","cf","pf","vo","Zu","mf","ff","hf","Xu","Ju","gf","el","bf","tl","yf","nl","ol","_f","wf","vf","al","sl","$o","nn","ll","xf","xo","So","dl","Sf","cl","pl","Tf","fl","Cf","hl","Af","bl","kf","Ef","_l","wl","Pf","zf","$l","xl","Of","Bf","Tl","Il","Df","Mf","Al","kl","lt","yt","Ut","Nt","Rf","Nf","Vf","Wf","Lf","Gf","Hf","Pl","zl","Me","jf","Dl","Bl","Kf","rr","Ml","Yf","Zf","Qf","Xf","Io","Rl","Ul","Jf","eh","Nl","Vl","Ll","th","rh","Gl","nh","oh","Fl","ih","jl","ah","sh","uh","Yl","Zl","lh","dh","ch","ph","mh","fh","hh","gh","Xl","on","ed","td","rd","nd","bh","yh","od","id","ad","sd","ud","ld","dd","cd","pd","md","fd","hd","wh","vh","bd","yd","$h","xh","wd","Sh","Th","$d","xd","Ih","Ch","Ah","kh","Eh","Ph","zh","Oh","Bh","Dh","Mh","Td","Rh","Uh","Nh","Vh","Wh","Id","Cd","Lh","Gh","kd","Hh","Fh","Pd","qh","an","jh","Od","Kh","Yh","Bd","Dd","Zh","Qh","Rd","Ud","Vd","Xh","Jh","eg","Wd","tg","rg","Gd","Fd","sn","ng","og","Ao","ko","un","ig","Yd","ag","Zd","ln","dn","Eo","Qd","Jd","sg","cn","Ma","url","se","ee","be","ne","ve","Be","$e","de","V","Ge","assign","s","window","importScripts","mountExternalData","startsWith","substring","Eb","unmountExternalData","WebAssembly","Memory","initial","maximum","shared","f","w","I","Qe","D","L","H","Q","Bn","Fb","fc","Gb","flush","all","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput","jsepInit","Ub","Yb","Nb","Xb","jb","Zb","bc","Vb","Wb","$b","jsepRegisterBuffer","registerBuffer","jsepGetBuffer","getBuffer","jsepCreateDownloader","createDownloader","jsepOnCreateSession","onCreateSession","jsepOnReleaseSession","onReleaseSession","jsepOnRunStart","onRunStart","cc","upload","ac","Ob","jsepEnsureTensor","dc","jsepDownloadTensor","jsepReleaseTensorId","jsepRegisterMLContext","registerMLContext","jsepCreateMLTensorDownloader","createMLTensorDownloader","jsepRegisterMLTensor","registerMLTensor","jsepCreateMLContext","createMLContext","jsepRegisterMLConstant","registerMLConstant","P","href","currentScript","substr","lastIndexOf","XMLHttpRequest","open","responseType","send","response","status","onerror","O","U","log","bind","q","K","cmd","startWorker","handlers","proxy","Mb","oc","wasmMemory","W","wasmModule","Un","pthread_ptr","Pn","yc","Fo","Y","Li","_c","start_routine","Bt","hr","ar","Gi","alert","qc","instantiateWasm","Instance","Vo","onunhandledrejection","reason","wasmBinary","X","re","he","_e","HEAP8","HEAP16","HEAPU8","HEAPU16","HEAP32","HEAPU32","HEAPF32","HEAPF64","HEAP64","HEAPU64","Ke","Lt","bn","Gt","yn","Ht","Do","clearInterval","dt","RuntimeError","_n","Mo","Ro","Uo","No","fetch","credentials","ok","arrayBuffer","catch","instantiate","gc","vc","Yo","Xo","Jo","ti","ri","ni","oi","ii","ai","si","Z","ui","li","di","ci","$c","Sc","Tc","Cc","kc","Ec","Pc","zc","Nc","Vc","Wc","ka","Lc","Gc","Hc","Fc","jc","Zc","Qc","Jc","kn","ep","np","op","ip","ap","sp","up","lp","dp","cp","pp","mp","fp","hp","gp","Ti","Ii","bp","yp","_p","wp","vp","$p","xp","Sp","Ai","z","Tp","Ip","Cp","Ap","kp","Pi","zi","Sn","Oi","Bi","Di","Mi","xn","Ni","zp","wn","Te","subarray","wasmOffsetConverter","alpha","beta","keepDims","noopWithEmptyAxes","axes","perm","blocksize","mode","ce","ge","le","autoPad","dilations","group","kernelShape","pads","strides","wIsConst","outputPadding","outputShape","activation","auto_pad","ceil_mode","count_include_pad","storage_order","kernel_shape","transA","transB","selectLastIndex","axis","numOutputs","splitSizes","antialias","coordinateTransformMode","cubicCoeffA","excludeOutside","extrapolationValue","keepAspectRatioPolicy","nearestMode","starts","ends","epsilon","equation","momentum","spatial","trainingMode","exclusive","blockSize","align_corners","padding_mode","reduction","numHeads","isUnidirectional","maskFilterValue","scale","doRotary","qkvHiddenSizes","pastPresentShareBuffer","Ie","w_is_const","activation_params","kvNumHeads","softcap","rotaryInterleaved","smoothSoftmax","localWindowSize","simplified","accuracyLevel","bits","interleaved","rotaryEmbeddingDim","gatherAxis","quantizeAxis","wi","vn","message","$n","terminate","Wo","ct","jo","qo","wt","Ye","Ab","hc","Qb","mc","_t","xe","Wn","Vn","Hi","gr","Lo","Go","Ho","Nn","forEach","targetThread","transferList","thread","loaded","threadId","filename","lineno","URL","workerData","ir","shift","qi","ji","wc","Jb","Ko","Zo","TextDecoder","Qo","decode","String","fromCharCode","Tn","charCodeAt","ei","Pt","pi","pt","Ze","Cn","xc","Sb","mi","fromWireType","toWireType","argPackAdvance","mt","readValueFromPointer","Db","An","st","Ne","Ve","En","Ic","Ac","Xe","fr","fi","Oc","Bc","Dc","Mc","Rc","Uc","Tb","hi","Atomics","nc","store","Fi","setTimeout","zn","Op","On","Wi","gi","sr","ft","bi","ur","yi","_i","Kc","Yc","Zi","Browser","Kb","Rb","resume","pause","Ki","Qi","lr","Xc","dr","vi","Function","tp","rp","$i","NaN","Date","getUTCSeconds","getUTCMinutes","getUTCHours","getUTCDate","getUTCMonth","getUTCFullYear","getUTCDay","getTime","UTC","zt","xi","Si","getSeconds","getMinutes","getHours","getDate","getMonth","getFullYear","getDay","getTimezoneOffset","setTime","getYear","isNaN","toLocaleTimeString","hour12","timeZoneName","Dn","Ci","now","performance","timeOrigin","navigator","hardwareConcurrency","grow","cr","Ot","ki","Pb","ec","Mn","Rn","Ei","USER","LOGNAME","PATH","PWD","HOME","LANG","languages","Ep","Ri","Ui","Pp","Ji","vt","Bb","Cb","setDate","setMonth","setFullYear","Hb","Lb","Ib","ub","rc","ic","lc","RegExp","floor","numThreads","unshift","Vi","pr","BindingError","InternalError","count_emval_handles","exports","Yi","Fibers","sc","fb","hb","emscripten_main_runtime_thread_id","sb","tb","ib","locateFile","instance","module","instantiateStreaming","_OrtInit","_OrtGetLastError","_OrtCreateSessionOptions","_OrtAppendExecutionProvider","Ha","_OrtAddFreeDimensionOverride","_OrtAddSessionConfigEntry","_OrtReleaseSessionOptions","La","_OrtReleaseSession","_OrtGetInputOutputCount","_OrtGetInputName","_OrtGetOutputName","_OrtFree","Qa","_OrtCreateTensor","_OrtGetTensorData","_OrtReleaseTensor","_OrtCreateRunOptions","_OrtAddRunConfigEntry","_OrtReleaseRunOptions","_OrtCreateBinding","Ya","_OrtBindOutput","_OrtClearBoundOutputs","_OrtReleaseBinding","ab","bb","_OrtEndProfiling","cb","_JsepOutput","db","_JsepGetNodeName","eb","mr","_free","gb","_malloc","kb","lb","mb","nb","ob","pb","qb","rb","dynCall_ii","vb","wb","xb","yb","zb","Xi","calledRun","___start_em_js","___stop_em_js","stackSave","stackRestore","stackAlloc","setValue","getValue","UTF8ToString","stringToUTF8","lengthBytesUTF8","PTR_SIZE","origin","blob","createObjectURL","MessageChannel","port1","validate","initTimeout","crossOriginIsolated","wasmPaths","mjs","revokeObjectURL","race","Mr","logSeverityLevel","logVerbosityLevel","tag","extra","WeakSet","session","use_ort_model_bytes_directly","enableMemPattern","preferredLayout","graphOptimizationLevel","executionMode","logId","optimizedModelFilePath","enableCpuMemArena","enableProfiling","enableGraphCapture","freeDimensionOverrides","te","reduce","Jn","headers","parseInt","getReader","done","read","Blob","Je","toISOString","eo","Lr","device","createBuffer","usage","GPUBufferUsage","COPY_DST","MAP_READ","getCommandEncoder","endComputePass","copyBufferToBuffer","mapAsync","GPUMapMode","READ","getMappedRange","destroy","storageCache","freeBuffers","freeUniformBuffers","buffersPending","capturedPendingBuffers","sessionCount","originalSize","mappedAtCreation","MAP_WRITE","COPY_SRC","unmap","createCommandEncoder","gpuData","queue","submit","finish","memcpy","registerExternalBuffer","capturedCommandList","currentSessionId","unregisterExternalBuffer","delete","STORAGE","UNIFORM","refreshPendingBuffers","sessionStatus","Se","cacheKey","oe","calcMatMulShape","calcShape","isValidBroadcast","getSizeFromDimensionRange","convertShape","sizeFromDimension","sizeToDimension","computeStrides","normalizeAxis","normalizeAxes","sortBasedOnPerm","padShape","areEqual","adjustPoolAttributes","adjustPadsBasedOnAutoPad","adjustPadAndReturnShape","computePoolOutputShape","computeShapeHelper","computeConvOutputShape","getShapeOfGemmResult","ae","keys","indices","storage","offsetToIndices","indicesToOffset","broadcastedIndicesToOffset","setByIndices","getByIndices","impl","indicesGet","rank","indicesSet","setByOffset","getByOffset","shape","normalizedDispatchGroup","limits","internalVariables","uniforms","variableIndex","guardAgainstOutOfBoundsWorkgroupSizes","mainStart","maxComputeWorkgroupSizeX","maxComputeWorkgroupSizeY","maxComputeWorkgroupSizeZ","maxComputeInvocationsPerWorkgroup","appendVariableUniforms","declareVariables","registerInternalVariable","registerInternalVariables","registerUniform","registerUniforms","uniformDeclaration","additionalImplementations","variablesInfo","ut","newShape","newPerm","shaderCache","inputDependencies","getRunData","outputs","dispatchGroup","programUniforms","getShaderSource","hint","compute","hs","qr","sum","prod","sumSquare","logSumExp","l1","l2","logSum","getBigInt64Array","ks","Kr","batchSize","sequenceLength","pastSequenceLength","kvSequenceLength","totalSequenceLength","maxSequenceLength","inputHiddenSize","hiddenSize","vHiddenSize","headSize","vHeadSize","maskType","broadcastResPosBias","passPastInKv","qkvFormat","nReps","sqrt","gpuDataType","outputCount","zs","validateInputContent","Bs","Zr","getFloat32Array","getUint16Array","_u","Eu","scalar","vector","Ou","bt","clipMax","clipMin","Xr","Mu","en","tn","Nu","Hu","trunc","top","bottom","front","back","padInfo","outDepth","outHeight","outWidth","dataFormat","inDepth","inHeight","inWidth","inChannels","outChannels","strideDepth","strideHeight","strideWidth","filterDepth","filterHeight","filterWidth","effectiveFilterDepth","effectiveFilterHeight","effectiveFilterWidth","dilationDepth","dilationHeight","dilationWidth","inShape","outShape","filterShape","ju","Yu","kernelCustomData","wT","adapterInfo","isArchitecture","Qu","rl","il","getInt32Array","ul","ml","symbolToIndices","inputIndex","addSymbol","hasEllipsis","symbolToInfo","lhs","outputDims","match","processTerm","count","ellipsisDims","dimValue","gl","yl","vl","Sl","Cl","El","Ol","alignCorners","paddingMode","To","Co","Wl","Hl","ql","Kl","Ql","isVendor","Jl","gd","ceilMode","countIncludePad","storageOrder","_d","vd","Sd","Ad","round","MAX_VALUE","MIN_VALUE","customDataBuffer","Ed","zd","Md","Nd","Ld","Hd","qd","jd","repo","attributesBound","getArtifact","setArtifact","programInfo","getComputePassEncoder","writeTimestamp","pendingDispatchNumber","binding","resource","createBindGroup","layout","computePipeline","getBindGroupLayout","kernelId","currentKernelId","bindGroup","setPipeline","setBindGroup","dispatchWorkgroups","maxDispatchNumber","queryType","build","feature","extension","features","createShaderModule","code","createComputePipeline","entryPoint","uniformVariablesInfo","normalizeDispatchGroupSize","maxComputeWorkgroupsPerDimension","cbrt","Kd","architecture","vendor","subgroupsSupported","subgroupsF16Supported","minSubgroupSize","maxSubgroupSize","subgroupSizeRange","commandEncoder","computePassEncoder","pendingKernels","pendingQueries","capturedPendingKernels","sessionExternalDataMapping","currentKernelCustomData","initialize","requiredLimits","maxComputeWorkgroupStorageSize","maxStorageBufferBindingSize","maxBufferSize","requiredFeatures","requestDevice","deviceInfo","info","requestAdapterInfo","gpuDataManager","programManager","kernels","kernelPersistentData","debug","onuncapturederror","GPUValidationError","writable","configurable","setQueryType","querySet","timestampWrites","beginningOfPassWriteIndex","endOfPassWriteIndex","beginComputePass","end","resolveQuerySet","queryResolveBuffer","kernelType","kernelName","programName","inputTensorViews","outputTensorViews","queryTimeBase","profiling","ondata","inputsMetadata","outputsMetadata","startTime","endTime","temporaryData","writeBuffer","offset","alloc","free","createKernel","kernelEntry","attributes","releaseKernel","computeKernel","pushErrorScope","popErrorScope","unregisterBuffers","createQuerySet","QUERY_RESOLVE","captureBegin","captureEnd","replay","Xd","mlContext","tensorShape","write","writeTensor","readTensor","sameTypeAndShape","tensorManager","wrapper","tensorWrapper","releaseTensor","ensureTensor","activeUpload","MLTensorUsage","WRITE","getCachedTensor","tensorTrackersById","freeTensors","externalTensors","reserveTensorId","releaseTensorId","releaseTensorsForSession","registerTensor","currentContext","createTensor","dimensions","readable","mlContextBySessionId","sessionIdsByMLContext","mlContextCache","activeSessionId","GPUDevice","findIndex","gpuDevice","createContext","getMLContext","uploadTensor","shouldTransferToMLTensor","downloadTensor","constant","tc","ug","nr","Po","lg","kt","dg","Et","Le","mn","pn","zo","Oo","Vt","Wt","pg","uc","mg","hn","customDataOffset","customDataSize","opKernelContext","output","gpu","adapter","powerPreference","forceFallbackAdapter","requestAdapter","externalData","path","preferredOutputLocation","handle","outputPreferredLocations","outputPreferredLocationsEncoded","Bo","pc","fetchModelAndCopyToWasmMemory","loadModel","OnnxruntimeWebAssemblyBackend","gn","initializeFlags","wasmBackend","fg","simd","cpus","bS","DEVICE_TO_EXECUTION_PROVIDER_MAPPING","auto","cpu","cuda","dml","webnn","supportedDevices","defaultDevices","ONNX","ORT_SYMBOL","Symbol","apis","IS_NODE_ENV","process","platform","arch","IS_WEBNN_AVAILABLE","IS_WEBGPU_AVAILABLE","deviceToExecutionProviders","wasmInitPromise","createInferenceSession","session_options","session_config","sessionPromise","config","isONNXTensor","ONNX_ENV","isONNXProxy","onnx","getNormalizedConfig","init_normalized_config","model_type","text_config","phi_config","decoder","decoderConfig","add_encoder_pkv","pick","num_decoder_layers","num_decoder_heads","decoder_hidden_size","num_encoder_layers","num_encoder_heads","encoder_hidden_size","num_layers","num_heads","hidden_size","normalized_config","getKeyValueShapes","prefix","decoderFeeds","is_encoder_decoder","encoder_dim_kv","decoder_dim_kv","encoder_dims","decoder_dims","dim_kv","num_attention_heads","multi_query","keyDims","valueDims","PretrainedConfig","max_position_embeddings","configJSON","from_pretrained","pretrained_model_name_or_path","progress_callback","cache_dir","local_files_only","revision","getModelJSON","loadConfig","AutoConfig","IS_BROWSER_ENV","IS_WEBWORKER_ENV","IS_WEB_CACHE_AVAILABLE","IS_PROCESS_AVAILABLE","IS_FS_AVAILABLE","isEmpty","IS_PATH_AVAILABLE","RUNNING_LOCALLY","dirname__","DEFAULT_CACHE_DIR","DEFAULT_LOCAL_MODEL_PATH","allowRemoteModels","remoteHost","remotePathTemplate","allowLocalModels","localModelPath","useFS","useBrowserCache","useFSCache","cacheDir","useCustomCache","customCache","obj","GenerationConfig","max_length","max_new_tokens","min_length","min_new_tokens","early_stopping","max_time","do_sample","num_beams","num_beam_groups","penalty_alpha","use_cache","temperature","top_k","top_p","typical_p","epsilon_cutoff","eta_cutoff","diversity_penalty","repetition_penalty","encoder_repetition_penalty","length_penalty","no_repeat_ngram_size","bad_words_ids","force_words_ids","renormalize_logits","constraints","forced_bos_token_id","forced_eos_token_id","remove_invalid_values","exponential_decay_length_penalty","suppress_tokens","begin_suppress_tokens","forced_decoder_ids","guidance_scale","num_return_sequences","output_attentions","output_hidden_states","output_scores","return_dict_in_generate","pad_token_id","bos_token_id","eos_token_id","encoder_no_repeat_ngram_size","decoder_start_token_id","generation_kwargs","LogitsProcessor","Callable","_call","input_ids","logits","LogitsWarper","LogitsProcessorList","processors","extend","toReturn","processor","iterator","ForcedBOSTokenLogitsProcessor","batch_logits_data","Infinity","ForcedEOSTokenLogitsProcessor","eos_token","SuppressTokensAtBeginLogitsProcessor","begin_index","token_id","WhisperTimeStampLogitsProcessor","generate_config","init_tokens","no_timestamps_token_id","timestamp_begin","max_initial_timestamp_index","seq","last_was_timestamp","penultimate_was_timestamp","last_allowed","logprobs","log_softmax","exp","NoRepeatNGramLogitsProcessor","getNgrams","prevInputIds","curLen","ngrams","ngram","generatedNgram","prevNgram","prevNgramKey","prevNgramValue","getGeneratedNgrams","bannedNgrams","ngramIdx","calcBannedNgramTokens","bannedTokens","generatedNgrams","RepetitionPenaltyLogitsProcessor","penalty","input_id","MinLengthLogitsProcessor","MinNewTokensLengthLogitsProcessor","prompt_length_to_skip","NoBadWordsLogitsProcessor","ids","bad_word_ids","mark","ClassifierFreeGuidanceLogitsProcessor","unguided_bsz","cond_logits","uncond_logits","TemperatureLogitsWarper","errorMessage","TopPLogitsWarper","filter_value","min_tokens_to_keep","TopKLogitsWarper","LogitsSampler","generation_config","sample","getLogits","index","vocabSize","logs","startIndex","randomSelect","probabilities","sumProbabilities","random","getSampler","MultinomialSampler","BeamSearchSampler","GreedySampler","argmax","topk","softmax","sampledIndex","StoppingCriteria","scores","StoppingCriteriaList","criteria","is_done","criterion","criterion_done","MaxLengthCriteria","EosTokenCriteria","last","eos_id","InterruptableStoppingCriteria","interrupted","interrupt","reset","BaseStreamer","put","stdout_write","stdout","TextStreamer","tokenizer","skip_prompt","callback_function","token_callback_function","decode_kwargs","token_cache","print_len","next_tokens_are_prompt","mergeArrays","printable_text","is_chinese_char","on_finalized_text","stream_end","WhisperTextStreamer","on_chunk_start","on_chunk_end","on_finalize","time_precision","skip_special_tokens","waiting_for_timestamp","time","MODEL_TYPES","MODEL_TYPE_MAPPING","MODEL_NAME_TO_CLASS_MAPPING","MODEL_CLASS_TO_NAME_MAPPING","constructSessions","names","fromEntries","fileName","custom_config","selectedDevice","dtype","DEFAULT_DEVICE_DTYPE_MAPPING","DATA_TYPES","fp32","selectedDtype","DEFAULT_DTYPE_SUFFIX_MAPPING","fp16","isWebGpuFp16Supported","kv_cache_dtype","suffix","modelFileName","subfolder","free_dimension_overrides","bufferPromise","getModelFile","use_external_data_format","externalDataPromises","fullPath","ext","ext_buffer","shapes","getSession","getOptionalConfigs","getQueryValue","URLSearchParams","search","runs","perf","warmup","inference","throughput","getPerf","sessionRun","checkedInputs","missingInputs","inputName","clone","numInputsProvided","numInputsNeeded","ignored","validateInputs","ortFeed","ort_tensor","numOfWarmups","loopStart","arrayInference","parseFloat","toFixed","replaceTensors","toI64Tensor","flat","boolTensor","seq2seqForward","model_inputs","encoder_outputs","decoder_input_ids","other_decoder_inputs","encoder_inputs","sessions","encoderForward","last_hidden_state","encoder_hidden_states","encoder_attention_mask","attention_mask","decoderForward","encoderFeeds","inputs_embeds","encode_text","token_type_ids","past_key_values","new_model_inputs","use_cache_branch","position_ids","bz","seq_len","createPositionIds","addPastKeyValues","fixed","imageTextToTextForward","pixel_values","logits_processor","image_features","encode_image","_merge_input_ids_with_image_features","target_length","past_length","cat","ones","decoder_prepare_inputs_for_generation","image_token_index","num_image_tokens","num_new_tokens","encoder_decoder_prepare_inputs_for_generation","image_text_to_text_prepare_inputs_for_generation","PreTrainedModel","main_input_name","forward_params","configs","modelName","modelType","can_generate","_forward","_prepare_inputs_for_generation","promises","model_file_name","decoder_model_merged","prompt_encoder_mask_decoder","embed_tokens","vision_encoder","encodec_decode","GITHUB_ISSUE_URL","forward","_get_logits_warper","warpers","_get_logits_processor","input_ids_seq_length","_prepare_generation_config","cls","gen_config","_get_stopping_criteria","stopping_criteria","_validate_model_class","generate_compatible_mappings","MODEL_FOR_CAUSAL_LM_MAPPING_NAMES","MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES","MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES","MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES","generate_compatible_classes","model_mapping","supported_models","prepare_inputs_for_generation","_update_model_kwargs_for_generation","generated_input_ids","getPastKeyValues","_prepare_model_inputs","model_kwargs","input_name","inputs_tensor","model_input_name","_prepare_encoder_decoder_kwargs_for_generation","prepared_inputs","_prepare_inputs_embeds","full_like","zeros_like","decoder_input_ids_batch_size","_prepare_decoder_input_ids_for_generation","batch_size","num_codebooks","ones_like","generate","streamer","input_ids_length","prepared_logits_processor","prepared_stopping_criteria","numInputs","sampler","all_input_ids","tolist","attentions","token_attentions","getAttentions","next_tokens_scores","batch_idx","sampledTokens","newTokenId","logProb","bigint","sequences","decoderResults","pastKeyValues","disposeEncoderPKVs","pkvs","newName","is_encoder_pkv","model_output","attnName","empty","ModelOutput","BaseModelOutput","hidden_states","BertPreTrainedModel","BertModel","BertForMaskedLM","MaskedLMOutput","BertForSequenceClassification","SequenceClassifierOutput","BertForTokenClassification","TokenClassifierOutput","BertForQuestionAnswering","QuestionAnsweringModelOutput","NomicBertPreTrainedModel","NomicBertModel","RoFormerPreTrainedModel","RoFormerModel","RoFormerForMaskedLM","RoFormerForSequenceClassification","RoFormerForTokenClassification","RoFormerForQuestionAnswering","ConvBertPreTrainedModel","ConvBertModel","ConvBertForMaskedLM","ConvBertForSequenceClassification","ConvBertForTokenClassification","ConvBertForQuestionAnswering","ElectraPreTrainedModel","ElectraModel","ElectraForMaskedLM","ElectraForSequenceClassification","ElectraForTokenClassification","ElectraForQuestionAnswering","CamembertPreTrainedModel","CamembertModel","CamembertForMaskedLM","CamembertForSequenceClassification","CamembertForTokenClassification","CamembertForQuestionAnswering","DebertaPreTrainedModel","DebertaModel","DebertaForMaskedLM","DebertaForSequenceClassification","DebertaForTokenClassification","DebertaForQuestionAnswering","DebertaV2PreTrainedModel","DebertaV2Model","DebertaV2ForMaskedLM","DebertaV2ForSequenceClassification","DebertaV2ForTokenClassification","DebertaV2ForQuestionAnswering","DistilBertPreTrainedModel","DistilBertModel","DistilBertForSequenceClassification","DistilBertForTokenClassification","DistilBertForQuestionAnswering","DistilBertForMaskedLM","EsmPreTrainedModel","EsmModel","EsmForMaskedLM","EsmForSequenceClassification","EsmForTokenClassification","MobileBertPreTrainedModel","MobileBertModel","MobileBertForMaskedLM","MobileBertForSequenceClassification","MobileBertForQuestionAnswering","MPNetPreTrainedModel","MPNetModel","MPNetForMaskedLM","MPNetForSequenceClassification","MPNetForTokenClassification","MPNetForQuestionAnswering","SqueezeBertPreTrainedModel","SqueezeBertModel","SqueezeBertForMaskedLM","SqueezeBertForSequenceClassification","SqueezeBertForQuestionAnswering","AlbertPreTrainedModel","AlbertModel","AlbertForSequenceClassification","AlbertForQuestionAnswering","AlbertForMaskedLM","T5PreTrainedModel","T5Model","T5ForConditionalGeneration","LongT5PreTrainedModel","LongT5Model","LongT5ForConditionalGeneration","MT5PreTrainedModel","MT5Model","MT5ForConditionalGeneration","BartPretrainedModel","BartModel","BartForConditionalGeneration","BartForSequenceClassification","MBartPreTrainedModel","MBartModel","MBartForConditionalGeneration","MBartForSequenceClassification","MBartForCausalLM","BlenderbotPreTrainedModel","BlenderbotModel","BlenderbotForConditionalGeneration","BlenderbotSmallPreTrainedModel","BlenderbotSmallModel","BlenderbotSmallForConditionalGeneration","RobertaPreTrainedModel","RobertaModel","RobertaForMaskedLM","RobertaForSequenceClassification","RobertaForTokenClassification","RobertaForQuestionAnswering","XLMPreTrainedModel","XLMModel","XLMWithLMHeadModel","XLMForSequenceClassification","XLMForTokenClassification","XLMForQuestionAnswering","XLMRobertaPreTrainedModel","XLMRobertaModel","XLMRobertaForMaskedLM","XLMRobertaForSequenceClassification","XLMRobertaForTokenClassification","XLMRobertaForQuestionAnswering","ASTPreTrainedModel","ASTModel","ASTForAudioClassification","WhisperPreTrainedModel","requires_attention_mask","WhisperModel","WhisperForConditionalGeneration","WhisperGenerationConfig","_retrieve_init_tokens","language","task","is_multilingual","language_token","whisper_language_to_code","lang_to_id","task_to_id","return_timestamps","return_token_timestamps","alignment_heads","_extract_token_timestamps","num_frames","generate_outputs","cross_attentions","median_filter_width","batch","decoder_layers","weights","transpose","std","calculatedMean","std_mean","smoothedWeights","aTensor","bTensor","stdTensorData","meanTensorData","cTensorData","medianFilter","batchedMatrices","timestampsShape","timestamps","matrix","neg","squeeze_","text_indices","time_indices","dynamic_time_warping","diffs","jumps","jump_times","VisionEncoderDecoderModel","LlavaPreTrainedModel","LlavaForConditionalGeneration","indexOfImage","noImages","allImages","stacked","stacked_attention_mask","Moondream1ForConditionalGeneration","Florence2PreTrainedModel","Florence2ForConditionalGeneration","text_features","decoder_attention_mask","decoder_inputs_embeds","CLIPPreTrainedModel","CLIPModel","CLIPTextModel","CLIPTextModelWithProjection","CLIPVisionModel","CLIPVisionModelWithProjection","SiglipPreTrainedModel","SiglipModel","SiglipTextModel","SiglipVisionModel","ChineseCLIPPreTrainedModel","ChineseCLIPModel","CLIPSegPreTrainedModel","CLIPSegModel","CLIPSegForImageSegmentation","GPT2PreTrainedModel","GPT2Model","GPT2LMHeadModel","JAISPreTrainedModel","JAISModel","JAISLMHeadModel","GPTNeoPreTrainedModel","GPTNeoModel","GPTNeoForCausalLM","GPTNeoXPreTrainedModel","GPTNeoXModel","GPTNeoXForCausalLM","GPTJPreTrainedModel","GPTJModel","GPTJForCausalLM","GPTBigCodePreTrainedModel","GPTBigCodeModel","GPTBigCodeForCausalLM","CodeGenPreTrainedModel","CodeGenModel","CodeGenForCausalLM","LlamaPreTrainedModel","LlamaModel","LlamaForCausalLM","GranitePreTrainedModel","GraniteModel","GraniteForCausalLM","CoherePreTrainedModel","CohereModel","CohereForCausalLM","GemmaPreTrainedModel","GemmaModel","GemmaForCausalLM","Gemma2PreTrainedModel","Gemma2Model","Gemma2ForCausalLM","OpenELMPreTrainedModel","OpenELMModel","OpenELMForCausalLM","Qwen2PreTrainedModel","Qwen2Model","Qwen2ForCausalLM","PhiPreTrainedModel","PhiModel","PhiForCausalLM","Phi3PreTrainedModel","Phi3Model","Phi3ForCausalLM","BloomPreTrainedModel","BloomModel","BloomForCausalLM","MptPreTrainedModel","MptModel","MptForCausalLM","OPTPreTrainedModel","OPTModel","OPTForCausalLM","ViTPreTrainedModel","ViTModel","ViTForImageClassification","PvtPreTrainedModel","PvtModel","PvtForImageClassification","ViTMAEPreTrainedModel","ViTMAEModel","ViTMSNPreTrainedModel","ViTMSNModel","ViTMSNForImageClassification","GroupViTPreTrainedModel","GroupViTModel","FastViTPreTrainedModel","FastViTModel","FastViTForImageClassification","VitMattePreTrainedModel","VitMatteForImageMatting","ImageMattingOutput","MobileViTPreTrainedModel","MobileViTModel","MobileViTForImageClassification","MobileViTV2PreTrainedModel","MobileViTV2Model","MobileViTV2ForImageClassification","OwlViTPreTrainedModel","OwlViTModel","OwlViTForObjectDetection","Owlv2PreTrainedModel","Owlv2Model","Owlv2ForObjectDetection","BeitPreTrainedModel","BeitModel","BeitForImageClassification","DetrPreTrainedModel","DetrModel","DetrForObjectDetection","DetrObjectDetectionOutput","DetrForSegmentation","DetrSegmentationOutput","pred_boxes","pred_masks","RTDetrPreTrainedModel","RTDetrModel","RTDetrForObjectDetection","RTDetrObjectDetectionOutput","TableTransformerPreTrainedModel","TableTransformerModel","TableTransformerForObjectDetection","TableTransformerObjectDetectionOutput","DeiTPreTrainedModel","DeiTModel","DeiTForImageClassification","HieraPreTrainedModel","HieraModel","HieraForImageClassification","ResNetPreTrainedModel","ResNetModel","ResNetForImageClassification","SwinPreTrainedModel","SwinModel","SwinForImageClassification","Swin2SRPreTrainedModel","Swin2SRModel","Swin2SRForImageSuperResolution","DPTPreTrainedModel","DPTModel","DPTForDepthEstimation","DepthAnythingPreTrainedModel","DepthAnythingForDepthEstimation","SapiensPreTrainedModel","SapiensForSemanticSegmentation","SapiensForDepthEstimation","SapiensForNormalEstimation","DepthProPreTrainedModel","DepthProForDepthEstimation","MaskFormerPreTrainedModel","MaskFormerModel","MaskFormerForInstanceSegmentation","GLPNPreTrainedModel","GLPNModel","GLPNForDepthEstimation","DonutSwinPreTrainedModel","DonutSwinModel","ConvNextPreTrainedModel","ConvNextModel","ConvNextForImageClassification","ConvNextV2PreTrainedModel","ConvNextV2Model","ConvNextV2ForImageClassification","Dinov2PreTrainedModel","Dinov2Model","Dinov2ForImageClassification","YolosPreTrainedModel","YolosModel","YolosForObjectDetection","YolosObjectDetectionOutput","SamPreTrainedModel","SamModel","get_image_embeddings","image_embeddings","image_positional_embeddings","input_labels","input_points","numElements","decoder_inputs","input_boxes","SamImageSegmentationOutput","iou_scores","MarianPreTrainedModel","MarianModel","MarianMTModel","M2M100PreTrainedModel","M2M100Model","M2M100ForConditionalGeneration","Wav2Vec2PreTrainedModel","Wav2Vec2Model","Wav2Vec2ForCTC","CausalLMOutput","Wav2Vec2ForSequenceClassification","Wav2Vec2ForAudioFrameClassification","PyAnnotePreTrainedModel","PyAnnoteModel","PyAnnoteForAudioFrameClassification","WeSpeakerResNetPreTrainedModel","WeSpeakerResNetModel","UniSpeechPreTrainedModel","UniSpeechModel","UniSpeechForCTC","UniSpeechForSequenceClassification","UniSpeechSatPreTrainedModel","UniSpeechSatModel","UniSpeechSatForCTC","UniSpeechSatForSequenceClassification","UniSpeechSatForAudioFrameClassification","Wav2Vec2BertPreTrainedModel","Wav2Vec2BertModel","Wav2Vec2BertForCTC","Wav2Vec2BertForSequenceClassification","HubertPreTrainedModel","HubertModel","HubertForCTC","HubertForSequenceClassification","WavLMPreTrainedModel","WavLMModel","WavLMForCTC","WavLMForSequenceClassification","WavLMForXVector","XVectorOutput","WavLMForAudioFrameClassification","SpeechT5PreTrainedModel","SpeechT5Model","SpeechT5ForSpeechToText","SpeechT5ForTextToSpeech","generate_speech","input_values","speaker_embeddings","threshold","minlenratio","maxlenratio","vocoder","reduction_factor","maxlen","minlen","num_mel_bins","spectrogramParts","decoder_outputs","idx","output_sequence","output_sequence_out","prob","spectrum","spectrogram","waveform","SpeechT5HifiGan","TrOCRPreTrainedModel","TrOCRForCausalLM","MistralPreTrainedModel","MistralModel","MistralForCausalLM","Starcoder2PreTrainedModel","Starcoder2Model","Starcoder2ForCausalLM","FalconPreTrainedModel","FalconModel","FalconForCausalLM","ClapPreTrainedModel","ClapModel","ClapTextModelWithProjection","ClapAudioModelWithProjection","VitsPreTrainedModel","VitsModel","VitsModelOutput","SegformerPreTrainedModel","SegformerModel","SegformerForImageClassification","SegformerForSemanticSegmentation","StableLmPreTrainedModel","StableLmModel","StableLmForCausalLM","EfficientNetPreTrainedModel","EfficientNetModel","EfficientNetForImageClassification","MusicgenPreTrainedModel","MusicgenModel","MusicgenForCausalLM","MusicgenForConditionalGeneration","_apply_and_filter_by_delay_pattern_mask","bs_x_codebooks","seqLength","upperBound","newDataSize","diff","inferred","clonedInputIds","structuredClone","output_ids","audio_codes","unsqueeze_","audio_values","MobileNetV1PreTrainedModel","MobileNetV1Model","MobileNetV1ForImageClassification","MobileNetV2PreTrainedModel","MobileNetV2Model","MobileNetV2ForImageClassification","MobileNetV3PreTrainedModel","MobileNetV3Model","MobileNetV3ForImageClassification","MobileNetV4PreTrainedModel","MobileNetV4Model","MobileNetV4ForImageClassification","DecisionTransformerPreTrainedModel","DecisionTransformerModel","PretrainedMixin","static","MODEL_CLASS_MAPPINGS","MODEL_CLASS_MAPPING","modelInfo","BASE_IF_FAIL","MODEL_MAPPING_NAMES_ENCODER_ONLY","MODEL_MAPPING_NAMES_ENCODER_DECODER","MODEL_MAPPING_NAMES_DECODER_ONLY","MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES","MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES","MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES","MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES","MODEL_FOR_MASKED_LM_MAPPING_NAMES","MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES","MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES","MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES","MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES","MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES","MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES","MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES","MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES","MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES","MODEL_FOR_MASK_GENERATION_MAPPING_NAMES","MODEL_FOR_CTC_MAPPING_NAMES","MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES","MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES","MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES","MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES","MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES","MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES","MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES","MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES","MODEL_CLASS_TYPE_MAPPING","mappings","CUSTOM_MAPPING","AutoModel","AutoModelForSequenceClassification","AutoModelForTokenClassification","AutoModelForSeq2SeqLM","AutoModelForSpeechSeq2Seq","AutoModelForTextToSpectrogram","AutoModelForTextToWaveform","AutoModelForCausalLM","AutoModelForMaskedLM","AutoModelForQuestionAnswering","AutoModelForVision2Seq","AutoModelForImageClassification","AutoModelForImageSegmentation","AutoModelForSemanticSegmentation","AutoModelForUniversalSegmentation","AutoModelForObjectDetection","AutoModelForZeroShotObjectDetection","AutoModelForMaskGeneration","AutoModelForCTC","AutoModelForAudioClassification","AutoModelForXVector","AutoModelForAudioFrameClassification","AutoModelForDocumentQuestionAnswering","AutoModelForImageMatting","AutoModelForImageToImage","AutoModelForDepthEstimation","AutoModelForNormalEstimation","AutoModelForImageFeatureExtraction","Seq2SeqLMOutput","decoder_attentions","embeddings","start_logits","end_logits","CausalLMOutputWithPast","alphas","WHISPER_LANGUAGES","WHISPER_LANGUAGE_MAPPING","WHISPER_TO_LANGUAGE_CODE_MAPPING","language_code","langs","prompt_ids","wrap","session_bytes","TensorOpRegistry","bilinear_interpolate_4d","_bilinear_interpolate_4d","bicubic_interpolate_4d","_bicubic_interpolate_4d","matmul","_matmul","stft","_stft","rfft","_rfft","_top_k","prepareImages","images","RawImage","prepareAudios","audios","sampling_rate","read_audio","get_bounding_box","box","asInteger","xmin","ymin","xmax","ymax","Pipeline","TextClassificationPipeline","texts","padding","truncation","function_to_apply","problem_type","sigmoid","id2label","vals","score","TokenClassificationPipeline","ignore_labels","isBatched","tokenData","topScoreIndex","entity","QuestionAnsweringPipeline","question","text_pair","special_tokens","all_special_ids","sepIndex","sep_token_id","ix","start_scores","end_scores","product","answer_tokens","answer","FillMaskPipeline","mask_token_index","mask_token_id","mask_token","itemLogits","sequence","token_str","vocab","Text2TextGenerationPipeline","_key","generate_kwargs","task_specific_params","tokenizer_options","TranslationPipeline","_build_translation_inputs","outputTokenIds","batch_decode","SummarizationPipeline","isChat","TextGenerationPipeline","isChatInput","apply_chat_template","add_generation_prompt","add_special_tokens","return_full_text","padding_side","text_inputs","decoded","promptLengths","textIndex","generated_text","role","content","ZeroShotClassificationPipeline","label2id","entailment_id","contradiction_id","candidate_labels","hypothesis_template","multi_label","hypotheses","softmaxEach","premise","entails_logits","hypothesis","scores_sorted","labels","FeatureExtractionPipeline","pooling","normalize","quantize","precision","token_embeddings","mean_pooling","quantize_embeddings","ImageFeatureExtractionPipeline","pool","preparedImages","pooler_output","image_embeds","AudioClassificationPipeline","audio","feature_extractor","preparedAudios","aud","ZeroShotAudioClassificationPipeline","single","audio_inputs","probs","logits_per_audio","AutomaticSpeechRecognitionPipeline","_call_whisper","_call_wav2vec2","predicted_ids","predicted_sentences","chunk_length_s","force_full_sequences","stride_length_s","chunk_length","max_source_positions","hop_length","chunks","jump","offset_end","subarr","is_first","is_last","input_features","chunk","token_timestamps","full_text","optional","_decode_asr","ImageToTextPipeline","ImageClassificationPipeline","ImageSegmentationPipeline","subtasks_mapping","panoptic","semantic","mask_threshold","overlap_mask_area_threshold","label_ids_to_fuse","target_sizes","subtask","imageSizes","pixel_mask","func","annotation","processed","segmentation","segment","segments_info","maskData","mask","label_id","ZeroShotImageClassificationPipeline","logits_per_image","ObjectDetectionPipeline","percentage","post_process_object_detection","boxes","classes","ZeroShotObjectDetectionPipeline","imageSize","DocumentQuestionAnsweringPipeline","TextToAudioPipeline","DEFAULT_VOCODER_ID","_call_text_to_spectrogram","_call_text_to_waveform","ImageToImagePipeline","reconstruction","squeeze","clamp_","mul_","round_","fromTensor","DepthEstimationPipeline","predicted_depth","prediction","interpolate","formatted","SUPPORTED_TASKS","AutoTokenizer","AutoProcessor","TASK_ALIASES","pipeline","pipelineInfo","pretrainedOptions","promise","loadItems","dispatchCallback","pipelineClass","center_to_corners_format","centerX","centerY","is_zero_shot","out_logits","out_bbox","num_boxes","num_classes","target_size","bbox","logit","maxIndex","post_process_semantic_segmentation","segmentation_data","row","hasLabel","remove_low_and_no_objects","class_logits","mask_logits","object_mask_threshold","num_labels","mask_probs_item","pred_scores_item","pred_labels_item","pred_label","pred_score","check_segment_validity","mask_labels","mask_probs","mask_k","mask_k_area","original_area","mask_probs_k_data","mask_exists","compute_segments","pred_scores","pred_labels","segments","bestScores","mask_probs_i_data","current_segment_id","pred_class","post_process_panoptic_segmentation","class_queries_logits","masks_queries_logits","num_queries","validate_audio_inputs","constraint_to_multiple_of","val","multiple","minVal","maxVal","bankers_round","enforce_size_divisibility","divisor","FeatureExtractor","ImageFeatureExtractor","image_mean","image_std","resample","do_rescale","rescale_factor","do_normalize","do_resize","do_thumbnail","size_divisibility","size_divisor","do_center_crop","crop_size","do_convert_rgb","do_crop_margin","pad_size","do_pad","do_flip_channel_order","thumbnail","input_height","input_width","output_height","output_width","resize","crop_margin","gray_threshold","gray_image","grayscale","minValue","x_min","y_min","x_max","y_max","gray_image_data","crop","pad_image","pixelData","imgDims","padSize","center","constant_values","imageHeight","imageWidth","imageChannels","paddedImageWidth","paddedImageHeight","paddedPixelData","h1","w1","calculateReflectOffset","rescale","get_resize_output_image_size","srcWidth","srcHeight","shortest_edge","longest_edge","max_size","shortResizeFactor","newWidth","newHeight","longResizeFactor","finalWidth","finalHeight","keep_aspect_ratio","ensure_multiple_of","scale_height","scale_width","do_convert_grayscale","rgb","crop_width","crop_height","center_crop","reshaped_input_size","padded","paddedWidth","paddedHeight","temp","original_size","permute","imageData","original_sizes","reshaped_input_sizes","SapiensFeatureExtractor","SegformerFeatureExtractor","PvtImageProcessor","DPTFeatureExtractor","DPTImageProcessor","BitImageProcessor","GLPNFeatureExtractor","CLIPFeatureExtractor","CLIPImageProcessor","ChineseCLIPFeatureExtractor","SiglipImageProcessor","ConvNextFeatureExtractor","crop_pct","resize_shortest_edge","ConvNextImageProcessor","ViTFeatureExtractor","ViTImageProcessor","EfficientNetImageProcessor","include_top","MobileNetV1FeatureExtractor","MobileNetV2FeatureExtractor","MobileNetV3FeatureExtractor","MobileNetV4FeatureExtractor","MobileViTFeatureExtractor","MobileViTImageProcessor","OwlViTFeatureExtractor","Owlv2ImageProcessor","RTDetrImageProcessor","DeiTFeatureExtractor","BeitFeatureExtractor","DonutFeatureExtractor","NougatImageProcessor","DetrFeatureExtractor","maskSize","full","post_process_instance_segmentation","MaskFormerFeatureExtractor","YolosFeatureExtractor","SamImageProcessor","reshape_input_points","is_bounding_box","calculateDimensions","originalImageSize","reshapedImageSize","resizeFactors","add_input_labels","post_process_masks","masks","binarize","output_masks","target_image_size","interpolated_mask","interpolate_4d","binarizedMaskData","generate_crop_boxes","crop_n_layers","overlap_ratio","points_per_crop","crop_n_points_downscale_factor","Swin2SRImageProcessor","VitMatteImageProcessor","trimaps","trimapData","WhisperFeatureExtractor","mel_filters","mel_filter_bank","n_fft","feature_size","window_function","_extract_fbank_features","power","log_mel","max_num_frames","nb_max_frames","maxValue","n_samples","Wav2Vec2FeatureExtractor","_zero_mean_unit_var_norm","variance","SeamlessM4TFeatureExtractor","periodic","fft_length","preemphasis","mel_floor","remove_dc_offset","pad_to_multiple_of","do_normalize_per_mel_bins","return_attention_mask","padded_attention_mask","num_features","num_channels","padded_data","padding_value","numPaddedFrames","view","reshapedNumFrames","attention_mask_data","padded_attention_mask_data","ASTFeatureExtractor","denom","features_data","ClapFeatureExtractor","nb_frequency_bins","frequency_min","frequency_max","mel_filters_slaney","fft_window_size","_get_input_mel","input_mel","longer","nb_max_samples","PyAnnoteFeatureExtractor","samples_to_frames","samples","post_process_speaker_diarization","num_samples","ratio","accumulated_segments","current_speaker","confidence","WeSpeakerFeatureExtractor","min_num_frames","fbank_centering_span","meanData","featuresData","offset1","offset2","offset3","SpeechT5FeatureExtractor","Processor","SamProcessor","WhisperProcessor","Wav2Vec2ProcessorWithLM","PyAnnoteProcessor","SpeechT5Processor","OwlViTProcessor","Florence2Processor","tasks_answer_post_processing_type","task_prompts_without_inputs","task_prompts_with_input","regexes","quad_boxes","bboxes","size_per_bin","construct_prompts","prompts","prompt","replaceAll","post_process_generation","image_size","task_answer_post_processing_type","final_answer","matches","matchAll","locations","preprocessorConfig","feature_extractor_type","image_processor_type","feature_extractor_class","FEATURE_EXTRACTOR_CLASS_MAPPING","PROCESSOR_CLASS_MAPPING","processor_class","loadTokenizer","legacy","createPattern","pattern","invert","Regex","regex","PROBLEMATIC_REGEX_MAP","escapeRegExp","objectToMap","prepareTensorForDecode","clean_up_tokenization","remove_accents","PUNCTUATION_REGEX","PUNCTUATION_ONLY_REGEX","BLOOM_SPLIT_CHARS","AddedToken","single_word","lstrip","rstrip","special","normalized","TokenizerModel","tokens_to_ids","unk_token_id","unk_token","end_of_word_suffix","fuse_unk","fromConfig","WordPieceTokenizer","Unigram","BPE","LegacyTokenizerModel","encode","arr","fused","convert_tokens_to_ids","convert_ids_to_tokens","max_input_chars_per_word","outputTokens","chars","isUnknown","subTokens","currentSubstring","continuing_subword_prefix","moreConfig","piece","unk_id","bos_token","minScore","unk_score","trie","CharTrie","populateNodes","lattice","beginPos","hasSingleNode","sliced","prefixedTokens","commonPrefixSearch","tokenId","tokenScore","len","insert","TokenLattice","tokenized","BYTES_TO_UNICODE","ccs","UNICODE_TO_BYTES","reverseDictionary","use_new_merge_format","merges","bpe_ranks","continuing_subword_suffix","byte_fallback","text_encoder","TextEncoder","ignore_merges","cache","bpe","cached","PriorityQueue","startingNode","next","previousNode","currentNode","_add_node","deleted","newPreviousNode","merged","bpe_token_list","byteTokens","padStart","target_lang","pad_token","Normalizer","BertNormalizer","Precompiled","NormalizerSequence","Replace","NFC","NFKC","NFKD","StripNormalizer","StripAccents","Lowercase","Prepend","strip_left","strip_right","trimStart","trimEnd","prepend","normalizers","normalizer","_tokenize_chinese_chars","stripAccents","_is_control","_clean_text","clean_text","handle_chinese_chars","lowercase","strip_accents","PreTokenizer","BertPreTokenizer","PreTokenizerSequence","WhitespacePreTokenizer","WhitespaceSplit","MetaspacePreTokenizer","ByteLevelPreTokenizer","SplitPreTokenizer","PunctuationPreTokenizer","DigitsPreTokenizer","ReplacePreTokenizer","pre_tokenize_text","pre_tokenize","add_prefix_space","trim_offsets","use_regex","byte_encoder","byte","fullMatch","regexSplit","digit_pattern","individual_digits","PostProcessor","TemplateProcessing","ByteLevelPostProcessor","RobertaProcessing","BertProcessing","PostProcessorSequence","post_process","sep","tokens_pair","middle","after","pair","processedTokens","SpecialToken","type_id","Sequence","Decoder","added_tokens","WordPieceDecoder","MetaspaceDecoder","ByteLevelDecoder","ReplaceDecoder","ByteFallback","FuseDecoder","StripDecoder","DecoderSequence","CTCDecoder","BPEDecoder","decode_chain","text_decoder","new_tokens","previous_byte_tokens","bytes","string","start_cut","stop_cut","cleanup","byte_decoder","fatal","ignoreBOM","convert_tokens_to_string","byteArray","sub_texts","current_sub_text","word_delimiter_token","grouped_tokens","decoders","toks","VitsDecoder","addPrefixSpace","replacement","strRep","str_rep","prepend_scheme","section_index","charsmap","precompiled_charsmap","parts","part","tokenizers","pretokenizers","preTokenizedText","whitespace_split","SPECIAL_TOKEN_ATTRIBUTES","padHelper","value_fn","side","padData","truncateHelper","PreTrainedTokenizer","return_token_type_ids","tokenizerJSON","tokenizerConfig","_tokenizer_config","pre_tokenizer","post_processor","addedToken","additional_special_tokens","added_tokens_regex","getToken","sep_token","model_max_length","remove_space","clean_up_tokenization_spaces","do_lowercase_and_remove_accent","chat_template","_compiled_template_cache","__type","return_tensor","encodedTokens","_encode_plus","flatMap","_encode_text","lowercase_and_remove_accent","sectionTokens","_tokenize_helper","tokens2","decode_args","token_ids","isIntegralNumber","decode_single","get_chat_template","tools","template_dict","conversation","documents","return_dict","tokenizer_kwargs","compiledTemplate","special_tokens_map","rendered","messages","BertTokenizer","AlbertTokenizer","MobileBertTokenizer","SqueezeBertTokenizer","DebertaTokenizer","DebertaV2Tokenizer","HerbertTokenizer","ConvBertTokenizer","RoFormerTokenizer","DistilBertTokenizer","CamembertTokenizer","XLMTokenizer","ElectraTokenizer","T5Tokenizer","GPT2Tokenizer","BartTokenizer","MBartTokenizer","languageRegex","language_codes","lang_to_token","raw_inputs","MBart50Tokenizer","RobertaTokenizer","BloomTokenizer","SPIECE_UNDERLINE","LlamaTokenizer","CodeLlamaTokenizer","XLMRobertaTokenizer","MPNetTokenizer","FalconTokenizer","GPTNeoXTokenizer","EsmTokenizer","Qwen2Tokenizer","GemmaTokenizer","Grok1Tokenizer","src_lang_token","src_lang","tgt_lang_token","tgt_lang","NllbTokenizer","M2M100Tokenizer","WhisperTokenizer","return_language","last_language","returnWordTimestamps","new_chunk","time_offset","previous_tokens","previous_token_timestamps","skip","right_stride_start","last_timestamp","first_timestamp","chunk_len","stride_left","stride_right","current_tokens","current_token_timestamps","resolved_tokens","findLongestCommonSequence","resolved_text","rounded_time","timestamp","resolved_token_timestamps","words","collateWordTimestamps","end_time","start_time","decoded_text","new_chunks","token_timestamp_sequences","leftSequence","leftLength","totalSequence","use_token_timestamp_sequences","total_token_timestamp_sequence","left_token_timestamp_sequence","rightSequence","maxIndices","rightLength","leftStart","leftStop","rightStart","rightStop","elem","matching","leftMid","rightMid","token_indices","combineTokensIntoWords","timings","prepend_punctionations","append_punctuations","word_tokens","splitTokensOnUnicode","splitTokensOnSpaces","mergePunctuations","decode_with_timestamps","decodeWithTimestamps","decoded_full","current_indices","unicode_offset","token_idx","subwords","subword_tokens_list","subword_indices_list","punctuationRegex","subword","subword_tokens","subword_indices","with_space","trimmed","punctuation","prepended","appended","newWords","newTokens","newIndices","CodeGenTokenizer","CLIPTokenizer","SiglipTokenizer","MarianTokenizer","supported_language_codes","matchInfo","remainder","Wav2Vec2CTCTokenizer","BlenderbotTokenizer","BlenderbotSmallTokenizer","SpeechT5Tokenizer","NougatTokenizer","VitsTokenizer","CohereTokenizer","tokenizerName","tokenizer_class","TOKENIZER_CLASS_MAPPING","AudioContext","getFile","audioCTX","sampleRate","decodeAudioData","numberOfChannels","SCALING_FACTOR","getChannelData","generalized_cosine_window","a_0","a_1","factor","PI","cos_vals","cos","hanning","hamming","HERTZ_TO_MEL_MAPPING","freq","log10","min_log_hertz","min_log_mel","logstep","hertz_to_mel","mel_scale","MEL_TO_HERTZ_MAPPING","mels","linspace","num_frequency_bins","num_mel_filters","min_frequency","max_frequency","triangularize_in_mel_space","mel_freqs","fft_freqs","filter_freqs","mel_to_hertz","fft_bin_width","filter_diff","slopes","slope","numFreqs","ret","down","_create_triangular_filter_bank","enorm","_db_conversion_helper","reference","min_value","db_range","logReference","frame_length","pad_mode","onesided","window_length","half_window","padReflect","d1","d1Max","fft","FFT","inputBuffer","outputBuffer","outputBufferSize","transposedMagnitudeData","buffer_size","realTransform","j2","pow","mel_spec","mel_spec_data","amplitude_to_db","power_to_db","isTypedArray","__proto__","arrs","props","comparator","maxSize","_heap","_comparator","_maxSize","peek","_siftUp","smallest","_smallest","_siftUpFrom","poppedValue","_swap","_siftDown","replacedValue","_parent","_left","_right","_greater","maxChild","log2","root","CharTrieNode","child","children","isLeaf","sentence","bosTokenId","eosTokenId","nodes","beginNodes","endNodes","bos","TokenLatticeNode","eos","pos","nodeId","viterbi","rnode","bestScore","bestNode","lnode","backtraceScore","tokenIds","DEVICE_TYPES","cachedResult","q8","int8","uint8","q4","bnb4","q4f16","closure","setPrototypeOf","CONTENT_TYPE_MAP","FileResponse","filePath","Headers","exists","statusText","stats","updateContentType","ReadableStream","controller","enqueue","close","readFile","json","isValidUrl","protocols","validHosts","protocol","hostname","urlOrPath","IS_CI","TESTING_REMOTELY","HF_TOKEN","HF_ACCESS_TOKEN","ERROR_MAPPING","FileCache","request","file","Buffer","outputPath","mkdir","recursive","writeFile","path_or_repo_id","caches","requestURL","pathJoin","localPath","remoteURL","encodeURIComponent","fsCacheKey","proposedCacheKey","toCacheResponse","tryCache","cacheHit","handleError","Response","progressInfo","userAgent","progress","total","contentLength","reader","newLoaded","newBuffer","readResponse","modelPath","jsonData","BROWSER_ENV","WEBWORKER_ENV","createCanvasFunction","ImageDataClass","loadImageFunction","createImageBitmap","rawChannels","metadata","rotate","raw","toBuffer","resolveWithObject","convert","RESAMPLING_MAPPING","fromURL","fromCanvas","fromBlob","ctx","channel_format","newData","red","green","blue","_update","rgba","resampleMethod","numChannels","toCanvas","toSharp","affine","interpolator","fit","kernel","pad","extract","width_offset","height_offset","sourceX","sourceY","destX","destY","y_padding","y_extract","x_padding","x_extract","toBlob","quality","convertToBlob","toTensor","cloned","clonedCanvas","save","toFile","mime","dataURL","downloadLink","click","remove","interpolate_data","in_channels","in_height","in_width","out_height","out_width","x_scale","y_scale","out_img","inStride","outStride","outOffset","x1","y1","x2","y2","w2","w3","w4","yStride","xStride","idx1","idx2","idx3","idx4","cOffset","permute_data","invStride","permutedData","newIndex","exps","sumExps","acc","dot","arr1","arr2","cos_sim","magnitude","indexOfMin","indexOfMax","isPowerOfTwo","number","P2FFT","_csize","table","angle","sin","_width","_bitrev","revShift","createComplexArray","fromComplexArray","complex","res","toComplexArray","transform","_transform4","_realTransform4","inverseTransform","inv","outOff","bitrev","off","_singleTransform2","_singleTransform4","quarterLen","limit","tableBr","tableBi","MBr","MBi","tableCr","tableCi","MCr","MCi","tableDr","tableDi","MDr","MDi","T0r","T0i","T1r","T1i","T2r","T2i","T3r","T3i","evenR","evenI","oddR","oddI","step2","step3","_singleRealTransform2","_singleRealTransform4","halfLen","hquarterLen","MAr","MAi","SA","SB","half","NP2FFT","nextP2","bufferSize","chirp","ichirp","_chirpBuffer","_buffer1","_buffer2","_outBuffer1","_outBuffer2","theta","baseR","baseI","result_mod","result_arg","atan2","i2","_slicedChirpBuffer","_transform","real","ib1","ib2","ob2","ob3","a_real","a_imag","b_real","b_imag","windowSize","outputArray","halfWindowSize","valuesIndex","decimals","output_length","input_length","cost","c0","c1","c2","DataTypeMap","float32","float16","float64","int16","uint16","int32","uint32","int64","uint64","bool","_getitem","iterLength","iterDims","iterSize","_subarray","safeIndex","this_data","o1","o2","totalElements","dimensionSize","reshapedArray","lastArray","sigmoid_","callback","map_","mul","div","div_","add_","sub","sub_","newTensorDims","newOffsets","sliceIndex","offsets","newDims","newBufferSize","originalIndex","keepdim","resultDims","resultIndex","resultMultiplier","normalize_","norm_data","s2","dimsToStride","calc_squeeze_dims","unsqueeze","calc_unsqueeze_dims","flatten_","start_dim","end_dim","dimsToKeepBefore","dimsToFlatten","dimsToKeepAfter","flatten","inferredIndex","productOther","curr","neg_","clamp","targetDims","sizeTensor","lastHiddenStateData","attentionMaskData","returnedData","embedDim","outIndex","attnMaskOffset","attn","avg","layer_norm","normalized_shape","featureDim","stdData","inputData","dimension","boundsCheck","tensors","resultSize","resultType","tensorData","currentDim","correction","inputDims","meanTensor","fullHelper","fill_value","typedArrayCls","zeros","signed","outputData","bit","arrayIndex","bitPosition","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","getPrototypeOf","__esModule","def","definition","toStringTag","scriptUrl"],"sourceRoot":""} \ No newline at end of file diff --git a/assets/dist_transformers/1.21.0-dev.20241109/transformers.min.mjs b/assets/dist_transformers/1.21.0-dev.20241122/transformers.min.mjs similarity index 100% rename from assets/dist_transformers/1.21.0-dev.20241109/transformers.min.mjs rename to assets/dist_transformers/1.21.0-dev.20241122/transformers.min.mjs diff --git a/assets/dist_transformers/1.21.0-dev.20241109/transformers.min.mjs.map b/assets/dist_transformers/1.21.0-dev.20241122/transformers.min.mjs.map similarity index 100% rename from assets/dist_transformers/1.21.0-dev.20241109/transformers.min.mjs.map rename to assets/dist_transformers/1.21.0-dev.20241122/transformers.min.mjs.map diff --git a/assets/dist_transformers/1.21.0-dev.20241109/transformers.mjs b/assets/dist_transformers/1.21.0-dev.20241122/transformers.mjs similarity index 100% rename from assets/dist_transformers/1.21.0-dev.20241109/transformers.mjs rename to assets/dist_transformers/1.21.0-dev.20241122/transformers.mjs diff --git a/assets/dist_transformers/1.21.0-dev.20241109/transformers.mjs.map b/assets/dist_transformers/1.21.0-dev.20241122/transformers.mjs.map similarity index 100% rename from assets/dist_transformers/1.21.0-dev.20241109/transformers.mjs.map rename to assets/dist_transformers/1.21.0-dev.20241122/transformers.mjs.map diff --git a/assets/dist_transformers/Notes.md b/assets/dist_transformers/Notes.md new file mode 100644 index 0000000..066d107 --- /dev/null +++ b/assets/dist_transformers/Notes.md @@ -0,0 +1,7 @@ +## Notes + +This version of Transformers.js distribution was built using the following components:: + +1. ONNX Runtime Web: [1.21.0-dev.20241122-a2ba3cb547](https://www.npmjs.com/package/onnxruntime-web/v/1.21.0-dev.20241122-a2ba3cb547) +2. Transformers.js: [v3 branch](https://github.com/huggingface/transformers.js/commit/7a58d6e11968dd85dc87ce37b2ab37213165889a) +3. Get performance data: [patch](https://github.com/ibelem/transformers.js/commit/5d1416f90d6e0a67dc84757bc6fe9754a86946d7) diff --git a/demos/image-classification/index.js b/demos/image-classification/index.js index 4178365..3ae4c9f 100644 --- a/demos/image-classification/index.js +++ b/demos/image-classification/index.js @@ -3,7 +3,8 @@ // // An example how to run Image Classification with webnn in onnxruntime-web. // -import * as transformers from "../../assets/dist_transformers/1.21.0-dev.20241109/transformers.js"; + +import * as transformers from "../../assets/dist_transformers/1.21.0-dev.20241122/transformers.js"; import { $, $$, @@ -23,7 +24,7 @@ import { transformers.env.backends.onnx.wasm.proxy = false; transformers.env.backends.onnx.wasm.simd = true; transformers.env.backends.onnx.wasm.numThreads = 1; -transformers.env.backends.onnx.wasm.wasmPaths = "../../assets/dist_transformers/1.21.0-dev.20241109/"; +transformers.env.backends.onnx.wasm.wasmPaths = "../../assets/dist_transformers/1.21.0-dev.20241122/"; const useRemoteModels = location.hostname.includes("github.io"); transformers.env.allowRemoteModels = useRemoteModels;