test_logprobs.py 43.9 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4

import itertools
5
import math
6
from collections.abc import Generator
7
from typing import get_args
8
9
10
11

import pytest
import torch

12
from tests.utils import large_gpu_mark
13
from tests.v1.sample.utils import (
14
15
    BatchLogprobsComposition,
    BatchLogprobsSpecType,
16
    assert_incr_detok_str_matches_non_incr_detok_str,
17
18
19
    compute_correct_cumulative_logprob,
    get_test_batch,
)
20
from vllm import SamplingParams
21
from vllm.config.model import LogprobsMode
22
from vllm.distributed import cleanup_dist_env_and_memory
23
from vllm.platforms import current_platform
24

25
from ...conftest import HfRunner, VllmRunner
26

27
MODEL = "meta-llama/Llama-3.2-1B-Instruct"
28
29
DTYPE = "half"

30
31
32
33
NONE = BatchLogprobsComposition.NONE
SAMPLE = BatchLogprobsComposition.SAMPLE
PROMPT = BatchLogprobsComposition.PROMPT
SAMPLE_PROMPT = BatchLogprobsComposition.SAMPLE_PROMPT
34

35
36
37
38
# On ROCm, floating-point reductions in attention and GEMM kernels are
# non-associative and sensitive to batch geometry. The ref LLM (no spec
# decode, default scheduling) and the spec-decode LLM (chunked prefill,
# different effective batch sizes) follow different reduction orders,
Jiayi Yan's avatar
Jiayi Yan committed
39
# producing numerically divergent logprobs that get misattributed to
40
41
42
43
44
# spec-decode incorrectness.
#
# Force LLM instances into an identical, deterministic execution
# mode so the test isolates spec-decode correctness only:
ROCM_DETERMINISM_KWARGS: dict = (
45
    dict(max_num_seqs=1, attention_backend="TRITON_ATTN")
46
47
48
49
    if current_platform.is_rocm()
    else {}
)

50
51
52
53

@pytest.fixture(
    scope="module",
    # Parameterize APC
54
55
    params=[False, True],
)
56
def vllm_model(vllm_runner, request) -> Generator[VllmRunner, None, None]:
57
    with vllm_runner(
58
59
60
61
62
63
64
65
        MODEL,
        dtype=DTYPE,
        max_logprobs=7,
        # Very small number of batched tokens to ensure
        # that we test chunking.
        max_num_batched_tokens=16,
        max_num_seqs=16,
        max_model_len=128,
66
        enable_chunked_prefill=True,
67
68
69
70
        enforce_eager=True,
        # TODO: enable this once we support it for
        # prompt logprobs.
        enable_prefix_caching=request.param,
71
        gpu_memory_utilization=0.4,
72
73
74
75
76
    ) as vllm_model:
        yield vllm_model


@pytest.fixture(scope="module")
77
def hf_model(hf_runner) -> Generator[HfRunner, None, None]:
78
79
80
81
82
83
    with hf_runner(MODEL, dtype=DTYPE) as hf_model:
        yield hf_model


def _repeat_logprob_config(
    test_prompts,
84
85
    logprob_prompt_logprob_list: BatchLogprobsSpecType,
) -> BatchLogprobsSpecType:
86
    """Ensure each test prompt has a logprob config.
87

88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
    A logprob config specifies the optional (i.e.
    may-be-`None`) number of sample logprobs and
    the optional number of prompt logprobs.

    If more test prompts than logprob configs are
    provided, the provided logprob configs are
    tiled to match the number of test prompts.

    If fewer test prompts than logprob configs
    are provided, the list of logprob configs
    is truncated to match the number of test
    prompts.

    Otherwise, the list of logprob configs
    is returned as-is.

    Args:
      test_prompts: list of prompts under test
      logprob_prompt_logprob_list: list of
                            (optional num sample logprob,
                             optional num prompt logprob)
                             tuples
110

111
    Returns:
112
      list of
113
114
115
116
117
118
119
120
121
122
      (optional num sample logprob,optional num prompt logprob)
      tuples which is either identical to
      `logprob_prompt_logprob_list`, or else repeats
      `logprob_prompt_logprob_list` enough times to match the
      number of `test_prompts`, or else is truncated to match
      the number of `test_prompts`
    """
    num_test_prompts = len(test_prompts)
    # Make sure there is a logprobs configuration for each test prompt
    logprob_prompt_logprob_list = list(
123
124
        itertools.islice(itertools.cycle(logprob_prompt_logprob_list), num_test_prompts)
    )
125
126
127
128
129
    # Now the number of prompts should match the number of sample params combos
    assert num_test_prompts == len(logprob_prompt_logprob_list)
    return logprob_prompt_logprob_list


130
131
132
133
134
135
136
def _run_and_validate(
    vllm_model: VllmRunner,
    test_prompts: list[str],
    vllm_sampling_params: SamplingParams,
    hf_logprobs: list[list[torch.Tensor]],
    hf_outputs: list[tuple[list[int], str]],
    logprob_prompt_logprob_list: BatchLogprobsSpecType,
137
    temperature: float,
138
139
    max_tokens: int,
    do_apc: bool,
140
) -> None:
141
    vllm_results = vllm_model.llm.generate(
142
143
        test_prompts, sampling_params=vllm_sampling_params
    )
144
145

    for vllm_result, hf_logprob, hf_output, logprob_prompt_logprob in zip(
146
147
        vllm_results, hf_logprobs, hf_outputs, logprob_prompt_logprob_list
    ):
148
149
150
151
152
153
        # Extract request-level (prompt)logprobs config
        num_top_logprobs, num_top_prompt_logprobs = logprob_prompt_logprob

        # Test whether sampled token output is consistent between vLLM and HF
        # vLLM prompt+completion should match HF output
        if temperature == 0.0:
