sched_test.go 21.7 KB
Newer Older
mashun1's avatar
v1  
mashun1 committed
1
2
3
4
5
package server

import (
	"bytes"
	"context"
xuxzh1's avatar
init  
xuxzh1 committed
6
	"errors"
mashun1's avatar
v1  
mashun1 committed
7
8
9
10
11
	"log/slog"
	"os"
	"testing"
	"time"

xuxzh1's avatar
init  
xuxzh1 committed
12
13
	"github.com/stretchr/testify/require"

mashun1's avatar
v1  
mashun1 committed
14
15
16
17
18
19
20
	"github.com/ollama/ollama/api"
	"github.com/ollama/ollama/app/lifecycle"
	"github.com/ollama/ollama/format"
	"github.com/ollama/ollama/gpu"
	"github.com/ollama/ollama/llm"
)

xuxzh1's avatar
init  
xuxzh1 committed
21
func TestMain(m *testing.M) {
mashun1's avatar
v1  
mashun1 committed
22
23
	os.Setenv("OLLAMA_DEBUG", "1")
	lifecycle.InitLogging()
xuxzh1's avatar
init  
xuxzh1 committed
24
	os.Exit(m.Run())
mashun1's avatar
v1  
mashun1 committed
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
}

func TestInitScheduler(t *testing.T) {
	ctx, done := context.WithCancel(context.Background())
	defer done()
	s := InitScheduler(ctx)
	s.loadedMu.Lock()
	require.NotNil(t, s.loaded)
	s.loadedMu.Unlock()
}

func TestLoad(t *testing.T) {
	ctx, done := context.WithTimeout(context.Background(), 20*time.Millisecond)
	defer done()
	s := InitScheduler(ctx)
	var ggml *llm.GGML // value not used in tests
	req := &LlmRequest{
		ctx:             ctx,
		model:           &Model{ModelPath: "foo"},
		opts:            api.DefaultOptions(),
		successCh:       make(chan *runnerRef, 1),
		errCh:           make(chan error, 1),
xuxzh1's avatar
init  
xuxzh1 committed
47
		sessionDuration: &api.Duration{Duration: 2 * time.Second},
mashun1's avatar
v1  
mashun1 committed
48
49
	}
	// Fail to load model first
xuxzh1's avatar
init  
xuxzh1 committed
50
51
	s.newServerFn = func(gpus gpu.GpuInfoList, model string, ggml *llm.GGML, adapters []string, projectors []string, opts api.Options, numParallel int) (llm.LlamaServer, error) {
		return nil, errors.New("something failed to load model blah")
mashun1's avatar
v1  
mashun1 committed
52
53
	}
	gpus := gpu.GpuInfoList{}
xuxzh1's avatar
init  
xuxzh1 committed
54
55
	s.load(req, ggml, gpus, 0)
	require.Empty(t, req.successCh)
mashun1's avatar
v1  
mashun1 committed
56
57
	require.Len(t, req.errCh, 1)
	s.loadedMu.Lock()
xuxzh1's avatar
init  
xuxzh1 committed
58
	require.Empty(t, s.loaded)
mashun1's avatar
v1  
mashun1 committed
59
60
61
62
	s.loadedMu.Unlock()
	err := <-req.errCh
	require.Contains(t, err.Error(), "this model may be incompatible")

xuxzh1's avatar
init  
xuxzh1 committed
63
64
	server := &mockLlm{estimatedVRAM: 10, estimatedVRAMByGPU: map[string]uint64{}}
	s.newServerFn = func(gpus gpu.GpuInfoList, model string, ggml *llm.GGML, adapters []string, projectors []string, opts api.Options, numParallel int) (llm.LlamaServer, error) {
mashun1's avatar
v1  
mashun1 committed
65
66
		return server, nil
	}
xuxzh1's avatar
init  
xuxzh1 committed
67
	s.load(req, ggml, gpus, 0)
mashun1's avatar
v1  
mashun1 committed
68
69
70
71
72
73
74
75
76
77
78
79
	select {
	case err := <-req.errCh:
		require.NoError(t, err)
	case resp := <-req.successCh:
		require.Equal(t, uint64(10), resp.estimatedVRAM)
		require.Equal(t, uint(1), resp.refCount)
		s.loadedMu.Lock()
		require.Len(t, s.loaded, 1)
		s.loadedMu.Unlock()
	}

	req.model.ModelPath = "dummy_model_path"
xuxzh1's avatar
init  
xuxzh1 committed
80
81
	server.waitResp = errors.New("wait failure")
	s.load(req, ggml, gpus, 0)
mashun1's avatar
v1  
mashun1 committed
82
83
84
85
	select {
	case err := <-req.errCh:
		require.Contains(t, err.Error(), "wait failure")
	case resp := <-req.successCh:
xuxzh1's avatar
init  
xuxzh1 committed
86
		t.Fatalf("unexpected success %v", resp)
mashun1's avatar
v1  
mashun1 committed
87
88
89
90
91
92
93
94
95
96
	}
	s.loadedMu.Lock()
	runner := s.loaded["dummy_model_path"]
	s.loadedMu.Unlock()
	require.NotNil(t, runner)
	require.Equal(t, uint(0), runner.refCount)
	time.Sleep(1 * time.Millisecond)
	require.Len(t, s.expiredCh, 1)
}

