-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpredict-onnx.c
More file actions
1897 lines (1791 loc) · 66.6 KB
/
Copy pathpredict-onnx.c
File metadata and controls
1897 lines (1791 loc) · 66.6 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.
*/
/* ONNX runtime backend for predict() — the opt-in foundation-model
* serving path (make loadable-onnx, -DSQLITE_PREDICT_ONNX). This file is
* the only one that links onnxruntime; the core build never sees it.
*
* Two io_spec layouts are implemented: "vector" (a self-contained,
* pre-trained model mapping a feature vector to a prediction — a
* distilled student, or any exported tabular classifier/regressor) and
* "in_context" (a teacher such as TabFM that ingests the training rows
* as context on every call). The in_context path is validated against
* real weights on the gated GPU CI job.
*
* Performance shape: the expensive costs are session
* creation and weight load, so sessions are cached process-global keyed by
* (weights, device, precision) and reused across calls; query rows are run
* in batches, not one at a time. Execution-provider selection is explicit
* and fails loud — a request for a provider this build lacks errors rather
* than silently dropping to CPU. */
#include "predict-internal.h"
#include "predict-student.h" /* PREDICT0_MAX_CLASS: caps io_spec output labels */
#ifndef SQLITE_CORE
SQLITE_EXTENSION_INIT3
#endif
#ifndef SQLITE_PREDICT_ONNX
/* Nothing in this translation unit when the runtime is not compiled in.
* The dispatcher in predict-tabular.c guards its call the same way. */
#else
#include "onnxruntime_c_api.h"
#ifdef __APPLE__
#include "coreml_provider_factory.h"
#endif
#define ONNX_BATCH 1024 /* query rows per forward pass */
static const OrtApi *g_ort = NULL;
static OrtEnv *g_env = NULL;
/* Process-global session cache. Sessions are expensive to build and safe
* to Run() concurrently, so we keep them for the process lifetime. The
* list head is a static global, so the sessions stay reachable at exit
* (no leak-checker false positives). */
typedef struct onnx_session {
char *key; /* content_hash|device|precision */
OrtSession *session;
struct onnx_session *next;
} onnx_session;
static onnx_session *g_cache = NULL;
static sqlite3_mutex *onnx_mutex(void) {
return sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_APP1);
}
/* ---- error plumbing ---- */
/* Turn an OrtStatus into a PREDICT_ERR_* message and release it. Returns
* SQLITE_ERROR so callers can `return onnx_fail(...)`. */
static int onnx_fail(OrtStatus *st, const char *code, const char *ctx,
char **errmsg) {
const char *m = st ? g_ort->GetErrorMessage(st) : "(no status)";
*errmsg = sqlite3_mprintf("%s: %s: %s", code, ctx, m);
if (st)
g_ort->ReleaseStatus(st);
return SQLITE_ERROR;
}
static int onnx_init(char **errmsg) {
if (g_env)
return SQLITE_OK;
g_ort = OrtGetApiBase()->GetApi(ORT_API_VERSION);
if (!g_ort) {
*errmsg = sqlite3_mprintf("%s: onnxruntime API version mismatch",
PREDICT_ERR_RUNTIME_UNAVAILABLE);
return SQLITE_ERROR;
}
OrtStatus *st =
g_ort->CreateEnv(ORT_LOGGING_LEVEL_WARNING, "sqlite-predict", &g_env);
if (st)
return onnx_fail(st, PREDICT_ERR_RUNTIME_UNAVAILABLE, "CreateEnv", errmsg);
return SQLITE_OK;
}
/* ---- io_spec introspection (derive an io_spec from the model) ---- */
/* The last dimension of input/output `idx`, or -1 if dynamic/unknown; sets
* *elem_type to the tensor element type. */
/* Non-zero if the status is an error; always consumes it. */
static int st_bad(OrtStatus *st) {
if (st) {
g_ort->ReleaseStatus(st);
return 1;
}
return 0;
}
static int64_t tensor_last_dim(OrtSession *s, int is_input, size_t idx,
ONNXTensorElementDataType *elem_type) {
OrtTypeInfo *ti = NULL;
int64_t last = -1;
*elem_type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED;
if (st_bad(is_input ? g_ort->SessionGetInputTypeInfo(s, idx, &ti)
: g_ort->SessionGetOutputTypeInfo(s, idx, &ti)))
return -1;
const OrtTensorTypeAndShapeInfo *tsi = NULL;
if (!st_bad(g_ort->CastTypeInfoToTensorInfo(ti, &tsi)) && tsi) {
size_t ndim = 0;
if (!st_bad(g_ort->GetTensorElementType(tsi, elem_type)) &&
!st_bad(g_ort->GetDimensionsCount(tsi, &ndim)) && ndim >= 1 &&
ndim <= 8) {
int64_t dims[8];
if (!st_bad(g_ort->GetDimensions(tsi, dims, ndim)))
last = dims[ndim - 1];
}
}
g_ort->ReleaseTypeInfo(ti);
return last;
}
int predict0_onnx_introspect(sqlite3 *db, const char *weights_uri,
char **io_spec_out, char **errmsg) {
*io_spec_out = NULL;
int rc = onnx_init(errmsg);
if (rc != SQLITE_OK)
return rc;
OrtSessionOptions *so = NULL;
OrtSession *sess = NULL;
OrtAllocator *alloc = NULL;
char *in_names[3] = {NULL, NULL, NULL};
char *out_name = NULL;
sqlite3_stmt *bld = NULL;
OrtStatus *st = g_ort->CreateSessionOptions(&so);
if (st)
return onnx_fail(st, PREDICT_ERR_INFERENCE, "CreateSessionOptions", errmsg);
st = g_ort->CreateSession(g_env, weights_uri, so, &sess);
g_ort->ReleaseSessionOptions(so);
if (st)
return onnx_fail(st, PREDICT_ERR_INFERENCE,
"cannot open model for introspection", errmsg);
#define INTRO_FAIL(...) \
do { \
*errmsg = sqlite3_mprintf(__VA_ARGS__); \
rc = SQLITE_ERROR; \
goto done; \
} while (0)
size_t n_in = 0, n_out = 0;
if (st_bad(g_ort->GetAllocatorWithDefaultOptions(&alloc)) ||
st_bad(g_ort->SessionGetInputCount(sess, &n_in)) ||
st_bad(g_ort->SessionGetOutputCount(sess, &n_out)))
INTRO_FAIL("%s: could not read model metadata", PREDICT_ERR_IO_SPEC);
if (n_out != 1)
INTRO_FAIL("%s: model has %zu outputs; provide an explicit io_spec with"
" output.name",
PREDICT_ERR_IO_SPEC, n_out);
if (n_in != 1 && n_in != 3)
INTRO_FAIL("%s: cannot derive io_spec for %zu inputs; provide an explicit"
" io_spec",
PREDICT_ERR_IO_SPEC, n_in);
for (size_t i = 0; i < n_in; i++) {
char *nm = NULL;
if (g_ort->SessionGetInputName(sess, i, alloc, &nm) || !nm)
INTRO_FAIL("%s: could not read input name %zu", PREDICT_ERR_IO_SPEC, i);
in_names[i] = sqlite3_mprintf("%s", nm);
alloc->Free(alloc, nm);
}
{
char *nm = NULL;
if (g_ort->SessionGetOutputName(sess, 0, alloc, &nm) || !nm)
INTRO_FAIL("%s: could not read output name", PREDICT_ERR_IO_SPEC);
out_name = sqlite3_mprintf("%s", nm);
alloc->Free(alloc, nm);
}
/* output shape/type -> kind */
ONNXTensorElementDataType out_type;
int64_t out_w = tensor_last_dim(sess, 0, 0, &out_type);
if (out_type != ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT)
INTRO_FAIL("%s: output is not a float tensor; provide an explicit io_spec",
PREDICT_ERR_IO_SPEC);
int classify = out_w > 1; /* [N,K>1] -> probs; [N,1]/[N] -> value */
int nlabels = classify ? (int)out_w : 0;
/* feature count from the query input's last dim (may be dynamic = -1) */
ONNXTensorElementDataType in_type;
size_t q_idx = 0; /* vector: the only input; in_context: x_query */
int layout_incontext = (n_in == 3);
if (layout_incontext) {
/* need inputs named x_train / y_train / x_query to map them */
int has_xt = 0, has_yt = 0, has_xq = 0;
for (int i = 0; i < 3; i++) {
if (strcmp(in_names[i], "x_train") == 0)
has_xt = 1;
else if (strcmp(in_names[i], "y_train") == 0)
has_yt = 1;
else if (strcmp(in_names[i], "x_query") == 0) {
has_xq = 1;
q_idx = i;
}
}
if (!has_xt || !has_yt || !has_xq)
INTRO_FAIL("%s: 3-input model must name its inputs x_train/y_train/"
"x_query to auto-derive; provide an explicit io_spec",
PREDICT_ERR_IO_SPEC);
}
int64_t nfeat = tensor_last_dim(sess, 1, q_idx, &in_type);
/* build the io_spec JSON via json_object (proper escaping of names) */
char *labels_json = NULL;
if (classify) {
sqlite3_str *ls = sqlite3_str_new(db);
sqlite3_str_appendchar(ls, 1, '[');
for (int k = 0; k < nlabels; k++)
sqlite3_str_appendf(ls, "%s\"%d\"", k ? "," : "", k);
sqlite3_str_appendchar(ls, 1, ']');
labels_json = sqlite3_str_finish(ls);
}
const char *sql =
layout_incontext
? "SELECT json_object('layout','in_context','nfeatures',?1,"
"'inputs',json_object('x_train','x_train','y_train','y_train',"
"'x_query','x_query'),'output',"
"CASE WHEN ?5 THEN json_object('name',?2,'kind','probs','labels',"
"json(?4)) ELSE json_object('name',?2,'kind','value') END)"
: "SELECT json_object('layout','vector','nfeatures',?1,'input',?3,"
"'output',CASE WHEN ?5 THEN json_object('name',?2,'kind','probs',"
"'labels',json(?4)) ELSE json_object('name',?2,'kind','value')"
" END)";
if (sqlite3_prepare_v2(db, sql, -1, &bld, NULL) != SQLITE_OK)
INTRO_FAIL("%s: could not build io_spec", PREDICT_ERR_IO_SPEC);
if (nfeat > 0)
sqlite3_bind_int64(bld, 1, nfeat);
else
sqlite3_bind_null(bld, 1); /* dynamic feature dim: validated at run time */
sqlite3_bind_text(bld, 2, out_name, -1, SQLITE_STATIC);
sqlite3_bind_text(bld, 3, in_names[0], -1, SQLITE_STATIC);
if (labels_json)
sqlite3_bind_text(bld, 4, labels_json, -1, SQLITE_STATIC);
else
sqlite3_bind_null(bld, 4);
sqlite3_bind_int(bld, 5, classify);
if (sqlite3_step(bld) == SQLITE_ROW)
*io_spec_out =
sqlite3_mprintf("%s", (const char *)sqlite3_column_text(bld, 0));
sqlite3_free(labels_json);
if (!*io_spec_out)
INTRO_FAIL("%s: could not serialize io_spec", PREDICT_ERR_IO_SPEC);
rc = SQLITE_OK;
#undef INTRO_FAIL
done:
if (bld)
sqlite3_finalize(bld);
for (int i = 0; i < 3; i++)
sqlite3_free(in_names[i]);
sqlite3_free(out_name);
if (sess)
g_ort->ReleaseSession(sess);
return rc;
}
/* ---- io_spec parsing ---- */
typedef enum { LAYOUT_VECTOR, LAYOUT_INCONTEXT } onnx_layout;
typedef struct {
onnx_layout layout;
/* vector: the single feature input. in_context: the x_query input. */
char *input_name;
/* in_context only: the training-context inputs and the train y column */
char *x_train_name;
char *y_train_name;
char *target_name;
char **features; /* feature order (optional); empty => positional mapping */
int nfeat; /* count of named features (0 => positional) */
int nfeatures; /* expected feature count for validation (0 => unknown) */
char *output_name;
char *output_kind; /* 'probs' | 'logits' | 'label' | 'value' */
char **labels;
int nlabels;
} onnx_io;
static void onnx_io_free(onnx_io *io) {
sqlite3_free(io->input_name);
sqlite3_free(io->x_train_name);
sqlite3_free(io->y_train_name);
sqlite3_free(io->target_name);
for (int i = 0; i < io->nfeat; i++)
sqlite3_free(io->features[i]);
sqlite3_free(io->features);
sqlite3_free(io->output_name);
sqlite3_free(io->output_kind);
for (int i = 0; i < io->nlabels; i++)
sqlite3_free(io->labels[i]);
sqlite3_free(io->labels);
memset(io, 0, sizeof(*io));
}
/* scalar json_extract(json, path) -> sqlite3_malloc'd text, NULL if absent */
static char *json_str(sqlite3 *db, const char *json, const char *path) {
sqlite3_stmt *s = NULL;
char *out = NULL;
if (sqlite3_prepare_v2(db, "SELECT json_extract(?1, ?2)", -1, &s, NULL) ==
SQLITE_OK) {
sqlite3_bind_text(s, 1, json, -1, SQLITE_STATIC);
sqlite3_bind_text(s, 2, path, -1, SQLITE_STATIC);
if (sqlite3_step(s) == SQLITE_ROW &&
sqlite3_column_type(s, 0) != SQLITE_NULL)
out = sqlite3_mprintf("%s", (const char *)sqlite3_column_text(s, 0));
}
sqlite3_finalize(s);
return out;
}
/* json boolean at path -> 1 if true, else 0 (JSON true extracts as integer 1). */
static int json_flag(sqlite3 *db, const char *json, const char *path) {
char *v = json_str(db, json, path);
int on = v && (strcmp(v, "1") == 0 || strcmp(v, "true") == 0);
sqlite3_free(v);
return on;
}
/* json array at path -> sqlite3_malloc'd char*[]; *n set. SQLITE_OK on success.
* An absent array is not an error: it yields *n == 0, so optional fields read
* as "not declared". A present-but-malformed array is an error and is never
* swallowed: the return code and *errmsg (ownership transfers to the caller)
* always propagate. max caps the element count (0 = unbounded). */
static int json_arr(sqlite3 *db, const char *json, const char *path,
char ***out, int *n, int max, char **errmsg) {
return predict0_json_str_array(db, json, path, out, n, max, errmsg);
}
static int onnx_io_parse(sqlite3 *db, const char *io_spec, onnx_io *io,
char **errmsg) {
memset(io, 0, sizeof(*io));
if (!io_spec) {
*errmsg = sqlite3_mprintf("%s: model has no io_spec", PREDICT_ERR_IO_SPEC);
return SQLITE_ERROR;
}
char *layout = json_str(db, io_spec, "$.layout");
int is_vector = layout && strcmp(layout, "vector") == 0;
int is_incontext = layout && strcmp(layout, "in_context") == 0;
if (!is_vector && !is_incontext) {
*errmsg = sqlite3_mprintf(
"%s: io_spec layout must be 'vector' or 'in_context'; got '%s'",
PREDICT_ERR_IO_SPEC, layout ? layout : "(none)");
sqlite3_free(layout);
return SQLITE_ERROR;
}
sqlite3_free(layout);
io->layout = is_incontext ? LAYOUT_INCONTEXT : LAYOUT_VECTOR;
/* output + feature schema are common to both layouts. features[] is
* optional: when absent the backend maps apply columns positionally, and
* nfeatures (if given) is the count to validate against. */
io->output_name = json_str(db, io_spec, "$.output.name");
io->output_kind = json_str(db, io_spec, "$.output.kind");
/* features[] is optional (absent -> nfeat 0, positional mapping), but a
* present-but-malformed array must fail loudly rather than read as absent. */
int rc_features = json_arr(db, io_spec, "$.features", &io->features,
&io->nfeat, PREDICT_MAX_FEAT, errmsg);
if (rc_features != SQLITE_OK) {
onnx_io_free(io);
return rc_features;
}
/* Labels bound the class space; cap them and surface an oversized set instead
* of silently truncating. Features use PREDICT_MAX_FEAT and positional
* mapping. */
int rc_labels = json_arr(db, io_spec, "$.output.labels", &io->labels,
&io->nlabels, PREDICT0_MAX_CLASS, errmsg);
if (rc_labels != SQLITE_OK) {
onnx_io_free(io);
return rc_labels;
}
char *nf = json_str(db, io_spec, "$.nfeatures");
io->nfeatures = nf ? atoi(nf) : io->nfeat; /* names imply their own count */
sqlite3_free(nf);
int inputs_ok;
if (io->layout == LAYOUT_VECTOR) {
io->input_name = json_str(db, io_spec, "$.input");
inputs_ok = io->input_name != NULL;
} else {
/* the model ingests the training rows as context each call */
io->input_name = json_str(db, io_spec, "$.inputs.x_query");
io->x_train_name = json_str(db, io_spec, "$.inputs.x_train");
io->y_train_name = json_str(db, io_spec, "$.inputs.y_train");
io->target_name = json_str(db, io_spec, "$.target");
inputs_ok = io->input_name && io->x_train_name && io->y_train_name &&
io->target_name;
}
int have_out = io->output_name && io->output_kind;
int classify = io->output_kind &&
(strcmp(io->output_kind, "probs") == 0 ||
strcmp(io->output_kind, "logits") == 0 ||
strcmp(io->output_kind, "label") == 0);
int regress = io->output_kind && strcmp(io->output_kind, "value") == 0;
if (!inputs_ok || !have_out || (!classify && !regress) ||
(classify && io->nlabels == 0)) {
*errmsg = sqlite3_mprintf(
"%s: io_spec needs output.name/kind"
" ('probs'|'logits'|'label'|'value'), labels[] for classifiers, and"
" the input names for its layout (vector: input; in_context:"
" inputs.x_train/y_train/x_query + target). features[] is optional"
" (positional mapping when omitted)",
PREDICT_ERR_IO_SPEC);
onnx_io_free(io);
return SQLITE_ERROR;
}
return SQLITE_OK;
}
/* ---- session cache ---- */
/* Build a session for (model, device, precision). Caller holds the mutex. */
static int onnx_build_session(const predict0_model_row *model,
const predict0_backend_opts *opts,
OrtSession **out, char **errmsg) {
int rc = SQLITE_OK;
OrtSessionOptions *so = NULL;
*out = NULL;
#define BUILD_CHECK(expr, code, ctx) \
do { \
OrtStatus *st_ = (expr); \
if (st_) { \
rc = onnx_fail(st_, code, ctx, errmsg); \
goto fail; \
} \
} while (0)
BUILD_CHECK(g_ort->CreateSessionOptions(&so), PREDICT_ERR_INFERENCE,
"CreateSessionOptions");
/* 0 lets onnxruntime pick a sane thread count. */
BUILD_CHECK(g_ort->SetIntraOpNumThreads(so, 0), PREDICT_ERR_INFERENCE,
"SetIntraOpNumThreads");
const char *device = opts->device ? opts->device : "cpu";
if (strcmp(device, "cpu") == 0) {
/* CPU EP is always present; nothing to append. */
} else if (strcmp(device, "coreml") == 0) {
#ifdef __APPLE__
BUILD_CHECK(OrtSessionOptionsAppendExecutionProvider_CoreML(so, 0),
PREDICT_ERR_RUNTIME_UNAVAILABLE, "append CoreML EP");
#else
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: CoreML is only available on Apple platforms",
PREDICT_ERR_RUNTIME_UNAVAILABLE);
goto fail;
#endif
} else if (strcmp(device, "cuda") == 0 || strcmp(device, "tensorrt") == 0) {
#ifdef SQLITE_PREDICT_ONNX_GPU
/* Real provider-options wiring. Appending fails loud if the EP is not in
* this onnxruntime build (i.e. onnxruntime-gpu is required). Compiled
* against the CPU headers for the CI compile-check; exercised for real on
* the gated GPU job. */
int fp16 = opts->precision && strcmp(opts->precision, "fp16") == 0;
if (strcmp(device, "cuda") == 0) {
OrtCUDAProviderOptionsV2 *cu = NULL;
BUILD_CHECK(g_ort->CreateCUDAProviderOptions(&cu),
PREDICT_ERR_RUNTIME_UNAVAILABLE, "CreateCUDAProviderOptions");
/* CUDA EP runs the model's own dtype; fp16 comes from an fp16 model,
* not an EP flag. */
OrtStatus *ap =
g_ort->SessionOptionsAppendExecutionProvider_CUDA_V2(so, cu);
g_ort->ReleaseCUDAProviderOptions(cu);
BUILD_CHECK(ap, PREDICT_ERR_RUNTIME_UNAVAILABLE, "append CUDA EP");
} else {
OrtTensorRTProviderOptionsV2 *trt = NULL;
BUILD_CHECK(g_ort->CreateTensorRTProviderOptions(&trt),
PREDICT_ERR_RUNTIME_UNAVAILABLE,
"CreateTensorRTProviderOptions");
if (fp16) {
const char *keys[] = {"trt_fp16_enable"};
const char *vals[] = {"1"};
OrtStatus *up =
g_ort->UpdateTensorRTProviderOptions(trt, keys, vals, 1);
if (up) {
g_ort->ReleaseTensorRTProviderOptions(trt);
rc = onnx_fail(up, PREDICT_ERR_RUNTIME_UNAVAILABLE,
"trt_fp16_enable", errmsg);
goto fail;
}
}
OrtStatus *ap =
g_ort->SessionOptionsAppendExecutionProvider_TensorRT_V2(so, trt);
g_ort->ReleaseTensorRTProviderOptions(trt);
BUILD_CHECK(ap, PREDICT_ERR_RUNTIME_UNAVAILABLE, "append TensorRT EP");
}
#else
/* Current state: the GPU execution providers are validated on the gated
* GPU CI job and compiled only into the GPU build. This CPU build does
* not silently fall back to CPU for a cuda/tensorrt request. */
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf(
"%s: device '%s' needs the GPU build (loadable-onnx-gpu); this build"
" serves cpu and coreml",
PREDICT_ERR_RUNTIME_UNAVAILABLE, device);
goto fail;
#endif
} else {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf(
"%s: unknown device '%s' (cpu|coreml|cuda|tensorrt)",
PREDICT_ERR_OPTIONS, device);
goto fail;
}
if (model->weights_uri) {
/* content-address check: the file must still hash to the
* content_hash recorded at registration. Runs once per session-cache
* miss, not per call. */
char hex[PREDICT_HEX_BUFSIZE];
char *herr = NULL;
if (predict0_hash_file(model->weights_uri, hex, &herr) != SQLITE_OK) {
rc = SQLITE_ERROR;
*errmsg = herr;
goto fail;
}
if (model->content_hash && strcmp(hex, model->content_hash) != 0) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf(
"%s: weights file does not match the registered content_hash: %s",
PREDICT_ERR_MODEL_HASH, model->weights_uri);
goto fail;
}
BUILD_CHECK(g_ort->CreateSession(g_env, model->weights_uri, so, out),
PREDICT_ERR_INFERENCE, "CreateSession from file");
} else if (model->weights && model->weights_len > 0) {
BUILD_CHECK(g_ort->CreateSessionFromArray(
g_env, model->weights, (size_t)model->weights_len, so, out),
PREDICT_ERR_INFERENCE, "CreateSession from blob");
} else {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: model has no weights to load",
PREDICT_ERR_INFERENCE);
goto fail;
}
#undef BUILD_CHECK
fail:
if (so)
g_ort->ReleaseSessionOptions(so);
return rc;
}
static int onnx_get_session(const predict0_model_row *model,
const predict0_backend_opts *opts,
OrtSession **out, char **errmsg) {
const char *device = opts->device ? opts->device : "cpu";
const char *precision = opts->precision ? opts->precision : "fp32";
char *key =
sqlite3_mprintf("%s|%s|%s", model->content_hash, device, precision);
if (!key) {
*errmsg = sqlite3_mprintf("%s: out of memory", PREDICT_ERR_RESOURCE);
return SQLITE_NOMEM;
}
sqlite3_mutex *mx = onnx_mutex();
sqlite3_mutex_enter(mx);
for (onnx_session *n = g_cache; n; n = n->next) {
if (strcmp(n->key, key) == 0) {
*out = n->session;
sqlite3_mutex_leave(mx);
sqlite3_free(key);
return SQLITE_OK;
}
}
OrtSession *sess = NULL;
int rc = onnx_build_session(model, opts, &sess, errmsg);
if (rc != SQLITE_OK) {
sqlite3_mutex_leave(mx);
sqlite3_free(key);
return rc;
}
onnx_session *node = sqlite3_malloc(sizeof(*node));
if (!node) {
g_ort->ReleaseSession(sess);
sqlite3_mutex_leave(mx);
sqlite3_free(key);
*errmsg = sqlite3_mprintf("%s: out of memory", PREDICT_ERR_RESOURCE);
return SQLITE_NOMEM;
}
node->key = key;
node->session = sess;
node->next = g_cache;
g_cache = node;
*out = sess;
sqlite3_mutex_leave(mx);
return SQLITE_OK;
}
/* ---- license gate ---- */
/* A permissive license runs freely; anything else requires the caller to
* name it in accept_license, so a non-commercial model (TabFM) cannot be
* used by accident. */
static int license_ok(const char *license, const char *accepted) {
if (!license)
return 0;
/* 'unspecified' is the default when a caller registers their own model
* without a license tag: they vouch for it, so it runs. The gate exists to
* catch redistributed non-commercial weights (e.g. TabFM), which carry an
* explicit restrictive tag and need accept_license to match. */
if (strcmp(license, "unspecified") == 0 || strcmp(license, "MIT") == 0 ||
strcmp(license, "Apache-2.0") == 0 ||
strcmp(license, "MIT OR Apache-2.0") == 0 ||
strcmp(license, "BSD-3-Clause") == 0 || strcmp(license, "CC0-1.0") == 0)
return 1;
return accepted && strcmp(accepted, license) == 0;
}
/* ---- output decoding (shared by both layouts) ---- */
/* Decode a [nbatch, width] float output tensor into predictions on
* rows[batch_row[b]]. Does not take ownership of `output`. */
static int decode_output(OrtValue *output, const onnx_io *io, int classify,
predict0_result *rows, const int *batch_row,
int nbatch, char **errmsg) {
int rc = SQLITE_OK;
OrtTensorTypeAndShapeInfo *ti = NULL;
size_t ndim = 0;
int64_t odims[8];
float *odata = NULL;
OrtStatus *st = g_ort->GetTensorTypeAndShape(output, &ti);
if (st) {
rc = onnx_fail(st, PREDICT_ERR_INFERENCE, "GetTensorTypeAndShape", errmsg);
goto out;
}
st = g_ort->GetDimensionsCount(ti, &ndim);
if (st) {
rc = onnx_fail(st, PREDICT_ERR_INFERENCE, "GetDimensionsCount", errmsg);
goto out;
}
if (ndim < 1 || ndim > 8) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: output has %zu dims (expected 1-2)",
PREDICT_ERR_INFERENCE, ndim);
goto out;
}
st = g_ort->GetDimensions(ti, odims, ndim);
if (st) {
rc = onnx_fail(st, PREDICT_ERR_INFERENCE, "GetDimensions", errmsg);
goto out;
}
int width = ndim == 1 ? 1 : (int)odims[ndim - 1];
st = g_ort->GetTensorMutableData(output, (void **)&odata);
if (st) {
rc = onnx_fail(st, PREDICT_ERR_INFERENCE, "GetTensorMutableData", errmsg);
goto out;
}
if (classify && width != io->nlabels) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: output width %d does not match %d labels",
PREDICT_ERR_INFERENCE, width, io->nlabels);
goto out;
}
for (int b = 0; b < nbatch; b++) {
predict0_result *out = &rows[batch_row[b]];
float *v = &odata[(size_t)b * width];
if (classify) {
int arg = 0;
for (int c = 1; c < width; c++)
if (v[c] > v[arg])
arg = c;
f64 conf;
if (strcmp(io->output_kind, "logits") == 0) {
f64 sum = 0, mx = v[arg];
for (int c = 0; c < width; c++)
sum += exp((f64)v[c] - mx);
conf = 1.0 / sum; /* softmax value at the argmax */
} else {
conf = (f64)v[arg]; /* already a probability */
}
out->prediction = sqlite3_mprintf("%s", io->labels[arg]);
out->confidence = conf;
out->has_conf = 1;
} else {
out->prediction = sqlite3_mprintf("%.17g", (f64)v[0]);
}
if (!out->prediction) {
rc = SQLITE_NOMEM;
*errmsg = sqlite3_mprintf("%s: out of memory", PREDICT_ERR_RESOURCE);
goto out;
}
out->status = "ok";
}
out:
if (ti)
g_ort->ReleaseTensorTypeAndShapeInfo(ti);
return rc;
}
/* Vector single-input forward pass: nbatch rows of F features -> preds. */
static int run_batch(OrtSession *session, OrtMemoryInfo *mem, const onnx_io *io,
int F, int classify, const f32 *batch, int nbatch,
predict0_result *rows, const int *batch_row,
char **errmsg) {
if (nbatch == 0)
return SQLITE_OK;
int rc = SQLITE_OK;
OrtValue *input = NULL, *output = NULL;
int64_t shape[2] = {nbatch, F};
OrtStatus *st = g_ort->CreateTensorWithDataAsOrtValue(
mem, (void *)batch, sizeof(f32) * (size_t)nbatch * F, shape, 2,
ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, &input);
if (st) {
rc = onnx_fail(st, PREDICT_ERR_INFERENCE, "CreateTensor", errmsg);
goto out;
}
const char *in_names[1] = {io->input_name};
const char *out_names[1] = {io->output_name};
st = g_ort->Run(session, NULL, in_names, (const OrtValue *const *)&input, 1,
out_names, 1, &output);
if (st) {
rc = onnx_fail(st, PREDICT_ERR_INFERENCE, "Run", errmsg);
goto out;
}
rc = decode_output(output, io, classify, rows, batch_row, nbatch, errmsg);
out:
if (output)
g_ort->ReleaseValue(output);
if (input)
g_ort->ReleaseValue(input);
return rc;
}
/* ---- forecast backend (sequence layout: context window -> quantile fan) ---- */
/* Run a two-head "core" sequence model once: input [1, L] -> two fans, each
* [1, Hg, ncol] where column 0 is the point head and columns 1..nq are the
* quantiles. Copies both into caller buffers pt_out and qs_out (each malloc'd
* Hg*ncol, caller frees) and reports Hg. Called once or twice (flip-invariance)
* by seq_reconstruct. Nothing here is model-specific; the shape (ncol) and how
* the two fans combine are all declared in the io_spec. */
static int seq_core_decode(OrtSession *session, OrtMemoryInfo *mem,
const char *in_name, const char *pt_name,
const char *qs_name, const f32 *ctx, int L, int ncol,
int need_h, float **pt_out, float **qs_out,
int *hg_out, char **errmsg) {
*pt_out = NULL;
*qs_out = NULL;
int rc = SQLITE_OK;
OrtValue *input = NULL, *outs[2] = {NULL, NULL};
OrtTensorTypeAndShapeInfo *ti = NULL;
int64_t shape[2] = {1, L};
OrtStatus *st = g_ort->CreateTensorWithDataAsOrtValue(
mem, (void *)ctx, sizeof(f32) * (size_t)L, shape, 2,
ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, &input);
if (st) {
rc = onnx_fail(st, PREDICT_ERR_INFERENCE, "CreateTensor", errmsg);
goto done;
}
const char *in_names[1] = {in_name};
const char *out_names[2] = {pt_name, qs_name};
st = g_ort->Run(session, NULL, in_names, (const OrtValue *const *)&input, 1,
out_names, 2, outs);
if (st) {
rc = onnx_fail(st, PREDICT_ERR_INFERENCE, "Run", errmsg);
goto done;
}
int hg = 0;
for (int o = 0; o < 2; o++) {
size_t ndim = 0;
int64_t od[8];
if (ti) {
g_ort->ReleaseTensorTypeAndShapeInfo(ti);
ti = NULL;
}
st = g_ort->GetTensorTypeAndShape(outs[o], &ti);
if (!st)
st = g_ort->GetDimensionsCount(ti, &ndim);
if (!st && ndim == 3)
st = g_ort->GetDimensions(ti, od, ndim);
if (st) {
rc = onnx_fail(st, PREDICT_ERR_INFERENCE, "GetShape", errmsg);
goto done;
}
if (ndim != 3 || od[0] != 1 || (int)od[2] != ncol) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf(
"%s: two-head core output must be [1, horizon, 1+quantiles=%d]",
PREDICT_ERR_INFERENCE, ncol);
goto done;
}
if (o == 0)
hg = (int)od[1];
else if ((int)od[1] != hg) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: two-head core outputs disagree on horizon",
PREDICT_ERR_INFERENCE);
goto done;
}
}
if (hg < need_h) {
rc = SQLITE_ERROR;
*errmsg = sqlite3_mprintf("%s: model forecasts at most %d steps, %d asked",
PREDICT_ERR_HORIZON, hg, need_h);
goto done;
}
float *pd = NULL, *qd = NULL;
st = g_ort->GetTensorMutableData(outs[0], (void **)&pd);
if (!st)
st = g_ort->GetTensorMutableData(outs[1], (void **)&qd);
if (st) {
rc = onnx_fail(st, PREDICT_ERR_INFERENCE, "GetData", errmsg);
goto done;
}
*pt_out = sqlite3_malloc(sizeof(float) * (size_t)hg * ncol);
*qs_out = sqlite3_malloc(sizeof(float) * (size_t)hg * ncol);
if (!*pt_out || !*qs_out) {
rc = SQLITE_NOMEM;
goto done;
}
memcpy(*pt_out, pd, sizeof(float) * (size_t)hg * ncol);
memcpy(*qs_out, qd, sizeof(float) * (size_t)hg * ncol);
*hg_out = hg;
done:
if (rc != SQLITE_OK) {
sqlite3_free(*pt_out);
sqlite3_free(*qs_out);
*pt_out = NULL;
*qs_out = NULL;
}
if (ti)
g_ort->ReleaseTensorTypeAndShapeInfo(ti);
if (outs[0])
g_ort->ReleaseValue(outs[0]);
if (outs[1])
g_ort->ReleaseValue(outs[1]);
if (input)
g_ort->ReleaseValue(input);
return rc;
}
/* Steps a two-head sequence core needs applied outside the ONNX graph, each
* declared independently in the io_spec (none are model-specific). */
typedef struct {
int flip_invariance; /* average forward with reflected+flipped (TTA) */
int continuous_head; /* blend: quantile spread recentered on point median */
int crossing_repair; /* enforce non-decreasing quantiles per step */
int denorm_instance; /* graph emits normalized; denorm with context mean/std */
} seq_post;
/* col c of a reflected fan under flip-invariance: keep the point head (col 0),
* reverse the quantile columns 1..nq (col c <-> ncol-c). */
#define FAN_FLIP(arr, h, c, ncol) \
((c) == 0 ? (arr)[(size_t)(h) * (ncol)] \
: (arr)[(size_t)(h) * (ncol) + ((ncol) - (c))])
/* Reconstruct a quantile fan from a two-head sequence core by applying the
* post-processing the ONNX graph could not carry (a second decode for flip-
* invariance, the continuous-head blend, crossing repair, instance denorm) as
* declared in `post`. Fills fan[horizon*nq] step-major. Column layout: col 0 is
* the point head, cols 1..nq the quantiles in io_spec order. This mirrors
* scripts/export_timesfm_onnx.py reconstruct() but is driven entirely by flags,
* so any two-head quantile core exported the same way is served, not just one. */
static int seq_reconstruct(OrtSession *session, const char *in_name,
const char *pt_name, const char *qs_name,
const f64 *ctx, int L, int horizon, int nq,
const f32 *levels, const seq_post *post, f64 *fan,
char **errmsg) {
int ncol = nq + 1;
int med = 0; /* column of the 0.5 quantile, for the continuous-head recenter */
if (post->continuous_head) {
f32 best = 2.0f;
for (int q = 0; q < nq; q++) {
f32 d = levels[q] < 0.5f ? 0.5f - levels[q] : levels[q] - 0.5f;
if (d < best) {
best = d;
med = q + 1;
}
}
}
int rc = SQLITE_OK, hg = 0, hg2 = 0;
f32 *cf = sqlite3_malloc(sizeof(f32) * (size_t)L);
f32 *rf = sqlite3_malloc(sizeof(f32) * (size_t)L);
f64 *ff = sqlite3_malloc(sizeof(f64) * (size_t)ncol);
f64 *qs = sqlite3_malloc(sizeof(f64) * (size_t)ncol);
f64 *out = sqlite3_malloc(sizeof(f64) * (size_t)ncol);
float *a1 = NULL, *b1 = NULL, *a2 = NULL, *b2 = NULL;
OrtMemoryInfo *mem = NULL;
if (!cf || !rf || !ff || !qs || !out) {
rc = SQLITE_NOMEM;
goto done;
}
f64 mu = 0;
for (int i = 0; i < L; i++)
mu += ctx[i];
mu /= L;
f64 var = 0;
for (int i = 0; i < L; i++)
var += (ctx[i] - mu) * (ctx[i] - mu);
f64 sigma = L > 1 ? sqrt(var / (L - 1)) : 0.0; /* unbiased std, matches torch */
if (sigma < 1e-6)
sigma = 1.0;
for (int i = 0; i < L; i++) {
cf[i] = (f32)ctx[i];
rf[i] = (f32)(2.0 * mu - ctx[i]); /* reflection -> internal -x */
}
OrtStatus *st =
g_ort->CreateCpuMemoryInfo(OrtArenaAllocator, OrtMemTypeDefault, &mem);
if (st) {
rc = onnx_fail(st, PREDICT_ERR_INFERENCE, "CreateCpuMemoryInfo", errmsg);
goto done;
}
if ((rc = seq_core_decode(session, mem, in_name, pt_name, qs_name, cf, L, ncol,
horizon, &a1, &b1, &hg, errmsg)) != SQLITE_OK)
goto done;
if (post->flip_invariance &&
(rc = seq_core_decode(session, mem, in_name, pt_name, qs_name, rf, L, ncol,
horizon, &a2, &b2, &hg2, errmsg)) != SQLITE_OK)
goto done;
for (int h = 0; h < horizon; h++) {
for (int c = 0; c < ncol; c++) {
if (post->flip_invariance) {
ff[c] = ((f64)a1[(size_t)h * ncol + c] - (f64)FAN_FLIP(a2, h, c, ncol)) / 2.0;
qs[c] = ((f64)b1[(size_t)h * ncol + c] - (f64)FAN_FLIP(b2, h, c, ncol)) / 2.0;
} else {
ff[c] = a1[(size_t)h * ncol + c];
qs[c] = b1[(size_t)h * ncol + c];
}
}
for (int c = 0; c < ncol; c++) /* default: serve the quantile head as-is */
out[c] = qs[c];
if (post->continuous_head)
for (int c = 1; c <= nq; c++) /* recenter the spread on the point median */
out[c] = qs[c] - qs[med] + ff[med];
if (post->crossing_repair) {
for (int c = med - 1; c >= 1; c--)
if (out[c] > out[c + 1])
out[c] = out[c + 1];
for (int c = med + 1; c <= nq; c++)
if (out[c] < out[c - 1])
out[c] = out[c - 1];
}
for (int q = 0; q < nq; q++)
fan[(size_t)h * nq + q] =
post->denorm_instance ? out[q + 1] * sigma + mu : out[q + 1];
}
done:
sqlite3_free(cf);
sqlite3_free(rf);
sqlite3_free(ff);
sqlite3_free(qs);
sqlite3_free(out);
sqlite3_free(a1);
sqlite3_free(b1);
sqlite3_free(a2);
sqlite3_free(b2);
if (mem)
g_ort->ReleaseMemoryInfo(mem);
return rc;
}
/* Run the sequence model and return its raw quantile fan for the horizon:
* *fan_out is malloc'd [horizon * nquant] step-major (fan[k*nquant + q]),
* *levels_out is malloc'd [nquant]; the caller frees both. Used by the
* forecast() point/interval reduction below and by distill_forecast's in-DB
* teacher labeling. */
int predict0_onnx_forecast_fan(sqlite3 *db, const predict0_model_row *model,
const predict0_backend_opts *opts,
const f64 *context, int ctx_len, int horizon,
f64 **fan_out, f32 **levels_out, int *nquant_out,
char **errmsg) {
*fan_out = NULL;
*levels_out = NULL;
*nquant_out = 0;
int rc = SQLITE_OK, nq = 0;
char *input_name = json_str(db, model->io_spec, "$.input");
char *output_name = json_str(db, model->io_spec, "$.output");
char *point_name = json_str(db, model->io_spec, "$.outputs.point");
char *quant_name = json_str(db, model->io_spec, "$.outputs.quantile");
char *patch_s = json_str(db, model->io_spec, "$.patch");
char *layout = json_str(db, model->io_spec, "$.layout");
char *denorm_s = json_str(db, model->io_spec, "$.denormalize");
int patch = patch_s ? atoi(patch_s) : 1;
/* A two-head core (point + quantile outputs) needs the post-processing the
* ONNX graph could not carry, applied here as declared. Nothing is keyed on a
* model name. */
seq_post post = {
.flip_invariance = json_flag(db, model->io_spec, "$.flip_invariance"),
.continuous_head = json_flag(db, model->io_spec, "$.continuous_head"),
.crossing_repair = json_flag(db, model->io_spec, "$.quantile_crossing_repair"),