Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
package onnxruntime
 
/*
#include "cshim.h"
#include <stdlib.h>
*/
import "C"
import (
    "context"
    "fmt"
    "math"
    "sync"
    "sync/atomic"
    "unsafe"
)
 
// IOInfo describes a single input or output of a model.
type IOInfo struct {
    Name     string
    DataType TensorElementDataType
    Shape    []int64 // dynamic dimensions are -1
}
 
// Session wraps an ORT inference session. It is safe for concurrent use:
// multiple goroutines may call Run simultaneously.
type Session struct {
    mu        sync.RWMutex
    handle    *C.OrtSession
    inputs    []IOInfo
    outputs   []IOInfo
    nameCache map[string]*C.char
    closed    bool
}
 
// NewSession creates a session from an ONNX model file.
// If opts is nil, default options are used.
func NewSession(modelPath string, opts *SessionOptions) (*Session, error) {
    if err := checkInit(); err != nil {
        return nil, err
    }
 
    ownOpts, opts, err := ensureOpts(opts)
    if err != nil {
        return nil, err
    }
    if ownOpts {
        defer func() { _ = opts.Close() }()
    }
 
    cPath, freePath, err := ortPath(modelPath)
    if err != nil {
        return nil, err
    }
    defer freePath()
 
    if err := opts.lockUsable("create session"); err != nil {
        return nil, err
    }
    var handle *C.OrtSession
    createErr := checkStatus(C.ort_CreateSession(env, cPath, opts.handle, &handle))
    opts.unlock()
    if createErr != nil {
        return nil, wrapErr("create session", createErr)
    }
 
    return finalizeSession(handle)
}
 
// NewSessionFromBytes creates a session from an in-memory ONNX model.
// If opts is nil, default options are used.
func NewSessionFromBytes(model []byte, opts *SessionOptions) (*Session, error) {
    if err := checkInit(); err != nil {
        return nil, err
    }
    if len(model) == 0 {
        return nil, fmt.Errorf("ort: create session: empty model data")
    }
 
    ownOpts, opts, err := ensureOpts(opts)
    if err != nil {
        return nil, err
    }
    if ownOpts {
        defer func() { _ = opts.Close() }()
    }
 
    if err := opts.lockUsable("create session from bytes"); err != nil {
        return nil, err
    }
    var handle *C.OrtSession
    createErr := checkStatus(C.ort_CreateSessionFromArray(
        env, unsafe.Pointer(&model[0]), C.size_t(len(model)), opts.handle, &handle))
    opts.unlock()
    if createErr != nil {
        return nil, wrapErr("create session from bytes", createErr)
    }
 
    return finalizeSession(handle)
}
 
// Inputs returns metadata for all model inputs.
func (s *Session) Inputs() []IOInfo {
    return copyIOInfo(s.inputs)
}
 
// Outputs returns metadata for all model outputs.
func (s *Session) Outputs() []IOInfo {
    return copyIOInfo(s.outputs)
}
 
// Run executes inference. inputs maps input names to tensors. outputNames
// lists which outputs to request; if nil, all outputs are returned.
// The returned tensors must be closed by the caller.
//
// Run is safe for concurrent use on the same session.
func (s *Session) Run(ctx context.Context, inputs map[string]*Tensor, outputNames []string) (map[string]*Tensor, error) {
    s.mu.RLock()
    defer s.mu.RUnlock()
 
    if s.closed {
        return nil, fmt.Errorf("ort: run: session is closed")
    }
 
    if ctx.Err() != nil {
        return nil, ctx.Err()
    }
 
    if outputNames == nil {
        outputNames = make([]string, len(s.outputs))
        for i, o := range s.outputs {
            outputNames[i] = o.Name
        }
    }
 
    if len(outputNames) == 0 {
        return nil, fmt.Errorf("ort: run: no output names specified")
    }
 
    return s.runInner(ctx, inputs, outputNames, nil)
}
 