xuxzh1's avatar
init  
xuxzh1 committed
97
type reqBundle struct {
mashun1's avatar
v1  
mashun1 committed
98
99
100
101
102
103
104
	ctx     context.Context //nolint:containedctx
	ctxDone func()
	srv     *mockLlm
	req     *LlmRequest
	ggml    *llm.GGML
}

xuxzh1's avatar
init  
xuxzh1 committed
105
func (scenario *reqBundle) newServer(gpus gpu.GpuInfoList, model string, ggml *llm.GGML, adapters []string, projectors []string, opts api.Options, numParallel int) (llm.LlamaServer, error) {
mashun1's avatar
v1  
mashun1 committed
106
107
108
	return scenario.srv, nil
}

xuxzh1's avatar
init  
xuxzh1 committed
109
110
111
func newScenarioRequest(t *testing.T, ctx context.Context, modelName string, estimatedVRAM uint64, duration *api.Duration) *reqBundle {
	b := &reqBundle{}
	b.ctx, b.ctxDone = context.WithCancel(ctx)
mashun1's avatar
v1  
mashun1 committed
112
113
114
	t.Helper()

	f, err := os.CreateTemp(t.TempDir(), modelName)
xuxzh1's avatar
init  
xuxzh1 committed
115
	require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
116
117
	defer f.Close()

xuxzh1's avatar
init  
xuxzh1 committed
118
	require.NoError(t, llm.WriteGGUF(f, llm.KV{
mashun1's avatar
v1  
mashun1 committed
119
120
121
122
123
124
125
126
127
128
129
		"general.architecture":          "llama",
		"general.name":                  "name",
		"llama.context_length":          uint32(32),
		"llama.embedding_length":        uint32(4096),
		"llama.block_count":             uint32(1),
		"llama.attention.head_count":    uint32(32),
		"llama.attention.head_count_kv": uint32(32),
		"tokenizer.ggml.tokens":         []string{" "},
		"tokenizer.ggml.scores":         []float32{0},
		"tokenizer.ggml.token_type":     []int32{0},
	}, []llm.Tensor{
xuxzh1's avatar
init  
xuxzh1 committed
130
131
132
133
		{Name: "blk.0.attn.weight", Kind: uint32(0), Offset: uint64(0), Shape: []uint64{1, 1, 1, 1}, WriterTo: bytes.NewReader(make([]byte, 32))},
		{Name: "output.weight", Kind: uint32(0), Offset: uint64(0), Shape: []uint64{1, 1, 1, 1}, WriterTo: bytes.NewReader(make([]byte, 32))},
	}))
	require.NoError(t, err)
mashun1's avatar
v1  
mashun1 committed
134
135
136

	fname := f.Name()
	model := &Model{Name: modelName, ModelPath: fname}
xuxzh1's avatar
init  
xuxzh1 committed
137
	b.ggml, err = llm.LoadModel(model.ModelPath, 0)
mashun1's avatar
v1  
mashun1 committed
138
139
	require.NoError(t, err)

xuxzh1's avatar
init  
xuxzh1 committed
140
141
142
143
144
	if duration == nil {
		duration = &api.Duration{Duration: 5 * time.Millisecond}
	}
	b.req = &LlmRequest{
		ctx:             b.ctx,
mashun1's avatar
v1  
mashun1 committed
145
146
		model:           model,
		opts:            api.DefaultOptions(),
xuxzh1's avatar
init  
xuxzh1 committed
147
		sessionDuration: duration,
mashun1's avatar
v1  
mashun1 committed
148
149
150
		successCh:       make(chan *runnerRef, 1),
		errCh:           make(chan error, 1),
	}
xuxzh1's avatar
init  
xuxzh1 committed
151
152
	b.srv = &mockLlm{estimatedVRAM: estimatedVRAM, estimatedVRAMByGPU: map[string]uint64{"": estimatedVRAM}}
	return b
mashun1's avatar
v1  
mashun1 committed
153
154
}

xuxzh1's avatar
init  
xuxzh1 committed
155
156
157
158
159
160
func getGpuFn() gpu.GpuInfoList {
	g := gpu.GpuInfo{Library: "metal"}
	g.TotalMemory = 24 * format.GigaByte
	g.FreeMemory = 12 * format.GigaByte
	return []gpu.GpuInfo{g}
}
mashun1's avatar
v1  
mashun1 committed
161

xuxzh1's avatar
init  
xuxzh1 committed
162
163
164
165
166
167
func getCpuFn() gpu.GpuInfoList {
	g := gpu.GpuInfo{Library: "cpu"}
	g.TotalMemory = 32 * format.GigaByte
	g.FreeMemory = 26 * format.GigaByte
	return []gpu.GpuInfo{g}
}
mashun1's avatar
v1  
mashun1 committed
168

