import { a as V, m as y, b as g, j as X, N as U, _ as Y } from "../../index-DSGwv2Yx.js";
import { isPackedTensor as x } from "../../utilities/packed.js";
import { reshape16 as C } from "../reshape16.js";
import { matMulMul as Z } from "../matMulMul.js";
import { matMulGelu as $ } from "../matMulGelu.js";
import ee from "./matMul16_program.js";
import { m as v } from "../../mat_mul-DP86qZtZ.js";
import { r as E } from "../../relu-DTvZKBsZ.js";
import { r as F } from "../../reshape-BIN71H3p.js";
import { t as N } from "../../transpose-Qxz-4os3.js";
function se(m) {
  const { A: s, B: t } = m.inputs, { transposeA: p, transposeB: i, scale: h, activation: c, scaleA: d, scaleB: f, forceOutputShape: r, perm: k, causalMask: w, pastLen: W } = m.attrs, z = m.backend, b = !x(s), B = !x(t);
  if (b && B) {
    const u = d !== void 0 ? y(s, g(d)) : s, l = f !== void 0 ? y(t, g(f)) : t;
    if (w)
      throw new Error("Causal mask is not supported for unpacked MatMul16.");
    let e;
    if (h !== void 0)
      e = Z(u, l, g(h), p, i);
    else if (c === "gelu")
      e = $(u, l);
    else if (c === "relu2") {
      const o = v(u, l, p, i), A = E(o);
      o.dispose(), e = X(A), A.dispose();
    } else c === "relu" ? e = E(v(u, l, p, i)) : e = v(u, l, p, i);
    if (k)
      if (r) {
        const o = F(e, r);
        e.dispose();
        const A = N(o, k);
        return o.dispose(), A;
      } else {
        const o = N(e, k);
        return e.dispose(), o;
      }
    else if (r) {
      const o = F(e, r);
      return e.dispose(), o;
    } else
      return e;
  }
  if (b && !B)
    throw new Error("When using mixed precision, A must be packed if B is packed.");
  if (!b && B)
    throw new Error("When using mixed precision, B must be packed if A is packed.");
  const M = s.shape.length, S = t.shape.length, I = s.shape.slice(0, -2), j = t.shape.slice(0, -2), R = U(I), D = U(j), q = Y(s.shape.slice(0, -2), t.shape.slice(0, -2)), K = Math.max(R, D), L = s.shape[M - 2], T = t.shape[S - 2], _ = s.shape[M - 1] * 2, H = t.shape[S - 1] * 2, G = C(s, [R, s.shape[M - 2], s.shape[M - 1]]), O = C(t, [D, t.shape[S - 2], t.shape[S - 1]]), a = new ee(K, L, T, _, H, p, i), n = [];
  h !== void 0 && (a.useScale(), n.push({ type: "float32", data: [h] })), d !== void 0 && (a.useScaleA(), n.push({ type: "float32", data: [d] })), f !== void 0 && (a.useScaleB(), n.push({ type: "float32", data: [f] })), c !== void 0 && a.useActivation(c), w && (a.useCausalMask(), n.push({ type: "int32", data: [W || 0] }));
  const P = a.outputShape.length;
  r && (m.attrs.originalShape = a.outputShape);
  const J = r ?? q.concat([a.outputShape[P - 2], a.outputShape[P - 1]]);
  a.setOutputShape(J, k);
  const Q = z.runWebGPUProgram(
    a,
    [G, O],
    "packedF16",
    n.length > 0 ? n : void 0
  );
  return G.dispose(), O.dispose(), Q;
}
const te = {
  kernelName: "MatMul16",
  backendName: "webgpu",
  kernelFunc: se
};
V(te);
