"docs/source/en/installation.mdx" did not exist on "12fd0736dcc51f77c52130ab10177d0c1d5a29d9"
context_test.go 10.2 KB
Newer Older
1
2
3
4
5
6
//go:build integration

package integration

import (
	"context"
7
8
	"log/slog"
	"sync"
9
10
11
12
13
14
	"testing"
	"time"

	"github.com/ollama/ollama/api"
)

15
16
17
18
19
20
21
22
23
func TestLongInputContext(t *testing.T) {
	// Setting NUM_PARALLEL to 1 ensures the allocated context is exactly what
	// we asked for and there is nothing extra that we could spill over into
	t.Setenv("OLLAMA_NUM_PARALLEL", "1")

	// Longer needed for small footprint GPUs
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
	defer cancel()
	// Set up the test data
24
25
26
27
28
29
30
31
	req := api.ChatRequest{
		Model: smol,
		Messages: []api.Message{
			{
				Role:    "user",
				Content: "Oh, don’t speak to me of Austria. Perhaps I don’t understand things, but Austria never has wished, and does not wish, for war. She is betraying us! Russia alone must save Europe. Our gracious sovereign recognizes his high vocation and will be true to it. That is the one thing I have faith in! Our good and wonderful sovereign has to perform the noblest role on earth, and he is so virtuous and noble that God will not forsake him. He will fulfill his vocation and crush the hydra of revolution, which has become more terrible than ever in the person of this murderer and villain! We alone must avenge the blood of the just one.... Whom, I ask you, can we rely on?... England with her commercial spirit will not and cannot understand the Emperor Alexander’s loftiness of soul. She has refused to evacuate Malta. She wanted to find, and still seeks, some secret motive in our actions. What answer did Novosíltsev get? None. The English have not understood and cannot understand the self-abnegation of our Emperor who wants nothing for himself, but only desires the good of mankind. And what have they promised? Nothing! And what little they have promised they will not perform! Prussia has always declared that Buonaparte is invincible, and that all Europe is powerless before him.... And I don’t believe a word that Hardenburg says, or Haugwitz either. This famous Prussian neutrality is just a trap. I have faith only in God and the lofty destiny of our adored monarch. He will save Europe! What country is this referring to?",
			},
		},
32
		Stream: &stream,
33
		Options: map[string]any{
34
35
36
37
38
39
40
41
42
43
			"temperature": 0,
			"seed":        123,
			"num_ctx":     128,
		},
	}
	client, _, cleanup := InitServerConnection(ctx, t)
	defer cleanup()
	if err := PullIfMissing(ctx, client, req.Model); err != nil {
		t.Fatalf("PullIfMissing failed: %v", err)
	}
44
	DoChat(ctx, t, client, req, []string{"russia", "german", "france", "england", "austria", "prussia", "europe", "individuals", "coalition", "conflict"}, 120*time.Second, 10*time.Second)
45
46
}

47
func TestContextExhaustion(t *testing.T) {
48
49
50
51
	// Setting NUM_PARALLEL to 1 ensures the allocated context is exactly what
	// we asked for and there is nothing extra that we could spill over into
	t.Setenv("OLLAMA_NUM_PARALLEL", "1")

Daniel Hiltgen's avatar
Daniel Hiltgen committed
52
	// Longer needed for small footprint GPUs
53
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
54
55
	defer cancel()
	// Set up the test data
56
57
58
59
60
61
62
63
	req := api.ChatRequest{
		Model: smol,
		Messages: []api.Message{
			{
				Role:    "user",
				Content: "Write me a story in english with a lot of emojis",
			},
		},
64
		Stream: &stream,
65
		Options: map[string]any{
66
67
68
69
70
			"temperature": 0,
			"seed":        123,
			"num_ctx":     128,
		},
	}
71
72
73
74
75
	client, _, cleanup := InitServerConnection(ctx, t)
	defer cleanup()
	if err := PullIfMissing(ctx, client, req.Model); err != nil {
		t.Fatalf("PullIfMissing failed: %v", err)
	}
76
	DoChat(ctx, t, client, req, []string{"once", "upon", "lived", "sunny", "cloudy", "clear", "water", "time", "travel", "world"}, 120*time.Second, 10*time.Second)
77
}
78

