Исходный код СУБД 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
import {
  InferenceSession,
  InferenceSessionHandler,
  LoraAdapterHandler,
  SessionHandler,
  Tensor,
  TRACE_FUNC_BEGIN,
  TRACE_FUNC_END,
} from 'onnxruntime-common';
 
import { OnnxruntimeWebAssemblyLoraAdapterHandler } from './lora-adapter-handler';
import { SerializableInternalBuffer, TensorMetadata } from './proxy-messages';
import { copyFromExternalBuffer, createSession, endProfiling, releaseSession, run } from './proxy-wrapper';
import { isGpuBufferSupportedType, isMLTensorSupportedType } from './wasm-common';
import { isNode } from './wasm-utils-env';
import { loadFile } from './wasm-utils-load-file';
 
export const encodeTensorMetadata = (tensor: Tensor, getName: () => string): TensorMetadata => {
  switch (tensor.location) {
    case 'cpu':
      return [tensor.type, tensor.dims, tensor.data, 'cpu'];
    case 'gpu-buffer':
      return [tensor.type, tensor.dims, { gpuBuffer: tensor.gpuBuffer }, 'gpu-buffer'];
    case 'ml-tensor':
      return [tensor.type, tensor.dims, { mlTensor: tensor.mlTensor }, 'ml-tensor'];
    default:
      throw new Error(`invalid data location: ${tensor.location} for ${getName()}`);
  }
};
 
export const decodeTensorMetadata = (tensor: TensorMetadata): Tensor => {
  switch (tensor[3]) {
    case 'cpu':
      return new Tensor(tensor[0], tensor[2], tensor[1]);
    case 'gpu-buffer': {
      const dataType = tensor[0];
      if (!isGpuBufferSupportedType(dataType)) {
        throw new Error(`not supported data type: ${dataType} for deserializing GPU tensor`);
      }
      const { gpuBuffer, download, dispose } = tensor[2];
      return Tensor.fromGpuBuffer(gpuBuffer, { dataType, dims: tensor[1], download, dispose });
    }
    case 'ml-tensor': {
      const dataType = tensor[0];
      if (!isMLTensorSupportedType(dataType)) {
        throw new Error(`not supported data type: ${dataType} for deserializing MLTensor tensor`);
      }
      const { mlTensor, download, dispose } = tensor[2];
      return Tensor.fromMLTensor(mlTensor, { dataType, dims: tensor[1], download, dispose });
    }
    default:
      throw new Error(`invalid data location: ${tensor[3]}`);
  }
};
 
export class OnnxruntimeWebAssemblySessionHandler implements InferenceSessionHandler {
  private sessionId: number;
 
  inputNames: readonly string[];
  outputNames: readonly string[];
  inputMetadata: readonly InferenceSession.ValueMetadata[];
  outputMetadata: readonly InferenceSession.ValueMetadata[];
 
  async fetchModelAndCopyToWasmMemory(path: string): Promise<SerializableInternalBuffer> {
    // fetch model from url and move to wasm heap.
    return copyFromExternalBuffer(await loadFile(path));
  }
 
  async loadModel(pathOrBuffer: string | Uint8Array, options?: InferenceSession.SessionOptions): Promise<void> {
    TRACE_FUNC_BEGIN();
    let model: Parameters<typeof createSession>[0];
 
    if (typeof pathOrBuffer === 'string') {
      if (isNode) {
        // node
        model = await loadFile(pathOrBuffer);
      } else {
        // browser
        // fetch model and copy to wasm heap.
        model = await this.fetchModelAndCopyToWasmMemory(pathOrBuffer);
      }
    } else {
      model = pathOrBuffer;
    }
 
    [this.sessionId, this.inputNames, this.outputNames, this.inputMetadata, this.outputMetadata] = await createSession(
      model,
      options,
    );
    TRACE_FUNC_END();
  }
 
  async dispose(): Promise<void> {
    return releaseSession(this.sessionId);
  }
 
  async run(
    feeds: SessionHandler.FeedsType,
    fetches: SessionHandler.FetchesType,
    options: InferenceSession.RunOptions,
    activeLoraAdapters: readonly LoraAdapterHandler[] = [],
  ): Promise<SessionHandler.ReturnType> {
    TRACE_FUNC_BEGIN();
    const loraAdapterIds = activeLoraAdapters.map((adapter) => {
      if (!(adapter instanceof OnnxruntimeWebAssemblyLoraAdapterHandler)) {
        throw new Error('LoRA adapter was not created by the WebAssembly backend.');
      }
      return adapter.adapterId;
    });
 
    const inputArray: Tensor[] = [];
    const inputIndices: number[] = [];
    Object.entries(feeds).forEach((kvp) => {
      const name = kvp[0];
      const tensor = kvp[1];
      const index = this.inputNames.indexOf(name);
      if (index === -1) {
        throw new Error(`invalid input '${name}'`);
      }
      inputArray.push(tensor);
      inputIndices.push(index);
    });
 
    const outputArray: Array<Tensor | null> = [];
    const outputIndices: number[] = [];
    Object.entries(fetches).forEach((kvp) => {
      const name = kvp[0];
      const tensor = kvp[1];
      const index = this.outputNames.indexOf(name);
      if (index === -1) {
        throw new Error(`invalid output '${name}'`);
      }
      outputArray.push(tensor);
      outputIndices.push(index);
    });
 
    const inputs = inputArray.map((t, i) =>
      encodeTensorMetadata(t, () => `input "${this.inputNames[inputIndices[i]]}"`),
    );
    const outputs = outputArray.map((t, i) =>
      t ? encodeTensorMetadata(t, () => `output "${this.outputNames[outputIndices[i]]}"`) : null,
    );
 
    const results = await run(this.sessionId, inputIndices, inputs, outputIndices, outputs, options, loraAdapterIds);
 
    const resultMap: SessionHandler.ReturnType = {};
    for (let i = 0; i < results.length; i++) {
      resultMap[this.outputNames[outputIndices[i]]] = outputArray[i] ?? decodeTensorMetadata(results[i]);
    }
    TRACE_FUNC_END();
    return resultMap;
  }
 
  startProfiling(): void {
    // TODO: implement profiling
  }
 
  endProfiling(): void {
    void endProfiling(this.sessionId);
  }
}