```python
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.cpp_extension import load_inline

# Fallback matmuls should at least use TF32 tensor cores.
torch.backends.cuda.matmul.allow_tf32 = True

# ---------------------------------------------------------------------------
# Single fused extension:
#   * vectorized FP32 -> FP16 cast (8 floats per thread, streaming loads)
#   * GEMM on tensor cores (FP16 inputs / FP32 accumulate / FP32 output, or
#     native FAST_16F on FP32 inputs) via a dedicated cuBLAS handle
#   * one-time autotune over: cublasGemmEx algo sweep (ALGO -1..23),
#     cublasGemmEx FAST_16F, and up to 32 cublasLt heuristic algorithms
#   * fused bias + GroupNorm + Swish + per-channel multiply + Swish epilogue
#     (warp-per-128-channel fast path for group_size == 32)
# ---------------------------------------------------------------------------
fused_cuda_source = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <cublas_v2.h>
#include <cublasLt.h>
#include <cuda_runtime.h>
#include <cuda_fp16.h>
#include <functional>
#include <algorithm>
#include <cstdint>

#define FULL_MASK 0xffffffffu

// ------------------------- vectorized FP32 -> FP16 -------------------------
__global__ void cast_f32_f16_vec8_kernel(const float4* __restrict__ in,
                                         float4* __restrict__ out,
                                         long n8) {
    long i = (long)blockIdx.x * blockDim.x + threadIdx.x;
    if (i >= n8) return;
    float4 a = __ldcs(in + 2 * i);
    float4 b = __ldcs(in + 2 * i + 1);
    __half2 h0 = __floats2half2_rn(a.x, a.y);
    __half2 h1 = __floats2half2_rn(a.z, a.w);
    __half2 h2 = __floats2half2_rn(b.x, b.y);
    __half2 h3 = __floats2half2_rn(b.z, b.w);
    float4 o;
    o.x = *reinterpret_cast<float*>(&h0);
    o.y = *reinterpret_cast<float*>(&h1);
    o.z = *reinterpret_cast<float*>(&h2);
    o.w = *reinterpret_cast<float*>(&h3);
    __stcs(out + i, o);
}

__global__ void cast_f32_f16_tail_kernel(const float* __restrict__ in,
                                         __half* __restrict__ out,
                                         long start, long numel) {
    long i = start + (long)blockIdx.x * blockDim.x + threadIdx.x;
    if (i < numel) out[i] = __float2half_rn(__ldcs(in + i));
}

static void cast_to_half(const float* in, void* out, long numel, cudaStream_t stream) {
    const int threads = 256;
    bool aligned = ((((uintptr_t)in) & 15) == 0) && ((((uintptr_t)out) & 15) == 0);
    long n8 = aligned ? (numel >> 3) : 0;
    if (n8 > 0) {
        long blocks = (n8 + threads - 1) / threads;
        cast_f32_f16_vec8_kernel<<<blocks, threads, 0, stream>>>(
            reinterpret_cast<const float4*>(in),
            reinterpret_cast<float4*>(out), n8);
    }
    long start = n8 << 3;
    if (start < numel) {
        long rem = numel - start;
        long blocks = (rem + threads - 1) / threads;
        cast_f32_f16_tail_kernel<<<blocks, threads, 0, stream>>>(
            in, reinterpret_cast<__half*>(out), start, numel);
    }
}

// -------------------- fused epilogue: bias + GN + swish --------------------
// Fast path: group_size == 32 and num_groups % 4 == 0 (one warp = 4 groups).
__global__ void fused_bias_gn_swish_mul_swish_vec4_kernel(
    const float* __restrict__ x,
    const float* __restrict__ bias,
    const float* __restrict__ gn_w,
    const float* __restrict__ gn_b,
    const float* __restrict__ mul_w,
    float* __restrict__ out,
    int num_groups,
    float eps,
    long total_quads)
{
    long warp_id = (long)blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5);
    if (warp_id >= total_quads) return;
    int lane = threadIdx.x & 31;

    long base = warp_id << 7;  // 128 floats per warp
    int ch0 = (int)(((warp_id << 2) % num_groups) << 5);
    int off = ch0 + (lane << 2);

    float4 v = __ldcs(reinterpret_cast<const float4*>(x + base + (lane << 2)));
    float4 b = *reinterpret_cast<const float4*>(bias + off);
    v.x += b.x; v.y += b.y; v.z += b.z; v.w += b.w;

    float s = (v.x + v.y) + (v.z + v.w);
    #pragma unroll
    for (int o = 4; o > 0; o >>= 1) s += __shfl_xor_sync(FULL_MASK, s, o, 8);
    float mean = s * (1.0f / 32.0f);

    float d0 = v.x - mean, d1 = v.y - mean, d2 = v.z - mean, d3 = v.w - mean;
    float ss = fmaf(d0, d0, fmaf(d1, d1, fmaf(d2, d2, d3 * d3)));
    #pragma unroll
    for (int o = 4; o > 0; o >>= 1) ss += __shfl_xor_sync(FULL_MASK, ss, o, 8);
    float rstd = rsqrtf(ss * (1.0f / 32.0f) + eps);

    float4 w = *reinterpret_cast<const float4*>(gn_w + off);
    float4 g = *reinterpret_cast<const float4*>(gn_b + off);
    float4 m = *reinterpret_cast<const float4*>(mul_w + off);

    #define EPILOGUE(val, ww, gg, mm)                      \
        {                                                  \
            float sc = rstd * (ww);                        \
            float y = fmaf(val, sc, (gg) - mean * sc);     \
            y = y / (1.0f + __expf(-y));                   \
            y = y * (mm);                                  \
            y = y / (1.0f + __expf(-y));                   \
            val = y;                                       \
        }
    EPILOGUE(v.x, w.x, g.x, m.x);
    EPILOGUE(v.y, w.y, g.y, m.y);
    EPILOGUE(v.z, w.z, g.z, m.z);
    EPILOGUE(v.w, w.w, g.w, m.w);
    #undef EPILOGUE

    __stcs(reinterpret_cast<float4*>(out + base + (lane << 2)), v);
}

// Generic fallback: one warp per group, arbitrary group_size.
__global__ void fused_bias_gn_swish_mul_swish_generic_kernel(
    const float* __restrict__ x,
    const float* __restrict__ bias,
    const float* __restrict__ gn_w,
    const float* __restrict__ gn_b,
    const float* __restrict__ mul_w,
    float* __restrict__ out,
    int num_groups,
    int group_size,
    float eps,
    long total_groups)
{
    long warp_id = (long)blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5);
    if (warp_id >= total_groups) return;
    int lane = threadIdx.x & 31;

    long base = warp_id * (long)group_size;
    int ch0 = (int)(warp_id % num_groups) * group_size;

    float sum = 0.f, sumsq = 0.f;
    for (int i = lane; i < group_size; i += 32) {
        float v = x[base + i] + bias[ch0 + i];
        sum += v;
        sumsq = fmaf(v, v, sumsq);
    }
    #pragma unroll
    for (int o = 16; o > 0; o >>= 1) {
        sum += __shfl_xor_sync(FULL_MASK, sum, o);
        sumsq += __shfl_xor_sync(FULL_MASK, sumsq, o);
    }
    float inv_n = 1.0f / (float)group_size;
    float mean = sum * inv_n;
    float var = fmaf(-mean, mean, sumsq * inv_n);
    float rstd = rsqrtf(var + eps);

    for (int i = lane; i < group_size; i += 32) {
        int c = ch0 + i;
        float v = x[base + i] + bias[c];
        float sc = rstd * gn_w[c];
        float y = fmaf(v, sc, gn_b[c] - mean * sc);
        y = y / (1.0f + __expf(-y));
        y = y * mul_w[c];
        y = y / (1.0f + __expf(-y));
        out[base + i] = y;
    }
}

static void epilogue_launch(float* h, const float* bias, const float* gnw,
                            const float* gnb, const float* mulw, float* out,
                            long rows, long channels, int num_groups, float eps,
                            cudaStream_t stream) {
    long group_size = channels / num_groups;
    long total_groups = rows * (long)num_groups;
    const int threads = 256;
    const int wpb = threads / 32;
    if (group_size == 32 && (num_groups % 4) == 0) {
        long quads = total_groups / 4;
        long blocks = (quads + wpb - 1) / wpb;
        fused_bias_gn_swish_mul_swish_vec4_kernel<<<blocks, threads, 0, stream>>>(
            h, bias, gnw, gnb, mulw, out, num_groups, eps, quads);
    } else {
        long blocks = (total_groups + wpb - 1) / wpb;
        fused_bias_gn_swish_mul_swish_generic_kernel<<<blocks, threads, 0, stream>>>(
            h, bias, gnw, gnb, mulw, out, num_groups, (int)group_size, eps, total_groups);
    }
}

// ------------------------------ GEMM plumbing ------------------------------
namespace {

struct Plan {
    long M = -1, N = -1, K = -1;
    int engine = 2;      // 0: Lt fp16, 1: gemmEx FAST_16F (fp32 io), 2: gemmEx fp16
    int gemm_algo = -1;  // cublasGemmAlgo_t for engine 2
    cublasLtMatmulAlgo_t algo{};
    size_t ws = 0;
    cublasLtMatmulDesc_t desc = nullptr;
    cublasLtMatrixLayout_t Adesc = nullptr, Bdesc = nullptr, Cdesc = nullptr;
    bool valid = false;
};

Plan g_plan;
cublasHandle_t g_blas = nullptr;
cublasLtHandle_t g_lt = nullptr;
void* g_ws = nullptr;
size_t g_ws_cap = 0;
void* g_xh = nullptr;
size_t g_xh_cap = 0;
const size_t kHandleWs = 64ull << 20;
const size_t kLtWsCap = 256ull << 20;

void init_once() {
    static bool done = false;
    if (done) return;
    done = true;
    TORCH_CHECK(cublasCreate(&g_blas) == CUBLAS_STATUS_SUCCESS, "cublasCreate failed");
    void* p = nullptr;
    if (cudaMalloc(&p, kHandleWs) == cudaSuccess && p != nullptr) {
        cublasSetWorkspace(g_blas, p, kHandleWs);  // intentionally leaked
    }
    if (cublasLtCreate(&g_lt) != CUBLAS_STATUS_SUCCESS) g_lt = nullptr;
}

void* ensure_buf(void** p, size_t* cap, size_t bytes) {
    if (bytes == 0) return nullptr;
    if (*cap < bytes) {
        cudaDeviceSynchronize();
        if (*p) cudaFree(*p);
        *p = nullptr;
        *cap = 0;
        if (cudaMalloc(p, bytes) != cudaSuccess) return nullptr;
        *cap = bytes;
    }
    return *p;
}

void free_lt_objs(Plan& p) {
    if (p.Adesc) { cublasLtMatrixLayoutDestroy(p.Adesc); p.Adesc = nullptr; }
    if (p.Bdesc) { cublasLtMatrixLayoutDestroy(p.Bdesc); p.Bdesc = nullptr; }
    if (p.Cdesc) { cublasLtMatrixLayoutDestroy(p.Cdesc); p.Cdesc = nullptr; }
    if (p.desc)  { cublasLtMatmulDescDestroy(p.desc);    p.desc = nullptr; }
}

void plan_clear() {
    free_lt_objs(g_plan);
    g_plan = Plan();
}

bool make_lt_objs(Plan& p) {
    if (cublasLtMatmulDescCreate(&p.desc, CUBLAS_COMPUTE_32F, CUDA_R_32F) != CUBLAS_STATUS_SUCCESS)
        return false;
    cublasOperation_t opT = CUBLAS_OP_T, opN = CUBLAS_OP_N;
    cublasLtMatmulDescSetAttribute(p.desc, CUBLASLT_MATMUL_DESC_TRANSA, &opT, sizeof(opT));
    cublasLtMatmulDescSetAttribute(p.desc, CUBLASLT_MATMUL_DESC_TRANSB, &opN, sizeof(opN));
    bool ok = (cublasLtMatrixLayoutCreate(&p.Adesc, CUDA_R_16F, p.K, p.N, p.K) == CUBLAS_STATUS_SUCCESS &&
               cublasLtMatrixLayoutCreate(&p.Bdesc, CUDA_R_16F, p.K, p.M, p.K) == CUBLAS_STATUS_SUCCESS &&
               cublasLtMatrixLayoutCreate(&p.Cdesc, CUDA_R_32F, p.N, p.M, p.N) == CUBLAS_STATUS_SUCCESS);
    if (!ok) free_lt_objs(p);
    return ok;
}

float time_op(const std::function<cublasStatus_t()>& fn, int warmup, int iters,
              cudaStream_t stream, bool* ok) {
    for (int i = 0; i < warmup; i++) {
        if (fn() != CUBLAS_STATUS_SUCCESS) { *ok = false; return 1e30f; }
    }
    cudaEvent_t e0, e1;
    cudaEventCreate(&e0);
    cudaEventCreate(&e1);
    cudaEventRecord(e0, stream);
    cublasStatus_t st = CUBLAS_STATUS_SUCCESS;
    for (int i = 0; i < iters; i++) {
        st = fn();
        if (st != CUBLAS_STATUS_SUCCESS) break;
    }
    cudaEventRecord(e1, stream);
    cudaEventSynchronize(e1);
    float ms = 0.f;
    cudaEventElapsedTime(&ms, e0, e1);
    cudaEventDestroy(e0);
    cudaEventDestroy(e1);
    *ok = (st == CUBLAS_STATUS_SUCCESS);
    return *ok ? ms / iters : 1e30f;
}

cublasStatus_t run_gemm(const Plan& p, const float* w32, const __half* w16,
                        const float* x32, const __half* x16, float* out,
                        cudaStream_t stream) {
    const float alpha = 1.0f, beta = 0.0f;
    long M = p.M, N = p.N, K = p.K;
    if (p.engine == 0) {
        return cublasLtMatmul(g_lt, p.desc, &alpha,
                              w16, p.Adesc, x16, p.Bdesc, &beta,
                              out, p.Cdesc, out, p.Cdesc,
                              &p.algo, g_ws, p.ws, stream);
    }
    cublasSetStream(g_blas, stream);
    if (p.engine == 1) {
        return cublasGemmEx(g_blas, CUBLAS_OP_T, CUBLAS_OP_N,
                            (int)N, (int)M, (int)K, &alpha,
                            w32, CUDA_R_32F, (int)K,
                            x32, CUDA_R_32F, (int)K,
                            &beta, out, CUDA_R_32F, (int)N,
                            CUBLAS_COMPUTE_32F_FAST_16F, CUBLAS_GEMM_DEFAULT);
    }
    return cublasGemmEx(g_blas, CUBLAS_OP_T, CUBLAS_OP_N,
                        (int)N, (int)M, (int)K, &alpha,
                        w16, CUDA_R_16F, (int)K,
                        x16, CUDA_R_16F, (int)K,
                        &beta, out, CUDA_R_32F, (int)N,
                        CUBLAS_COMPUTE_32F, (cublasGemmAlgo_t)p.gemm_algo);
}

void autotune(const float* x32, const float* w32, const __half* w16,
              __half* xh, float* out, long M, long N, long K,
              cudaStream_t stream) {
    plan_clear();
    const float alpha = 1.0f, beta = 0.0f;
    Plan best;
    best.M = M; best.N = N; best.K = K;
    best.engine = 2; best.gemm_algo = -1;
    float best_t = 1e30f;
    bool have = false;
    bool ok = false;

    // ---- cublasGemmEx fp16: sweep DEFAULT + ALGO0..23 ----
    for (int a = -1; a < 24; a++) {
        auto fn = [&]() -> cublasStatus_t {
            cublasSetStream(g_blas, stream);
            return cublasGemmEx(g_blas, CUBLAS_OP_T, CUBLAS_OP_N,
                                (int)N, (int)M, (int)K, &alpha,
                                w16, CUDA_R_16F, (int)K,
                                xh, CUDA_R_16F, (int)K,
                                &beta, out, CUDA_R_32F, (int)N,
                                CUBLAS_COMPUTE_32F, (cublasGemmAlgo_t)a);
        };
        float t = time_op(fn, 1, 3, stream, &ok);
        if (ok && t < best_t) {
            best_t = t; best.engine = 2; best.gemm_algo = a; have = true;
        }
    }

    // ---- cublasGemmEx FAST_16F on fp32 inputs (no cast needed) ----
    {
        auto fn = [&]() -> cublasStatus_t {
            cublasSetStream(g_blas, stream);
            return cublasGemmEx(g_blas, CUBLAS_OP_T, CUBLAS_OP_N,
                                (int)N, (int)M, (int)K, &alpha,
                                w32, CUDA_R_32F, (int)K,
                                x32, CUDA_R_32F, (int)K,
                                &beta, out, CUDA_R_32F, (int)N,
                                CUBLAS_COMPUTE_32F_FAST_16F, CUBLAS_GEMM_DEFAULT);
        };
        float t = time_op(fn, 1, 3, stream, &ok);
        if (ok && t < best_t) {
            best_t = t; best.engine = 1; have = true;
        }
    }

    // ---- cublasLt fp16 heuristic search ----
    if (g_lt != nullptr) {
        Plan tmp; tmp.M = M; tmp.N = N; tmp.K = K;
        if (make_lt_objs(tmp)) {
            cublasLtMatmulPreference_t pref;
            if (cublasLtMatmulPreferenceCreate(&pref) == CUBLAS_STATUS_SUCCESS) {
                size_t maxws = kLtWsCap;
                cublasLtMatmulPreferenceSetAttribute(
                    pref, CUBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES, &maxws, sizeof(maxws));
                cublasLtMatmulHeuristicResult_t hres[32];
                int hc = 0;
                cublasLtMatmulAlgoGetHeuristic(g_lt, tmp.desc, tmp.Adesc, tmp.Bdesc,
                                               tmp.Cdesc, tmp.Cdesc, pref, 32, hres, &hc);
                for (int i = 0; i < hc; i++) {
                    if (hres[i].state != CUBLAS_STATUS_SUCCESS) continue;
                    size_t aws = hres[i].workspaceSize;
                    if (aws > kLtWsCap) continue;
                    if (aws > 0 && ensure_buf(&g_ws, &g_ws_cap, aws) == nullptr) continue;
                    cublasLtMatmulAlgo_t algo = hres[i].algo;
                    auto fn = [&]() -> cublasStatus_t {
                        return cublasLtMatmul(g_lt, tmp.desc, &alpha,
                                              w16, tmp.Adesc, xh, tmp.Bdesc, &beta,
                                              out, tmp.Cdesc, out, tmp.Cdesc,
                                              &algo, g_ws, aws, stream);
                    };
                    float t = time_op(fn, 1, 3, stream, &ok);
                    if (ok && t < best_t) {
                        best_t = t; best.engine = 0; best.algo = algo;
                        best.ws = aws; have = true;
                    }
                }
                cublasLtMatmulPreferenceDestroy(pref);
            }
            free_lt_objs(tmp);
        }
    }

    if (have && best.engine == 0) {
        if (!make_lt_objs(best)) {
            best.engine = 2; best.gemm_algo = -1;
        }
    }
    g_plan = best;
    g_plan.valid = true;
}

}  // namespace

torch::Tensor fused_forward_cuda(torch::Tensor x, torch::Tensor w, torch::Tensor w_half,
                                 torch::Tensor bias, torch::Tensor gn_w,
                                 torch::Tensor gn_b, torch::Tensor mul_w,
                                 int64_t num_groups, double eps) {
    TORCH_CHECK(x.is_cuda() && w.is_cuda(), "inputs must be CUDA tensors");
    TORCH_CHECK(x.scalar_type() == at::kFloat, "x must be float32");
    const c10::cuda::CUDAGuard device_guard(x.device());
    init_once();

    auto xc = x.contiguous();
    auto wc = w.contiguous();
    auto whc = w_half.contiguous();
    auto bc = bias.contiguous();
    auto gwc = gn_w.contiguous();
    auto gbc = gn_b.contiguous();
    auto mc = mul_w.contiguous();

    long K = xc.size(-1);
    long M = xc.numel() / K;
    long N = wc.size(0);
    TORCH_CHECK(wc.size(1) == K, "weight shape mismatch");

    auto out = at::empty({M, N}, xc.options());
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();

    bool need_plan = !(g_plan.valid && g_plan.M == M && g_plan.N == N && g_plan.K == K);

    if (need_plan) {
        TORCH_CHECK(ensure_buf(&g_xh, &g_xh_cap, (size_t)M * (size_t)K * 2) != nullptr,
                    "half buffer allocation failed");
        cast_to_half(xc.data_ptr<float>(), g_xh, xc.numel(), stream);
        autotune(xc.data_ptr<float>(), wc.data_ptr<float>(),
                 reinterpret_cast<const __half*>(whc.data_ptr()),
                 reinterpret_cast<__half*>(g_xh), out.data_ptr<float>(),
                 M, N, K, stream);
    }

    const __half* xh = nullptr;
    if (g_plan.engine != 1) {
        TORCH_CHECK(ensure_buf(&g_xh, &g_xh_cap, (size_t)M * (size_t)K * 2) != nullptr,
                    "half buffer allocation failed");
        cast_to_half(xc.data_ptr<float>(), g_xh, xc.numel(), stream);
        xh = reinterpret_cast<const __half*>(g_xh);
    }

    TORCH_CHECK(run_gemm(g_plan, wc.data_ptr<float>(),
                         reinterpret_cast<const __half*>(whc.data_ptr()),
                         xc.data_ptr<float>(), xh, out.data_ptr<float>(),
                         stream) == CUBLAS_STATUS_SUCCESS, "GEMM failed");

    epilogue_launch(out.data_ptr<float>(), bc.data_ptr<float>(),
                    gwc.data_ptr<float>(), gbc.data_ptr<float>(),
                    mc.data_ptr<float>(), out.data_ptr<float>(),
                    M, N, (int)num_groups, (float)eps, stream);
    return out;
}
"""

fused_cpp_source = (
    "torch::Tensor fused_forward_cuda(torch::Tensor x, torch::Tensor w, "
    "torch::Tensor w_half, torch::Tensor bias, torch::Tensor gn_w, "
    "torch::Tensor gn_b, torch::Tensor mul_w, int64_t num_groups, double eps);"
)

fused_ops = load_inline(
    name="fused_gemm_gn_swish_v6",
    cpp_sources=fused_cpp_source,
    cuda_sources=fused_cuda_source,
    functions=["fused_forward_cuda"],
    verbose=False,
    extra_cflags=["-O3"],
    extra_cuda_cflags=["-O3", "--use_fast_math"],
    extra_ldflags=["-lcublas", "-lcublasLt"],
)


class ModelNew(nn.Module):
    """
    Optimized model:
      * One fused CUDA entry point for the whole forward pass.
      * GEMM on tensor cores (FP16 inputs, FP32 accumulate/output, or native
        FAST_16F on FP32 inputs) using a dedicated cuBLAS handle with a large
        workspace.
      * One-time autotuning across cublasGemmEx algorithms, FAST_16F mode,
        and up to 32 cublasLt heuristic algorithms (including split-K
        variants with a large workspace budget).
      * Cached half-precision weight and activations buffer.
      * Fused bias + GroupNorm + Swish + Multiply + Swish epilogue kernel
        with a warp-per-128-channels vectorized fast path.
    """
    def __init__(self, in_features, out_features, num_groups, multiply_weight_shape):
        super(ModelNew, self).__init__()
        self.gemm = nn.Linear(in_features, out_features)
        self.group_norm = nn.GroupNorm(num_groups, out_features)
        self.multiply_weight = nn.Parameter(torch.randn(multiply_weight_shape))
        self.num_groups = num_groups
        self.eps = self.group_norm.eps
        self._w_half = None
        self._w_half_key = None
        self._fwd = fused_ops.fused_forward_cuda

    def _half_weight(self):
        w = self.gemm.weight
        key = (w._version, w.data_ptr(), w.device)
        if self._w_half is None or self._w_half_key != key:
            self._w_half = w.detach().half().contiguous()
            self._w_half_key = key
        return self._w_half

    def forward(self, x):
        if x.is_cuda and x.dtype == torch.float32:
            two_d = x.dim() == 2
            x2 = x if two_d else x.reshape(-1, x.shape[-1])
            y = self._fwd(
                x2,
                self.gemm.weight,
                self._half_weight(),
                self.gemm.bias,
                self.group_norm.weight,
                self.group_norm.bias,
                self.multiply_weight,
                self.num_groups,
                self.eps,
            )
            return y if two_d else y.view(*x.shape[:-1], y.shape[-1])
        # Fallback for CPU / non-float32 inputs
        x = self.gemm(x)
        x = self.group_norm(x)
        x = x * torch.sigmoid(x)
        x = x * self.multiply_weight
        x = x * torch.sigmoid(x)
        return x
```