// RunWithOptions executes inference with explicit run options.
func (s *Session) RunWithOptions(ctx context.Context, opts *RunOptions, inputs map[string]*Tensor, outputNames []string) (map[string]*Tensor, error) {
    s.mu.RLock()
    defer s.mu.RUnlock()
 
    if s.closed {
        return nil, fmt.Errorf("ort: run: session is closed")
    }
 
    if ctx.Err() != nil {
        return nil, ctx.Err()
    }
 
    if outputNames == nil {
        outputNames = make([]string, len(s.outputs))
        for i, o := range s.outputs {
            outputNames[i] = o.Name
        }
    }
 
    if len(outputNames) == 0 {
        return nil, fmt.Errorf("ort: run: no output names specified")
    }
 
    return s.runInner(ctx, inputs, outputNames, opts)
}
 
func (s *Session) runInner(ctx context.Context, inputs map[string]*Tensor, outputNames []string, opts *RunOptions) (map[string]*Tensor, error) {
    nInputs := len(inputs)
    nOutputs := len(outputNames)
    cInputNames := make([]*C.char, nInputs)
    cInputValues := make([]*C.OrtValue, nInputs)
    var tempNames []*C.char
    defer func() {
        for _, cs := range tempNames {
            C.free(unsafe.Pointer(cs))
        }
    }()
    i := 0
    for name, tensor := range inputs {
        if err := rejectNUL(name, "run input name"); err != nil {
            return nil, err
        }
        if tensor == nil || tensor.closed || tensor.value == nil {
            return nil, fmt.Errorf("ort: run: input %q: tensor is nil or closed", name)
        }
        if cached, ok := s.nameCache[name]; ok {
            cInputNames[i] = cached
        } else {
            cs := C.CString(name)
            cInputNames[i] = cs
            tempNames = append(tempNames, cs)
        }
        cInputValues[i] = tensor.value
        i++
    }
 
    cOutputNames := make([]*C.char, nOutputs)
    seenOutputNames := make(map[string]struct{}, nOutputs)
    for i, name := range outputNames {
        if err := rejectNUL(name, "run output name"); err != nil {
            return nil, err
        }
        if _, exists := seenOutputNames[name]; exists {
            return nil, fmt.Errorf("ort: run: duplicate output name %q", name)
        }
        seenOutputNames[name] = struct{}{}
        if cached, ok := s.nameCache[name]; ok {
            cOutputNames[i] = cached
        } else {
            cs := C.CString(name)
            cOutputNames[i] = cs
            tempNames = append(tempNames, cs)
        }
    }
 
    cOutputValues := make([]*C.OrtValue, nOutputs)
 
    var runOpts *C.OrtRunOptions
    if opts != nil {
        if err := opts.lockUsable("run"); err != nil {
            return nil, err
        }
        defer opts.unlock()
        runOpts = opts.handle
    }
 
    // Cancellation is delivered to ORT by setting the terminate flag on the run
    // options, so a cancellable context needs run options even when the caller
    // supplied none.
    if ctx.Done() != nil {
        callerOpts := opts != nil
        if !callerOpts {
            if err := checkStatus(C.ort_CreateRunOptions(&runOpts)); err != nil {
                return nil, wrapErr("create run options", err)
            }
            // Registered before the watcher's stop-and-join defer: defers run LIFO,
            // so the watcher is joined before these run options are released and can
            // never touch freed memory.
            defer C.ort_ReleaseRunOptions(runOpts)
        }
 
        var terminated atomic.Bool
        stopWatcher := make(chan struct{})
        watcherDone := make(chan struct{})
        done := ctx.Done()
        go func() {
            defer close(watcherDone)
            select {
            case <-done:
                // A failed terminate can only mean cancellation goes unnoticed;
                // the run's own result is reported instead.
                _ = checkStatus(C.ort_RunOptionsSetTerminate(runOpts))
                terminated.Store(true)
            case <-stopWatcher:
            }
        }()
        defer func() {
            close(stopWatcher)
            <-watcherDone
            // The terminate flag is sticky: left set, it would abort the caller's
            // next run with these options.
            if callerOpts && terminated.Load() {
                opts.restoreTerminate(runOpts)
            }
        }()
    }
 
    var inNamesPtr **C.char
    var inValuesPtr **C.OrtValue
    if nInputs > 0 {
        inNamesPtr = &cInputNames[0]
        inValuesPtr = &cInputValues[0]
    }
 
    err := checkStatus(C.ort_Run(
        s.handle, runOpts,
        inNamesPtr,
        inValuesPtr, C.size_t(nInputs),
        &cOutputNames[0], C.size_t(nOutputs),
        &cOutputValues[0],
    ))
 
    if err != nil {
        for _, v := range cOutputValues {
            if v != nil {
                C.ort_ReleaseValue(v)
            }
        }
        if ctx.Err() != nil {
            return nil, ctx.Err()
        }
        return nil, wrapErr("run", err)
    }
 
    result := make(map[string]*Tensor, nOutputs)
    for i, name := range outputNames {
        t, err := wrapOutputTensor(cOutputValues[i])
        if err != nil {
            for _, v := range cOutputValues[i:] {
                if v != nil {
                    C.ort_ReleaseValue(v)
                }
            }
            for _, existing := range result {
                _ = existing.Close()
            }
            return nil, wrapErr("wrap output "+name, err)
        }
        result[name] = t
    }
 
    return result, nil
}
 
