gemv_utils.h 6.59 KB
Newer Older
one's avatar
one committed
1
2
#pragma once

3
#include "hip_compat.h"
one's avatar
one committed
4
5
6
7
8
9
10
#include <algorithm>
#include <functional>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>

11
// ============================================================================
one's avatar
one committed
12
// Error Handling
13
// ============================================================================
one's avatar
one committed
14
15
16
17
18
19
20
21

inline void checkHipErrors(hipError_t result) {
  if (result != hipSuccess) {
    std::cerr << "HIP Error: " << hipGetErrorString(result) << std::endl;
    exit(1);
  }
}

22
23
24
25
26
27
28
29
30
31
32
33
34
// ============================================================================
// Device Info
// ============================================================================

/// L2 cache size in MB
inline int get_l2_cache_size(int device = 0) {
  hipDeviceProp_t prop;
  checkHipErrors(hipGetDeviceProperties(&prop, device));

  return prop.l2CacheSize / 1024 / 1024;
}

// ============================================================================
one's avatar
one committed
35
// Command Line Parsing
36
// ============================================================================
one's avatar
one committed
37
38
39
40
41
42
43
44
45

inline char *getCmdOption(char **begin, char **end, const std::string &option) {
  char **itr = std::find(begin, end, option);
  if (itr != end && ++itr != end) {
    return *itr;
  }
  return 0;
}

46
// ============================================================================
one's avatar
one committed
47
// CPU Reference & Verification
48
// ============================================================================
one's avatar
one committed
49
50

inline void gemv_cpu(int M, int K, float alpha, const hip_bfloat16 *h_A,
one's avatar
one committed
51
52
                     int lda, const hip_bfloat16 *h_x, float beta,
                     hip_bfloat16 *h_y) {
one's avatar
one committed
53
54
55
56
57
58
59
  for (int m = 0; m < M; ++m) {
    float sum = 0.0f;
    for (int k = 0; k < K; ++k) {
      float val_a = static_cast<float>(h_A[m * lda + k]);
      float val_x = static_cast<float>(h_x[k]);
      sum += val_a * val_x;
    }
60
    h_y[m] = hip_bfloat16(alpha * sum + beta * static_cast<float>(h_y[m]));
one's avatar
one committed
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
  }

  return;
}

inline bool verify_result(int M, const hip_bfloat16 *h_y_gpu,
                          const hip_bfloat16 *h_y_ref) {
  float max_diff = 0.0f;
  int err_count = 0;
  for (int i = 0; i < M; ++i) {
    float gpu_val = static_cast<float>(h_y_gpu[i]);
    float cpu_val = static_cast<float>(h_y_ref[i]);
    float diff = std::abs(gpu_val - cpu_val);

    // bfloat16 的精度有限,容忍度需要稍大一点
    // 同时也考虑数值大小,这里使用简单的绝对误差 + 相对误差阈值
    if (diff > 0.1f && diff / (std::abs(cpu_val) + 1e-6) > 0.01) {
      if (err_count < 5) {
        std::cerr << "Mismatch at index " << i << ": GPU=" << gpu_val
                  << ", CPU=" << cpu_val << ", Diff=" << diff << std::endl;
      }
      err_count++;
    }
    max_diff = std::max(max_diff, diff);
  }

  if (err_count > 0) {
    std::cerr << "Total mismatches: " << err_count << ", Max Diff: " << max_diff
              << std::endl;
    return false;
  }
  return true;
}

95
// ============================================================================
one's avatar
one committed
96
// Benchmark Framework
97
// ============================================================================
one's avatar
one committed
98
99

// 定义统一的 Kernel Launcher 签名
one's avatar
one committed
100
101
102
using KernelLauncher = std::function<void(
    int M, int K, float alpha, const hip_bfloat16 *A, int lda,
    const hip_bfloat16 *x, float beta, hip_bfloat16 *y)>;
one's avatar
one committed
103
104
105
106
107
108
109
110

struct KernelCase {
  std::string name;
  KernelLauncher func;
};

