-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpool.go
206 lines (174 loc) · 4.66 KB
/
pool.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
package gobergamot
import (
"bytes"
"context"
"errors"
"fmt"
"github.com/tetratelabs/wazero"
"github.com/KSpaceer/gobergamot/internal/errgroup"
)
var ErrClosed = errors.New("pool closed")
type PoolConfig struct {
Config
PoolSize uint
}
func (cfg PoolConfig) Validate() error {
var err error
if cfg.PoolSize == 0 {
err = errors.Join(err, errors.New("zero pool size"))
}
return errors.Join(err, cfg.Config.Validate())
}
// NewPool compiles Translator instances and runs them as workers.
func NewPool(ctx context.Context, cfg PoolConfig) (*Pool, error) {
err := cfg.Validate()
if err != nil {
return nil, err
}
if cfg.BergamotOptions == nil {
cfg.BergamotOptions = DefaultBergamotOptions()
}
if cfg.Config.WASMCache == nil {
// using cache to speed up workers creation
cfg.Config.WASMCache = wazero.NewCompilationCache()
}
p := &Pool{
cfg: cfg,
reqChan: make(chan workerRequest),
done: make(chan struct{}),
eg: errgroup.New(),
}
// converting Config FileBundle into byte slices
// to share between workers to read
if err = filesToBytes(p); err != nil {
return nil, err
}
translators, err := p.buildTranslators(ctx)
if err != nil {
return nil, fmt.Errorf("failed to setup translators: %w", err)
}
for i := range translators {
p.eg.Go(func() error {
return p.runWorker(translators[i])
})
}
return p, nil
}
type Pool struct {
cfg PoolConfig
reqChan chan workerRequest
eg errgroup.Errgroup
done chan struct{}
modelBytes []byte
shortlistBytes []byte
vocabularyBytes []byte
}
type workerRequest struct {
ctx context.Context
reqs []TranslationRequest
respChan chan workerResponse
}
type workerResponse struct {
outputs []string
err error
}
// Translate is similar to Translator.Translate except the request is asynchronously given
// to any free worker in the pool.
func (p *Pool) Translate(ctx context.Context, request TranslationRequest) (string, error) {
output, err := p.TranslateMultiple(ctx, request)
if err != nil {
return "", err
}
if len(output) < 1 {
return "", fmt.Errorf("expected translated texts to have at least 1 element")
}
return output[0], nil
}
// TranslateMultiple is similar to Translator.TranslateMultiple except the requests are asynchronously given
// to any free worker in the pool.
func (p *Pool) TranslateMultiple(ctx context.Context, requests ...TranslationRequest) ([]string, error) {
req := workerRequest{
ctx: ctx,
reqs: requests,
respChan: make(chan workerResponse, 1),
}
select {
case <-p.done:
return nil, fmt.Errorf("did not found available worker: %w", ErrClosed)
case <-ctx.Done():
return nil, fmt.Errorf("did not found available worker: %w", ctx.Err())
case p.reqChan <- req:
}
select {
case <-p.done:
return nil, fmt.Errorf("failed to wait response: %w", ErrClosed)
case <-ctx.Done():
return nil, fmt.Errorf("failed to wait response: %w", ctx.Err())
case resp := <-req.respChan:
return resp.outputs, resp.err
}
}
// Close closes existing Translator instances and waits for their completion
func (p *Pool) Close(ctx context.Context) error {
close(p.done)
errCh := make(chan error)
go func() {
errCh <- p.eg.Wait()
}()
select {
case <-ctx.Done():
return ctx.Err()
case err := <-errCh:
return err
}
}
func (p *Pool) runWorker(translator *Translator) error {
for {
select {
case <-p.done:
return translator.Close(context.Background())
case req := <-p.reqChan:
var resp workerResponse
resp.outputs, resp.err = translator.TranslateMultiple(req.ctx, req.reqs...)
req.respChan <- resp
}
}
}
func (p *Pool) buildTranslators(ctx context.Context) ([]*Translator, error) {
eg := errgroup.New()
translators := make([]*Translator, p.cfg.PoolSize)
for i := uint(0); i < p.cfg.PoolSize; i++ {
i := i
eg.Go(func() error {
cfg := p.cfg.Config
cfg.Model = bytes.NewBuffer(p.modelBytes)
cfg.LexicalShortlist = bytes.NewBuffer(p.shortlistBytes)
cfg.Vocabulary = bytes.NewBuffer(p.vocabularyBytes)
translator, err := New(ctx, cfg)
translators[i] = translator
return err
})
}
err := eg.Wait()
return translators, err
}
func filesToBytes(p *Pool) error {
var err error
wrappingFile := new(alignedMemoryFile)
wrappingFile.Reader = p.cfg.Model
p.modelBytes, err = wrappingFile.readAll()
if err != nil {
return fmt.Errorf("failed to read model: %w", err)
}
wrappingFile.Reader = p.cfg.LexicalShortlist
p.shortlistBytes, err = wrappingFile.readAll()
if err != nil {
return fmt.Errorf("failed to read shortlist: %w", err)
}
wrappingFile.Reader = p.cfg.Vocabulary
p.vocabularyBytes, err = wrappingFile.readAll()
if err != nil {
return fmt.Errorf("failed to read vocabulary: %w", err)
}
return nil
}