154
155
156
157
            assert (
                vllm_result.prompt_token_ids + vllm_result.outputs[0].token_ids
                == hf_output[0]
            )
158
159
        else:
            # Sampled tokens won't match if not greedy
160
161
162
163
            assert (
                vllm_result.prompt_token_ids
                == hf_output[0][: len(vllm_result.prompt_token_ids)]
            )
164
165
166
167
168
169
170
171

        # Validate sample logprobs
        if num_top_logprobs is not None:
            assert num_top_logprobs is not None
            # Confirm that the structure of the sample logprobs in the result is
            # correct
            assert vllm_result.outputs[0].logprobs is not None
            assert len(vllm_result.outputs[0].logprobs) == max_tokens
172
173
174
            for logprobs, token_id in zip(
                vllm_result.outputs[0].logprobs, vllm_result.outputs[0].token_ids
            ):
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
                assert logprobs is not None

                # Confirm that the output token appears among the logprobs
                assert token_id in logprobs
                token_in_topk = logprobs[token_id].rank <= num_top_logprobs

                # If the output token is not included in the top K
                # logprob, it can return 1 more data
                if token_in_topk and num_top_logprobs != 0:
                    assert len(logprobs) == num_top_logprobs
                else:
                    assert len(logprobs) == num_top_logprobs + 1

                if num_top_logprobs > 0:
                    # We should have an entry for each of the topk ranks
                    all_ranks = {lp.rank for lp in logprobs.values()}
191
                    assert all(r in all_ranks for r in range(1, num_top_logprobs + 1))
192
193

            output_text = vllm_result.outputs[0].text
194
            output_string_from_most_likely_tokens_lst: list[str] = []
195
196
197
            for top_logprobs in vllm_result.outputs[0].logprobs:
                top_logprob = next(iter(top_logprobs.values()))
                output_string_from_most_likely_tokens_lst.append(
198
199
                    top_logprob.decoded_token
                )
200
201

            output_string_from_most_likely_tokens = "".join(
202
203
                output_string_from_most_likely_tokens_lst
            )
204
            assert_incr_detok_str_matches_non_incr_detok_str(
205
206
                output_text,
                output_string_from_most_likely_tokens,
207
208
                "The output text from the top logprob for each token "
                "position should be the same as the output text in the "
209
210
                "result.",
            )
211
212
213
214
215
216
217
218
219
220
221

            # Compare vLLM sample logprobs to HF
            vllm_sample_logprobs = vllm_result.outputs[0].logprobs
            for i, top_logprobs in enumerate(vllm_sample_logprobs):
                for token_id, sample_logprob in top_logprobs.items():
                    if temperature == 0.0 or i == 0:
                        logprob = sample_logprob.logprob
                        torch.testing.assert_close(
                            logprob,
                            hf_logprob[i][-1][token_id].item(),
                            atol=1e-2,
222
223
224
225
226
227
                            rtol=1e-2,
                        )
                    assert isinstance(sample_logprob.decoded_token, str), (
                        "The token should be decoded by the time it is"
                        " returned to the user."
                    )
228
229
230
231
232
233
234
235
236

            # At this point we know the sample logprobs are correct for this
            # request. Validate that cumulative_logprob is actually the sum.
            # For each request, assert that the returned cumulative logprob
            # matches the correct value, which is computed below.
            torch.testing.assert_close(
                vllm_result.outputs[0].cumulative_logprob,
                compute_correct_cumulative_logprob(vllm_result.outputs[0]),
                atol=1e-6,
237
238
                rtol=1e-6,
            )
239
240
241
242
243
244
245
246
247
248
249
250
        else:
            # Logprobs disabled for this request; should be None
            assert vllm_result.outputs[0].logprobs is None

        # Validate prompt logprobs
        if num_top_prompt_logprobs is not None:
            # Confirm that structure of prompt logprobs in result is correct
            assert vllm_result.prompt_logprobs is not None
            # - The first prompt logprob is always None
            assert vllm_result.prompt_logprobs[0] is None
            # - Prompt logprobs are returned for all indices in
            #   the prompt
251
            assert len(vllm_result.prompt_logprobs) == len(vllm_result.prompt_token_ids)
252
            for prompt_logprobs, prompt_token_id in zip(
253
254
                vllm_result.prompt_logprobs[1:], vllm_result.prompt_token_ids[1:]
            ):
255
256
257
258
                assert prompt_logprobs is not None

                # Confirm that the prompt token appears among the logprobs
                assert prompt_token_id in prompt_logprobs
259
260
261
                token_in_topk = (
                    prompt_logprobs[prompt_token_id].rank <= num_top_prompt_logprobs
                )
262
263
264
265
266
267
268
269
270
271
272

                # If the prompt token is not included in the top K
                # logprob, it can return 1 more data
                if token_in_topk and num_top_prompt_logprobs != 0:
                    assert len(prompt_logprobs) == num_top_prompt_logprobs
                else:
                    assert len(prompt_logprobs) == num_top_prompt_logprobs + 1

                if num_top_prompt_logprobs > 0:
                    # We should have an entry for each of the topk ranks
                    all_ranks = {lp.rank for lp in prompt_logprobs.values()}
273
274
275
                    assert all(
                        r in all_ranks for r in range(1, num_top_prompt_logprobs + 1)
                    )