xuxzh1's avatar
init  
xuxzh1 committed
169
170
171
func TestRequestsSameModelSameRequest(t *testing.T) {
	ctx, done := context.WithTimeout(context.Background(), 500*time.Millisecond)
	defer done()
mashun1's avatar
v1  
mashun1 committed
172
	s := InitScheduler(ctx)
xuxzh1's avatar
init  
xuxzh1 committed
173
174
175
176
177
178
179
180
181
182
	s.getGpuFn = getGpuFn
	s.getCpuFn = getCpuFn
	a := newScenarioRequest(t, ctx, "ollama-model-1", 10, &api.Duration{Duration: 5 * time.Millisecond})
	b := newScenarioRequest(t, ctx, "ollama-model-1", 11, &api.Duration{Duration: 0})
	b.req.model = a.req.model
	b.ggml = a.ggml

	s.newServerFn = a.newServer
	slog.Info("a")
	s.pendingReqCh <- a.req
mashun1's avatar
v1  
mashun1 committed
183
184
185
	require.Len(t, s.pendingReqCh, 1)
	s.Run(ctx)
	select {
xuxzh1's avatar
init  
xuxzh1 committed
186
187
188
189
190
191
	case resp := <-a.req.successCh:
		require.Equal(t, resp.llama, a.srv)
		require.Empty(t, s.pendingReqCh)
		require.Empty(t, a.req.errCh)
	case err := <-a.req.errCh:
		t.Fatal(err.Error())
mashun1's avatar
v1  
mashun1 committed
192
	case <-ctx.Done():
xuxzh1's avatar
init  
xuxzh1 committed
193
		t.Fatal("timeout")
mashun1's avatar
v1  
mashun1 committed
194
195
196
	}

	// Same runner as first request due to not needing a reload
xuxzh1's avatar
init  
xuxzh1 committed
197
198
199
	s.newServerFn = b.newServer
	slog.Info("b")
	s.pendingReqCh <- b.req
mashun1's avatar
v1  
mashun1 committed
200
	select {
xuxzh1's avatar
init  
xuxzh1 committed
201
202
203
204
205
206
	case resp := <-b.req.successCh:
		require.Equal(t, resp.llama, a.srv)
		require.Empty(t, s.pendingReqCh)
		require.Empty(t, b.req.errCh)
	case err := <-b.req.errCh:
		t.Fatal(err.Error())
mashun1's avatar
v1  
mashun1 committed
207
	case <-ctx.Done():
xuxzh1's avatar
init  
xuxzh1 committed
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
		t.Fatal("timeout")
	}
}

func TestRequestsSimpleReloadSameModel(t *testing.T) {
	ctx, done := context.WithTimeout(context.Background(), 500*time.Millisecond)
	defer done()
	s := InitScheduler(ctx)
	s.getGpuFn = getGpuFn
	s.getCpuFn = getCpuFn
	a := newScenarioRequest(t, ctx, "ollama-model-1", 10, &api.Duration{Duration: 5 * time.Millisecond})
	b := newScenarioRequest(t, ctx, "ollama-model-1", 20, &api.Duration{Duration: 5 * time.Millisecond})
	tmpModel := *a.req.model
	b.req.model = &tmpModel
	b.ggml = a.ggml

	s.newServerFn = a.newServer
	slog.Info("a")
	s.pendingReqCh <- a.req
	require.Len(t, s.pendingReqCh, 1)
	s.Run(ctx)
	select {
	case resp := <-a.req.successCh:
		require.Equal(t, resp.llama, a.srv)
		require.Empty(t, s.pendingReqCh)
		require.Empty(t, a.req.errCh)
	case err := <-a.req.errCh:
		t.Fatal(err.Error())
	case <-ctx.Done():
		t.Fatal("timeout")
mashun1's avatar
v1  
mashun1 committed
238
239
240
	}

	// Trigger a reload
xuxzh1's avatar
init  
xuxzh1 committed
241
242
243
244
	s.newServerFn = b.newServer
	b.req.model.AdapterPaths = []string{"new"}
	slog.Info("b")
	s.pendingReqCh <- b.req
mashun1's avatar
v1  
mashun1 committed
245
246
	// finish first two requests, so model can reload
	time.Sleep(1 * time.Millisecond)
xuxzh1's avatar
init  
xuxzh1 committed
247
	a.ctxDone()
mashun1's avatar
v1  
mashun1 committed
248
	select {
xuxzh1's avatar
init  
xuxzh1 committed
249
250
251
252
253
254
	case resp := <-b.req.successCh:
		require.Equal(t, resp.llama, b.srv)
		require.Empty(t, s.pendingReqCh)
		require.Empty(t, b.req.errCh)
	case err := <-b.req.errCh:
		t.Fatal(err.Error())
mashun1's avatar
v1  
mashun1 committed
255
	case <-ctx.Done():
xuxzh1's avatar
init  
xuxzh1 committed
256
		t.Fatal("timeout")
mashun1's avatar
v1  
mashun1 committed
257
	}
xuxzh1's avatar
init  
xuxzh1 committed
258
}
mashun1's avatar
v1  
mashun1 committed
259

