logprob_test.go 14.1 KB
Newer Older
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
package common

import (
	"math"
	"testing"

	"github.com/ollama/ollama/llm"
)

func TestCalculateLogprobs(t *testing.T) {
	tokens := map[int]string{
		0: "hello",
		1: "hi",
		2: "hey",
		3: "world",
	}
	decoder := func(tokenID int) string {
		if text, ok := tokens[tokenID]; ok {
			return text
		}
		return ""
	}

	tests := []struct {
		name          string
		logits        []float32
		selectedToken int
		topK          int
		wantLen       int
		wantToken     string
	}{
		{
			name:          "Empty logits",
			logits:        []float32{},
			selectedToken: 0,
			topK:          0,
			wantLen:       0,
		},
		{
			name:          "Single token without top logprobs",
			logits:        []float32{1.0, 0.5, 0.3, 0.1},
			selectedToken: 0,
			topK:          0,
			wantLen:       1,
			wantToken:     "hello",
		},
		{
			name:          "Single token with top logprobs",
			logits:        []float32{1.0, 0.5, 0.3, 0.1},
			selectedToken: 0,
			topK:          3,
			wantLen:       1,
			wantToken:     "hello",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result := CalculateLogprobs(tt.logits, tt.selectedToken, tt.topK, decoder)
			if len(result) != tt.wantLen {
				t.Errorf("CalculateLogprobs() returned %d results, want %d", len(result), tt.wantLen)
			}
			if tt.wantLen > 0 && result[0].Token != tt.wantToken {
				t.Errorf("CalculateLogprobs() token = %s, want %s", result[0].Token, tt.wantToken)
			}
			if tt.topK > 0 && len(result) > 0 {
				if len(result[0].TopLogprobs) != tt.topK {
					t.Errorf("CalculateLogprobs() top logprobs count = %d, want %d", len(result[0].TopLogprobs), tt.topK)
				}
			}
		})
	}
}

func TestCalculateLogprobsNumericalStability(t *testing.T) {
	tokens := map[int]string{
		0: "a",
		1: "b",
		2: "c",
	}
	decoder := func(tokenID int) string {
		if text, ok := tokens[tokenID]; ok {
			return text
		}
		return ""
	}

	// Test with very large logits to ensure numerical stability
	logits := []float32{1000.0, 999.0, 998.0}
	result := CalculateLogprobs(logits, 0, 3, decoder)

	if len(result) != 1 {
		t.Fatalf("Expected 1 result, got %d", len(result))
	}

	// Check that log probabilities are finite and reasonable
	if math.IsInf(result[0].Logprob, 0) || math.IsNaN(result[0].Logprob) {
		t.Errorf("Selected token logprob is not finite: %f", result[0].Logprob)
	}

	for i, tlp := range result[0].TopLogprobs {
		if math.IsInf(tlp.Logprob, 0) || math.IsNaN(tlp.Logprob) {
			t.Errorf("Top logprob[%d] is not finite: %f", i, tlp.Logprob)
		}
	}

	// Top logprobs should be in descending order
	for i := 1; i < len(result[0].TopLogprobs); i++ {
		if result[0].TopLogprobs[i].Logprob > result[0].TopLogprobs[i-1].Logprob {
			t.Errorf("Top logprobs not in descending order: %f > %f",
				result[0].TopLogprobs[i].Logprob, result[0].TopLogprobs[i-1].Logprob)
		}
	}
}