inline void run_benchmark(const std::vector<KernelCase> &cases, int M, int K,
                          float alpha, const hip_bfloat16 *A, int lda,
one's avatar
one committed
111
                          const hip_bfloat16 *x, float beta, hip_bfloat16 *y,
one's avatar
one committed
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
                          bool do_verify) {

  std::cout << "GEMV Benchmarks" << std::endl;

  hipEvent_t start, stop;
  checkHipErrors(hipEventCreate(&start));
  checkHipErrors(hipEventCreate(&stop));

  // 准备 verification 数据
  std::vector<hip_bfloat16> h_y_ref(M);
  std::vector<hip_bfloat16> h_y_gpu(M);
  std::vector<hip_bfloat16> h_A(M * K);
  std::vector<hip_bfloat16> h_x(K);

  if (do_verify) {
    std::cout << "Verifying results against CPU reference..." << std::endl;
    // 把 A 和 x 拷回 host 端计算
    checkHipErrors(hipMemcpy(h_A.data(), A, M * K * sizeof(hip_bfloat16),
                             hipMemcpyDeviceToHost));
    checkHipErrors(hipMemcpy(h_x.data(), x, K * sizeof(hip_bfloat16),
                             hipMemcpyDeviceToHost));

    // 计算 CPU Reference
one's avatar
one committed
135
    gemv_cpu(M, K, alpha, h_A.data(), lda, h_x.data(), beta, h_y_ref.data());
one's avatar
one committed
136
137
138
139
140
141
142
143
144
  }

  // 列宽
  const int w_table = 80;

  // 表头
  printf("%s\n", std::string(w_table, '-').c_str());
  printf("M=%d, K=%d, N=1\n", M, K);
  printf("lda=%d\n", lda);
145
146
  printf("sizeof(A)=%lu MB\n", M * lda * sizeof(hip_bfloat16) / 1024 / 1024);
  printf("L2 cache=%d MB\n", get_l2_cache_size());
one's avatar
one committed
147
148
149
150
151
152
153
154
155
156
157
158
159
  printf("%s\n", std::string(w_table, '-').c_str());
  printf("%-38s %10s %10s %10s %8s\n", "Kernel Name", "Time (us)", "GFLOPS",
         "BW (GB/s)", "Result");

  for (const auto &k : cases) {
    std::string result_status = "Skipped";

    // 1. Verification (如果启用)
    if (do_verify) {
      // 清零 d_y
      checkHipErrors(hipMemset(y, 0, M * sizeof(hip_bfloat16)));

      // 运行一次
one's avatar
one committed
160
      k.func(M, K, alpha, A, lda, x, beta, y);
one's avatar
one committed
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
      checkHipErrors(hipDeviceSynchronize());

      // 拷回结果
      checkHipErrors(hipMemcpy(h_y_gpu.data(), y, M * sizeof(hip_bfloat16),
                               hipMemcpyDeviceToHost));

      if (verify_result(M, h_y_gpu.data(), h_y_ref.data())) {
        result_status = "PASS";
      } else {
        result_status = "FAIL";
      }
    }

    // 2. Warmup
    for (int i = 0; i < 100; ++i) {
one's avatar
one committed
176
      k.func(M, K, alpha, A, lda, x, beta, y);
one's avatar
one committed
177
178
179
180
    }
    checkHipErrors(hipDeviceSynchronize());

    // 3. Timing
181
    int num_runs = 100;
one's avatar
one committed
182
183
    checkHipErrors(hipEventRecord(start));
    for (int i = 0; i < num_runs; ++i) {
one's avatar
one committed
184
      k.func(M, K, alpha, A, lda, x, beta, y);
one's avatar
one committed
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
    }
    checkHipErrors(hipEventRecord(stop));
    checkHipErrors(hipEventSynchronize(stop));

    float total_ms = 0;
    checkHipErrors(hipEventElapsedTime(&total_ms, start, stop));
    float avg_ms = total_ms / num_runs;

    // 4. Metrics
    double gflops = (2.0 * M * K) / (avg_ms * 1e-3) / 1e9;

    // Bandwidth = Read A + Read x + Write y
    // A: M*K, x: K, y: M
    double bytes_moved = (double)(M * K + K + M) * sizeof(hip_bfloat16);
    double bw = bytes_moved / (avg_ms * 1e-3) / 1e9;

one's avatar
one committed
201
202
    printf("%-38s %10.1f %10.2f %10.2f %8s\n", k.name.c_str(), avg_ms * 1e3,
           gflops, bw, result_status.c_str());
one's avatar
one committed
203
204
205
206
207
208
209
210
211
  }

  std::cout << std::string(w_table, '-') << std::endl;

  checkHipErrors(hipEventDestroy(start));
  checkHipErrors(hipEventDestroy(stop));

  return;
}