xuxzh1's avatar
init  
xuxzh1 committed
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
func TestRequestsMultipleLoadedModels(t *testing.T) {
	ctx, done := context.WithTimeout(context.Background(), 500*time.Millisecond)
	defer done()
	s := InitScheduler(ctx)
	s.getGpuFn = getGpuFn
	s.getCpuFn = getCpuFn

	// Multiple loaded models
	a := newScenarioRequest(t, ctx, "ollama-model-3a", 1*format.GigaByte, nil)
	b := newScenarioRequest(t, ctx, "ollama-model-3b", 24*format.GigaByte, nil)
	c := newScenarioRequest(t, ctx, "ollama-model-4a", 30, nil)
	c.req.opts.NumGPU = 0                                       // CPU load, will be allowed
	d := newScenarioRequest(t, ctx, "ollama-model-3c", 30, nil) // Needs prior unloaded

	t.Setenv("OLLAMA_MAX_LOADED_MODELS", "1")
	s.newServerFn = a.newServer
	slog.Info("a")
	s.pendingReqCh <- a.req
	s.Run(ctx)
mashun1's avatar
v1  
mashun1 committed
279
	select {
xuxzh1's avatar
init  
xuxzh1 committed
280
281
282
283
284
285
	case resp := <-a.req.successCh:
		require.Equal(t, resp.llama, a.srv)
		require.Empty(t, s.pendingReqCh)
		require.Empty(t, a.req.errCh)
	case err := <-a.req.errCh:
		t.Fatal(err.Error())
mashun1's avatar
v1  
mashun1 committed
286
	case <-ctx.Done():
xuxzh1's avatar
init  
xuxzh1 committed
287
		t.Fatal("timeout")
mashun1's avatar
v1  
mashun1 committed
288
289
290
291
292
	}
	s.loadedMu.Lock()
	require.Len(t, s.loaded, 1)
	s.loadedMu.Unlock()

xuxzh1's avatar
init  
xuxzh1 committed
293
294
295
296
	t.Setenv("OLLAMA_MAX_LOADED_MODELS", "0")
	s.newServerFn = b.newServer
	slog.Info("b")
	s.pendingReqCh <- b.req
mashun1's avatar
v1  
mashun1 committed
297
	select {
xuxzh1's avatar
init  
xuxzh1 committed
298
299
300
301
302
303
	case resp := <-b.req.successCh:
		require.Equal(t, resp.llama, b.srv)
		require.Empty(t, s.pendingReqCh)
		require.Empty(t, b.req.errCh)
	case err := <-b.req.errCh:
		t.Fatal(err.Error())
mashun1's avatar
v1  
mashun1 committed
304
	case <-ctx.Done():
xuxzh1's avatar
init  
xuxzh1 committed
305
		t.Fatal("timeout")
mashun1's avatar
v1  
mashun1 committed
306
307
308
309
310
311
	}
	s.loadedMu.Lock()
	require.Len(t, s.loaded, 2)
	s.loadedMu.Unlock()

	// This is a CPU load with NumGPU = 0 so it should load
xuxzh1's avatar
init  
xuxzh1 committed
312
313
314
	s.newServerFn = c.newServer
	slog.Info("c")
	s.pendingReqCh <- c.req
mashun1's avatar
v1  
mashun1 committed
315
	select {
xuxzh1's avatar
init  
xuxzh1 committed
316
317
318
319
320
321
	case resp := <-c.req.successCh:
		require.Equal(t, resp.llama, c.srv)
		require.Empty(t, s.pendingReqCh)
		require.Empty(t, c.req.errCh)
	case err := <-c.req.errCh:
		t.Fatal(err.Error())
mashun1's avatar
v1  
mashun1 committed
322
	case <-ctx.Done():
xuxzh1's avatar
init  
xuxzh1 committed
323
		t.Fatal("timeout")
mashun1's avatar
v1  
mashun1 committed
324
325
326
327
328
329
	}
	s.loadedMu.Lock()
	require.Len(t, s.loaded, 3)
	s.loadedMu.Unlock()

	// Try to load a model that wont fit
xuxzh1's avatar
init  
xuxzh1 committed
330
331
	s.newServerFn = d.newServer
	slog.Info("d")
mashun1's avatar
v1  
mashun1 committed
332
333
334
	s.loadedMu.Lock()
	require.Len(t, s.loaded, 3)
	s.loadedMu.Unlock()
xuxzh1's avatar
init  
xuxzh1 committed
335
	a.ctxDone() // Won't help since this one isn't big enough to make room
mashun1's avatar
v1  
mashun1 committed
336
	time.Sleep(2 * time.Millisecond)
xuxzh1's avatar
init  
xuxzh1 committed
337
	s.pendingReqCh <- d.req
mashun1's avatar
v1  
mashun1 committed
338
339
340
341
342
	// finish prior request, so new model can load
	time.Sleep(6 * time.Millisecond)
	s.loadedMu.Lock()
	require.Len(t, s.loaded, 2)
	s.loadedMu.Unlock()
xuxzh1's avatar
init  
xuxzh1 committed
343
	b.ctxDone()
mashun1's avatar
v1  
mashun1 committed
344
	select {
xuxzh1's avatar
init  
xuxzh1 committed
345
346
347
348
	case resp := <-d.req.successCh:
		require.Equal(t, resp.llama, d.srv)
		require.Empty(t, s.pendingReqCh)
		require.Empty(t, d.req.errCh)
mashun1's avatar
v1  
mashun1 committed
349
	case <-ctx.Done():
xuxzh1's avatar
init  
xuxzh1 committed
350
		t.Fatal("timeout")
mashun1's avatar
v1  
mashun1 committed
351
352
353
354
355
356
357
358
359
360
	}
	s.loadedMu.Lock()
	require.Len(t, s.loaded, 2)
	s.loadedMu.Unlock()
}