// EndProfiling ends profiling and returns the profile file path.
func (s *Session) EndProfiling() (string, error) {
    s.mu.RLock()
    defer s.mu.RUnlock()
 
    if s.closed {
        return "", fmt.Errorf("ort: end profiling: session is closed")
    }
 
    var allocator *C.OrtAllocator
    if err := checkStatus(C.ort_GetAllocatorWithDefaultOptions(&allocator)); err != nil {
        return "", wrapErr("get allocator", err)
    }
 
    var cPath *C.char
    if err := checkStatus(C.ort_SessionEndProfiling(s.handle, allocator, &cPath)); err != nil {
        return "", wrapErr("end profiling", err)
    }
    path := C.GoString(cPath)
    C.ort_AllocatorFree(allocator, unsafe.Pointer(cPath))
    return path, nil
}
 
// Close releases the session. It is idempotent. Close waits for any
// in-flight Run calls to complete.
func (s *Session) Close() error {
    if s == nil {
        return nil
    }
    s.mu.Lock()
    defer s.mu.Unlock()
 
    if s.closed {
        return nil
    }
    s.closed = true
    for _, cs := range s.nameCache {
        C.free(unsafe.Pointer(cs))
    }
    s.nameCache = nil
    C.ort_ReleaseSession(s.handle)
    s.handle = nil
    sessionCount.Add(-1)
    return nil
}
 
func ensureOpts(opts *SessionOptions) (bool, *SessionOptions, error) {
    if opts != nil {
        return false, opts, nil
    }
    o, err := NewSessionOptions()
    if err != nil {
        return false, nil, err
    }
    return true, o, nil
}
 
func finalizeSession(handle *C.OrtSession) (*Session, error) {
    inputs, err := introspectIO(handle, true)
    if err != nil {
        C.ort_ReleaseSession(handle)
        return nil, err
    }
 
    outputs, err := introspectIO(handle, false)
    if err != nil {
        C.ort_ReleaseSession(handle)
        return nil, err
    }
 
    cache := make(map[string]*C.char, len(inputs)+len(outputs))
    for _, info := range inputs {
        cache[info.Name] = C.CString(info.Name)
    }
    for _, info := range outputs {
        if _, ok := cache[info.Name]; !ok {
            cache[info.Name] = C.CString(info.Name)
        }
    }
 
    sessionCount.Add(1)
    return &Session{
        handle:    handle,
        inputs:    inputs,
        outputs:   outputs,
        nameCache: cache,
    }, nil
}
 
