main
md 126 lines 4.94 KB
Rendered Raw
1 # Hidden State Extraction
2
3 The Hidden State Extraction feature allows vLLM to save intermediate layer activations from a target model during inference. This is useful for training [EAGLE](eagle.md)-style draft models, knowledge distillation, or offline analysis of model internals.
4
5 !!! note
6 It is possible to save the last-layer's output hidden states by passing `num_hidden_layers` as a layer id. Note that these are _not_ normalized using the output norm.
7
8 ## Offline Example
9
10 ```python
11 import tempfile
12
13 from vllm import LLM, SamplingParams
14 from vllm.config.kv_transfer import KVTransferConfig
15 from vllm.distributed.kv_transfer.kv_connector.v1 import (
16 example_hidden_states_connector,
17 )
18
19 with tempfile.TemporaryDirectory() as tmpdir:
20 llm = LLM(
21 model="Qwen/Qwen3-8B",
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": [1, 2, 3, 4],
28 },
29 },
30 },
31 kv_transfer_config=KVTransferConfig(
32 kv_connector="ExampleHiddenStatesConnector",
33 kv_role="kv_producer",
34 kv_connector_extra_config={
35 "shared_storage_path": tmpdir,
36 },
37 ),
38 )
39
40 outputs = llm.generate(
41 ["The future of AI is"],
42 SamplingParams(max_tokens=1),
43 )
44
45 for output in outputs:
46 path = output.kv_transfer_params["hidden_states_path"]
47 obj = example_hidden_states_connector.load_hidden_states(path)
48 print(f"token_ids: {obj['token_ids'].shape}")
49 print(f"hidden_states: {obj['hidden_states'].shape}")
50 ```
51
52 A complete example is available at [`examples/features/speculative_decoding/extract_hidden_states_offline.py`](../../../examples/features/speculative_decoding/extract_hidden_states_offline.py).
53
54 ## Online Example
55
56 For improved performance, it is recommended to use a RAM-mounted file system such as `/dev/shm/` for online usage in which the client cleans up the files soon after they are generated.
57
58 ```bash
59 vllm serve Qwen/Qwen3-8B \
60 --speculative_config '{"method": "extract_hidden_states", "num_speculative_tokens": 1, "draft_model_config": {"hf_config": {"eagle_aux_hidden_state_layer_ids": [1, 2, 3, 4]}}}' \
61 --kv_transfer_config '{"kv_connector": "ExampleHiddenStatesConnector", "kv_role": "kv_producer", "kv_connector_extra_config": {"shared_storage_path": "/dev/shm/hidden_states"}}'
62 ```
63
64 ## Per-Request Options
65
66 Both offline and online modes support per-request options via `kv_transfer_params`:
67
68 | Parameter | Default | Description |
69 | --- | --- | --- |
70 | `hidden_states_path` | Auto-generated | Custom file path for saving hidden states. If not set, files are saved to `<shared_storage_path>/<request_id>.safetensors`. Requires `allow_custom_save_path` to be enabled in the server config. |
71 | `include_output_tokens` | `False` | When `True`, save hidden states for both prompt and generated output tokens. When `False`, only prompt token hidden states are saved. |
72
73 ### Offline usage
74
75 Pass per-request options via `extra_args` on `SamplingParams`:
76
77 ```python
78 SamplingParams(
79 max_tokens=32,
80 extra_args={
81 "kv_transfer_params": {
82 "hidden_states_path": "/tmp/my_output.safetensors",
83 "include_output_tokens": True,
84 }
85 },
86 )
87 ```
88
89 ### Online usage
90
91 Pass `kv_transfer_params` as a top-level field in the API request:
92
93 ```json
94 {
95 "model": "Qwen/Qwen3-8B",
96 "messages": [{"role": "user", "content": "Hello"}],
97 "max_tokens": 32,
98 "kv_transfer_params": {
99 "hidden_states_path": "/tmp/my_output.safetensors",
100 "include_output_tokens": true
101 }
102 }
103 ```
104
105 ## Configuration
106
107 The `kv_connector_extra_config` dict accepts these server-level options:
108
109 | Parameter | Default | Description |
110 | --- | --- | --- |
111 | `shared_storage_path` | `/tmp` | Directory where hidden state files are saved (used when `hidden_states_path` is not set per-request) |
112 | `allow_custom_save_path` | `False` | Allow API clients to specify custom file paths via `hidden_states_path`. When disabled, client-provided paths are ignored with a warning. Enable only with trusted clients — custom paths can write to arbitrary locations on the server. |
113 | `num_writer_threads` | `8` | Thread pool size for async disk writes |
114 | `use_synchronization_lock` | `True` | Use file locks so concurrent readers block until writes complete. Can be disabled for batch generation where synchronization is not needed. |
115
116 ## Output Format
117
118 Each request produces a `.safetensors` file containing:
119
120 - **`hidden_states`** — shape `[num_tokens, num_extracted_layers, hidden_size]`
121 - **`token_ids`** — shape `[num_tokens]`
122
123 The file path is returned in `output.kv_transfer_params["hidden_states_path"]`. Use `load_hidden_states()` from the connector module to read the file with proper synchronization.
124
125 !!! note
126 Chunked prefill is not compatible with this feature and must be disabled.