func TestGetRunner(t *testing.T) {
	ctx, done := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer done()

xuxzh1's avatar
init  
xuxzh1 committed
361
362
363
364
	a := newScenarioRequest(t, ctx, "ollama-model-1a", 10, &api.Duration{Duration: 2 * time.Millisecond})
	b := newScenarioRequest(t, ctx, "ollama-model-1b", 10, &api.Duration{Duration: 2 * time.Millisecond})
	c := newScenarioRequest(t, ctx, "ollama-model-1c", 10, &api.Duration{Duration: 2 * time.Millisecond})
	t.Setenv("OLLAMA_MAX_QUEUE", "1")
mashun1's avatar
v1  
mashun1 committed
365
	s := InitScheduler(ctx)
xuxzh1's avatar
init  
xuxzh1 committed
366
367
368
369
370
	s.getGpuFn = getGpuFn
	s.getCpuFn = getCpuFn
	s.newServerFn = a.newServer
	slog.Info("a")
	successCh1a, errCh1a := s.GetRunner(a.ctx, a.req.model, a.req.opts, a.req.sessionDuration)
mashun1's avatar
v1  
mashun1 committed
371
	require.Len(t, s.pendingReqCh, 1)
xuxzh1's avatar
init  
xuxzh1 committed
372
373
	slog.Info("b")
	successCh1b, errCh1b := s.GetRunner(b.ctx, b.req.model, b.req.opts, b.req.sessionDuration)
mashun1's avatar
v1  
mashun1 committed
374
	require.Len(t, s.pendingReqCh, 1)
xuxzh1's avatar
init  
xuxzh1 committed
375
	require.Empty(t, successCh1b)
mashun1's avatar
v1  
mashun1 committed
376
377
378
379
380
381
	require.Len(t, errCh1b, 1)
	err := <-errCh1b
	require.Contains(t, err.Error(), "server busy")
	s.Run(ctx)
	select {
	case resp := <-successCh1a:
xuxzh1's avatar
init  
xuxzh1 committed
382
383
384
385
386
		require.Equal(t, resp.llama, a.srv)
		require.Empty(t, s.pendingReqCh)
		require.Empty(t, errCh1a)
	case err := <-errCh1a:
		t.Fatal(err.Error())
mashun1's avatar
v1  
mashun1 committed
387
	case <-ctx.Done():
xuxzh1's avatar
init  
xuxzh1 committed
388
		t.Fatal("timeout")
mashun1's avatar
v1  
mashun1 committed
389
	}
xuxzh1's avatar
init  
xuxzh1 committed
390
	a.ctxDone() // Set "a" model to idle so it can unload
mashun1's avatar
v1  
mashun1 committed
391
392
393
394
	s.loadedMu.Lock()
	require.Len(t, s.loaded, 1)
	s.loadedMu.Unlock()

xuxzh1's avatar
init  
xuxzh1 committed
395
396
397
	c.req.model.ModelPath = "bad path"
	slog.Info("c")
	successCh1c, errCh1c := s.GetRunner(c.ctx, c.req.model, c.req.opts, c.req.sessionDuration)
mashun1's avatar
v1  
mashun1 committed
398
	// Starts in pending channel, then should be quickly processsed to return an error
xuxzh1's avatar
init  
xuxzh1 committed
399
400
	time.Sleep(20 * time.Millisecond) // Long enough for the "a" model to expire and unload
	require.Empty(t, successCh1c)
mashun1's avatar
v1  
mashun1 committed
401
	s.loadedMu.Lock()
xuxzh1's avatar
init  
xuxzh1 committed
402
	require.Empty(t, s.loaded)
mashun1's avatar
v1  
mashun1 committed
403
404
405
406
	s.loadedMu.Unlock()
	require.Len(t, errCh1c, 1)
	err = <-errCh1c
	require.Contains(t, err.Error(), "bad path")
xuxzh1's avatar
init  
xuxzh1 committed
407
	b.ctxDone()
mashun1's avatar
v1  
mashun1 committed
408
409
410
411
412
413
414
415
}