276
277
278
279
280
281
282
283
284
285
286

            # Compare prompt logprobs to HF
            # The first prompt logprob is always None, so we compare it from
            # 1:.
            vllm_prompt_logprobs = vllm_result.prompt_logprobs[1:]
            for i, vllm_prompt_logprob_dict in enumerate(vllm_prompt_logprobs):
                for token_id, logprob in vllm_prompt_logprob_dict.items():
                    torch.testing.assert_close(
                        logprob.logprob,
                        hf_logprob[0][i][token_id].item(),
                        atol=2e-2,
287
288
                        rtol=2e-2,
                    )
289
290
291
292
        else:
            assert vllm_result.prompt_logprobs is None


293
294
295
@pytest.mark.parametrize(
    "batch_logprobs_composition", [NONE, SAMPLE, PROMPT, SAMPLE_PROMPT]
)
296
297
@pytest.mark.parametrize("temperature", [0.0, 2.0])
def test_get_logprobs_and_prompt_logprobs(
298
299
300
301
302
303
    hf_model,
    vllm_model,
    batch_logprobs_composition: BatchLogprobsComposition,
    temperature: float,
    example_prompts: list[str],
) -> None:
304
    """Test V1 Engine logprobs & prompt logprobs
305

306
307
308
309
310
311
312
313
314
315
316
317
    Exercise a variety of combinations of `logprobs` and `prompt_logprobs`
    settings and validate that
    * The generated logprobs and prompt logprobs are consistent with the
      configuration settings, in terms of whether or not the logprobs
      (of either type) were requested and how many were requested
    * The generated logprobs are consistent with the generated tokens
    * The generated (prompt)logprobs are consistent with HuggingFace
      (prompt)logprobs, as a reference

    batch_logprobs_composition controls the logprobs configurations for
    requests in the batch under test.

318
319
320
321
    APC tests run two test iterations so that cache hits occur.

    To save time, only test one APC-enabled scenario
    (sample & prompt logprobs enabled, temperature>0.0).
322

323
    Args:
324
325
      hf_model: HuggingFace reference model fixture
      vllm_model: vLLM model fixture
326
      batch_logprobs_composition: logprobs configuration for test batch
327
328
      temperature: "temperature" sampling parameter
      example_prompts: example prompt fixture
329
    """
330
331
    vllm_config = vllm_model.llm.llm_engine.vllm_config
    do_apc = vllm_config.cache_config.enable_prefix_caching
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
    if do_apc and (temperature < 2.0 or batch_logprobs_composition != SAMPLE_PROMPT):
        # Skip some test-cases to save time.
        pytest.skip()
    test_prompts = example_prompts

    max_tokens = 5
    hf_outputs = hf_model.generate_greedy(
        test_prompts,
        max_tokens=max_tokens,
    )
    hf_logprobs = hf_model.generate_greedy_logprobs(
        test_prompts,
        max_tokens=max_tokens,
    )

    # Batch has mixed sample params
    # (different logprobs/prompt logprobs combos)
    logprob_prompt_logprob_list = get_test_batch(batch_logprobs_composition)

    # Ensure that each test prompt has a logprob config for testing
    logprob_prompt_logprob_list = _repeat_logprob_config(
        test_prompts, logprob_prompt_logprob_list
    )
    # Generate SamplingParams
    vllm_sampling_params = [
        SamplingParams(
358
            max_tokens=max_tokens,
359
360
361
362
            logprobs=num_lp,
            prompt_logprobs=num_plp,
            temperature=temperature,
            seed=1984,
363
        )
364
365
366
367
368
369
370
371
372
373
374
        for num_lp, num_plp in logprob_prompt_logprob_list
    ]
    for _ in range(2 if do_apc else 1):
        _run_and_validate(
            vllm_model=vllm_model,
            test_prompts=test_prompts,
            vllm_sampling_params=vllm_sampling_params,
            hf_logprobs=hf_logprobs,
            hf_outputs=hf_outputs,
            logprob_prompt_logprob_list=logprob_prompt_logprob_list,
            temperature=temperature,
375
            max_tokens=max_tokens,
376
            do_apc=do_apc,
377
378
379
        )


380
def test_max_logprobs():
381
382
    """vLLM v1 engine should fail a request with `logprobs > max_logprobs`
    Should also fail for `prompt_logprobs > max_logprobs`
383
    APC should not matter as this test checks basic request validation.
384
    """
385
    with VllmRunner(
386
387
388
389
390
        "facebook/opt-125m",
        max_logprobs=1,
        enable_prefix_caching=False,
        gpu_memory_utilization=0.15,
        max_model_len=256,
391
392
393
394
    ) as runner:
        vllm_sampling_params = SamplingParams(logprobs=1)
        # should pass
        runner.generate(["Hello world"], sampling_params=vllm_sampling_params)
395

396
397
398
        bad_sampling_params = SamplingParams(logprobs=2)
        with pytest.raises(ValueError):
            runner.generate(["Hello world"], sampling_params=bad_sampling_params)
399
400


401
def test_none_logprobs(vllm_model, example_prompts):
402
    """Engine should return `logprobs` and `prompt_logprobs` as `None`
403

404
405
406
407
    Args:
      vllm_model: vLLM model fixture
      example_prompts: list of example prompts (test fixture)
    """
408
    max_tokens = 5
409

410
411
412
413
414
415
416
417
418
419
    sampling_params_logprobs_none = SamplingParams(
        max_tokens=max_tokens,
        logprobs=None,
        prompt_logprobs=None,
        temperature=0.0,
    )
    results_logprobs_none = vllm_model.llm.generate(
        example_prompts,
        sampling_params=sampling_params_logprobs_none,
    )
420

421
422
423
424
425
426
    for i in range(len(results_logprobs_none)):
        # Check sample logprobs are None
        assert results_logprobs_none[i].outputs[0].logprobs is None
        assert results_logprobs_none[i].outputs[0].cumulative_logprob is None
        # Check prompt logprobs are None
        assert results_logprobs_none[i].prompt_logprobs is None
