unittest_utils.h 7.07 KB
Newer Older
Li Zhang's avatar
Li Zhang committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
 * Copyright (c) 2022-2023, NVIDIA CORPORATION.  All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

Chen Xin's avatar
Chen Xin committed
19
20
21
22
23
24
25
26
27
#include <algorithm>  // min, max
#include <assert.h>   // assert
#include <float.h>    // FLT_MAX
#include <iostream>   // snprintf
#include <limits>     // numeric_limits
#include <math.h>     // expf, log
#include <stdlib.h>   // rand
#include <string>     // string
#include <vector>     // vector
Li Zhang's avatar
Li Zhang committed
28

lvhan028's avatar
lvhan028 committed
29
30
31
#include "src/turbomind/utils/cuda_utils.h"
#include "src/turbomind/utils/memory_utils.h"
#include "src/turbomind/utils/string_utils.h"
Li Zhang's avatar
Li Zhang committed
32
33
34
35
36

#define PRINT_LIMIT 16
#define EPSILON (1e-20)
#define EPSILON_FP16 (1e-10)

lvhan028's avatar
lvhan028 committed
37
using namespace turbomind;
Li Zhang's avatar
Li Zhang committed
38

Chen Xin's avatar
Chen Xin committed
39
class TestFailureError: public std::exception {
Li Zhang's avatar
Li Zhang committed
40
41
private:
    std::string msg_;
Chen Xin's avatar
Chen Xin committed
42

Li Zhang's avatar
Li Zhang committed
43
44
public:
    explicit TestFailureError() = default;
Chen Xin's avatar
Chen Xin committed
45
46
    explicit TestFailureError(std::string name, std::string msg = "")
    {
Li Zhang's avatar
Li Zhang committed
47
48
        msg_ = fmtstr("TEST FAIL [%s] %s", name.c_str(), msg.c_str());
    }
Chen Xin's avatar
Chen Xin committed
49
50
    const char* what() const throw()
    {
Li Zhang's avatar
Li Zhang committed
51
52
53
54
        return msg_.c_str();
    }
};