// TODO - add one scenario that triggers the bogus finished event with positive ref count
func TestPrematureExpired(t *testing.T) {
	ctx, done := context.WithTimeout(context.Background(), 500*time.Millisecond)
	defer done()

	// Same model, same request
xuxzh1's avatar
init  
xuxzh1 committed
416
	scenario1a := newScenarioRequest(t, ctx, "ollama-model-1a", 10, nil)
mashun1's avatar
v1  
mashun1 committed
417
418
419
420
421
422
423
424
425
426
427
428
429
430
	s := InitScheduler(ctx)
	s.getGpuFn = func() gpu.GpuInfoList {
		g := gpu.GpuInfo{Library: "metal"}
		g.TotalMemory = 24 * format.GigaByte
		g.FreeMemory = 12 * format.GigaByte
		return []gpu.GpuInfo{g}
	}
	s.newServerFn = scenario1a.newServer
	successCh1a, errCh1a := s.GetRunner(scenario1a.ctx, scenario1a.req.model, scenario1a.req.opts, scenario1a.req.sessionDuration)
	require.Len(t, s.pendingReqCh, 1)
	s.Run(ctx)
	select {
	case resp := <-successCh1a:
		require.Equal(t, resp.llama, scenario1a.srv)
xuxzh1's avatar
init  
xuxzh1 committed
431
432
		require.Empty(t, s.pendingReqCh)
		require.Empty(t, errCh1a)
mashun1's avatar
v1  
mashun1 committed
433
434
435
436
437
		s.loadedMu.Lock()
		require.Len(t, s.loaded, 1)
		s.loadedMu.Unlock()
		slog.Info("sending premature expired event now")
		s.expiredCh <- resp // Shouldn't happen in real life, but make sure its safe
xuxzh1's avatar
init  
xuxzh1 committed
438
439
	case err := <-errCh1a:
		t.Fatal(err.Error())
mashun1's avatar
v1  
mashun1 committed
440
	case <-ctx.Done():
xuxzh1's avatar
init  
xuxzh1 committed
441
		t.Fatal("timeout")
mashun1's avatar
v1  
mashun1 committed
442
	}
xuxzh1's avatar
init  
xuxzh1 committed
443
	time.Sleep(scenario1a.req.sessionDuration.Duration)
mashun1's avatar
v1  
mashun1 committed
444
445
446
447
	scenario1a.ctxDone()
	time.Sleep(20 * time.Millisecond)
	require.LessOrEqual(t, len(s.finishedReqCh), 1)
	time.Sleep(10 * time.Millisecond)
xuxzh1's avatar
init  
xuxzh1 committed
448
	require.Empty(t, s.finishedReqCh)
mashun1's avatar
v1  
mashun1 committed
449
	s.loadedMu.Lock()
xuxzh1's avatar
init  
xuxzh1 committed
450
	require.Empty(t, s.loaded)
mashun1's avatar
v1  
mashun1 committed
451
452
453
454
455
456
457
458
459
460
461
462
463
	s.loadedMu.Unlock()

	// also shouldn't happen in real life
	s.finishedReqCh <- scenario1a.req
	time.Sleep(5 * time.Millisecond)
}

func TestUseLoadedRunner(t *testing.T) {
	ctx, done := context.WithTimeout(context.Background(), 100*time.Millisecond)
	req := &LlmRequest{
		ctx:             ctx,
		opts:            api.DefaultOptions(),
		successCh:       make(chan *runnerRef, 1),
xuxzh1's avatar
init  
xuxzh1 committed
464
		sessionDuration: &api.Duration{Duration: 2},
mashun1's avatar
v1  
mashun1 committed
465
466
	}
	finished := make(chan *LlmRequest)
xuxzh1's avatar
init  
xuxzh1 committed
467
468
	llm1 := &mockLlm{estimatedVRAMByGPU: map[string]uint64{}}
	r1 := &runnerRef{llama: llm1, sessionDuration: 1, numParallel: 1}
mashun1's avatar
v1  
mashun1 committed
469
470
471
472
473
474
	req.useLoadedRunner(r1, finished)
	require.Equal(t, uint(1), r1.refCount)
	require.Equal(t, time.Duration(2), r1.sessionDuration)
	select {
	case success := <-req.successCh:
		require.Equal(t, r1, success)
xuxzh1's avatar
init  
xuxzh1 committed
475
476
	case err := <-req.errCh:
		t.Fatal(err.Error())
mashun1's avatar
v1  
mashun1 committed
477
	case <-ctx.Done():
xuxzh1's avatar
init  
xuxzh1 committed
478
		t.Fatal("timeout")
mashun1's avatar
v1  
mashun1 committed
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
	}
	done()
	fin := <-finished
	require.Equal(t, req, fin)
}

func TestUpdateFreeSpace(t *testing.T) {
	ctx, done := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer done()
	gpus := gpu.GpuInfoList{
		{
			Library: "a",
			ID:      "1",
		},
		{
			Library: "a",
			ID:      "2",
		},
	}
	gpus[0].TotalMemory = 1000
	gpus[0].FreeMemory = 900
	gpus[1].TotalMemory = 2000
	gpus[1].FreeMemory = 1900
xuxzh1's avatar
init  
xuxzh1 committed
502
503
504
505
	llm1 := &mockLlm{estimatedVRAMByGPU: map[string]uint64{"1": 50, "2": 50}}
	llm2 := &mockLlm{estimatedVRAMByGPU: map[string]uint64{"1": 125, "2": 75}}
	r1 := &runnerRef{llama: llm1, gpus: gpus, numParallel: 1}
	r2 := &runnerRef{llama: llm2, gpus: gpus, numParallel: 1}
mashun1's avatar
v1  
mashun1 committed
506
507
508
509
510
511
512
513

	s := InitScheduler(ctx)
	s.loadedMu.Lock()
	s.loaded["a"] = r1
	s.loaded["b"] = r2
	s.loadedMu.Unlock()

	s.updateFreeSpace(gpus)
xuxzh1's avatar
init  
xuxzh1 committed
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
	require.Equal(t, uint64(1000-50-125), gpus[0].FreeMemory)
	require.Equal(t, uint64(2000-50-75), gpus[1].FreeMemory)
}

