File size: 12,967 Bytes
3386f25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/*
StyleForge - Fused Feed-Forward Network Kernel

Fuses: Linear → GELU → Linear → Bias → Residual

Key Optimizations:
- Single kernel launch for entire FFN block
- Shared memory for input and intermediate values
- Inline GELU activation
- Residual connection fused in
- Vectorized memory access

Performance Target: 4-5x speedup over PyTorch sequential implementation
*/

#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <math.h>

// ============================================
// CUDA Error Checking
// ============================================
#define CUDA_CHECK(call) \
    do { \
        cudaError_t err = call; \
        if (err != cudaSuccess) { \
            printf("CUDA error at %s:%d: %s\n", __FILE__, __LINE__, \
                   cudaGetErrorString(err)); \
            std::abort(); \
        } \
    } while (0)

// ============================================
// Configuration
// ============================================
#define TILE_SIZE 16
#define WARP_SIZE 32

// ============================================
// GELU Activation (Inline)
// ============================================

__device__ __forceinline__ float gelu(float x) {
    // GELU approximation: 0.5 * x * (1 + tanh(sqrt(2/pi) * (x + 0.044715 * x^3)))
    const float sqrt_2_over_pi = 0.7978845608f;
    const float coeff = 0.044715f;
    float x_cubed = x * x * x;
    float tanh_arg = sqrt_2_over_pi * (x + coeff * x_cubed);

    // Fast tanh approximation using exp
    float tanh_val;
    asm volatile("tanh.approx.f32 %0, %1;" : "=f"(tanh_val) : "f"(tanh_arg));

    return 0.5f * x * (1.0f + tanh_val);
}

// Alternative: Exact GELU using erf
__device__ __forceinline__ float gelu_exact(float x) {
    return 0.5f * x * (1.0f + erff(x * 0.70710678f));
}

// ============================================
// Vectorized GEMM Helper
// ============================================

template<int N>
__device__ __forceinline__ float dot_product(
    const float* __restrict__ a,
    const float* __restrict__ b,
    int offset_a,
    int offset_b,
    int stride_b
) {
    float sum = 0.0f;
    #pragma unroll
    for (int i = 0; i < N; i++) {
        sum += a[offset_a + i] * b[offset_b + i * stride_b];
    }
    return sum;
}

// ============================================
// Fused FFN Kernel V1
// ============================================

template<int EMBED_DIM, int FFN_DIM>
__global__ void fused_ffn_kernel_v1(
    const float* __restrict__ input,      // [B, S, E]
    const float* __restrict__ fc1_weight, // [E, F]
    const float* __restrict__ fc1_bias,   // [F]
    const float* __restrict__ fc2_weight, // [F, E]
    const float* __restrict__ fc2_bias,   // [E]
    float* __restrict__ output,           // [B, S, E]
    int batch_size,
    int seq_len,
    int embed_dim,
    int ffn_dim
) {
    // Grid: (seq_len, batch_size)
    int token_idx = blockIdx.x;
    int batch_idx = blockIdx.y;
    int tid = threadIdx.x;

    if (token_idx >= seq_len) return;

    // Shared memory for input and intermediate
    __shared__ float s_input[EMBED_DIM];
    __shared__ float s_intermediate[FFN_DIM];

    // Load input to shared memory
    if (tid < EMBED_DIM) {
        int input_idx = ((int64_t)batch_idx * seq_len + token_idx) * embed_dim + tid;
        s_input[tid] = input[input_idx];
    }
    __syncthreads();

    // ============================================
    // Stage 1: FC1 (Linear) + GELU Activation
    // ============================================

    if (tid < FFN_DIM) {
        float val = fc1_bias[tid];  // Start with bias

        // Matrix-vector multiply: input @ fc1_weight
        #pragma unroll 4
        for (int i = 0; i < EMBED_DIM; i++) {
            val += s_input[i] * fc1_weight[i * ffn_dim + tid];
        }

        // Apply GELU activation
        s_intermediate[tid] = gelu(val);
    }
    __syncthreads();

    // ============================================
    // Stage 2: FC2 (Linear) + Bias + Residual
    // ============================================

    if (tid < EMBED_DIM) {
        float val = fc2_bias[tid];  // Start with bias

        // Matrix-vector multiply: intermediate @ fc2_weight
        #pragma unroll 4
        for (int i = 0; i < FFN_DIM; i++) {
            val += s_intermediate[i] * fc2_weight[i * embed_dim + tid];
        }

        // Add residual connection
        val += s_input[tid];

        // Write output
        int out_idx = ((int64_t)batch_idx * seq_len + token_idx) * embed_dim + tid;
        output[out_idx] = val;
    }
}

