Merge pull request 'finish embeddingbag #3' (#149) from wwmm/GPUCodeForces:embeddingbag into main

This commit is contained in:
Kuohais 2025-11-18 10:21:13 +08:00
commit cefbbe0b95
4 changed files with 275 additions and 0 deletions

View File

@ -0,0 +1,96 @@
# embeddingbag_cuda.py
import torch
from torch.utils.cpp_extension import load_inline
from embeddingbag_torch import BATCH_SIZE, EMB_DIM, VOCAB_SIZE # 导入维度常量
N_ELEMENTS = BATCH_SIZE * EMB_DIM
class ModelNew(torch.nn.Module):
def __init__(self, embedding_weight):
super().__init__()
self.register_buffer('weight', embedding_weight)
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
#include <torch/extension.h>
torch::Tensor embbag_forward_cuda(torch::Tensor input, torch::Tensor offsets, torch::Tensor weight);
"""
cuda_source = """
#include <cuda_runtime.h>
#include <cmath>
#define BLOCK_SIZE 256
__global__ void embbag_safe_kernel(
const long* input,
const long* offsets,
const float* weight,
float* output,
int num_batches, int feature_dim, int max_total_indices
) {
int batch_idx = blockIdx.x;
if (batch_idx >= num_batches) return;
int feature_idx = threadIdx.x;
if (feature_idx >= feature_dim) return;
long start_idx = offsets[batch_idx];
long end_idx = (batch_idx == num_batches - 1) ? max_total_indices : offsets[batch_idx + 1];
long seq_len = end_idx - start_idx;
float final_sum = 0.0f;
if (seq_len > 0) {
for (long i = start_idx; i < end_idx; ++i) {
long vocab_index = input[i];
final_sum += weight[vocab_index * feature_dim + feature_idx];
}
output[batch_idx * feature_dim + feature_idx] = final_sum / (float)seq_len;
} else {
output[batch_idx * feature_dim + feature_idx] = 0.0f; // Handle empty sequence
}
}
torch::Tensor embbag_forward_cuda(torch::Tensor input, torch::Tensor offsets, torch::Tensor weight) {
TORCH_CHECK(input.is_cuda(), "Input must be a CUDA tensor");
TORCH_CHECK(input.dtype() == torch::kLong, "Input indices must be LongTensor");
TORCH_CHECK(offsets.dtype() == torch::kLong, "Offsets must be LongTensor");
input = input.contiguous();
offsets = offsets.contiguous();
weight = weight.contiguous();
int num_batches = offsets.size(0);
int feature_dim = weight.size(1);
int max_total_indices = input.size(0);
auto output = torch::empty({num_batches, feature_dim}, input.options().dtype(torch::kFloat32));
embbag_safe_kernel<<<num_batches, feature_dim>>>(
input.data_ptr<long>(),
offsets.data_ptr<long>(),
weight.data_ptr<float>(),
output.data_ptr<float>(),
num_batches, feature_dim, max_total_indices
);
return output;
}
"""
self.embbag_op = load_inline(
name="embbag_fused_op_safe_final_v2",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["embbag_forward_cuda"],
extra_cuda_cflags=["-O3", "--use_fast_math"],
verbose=True
)
def forward(self, input: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:
return self.embbag_op.embbag_forward_cuda(input, offsets, self.weight)

View File

@ -0,0 +1,42 @@
# embeddingbag_torch.py
import torch
import torch.nn as nn
import torch.nn.functional as F
BATCH_SIZE = 1024
EMB_DIM = 256
VOCAB_SIZE = 50000
class Model(nn.Module):
def __init__(self, embedding_weight):
super().__init__()
self.criterion = nn.EmbeddingBag(
VOCAB_SIZE, EMB_DIM, mode='mean', sparse=False, _weight=embedding_weight
)
def forward(self, input: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:
return self.criterion(input, offsets)
def get_inputs():
AVG_LEN = 10
TOTAL_INDICES = BATCH_SIZE * AVG_LEN
indices = torch.randint(0, VOCAB_SIZE, (TOTAL_INDICES,), dtype=torch.long)
offsets = [0]
current_offset = 0
for _ in range(BATCH_SIZE - 1):
seq_len = torch.randint(1, AVG_LEN * 2, (1,)).item()
current_offset += seq_len
offsets.append(current_offset)
offsets = torch.tensor(offsets, dtype=torch.long)
if offsets[-1].item() > indices.shape[0]:
indices = indices[:offsets[-1].item()]
return [indices.cuda(), offsets.cuda()]
def get_init_inputs():
weight = torch.randn(VOCAB_SIZE, EMB_DIM, dtype=torch.float32)
return [weight]

49
S1/wwmm_#3/prompt.txt Normal file
View File

@ -0,0 +1,49 @@
You write custom CUDA kernels to replace the pytorch operators in the given architecture to get speedups.
You have complete freedom to choose the set of operators you want to replace. You may make the decision to replace some operators with custom CUDA kernels and leave others unchanged. You may replace multiple operators with custom implementations, consider operator fusion opportunities (combining multiple operators into a single kernel, for example, combining matmul+relu), or algorithmic changes (such as online softmax). You are only limited by your imagination.
Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is:
```python
# embeddingbag_torch.py
import torch
import torch.nn as nn
import torch.nn.functional as F
BATCH_SIZE = 1024
EMB_DIM = 256
VOCAB_SIZE = 50000
class Model(nn.Module):
def __init__(self, embedding_weight):
super().__init__()
self.criterion = nn.EmbeddingBag(
VOCAB_SIZE, EMB_DIM, mode='mean', sparse=False, _weight=embedding_weight
)
def forward(self, input: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor:
return self.criterion(input, offsets)
def get_inputs():
AVG_LEN = 10
TOTAL_INDICES = BATCH_SIZE * AVG_LEN
indices = torch.randint(0, VOCAB_SIZE, (TOTAL_INDICES,), dtype=torch.long)
offsets = [0]
current_offset = 0
for _ in range(BATCH_SIZE - 1):
seq_len = torch.randint(1, AVG_LEN * 2, (1,)).item()
current_offset += seq_len
offsets.append(current_offset)
offsets = torch.tensor(offsets, dtype=torch.long)
if offsets[-1].item() > indices.shape[0]:
indices = indices[:offsets[-1].item()]
return [indices.cuda(), offsets.cuda()]
def get_init_inputs():
weight = torch.randn(VOCAB_SIZE, EMB_DIM, dtype=torch.float32)
return [weight]

88
S1/wwmm_#3/run_code.py Normal file
View File

@ -0,0 +1,88 @@
###########################################################
# 性能和精度验证程序
###########################################################
import torch
import torch.nn as nn
import time
from embeddingbag_torch import Model, get_inputs, get_init_inputs
from embeddingbag_cuda import ModelNew
def run_benchmark():
# 检查 CUDA 是否可用
if not torch.cuda.is_available():
print("CUDA 不可用,请确保您有可用的 NVIDIA GPU 并已正确安装 PyTorch CUDA 版本。")
return
else:
device = torch.device("cuda")
# 初始化模型
init_inputs = get_init_inputs()
init_inputs = [
x.cuda(device=device) if isinstance(x, torch.Tensor) else x for x in init_inputs
]
inputs = get_inputs()
inputs = [
x.cuda(device=device) if isinstance(x, torch.Tensor) else x for x in inputs
]
torch_model = Model(*init_inputs).cuda()
cuda_model = ModelNew(*init_inputs).cuda()
torch_model.eval()
cuda_model.eval()
print("-------------------- 精度对齐验证 --------------------")
with torch.no_grad():
output_torch = torch_model(*inputs)
output_cuda = cuda_model(*inputs)
# 更严格的精度检查
abs_diff = (output_torch - output_cuda).abs()
max_diff = abs_diff.max().item()
mean_diff = abs_diff.mean().item()
print(f"最大差异: {max_diff:.6f}")
print(f"平均差异: {mean_diff:.6f}")
precision_flag = torch.allclose(output_torch, output_cuda, rtol=1e-05, atol=1e-05)
if precision_flag:
print("✅ 精度对齐:两个模型的输出结果非常接近。")
else:
print("❌ 精度不一致!")
print("\n-------------------- 性能加速比测试 --------------------")
num_iterations = 1000 # 增加迭代次数以获得更准确的时间测量
# Warm up
for _ in range(100):
_ = torch_model(*inputs)
_ = cuda_model(*inputs)
# PyTorch 模型计时
torch.cuda.synchronize()
start_time = time.time()
for _ in range(num_iterations):
_ = torch_model(*inputs)
torch.cuda.synchronize()
torch_time = (time.time() - start_time) / num_iterations
# 自定义 CUDA 内核计时
torch.cuda.synchronize()
start_time = time.time()
for _ in range(num_iterations):
_ = cuda_model(*inputs)
torch.cuda.synchronize()
cuda_time = (time.time() - start_time) / num_iterations
print(f"PyTorch (matmul + relu) 平均执行时间: {torch_time:.6f}")
print(f"自定义 CUDA ReLU 平均执行时间: {cuda_time:.6f}")
speedup = 0
if cuda_time > 0:
speedup = torch_time / cuda_time
print(f"加速比 (Speedup): {speedup:.2f}x")
else:
print("CUDA 内核执行时间为0无法计算加速比。")
return precision_flag, speedup
if __name__ == "__main__":
precision_flag, speedup = run_benchmark()