gemv_utils.h 6.37 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

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

109
110
inline void run_benchmark(int warmups, int loops,
                          const std::vector<KernelCase> &cases, int M, int K,
one's avatar
one committed
111
                          float alpha, const hip_bfloat16 *A, int lda,
one's avatar
one committed
112
                          const hip_bfloat16 *x, float beta, hip_bfloat16 *y,
one's avatar
one committed
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
                          bool do_verify) {
  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
133
    gemv_cpu(M, K, alpha, h_A.data(), lda, h_x.data(), beta, h_y_ref.data());
one's avatar
one committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
  }

  // 列宽
  const int w_table = 80;

  // 表头
  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
153
      k.func(M, K, alpha, A, lda, x, beta, y);
one's avatar
one committed
154
155
156
157
158
159
160
161
162
163
164
165
166
167
      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
168
    for (int i = 0; i < warmups; ++i) {
one's avatar
one committed
169
      k.func(M, K, alpha, A, lda, x, beta, y);
one's avatar
one committed
170
171
172
173
    }
    checkHipErrors(hipDeviceSynchronize());

    // 3. Timing
174
    int num_runs = loops;
one's avatar
one committed
175
176
    checkHipErrors(hipEventRecord(start));
    for (int i = 0; i < num_runs; ++i) {
one's avatar
one committed
177
      k.func(M, K, alpha, A, lda, x, beta, y);
one's avatar
one committed
178
179
180
181
182
183
184
185
186
187
188
    }
    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;

one's avatar
one committed
189
    // Bandwidth = Read A + Read x + Read y + Write y
one's avatar
one committed
190
    // A: M*K, x: K, y: M
one's avatar
one committed
191
    double bytes_moved = (double)(M * K + K + M + M) * sizeof(hip_bfloat16);
one's avatar
one committed
192
193
    double bw = bytes_moved / (avg_ms * 1e-3) / 1e9;

one's avatar
one committed
194
195
    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
196
197
198
199
200
201
202
203
204
  }

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

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

  return;
}