427
428


429
def test_zero_logprobs(vllm_model, example_prompts):
430
    """Engine should return sampled token and prompt token logprobs
431

432
433
434
435
    Args:
      vllm_model: vLLM model fixture
      example_prompts: list of example prompts (test fixture)
    """
436
    max_tokens = 5
437

438
439
440
441
442
443
    sampling_params_logprobs_zero = SamplingParams(
        max_tokens=max_tokens, logprobs=0, prompt_logprobs=0, temperature=0.0
    )
    results_logprobs_zero = vllm_model.llm.generate(
        example_prompts, sampling_params=sampling_params_logprobs_zero
    )
444

445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
    for i in range(len(results_logprobs_zero)):
        # Check that there is one sample logprob dict for each
        # sample token
        logprobs = results_logprobs_zero[i].outputs[0].logprobs
        prompt_logprobs = results_logprobs_zero[i].prompt_logprobs
        sampled_token_ids = results_logprobs_zero[i].outputs[0].token_ids
        prompt_token_ids = results_logprobs_zero[i].prompt_token_ids
        assert logprobs is not None
        assert len(sampled_token_ids) == len(logprobs)
        assert results_logprobs_zero[i].outputs[0].cumulative_logprob is not None
        # Check that there is one prompt logprob dict for each
        # prompt token
        assert prompt_logprobs is not None
        assert len(prompt_token_ids) == len(prompt_logprobs)


def test_all_logprobs(example_prompts):
462
    """Engine should return all vocabulary logprobs and prompt logprobs
463
464
465
466

    Args:
      example_prompts: list of example prompts (test fixture)
    """
467
    with VllmRunner(
468
469
470
471
472
        "facebook/opt-125m",
        max_logprobs=-1,
        enable_prefix_caching=False,
        gpu_memory_utilization=0.15,
        max_model_len=256,
473
474
475
476
477
478
479
480
    ) as runner:
        sampling_params_logprobs_all = SamplingParams(
            max_tokens=5, logprobs=-1, prompt_logprobs=-1
        )
        results_logprobs_all = runner.llm.generate(
            example_prompts, sampling_params=sampling_params_logprobs_all
        )
        vocab_size = runner.llm.llm_engine.model_config.get_vocab_size()
481

482
483
484
485
486
487
488
489
490
491
        for i in range(len(results_logprobs_all)):
            logprobs = results_logprobs_all[i].outputs[0].logprobs
            prompt_logprobs = results_logprobs_all[i].prompt_logprobs
            assert logprobs is not None
            for logprob in logprobs:
                assert len(logprob) == vocab_size
            assert prompt_logprobs is not None
            assert prompt_logprobs[0] is None
            for prompt_logprob in prompt_logprobs[1:]:
                assert len(prompt_logprob) == vocab_size
492
493


494
@pytest.mark.parametrize("logprobs_mode", get_args(LogprobsMode))
495
def test_logprobs_mode(logprobs_mode: LogprobsMode):
496
497
498
499
500
    """Test with LLM engine with different logprobs_mode.
    For logprobs, we should have non-positive values.
    For logits, we should expect at least one positive values.
    """
    from vllm import LLM
501

502
503
504
505
506
507
508
509
510
    llm = LLM(
        "facebook/opt-125m",
        max_logprobs=5,
        enable_prefix_caching=False,
        # 2 other llms alive during whole session
        gpu_memory_utilization=0.05,
        max_model_len=16,
        logprobs_mode=logprobs_mode,
    )
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
    try:
        vllm_sampling_params = SamplingParams(logprobs=1)
        results = llm.generate(["Hello world"], sampling_params=vllm_sampling_params)

        total_token_with_logprobs = 0
        positive_values = 0
        for output in results[0].outputs:
            for logprobs in output.logprobs:
                for token_id in logprobs:
                    logprob = logprobs[token_id]
                    if logprobs_mode in ("raw_logprobs", "processed_logprobs"):
                        assert logprob.logprob <= 0
                    if logprob.logprob > 0:
                        positive_values = positive_values + 1
                    total_token_with_logprobs = total_token_with_logprobs + 1
        assert total_token_with_logprobs >= len(results[0].outputs)
        if logprobs_mode in ("raw_logits", "processed_logits"):
            assert positive_values > 0
    finally:
        del llm
531
        torch.accelerator.empty_cache()
532
        cleanup_dist_env_and_memory()
533
534


