summaryrefslogtreecommitdiff
path: root/gpt2/model.go
blob: feea423f85bb5bb774ad40b91bc295bfc8eb00b6 (plain)
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
package gpt2

import (
	"errors"
	"math"
	"os"
	"slices"
	"sort"
	"strconv"

	ort "github.com/yalue/onnxruntime_go"
)

type Model struct {
	name      string
	deviceID  string
	config    Config
	options   Options
	session   *ort.DynamicAdvancedSession
	allocator *Allocator
}

func NewModel(name string, cfg Config, opts Options) *Model {
	deviceID := CUDADeviceID()

	return &Model{
		name:     name,
		deviceID: deviceID,
		config:   cfg,
		options:  opts,
	}
}

func CUDADeviceID() string {
	id, ok := os.LookupEnv("ONNXRUNTIME_CUDA_DEVICE_ID")

	if !ok {
		return defaultDeviceID
	}

	return id
}

func SharedLibraryPath() string {
	p, ok := os.LookupEnv("ONNXRUNTIME_SHARED_LIBRARY_PATH")

	if !ok {
		// TODO embed runtime binaries
	}

	return p
}

func IntraOpNumThreads() int {
	s, ok := os.LookupEnv("ONNXRUNTIME_INTRA_OP_NUM_THREADS")

	if !ok {
		return 0
	}

	n, err := strconv.Atoi(s)

	if err != nil {
		return 0
	}

	return n
}

func (m *Model) Init() error {
	m.allocator = NewAllocator(m.config, m.options, 1)

	var options *ort.SessionOptions

	if o, err := ort.NewSessionOptions(); err != nil {
		return err
	} else {
		options = o

		defer options.Destroy()
	}

	if m.deviceID != "" {
		if err := WithCUDAProvider(options, m.deviceID); err != nil {
			return err
		}
	}

	if n := IntraOpNumThreads(); n > 0 {
		if err := options.SetIntraOpNumThreads(n); err != nil {
			return err
		}
	}

	if s, err := ort.NewDynamicAdvancedSession(m.name, m.allocator.InputNames(), m.allocator.OutputNames(), options); err != nil {
		return err
	} else {
		m.session = s
	}

	return nil
}

func (m *Model) Destroy() error {
	m.allocator.Destroy()

	return m.session.Destroy()
}

func (m *Model) Generate(prompt []int64, steps int64, logits *[][]float32) ([]int64, error) {
	if !m.options.WithLogits {
		panic("generate requires logits output")
	}

	if steps > 0 && !m.options.WithCache {
		panic("generate with steps > 0 requires cache")
	}

	if len(prompt) == 0 {
		return nil, errors.New("empty prompt")
	}

	if int64(len(prompt))+steps > int64(m.config.NumPositions) {
		return nil, errors.New("sequence length exceeds context limit")
	}

	if err := m.allocator.Init(prompt); err != nil {
		return nil, err
	}

	if err := m.forward(m.allocator); err != nil {
		return nil, err
	}

	r := make([]int64, steps)

	for step := range steps {
		l := m.logits(m.allocator.Value("logits"))

		if logits != nil {
			*logits = append(*logits, l...)
		}

		next := m.sample(l[len(l)-1])

		r[step] = next

		if err := m.allocator.Step(next); err != nil {
			return nil, err
		}

		if err := m.forward(m.allocator); err != nil {
			return nil, err
		}
	}

	if logits != nil {
		for _, l := range m.logits(m.allocator.Value("logits")) {
			*logits = append(*logits, l)
		}
	}

	return r, nil
}

func (m *Model) Score(tokens []int64, batchSize int, logProbs *[]float32) error {
	if !m.options.WithLogProbs {
		panic("score requires token_logprobs output")
	}

	m.allocator.SetBatchSize(batchSize)

	if err := m.allocator.Init(tokens); err != nil {
		return err
	}

	if err := m.forward(m.allocator); err != nil {
		return err
	}

	if logProbs != nil {
		d := m.allocator.Value("token_logprobs").(*ort.Tensor[float32]).GetData()

		*logProbs = append(*logProbs, d...)
	}

	return nil
}

func (m *Model) logits(output ort.Value) [][]float32 {
	d := output.(*ort.Tensor[float32]).GetData()
	n := len(d) / m.config.VocabSize
	l := make([][]float32, n)

	for i := range n {
		s := i * m.config.VocabSize

		l[i] = d[s : s+m.config.VocabSize : s+m.config.VocabSize]
	}

	return l
}

func (m *Model) sample(logits []float32) int64 {
	idx, _ := topK(softmax(logits), 5)

	return int64(idx[0])
}

func (m *Model) forward(alloc *Allocator) error {
	var binding *ort.IoBinding

	if b, err := m.session.CreateIoBinding(); err != nil {
		return err
	} else {
		binding = b

		defer binding.Destroy()
	}

	inputNames, inputs := alloc.Inputs()
	outputNames, outputs := alloc.Outputs()

	for i, name := range inputNames {
		if err := binding.BindInput(name, inputs[i]); err != nil {
			return err
		}
	}

	for i, name := range outputNames {
		if err := binding.BindOutput(name, outputs[i]); err != nil {
			return err
		}
	}

	return m.session.RunWithBinding(binding)
}

func softmax(logits []float32) []float32 {
	m := slices.Max(logits)

	s := float32(0.0)
	r := make([]float32, len(logits))

	for i, v := range logits {
		e := float32(math.Exp(float64(v - m)))

		r[i] = e
		s += e
	}

	for i := range r {
		r[i] /= s
	}

	return r
}

func topK(p []float32, k int) ([]int, []float32) {
	n := len(p)

	if k > n {
		k = n
	}

	idx := make([]int, n)

	for i := range idx {
		idx[i] = i
	}

	sort.Slice(idx, func(i, j int) bool {
		return p[idx[i]] > p[idx[j]]
	})

	topIdx := idx[:k]
	topP := make([]float32, k)

	for i := 0; i < k; i++ {
		topP[i] = p[topIdx[i]]
	}

	return topIdx, topP
}