#
# Copyright (c) 2025 Huawei Technologies Co., Ltd. All Rights Reserved.
# Copyright 2023 The vLLM team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This file is a part of the vllm-ascend project.
# Adapted from vllm/tests/basic_correctness/test_basic_correctness.py
#
"""Compare the short outputs of HF and vLLM when using greedy sampling.

Run `pytest tests/e2e/multicard/long_sequence/test_prefix_caching_cp.py`
"""

from typing import Any, Dict

import pytest

from tests.e2e.conftest import _LONG_PROMPTS, VllmRunner

MODELS = [
    "vllm-ascend/Qwen3-30B-A3B-W8A8", "vllm-ascend/DeepSeek-V2-Lite-W8A8"
]

SETTINGS: Dict[str, Dict[str, Any]] = {
    "vllm-ascend/Qwen3-30B-A3B-W8A8": {
        "TP": 2,
        "PCP": 2,
        "DCP": 1,
        "quantization": "ascend",
    },
    "vllm-ascend/DeepSeek-V2-Lite-W8A8": {
        "TP": 2,
        "PCP": 2,
        "DCP": 2,
        "quantization": "ascend",
    }
}

# A prompt containing a large markdown table. The table is randomly generated by GPT-4.
with open(_LONG_PROMPTS[0], 'r', encoding='utf-8') as file:
    LONG_PROMPT = file.read()

INPUT_PROMPTS = [
    LONG_PROMPT +
    "Question: what is the age of John Doe? Your answer: The age of John Doe is ",
    LONG_PROMPT +
    "Question: what is the age of Umar Black? Your answer: The age of Umar Black is "
]

VLLM_OUTPUT = [INPUT_PROMPTS[0] + "29", INPUT_PROMPTS[1] + "39"]


@pytest.mark.parametrize("model", MODELS)
@pytest.mark.parametrize("max_tokens", [2])
def test_models_prefix_cache_with_cp_basic(
        model: str, max_tokens: int, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("HCCL_BUFFSIZE", "768")
    with VllmRunner(
            model,
            block_size=128,
            enforce_eager=True,
            max_model_len=4096,
            enable_prefix_caching=True,
            enable_expert_parallel=True,
            max_num_batched_tokens=4096,
            tensor_parallel_size=SETTINGS[model]['TP'],
            quantization=SETTINGS[model]["quantization"],
            prefill_context_parallel_size=SETTINGS[model]['PCP'],
            decode_context_parallel_size=SETTINGS[model]['DCP']) as vllm_model:
        prefix_cache_outputs = vllm_model.generate_greedy(
            INPUT_PROMPTS, max_tokens)

    for i in range(len(prefix_cache_outputs)):
        assert prefix_cache_outputs[i][1] == VLLM_OUTPUT[i]


@pytest.mark.parametrize("model", MODELS)
@pytest.mark.parametrize("max_tokens", [2])
def test_models_prefix_cache_with_cp_piecewise(
        model: str, max_tokens: int, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("HCCL_BUFFSIZE", "768")
    with VllmRunner(
            model,
            block_size=128,
            max_model_len=4096,
            enforce_eager=False,
            enable_prefix_caching=True,
            enable_expert_parallel=True,
            max_num_batched_tokens=4096,
            tensor_parallel_size=SETTINGS[model]['TP'],
            quantization=SETTINGS[model]["quantization"],
            prefill_context_parallel_size=SETTINGS[model]['PCP'],
            decode_context_parallel_size=SETTINGS[model]['DCP']) as vllm_model:
        prefix_cache_outputs = vllm_model.generate_greedy(
            INPUT_PROMPTS, max_tokens)

    for i in range(len(prefix_cache_outputs)):
        assert prefix_cache_outputs[i][1] == VLLM_OUTPUT[i]


@pytest.mark.parametrize("model", MODELS)
@pytest.mark.parametrize("max_tokens", [2])
def test_models_prefix_cache_with_cp_full_graph(
        model: str, max_tokens: int, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("HCCL_BUFFSIZE", "768")
    with VllmRunner(model,
                    block_size=128,
                    max_model_len=4096,
                    enforce_eager=False,
                    enable_prefix_caching=True,
                    enable_expert_parallel=True,
                    max_num_batched_tokens=4096,
                    tensor_parallel_size=SETTINGS[model]['TP'],
                    quantization=SETTINGS[model]["quantization"],
                    prefill_context_parallel_size=SETTINGS[model]['PCP'],
                    decode_context_parallel_size=SETTINGS[model]['DCP'],
                    compilation_config={
                        "cudagraph_capture_sizes": [4, 8, 24, 48, 60],
                        "cudagraph_mode": "FULL_DECODE_ONLY"
                    }) as vllm_model:
        prefix_cache_outputs = vllm_model.generate_greedy(
            INPUT_PROMPTS, max_tokens)

    for i in range(len(prefix_cache_outputs)):
        assert prefix_cache_outputs[i][1] == VLLM_OUTPUT[i]
