main
py 84 lines 3.04 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3 import os
4 import tempfile
5
6 from vllm import LLM, SamplingParams
7 from vllm.config.kv_transfer import KVTransferConfig
8 from vllm.distributed.kv_transfer.kv_connector.v1 import (
9 example_hidden_states_connector,
10 )
11
12 # NOTE: If changing the interface of the ExampleHiddenStatesConnector, please also
13 # update the benchmark in benchmarks/benchmark_hidden_state_extraction.py
14 # and the docs in docs/features/speculative_decoding/extract_hidden_states.md
15
16 # Example: Using the custom "extract_hidden_states" speculator method and
17 # ExampleHiddenStatesConnector to extract and save hidden states from vllm
18
19 with tempfile.TemporaryDirectory() as tmpdirname:
20 llm = LLM(
21 model="Qwen/Qwen3-8B", # Your target model
22 speculative_config={
23 "method": "extract_hidden_states",
24 "num_speculative_tokens": 1,
25 "draft_model_config": {
26 "hf_config": {
27 "eagle_aux_hidden_state_layer_ids": [ # Target model layer indices
28 1,
29 2,
30 3,
31 4,
32 ],
33 },
34 },
35 },
36 kv_transfer_config=KVTransferConfig(
37 kv_connector="ExampleHiddenStatesConnector",
38 kv_role="kv_producer",
39 kv_connector_extra_config={
40 "shared_storage_path": tmpdirname,
41 "allow_custom_save_path": True,
42 },
43 ),
44 )
45
46 prompts = ["Generate a sentence with hidden states", "Write a python function"]
47
48 # One request uses defaults, the other uses a custom save path and
49 # includes output token hidden states via per-request kv_transfer_params.
50 sampling_params_list = [
51 SamplingParams(max_tokens=1),
52 SamplingParams(
53 max_tokens=10,
54 extra_args={
55 "kv_transfer_params": {
56 "hidden_states_path": os.path.join(
57 tmpdirname, "custom_output.safetensors"
58 ),
59 "include_output_tokens": True,
60 }
61 },
62 ),
63 ]
64 outputs = llm.generate(prompts, sampling_params_list)
65
66 for output in outputs:
67 print("\nPrompt:", output.prompt)
68 print("Prompt token ids:", output.prompt_token_ids)
69
70 hidden_states_path = output.kv_transfer_params.get("hidden_states_path")
71 assert hidden_states_path is not None
72 print("Hidden states path:", hidden_states_path)
73
74 obj = example_hidden_states_connector.load_hidden_states(hidden_states_path)
75 token_ids = obj["token_ids"]
76 hidden_states = obj["hidden_states"]
77
78 print("Extracted token ids:", token_ids)
79 print(
80 "Extracted hidden states shape:", hidden_states.shape
81 ) # [num_tokens, num_extracted_layers, hidden_size]
82 print("Extracted hidden states:", hidden_states)
83
84 example_hidden_states_connector.cleanup_hidden_states(hidden_states_path)