// ============================================
// Fused FFN Kernel V2 (Optimized with float4)
// ============================================

template<int EMBED_DIM, int FFN_DIM>
__global__ void fused_ffn_kernel_v2(
    const float* __restrict__ input,
    const float* __restrict__ fc1_weight,
    const float* __restrict__ fc1_bias,
    const float* __restrict__ fc2_weight,
    const float* __restrict__ fc2_bias,
    float* __restrict__ output,
    int batch_size,
    int seq_len,
    int embed_dim,
    int ffn_dim
) {
    // Vectorized memory loads using float4
    const float4* input_vec = reinterpret_cast<const float4*>(input);
    const float4* fc1_vec = reinterpret_cast<const float4*>(fc1_weight);
    float4* output_vec = reinterpret_cast<float4*>(output);

    int token_idx = blockIdx.x;
    int batch_idx = blockIdx.y;
    int tid = threadIdx.x;

    if (token_idx >= seq_len) return;

    // Shared memory (padded for float4 alignment)
    __shared__ float s_input[EMBED_DIM];
    __shared__ float s_intermediate[FFN_DIM];

    // Vectorized load of input
    int vec_size = embed_dim / 4;
    int input_vec_offset = ((int64_t)batch_idx * seq_len + token_idx) * vec_size;

    if (tid * 4 < EMBED_DIM) {
        float4 vec = input_vec[input_vec_offset + tid];
        s_input[tid * 4 + 0] = vec.x;
        s_input[tid * 4 + 1] = vec.y;
        s_input[tid * 4 + 2] = vec.z;
        s_input[tid * 4 + 3] = vec.w;
    }
    __syncthreads();

    // FC1 + GELU
    if (tid < FFN_DIM) {
        float val = fc1_bias[tid];
        #pragma unroll 4
        for (int i = 0; i < EMBED_DIM; i++) {
            val += s_input[i] * fc1_weight[i * ffn_dim + tid];
        }
        s_intermediate[tid] = gelu(val);
    }
    __syncthreads();

    // FC2 + Bias + Residual
    if (tid * 4 < EMBED_DIM) {
        float vals[4];
        #pragma unroll
        for (int j = 0; j < 4; j++) {
            int out_dim = tid * 4 + j;
            if (out_dim < EMBED_DIM) {
                vals[j] = fc2_bias[out_dim];
                #pragma unroll 4
                for (int i = 0; i < FFN_DIM; i++) {
                    vals[j] += s_intermediate[i] * fc2_weight[i * embed_dim + out_dim];
                }
                vals[j] += s_input[out_dim];  // Residual
            }
        }

        // Vectorized store
        int out_vec_offset = ((int64_t)batch_idx * seq_len + token_idx) * vec_size + tid;
        if (tid * 4 < EMBED_DIM) {
            float4 vec;
            vec.x = vals[0];
            vec.y = vals[1];
            vec.z = vals[2];
            vec.w = vals[3];
            output_vec[out_vec_offset] = vec;
        }
    }
}

// ============================================
// Launcher Function
// ============================================

