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
|
/* tests/test_bf16_model.c - F32 vs BF16 loader/dispatch parity on a tiny
* synthetic model. Hermetic: builds its own model dirs. Runs via
* `make test`. */
#include "embed.h"
#include "tiny_model.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
int main(void) {
char root[1024], f32_dir[1088], bf16_dir[1088];
snprintf(root, sizeof(root), "%s/pplx-bf16-test-XXXXXX",
getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp");
if (!mkdtemp(root)) { perror("mkdtemp"); return 2; }
snprintf(f32_dir, sizeof(f32_dir), "%s/f32", root);
snprintf(bf16_dir, sizeof(bf16_dir), "%s/bf16", root);
if (mkdir(f32_dir, 0755) != 0 || mkdir(bf16_dir, 0755) != 0 ||
tm_write_model(f32_dir, "F32") != 0 ||
tm_write_model(bf16_dir, "BF16") != 0) {
fprintf(stderr, "fixture creation failed\n");
return 2;
}
int ids[] = {1, 2, 3, 4};
pplx_model_t *mf32 = pplx_model_load(f32_dir);
pplx_model_t *mbf16 = pplx_model_load(bf16_dir);
if (!mf32 || !mbf16) {
fprintf(stderr, "model load failed\n");
return 1;
}
const pplx_config_t *cfg = pplx_model_config(mf32);
int dim = cfg->hidden_size;
float *a = (float *)malloc((size_t)dim * sizeof(float));
float *b = (float *)malloc((size_t)dim * sizeof(float));
pplx_workspace_t *wf32 = pplx_workspace_new(mf32);
pplx_workspace_t *wbf16 = pplx_workspace_new(mbf16);
if (!a || !b || !wf32 || !wbf16) {
fprintf(stderr, "allocation failed\n");
return 1;
}
if (pplx_model_embed_into(mf32, wf32, ids, 4, a) != 0 ||
pplx_model_embed_into(mbf16, wbf16, ids, 4, b) != 0) {
fprintf(stderr, "embedding failed\n");
return 1;
}
float max_diff = 0.0f;
float norm = 0.0f;
for (int i = 0; i < dim; i++) {
if (!isfinite(a[i]) || !isfinite(b[i])) {
fprintf(stderr, "non-finite embedding value\n");
return 1;
}
float d = fabsf(a[i] - b[i]);
if (d > max_diff) max_diff = d;
norm += b[i] * b[i];
}
norm = sqrtf(norm);
/* Embeddings are intentionally unnormalized; require a sane nonzero
* magnitude and tight F32-vs-BF16 parity, not unit norm. */
if (norm <= 1e-6f || max_diff > 2e-5f) {
fprintf(stderr, "bad parity: norm=%.9g max_diff=%.9g\n", norm, max_diff);
return 1;
}
printf("ok: bf16 model parity dim=%d max_abs_diff=%.9g norm=%.9g\n",
dim, max_diff, norm);
pplx_workspace_free(wf32);
pplx_workspace_free(wbf16);
pplx_model_free(mf32);
pplx_model_free(mbf16);
free(a);
free(b);
return 0;
}
|