-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpredict-distill.c
More file actions
1724 lines (1637 loc) · 57.3 KB
/
Copy pathpredict-distill.c
File metadata and controls
1724 lines (1637 loc) · 57.3 KB
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* SPDX-License-Identifier: MIT OR Apache-2.0
* Copyright (c) 2026 Pure Storage, Inc.
*/
/* distill_predict() / distill_forecast(): the distillation recipes.
*
* Fits a native student via the trainers in predict-train.c. distill_predict() fits a student
* on a training signal (the target column by default, or a named teacher
* model's predictions), evaluates it on a held-out fraction, serializes it via
* predict-student.c, and registers it in _predict_models. The student then
* serves through predict0_tree_run with no onnxruntime. The blob format,
* deserializers, and inference runtime all live in predict-student.c. */
#include "predict-internal.h"
#include "predict-student.h"
#include "predict-train.h"
#ifndef SQLITE_CORE
SQLITE_EXTENSION_INIT3
#endif
/* ---- the distill_predict() operation ---- */
typedef struct {
char *target, *task, *student_id, *teacher, *student_kind;
char *proba; /* JSON array of soft-target probability column names */
char *classes; /* JSON array of class labels, same order as `proba` */
} DistOpts;
static void dist_opts_free(DistOpts *o) {
sqlite3_free(o->target);
sqlite3_free(o->task);
sqlite3_free(o->student_id);
sqlite3_free(o->teacher);
sqlite3_free(o->student_kind);
sqlite3_free(o->proba);
sqlite3_free(o->classes);
}
/* Return the class index for `s`, interning it into *labels (growing *cap and
* *nclass on first sight). Returns -1 and sets *rc = SQLITE_NOMEM on OOM; a
* valid index is always >= 0. */
static int dist_opt_cb(void *ctx, const char *key, sqlite3_value *value,
char **errmsg) {
DistOpts *o = ctx;
if (sqlite3_value_type(value) != SQLITE_TEXT) {
*errmsg = sqlite3_mprintf("%s: wrong type for option '%s'",
PREDICT_ERR_OPTIONS, key);
return 1;
}
char **slot = strcmp(key, "target") == 0 ? &o->target
: strcmp(key, "task") == 0 ? &o->task
: strcmp(key, "student_id") == 0 ? &o->student_id
: strcmp(key, "teacher") == 0 ? &o->teacher
: strcmp(key, "student_kind") == 0 ? &o->student_kind
: strcmp(key, "proba") == 0 ? &o->proba
: strcmp(key, "classes") == 0 ? &o->classes
: NULL;
if (slot) {
sqlite3_free(*slot); /* free-before-assign: duplicate JSON key */
*slot = sqlite3_mprintf("%s", (const char *)sqlite3_value_text(value));
}
return 0;
}
static const char *const DIST_OPTION_KEYS[] = {
"target", "task", "student_id", "teacher", "student_kind",
"proba", "classes", NULL};
static int name_index(char *const *arr, int n, const char *s) {
for (int i = 0; i < n; i++)
if (strcmp(arr[i], s) == 0)
return i;
return -1;
}
typedef struct {
char *model_id;
char content_hash[PREDICT_HEX_BUFSIZE];
int train_rows;
double metric;
} DistResult;
static void append_ident(sqlite3_str *s, const char *nm) {
sqlite3_str_appendchar(s, 1, '"');
for (const char *c = nm; *c; c++) {
if (*c == '"')
sqlite3_str_appendchar(s, 1, '"');
sqlite3_str_appendchar(s, 1, *c);
}
sqlite3_str_appendchar(s, 1, '"');
}
/* Hash a serialized student blob and register it under student_id
* (kind='student'; runtime='tree' also covers MLP/forest blobs, "native
* in-core runtime" as opposed to onnx). hash_out receives the
* content_hash hex. Returns SQLITE_OK, or SQLITE_ERROR with *errmsg set
* (STUDENT_EXISTS on an id collision). */
/* The training pipeline. Fills *res on success. */
static int distill_train(sqlite3 *db, const char *tq, DistOpts *o,
DistResult *res, char **errmsg) {
int rc = SQLITE_OK;
int classify = !o->task || strcmp(o->task, "classify") == 0;
memset(res, 0, sizeof(*res));
/* ---- 1. introspect train_query columns ---- */
sqlite3_stmt *iq = NULL;
if (predict0_prepare_ro(db, tq, "train_query", &iq, errmsg) != SQLITE_OK)
return SQLITE_ERROR;
int ncol = sqlite3_column_count(iq);
int target_col = -1;
char *feat_names[TREE_MAX_FEAT];
int feat_col[TREE_MAX_FEAT];
int nfeat = 0;
for (int i = 0; i < ncol; i++) {
const char *nm = sqlite3_column_name(iq, i);
if (nm && o->target && strcmp(nm, o->target) == 0) {
target_col = i;
} else if (nfeat < TREE_MAX_FEAT) {
feat_names[nfeat] = sqlite3_mprintf("%s", nm ? nm : "");
feat_col[nfeat] = i;
nfeat++;
} else {
sqlite3_finalize(iq);
for (int f = 0; f < nfeat; f++)
sqlite3_free(feat_names[f]);
*errmsg = sqlite3_mprintf("%s: too many feature columns (max %d)",
PREDICT_ERR_SCHEMA, TREE_MAX_FEAT);
return SQLITE_ERROR;
}
}
sqlite3_finalize(iq);
if (target_col < 0 || nfeat == 0) {
for (int f = 0; f < nfeat; f++)
sqlite3_free(feat_names[f]);
*errmsg = sqlite3_mprintf(
target_col < 0 ? "%s: no such target column: %s"
: "%s: train_query needs feature columns%s",
target_col < 0 ? PREDICT_ERR_TARGET : PREDICT_ERR_SCHEMA,
target_col < 0 ? (o->target ? o->target : "(none)") : "");
return SQLITE_ERROR;
}
/* quoted feature list for the teacher's apply query */
sqlite3_str *fl = sqlite3_str_new(db);
for (int f = 0; f < nfeat; f++) {
if (f)
sqlite3_str_appendchar(fl, 1, ',');
append_ident(fl, feat_names[f]);
}
char *feat_list = sqlite3_str_finish(fl);
/* all further allocations flow to a single cleanup */
f32 *X = NULL;
char **y_true_c = NULL; /* classify: true labels */
f64 *y_true_r = NULL; /* regress: true values */
i32 *y_teach = NULL; /* classify: teacher class index */
f32 *y_teach_r = NULL; /* regress: teacher value */
char **labels = NULL; /* teacher class vocabulary */
int nclass = 0, nlab_cap = 0;
int n = 0, cap = 0;
Tree tree;
memset(&tree, 0, sizeof(tree));
Forest forest;
memset(&forest, 0, sizeof(forest));
MLP mlp;
memset(&mlp, 0, sizeof(mlp));
void *blob = NULL;
int blob_len = 0;
int *idx = NULL;
char *read_sql = NULL, *apply_sql = NULL, *teacher_sql = NULL;
sqlite3_stmt *rq = NULL, *tqs = NULL;
char **proba_names = NULL, **soft_labels = NULL; /* soft distillation */
int nproba = 0, nsoft = 0, *proba_col = NULL;
f32 *soft_P = NULL; /* [n, nproba] teacher class probabilities */
sqlite3_stmt *sps = NULL;
int soft = o->proba != NULL;
const char *teacher = o->teacher; /* NULL => train directly on the target */
const char *task = classify ? "classify" : "regress";
/* ---- soft-label distillation setup: teacher class probabilities live in
* named columns (`proba`), one per class (`classes`), which the gbt student
* matches instead of a hard label. Exclude those columns from the features
* and capture their indices. ---- */
if (soft) {
if (!classify) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: 'proba' (soft distillation) is"
" classification only",
PREDICT_ERR_OPTIONS);
goto done;
}
if (o->student_kind && strcmp(o->student_kind, "gbt") != 0 &&
strcmp(o->student_kind, "mlp") != 0) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: soft distillation requires student_kind"
" 'gbt' or 'mlp'",
PREDICT_ERR_OPTIONS);
goto done;
}
if (!o->classes) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: 'proba' requires 'classes'",
PREDICT_ERR_OPTIONS);
goto done;
}
rc = predict0_json_str_array(db, o->proba, NULL, &proba_names, &nproba,
PREDICT0_MAX_CLASS, errmsg);
if (rc != SQLITE_OK)
goto done;
rc = predict0_json_str_array(db, o->classes, NULL, &soft_labels, &nsoft,
PREDICT0_MAX_CLASS, errmsg);
if (rc != SQLITE_OK)
goto done;
if (nproba < 2 || nproba != nsoft) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf(
"%s: 'proba' and 'classes' must be equal-length arrays of >= 2",
PREDICT_ERR_OPTIONS);
goto done;
}
/* Defensive invariant: predict0_json_str_array already caps proba/classes
* at PREDICT0_MAX_CLASS during parsing; kept in case that changes. */
if (nproba > PREDICT0_MAX_CLASS) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: too many classes (%d); the maximum is %d",
PREDICT_ERR_SCHEMA, nproba, PREDICT0_MAX_CLASS);
goto done;
}
proba_col = sqlite3_malloc(sizeof(int) * nproba);
if (!proba_col) {
rc = SQLITE_NOMEM;
goto done;
}
for (int k = 0; k < nproba; k++)
proba_col[k] = -1;
int w = 0;
for (int r = 0; r < nfeat; r++) {
int k = name_index(proba_names, nproba, feat_names[r]);
if (k >= 0) {
proba_col[k] = feat_col[r]; /* query column index of this class prob */
sqlite3_free(feat_names[r]);
} else {
feat_names[w] = feat_names[r];
feat_col[w] = feat_col[r];
w++;
}
}
nfeat = w;
for (int k = 0; k < nproba; k++)
if (proba_col[k] < 0) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: proba column '%s' not in train_query",
PREDICT_ERR_SCHEMA, proba_names[k]);
goto done;
}
if (nfeat == 0) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: no feature columns left after excluding"
" proba columns",
PREDICT_ERR_SCHEMA);
goto done;
}
}
/* ---- 2. read features + true labels (row_number keeps a stable order) ---- */
read_sql = sqlite3_mprintf(
"SELECT (row_number() OVER ()) AS _rid, * FROM (%s) ORDER BY _rid", tq);
if (!read_sql) {
rc = SQLITE_NOMEM;
goto done;
}
if (sqlite3_prepare_v2(db, read_sql, -1, &rq, NULL) != SQLITE_OK) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: could not read train_query: %s",
PREDICT_ERR_SCHEMA, sqlite3_errmsg(db));
goto done;
}
int sr;
while ((sr = sqlite3_step(rq)) == SQLITE_ROW) {
if (n == cap) {
cap = cap ? cap * 2 : 256;
f32 *gx = sqlite3_realloc(X, sizeof(f32) * (size_t)cap * nfeat);
if (!gx) {
rc = SQLITE_NOMEM;
goto done;
}
X = gx;
if (classify) {
char **g = sqlite3_realloc(y_true_c, sizeof(char *) * cap);
i32 *gt = sqlite3_realloc(y_teach, sizeof(i32) * cap);
if (!g || !gt) {
sqlite3_free(g);
sqlite3_free(gt);
rc = SQLITE_NOMEM;
goto done;
}
y_true_c = g;
y_teach = gt;
} else {
f64 *g = sqlite3_realloc(y_true_r, sizeof(f64) * cap);
f32 *gt = sqlite3_realloc(y_teach_r, sizeof(f32) * cap);
if (!g || !gt) {
sqlite3_free(g);
sqlite3_free(gt);
rc = SQLITE_NOMEM;
goto done;
}
y_true_r = g;
y_teach_r = gt;
}
}
f32 *row = &X[(size_t)n * nfeat];
for (int f = 0; f < nfeat; f++) {
int c = feat_col[f] + 1; /* +1 for the _rid prefix column */
int ct = sqlite3_column_type(rq, c);
if (ct != SQLITE_INTEGER && ct != SQLITE_FLOAT) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: train feature '%s' is not numeric",
PREDICT_ERR_SCHEMA, feat_names[f]);
goto done;
}
row[f] = (f32)sqlite3_column_double(rq, c);
}
if (classify) {
const char *lab =
(const char *)sqlite3_column_text(rq, target_col + 1);
y_true_c[n] = sqlite3_mprintf("%s", lab ? lab : "");
} else {
int ct = sqlite3_column_type(rq, target_col + 1);
if (ct != SQLITE_INTEGER && ct != SQLITE_FLOAT) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: regress target must be numeric",
PREDICT_ERR_TARGET);
goto done;
}
y_true_r[n] = sqlite3_column_double(rq, target_col + 1);
}
n++;
}
/* A terminal step code other than DONE is a read failure, not end-of-data:
* surface it rather than train on the partial rows collected so far. Capture
* the message before finalize clears it. */
if (rc == SQLITE_OK && sr != SQLITE_DONE) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: could not read train_query: %s",
PREDICT_ERR_SCHEMA, sqlite3_errmsg(db));
}
sqlite3_finalize(rq);
rq = NULL;
if (rc != SQLITE_OK)
goto done;
if (n < DISTILL_MIN_ROWS) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: need at least %d train rows, got %d",
PREDICT_ERR_SCHEMA, DISTILL_MIN_ROWS, n);
goto done;
}
/* soft distillation: read the probability columns in the same row order and
* normalize each row to a distribution (defensive: clamp negatives, rescale;
* a degenerate row falls back to uniform). */
if (soft) {
soft_P = sqlite3_malloc(sizeof(f32) * (size_t)n * nproba);
if (!soft_P) {
rc = SQLITE_NOMEM;
goto done;
}
if (sqlite3_prepare_v2(db, read_sql, -1, &sps, NULL) != SQLITE_OK) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: could not re-read proba columns: %s",
PREDICT_ERR_SCHEMA, sqlite3_errmsg(db));
goto done;
}
int si = 0;
while (si < n && sqlite3_step(sps) == SQLITE_ROW) {
f64 sum = 0;
for (int k = 0; k < nproba; k++) {
f64 v = sqlite3_column_double(sps, proba_col[k] + 1); /* +1 for _rid */
if (v < 0)
v = 0;
soft_P[(size_t)si * nproba + k] = (f32)v;
sum += v;
}
if (sum > 1e-12)
for (int k = 0; k < nproba; k++)
soft_P[(size_t)si * nproba + k] /= (f32)sum;
else
for (int k = 0; k < nproba; k++)
soft_P[(size_t)si * nproba + k] = 1.f / nproba;
si++;
}
sqlite3_finalize(sps);
sps = NULL;
if (si != n) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: proba re-read yielded %d of %d rows",
PREDICT_ERR_RESOURCE, si, n);
goto done;
}
}
/* ---- 3. training signal per row ----
* Soft distillation: the class vocabulary is the given `classes`, and the
* per-row soft targets are already in soft_P; there is no teacher to run.
* Otherwise, with no teacher (the default) the student trains directly on
* the target column: it already holds the labels, or a strong teacher's
* precomputed predictions (e.g. an offline TabFM run) that you want
* compressed into a native student that runs anywhere. A named teacher is a
* registered predict() model, re-run over the same rows (aligned by _rid) to
* relabel them. */
if (soft) {
labels = soft_labels; /* transfer ownership; matched to soft_P columns */
soft_labels = NULL;
nclass = nproba;
} else if (!teacher) {
for (int i = 0; i < n; i++) {
if (classify) {
int cl = predict0_intern_label(&labels, &nclass, &nlab_cap,
y_true_c[i], PREDICT0_MAX_CLASS, &rc,
errmsg);
if (cl < 0)
goto done;
y_teach[i] = cl;
} else {
y_teach_r[i] = (f32)y_true_r[i];
}
}
} else {
apply_sql = sqlite3_mprintf(
"SELECT (row_number() OVER ()) AS _rid, %s FROM (%s) ORDER BY _rid",
feat_list, tq);
teacher_sql = sqlite3_mprintf(
"SELECT prediction FROM predict_batch(%Q, %Q, json_object('target',%Q,'task',"
"%Q,'model',%Q))",
tq, apply_sql, o->target, task, teacher);
if (!apply_sql || !teacher_sql) {
rc = SQLITE_NOMEM;
goto done;
}
if (sqlite3_prepare_v2(db, teacher_sql, -1, &tqs, NULL) != SQLITE_OK) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: teacher query for '%s' does not"
" prepare: %s",
PREDICT_ERR_SCHEMA, teacher,
sqlite3_errmsg(db));
goto done;
}
int ti = 0;
int tstep;
while ((tstep = sqlite3_step(tqs)) == SQLITE_ROW && ti < n) {
if (classify) {
const char *pred = (const char *)sqlite3_column_text(tqs, 0);
int cl = predict0_intern_label(&labels, &nclass, &nlab_cap,
pred ? pred : "", PREDICT0_MAX_CLASS, &rc,
errmsg);
if (cl < 0)
goto done;
y_teach[ti] = cl;
} else {
y_teach_r[ti] = (f32)sqlite3_column_double(tqs, 0);
}
ti++;
}
/* Require exactly n teacher labels: DONE with ti == n. If the loop stopped
* because ti hit n while the query still had rows (tstep == SQLITE_ROW), the
* teacher over-produced; fail rather than silently drop the extra. */
int tdone = tstep == SQLITE_DONE && ti == n;
char *terr = tdone ? NULL : sqlite3_mprintf("%s", sqlite3_errmsg(db));
sqlite3_finalize(tqs);
tqs = NULL;
if (!tdone) {
int too_many = tstep == SQLITE_ROW;
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf(
"%s: teacher produced %s labels for %d train rows (%s)",
PREDICT_ERR_SCHEMA, too_many ? "too many" : "too few", n,
terr ? terr : (too_many ? "extra rows" : "short read"));
sqlite3_free(terr);
goto done;
}
sqlite3_free(terr);
}
if (classify && nclass < 2) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf(
"%s: %s produced a single class; nothing to distill", PREDICT_ERR_SCHEMA,
teacher ? "teacher" : "target column");
goto done;
}
/* Defensive invariant: predict0_intern_label and the soft-label nproba check
* already cap this before any allocation; kept so the bound holds even if
* those paths change. */
if (classify && nclass > PREDICT0_MAX_CLASS) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: too many classes (%d); the maximum is %d",
PREDICT_ERR_SCHEMA, nclass, PREDICT0_MAX_CLASS);
goto done;
}
/* ---- 4. fit the student on the fit split (teacher targets) ---- */
int n_hold = n / 5;
if (n_hold < 1)
n_hold = 1;
int n_fit = n - n_hold;
int is_mlp_student = o->student_kind && strcmp(o->student_kind, "mlp") == 0;
int is_gbt = !is_mlp_student &&
(soft || (o->student_kind && strcmp(o->student_kind, "gbt") == 0));
int correct = 0;
f64 sse = 0;
if (is_mlp_student) {
if (!classify) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: mlp student is classification only",
PREDICT_ERR_OPTIONS);
goto done;
}
rc = predict0_train_mlp(X, n_fit, nfeat, nclass, y_teach, soft ? soft_P : NULL,
0 /* classify */, MLP_HIDDEN, MLP_EPOCHS, MLP_LR,
0 /* no skip */, &mlp, errmsg);
if (rc != SQLITE_OK)
goto done;
mlp.feat_names = sqlite3_malloc(sizeof(char *) * nfeat);
if (!mlp.feat_names) {
rc = SQLITE_NOMEM;
*errmsg = sqlite3_mprintf("%s: out of memory", PREDICT_ERR_RESOURCE);
goto done;
}
for (int f = 0; f < nfeat; f++)
mlp.feat_names[f] = feat_names[f];
mlp.labels = labels; /* transfer */
nfeat = 0;
labels = NULL;
f32 *hb = sqlite3_malloc(sizeof(f32) * mlp.nhid);
f32 *ob = sqlite3_malloc(sizeof(f32) * mlp.nout);
if (!hb || !ob) {
sqlite3_free(hb);
sqlite3_free(ob);
rc = SQLITE_NOMEM;
*errmsg = sqlite3_mprintf("%s: out of memory", PREDICT_ERR_RESOURCE);
goto done;
}
for (int i = n_fit; i < n; i++) {
char *pred = NULL;
f64 conf = 0;
int hc = 0;
if (predict0_mlp_predict_row(&mlp, &X[(size_t)i * mlp.nfeat], hb, ob, &pred, &conf,
&hc) != SQLITE_OK) {
sqlite3_free(hb);
sqlite3_free(ob);
rc = SQLITE_NOMEM;
*errmsg = sqlite3_mprintf("%s: out of memory", PREDICT_ERR_RESOURCE);
goto done;
}
if (strcmp(pred, y_true_c[i]) == 0)
correct++;
sqlite3_free(pred);
}
sqlite3_free(hb);
sqlite3_free(ob);
res->metric = (f64)correct / n_hold;
rc = predict0_mlp_serialize(&mlp, &blob, &blob_len);
if (rc != SQLITE_OK) {
*errmsg = sqlite3_mprintf("%s: out of memory", PREDICT_ERR_RESOURCE);
goto done;
}
} else if (is_gbt) {
rc = predict0_train_gbt(X, n_fit, nfeat, classify ? 0 : 1, nclass, y_teach,
y_teach_r, soft ? soft_P : NULL, &forest, errmsg);
if (rc != SQLITE_OK)
goto done;
forest.feat_names = sqlite3_malloc(sizeof(char *) * nfeat);
if (!forest.feat_names) {
rc = SQLITE_NOMEM;
*errmsg = sqlite3_mprintf("%s: out of memory", PREDICT_ERR_RESOURCE);
goto done;
}
for (int f = 0; f < nfeat; f++)
forest.feat_names[f] = feat_names[f];
forest.labels = labels; /* transfer */
nfeat = 0;
labels = NULL;
f64 *scbuf = classify ? sqlite3_malloc(sizeof(f64) * forest.n_score) : NULL;
if (classify && !scbuf) {
rc = SQLITE_NOMEM;
*errmsg = sqlite3_mprintf("%s: out of memory", PREDICT_ERR_RESOURCE);
goto done;
}
for (int i = n_fit; i < n; i++) {
char *pred = NULL;
f64 conf = 0;
int hc = 0;
if (predict0_forest_predict_row(&forest, &X[(size_t)i * forest.nfeat], scbuf,
&pred, &conf, &hc) != SQLITE_OK) {
sqlite3_free(scbuf);
rc = SQLITE_NOMEM;
*errmsg = sqlite3_mprintf("%s: out of memory", PREDICT_ERR_RESOURCE);
goto done;
}
if (classify) {
if (strcmp(pred, y_true_c[i]) == 0)
correct++;
} else {
f64 d = strtod(pred, NULL) - y_true_r[i];
sse += d * d;
}
sqlite3_free(pred);
}
sqlite3_free(scbuf);
res->metric = classify ? (f64)correct / n_hold : sqrt(sse / n_hold);
rc = predict0_forest_serialize(&forest, &blob, &blob_len);
if (rc != SQLITE_OK) {
*errmsg = sqlite3_mprintf("%s: out of memory", PREDICT_ERR_RESOURCE);
goto done;
}
} else {
idx = sqlite3_malloc(sizeof(int) * n_fit);
if (!idx) {
rc = SQLITE_NOMEM;
goto done;
}
for (int i = 0; i < n_fit; i++)
idx[i] = i;
Builder b;
memset(&b, 0, sizeof(b));
b.X = X;
b.nfeat = nfeat;
b.yc = y_teach;
b.yr = y_teach_r;
b.nclass = nclass;
b.task = classify ? 0 : 1;
int root = predict0_bld_build(&b, idx, n_fit, 0);
if (root < 0) {
sqlite3_free(b.nodes);
rc = SQLITE_NOMEM;
*errmsg = sqlite3_mprintf("%s: out of memory", PREDICT_ERR_RESOURCE);
goto done;
}
/* root is index 0 (first node allocated). Move the feature names into a
* heap array the tree owns (the local is a stack array). */
tree.feat_names = sqlite3_malloc(sizeof(char *) * nfeat);
if (!tree.feat_names) {
sqlite3_free(b.nodes);
rc = SQLITE_NOMEM;
*errmsg = sqlite3_mprintf("%s: out of memory", PREDICT_ERR_RESOURCE);
goto done;
}
for (int f = 0; f < nfeat; f++)
tree.feat_names[f] = feat_names[f];
tree.task = b.task;
tree.nfeat = nfeat;
tree.nclass = nclass;
tree.labels = labels;
tree.n_nodes = b.n;
tree.nodes = b.nodes;
nfeat = 0; /* feature-name strings now owned by the tree */
labels = NULL;
for (int i = n_fit; i < n; i++) {
int leaf = predict0_tree_walk(&tree, &X[(size_t)i * tree.nfeat]);
if (leaf < 0)
continue;
const TreeNode *ln = &tree.nodes[leaf];
if (classify) {
if (strcmp(tree.labels[ln->klass], y_true_c[i]) == 0)
correct++;
} else {
f64 d = (f64)ln->value - y_true_r[i];
sse += d * d;
}
}
res->metric = classify ? (f64)correct / n_hold : sqrt(sse / n_hold);
rc = predict0_tree_serialize(&tree, &blob, &blob_len);
if (rc != SQLITE_OK) {
*errmsg = sqlite3_mprintf("%s: out of memory", PREDICT_ERR_RESOURCE);
goto done;
}
}
rc = predict0_register_student(db, o->student_id, blob, blob_len, res->content_hash,
errmsg);
if (rc != SQLITE_OK)
goto done;
res->model_id = sqlite3_mprintf("%s", o->student_id);
res->train_rows = n;
rc = SQLITE_OK;
done:
sqlite3_free(feat_list);
sqlite3_free(read_sql);
sqlite3_free(apply_sql);
sqlite3_free(teacher_sql);
if (rq)
sqlite3_finalize(rq);
if (tqs)
sqlite3_finalize(tqs);
sqlite3_free(X);
if (y_true_c)
for (int i = 0; i < n; i++)
sqlite3_free(y_true_c[i]);
sqlite3_free(y_true_c);
sqlite3_free(y_true_r);
sqlite3_free(y_teach);
sqlite3_free(y_teach_r);
for (int f = 0; f < nfeat; f++) /* only if not transferred to the tree */
sqlite3_free(feat_names[f]);
if (labels)
for (int i = 0; i < nclass; i++)
sqlite3_free(labels[i]);
sqlite3_free(labels);
if (proba_names)
for (int k = 0; k < nproba; k++)
sqlite3_free(proba_names[k]);
sqlite3_free(proba_names);
if (soft_labels) /* NULL once transferred to `labels` */
for (int k = 0; k < nsoft; k++)
sqlite3_free(soft_labels[k]);
sqlite3_free(soft_labels);
sqlite3_free(proba_col);
sqlite3_free(soft_P);
if (sps)
sqlite3_finalize(sps);
sqlite3_free(idx);
sqlite3_free(blob);
predict0_tree_free(&tree);
predict0_forest_free(&forest);
predict0_mlp_free(&mlp);
return rc;
}
/* ---- distill vtab ---- */
#define DL_MODEL 0
#define DL_HASH 1
#define DL_ROWS 2
#define DL_METRIC 3
#define DL_TRAINQ 4
#define DL_OPTIONS 5
typedef struct {
sqlite3_vtab base;
sqlite3 *db;
} dl_vtab;
typedef struct {
sqlite3_vtab_cursor base;
DistResult res;
int done;
} dl_cursor;
static int dl_connect(sqlite3 *db, void *pAux, int argc,
const char *const *argv, sqlite3_vtab **ppVtab,
char **pzErr) {
UNUSED_PARAMETER(pAux);
UNUSED_PARAMETER(argc);
UNUSED_PARAMETER(argv);
UNUSED_PARAMETER(pzErr);
dl_vtab *v = sqlite3_malloc(sizeof(*v));
if (!v)
return SQLITE_NOMEM;
memset(v, 0, sizeof(*v));
v->db = db;
int rc = sqlite3_declare_vtab(
db, "CREATE TABLE x(model_id TEXT, content_hash TEXT, train_rows INTEGER,"
" holdout_metric REAL, train_query HIDDEN,"
" options HIDDEN)");
if (rc != SQLITE_OK) {
sqlite3_free(v);
return rc;
}
*ppVtab = &v->base;
return SQLITE_OK;
}
static int dl_disconnect(sqlite3_vtab *p) {
sqlite3_free(p);
return SQLITE_OK;
}
static int dl_best_index(sqlite3_vtab *pVtab, sqlite3_index_info *pIdx) {
int seen_train = 0;
for (int i = 0; i < pIdx->nConstraint; i++) {
const struct sqlite3_index_constraint *c = &pIdx->aConstraint[i];
if (c->op != SQLITE_INDEX_CONSTRAINT_EQ)
continue;
int argv = c->iColumn == DL_TRAINQ ? 1 : c->iColumn == DL_OPTIONS ? 2 : 0;
if (!argv)
continue;
if (!c->usable)
return SQLITE_CONSTRAINT;
pIdx->aConstraintUsage[i].argvIndex = argv;
pIdx->aConstraintUsage[i].omit = 1;
if (argv == 1)
seen_train = 1;
}
if (!seen_train) {
pVtab->zErrMsg = sqlite3_mprintf(
"%s: distill_predict(train_query, options) requires a train_query",
PREDICT_ERR_SCHEMA);
return SQLITE_ERROR;
}
pIdx->estimatedCost = 1e6;
return SQLITE_OK;
}
static int dl_open(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCur) {
UNUSED_PARAMETER(pVtab);
dl_cursor *c = sqlite3_malloc(sizeof(*c));
if (!c)
return SQLITE_NOMEM;
memset(c, 0, sizeof(*c));
*ppCur = &c->base;
return SQLITE_OK;
}
static int dl_close(sqlite3_vtab_cursor *pCur) {
dl_cursor *c = (dl_cursor *)pCur;
sqlite3_free(c->res.model_id);
sqlite3_free(c);
return SQLITE_OK;
}
static int dl_filter(sqlite3_vtab_cursor *pCur, int idxNum, const char *idxStr,
int argc, sqlite3_value **argv) {
UNUSED_PARAMETER(idxNum);
UNUSED_PARAMETER(idxStr);
dl_cursor *cur = (dl_cursor *)pCur;
dl_vtab *vtab = (dl_vtab *)cur->base.pVtab;
sqlite3 *db = vtab->db;
sqlite3_free(cur->res.model_id);
memset(&cur->res, 0, sizeof(cur->res));
cur->done = 0;
const char *tq =
argc >= 1 ? (const char *)sqlite3_value_text(argv[0]) : NULL;
const char *options =
argc >= 2 ? (const char *)sqlite3_value_text(argv[1]) : NULL;
if (!tq) {
sqlite3_free(vtab->base.zErrMsg);
vtab->base.zErrMsg =
sqlite3_mprintf("%s: train_query is required", PREDICT_ERR_SCHEMA);
return SQLITE_ERROR;
}
DistOpts o;
memset(&o, 0, sizeof(o));
char *emsg = NULL;
if (predict0_options_parse(db, options, DIST_OPTION_KEYS, dist_opt_cb, &o,
&emsg)) {
sqlite3_free(vtab->base.zErrMsg);
vtab->base.zErrMsg = emsg;
dist_opts_free(&o);
return SQLITE_ERROR;
}
#define DL_FAIL(...) \
do { \
sqlite3_free(vtab->base.zErrMsg); \
vtab->base.zErrMsg = sqlite3_mprintf(__VA_ARGS__); \
dist_opts_free(&o); \
return SQLITE_ERROR; \
} while (0)
if (!o.target)
DL_FAIL("%s: distill_predict requires a target option", PREDICT_ERR_TARGET);
if (!o.student_id)
DL_FAIL("%s: distill_predict requires a student_id option",
PREDICT_ERR_OPTIONS);
if (o.task && strcmp(o.task, "classify") != 0 &&
strcmp(o.task, "regress") != 0)
DL_FAIL("%s: task must be classify|regress: %s", PREDICT_ERR_TASK, o.task);
if (o.student_kind && strcmp(o.student_kind, "tree") != 0 &&
strcmp(o.student_kind, "gbt") != 0 &&
strcmp(o.student_kind, "mlp") != 0)
DL_FAIL("%s: student_kind '%s' is not available; use 'tree', 'gbt', or"
" 'mlp'",
PREDICT_ERR_OPTIONS, o.student_kind);
char *ensure_err = NULL;
if (predict0_registry_ensure(db, &ensure_err) != SQLITE_OK) {
sqlite3_free(vtab->base.zErrMsg);
vtab->base.zErrMsg = ensure_err;
dist_opts_free(&o);
return SQLITE_ERROR;
}
char *existing = predict0_registry_model_hash(db, o.student_id);
if (existing) {
sqlite3_free(existing);
DL_FAIL("%s: student '%s' already exists", PREDICT_ERR_STUDENT_EXISTS,
o.student_id);
}
#undef DL_FAIL
int rc = distill_train(db, tq, &o, &cur->res, &emsg);
dist_opts_free(&o);
if (rc != SQLITE_OK) {
sqlite3_free(vtab->base.zErrMsg);
vtab->base.zErrMsg = emsg;
return SQLITE_ERROR;
}
return SQLITE_OK;
}
static int dl_next(sqlite3_vtab_cursor *pCur) {
((dl_cursor *)pCur)->done = 1;
return SQLITE_OK;
}
static int dl_eof(sqlite3_vtab_cursor *pCur) {
return ((dl_cursor *)pCur)->done;
}
static int dl_column(sqlite3_vtab_cursor *pCur, sqlite3_context *ctx, int col) {
dl_cursor *c = (dl_cursor *)pCur;
switch (col) {
case DL_MODEL:
sqlite3_result_text(ctx, c->res.model_id, -1, SQLITE_TRANSIENT);
break;
case DL_HASH:
sqlite3_result_text(ctx, c->res.content_hash, -1, SQLITE_TRANSIENT);
break;
case DL_ROWS:
sqlite3_result_int(ctx, c->res.train_rows);
break;
case DL_METRIC:
sqlite3_result_double(ctx, c->res.metric);
break;
default:
break;
}
return SQLITE_OK;
}
static int dl_rowid(sqlite3_vtab_cursor *pCur, sqlite3_int64 *pRowid) {
UNUSED_PARAMETER(pCur);
*pRowid = 1;
return SQLITE_OK;
}
static sqlite3_module distillModule = {
/* iVersion */ 0,
/* xCreate */ NULL,
/* xConnect */ dl_connect,
/* xBestIndex */ dl_best_index,
/* xDisconnect */ dl_disconnect,
/* xDestroy */ NULL,
/* xOpen */ dl_open,
/* xClose */ dl_close,
/* xFilter */ dl_filter,
/* xNext */ dl_next,
/* xEof */ dl_eof,
/* xColumn */ dl_column,
/* xRowid */ dl_rowid,
/* xUpdate */ NULL,
/* xBegin */ NULL,
/* xSync */ NULL,
/* xCommit */ NULL,
/* xRollback */ NULL,
/* xFindMethod */ NULL,
/* xRename */ NULL,
/* xSavepoint */ NULL,
/* xRelease */ NULL,
/* xRollbackTo */ NULL,
/* xShadowName */ NULL,
/* xIntegrity */ NULL};
/* ---- distill_forecast: train a native forecast student (PSFCST) ----
*
* The train_query returns context + horizon columns per row: the first
* `context` columns are a raw history window, the next `horizon` are the
* teacher's forecast for that window (computed offline, e.g. by a foundation
* model). Each row is instance-normalized by its own window before a multi-
* output regression MLP is fit to reproduce the teacher. The student serves
* through forecast() with no teacher and no onnxruntime. */
#define FCST_HIDDEN 256 /* forecast student residual width (benchmark-chosen:
* 256 is the m4_hourly optimum, 128 and 512 both worse) */
#define FCST_EPOCHS 1500 /* forecast regression trains longer at a gentler LR */
#define FCST_LR 0.005f
typedef struct {
char *model_id;
char content_hash[PREDICT_HEX_BUFSIZE];
int train_rows;
f64 metric; /* holdout RMSE in normalized space */
} FcstResult;
#define FCST_TEACHER_MAX_WIN 4000 /* teacher= mode: window budget per call */
/* Train + register a forecast student from a prepared, instance-normalized
* training matrix X [n,L], Y [n,H*Q]. Does not own X/Y. */
static int fdistill_fit(sqlite3 *db, const f32 *X, const f32 *Y, int n, int L,
int H, int Q, const f32 *levels, const char *student_id,