torch::Tensor fused_ffn_forward(
    torch::Tensor input,
    torch::Tensor fc1_weight,
    torch::Tensor fc1_bias,
    torch::Tensor fc2_weight,
    torch::Tensor fc2_bias,
    bool use_vectorized = true
) {
    TORCH_CHECK(input.device().is_cuda(), "Input must be on CUDA");
    TORCH_CHECK(input.dtype() == torch::kFloat32, "Input must be float32");

    const int batch_size = input.size(0);
    const int seq_len = input.size(1);
    const int embed_dim = input.size(2);
    const int ffn_dim = fc1_bias.size(0);

    auto output = torch::zeros_like(input);

    dim3 block(512);  // Threads per block
    dim3 grid(seq_len, batch_size);

    int smem_size = sizeof(float) * (embed_dim + ffn_dim);

    // Launch appropriate kernel based on dimensions
    // Since template parameters must be compile-time constants,
    // we use a series of if-else checks

    if (embed_dim == 128 && ffn_dim == 512) {
        if (use_vectorized) {
            fused_ffn_kernel_v2<128, 512><<<grid, block, smem_size>>>(
                input.data_ptr<float>(), fc1_weight.data_ptr<float>(),
                fc1_bias.data_ptr<float>(), fc2_weight.data_ptr<float>(),
                fc2_bias.data_ptr<float>(), output.data_ptr<float>(),
                batch_size, seq_len, embed_dim, ffn_dim);
        } else {
            fused_ffn_kernel_v1<128, 512><<<grid, block, smem_size>>>(
                input.data_ptr<float>(), fc1_weight.data_ptr<float>(),
                fc1_bias.data_ptr<float>(), fc2_weight.data_ptr<float>(),
                fc2_bias.data_ptr<float>(), output.data_ptr<float>(),
                batch_size, seq_len, embed_dim, ffn_dim);
        }
    } else if (embed_dim == 256 && ffn_dim == 1024) {
        if (use_vectorized) {
            fused_ffn_kernel_v2<256, 1024><<<grid, block, smem_size>>>(
                input.data_ptr<float>(), fc1_weight.data_ptr<float>(),
                fc1_bias.data_ptr<float>(), fc2_weight.data_ptr<float>(),
                fc2_bias.data_ptr<float>(), output.data_ptr<float>(),
                batch_size, seq_len, embed_dim, ffn_dim);
        } else {
            fused_ffn_kernel_v1<256, 1024><<<grid, block, smem_size>>>(
                input.data_ptr<float>(), fc1_weight.data_ptr<float>(),
                fc1_bias.data_ptr<float>(), fc2_weight.data_ptr<float>(),
                fc2_bias.data_ptr<float>(), output.data_ptr<float>(),
                batch_size, seq_len, embed_dim, ffn_dim);
        }
    } else if (embed_dim == 512 && ffn_dim == 2048) {
        if (use_vectorized) {
            fused_ffn_kernel_v2<512, 2048><<<grid, block, smem_size>>>(
                input.data_ptr<float>(), fc1_weight.data_ptr<float>(),
                fc1_bias.data_ptr<float>(), fc2_weight.data_ptr<float>(),
                fc2_bias.data_ptr<float>(), output.data_ptr<float>(),
                batch_size, seq_len, embed_dim, ffn_dim);
        } else {
            fused_ffn_kernel_v1<512, 2048><<<grid, block, smem_size>>>(
                input.data_ptr<float>(), fc1_weight.data_ptr<float>(),
                fc1_bias.data_ptr<float>(), fc2_weight.data_ptr<float>(),
                fc2_bias.data_ptr<float>(), output.data_ptr<float>(),
                batch_size, seq_len, embed_dim, ffn_dim);
        }
    } else if (embed_dim == 768 && ffn_dim == 3072) {
        if (use_vectorized) {
            fused_ffn_kernel_v2<768, 3072><<<grid, block, smem_size>>>(
                input.data_ptr<float>(), fc1_weight.data_ptr<float>(),
                fc1_bias.data_ptr<float>(), fc2_weight.data_ptr<float>(),
                fc2_bias.data_ptr<float>(), output.data_ptr<float>(),
                batch_size, seq_len, embed_dim, ffn_dim);
        } else {
            fused_ffn_kernel_v1<768, 3072><<<grid, block, smem_size>>>(
                input.data_ptr<float>(), fc1_weight.data_ptr<float>(),
                fc1_bias.data_ptr<float>(), fc2_weight.data_ptr<float>(),
                fc2_bias.data_ptr<float>(), output.data_ptr<float>(),
                batch_size, seq_len, embed_dim, ffn_dim);
        }
    } else if (embed_dim == 1024 && ffn_dim == 4096) {
        if (use_vectorized) {
            fused_ffn_kernel_v2<1024, 4096><<<grid, block, smem_size>>>(
                input.data_ptr<float>(), fc1_weight.data_ptr<float>(),
                fc1_bias.data_ptr<float>(), fc2_weight.data_ptr<float>(),
                fc2_bias.data_ptr<float>(), output.data_ptr<float>(),
                batch_size, seq_len, embed_dim, ffn_dim);
        } else {
            fused_ffn_kernel_v1<1024, 4096><<<grid, block, smem_size>>>(
                input.data_ptr<float>(), fc1_weight.data_ptr<float>(),
                fc1_bias.data_ptr<float>(), fc2_weight.data_ptr<float>(),
                fc2_bias.data_ptr<float>(), output.data_ptr<float>(),
                batch_size, seq_len, embed_dim, ffn_dim);
        }
    } else {
        // Generic fallback - use PyTorch for unsupported dimensions
        // For now, return the output as-is (no-op)
        // In production, we'd want to either:
        // 1. Add more template specializations, or
        // 2. Fall back to a non-templated kernel
        TORCH_CHECK(false,
            "Unsupported FFN dimensions: embed_dim=", embed_dim,
            ", ffn_dim=", ffn_dim, ". Supported: (128,512), (256,1024), (512,2048), (768,3072), (1024,4096)");
    }

    CUDA_CHECK(cudaGetLastError());

    return output;
}

// ============================================
// Pybind11 Module
// ============================================

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &fused_ffn_forward, "Fused FFN (CUDA)");
}