func introspectIO(session *C.OrtSession, isInput bool) ([]IOInfo, error) {
    var count C.size_t
    var err error
    if isInput {
        err = checkStatus(C.ort_SessionGetInputCount(session, &count))
    } else {
        err = checkStatus(C.ort_SessionGetOutputCount(session, &count))
    }
    if err != nil {
        return nil, wrapErr("get io count", err)
    }
    if uint64(count) > uint64(math.MaxInt)/uint64(unsafe.Sizeof(IOInfo{})) {
        return nil, fmt.Errorf("ort: get io count: count %d exceeds addressable range", uint64(count))
    }
 
    var allocator *C.OrtAllocator
    if err := checkStatus(C.ort_GetAllocatorWithDefaultOptions(&allocator)); err != nil {
        return nil, wrapErr("get allocator", err)
    }
 
    infos := make([]IOInfo, int(count))
    for i := C.size_t(0); i < count; i++ {
        var cName *C.char
        if isInput {
            err = checkStatus(C.ort_SessionGetInputName(session, i, allocator, &cName))
        } else {
            err = checkStatus(C.ort_SessionGetOutputName(session, i, allocator, &cName))
        }
        if err != nil {
            return nil, wrapErr("get io name", err)
        }
        infos[i].Name = C.GoString(cName)
        C.ort_AllocatorFree(allocator, unsafe.Pointer(cName))
 
        var typeInfo *C.OrtTypeInfo
        if isInput {
            err = checkStatus(C.ort_SessionGetInputTypeInfo(session, i, &typeInfo))
        } else {
            err = checkStatus(C.ort_SessionGetOutputTypeInfo(session, i, &typeInfo))
        }
        if err != nil {
            return nil, wrapErr("get io type info", err)
        }
 
        var onnxType C.enum_ONNXType
        if err := checkStatus(C.ort_GetOnnxTypeFromTypeInfo(typeInfo, &onnxType)); err != nil {
            C.ort_ReleaseTypeInfo(typeInfo)
            return nil, wrapErr("get onnx type", err)
        }
 
        if onnxType == C.ONNX_TYPE_TENSOR {
            var tensorInfo *C.OrtTensorTypeAndShapeInfo
            if err := checkStatus(C.ort_CastTypeInfoToTensorInfo(typeInfo, &tensorInfo)); err != nil {
                C.ort_ReleaseTypeInfo(typeInfo)
                return nil, wrapErr("cast to tensor info", err)
            }
 
            var cDtype C.enum_ONNXTensorElementDataType
            if err := checkStatus(C.ort_GetTensorElementType(tensorInfo, &cDtype)); err != nil {
                C.ort_ReleaseTypeInfo(typeInfo)
                return nil, wrapErr("get element type", err)
            }
            infos[i].DataType = TensorElementDataType(cDtype)
 
            var ndims C.size_t
            if err := checkStatus(C.ort_GetDimensionsCount(tensorInfo, &ndims)); err != nil {
                C.ort_ReleaseTypeInfo(typeInfo)
                return nil, wrapErr("get dims count", err)
            }
            if uint64(ndims) > uint64(math.MaxInt/int(unsafe.Sizeof(int64(0)))) {
                C.ort_ReleaseTypeInfo(typeInfo)
                return nil, fmt.Errorf("ort: get dims: dimension count %d exceeds addressable range", uint64(ndims))
            }
 
            shape := make([]int64, int(ndims))
            if ndims > 0 {
                if err := checkStatus(C.ort_GetDimensions(tensorInfo,
                    (*C.int64_t)(unsafe.Pointer(&shape[0])), ndims)); err != nil {
                    C.ort_ReleaseTypeInfo(typeInfo)
                    return nil, wrapErr("get dims", err)
                }
            }
            infos[i].Shape = shape
        }
 
        C.ort_ReleaseTypeInfo(typeInfo)
    }
 
    return infos, nil
}
 
func copyIOInfo(infos []IOInfo) []IOInfo {
    out := make([]IOInfo, len(infos))
    for i, info := range infos {
        out[i] = IOInfo{
            Name:     info.Name,
            DataType: info.DataType,
            Shape:    copyShape(info.Shape),
        }
    }
    return out
}