79
// Send multiple generate requests with prior context and ensure the response is coherant and expected
80
func TestParallelGenerateWithHistory(t *testing.T) {
81
	modelName := "gpt-oss:20b"
82
83
84
85
86
87
88
89
90
	req, resp := GenerateRequests()
	numParallel := 2
	iterLimit := 2

	softTimeout, hardTimeout := getTimeouts(t)
	ctx, cancel := context.WithTimeout(context.Background(), hardTimeout)
	defer cancel()
	client, _, cleanup := InitServerConnection(ctx, t)
	defer cleanup()
91
92
	initialTimeout := 120 * time.Second
	streamTimeout := 20 * time.Second
93
94

	// Get the server running (if applicable) warm the model up with a single initial request
95
	slog.Info("loading", "model", modelName)
96
	err := client.Generate(ctx,
97
		&api.GenerateRequest{Model: modelName, KeepAlive: &api.Duration{Duration: 10 * time.Second}},
98
99
100
		func(response api.GenerateResponse) error { return nil },
	)
	if err != nil {
101
102
103
104
105
106
107
		t.Fatalf("failed to load model %s: %s", modelName, err)
	}
	gpuPercent := getGPUPercent(ctx, t, client, modelName)
	if gpuPercent < 80 {
		slog.Warn("Low GPU percentage - increasing timeouts", "percent", gpuPercent)
		initialTimeout = 240 * time.Second
		streamTimeout = 30 * time.Second
108
109
110
111
112
113
114
115
	}

	var wg sync.WaitGroup
	wg.Add(numParallel)
	for i := range numParallel {
		go func(i int) {
			defer wg.Done()
			k := i % len(req)
116
			req[k].Model = modelName
117
118
119
120
121
122
123
124
			for j := 0; j < iterLimit; j++ {
				if time.Now().Sub(started) > softTimeout {
					slog.Info("exceeded soft timeout, winding down test")
					return
				}
				slog.Info("Starting", "thread", i, "iter", j)
				// On slower GPUs it can take a while to process the concurrent requests
				// so we allow a much longer initial timeout
125
				c := DoGenerate(ctx, t, client, req[k], resp[k], initialTimeout, streamTimeout)
126
127
128
129
130
131
				req[k].Context = c
				req[k].Prompt = "tell me more!"
			}
		}(i)
	}
	wg.Wait()
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
// Send generate requests with prior context and ensure the response is coherant and expected
func TestGenerateWithHistory(t *testing.T) {
	req := api.GenerateRequest{
		Model:     smol,
		Prompt:    rainbowPrompt,
		Stream:    &stream,
		KeepAlive: &api.Duration{Duration: 10 * time.Second},
		Options: map[string]any{
			"num_ctx": 16384,
		},
	}

	softTimeout, hardTimeout := getTimeouts(t)
	ctx, cancel := context.WithTimeout(context.Background(), hardTimeout)
	defer cancel()
	client, _, cleanup := InitServerConnection(ctx, t)
	defer cleanup()

	// Get the server running (if applicable) warm the model up with a single initial request
	slog.Info("loading", "model", req.Model)
	err := client.Generate(ctx,
		&api.GenerateRequest{Model: req.Model, KeepAlive: &api.Duration{Duration: 10 * time.Second}, Options: req.Options},
		func(response api.GenerateResponse) error { return nil },
	)
	if err != nil {
		t.Fatalf("failed to load model %s: %s", req.Model, err)
	}

	req.Context = DoGenerate(ctx, t, client, req, rainbowExpected, 30*time.Second, 20*time.Second)

	for i := 0; i < len(rainbowFollowups); i++ {
		req.Prompt = rainbowFollowups[i]
		if time.Now().Sub(started) > softTimeout {
			slog.Info("exceeded soft timeout, winding down test")
			return
		}
		req.Context = DoGenerate(ctx, t, client, req, rainbowExpected, 30*time.Second, 20*time.Second)
	}
}

174
// Send multiple chat requests with prior context and ensure the response is coherant and expected
175
func TestParallelChatWithHistory(t *testing.T) {
176
	modelName := "gpt-oss:20b"
177
178
179
180
181
182
183
184
185
	req, resp := ChatRequests()
	numParallel := 2
	iterLimit := 2

	softTimeout, hardTimeout := getTimeouts(t)
	ctx, cancel := context.WithTimeout(context.Background(), hardTimeout)
	defer cancel()
	client, _, cleanup := InitServerConnection(ctx, t)
	defer cleanup()
186
187
	initialTimeout := 120 * time.Second
	streamTimeout := 20 * time.Second
188
189

	// Get the server running (if applicable) warm the model up with a single initial empty request
190
	slog.Info("loading", "model", modelName)
191
	err := client.Generate(ctx,
192
		&api.GenerateRequest{Model: modelName, KeepAlive: &api.Duration{Duration: 10 * time.Second}},
193
194
195
		func(response api.GenerateResponse) error { return nil },
	)
	if err != nil {
196
197
198
199
200
201
202
		t.Fatalf("failed to load model %s: %s", modelName, err)
	}
	gpuPercent := getGPUPercent(ctx, t, client, modelName)
	if gpuPercent < 80 {
		slog.Warn("Low GPU percentage - increasing timeouts", "percent", gpuPercent)
		initialTimeout = 240 * time.Second
		streamTimeout = 30 * time.Second
203
	}
204

205
206
207
208
209
210
	var wg sync.WaitGroup
	wg.Add(numParallel)
	for i := range numParallel {
		go func(i int) {
			defer wg.Done()
			k := i % len(req)
211
			req[k].Model = modelName
212
213
214
215
216
217
218
219
			for j := 0; j < iterLimit; j++ {
				if time.Now().Sub(started) > softTimeout {
					slog.Info("exceeded soft timeout, winding down test")
					return
				}
				slog.Info("Starting", "thread", i, "iter", j)
				// On slower GPUs it can take a while to process the concurrent requests
				// so we allow a much longer initial timeout
220
				assistant := DoChat(ctx, t, client, req[k], resp[k], initialTimeout, streamTimeout)
221
222
223
224
225
226
227
228
229
230
231
				if assistant == nil {
					t.Fatalf("didn't get an assistant response for context")
				}
				req[k].Messages = append(req[k].Messages,
					*assistant,
					api.Message{Role: "user", Content: "tell me more!"},
				)
			}
		}(i)
	}
	wg.Wait()
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

// Send generate requests with prior context and ensure the response is coherant and expected
func TestChatWithHistory(t *testing.T) {
	req := api.ChatRequest{
		Model:     smol,
		Stream:    &stream,
		KeepAlive: &api.Duration{Duration: 10 * time.Second},
		Options: map[string]any{
			"num_ctx": 16384,
		},
		Messages: []api.Message{
			{
				Role:    "user",
				Content: rainbowPrompt,
			},
		},
	}

	softTimeout, hardTimeout := getTimeouts(t)
	ctx, cancel := context.WithTimeout(context.Background(), hardTimeout)
	defer cancel()
	client, _, cleanup := InitServerConnection(ctx, t)
	defer cleanup()

	// Get the server running (if applicable) warm the model up with a single initial request
	slog.Info("loading", "model", req.Model)
	err := client.Generate(ctx,
		&api.GenerateRequest{Model: req.Model, KeepAlive: &api.Duration{Duration: 10 * time.Second}, Options: req.Options},
		func(response api.GenerateResponse) error { return nil },
	)
	if err != nil {
		t.Fatalf("failed to load model %s: %s", req.Model, err)
	}

	assistant := DoChat(ctx, t, client, req, rainbowExpected, 30*time.Second, 20*time.Second)

	for i := 0; i < len(rainbowFollowups); i++ {
		if time.Now().Sub(started) > softTimeout {
			slog.Info("exceeded soft timeout, winding down test")
			return
		}
		req.Messages = append(req.Messages,
			*assistant,
			api.Message{Role: "user", Content: rainbowFollowups[i]},
		)

		assistant = DoChat(ctx, t, client, req, rainbowExpected, 30*time.Second, 20*time.Second)
		if assistant == nil {
			t.Fatalf("didn't get an assistant response for context")
		}
	}
}