Chen Xin's avatar
Chen Xin committed
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#define EXPECT_TRUE(cond)                                                                                              \
    do {                                                                                                               \
        if (!(cond)) {                                                                                                 \
            TM_LOG_ERROR("TEST FAIL [%s]: %s at %s:%d", __func__, #cond, __FILE__, __LINE__);                          \
            throw TestFailureError(__func__);                                                                          \
        }                                                                                                              \
    } while (false)

#define EXPECT_FALSE(cond)                                                                                             \
    do {                                                                                                               \
        if (cond) {                                                                                                    \
            TM_LOG_ERROR("TEST FAIL [%s]: %s at %s:%d", __func__, #cond, __FILE__, __LINE__);                          \
            throw TestFailureError(__func__);                                                                          \
        }                                                                                                              \
    } while (false)
Li Zhang's avatar
Li Zhang committed
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

bool almostEqual(float a, float b, float atol = 1e-5, float rtol = 1e-8)
{
    // Params: a = value to compare and b = reference
    // This function follows implementation of numpy.isclose(), which checks
    //   abs(a - b) <= (atol + rtol * abs(b)).
    // Note that the inequality above is asymmetric where b is considered as
    // a reference value. To account into both absolute/relative errors, it
    // uses absolute tolerance and relative tolerance at the same time. The
    // default values of atol and rtol borrowed from numpy.isclose(). For the
    // case of nan value, the result will be true.
    if (isnan(a) && isnan(b)) {
        return true;
    }
    return fabs(a - b) <= (atol + rtol * fabs(b));
}

template<typename T>
Chen Xin's avatar
Chen Xin committed
88
89
90
91
92
bool checkResult(std::string name, T* out, T* ref, size_t size, float atol, float rtol)
{
    size_t failures     = 0;
    float  relative_gap = 0.0f;
    ;
Li Zhang's avatar
Li Zhang committed
93
94
95
96
97
98
99
100
101

    for (size_t i = 0; i < size; ++i) {
        // The values for the output and the reference.
        float a = (float)out[i];
        float b = (float)ref[i];

        bool ok = almostEqual(a, b, atol, rtol);
        // Print the error.
        if (!ok && failures < 4) {
lvhan028's avatar
lvhan028 committed
102
103
104
105
106
            TM_LOG_ERROR(">> invalid result for i=%lu:", i);
            TM_LOG_ERROR(">>    found......: %10.6f", a);
            TM_LOG_ERROR(">>    expected...: %10.6f", b);
            TM_LOG_ERROR(">>    error......: %.6f", fabsf(a - b));
            TM_LOG_ERROR(">>    tol........: %.6f", atol + rtol * fabs(b));
Li Zhang's avatar
Li Zhang committed
107
108
109
110
111
112
113
114
115
116
117
        }
        // Update the number of failures.
        failures += ok ? 0 : 1;
        // Update the relative gap.
        relative_gap += fabsf(a - b) / (fabsf(b) + EPSILON);
    }

    relative_gap /= size;

    // Allow not matched up to 1% elements.
    size_t tol_failures = (size_t)(0.01 * size);
lvhan028's avatar
lvhan028 committed
118
    TM_LOG_INFO("check...%6s : %-50s (failures: %.2f%% atol: %.2e rtol: %.2e rel_gap: %.2e%%)",
Chen Xin's avatar
Chen Xin committed
119
120
121
122
123
124
                failures <= tol_failures ? "....OK" : "FAILED",
                name.c_str(),
                100. * failures / size,
                atol,
                rtol,
                100. * relative_gap);
Li Zhang's avatar
Li Zhang committed
125
126
127
128
    return failures <= tol_failures;
}

template<typename T>
Chen Xin's avatar
Chen Xin committed
129
bool checkResult(std::string name, T* out, T* ref, size_t size, bool device_out = true, bool device_ref = false)
Li Zhang's avatar
Li Zhang committed
130
{
Chen Xin's avatar
Chen Xin committed
131
132
133
    bool  is_fp32 = sizeof(T) == 4;
    float atol    = is_fp32 ? 1e-4f : 1e-3f;
    float rtol    = is_fp32 ? 1e-2f : 1e-1f;
Li Zhang's avatar
Li Zhang committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147

    T* h_out = nullptr;
    if (device_out) {
        h_out = new T[size];
        cudaMemcpy(h_out, out, sizeof(T) * size, cudaMemcpyDeviceToHost);
        out = h_out;
    }
    T* h_ref = nullptr;
    if (device_ref) {
        h_ref = new T[size];
        cudaMemcpy(h_ref, ref, sizeof(T) * size, cudaMemcpyDeviceToHost);
        ref = h_ref;
    }
    bool is_ok = checkResult(name, out, ref, size, atol, rtol);
Chen Xin's avatar
Chen Xin committed
148
    if (h_out != nullptr) {
Li Zhang's avatar
Li Zhang committed
149
150
151
152
153
154
155
156
157
        delete[] h_out;
    }
    if (h_ref != nullptr) {
        delete[] h_ref;
    }
    return is_ok;
}

template<typename T>
Chen Xin's avatar
Chen Xin committed
158
159
void initRandom(T* ptr, size_t size, float minval, float maxval)
{
Li Zhang's avatar
Li Zhang committed
160
161
162
163
164
165
166
    for (size_t i = 0; i < size; ++i) {
        float val = static_cast<float>(rand()) / static_cast<float>(RAND_MAX);
        val *= (maxval - minval);
        ptr[i] = static_cast<T>(minval + val);
    }
}

Chen Xin's avatar
Chen Xin committed
167
168
void initRandomInt(int* ptr, size_t size, int minval, int maxval)
{
Li Zhang's avatar
Li Zhang committed
169
170
171
172
173
174
175
176
    assert(minval < maxval);
    int mod = maxval - minval;
    for (size_t i = 0; i < size; ++i) {
        ptr[i] = minval + rand() % mod;
    }
}

template<typename T>
Chen Xin's avatar
Chen Xin committed
177
178
void tile(T* x, int m, int n)
{
Li Zhang's avatar
Li Zhang committed
179
180
181
182
183
184
185
186
    for (int i = 1; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            x[i * n + j] = x[j];
        }
    }
}

template<typename T>
Chen Xin's avatar
Chen Xin committed
187
188
void tile(T* dst, T* src, int m, int n)
{
Li Zhang's avatar
Li Zhang committed
189
190
191
192
193
194
195
196
197
198
    for (int i = 1; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            dst[i * n + j] = src[j];
        }
    }
}

#define HALF_FLT_MAX 65504.0f

template<typename T>
Chen Xin's avatar
Chen Xin committed
199
200
bool isHalf()
{
Li Zhang's avatar
Li Zhang committed
201
202
203
204
    return std::is_same<T, half>::value;
}

template<typename T>
Chen Xin's avatar
Chen Xin committed
205
206
static inline void printMatrixWithLimit(T* ptr, int m, int k, int stride, bool is_device_ptr)
{
Li Zhang's avatar
Li Zhang committed
207
208
    printMatrix(ptr, std::min(PRINT_LIMIT, m), std::min(PRINT_LIMIT, k), stride, is_device_ptr);
}