File size: 12,390 Bytes
68888be | 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 | // hkimi layer-test | selftest
//
// layer-test runs single layers of a store, alone: the way to try real K3.1 Pro
// tensors before the whole 1.56 TB is on a disk (tools/pick_shards.py says which
// shards a couple of layers need). The same random hidden states go through each
// layer on the chosen backend and on the CPU reference, and a few experts are
// computed again on the host straight from their stored record.
//
// --dump DIR writes every layer's input and output (layer-N.in.bin, layer-N.out.bin,
// float32 [rows, hidden]) for tools/ref_forward.py --layer N --hidden-in ...
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include "cli/args.h"
#include "cli/commands.h"
#include "common/base.h"
#include "common/numeric.h"
#include "common/threads.h"
#include "format/store.h"
#include "gpu/backend.h"
#include "gpu/selftest.h"
#include "io/file_io.h"
#include "model/layers.h"
#include "model/weights.h"
#include "reader/reader.h"
namespace hk {
namespace {
// the first tensor of layer L the store lacks ("" if complete)
std::string missing_tensor(const Store& store, int L) {
const ModelConfig& c = store.config();
for (const TensorNeed& n : layer_tensors(c, L))
if (!store.has(n.name)) return n.name;
if (c.is_moe(L)) {
const std::string bias = c.n_layer(L, "block_sparse_moe.gate.e_score_correction_bias");
if (!store.has(bias)) return bias;
if (!store.has_experts(L)) return strfmt("the routed experts of layer %d", L);
}
return "";
}
void dump_f32(const std::string& path, const std::vector<float>& v) {
std::ofstream f(std::filesystem::u8path(path), std::ios::binary);
f.write((const char*)v.data(), (std::streamsize)(v.size() * sizeof(float)));
HK_CHECK(f.good(), "cannot write %s", path.c_str());
}
double sq(const float* a, const float* b, size_t n) { // sum (a - b)^2, or sum a^2 when b is null
double s = 0;
for (size_t i = 0; i < n; ++i) {
const double d = b ? (double)a[i] - b[i] : (double)a[i];
s += d * d;
}
return s;
}
inline float dotf(const float* a, const float* b, int n) {
float acc[8] = {0, 0, 0, 0, 0, 0, 0, 0};
int i = 0;
for (; i + 8 <= n; i += 8)
for (int j = 0; j < 8; ++j) acc[j] += a[i + j] * b[i + j];
float s = ((acc[0] + acc[4]) + (acc[1] + acc[5])) + ((acc[2] + acc[6]) + (acc[3] + acc[7]));
for (; i < n; ++i) s += a[i] * b[i];
return s;
}
inline float glu1(const Act& act, float g, float u) {
if (act.kind == ActKind::SILU) return g * sigmoidf(g) * u;
float a = act.beta * std::tanh(g / act.beta) * sigmoidf(g);
float b = act.lbeta > 0 ? act.lbeta * std::tanh(u / act.lbeta) : u;
return a * b;
}
// one expert on the CPU from its stored record: Y[n, in] = down( act(gate X, up X) )
void host_expert_ffn(const ExpertViews& v, const Act& act, const float* X, int n, float* Y) {
const int inter = v.desc[0].rows, in = v.desc[0].cols;
std::vector<float> H((size_t)n * (size_t)inter);
parallel_for(inter, 8, [&](int64_t j0, int64_t j1) {
std::vector<float> g((size_t)in), u((size_t)in);
for (int64_t j = j0; j < j1; ++j) {
planes_decode_row(v.desc[0], v.view[0], (int)j, g.data());
planes_decode_row(v.desc[1], v.view[1], (int)j, u.data());
for (int i = 0; i < n; ++i) {
const float* x = X + (size_t)i * in;
H[(size_t)i * inter + j] = glu1(act, dotf(g.data(), x, in), dotf(u.data(), x, in));
}
}
});
parallel_for(in, 8, [&](int64_t o0, int64_t o1) {
std::vector<float> d((size_t)inter);
for (int64_t o = o0; o < o1; ++o) {
planes_decode_row(v.desc[2], v.view[2], (int)o, d.data());
for (int i = 0; i < n; ++i) Y[(size_t)i * in + o] = dotf(d.data(), H.data() + (size_t)i * inter, inter);
}
});
}
// computes some of a sweep's experts again on the host
struct ExpertProbe : SweepObserver {
const Store& store;
IoEngine& io; // its own engine: the reader's has reads in flight
int budget; // experts to measure
int measured = 0;
double err = 0, norm = 0;
int file = -1, file_layer = -1;
ExpertProbe(const Store& s, IoEngine& i, int n) : store(s), io(i), budget(n) {}
void on_expert(int layer, int expert, const float* Xc, const float* Yc, const int32_t*, int n, int dim) override {
if (measured >= budget) return;
const ModelConfig& c = store.config();
const ExpertLayer& el = store.experts(layer);
if (file_layer != layer) {
file = io.open(store.path(el.file));
file_layer = layer;
}
AlignedBuf rec(el.record_bytes());
io.read_aligned(file, el.record_offset(expert), el.record_bytes(), rec.data());
const Act act = act_of(c);
const int rows = std::min(n, 4); // a few rows per expert are enough for an average
std::vector<float> y((size_t)rows * (size_t)dim);
ExpertViews v = expert_views(el, rec.data(), 4);
host_expert_ffn(v, act, Xc, rows, y.data());
err += sq(y.data(), Yc, y.size());
norm += sq(Yc, nullptr, y.size());
++measured;
}
};
} // namespace
int cmd_layer_test(const Args& a) {
a.allow({"layers", "rows", "seed", "backend", "engine", "buffered", "chunk", "io-depth", "no-reference", "check-experts", "tolerance",
"dump"});
Store store = Store::open(a.need_pos(0, "the store directory"));
const ModelConfig& c = store.config();
const int d = c.hidden;
std::vector<int> layers = parse_int_list(a.str("layers"));
if (layers.empty()) {
for (int L = 0; L < c.layers; ++L)
if (missing_tensor(store, L).empty()) layers.push_back(L);
HK_CHECK(!layers.empty(), "this store holds no complete layer (convert at least one with: hkimi convert <checkpoint> <store> --layers N)");
}
const int rows = (int)a.num("rows", 48);
HK_CHECK(rows >= 1, "--rows must be positive");
const double tol = a.real("tolerance", 1e-3);
const std::string dump = a.str("dump");
if (!dump.empty()) make_dirs(dump);
std::unique_ptr<Backend> bk = Backend::create(a.str("backend", "auto"));
std::unique_ptr<Backend> ref;
if (bk->is_gpu() && !a.flag("no-reference")) ref = make_cpu_backend();
IoOptions io_opt;
io_opt.engine = a.str("engine", "auto");
io_opt.direct = !a.flag("buffered");
io_opt.queue_depth = (int)a.num("io-depth", 16) * 2;
std::unique_ptr<IoEngine> io = IoEngine::create(io_opt), io_ref = IoEngine::create(io_opt), io_probe = IoEngine::create(io_opt);
printf("%s\n", c.summary().c_str());
printf("backend %s (%s), reads by %s; %d rows of random hidden states per layer\n", bk->name(), bk->device_name().c_str(), io->name(),
rows);
if (!ref) printf("no second backend to compare with: this run checks that the layers load and run, and times them\n");
int failed = 0;
for (int L : layers) {
HK_CHECK(L >= 0 && L < c.layers, "layer %d does not exist (the model has layers 0..%d)", L, c.layers - 1);
const std::string miss = missing_tensor(store, L);
HK_CHECK(miss.empty(), "layer %d is not complete in this store: %s is missing", L, miss.c_str());
Rng rng((uint64_t)a.num("seed", 1) * 1000003u + (uint64_t)L);
std::vector<float> x((size_t)rows * (size_t)d);
for (float& v : x) v = (float)rng.normal();
const std::vector<int32_t> dummy((size_t)rows, 0);
auto run = [&](Backend& b, IoEngine& e, SweepObserver* obs, SweepStats* st) {
ReaderOptions ro;
ro.chunk = (int)a.num("chunk", ro.chunk);
ro.io_depth = (int)a.num("io-depth", ro.io_depth);
ro.first_layer = ro.last_layer = L;
ro.hidden_io = true;
Reader reader(store, b, e, ro);
SeqCheckpoint ck;
ck.reset(c);
SeqJob job;
job.tokens = &dummy;
job.ckpt = &ck;
job.end = rows;
job.hidden_in = &x;
*st = reader.sweep(job, obs);
return job.hidden_out;
};
ExpertProbe probe(store, *io_probe, (int)a.num("check-experts", 24));
SweepStats st;
std::vector<float> y = run(*bk, *io, c.is_moe(L) ? &probe : nullptr, &st);
if (!dump.empty()) {
dump_f32(path_join(dump, strfmt("layer-%d.in.bin", L)), x);
dump_f32(path_join(dump, strfmt("layer-%d.out.bin", L)), y);
}
bool finite = true;
for (float v : y) finite = finite && std::isfinite(v);
const char* kind = c.is_kda(L) ? "KDA" : (c.is_dsa(L) ? "full attention + indexer" : "full attention");
printf("layer %d (%s, %s): %s read in %.2f s", L, kind, c.is_moe(L) ? "MoE" : "dense MLP", human_bytes((double)st.bytes_read).c_str(),
st.seconds);
if (c.is_moe(L)) printf(", %d of %d experts used by %d picks", st.expert_reads, c.n_experts, rows * c.top_k);
printf("\n");
if (!finite) {
printf(" FAIL: the output has non-finite values\n");
++failed;
}
if (ref) {
SweepStats st2;
std::vector<float> y2 = run(*ref, *io_ref, nullptr, &st2);
const double rel = std::sqrt(sq(y.data(), y2.data(), y.size()) / std::max(sq(y2.data(), nullptr, y2.size()), 1e-30));
const bool ok = rel <= tol;
printf(" %s against the CPU reference: relative difference %.1e %s (CPU took %.2f s)\n", bk->name(), rel, ok ? "ok" : "FAIL",
st2.seconds);
failed += ok ? 0 : 1;
}
if (probe.measured > 0 && probe.norm > 0) {
const double rel = std::sqrt(probe.err / probe.norm);
printf(" %d experts computed again on the host from their stored record: relative difference %.2g\n", probe.measured, rel);
if (rel > 1e-3) {
printf(" FAIL: an expert rebuilt on the host does not match the backend\n");
++failed;
}
}
}
if (!dump.empty())
printf("inputs and outputs written to %s (to compare with the NumPy reference: python tools/ref_forward.py <checkpoint or store> "
"--check-dump %s)\n",
dump.c_str(), dump.c_str());
printf("%zu layer(s) tested, %d problem(s)\n", layers.size(), failed);
return failed ? 1 : 0;
}
static void set_env(const char* name, const char* value) {
#if defined(_WIN32)
_putenv_s(name, value);
#else
setenv(name, value, 1);
#endif
}
int cmd_selftest(const Args& a) {
a.allow({"backend", "quick", "seed"});
std::unique_ptr<Backend> ref = make_cpu_backend();
std::unique_ptr<Backend> dut = Backend::create(a.str("backend", "auto"));
const bool gpu = dut->is_gpu();
printf("reference: cpu under test: %s (%s)\n", dut->name(), dut->device_name().c_str());
int failed = 0, total = 0;
// A GPU backend runs twice: as usual, then with tiny work buffers and packed weights,
// so the small test matrices go through the slicing and batching code big models use.
for (int pass = 0; pass < (gpu ? 2 : 1); ++pass) {
if (pass == 1) {
dut.reset();
set_env("HKIMI_CUDA_TEST_SMALL", "1");
dut = Backend::create(a.str("backend", "auto"));
printf("again with small work buffers and packed weights:\n");
}
SelftestReport r = backend_selftest(*ref, *dut, (uint64_t)a.num("seed", 1), a.flag("quick"));
for (const SelftestCase& c : r.cases) {
if (c.bits) printf(" %-38s %s %.4g%% of the values differ\n", c.name.c_str(), c.ok ? "ok " : "FAIL", 100.0 * c.rel_err);
else printf(" %-38s %s max rel err %.2e\n", c.name.c_str(), c.ok ? "ok " : "FAIL", c.rel_err);
}
failed += (int)r.cases.size() - r.passed;
total += (int)r.cases.size();
}
printf("%d of %d checks passed: every operation against the CPU reference, and a row alone against the same row in a batch\n",
total - failed, total);
if (!gpu) printf("note: this compared the CPU backend with itself; run a CUDA build to check the GPU.\n");
return failed == 0 ? 0 : 1;
}
} // namespace hk
|