func TestCalculateLogprobsProbabilityCorrectness(t *testing.T) {
	tokens := map[int]string{
		0: "hello",
		1: "world",
		2: "foo",
		3: "bar",
	}
	decoder := func(tokenID int) string {
		if text, ok := tokens[tokenID]; ok {
			return text
		}
		return ""
	}

	tests := []struct {
		name          string
		logits        []float32
		selectedToken int
		topK          int
	}{
		{
			name:          "Uniform logits",
			logits:        []float32{1.0, 1.0, 1.0, 1.0},
			selectedToken: 0,
			topK:          4,
		},
		{
			name:          "Different logits",
			logits:        []float32{2.0, 1.0, 0.5, 0.1},
			selectedToken: 0,
			topK:          4,
		},
		{
			name:          "Negative logits",
			logits:        []float32{-1.0, -2.0, -3.0, -4.0},
			selectedToken: 0,
			topK:          4,
		},
		{
			name:          "Mixed logits",
			logits:        []float32{5.0, -5.0, 0.0, 2.5},
			selectedToken: 0,
			topK:          4,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result := CalculateLogprobs(tt.logits, tt.selectedToken, tt.topK, decoder)

			if len(result) != 1 {
				t.Fatalf("Expected 1 result, got %d", len(result))
			}

			// Verify all probabilities are non-positive (log probabilities should be <= 0)
			if result[0].Logprob > 0 {
				t.Errorf("Selected token logprob should be <= 0, got %f", result[0].Logprob)
			}

			for i, tlp := range result[0].TopLogprobs {
				if tlp.Logprob > 0 {
					t.Errorf("Top logprob[%d] should be <= 0, got %f", i, tlp.Logprob)
				}
			}

			// Verify that probabilities sum to approximately 1
			// Sum of exp(logprob) for all tokens should equal 1
			var probSum float64
			for _, lp := range result[0].TopLogprobs {
				probSum += math.Exp(lp.Logprob)
			}

			// For uniform logits, each probability should be 1/n
			if tt.name == "Uniform logits" {
				expectedProb := 1.0 / float64(len(tt.logits))
				actualProb := math.Exp(result[0].Logprob)
				if math.Abs(actualProb-expectedProb) > 1e-6 {
					t.Errorf("For uniform logits, expected probability %f, got %f",
						expectedProb, actualProb)
				}
			}

			// Verify top logprobs are sorted in descending order
			for i := 1; i < len(result[0].TopLogprobs); i++ {
				if result[0].TopLogprobs[i].Logprob > result[0].TopLogprobs[i-1].Logprob {
					t.Errorf("Top logprobs not sorted: position %d (%f) > position %d (%f)",
						i, result[0].TopLogprobs[i].Logprob,
						i-1, result[0].TopLogprobs[i-1].Logprob)
				}
			}

			// Verify the selected token appears in top logprobs
			selectedText := decoder(tt.selectedToken)
			found := false
			for _, tlp := range result[0].TopLogprobs {
				if tlp.Token == selectedText {
					found = true
					// The logprob in top logprobs should match the selected token's logprob
					if math.Abs(tlp.Logprob-result[0].Logprob) > 1e-6 {
						t.Errorf("Selected token logprob mismatch: main=%f, in top=%f",
							result[0].Logprob, tlp.Logprob)
					}
					break
				}
			}
			if !found {
				t.Errorf("Selected token %q not found in top logprobs", selectedText)
			}
		})
	}
}

func TestCalculateLogprobsSoftmaxCorrectness(t *testing.T) {
	// Test that softmax calculation is correct by verifying probabilities sum to 1
	decoder := func(tokenID int) string {
		return string(rune('A' + tokenID))
	}

	tests := []struct {
		name   string
		logits []float32
	}{
		{
			name:   "Small vocabulary",
			logits: []float32{1.0, 2.0, 3.0},
		},
		{
			name:   "Large differences",
			logits: []float32{10.0, 0.0, -10.0},
		},
		{
			name:   "All equal",
			logits: []float32{5.0, 5.0, 5.0, 5.0, 5.0},
		},
		{
			name:   "Very large values",
			logits: []float32{500.0, 499.0, 498.0},
		},
		{
			name:   "Very small values",
			logits: []float32{-500.0, -499.0, -498.0},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// Calculate logprobs for all tokens
			var totalProb float64
			for i := range tt.logits {
				result := CalculateLogprobs(tt.logits, i, 0, decoder)
				if len(result) != 1 {
					t.Fatalf("Expected 1 result, got %d", len(result))
				}
				prob := math.Exp(result[0].Logprob)
				totalProb += prob

				// Verify each probability is between 0 and 1
				if prob < 0 || prob > 1 {
					t.Errorf("Token %d probability %f is out of range [0, 1]", i, prob)
				}
			}

			// Total probability should be very close to 1.0 (allowing for floating point errors)
			if math.Abs(totalProb-1.0) > 1e-5 {
				t.Errorf("Total probability sum is %f, expected 1.0", totalProb)
			}
		})
	}
}