535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
class TestCorrectDecodedToken:
    """Unit tests for _correct_decoded_token method in LogprobsProcessor.

    This method handles UTF-8 decoding issues where incomplete byte sequences
    result in the Unicode replacement character "�" (U+FFFD). This commonly
    happens with byte-fallback tokenization when multi-byte UTF-8 characters
    are split across tokens.
    """

    @pytest.fixture
    def mock_tokenizer(self):
        """Create a mock tokenizer for testing."""
        from unittest.mock import Mock

        tokenizer = Mock()
        return tokenizer

    @pytest.fixture
    def processor_with_empty_logprobs(self, mock_tokenizer):
        """Create a LogprobsProcessor with empty logprobs."""
        from vllm.v1.engine.logprobs import LogprobsProcessor

        processor = LogprobsProcessor(
            tokenizer=mock_tokenizer,
            logprobs=[],
            prompt_logprobs=None,
            cumulative_logprob=0.0,
            num_logprobs=1,
            num_prompt_logprobs=None,
        )
        return processor

    @pytest.fixture
    def processor_with_previous_logprobs(self, mock_tokenizer):
        """Create a LogprobsProcessor with previous logprobs."""
        from vllm.v1.engine.logprobs import LogprobsProcessor

        processor = LogprobsProcessor(
            tokenizer=mock_tokenizer,
            logprobs=[{123: None}],  # Previous token ID is 123
            prompt_logprobs=None,
            cumulative_logprob=0.0,
            num_logprobs=1,
            num_prompt_logprobs=None,
        )
        return processor

    def test_correction_with_previous_token_in_list(
        self, processor_with_empty_logprobs
    ):
        """Test correction using previous token in the same list.

        Scenario: Token at idx=1 ends with "�", but when decoded with
        the previous token (idx=0), it forms a valid UTF-8 sequence.
        Example: token[0]="�", token[1]="�" -> together form "polarized"
        """
        processor = processor_with_empty_logprobs
        tokens = [100, 101, 102]  # token IDs

        # Mock tokenizer behavior:
        # - decode([102]) returns "�" (ends with replacement char)
        # - decode([101, 102]) returns "valid" (no replacement char)
        processor.tokenizer.decode.side_effect = lambda ids: (
            "valid" if ids == [101, 102] else "�"
        )

        result = processor._correct_decoded_token(2, tokens)
        assert result == "valid"
        processor.tokenizer.decode.assert_called_with([101, 102])

    def test_correction_with_previous_logprob_token(
        self, processor_with_previous_logprobs
    ):
        """Test correction using previous logprob token.

        Scenario: Cannot correct with previous token in list (idx=0),
        but can correct with previous logprob token.
        """
        processor = processor_with_previous_logprobs
        tokens = [100]  # single token

        # Mock tokenizer behavior:
        # - decode([100]) returns "�" (ends with replacement char)
        # - decode([123, 100]) returns " "polarized" (no replacement char)
        # Token 123 is from previous logprobs
        def mock_decode(ids):
            if ids == [123, 100]:
                return ' "polarized"'
            return "�"

        processor.tokenizer.decode.side_effect = mock_decode

        result = processor._correct_decoded_token(0, tokens)
        assert result == ' "polarized"'

    def test_correction_at_idx_zero_no_previous_logprobs(
        self, processor_with_empty_logprobs
    ):
        """Test correction at idx=0 with no previous logprobs.

        Scenario: First token in list, no previous logprobs available.
        Should return empty string as fallback.
        """
        processor = processor_with_empty_logprobs
        tokens = [100]

        # Mock tokenizer always returns "�"
        processor.tokenizer.decode.return_value = "�"

        result = processor._correct_decoded_token(0, tokens)
        assert result == ""

    def test_correction_at_idx_zero_with_previous_logprobs(
        self, processor_with_previous_logprobs
    ):
        """Test correction at idx=0 with previous logprobs available.

        Scenario: First token in list, but previous logprobs exist.
        Should try correction with previous logprob token.
        """
        processor = processor_with_previous_logprobs
        tokens = [200]

        # Mock tokenizer behavior
        def mock_decode(ids):
            if ids == [123, 200]:
                return "corrected"
            return "�"

        processor.tokenizer.decode.side_effect = mock_decode

        result = processor._correct_decoded_token(0, tokens)
        assert result == "corrected"

    def test_no_correction_needed_returns_fallback(
        self, processor_with_previous_logprobs
    ):
        """Test fallback to empty string when no correction works.

        Scenario: All correction attempts still end with "�".
        Should return empty string as final fallback.
        """
        processor = processor_with_previous_logprobs
        tokens = [100, 101, 102]

        # Mock tokenizer always returns text ending with "�"
        processor.tokenizer.decode.return_value = "still�"

        result = processor._correct_decoded_token(2, tokens)
        assert result == ""

    def test_middle_token_correction(self, processor_with_previous_logprobs):
        """Test correction for a token in the middle of the list.

        Scenario: Token at idx=5 in a longer list needs correction.
        """
        processor = processor_with_previous_logprobs
        tokens = [10, 20, 30, 40, 50, 60, 70, 80]

        # Mock tokenizer behavior for middle token
        def mock_decode(ids):
            if ids == [50, 60]:
                return "olar"
            return "�"

        processor.tokenizer.decode.side_effect = mock_decode

        result = processor._correct_decoded_token(5, tokens)
        assert result == "olar"

    def test_multiple_consecutive_replacement_chars(
        self, processor_with_previous_logprobs
    ):
        """Test handling of multiple consecutive replacement characters.

        Scenario: Sequence like ["�", "�", "p"] where first two should
        become empty strings.
        """
        processor = processor_with_previous_logprobs

        # Test first replacement char
        tokens = [100, 101, 102]
        processor.tokenizer.decode.return_value = "still�"
        result1 = processor._correct_decoded_token(0, tokens)
        assert result1 == ""

        # Test second replacement char
        result2 = processor._correct_decoded_token(1, tokens)
        assert result2 == ""

    def test_correction_with_multibyte_utf8(self, processor_with_previous_logprobs):
        """Test correction involving multi-byte UTF-8 characters.

        Scenario: Byte-fallback tokenization splits multi-byte UTF-8
        characters (e.g., curly quotes, Chinese characters, emojis).
        Example from user: "�", "�" -> "", "\""
        """
        processor = processor_with_previous_logprobs
        tokens = [200, 201]

        # Mock tokenizer behavior for multi-byte UTF-8 correction
        def mock_decode(ids):
            # When decoding first token (idx=0) with previous logprob token
            if ids == [123, 200]:
                return ' "'  # Space + left curly quote
            # When decoding second token (idx=1) with previous token in list
            elif ids == [200, 201]:
                return '"'  # Right curly quote
            # When decoding second token (idx=1) with previous logprob + prev token
            elif ids == [123, 200, 201]:
                return ' ""'  # Full sequence
            return "�"

        processor.tokenizer.decode.side_effect = mock_decode

        # First token correction (idx=0)
        # Will call decode([123, 200]) since idx=0 uses previous logprob token
        result1 = processor._correct_decoded_token(0, tokens)
        assert result1 == ' "'

        # Second token correction (idx=1)
        # Will call decode([200, 201]) since idx>0 uses previous token in list
        result2 = processor._correct_decoded_token(1, tokens)
        assert result2 == '"'

    def test_real_world_opt125m_scenario(self, mock_tokenizer):
        """Test the real-world scenario from user's example.

        User's example with facebook/opt-125m:
        Before: [" the", " term", " �", "�", "p", "olar", "ized", "�", "�", ...]
        After: [" the", " term", "", " "", "p", "olar", "ized", "", "\"", ...]
        """
        from vllm.v1.engine.logprobs import LogprobsProcessor

        # Simulate the sequence of tokens
        processor = LogprobsProcessor(
            tokenizer=mock_tokenizer,
            logprobs=[],
            prompt_logprobs=None,
            cumulative_logprob=0.0,
            num_logprobs=1,
            num_prompt_logprobs=None,
        )

        # Token IDs representing the problematic sequence
        tokens = [1, 2, 3, 4, 5, 6, 7, 8, 9]  # placeholder IDs

        # Mock decode behavior simulating the real scenario
        def mock_decode(ids):
            # Simulate cases where individual tokens decode to "�"
            # but combinations decode correctly
            if len(ids) == 1:
