forked from knights-analytics/hugot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hugot.go
333 lines (296 loc) · 11.2 KB
/
hugot.go
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
package hugot
import (
"context"
"errors"
"fmt"
"slices"
util "github.com/knights-analytics/hugot/utils"
ort "github.com/yalue/onnxruntime_go"
"github.com/knights-analytics/hugot/pipelines"
)
// Session allows for the creation of new pipelines and holds the pipeline already created.
type Session struct {
featureExtractionPipelines pipelineMap[*pipelines.FeatureExtractionPipeline]
tokenClassificationPipelines pipelineMap[*pipelines.TokenClassificationPipeline]
textClassificationPipelines pipelineMap[*pipelines.TextClassificationPipeline]
zeroShotClassificationPipelines pipelineMap[*pipelines.ZeroShotClassificationPipeline]
ortOptions *ort.SessionOptions
}
type pipelineMap[T pipelines.Pipeline] map[string]T
func (m pipelineMap[T]) Destroy() error {
var err error
for _, p := range m {
err = p.Destroy()
}
return err
}
func (m pipelineMap[T]) GetStats() []string {
var stats []string
for _, p := range m {
stats = append(stats, p.GetStats()...)
}
return stats
}
// FeatureExtractionConfig is the configuration for a feature extraction pipeline
type FeatureExtractionConfig = pipelines.PipelineConfig[*pipelines.FeatureExtractionPipeline]
// FeatureExtractionOption is an option for a feature extraction pipeline
type FeatureExtractionOption = pipelines.PipelineOption[*pipelines.FeatureExtractionPipeline]
// TextClassificationConfig is the configuration for a text classification pipeline
type TextClassificationConfig = pipelines.PipelineConfig[*pipelines.TextClassificationPipeline]
// type ZSCConfig = pipelines.PipelineConfig[*pipelines.ZeroShotClassificationPipeline]
type ZeroShotClassificationConfig = pipelines.PipelineConfig[*pipelines.ZeroShotClassificationPipeline]
// TextClassificationOption is an option for a text classification pipeline
type TextClassificationOption = pipelines.PipelineOption[*pipelines.TextClassificationPipeline]
// TokenClassificationConfig is the configuration for a token classification pipeline
type TokenClassificationConfig = pipelines.PipelineConfig[*pipelines.TokenClassificationPipeline]
// TokenClassificationOption is an option for a token classification pipeline
type TokenClassificationOption = pipelines.PipelineOption[*pipelines.TokenClassificationPipeline]
// NewSession is the main entrypoint to hugot and is used to create a new hugot session object.
// ortLibraryPath should be the path to onnxruntime.so. If it's the empty string, hugot will try
// to load the library from the default location (/usr/lib/onnxruntime.so).
// A new session must be destroyed when it's not needed any more to avoid memory leaks. See the Destroy method.
// Note moreover that there can be at most one hugot session active (i.e., the Session object is a singleton),
// otherwise NewSession will return an error.
func NewSession(options ...WithOption) (*Session, error) {
if ort.IsInitialized() {
return nil, errors.New("another session is currently active, and only one session can be active at one time")
}
session := &Session{
featureExtractionPipelines: map[string]*pipelines.FeatureExtractionPipeline{},
textClassificationPipelines: map[string]*pipelines.TextClassificationPipeline{},
tokenClassificationPipelines: map[string]*pipelines.TokenClassificationPipeline{},
zeroShotClassificationPipelines: map[string]*pipelines.ZeroShotClassificationPipeline{},
}
// set session options and initialise
if initialised, err := session.initialiseORT(options...); err != nil {
if initialised {
destroyErr := session.Destroy()
return nil, errors.Join(err, destroyErr)
}
return nil, err
}
return session, nil
}
func (s *Session) initialiseORT(options ...WithOption) (bool, error) {
// Collect options into a struct, so they can be applied in the correct order later
o := &ortOptions{}
for _, option := range options {
option(o)
}
// Set pre-initialisation options
if o.libraryPath != "" {
ortPathExists, err := util.FileSystem.Exists(context.Background(), o.libraryPath)
if err != nil {
return false, err
}
if !ortPathExists {
return false, fmt.Errorf("cannot find the ort library at: %s", o.libraryPath)
}
ort.SetSharedLibraryPath(o.libraryPath)
}
// Start OnnxRuntime
if err := ort.InitializeEnvironment(); err != nil {
return false, err
}
if o.telemetry {
if err := ort.EnableTelemetry(); err != nil {
return true, err
}
} else {
if err := ort.DisableTelemetry(); err != nil {
return true, err
}
}
// Create session options for use in all pipelines
sessionOptions, optionsError := ort.NewSessionOptions()
if optionsError != nil {
return true, optionsError
}
s.ortOptions = sessionOptions
if o.intraOpNumThreads != 0 {
if err := sessionOptions.SetIntraOpNumThreads(o.intraOpNumThreads); err != nil {
return true, err
}
}
if o.interOpNumThreads != 0 {
if err := sessionOptions.SetInterOpNumThreads(o.interOpNumThreads); err != nil {
return true, err
}
}
if o.cpuMemArenaSet {
if err := sessionOptions.SetCpuMemArena(o.cpuMemArena); err != nil {
return true, err
}
}
if o.memPatternSet {
if err := sessionOptions.SetMemPattern(o.memPattern); err != nil {
return true, err
}
}
if o.cudaOptionsSet {
cudaOptions, optErr := ort.NewCUDAProviderOptions()
if optErr != nil {
return true, optErr
}
if len(o.cudaOptions) > 0 {
optErr = cudaOptions.Update(o.cudaOptions)
if optErr != nil {
return true, optErr
}
}
if err := sessionOptions.AppendExecutionProviderCUDA(cudaOptions); err != nil {
return true, err
}
}
if o.coreMLOptionsSet {
if err := sessionOptions.AppendExecutionProviderCoreML(o.coreMLOptions); err != nil {
return true, err
}
}
if o.directMLOptionsSet {
if err := sessionOptions.AppendExecutionProviderDirectML(o.directMLOptions); err != nil {
return true, err
}
}
if o.openVINOOptionsSet {
if err := sessionOptions.AppendExecutionProviderOpenVINO(o.openVINOOptions); err != nil {
return true, err
}
}
if o.tensorRTOptionsSet {
tensorRTOptions, optErr := ort.NewTensorRTProviderOptions()
if optErr != nil {
return true, optErr
}
if len(o.cudaOptions) > 0 {
optErr = tensorRTOptions.Update(o.tensorRTOptions)
if optErr != nil {
return true, optErr
}
}
if err := sessionOptions.AppendExecutionProviderTensorRT(tensorRTOptions); err != nil {
return true, err
}
}
return true, nil
}
type pipelineNotFoundError struct {
pipelineName string
}
func (e *pipelineNotFoundError) Error() string {
return fmt.Sprintf("Pipeline with name %s not found", e.pipelineName)
}
// NewPipeline can be used to create a new pipeline of type T. The initialised pipeline will be returned and it
// will also be stored in the session object so that all created pipelines can be destroyed with session.Destroy()
// at once.
func NewPipeline[T pipelines.Pipeline](s *Session, pipelineConfig pipelines.PipelineConfig[T]) (T, error) {
var pipeline T
var err error
if pipelineConfig.Name == "" {
return pipeline, errors.New("a name for the pipeline is required")
}
_, getError := GetPipeline[T](s, pipelineConfig.Name)
var notFoundError *pipelineNotFoundError
if getError == nil {
return pipeline, fmt.Errorf("pipeline %s has already been initialised", pipelineConfig.Name)
} else if !errors.As(getError, ¬FoundError) {
return pipeline, getError
}
switch any(pipeline).(type) {
case *pipelines.TokenClassificationPipeline:
config := any(pipelineConfig).(pipelines.PipelineConfig[*pipelines.TokenClassificationPipeline])
pipelineInitialised, err := pipelines.NewTokenClassificationPipeline(config, s.ortOptions)
if err != nil {
return pipeline, err
}
s.tokenClassificationPipelines[config.Name] = pipelineInitialised
pipeline = any(pipelineInitialised).(T)
case *pipelines.TextClassificationPipeline:
config := any(pipelineConfig).(pipelines.PipelineConfig[*pipelines.TextClassificationPipeline])
pipelineInitialised, err := pipelines.NewTextClassificationPipeline(config, s.ortOptions)
if err != nil {
return pipeline, err
}
s.textClassificationPipelines[config.Name] = pipelineInitialised
pipeline = any(pipelineInitialised).(T)
case *pipelines.FeatureExtractionPipeline:
config := any(pipelineConfig).(pipelines.PipelineConfig[*pipelines.FeatureExtractionPipeline])
pipelineInitialised, err := pipelines.NewFeatureExtractionPipeline(config, s.ortOptions)
if err != nil {
return pipeline, err
}
s.featureExtractionPipelines[config.Name] = pipelineInitialised
pipeline = any(pipelineInitialised).(T)
case *pipelines.ZeroShotClassificationPipeline:
config := any(pipelineConfig).(pipelines.PipelineConfig[*pipelines.ZeroShotClassificationPipeline])
pipelineInitialised, err := pipelines.NewZeroShotClassificationPipeline(config, s.ortOptions)
if err != nil {
return pipeline, err
}
s.zeroShotClassificationPipelines[config.Name] = pipelineInitialised
pipeline = any(pipelineInitialised).(T)
default:
return pipeline, fmt.Errorf("not implemented")
}
return pipeline, err
}
// GetPipeline can be used to retrieve a pipeline of type T with the given name from the session
func GetPipeline[T pipelines.Pipeline](s *Session, name string) (T, error) {
var pipeline T
switch any(pipeline).(type) {
case *pipelines.TokenClassificationPipeline:
p, ok := s.tokenClassificationPipelines[name]
if !ok {
return pipeline, &pipelineNotFoundError{pipelineName: name}
}
return any(p).(T), nil
case *pipelines.TextClassificationPipeline:
p, ok := s.textClassificationPipelines[name]
if !ok {
return pipeline, &pipelineNotFoundError{pipelineName: name}
}
return any(p).(T), nil
case *pipelines.FeatureExtractionPipeline:
p, ok := s.featureExtractionPipelines[name]
if !ok {
return pipeline, &pipelineNotFoundError{pipelineName: name}
}
return any(p).(T), nil
case *pipelines.ZeroShotClassificationPipeline:
p, ok := s.zeroShotClassificationPipelines[name]
if !ok {
return pipeline, &pipelineNotFoundError{pipelineName: name}
}
return any(p).(T), nil
default:
return pipeline, errors.New("pipeline type not supported")
}
}
// Destroy deletes the hugot session and onnxruntime environment and all initialized pipelines, freeing memory.
// A hugot session should be destroyed when not neeeded any more, preferably with a defer() call.
func (s *Session) Destroy() error {
return errors.Join(
s.featureExtractionPipelines.Destroy(),
s.tokenClassificationPipelines.Destroy(),
s.textClassificationPipelines.Destroy(),
s.zeroShotClassificationPipelines.Destroy(),
s.ortOptions.Destroy(),
ort.DestroyEnvironment(),
)
}
// GetStats returns runtime statistics for all initialized pipelines for profiling purposes. We currently record for each pipeline:
// the total runtime of the tokenization step
// the number of batch calls to the tokenization step
// the average time per tokenization batch call
// the total runtime of the inference (i.e. onnxruntime) step
// the number of batch calls to the onnxruntime inference
// the average time per onnxruntime inference batch call
func (s *Session) GetStats() []string {
// slices.Concat() is not implemented in experimental x/exp/slices package
return slices.Concat(
s.tokenClassificationPipelines.GetStats(),
s.textClassificationPipelines.GetStats(),
s.featureExtractionPipelines.GetStats(),
s.zeroShotClassificationPipelines.GetStats(),
)
}