func TestFilterGPUsWithoutLoadingModels(t *testing.T) {
	ctx, done := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer done()
	gpus := gpu.GpuInfoList{
		{
			Library: "cuda",
			ID:      "0",
		},
		{
			Library: "cuda",
			ID:      "1",
		},
	}
	r1 := &runnerRef{gpus: gpu.GpuInfoList{gpus[0]}, loading: true}

	s := InitScheduler(ctx)
	s.loadedMu.Lock()
	s.loaded["a"] = r1
	s.loadedMu.Unlock()

	tmp := s.filterGPUsWithoutLoadingModels(gpus)
	require.Len(t, tmp, 1)
	require.Equal(t, "1", tmp[0].ID)

	r1.gpus = gpu.GpuInfoList{gpus[1]}
	tmp = s.filterGPUsWithoutLoadingModels(gpus)
	require.Len(t, tmp, 1)
	require.Equal(t, "0", tmp[0].ID)

	r1.gpus = gpu.GpuInfoList{}
	tmp = s.filterGPUsWithoutLoadingModels(gpus)
	require.Len(t, tmp, 2)
mashun1's avatar
v1  
mashun1 committed
550
551
552
553
554
555
}

func TestFindRunnerToUnload(t *testing.T) {
	ctx, done := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer done()

xuxzh1's avatar
init  
xuxzh1 committed
556
557
	r1 := &runnerRef{refCount: 1, sessionDuration: 1, numParallel: 1}
	r2 := &runnerRef{sessionDuration: 2, numParallel: 1}
mashun1's avatar
v1  
mashun1 committed
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575

	s := InitScheduler(ctx)
	s.loadedMu.Lock()
	s.loaded["a"] = r1
	s.loaded["b"] = r2
	s.loadedMu.Unlock()

	resp := s.findRunnerToUnload()
	require.Equal(t, r2, resp)
	r2.refCount = 1
	resp = s.findRunnerToUnload()
	require.Equal(t, r1, resp)
}

func TestNeedsReload(t *testing.T) {
	ctx, done := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer done()

xuxzh1's avatar
init  
xuxzh1 committed
576
	llm := &mockLlm{estimatedVRAMByGPU: map[string]uint64{}}
mashun1's avatar
v1  
mashun1 committed
577
578
	do := api.DefaultOptions()
	runner := &runnerRef{
xuxzh1's avatar
init  
xuxzh1 committed
579
580
581
582
583
584
585
		model: &Model{
			AdapterPaths:   []string{"adapter1"},
			ProjectorPaths: []string{"projector1"},
		},
		Options:     &do,
		llama:       llm,
		numParallel: 1,
mashun1's avatar
v1  
mashun1 committed
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
	}
	req := &LlmRequest{
		model: &Model{
			AdapterPaths:   []string{"adapter2"},
			ProjectorPaths: []string{"projector2"},
		},
		opts: api.DefaultOptions(),
	}
	resp := runner.needsReload(ctx, req)
	require.True(t, resp)
	req.model.AdapterPaths = runner.model.AdapterPaths
	resp = runner.needsReload(ctx, req)
	require.True(t, resp)
	req.model.ProjectorPaths = runner.model.ProjectorPaths
	runner.loading = true
	req.opts.NumBatch = 1234
	resp = runner.needsReload(ctx, req)
	require.True(t, resp)
	req.opts.NumBatch = runner.Options.NumBatch
xuxzh1's avatar
init  
xuxzh1 committed
605
	llm.pingResp = errors.New("foo")
mashun1's avatar
v1  
mashun1 committed
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
	resp = runner.needsReload(ctx, req)
	require.True(t, resp)
	llm.pingResp = nil
	resp = runner.needsReload(ctx, req)
	require.False(t, resp)
	req.opts.NumGPU = 99
	resp = runner.needsReload(ctx, req)
	require.True(t, resp)
	req.opts.NumGPU = -1
	resp = runner.needsReload(ctx, req)
	require.False(t, resp)
}

func TestUnloadAllRunners(t *testing.T) {
	ctx, done := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer done()

xuxzh1's avatar
init  
xuxzh1 committed
623
624
	llm1 := &mockLlm{estimatedVRAMByGPU: map[string]uint64{}}
	llm2 := &mockLlm{estimatedVRAMByGPU: map[string]uint64{}}
mashun1's avatar
v1  
mashun1 committed
625
626
627
	s := InitScheduler(ctx)
	s.unloadAllRunners()

xuxzh1's avatar
init  
xuxzh1 committed
628
629
	r1 := &runnerRef{llama: llm1, numParallel: 1}
	r2 := &runnerRef{llama: llm2, numParallel: 1}
mashun1's avatar
v1  
mashun1 committed
630
631
632
633
634
635
636
637
638
639
640
641

	s.loadedMu.Lock()
	s.loaded["a"] = r1
	s.loaded["b"] = r2
	s.loadedMu.Unlock()
	s.unloadAllRunners()

	require.True(t, llm1.closeCalled)
	require.True(t, llm2.closeCalled)
}

func TestUnload(t *testing.T) {
xuxzh1's avatar
init  
xuxzh1 committed
642
643
644
	llm1 := &mockLlm{estimatedVRAMByGPU: map[string]uint64{}}
	r1 := &runnerRef{llama: llm1, numParallel: 1}
	r2 := &runnerRef{model: &Model{AdapterPaths: []string{"A"}}, numParallel: 1}
mashun1's avatar
v1  
mashun1 committed
645
646
647
648
649
650
	r1.unload()
	require.True(t, llm1.closeCalled)
	r2.unload()
	require.Nil(t, r2.model)
}