787
                if ids[0] in (3, 4, 8, 9):
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
                    return "�"
            elif len(ids) == 2:
                if ids == [2, 3]:
                    return " term�"  # Still ends with �, need more context
                elif ids == [3, 4]:
                    return ' "'  # Corrected to space + left curly quote
                elif ids == [7, 8]:
                    return "ized�"  # Still ends with �
                elif ids == [8, 9]:
                    return '"'  # Corrected to right curly quote
            elif len(ids) == 3:
                if ids == [1, 2, 3]:
                    return " the term�"  # Still ends with issue
                elif ids == [2, 3, 4]:
                    return ' term "'  # With all context
            return "normal_text"

        mock_tokenizer.decode.side_effect = mock_decode

        # Test token at index 2 (should fail to correct, return "")
        # Token 3 individually is "�"
        # decode([2, 3]) = " term�" (still ends with �)
        # No previous logprobs, so fallback to ""
        result = processor._correct_decoded_token(2, tokens)
        assert result == ""

        # Test token at index 3 (should correct to " "")
        # Token 4 individually is "�"
        # decode([3, 4]) = " "" (corrected!)
        processor.logprobs = [{2: None}]  # Add previous logprob
        result = processor._correct_decoded_token(3, tokens)
        assert result == ' "'


def test_verify_tokens_integration():
    """Integration test for _verify_tokens with real model.

    This test validates that _verify_tokens correctly identifies and
    corrects tokens ending with the replacement character "�".
    Uses facebook/opt-125m which is known to produce these issues.
    """
829
    with VllmRunner(
830
831
832
833
834
        "facebook/opt-125m",
        max_logprobs=0,
        enable_prefix_caching=False,
        gpu_memory_utilization=0.15,
        max_model_len=256,
835
836
837
838
839
840
841
842
843
844
    ) as runner:
        # Use a prompt that triggers multi-byte UTF-8 issues
        # Based on user's example: "In this example,"
        test_prompts = ["In this example,"]

        sampling_params = SamplingParams(
            max_tokens=16,
            temperature=0,
            logprobs=0,
        )
845

846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
        results = runner.llm.generate(test_prompts, sampling_params=sampling_params)

        # Verify that decoded tokens don't contain replacement characters
        for result in results:
            assert result.outputs[0].logprobs is not None
            for logprob_dict in result.outputs[0].logprobs:
                for token_id, logprob_info in logprob_dict.items():
                    decoded_token = logprob_info.decoded_token
                    # Decoded tokens should not end with replacement character
                    # They should either be corrected or empty string
                    assert not decoded_token.endswith("�"), (
                        f"Token {token_id} decoded to '{decoded_token}' which "
                        f"ends with replacement character"
                    )
                    # Decoded tokens should not contain lone replacement characters
                    assert decoded_token != "�", (
                        f"Token {token_id} is a lone replacement character"
                    )
864
865
866
867
868
869
870
871


def test_utf8_edge_cases_with_real_model():
    """Test various UTF-8 edge cases with a real model.

    Tests prompts that are likely to trigger byte-fallback tokenization
    and multi-byte UTF-8 splitting.
    """
872
    with VllmRunner(
873
874
875
876
877
        "facebook/opt-125m",
        max_logprobs=1,
        enable_prefix_caching=False,
        gpu_memory_utilization=0.15,
        max_model_len=256,
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
    ) as runner:
        # Prompts with various multi-byte UTF-8 characters
        test_prompts = [
            'Smart quotes: "Hello"',  # Curly quotes
            "Em dash — test",  # Em dash
            "Ellipsis… continues",  # Ellipsis
            "Chinese: 你好",  # Chinese characters
            "Emoji: 😀 🎉",  # Emojis
            'Mixed: "quoted" — with symbols',  # Mixed
        ]

        sampling_params = SamplingParams(
            max_tokens=10,
            temperature=0,
            logprobs=1,
        )
894

895
        results = runner.llm.generate(test_prompts, sampling_params=sampling_params)
896

897
898
899
        for i, result in enumerate(results):
            prompt = test_prompts[i]
            assert result.outputs[0].logprobs is not None