func TestCalculateLogprobsSelectedTokenCorrectness(t *testing.T) {
	decoder := func(tokenID int) string {
		return string(rune('A' + tokenID))
	}

	logits := []float32{3.0, 1.0, 2.0, 0.5}

	// Test that selecting different tokens gives the correct probabilities
	// and that the highest logit has the highest probability
	maxLogitIndex := 0
	maxLogitValue := logits[0]
	for i, logit := range logits[1:] {
		if logit > maxLogitValue {
			maxLogitValue = logit
			maxLogitIndex = i + 1
		}
	}

	var maxProb float64
	var maxProbIndex int

	for i := range logits {
		result := CalculateLogprobs(logits, i, 0, decoder)
		prob := math.Exp(result[0].Logprob)

		if prob > maxProb {
			maxProb = prob
			maxProbIndex = i
		}

		// Verify the token matches
		expectedToken := decoder(i)
		if result[0].Token != expectedToken {
			t.Errorf("Token %d: expected token %q, got %q", i, expectedToken, result[0].Token)
		}
	}

	// The token with the highest logit should have the highest probability
	if maxProbIndex != maxLogitIndex {
		t.Errorf("Token with highest probability (%d) doesn't match token with highest logit (%d)",
			maxProbIndex, maxLogitIndex)
	}
}

func TestCalculateLogprobsTopKOrdering(t *testing.T) {
	tokens := map[int]string{
		0: "first",
		1: "second",
		2: "third",
		3: "fourth",
		4: "fifth",
	}
	decoder := func(tokenID int) string {
		return tokens[tokenID]
	}

	// Logits in non-sorted order
	logits := []float32{2.0, 5.0, 1.0, 4.0, 3.0}
	// Expected order by probability: 1 (5.0), 3 (4.0), 4 (3.0), 0 (2.0), 2 (1.0)
	expectedOrder := []string{"second", "fourth", "fifth", "first", "third"}

	result := CalculateLogprobs(logits, 0, 5, decoder)

	if len(result) != 1 {
		t.Fatalf("Expected 1 result, got %d", len(result))
	}

	if len(result[0].TopLogprobs) != 5 {
		t.Fatalf("Expected 5 top logprobs, got %d", len(result[0].TopLogprobs))
	}

	// Verify ordering matches expected
	for i, tlp := range result[0].TopLogprobs {
		if tlp.Token != expectedOrder[i] {
			t.Errorf("Position %d: expected token %q, got %q", i, expectedOrder[i], tlp.Token)
		}
	}

	// Verify probabilities are in descending order
	for i := 1; i < len(result[0].TopLogprobs); i++ {
		if result[0].TopLogprobs[i].Logprob > result[0].TopLogprobs[i-1].Logprob {
			t.Errorf("Probabilities not in descending order at position %d: %f > %f",
				i, result[0].TopLogprobs[i].Logprob, result[0].TopLogprobs[i-1].Logprob)
		}
	}
}