xuxzh1's avatar
init  
xuxzh1 committed
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
func TestAlreadyCanceled(t *testing.T) {
	ctx, done := context.WithTimeout(context.Background(), 500*time.Millisecond)
	defer done()
	dctx, done2 := context.WithCancel(ctx)
	done2()
	scenario1a := newScenarioRequest(t, dctx, "ollama-model-1", 10, &api.Duration{Duration: 0})
	s := InitScheduler(ctx)
	slog.Info("scenario1a")
	s.pendingReqCh <- scenario1a.req
	require.Len(t, s.pendingReqCh, 1)
	s.Run(ctx)
	time.Sleep(5 * time.Millisecond)
	require.Empty(t, s.pendingReqCh)
	require.Empty(t, scenario1a.req.errCh)
	require.Empty(t, scenario1a.req.successCh)
}

func TestHomogeneousGPUs(t *testing.T) {
	ctx, done := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer done()
	s := InitScheduler(ctx)

	s.getGpuFn = func() gpu.GpuInfoList {
		// Set memory values to require the model to be spread
		gpus := []gpu.GpuInfo{
			{Library: "cuda"},
			{Library: "rocm"},
		}
		gpus[0].TotalMemory = 1 * format.GibiByte
		gpus[0].FreeMemory = 256 * format.MebiByte
		gpus[1].TotalMemory = 1 * format.GibiByte
		gpus[1].FreeMemory = 256 * format.MebiByte
		return gpus
	}
	s.getCpuFn = getCpuFn
	a := newScenarioRequest(t, ctx, "ollama-model-1", 10, &api.Duration{Duration: 5 * time.Millisecond})
	s.newServerFn = func(gpus gpu.GpuInfoList, model string, ggml *llm.GGML, adapters []string, projectors []string, opts api.Options, numParallel int) (llm.LlamaServer, error) {
		require.Len(t, gpus, 1)
		return a.newServer(gpus, model, ggml, adapters, projectors, opts, numParallel)
	}
	slog.Info("a")
	s.pendingReqCh <- a.req
	require.Len(t, s.pendingReqCh, 1)
	s.Run(ctx)
	select {
	case resp := <-a.req.successCh:
		require.Equal(t, resp.llama, a.srv)
		require.Empty(t, s.pendingReqCh)
		require.Empty(t, a.req.errCh)
	case err := <-a.req.errCh:
		t.Fatal(err.Error())
	case <-ctx.Done():
		t.Fatal("timeout")
	}
}

mashun1's avatar
v1  
mashun1 committed
707
type mockLlm struct {
xuxzh1's avatar
init  
xuxzh1 committed
708
709
710
711
712
713
714
715
716
717
718
719
720
721
	pingResp           error
	waitResp           error
	completionResp     error
	embeddingResp      []float32
	embeddingRespErr   error
	tokenizeResp       []int
	tokenizeRespErr    error
	detokenizeResp     string
	detonekizeRespErr  error
	closeResp          error
	closeCalled        bool
	estimatedVRAM      uint64
	estimatedTotal     uint64
	estimatedVRAMByGPU map[string]uint64
mashun1's avatar
v1  
mashun1 committed
722
723
724
725
726
727
728
}

func (s *mockLlm) Ping(ctx context.Context) error             { return s.pingResp }
func (s *mockLlm) WaitUntilRunning(ctx context.Context) error { return s.waitResp }
func (s *mockLlm) Completion(ctx context.Context, req llm.CompletionRequest, fn func(llm.CompletionResponse)) error {
	return s.completionResp
}
xuxzh1's avatar
init  
xuxzh1 committed
729
730

func (s *mockLlm) Embedding(ctx context.Context, input string) ([]float32, error) {
mashun1's avatar
v1  
mashun1 committed
731
732
	return s.embeddingResp, s.embeddingRespErr
}
xuxzh1's avatar
init  
xuxzh1 committed
733

mashun1's avatar
v1  
mashun1 committed
734
735
736
func (s *mockLlm) Tokenize(ctx context.Context, content string) ([]int, error) {
	return s.tokenizeResp, s.tokenizeRespErr
}
xuxzh1's avatar
init  
xuxzh1 committed
737

mashun1's avatar
v1  
mashun1 committed
738
739
740
func (s *mockLlm) Detokenize(ctx context.Context, tokens []int) (string, error) {
	return s.detokenizeResp, s.detonekizeRespErr
}
xuxzh1's avatar
init  
xuxzh1 committed
741

mashun1's avatar
v1  
mashun1 committed
742
743
744
745
func (s *mockLlm) Close() error {
	s.closeCalled = true
	return s.closeResp
}
xuxzh1's avatar
init  
xuxzh1 committed
746
747
748
func (s *mockLlm) EstimatedVRAM() uint64                  { return s.estimatedVRAM }
func (s *mockLlm) EstimatedTotal() uint64                 { return s.estimatedTotal }
func (s *mockLlm) EstimatedVRAMByGPU(gpuid string) uint64 { return s.estimatedVRAMByGPU[gpuid] }