900

901
902
903
904
905
906
907
908
909
            # Check that no decoded tokens end with replacement character
            for logprob_dict in result.outputs[0].logprobs:
                for token_id, logprob_info in logprob_dict.items():
                    decoded_token = logprob_info.decoded_token
                    assert not decoded_token.endswith("�"), (
                        f"Prompt: '{prompt}'\n"
                        f"Token {token_id} decoded to '{decoded_token}' which "
                        f"ends with replacement character"
                    )
910
911
912
913
914
915
916
917
918


def test_correct_decoded_token_preserves_valid_tokens():
    """Test that valid tokens (not ending with �) are not modified.

    The _correct_decoded_token method should only be called for tokens
    ending with "�", but this test verifies the broader _verify_tokens
    logic doesn't affect valid tokens.
    """
919
    with VllmRunner(
920
921
922
923
924
        "facebook/opt-125m",
        max_logprobs=2,
        enable_prefix_caching=False,
        gpu_memory_utilization=0.15,
        max_model_len=256,
925
926
927
928
929
930
931
932
933
    ) as runner:
        # Simple prompt with standard ASCII characters
        test_prompts = ["Hello world, this is a test."]

        sampling_params = SamplingParams(
            max_tokens=10,
            temperature=0,
            logprobs=2,
        )
934

935
        results = runner.llm.generate(test_prompts, sampling_params=sampling_params)
936

937
938
        for result in results:
            assert result.outputs[0].logprobs is not None
939

940
941
942
943
944
945
946
947
            # All decoded tokens should be valid strings
            for logprob_dict in result.outputs[0].logprobs:
                for token_id, logprob_info in logprob_dict.items():
                    decoded_token = logprob_info.decoded_token
                    # Valid tokens should be non-empty strings (or empty if corrected)
                    assert isinstance(decoded_token, str)
                    # Should not contain replacement character
                    assert "�" not in decoded_token
948
949


950
951
952
953
954
955
956
@pytest.mark.parametrize("logprobs_mode", get_args(LogprobsMode))
@pytest.mark.parametrize(
    "model_setup",
    [
        pytest.param(
            (
                "eagle",
957
                "meta-llama/Llama-3.2-1B-Instruct",
958
959
960
961
962
963
                {
                    "method": "eagle",
                    "model": "nm-testing/Llama3_2_1B_speculator.eagle3",
                    "num_speculative_tokens": 3,
                },
                0,
964
965
            ),
            marks=large_gpu_mark(min_gb=32),
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
            id="eagle0",
        ),
        pytest.param(
            (
                "eagle",
                "meta-llama/Llama-3.2-1B-Instruct",
                {
                    "method": "eagle",
                    "model": "nm-testing/Llama3_2_1B_speculator.eagle3",
                    "num_speculative_tokens": 3,
                },
                3,
            ),
            marks=large_gpu_mark(min_gb=32),
            id="eagle3",
        ),
        pytest.param(
            (
                "ngram",
                "meta-llama/Llama-3.2-1B-Instruct",
                {
                    "method": "ngram",
                    "prompt_lookup_max": 5,
                    "prompt_lookup_min": 3,
                    "num_speculative_tokens": 3,
                },
                3,
            ),
            marks=large_gpu_mark(min_gb=32),
            id="ngram",
996
997
998
999
1000
        ),
    ],
)
def test_spec_decode_logprobs(
    logprobs_mode: LogprobsMode,
1001
    model_setup: tuple[str, str, dict, int],
1002
    monkeypatch,
1003
1004
1005
):
    """Spec decode logprobs should match those of the base model.

1006
1007
1008
1009
1010
    Runs the base model and spec decode model sequentially, ensuring
    only one LLM instance is alive at a time to avoid GPU memory
    contention. Both use identical chunked prefill settings and eager
    mode to control for infrastructure differences.

1011
1012
    Args:
        logprobs_mode: logprobs mode.
1013
1014
        model_setup: Tuple of (method, base model name,
            speculative_config dict, top_logprobs).
1015
        monkeypatch: pytest fixture for setting env vars.
1016
1017
1018
    """
    from vllm import LLM

1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
    # The ROCm skinny GEMM kernels (gemm_kernels.cu) are
    # non-deterministic across LLM instantiations due to persistent
    # workgroup scheduling and wave-level shuffle reductions, which
    # causes logprob differences that get misattributed to spec decode.
    # Disable them so this test isolates spec decode correctness only.
    # TODO(akaratza): Remove this workaround once the follow-up to
    # https://github.com/vllm-project/vllm/pull/33493#issuecomment-3906083975
    # lands with a determinism fix for wvSplitK kernels.
    monkeypatch.setenv("VLLM_ROCM_USE_SKINNY_GEMM", "0")

1029
1030
    method, model_name, spec_config, top_logprobs = model_setup

1031
    prompt = "Hello world " * 50
1032
    sampling_params = SamplingParams(
1033
        temperature=0, logprobs=top_logprobs, max_tokens=10, ignore_eos=False
1034
    )
1035
1036
1037
1038
1039
1040
1041
    penalty_sampling_params = SamplingParams(
        temperature=0,
        logprobs=top_logprobs,
        max_tokens=10,
        ignore_eos=False,
        presence_penalty=-1.0,
    )
1042

1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
    max_model_len = 256

    # Run base LLM.
    ref_llm = LLM(
        model=model_name,
        max_logprobs=5,
        max_model_len=max_model_len,
        seed=42,
        logprobs_mode=logprobs_mode,
        gpu_memory_utilization=0.4,
1053
        enable_prefix_caching=False,
1054
        **ROCM_DETERMINISM_KWARGS,
1055
1056
1057
    )
    ref_results = ref_llm.generate(
        [prompt, prompt], [sampling_params, penalty_sampling_params]
1058
1059
1060
    )
    # Collect logprobs outputs from reference LLM.
    ref_logprobs = []
