-
Notifications
You must be signed in to change notification settings - Fork 548
Expand file tree
/
Copy pathml_binding.go
More file actions
344 lines (287 loc) · 8.99 KB
/
ml_binding.go
File metadata and controls
344 lines (287 loc) · 8.99 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
// Package ml_binding provides Go bindings for Linfa-based traditional ML algorithms.
//
// This package wraps Rust implementations of:
// - KNN (K-Nearest Neighbors) via linfa-nn
// - KMeans clustering via linfa-clustering
// - SVM (Support Vector Machine) via linfa-svm
//
// Reference: FusionFactory (arXiv:2507.10540) - Query-level fusion via tailored LLM routers
//
// Training is done in Python (src/training/model_selection/ml_model_selection/).
// This package provides inference-only functionality, loading models from JSON.
package ml_binding
/*
#cgo LDFLAGS: -L${SRCDIR}/target/release -lml_semantic_router -lm -ldl -lpthread
#include <stdlib.h>
#include <stdint.h>
// KNN functions (inference only - training done in Python)
void* ml_knn_new(int k);
void ml_knn_free(void* handle);
char* ml_knn_select(void* handle, double* query, size_t query_len);
int ml_knn_is_trained(void* handle);
char* ml_knn_to_json(void* handle);
void* ml_knn_from_json(char* json);
// KMeans functions (inference only - training done in Python)
void* ml_kmeans_new(int num_clusters);
void ml_kmeans_free(void* handle);
char* ml_kmeans_select(void* handle, double* query, size_t query_len);
int ml_kmeans_is_trained(void* handle);
char* ml_kmeans_to_json(void* handle);
void* ml_kmeans_from_json(char* json);
// SVM functions (inference only - training done in Python)
void* ml_svm_new();
void* ml_svm_new_with_kernel(int kernel_type, double gamma);
void ml_svm_free(void* handle);
char* ml_svm_select(void* handle, double* query, size_t query_len);
int ml_svm_is_trained(void* handle);
char* ml_svm_to_json(void* handle);
void* ml_svm_from_json(char* json);
// Memory management
void ml_free_string(char* ptr);
*/
import "C"
import (
"errors"
"sync"
"unsafe"
)
// =============================================================================
// KNN Selector (Inference Only)
// =============================================================================
// KNNSelector wraps the Linfa KNN implementation for inference
type KNNSelector struct {
handle unsafe.Pointer
mu sync.RWMutex
}
// NewKNNSelector creates a new KNN selector with the specified k value
func NewKNNSelector(k int) *KNNSelector {
handle := C.ml_knn_new(C.int(k))
if handle == nil {
return nil
}
return &KNNSelector{handle: handle}
}
// Close releases the KNN selector resources
func (s *KNNSelector) Close() {
s.mu.Lock()
defer s.mu.Unlock()
if s.handle != nil {
C.ml_knn_free(s.handle)
s.handle = nil
}
}
// Select selects the best model for a query embedding
func (s *KNNSelector) Select(query []float64) (string, error) {
s.mu.RLock()
defer s.mu.RUnlock()
if s.handle == nil {
return "", errors.New("selector not initialized")
}
cQuery := make([]C.double, len(query))
for i, v := range query {
cQuery[i] = C.double(v)
}
result := C.ml_knn_select(s.handle, &cQuery[0], C.size_t(len(query)))
if result == nil {
return "", errors.New("KNN selection failed")
}
defer C.ml_free_string(result)
return C.GoString(result), nil
}
// IsTrained returns whether the model has been loaded
func (s *KNNSelector) IsTrained() bool {
s.mu.RLock()
defer s.mu.RUnlock()
if s.handle == nil {
return false
}
return C.ml_knn_is_trained(s.handle) != 0
}
// ToJSON serializes the model to JSON
func (s *KNNSelector) ToJSON() (string, error) {
if s.handle == nil {
return "", errors.New("selector not initialized")
}
result := C.ml_knn_to_json(s.handle)
if result == nil {
return "", errors.New("JSON serialization failed")
}
defer C.ml_free_string(result)
return C.GoString(result), nil
}
// KNNFromJSON loads a KNN selector from JSON (the primary way to load trained models)
func KNNFromJSON(json string) (*KNNSelector, error) {
cJSON := C.CString(json)
defer C.free(unsafe.Pointer(cJSON))
handle := C.ml_knn_from_json(cJSON)
if handle == nil {
return nil, errors.New("failed to load KNN from JSON")
}
return &KNNSelector{handle: handle}, nil
}
// =============================================================================
// KMeans Selector (Inference Only)
// =============================================================================
// KMeansSelector wraps the Linfa KMeans implementation for inference
type KMeansSelector struct {
handle unsafe.Pointer
mu sync.RWMutex
}
// NewKMeansSelector creates a new KMeans selector with the specified number of clusters
func NewKMeansSelector(numClusters int) *KMeansSelector {
handle := C.ml_kmeans_new(C.int(numClusters))
if handle == nil {
return nil
}
return &KMeansSelector{handle: handle}
}
// Close releases the KMeans selector resources
func (s *KMeansSelector) Close() {
s.mu.Lock()
defer s.mu.Unlock()
if s.handle != nil {
C.ml_kmeans_free(s.handle)
s.handle = nil
}
}
// Select selects the best model for a query embedding
func (s *KMeansSelector) Select(query []float64) (string, error) {
s.mu.RLock()
defer s.mu.RUnlock()
if s.handle == nil {
return "", errors.New("selector not initialized")
}
cQuery := make([]C.double, len(query))
for i, v := range query {
cQuery[i] = C.double(v)
}
result := C.ml_kmeans_select(s.handle, &cQuery[0], C.size_t(len(query)))
if result == nil {
return "", errors.New("KMeans selection failed")
}
defer C.ml_free_string(result)
return C.GoString(result), nil
}
// IsTrained returns whether the model has been loaded
func (s *KMeansSelector) IsTrained() bool {
s.mu.RLock()
defer s.mu.RUnlock()
if s.handle == nil {
return false
}
return C.ml_kmeans_is_trained(s.handle) != 0
}
// ToJSON serializes the model to JSON
func (s *KMeansSelector) ToJSON() (string, error) {
if s.handle == nil {
return "", errors.New("selector not initialized")
}
result := C.ml_kmeans_to_json(s.handle)
if result == nil {
return "", errors.New("JSON serialization failed")
}
defer C.ml_free_string(result)
return C.GoString(result), nil
}
// KMeansFromJSON loads a KMeans selector from JSON (the primary way to load trained models)
func KMeansFromJSON(json string) (*KMeansSelector, error) {
cJSON := C.CString(json)
defer C.free(unsafe.Pointer(cJSON))
handle := C.ml_kmeans_from_json(cJSON)
if handle == nil {
return nil, errors.New("failed to load KMeans from JSON")
}
return &KMeansSelector{handle: handle}, nil
}
// =============================================================================
// SVM Selector (Inference Only)
// =============================================================================
// SVMKernelType defines the kernel type for SVM
type SVMKernelType int
const (
// SVMKernelLinear uses linear kernel: f(x) = w·x - b
SVMKernelLinear SVMKernelType = 0
// SVMKernelRBF uses RBF (Gaussian) kernel: f(x) = Σ(αᵢ·exp(-γ||x-xᵢ||²))
SVMKernelRBF SVMKernelType = 1
)
// SVMSelector wraps the Linfa SVM implementation for inference
type SVMSelector struct {
handle unsafe.Pointer
mu sync.RWMutex
}
// NewSVMSelector creates a new SVM selector with default (RBF) kernel
func NewSVMSelector() *SVMSelector {
handle := C.ml_svm_new()
if handle == nil {
return nil
}
return &SVMSelector{handle: handle}
}
// NewSVMSelectorWithKernel creates a new SVM selector with specified kernel
// kernelType: SVMKernelLinear or SVMKernelRBF
// gamma: RBF gamma parameter (use 0 for auto = 1.0)
func NewSVMSelectorWithKernel(kernelType SVMKernelType, gamma float64) *SVMSelector {
handle := C.ml_svm_new_with_kernel(C.int(kernelType), C.double(gamma))
if handle == nil {
return nil
}
return &SVMSelector{handle: handle}
}
// Close releases the SVM selector resources
func (s *SVMSelector) Close() {
s.mu.Lock()
defer s.mu.Unlock()
if s.handle != nil {
C.ml_svm_free(s.handle)
s.handle = nil
}
}
// Select selects the best model for a query embedding
func (s *SVMSelector) Select(query []float64) (string, error) {
s.mu.RLock()
defer s.mu.RUnlock()
if s.handle == nil {
return "", errors.New("selector not initialized")
}
cQuery := make([]C.double, len(query))
for i, v := range query {
cQuery[i] = C.double(v)
}
result := C.ml_svm_select(s.handle, &cQuery[0], C.size_t(len(query)))
if result == nil {
return "", errors.New("SVM selection failed")
}
defer C.ml_free_string(result)
return C.GoString(result), nil
}
// IsTrained returns whether the model has been loaded
func (s *SVMSelector) IsTrained() bool {
s.mu.RLock()
defer s.mu.RUnlock()
if s.handle == nil {
return false
}
return C.ml_svm_is_trained(s.handle) != 0
}
// ToJSON serializes the model to JSON
func (s *SVMSelector) ToJSON() (string, error) {
if s.handle == nil {
return "", errors.New("selector not initialized")
}
result := C.ml_svm_to_json(s.handle)
if result == nil {
return "", errors.New("JSON serialization failed")
}
defer C.ml_free_string(result)
return C.GoString(result), nil
}
// SVMFromJSON loads an SVM selector from JSON (the primary way to load trained models)
func SVMFromJSON(json string) (*SVMSelector, error) {
cJSON := C.CString(json)
defer C.free(unsafe.Pointer(cJSON))
handle := C.ml_svm_from_json(cJSON)
if handle == nil {
return nil, errors.New("failed to load SVM from JSON")
}
return &SVMSelector{handle: handle}, nil
}