func TestLogprobsWithStopSequences(t *testing.T) {
	tests := []struct {
		name              string
		pendingResponses  []string
		pendingLogprobs   []llm.Logprob
		stop              string
		expectedResponses []string
		expectedLogprobs  int
	}{
		{
			name:             "Single token stop",
			pendingResponses: []string{"Hello", " world", "!"},
			pendingLogprobs: []llm.Logprob{
				{TokenLogprob: llm.TokenLogprob{Token: "Hello", Logprob: -0.1}},
				{TokenLogprob: llm.TokenLogprob{Token: " world", Logprob: -0.2}},
				{TokenLogprob: llm.TokenLogprob{Token: "!", Logprob: -0.3}},
			},
			stop:              "!",
			expectedResponses: []string{"Hello", " world"},
			expectedLogprobs:  2,
		},
		{
			name:             "Multi-token stop sequence",
			pendingResponses: []string{"Hello", " ", "there", "STOP"},
			pendingLogprobs: []llm.Logprob{
				{TokenLogprob: llm.TokenLogprob{Token: "Hello", Logprob: -0.1}},
				{TokenLogprob: llm.TokenLogprob{Token: " ", Logprob: -0.2}},
				{TokenLogprob: llm.TokenLogprob{Token: "there", Logprob: -0.3}},
				{TokenLogprob: llm.TokenLogprob{Token: "STOP", Logprob: -0.4}},
			},
			stop:              "STOP",
			expectedResponses: []string{"Hello", " ", "there"},
			expectedLogprobs:  3,
		},
		{
			name:             "Partial token stop",
			pendingResponses: []string{"Hello", " the", "re!"},
			pendingLogprobs: []llm.Logprob{
				{TokenLogprob: llm.TokenLogprob{Token: "Hello", Logprob: -0.1}},
				{TokenLogprob: llm.TokenLogprob{Token: " the", Logprob: -0.2}},
				{TokenLogprob: llm.TokenLogprob{Token: "re!", Logprob: -0.3}},
			},
			stop:              "there!",
			expectedResponses: []string{"Hello", " "},
			expectedLogprobs:  2,
		},
		{
			name:             "Stop at beginning of last token",
			pendingResponses: []string{"Hello", " world", "END"},
			pendingLogprobs: []llm.Logprob{
				{TokenLogprob: llm.TokenLogprob{Token: "Hello", Logprob: -0.1}},
				{TokenLogprob: llm.TokenLogprob{Token: " world", Logprob: -0.2}},
				{TokenLogprob: llm.TokenLogprob{Token: "END", Logprob: -0.3}},
			},
			stop:              "END",
			expectedResponses: []string{"Hello", " world"},
			expectedLogprobs:  2,
		},
		{
			name:             "Multi-token stop across tokens",
			pendingResponses: []string{"Text", " ", "with", " ", "stop", " ", "word"},
			pendingLogprobs: []llm.Logprob{
				{TokenLogprob: llm.TokenLogprob{Token: "Text", Logprob: -0.1}},
				{TokenLogprob: llm.TokenLogprob{Token: " ", Logprob: -0.2}},
				{TokenLogprob: llm.TokenLogprob{Token: "with", Logprob: -0.3}},
				{TokenLogprob: llm.TokenLogprob{Token: " ", Logprob: -0.4}},
				{TokenLogprob: llm.TokenLogprob{Token: "stop", Logprob: -0.5}},
				{TokenLogprob: llm.TokenLogprob{Token: " ", Logprob: -0.6}},
				{TokenLogprob: llm.TokenLogprob{Token: "word", Logprob: -0.7}},
			},
			stop:              "stop word",
			expectedResponses: []string{"Text", " ", "with", " "},
			expectedLogprobs:  4,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// Simulate the stop sequence detection and truncation
			origLen := len(tt.pendingResponses)
			responses, tokenTruncated := TruncateStop(tt.pendingResponses, tt.stop)
			newLen := len(responses)

			// Simulate logprobs truncation
			logprobs := make([]llm.Logprob, len(tt.pendingLogprobs))
			copy(logprobs, tt.pendingLogprobs)

			origLogprobsLen := len(logprobs)
			numTokensRemoved := origLen - newLen
			newLogprobsLen := origLogprobsLen - numTokensRemoved
			if newLogprobsLen < 0 {
				newLogprobsLen = 0
			}
			logprobs = logprobs[:newLogprobsLen]

			// Verify responses were truncated correctly
			if len(responses) != len(tt.expectedResponses) {
				t.Errorf("Expected %d responses, got %d", len(tt.expectedResponses), len(responses))
			}

			// Verify logprobs count matches truncated responses
			if len(logprobs) != tt.expectedLogprobs {
				t.Errorf("Expected %d logprobs after truncation, got %d", tt.expectedLogprobs, len(logprobs))
			}

			// Verify logprobs count matches response count
			if len(logprobs) != len(responses) {
				t.Errorf("Logprobs count (%d) doesn't match responses count (%d)", len(logprobs), len(responses))
			}

			// Verify the correct logprobs were kept (skip last token if it was truncated)
			// When tokenTruncated is true, the last response token may not match the logprob token
			checkLen := len(logprobs)
			if tokenTruncated && checkLen > 0 {
				checkLen-- // Skip checking the last token when it was partially truncated
			}

			for i := range checkLen {
				if i < len(responses) && logprobs[i].Token != responses[i] {
					t.Errorf("Logprob[%d] token %q doesn't match response[%d] %q",
						i, logprobs[i].Token, i, responses[i])
				}
			}
		})
	}
}