1061
1062
1063
1064
    for results in ref_results:
        for output in results.outputs:
            for logprobs in output.logprobs:
                ref_logprobs.extend(logprobs.values())
1065
    del ref_llm
1066
    torch.accelerator.empty_cache()
1067
1068
1069
    cleanup_dist_env_and_memory()

    # Run spec decode LLM.
1070
1071
    # Add max_model_len to spec_config if not present
    spec_config_with_len = {**spec_config, "max_model_len": max_model_len}
1072
1073
    spec_llm = LLM(
        model_name,
1074
        speculative_config=spec_config_with_len,
1075
1076
1077
1078
1079
        max_logprobs=5,
        max_model_len=max_model_len,
        seed=42,
        logprobs_mode=logprobs_mode,
        gpu_memory_utilization=0.4,
1080
1081
1082
        # Force prefill chunking
        enable_chunked_prefill=True,
        max_num_batched_tokens=32,
1083
        enable_prefix_caching=False,
1084
        **ROCM_DETERMINISM_KWARGS,
1085
1086
1087
    )
    spec_results = spec_llm.generate(
        [prompt, prompt], [sampling_params, penalty_sampling_params]
1088
1089
1090
    )
    # Collect logprobs outputs from spec decode LLM.
    spec_logprobs = []
1091
1092
1093
1094
    for results in spec_results:
        for output in results.outputs:
            for logprobs in output.logprobs:
                spec_logprobs.extend(logprobs.values())
1095
    del spec_llm
1096
    torch.accelerator.empty_cache()
1097
1098
1099
1100
1101
    cleanup_dist_env_and_memory()

    # Per-token logprobs are expected to be the same.
    assert len(ref_logprobs) == len(spec_logprobs)
    for ref_logprob, spec_logprob in zip(ref_logprobs, spec_logprobs):
1102
1103
        assert math.isclose(
            ref_logprob.logprob, spec_logprob.logprob, rel_tol=5e-2, abs_tol=1e-1
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
        ), (
            f"Logprob mismatch: ref={ref_logprob.logprob} "
            f"spec={spec_logprob.logprob} "
            f"diff={abs(ref_logprob.logprob - spec_logprob.logprob)} "
            f"(token={ref_logprob.decoded_token!r})"
        )
        assert ref_logprob.rank == spec_logprob.rank, (
            f"Rank mismatch: ref={ref_logprob.rank} "
            f"spec={spec_logprob.rank} "
            f"(token={ref_logprob.decoded_token!r})"
1114
        )
1115
        assert ref_logprob.decoded_token == spec_logprob.decoded_token
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191


def test_prompt_logprobs_with_chunking_and_preemption():
    """Test that prompt logprobs are correctly returned when using
    both chunked prefill and preemption.

    This test ensures that the num_prompt_logprobs tracking persists
    across preemptions and prefill chunks.
    """

    # Create prompts that will trigger chunking and preemption
    prompts = [
        "The following numbers of the sequence "
        + ", ".join(str(i) for i in range(10))
        + " are:",
        "In one word, the capital of France is ",
    ] + [f"Tell me about the number {i}: " for i in range(32)]

    sampling_params = SamplingParams(
        temperature=0.0,
        max_tokens=40,
        min_tokens=20,
        prompt_logprobs=2,  # Request prompt logprobs
    )

    with VllmRunner(
        "Qwen/Qwen3-0.6B",
        max_model_len=512,
        enable_chunked_prefill=True,
        max_num_batched_tokens=48,  # Force prefill chunking
        num_gpu_blocks_override=32,  # Force preemptions
        disable_log_stats=False,
        gpu_memory_utilization=0.25,
    ) as vllm_model:
        metrics_before = vllm_model.llm.get_metrics()

        # Generate with prompt logprobs using generate_w_logprobs which
        # returns (output_ids, output_str, output_logprobs, prompt_logprobs)
        outputs = vllm_model.generate_w_logprobs(
            prompts, sampling_params=sampling_params, include_prompt_token_ids=True
        )

        # Verify that all outputs have prompt logprobs
        for i, output in enumerate(outputs):
            _, _, _, prompt_token_ids, prompt_logprobs = output
            assert prompt_logprobs is not None and len(prompt_logprobs) > 0, (
                f"Output {i} missing prompt logprobs"
            )
            assert len(prompt_logprobs) == len(prompt_token_ids), (
                "Unexpected number of prompt logprob positions"
            )

            # Each position should have the requested number of logprobs
            for pos, logprobs_dict in enumerate(prompt_logprobs):
                if logprobs_dict is not None:  # First token may be None
                    assert (
                        sampling_params.prompt_logprobs
                        <= len(logprobs_dict)
                        <= sampling_params.prompt_logprobs + 1
                    ), (
                        f"Output {i} position {pos} has {len(logprobs_dict)} "
                        f"logprobs, expected {sampling_params.prompt_logprobs}"
                    )

        # Check that we actually had preemptions
        metrics_after = vllm_model.llm.get_metrics()
        preemptions_before = next(
            (m.value for m in metrics_before if m.name == "vllm:num_preemptions"), 0
        )
        preemptions_after = next(
            (m.value for m in metrics_after if m.name == "vllm:num_preemptions"), 0
        )
        preemptions = preemptions_after - preemptions_before
        assert preemptions > 0, "Test did not trigger any preemptions"

        print(f"Test passed with {preemptions} preemptions")