zymatrix commited on
Commit
3ef33ff
·
verified ·
1 Parent(s): 49216ff

Enable centered-power vLLM prompt scoring and future hook at startup

Browse files
snapshots/centered_startup_fix_20261012_172656/install_snapshot.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Install one immutable, hash-verified centered-power snapshot on cuhksz."""
2
+
3
+ import ast
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import subprocess
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ import yaml
12
+ from huggingface_hub import snapshot_download
13
+
14
+
15
+ def digest(data):
16
+ return hashlib.sha256(data).hexdigest()
17
+
18
+
19
+ revision, prefix, manifest_hash = sys.argv[1:]
20
+ staging = Path('/data/zhangyu/.sharpen-snapshots') / prefix.split('/')[-1]
21
+ snapshot_download('zymatrix/sharpen', repo_type='dataset', revision=revision,
22
+ allow_patterns=[prefix + '/*'], local_dir=staging)
23
+ source = staging / prefix
24
+ manifest_bytes = (source / 'manifest.json').read_bytes()
25
+ if digest(manifest_bytes) != manifest_hash:
26
+ raise RuntimeError('Downloaded manifest hash differs from the uploaded manifest.')
27
+ manifest = json.loads(manifest_bytes)
28
+ target = Path(manifest['target_root'])
29
+ if target != Path('/data/zhangyu/Sharpen-OPSD') or manifest['objective'] != 'centered_power_student':
30
+ raise ValueError('Unexpected installation target or objective.')
31
+
32
+ # Verify the complete source and existing target before replacing any implementation file.
33
+ installed_data = {}
34
+ for relative, expected in manifest['files'].items():
35
+ relative_path = Path(relative)
36
+ if relative_path.is_absolute() or '..' in relative_path.parts:
37
+ raise ValueError('Snapshot file paths must be repository-relative.')
38
+ data = (source / relative).read_bytes()
39
+ if digest(data) != expected:
40
+ raise RuntimeError('Source hash mismatch: ' + relative)
41
+ if digest((target / relative).read_bytes()) != manifest['expected_target_hashes'][relative]:
42
+ raise RuntimeError('Target changed since inspection: ' + relative)
43
+ if relative.endswith('.py'):
44
+ ast.parse(data, filename=relative)
45
+ elif relative.endswith('.sh'):
46
+ subprocess.run(['bash', '-n', str(source / relative)], check=True)
47
+ elif relative.endswith('.yaml'):
48
+ yaml.safe_load(data)
49
+ for key, change in manifest['path_rewrites'].get(relative, {}).items():
50
+ config = yaml.safe_load(data)
51
+ if config.get(key) != change['before']:
52
+ raise RuntimeError('Unexpected source path setting: ' + key)
53
+ if key in config:
54
+ before = f"{key}: {change['before']}".encode()
55
+ after = f"{key}: {change['after']}".encode()
56
+ if data.count(before) != 1:
57
+ raise RuntimeError('Path rewrite must match one YAML entry: ' + key)
58
+ data = data.replace(before, after)
59
+ else:
60
+ data += f"\n{key}: {change['after']}\n".encode()
61
+ if relative.endswith('.yaml'):
62
+ yaml.safe_load(data)
63
+ installed_data[relative] = data
64
+ for relative, expected in manifest['existing_dependencies'].items():
65
+ if digest((target / relative).read_bytes()) != expected:
66
+ raise RuntimeError('Existing dependency hash mismatch: ' + relative)
67
+
68
+ for relative, data in installed_data.items():
69
+ destination = target / relative
70
+ temporary = destination.with_name(destination.name + '.centered-install-tmp')
71
+ temporary.write_bytes(data)
72
+ temporary.chmod(manifest['modes'][relative])
73
+ os.replace(temporary, destination)
74
+ if digest(destination.read_bytes()) != digest(data):
75
+ raise RuntimeError('Installed file hash mismatch: ' + relative)
76
+
77
+ report = {
78
+ 'revision': revision, 'snapshot_prefix': prefix, 'manifest_sha256': manifest_hash,
79
+ 'source': str(source), 'target': str(target), 'objective': manifest['objective'],
80
+ 'path_rewrites': manifest['path_rewrites'], 'source_hashes_verified': True,
81
+ 'existing_dependencies_verified': True, 'syntax_checks': 'passed',
82
+ 'installed_hashes': {relative: digest(data) for relative, data in installed_data.items()},
83
+ 'launch_config': manifest['launch'],
84
+ }
85
+ report_path = target / 'logs' / ('sync_' + prefix.split('/')[-1] + '.json')
86
+ report_path.write_text(json.dumps(report, indent=2) + '\n')
87
+ print(json.dumps({'status': 'installed', 'revision': revision, 'files': len(installed_data),
88
+ 'report': str(report_path)}))
snapshots/centered_startup_fix_20261012_172656/manifest.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "objective": "centered_power_student",
3
+ "created_at": "2026-10-12T17:26:56.038350+08:00",
4
+ "repo": "zymatrix/sharpen",
5
+ "snapshot_prefix": "snapshots/centered_startup_fix_20261012_172656",
6
+ "target_root": "/data/zhangyu/Sharpen-OPSD",
7
+ "parent_revision": "49216ffd54a4e50ddf87142368cf09255b7a0ff3",
8
+ "files": {
9
+ "third_party/verl/verl/workers/rollout/vllm_rollout/vllm_async_server.py": "15ce26456f50cc285cbd0416d5062d9b7ba38205a4397b72b737513eeb2ecc21",
10
+ "third_party/verl/tests/workers/rollout/test_sps_vllm_contract_on_cpu.py": "ff9e4cf904a66b8dab90ee3cb7e0640add4e903c93b666d57589225cc34c2f1c"
11
+ },
12
+ "modes": {
13
+ "third_party/verl/verl/workers/rollout/vllm_rollout/vllm_async_server.py": 420,
14
+ "third_party/verl/tests/workers/rollout/test_sps_vllm_contract_on_cpu.py": 420
15
+ },
16
+ "expected_target_hashes": {
17
+ "third_party/verl/verl/workers/rollout/vllm_rollout/vllm_async_server.py": "f3370bbaf8d2f749c8cf279ad9f69e118bd26e56289e8d6dc6ed5252012ae632",
18
+ "third_party/verl/tests/workers/rollout/test_sps_vllm_contract_on_cpu.py": "d0a737c2b43cff835a5eee9ba8b43ab50049783f2e7925d3349468dfd3fb5ca1"
19
+ },
20
+ "existing_dependencies": {
21
+ "third_party/verl/verl/workers/config/model.py": "64e9f280833292315cc2d14a73782d00a24604151f819a46363252edd60daa5e",
22
+ "third_party/verl/verl/trainer/config/model/hf_model.yaml": "8325ec2a11fcabfa1fb3f5999f3f59d813fd9f1222933fad0a845e51ef35f753",
23
+ "third_party/verl/verl/utils/dataset/rl_dataset.py": "95e7bdb8514c70d545468ab6a280f2bb172e62e4a0bac77eeb3379975a393a0a",
24
+ "src/opsd_format.py": "d0a3d9c40b8a1c5f69853c9bd84f3993f17e1f2f09e387fc7fa81b349907af6c",
25
+ "src/verl_reward.py": "e5a0867add7be89551d6d2390e6056727442a1e5f6e3db1202e9f0d1a0c8552a",
26
+ "third_party/verl/verl/utils/tracking.py": "cdac58d4ce9e68ca8a941aea634e4ae7581ce01b82fc37ecf59b4b09a1b1297a",
27
+ "src/data_utils.py": "dc715ff0ac64ceafb5da93d09bf86c0a9fa7435916370a9dd38544f9db3f409f",
28
+ "src/verl_main.py": "4293e63d924307695b81da17a83838686bfc4332331b998ddf7fe8dfda6816fd"
29
+ },
30
+ "path_rewrites": {},
31
+ "installer_sha256": "379d97eeb3e432d5461eba443491ed4b6e5ed76881aca7da6ac4faac0a094732",
32
+ "launch": {
33
+ "fresh_base": true,
34
+ "model_path": "/data/zhangyu/model/Qwen3-4B",
35
+ "devices": [
36
+ 4,
37
+ 5,
38
+ 6,
39
+ 7
40
+ ],
41
+ "training_batch_size": 32,
42
+ "total_training_steps": 450,
43
+ "save_freq": 25,
44
+ "test_freq": 10,
45
+ "val_before_train": true
46
+ },
47
+ "reason": "Server startup still matched obsolete objective ess_power_student, skipping base prompt-scoring and future-weight hooks; first auxiliary scoring caused CUDA illegal access."
48
+ }
snapshots/centered_startup_fix_20261012_172656/third_party/verl/tests/workers/rollout/test_sps_vllm_contract_on_cpu.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from verl.experimental.agent_loop.agent_loop import _validate_sps_sampling_params
4
+ from verl.experimental.agent_loop.single_turn_agent_loop import (
5
+ _ensure_sps_outputs,
6
+ _validate_future_output,
7
+ )
8
+ from verl.workers.rollout.replica import TokenOutput
9
+
10
+
11
+ def test_sps_n_sampling_requires_exact_count():
12
+ outputs = [TokenOutput(token_ids=[1], log_probs=[-0.1]) for _ in range(8)]
13
+ assert len(_ensure_sps_outputs(outputs, 8)) == 8
14
+ with pytest.raises(RuntimeError, match="expected 8"):
15
+ _ensure_sps_outputs(outputs[:7], 8)
16
+
17
+
18
+ def test_non_eos_future_must_fill_fixed_horizon():
19
+ with pytest.raises(RuntimeError, match="exactly 3"):
20
+ _validate_future_output(TokenOutput(token_ids=[1, 2], log_probs=[-0.1, -0.2]), 3, {99})
21
+
22
+
23
+ def test_eos_future_may_end_early_and_scores_eos():
24
+ tokens, log_probs = _validate_future_output(
25
+ TokenOutput(token_ids=[1, 99], log_probs=[-0.1, -0.2]), 3, {99}
26
+ )
27
+ assert tokens == [1, 99]
28
+ assert log_probs == [-0.1, -0.2]
29
+
30
+
31
+ def test_future_rejects_tokens_after_first_eos():
32
+ with pytest.raises(RuntimeError, match="tokens after EOS"):
33
+ _validate_future_output(
34
+ TokenOutput(token_ids=[99, 1, 99], log_probs=[-0.1, -0.2, -0.3]), 3, {99}
35
+ )
36
+
37
+
38
+ @pytest.mark.parametrize("parameter,value", [
39
+ ("top_p", 0.95), ("top_k", 20), ("min_p", 0.1), ("repetition_penalty", 1.1),
40
+ ("presence_penalty", 0.1), ("frequency_penalty", 0.1), ("min_tokens", 1), ("ignore_eos", True),
41
+ ])
42
+ def test_future_requires_full_support_and_real_eos(parameter, value):
43
+ _validate_sps_sampling_params({"temperature": 0.5}, future_exponent=2)
44
+ with pytest.raises(ValueError):
45
+ _validate_sps_sampling_params({"temperature": 0.5, parameter: value}, future_exponent=2)
46
+ with pytest.raises(ValueError, match="temperature"):
47
+ _validate_sps_sampling_params({"temperature": 0.5})
48
+
49
+
50
+ def _serving_method_for_cpu():
51
+ """Execute the real request method with a fake vLLM engine (no GPU package)."""
52
+ import ast
53
+ from pathlib import Path
54
+ from types import SimpleNamespace
55
+
56
+ path = Path(__file__).parents[3] / "verl/workers/rollout/vllm_rollout/vllm_async_server.py"
57
+ tree = ast.parse(path.read_text())
58
+ method = next(node for node in ast.walk(tree) if isinstance(node, ast.AsyncFunctionDef)
59
+ and node.name == "generate_n")
60
+ future = ast.ImportFrom(module="__future__", names=[ast.alias(name="annotations")], level=0)
61
+ module = ast.Module(body=[future, method], type_ignores=[])
62
+ namespace = {
63
+ "normalize_token_ids": list, "qwen2_5_vl_dedup_image_tokens": lambda tokens, _: tokens,
64
+ "TokenOutput": TokenOutput, "TokensPrompt": lambda **kwargs: kwargs,
65
+ "SamplingParams": lambda **kwargs: SimpleNamespace(
66
+ n=kwargs.pop("n", 1), prompt_logprobs=kwargs.pop("prompt_logprobs", None), **kwargs),
67
+ "RequestOutputKind": SimpleNamespace(FINAL_ONLY="final_only"),
68
+ "VLLM_LORA_INT_ID": 1, "VLLM_LORA_NAME": "student", "VLLM_LORA_PATH": "adapter",
69
+ "LoRARequest": lambda **kwargs: kwargs,
70
+ "extract_prompt_logprobs": lambda **kwargs: None,
71
+ }
72
+ exec(compile(ast.fix_missing_locations(module), str(path), "exec"), namespace)
73
+ return namespace["generate_n"]
74
+
75
+
76
+ @pytest.mark.parametrize("objective,targets,expected", [
77
+ ("centered_power_student", "all-linear", {"vocab_size": 10, "crpd_base_scoring": True}),
78
+ (None, "all-linear", {"vocab_size": 10}),
79
+ ("centered_power_student", "q_proj", None),
80
+ ])
81
+ def test_actual_server_startup_enables_centered_power_prompt_and_future_patch(objective, targets, expected):
82
+ import ast
83
+ import asyncio
84
+ import inspect
85
+ from pathlib import Path
86
+ from types import SimpleNamespace
87
+
88
+ from omegaconf import OmegaConf
89
+
90
+ # Run the real startup path through its first RPC; HTTP startup needs no CPU stub.
91
+ path = Path(__file__).parents[3] / "verl/workers/rollout/vllm_rollout/vllm_async_server.py"
92
+ method = next(node for node in ast.walk(ast.parse(path.read_text()))
93
+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "run_server")
94
+
95
+ class InitializationComplete(Exception):
96
+ pass
97
+
98
+ class Engine:
99
+ def __init__(self):
100
+ self.calls = []
101
+ self.cache_reset = False
102
+
103
+ async def reset_mm_cache(self):
104
+ self.cache_reset = True
105
+
106
+ async def collective_rpc(self, **kwargs):
107
+ self.calls.append(kwargs)
108
+ raise InitializationComplete
109
+
110
+ engine = Engine()
111
+ engine_args = SimpleNamespace(create_engine_config=lambda **kwargs: SimpleNamespace(
112
+ parallel_config=SimpleNamespace()))
113
+ namespace = {
114
+ "inspect": inspect,
115
+ "AsyncEngineArgs": SimpleNamespace(from_cli_args=lambda args: engine_args),
116
+ "AsyncLLM": SimpleNamespace(from_vllm_config=lambda **kwargs: engine),
117
+ "UsageContext": SimpleNamespace(OPENAI_API_SERVER="server"),
118
+ }
119
+ future = ast.ImportFrom(module="__future__", names=[ast.alias(name="annotations")], level=0)
120
+ module = ast.fix_missing_locations(ast.Module(body=[future, method], type_ignores=[]))
121
+ exec(compile(module, str(path), "exec"), namespace)
122
+ server = SimpleNamespace(
123
+ _dp_master_port=1234, config=OmegaConf.create({"custom": {"objective": objective}}),
124
+ model_config=SimpleNamespace(target_modules=targets, tokenizer=list(range(10))),
125
+ )
126
+ if expected is None:
127
+ with pytest.raises(ValueError, match="all-linear"):
128
+ asyncio.run(namespace["run_server"](server, SimpleNamespace()))
129
+ assert not engine.calls
130
+ else:
131
+ with pytest.raises(InitializationComplete):
132
+ asyncio.run(namespace["run_server"](server, SimpleNamespace()))
133
+ assert engine.calls == [{"method": "monkey_patch_model", "kwargs": expected}]
134
+ assert engine.cache_reset
135
+
136
+
137
+ def test_actual_serving_method_requires_loaded_student_adapter_and_allows_explicit_base():
138
+ import asyncio
139
+ from types import SimpleNamespace
140
+
141
+ from omegaconf import OmegaConf
142
+
143
+ class Engine:
144
+ loaded = False
145
+
146
+ def __init__(self):
147
+ self.requests = []
148
+
149
+ async def list_loras(self):
150
+ return [1] if self.loaded else []
151
+
152
+ async def generate(self, **kwargs):
153
+ self.requests.append(kwargs)
154
+ yield SimpleNamespace(outputs=[SimpleNamespace(
155
+ index=index, token_ids=[7], logprobs=[{7: SimpleNamespace(logprob=-0.2 - index * 0.1)}],
156
+ finish_reason="length", num_preempted=0,
157
+ ) for index in range(kwargs["sampling_params"].n)])
158
+
159
+ async def exercise():
160
+ engine = Engine()
161
+ server = SimpleNamespace(
162
+ config=OmegaConf.create({"max_model_len": 20, "prompt_length": 4, "response_length": 8,
163
+ "enable_rollout_routing_replay": False, "logprobs_mode": "processed_logprobs"}),
164
+ model_config=SimpleNamespace(processor=None), engine=engine, lora_as_adapter=True, global_steps=0,
165
+ )
166
+ generate = _serving_method_for_cpu()
167
+ params = {"max_tokens": 1, "use_lora": True, "crpd_require_adapter": True, "logprobs": True}
168
+ with pytest.raises(RuntimeError, match="refusing base fallback"):
169
+ await generate(server, [1, 2], params, "student")
170
+ assert not engine.requests
171
+ base = await generate(server, [1, 2], {**params, "use_lora": False}, "base")
172
+ assert engine.requests[-1]["lora_request"] is None
173
+ assert base[0].log_probs == [-0.2]
174
+ engine.loaded = True
175
+ await generate(server, [1, 2], params, "student")
176
+ assert engine.requests[-1]["lora_request"]["lora_int_id"] == 1
177
+ with pytest.raises(ValueError, match="only 18 fit"):
178
+ await generate(server, [1, 2], {**params, "max_tokens": 19, "sps_strict_context": True}, "long")
179
+ assert len(engine.requests) == 2
180
+ future = {**params, "use_lora": False, "power_future_exponent": 2, "temperature": 0.5}
181
+ output = (await generate(server, [1, 2], future, "future"))[0]
182
+ assert engine.requests[-1]["lora_request"] is None
183
+ assert not hasattr(engine.requests[-1]["sampling_params"], "power_future_exponent")
184
+ assert engine.requests[-1]["sampling_params"].extra_args == {"power_future_exponent": 2.0}
185
+ assert output.extra_fields["decode_logprobs_mode"] == "power_log_weights"
186
+ assert output.extra_fields["future_log_power_weights"] == [-0.2]
187
+ assert output.log_probs is None
188
+ futures = await generate(server, [1, 2], {**future, "n": 2}, "two_futures")
189
+ assert futures[0].extra_fields is not futures[1].extra_fields
190
+ assert futures[0].extra_fields["future_log_power_weights"] == [-0.2]
191
+ assert futures[1].extra_fields["future_log_power_weights"] == [pytest.approx(-0.3)]
192
+ with pytest.raises(ValueError, match="frozen-base"):
193
+ await generate(server, [1, 2], {**future, "use_lora": True}, "wrong_adapter")
194
+ with pytest.raises(ValueError, match="temperature"):
195
+ await generate(server, [1, 2], {**future, "temperature": 1}, "wrong_temperature")
196
+ server.config.logprobs_mode = "raw_logprobs"
197
+ with pytest.raises(ValueError, match="processed proposal"):
198
+ await generate(server, [1, 2], future, "wrong_mode")
199
+ server.config.logprobs_mode = "processed_logprobs"
200
+ output = (await generate(server, [1, 2], {**params, "use_lora": False, "prompt_logprobs": 0}, "score"))[0]
201
+ assert output.extra_fields["prompt_logprobs_mode"] == "raw_logprobs"
202
+ server.lora_as_adapter = False
203
+ with pytest.raises(RuntimeError, match="unmerged"):
204
+ await generate(server, [1, 2], params, "merged")
205
+
206
+ asyncio.run(exercise())
207
+
208
+
209
+ def test_power_sampler_keeps_selected_tokens_and_other_rows_logprobs_with_batch_reordering():
210
+ import ast
211
+ from pathlib import Path
212
+ from types import SimpleNamespace
213
+
214
+ import torch
215
+
216
+ path = Path(__file__).parents[3] / "verl/workers/rollout/vllm_rollout/utils.py"
217
+ node = next(node for node in ast.walk(ast.parse(path.read_text()))
218
+ if isinstance(node, ast.FunctionDef) and node.name == "patch_power_future_sampler")
219
+ namespace = {"torch": torch}
220
+ exec(compile(ast.fix_missing_locations(ast.Module(body=[node], type_ignores=[])), str(path), "exec"), namespace)
221
+
222
+ class Sampler(torch.nn.Module):
223
+ def forward(self, logits, metadata):
224
+ logits.div_(metadata.temperature.unsqueeze(-1))
225
+ proposal = logits.log_softmax(-1)
226
+ tokens = torch.multinomial(proposal.exp(), 1)
227
+ return SimpleNamespace(sampled_token_ids=tokens, logprobs_tensors=SimpleNamespace(
228
+ logprobs=proposal.gather(-1, tokens)))
229
+
230
+ runner = SimpleNamespace(
231
+ sampler=Sampler(), input_batch=SimpleNamespace(req_ids=["student", "future", "validation"]),
232
+ requests={key: SimpleNamespace(sampling_params=SimpleNamespace(
233
+ extra_args={"power_future_exponent": 2.0} if key == "future" else None,
234
+ )) for key in ["student", "future", "validation"]},
235
+ )
236
+ namespace["patch_power_future_sampler"](runner)
237
+ patched = runner.sampler.forward
238
+ namespace["patch_power_future_sampler"](runner)
239
+ assert runner.sampler.forward is patched
240
+ for request_ids, temperatures, future_row in [
241
+ (["student", "future", "validation"], [1.0, 0.5, 0.7], 1),
242
+ (["future", "validation", "student"], [0.5, 0.7, 1.0], 0),
243
+ ]:
244
+ runner.input_batch.req_ids = request_ids
245
+ logits = torch.tensor([[1.0, -0.5, 0.3], [-0.8, 1.2, 0.2], [0.2, 0.8, -0.6]])
246
+ metadata = SimpleNamespace(temperature=torch.tensor(temperatures))
247
+ torch.manual_seed(17)
248
+ reference = Sampler()(logits.clone(), metadata)
249
+ torch.manual_seed(17)
250
+ actual = runner.sampler(logits.clone(), metadata)
251
+ torch.testing.assert_close(actual.sampled_token_ids, reference.sampled_token_ids)
252
+ raw = logits.log_softmax(-1).gather(-1, actual.sampled_token_ids)
253
+ expected = 2 * raw[future_row] - reference.logprobs_tensors.logprobs[future_row]
254
+ torch.testing.assert_close(actual.logprobs_tensors.logprobs[future_row], expected)
255
+ ordinary = [index for index in range(3) if index != future_row]
256
+ torch.testing.assert_close(actual.logprobs_tensors.logprobs[ordinary],
257
+ reference.logprobs_tensors.logprobs[ordinary])
258
+
259
+
260
+ @pytest.mark.parametrize("wrapped", [False, True])
261
+ def test_crpd_prompt_scoring_bypasses_unused_lora_logits_and_preserves_transformer_adapters(monkeypatch, wrapped):
262
+ import ast
263
+ import sys
264
+ from pathlib import Path
265
+ from types import ModuleType, SimpleNamespace
266
+
267
+ class LogitsProcessorWithLoRA:
268
+ def __init__(self, base_layer):
269
+ self.base_layer = base_layer
270
+
271
+ def __call__(self, lm_head, rows):
272
+ if len(rows) > 1:
273
+ raise RuntimeError("decode LoRA mapping is too short for prompt rows")
274
+ return self.base_layer(lm_head.base_layer, rows)
275
+
276
+ module = ModuleType("vllm.lora.layers.logits_processor")
277
+ module.LogitsProcessorWithLoRA = LogitsProcessorWithLoRA
278
+ monkeypatch.setitem(sys.modules, module.__name__, module)
279
+ path = Path(__file__).parents[3] / "verl/workers/rollout/vllm_rollout/utils.py"
280
+ tree = ast.parse(path.read_text())
281
+ method = next(node for node in ast.walk(tree) if isinstance(node, ast.FunctionDef)
282
+ and node.name == "monkey_patch_model")
283
+ namespace = {
284
+ "monkey_patch_compute_logits": lambda *_: None,
285
+ "patch_vllm_moe_model_weight_loader": lambda *_: None,
286
+ "patch_power_future_sampler": lambda *_: None,
287
+ "logger": SimpleNamespace(info=lambda *_: None),
288
+ }
289
+ exec(compile(ast.fix_missing_locations(ast.Module(body=[method], type_ignores=[])), str(path), "exec"), namespace)
290
+ base = lambda lm_head, rows: lm_head.quant_method.apply(rows)
291
+ base_head = SimpleNamespace(quant_method=SimpleNamespace(apply=lambda rows: [value * 2 for value in rows]))
292
+ adapter = object()
293
+
294
+ class Model:
295
+ def __init__(self):
296
+ self.logits_processor = LogitsProcessorWithLoRA(base)
297
+ self.lm_head = SimpleNamespace(base_layer=base_head)
298
+ self.transformer_adapter = adapter
299
+
300
+ def compute_logits(self, rows):
301
+ return self.logits_processor(self.lm_head, rows)
302
+
303
+ class CUDAGraphWrapper:
304
+ # vLLM delegates reads, but assignments stay on the wrapper.
305
+ def __init__(self, runnable):
306
+ self.runnable = runnable
307
+
308
+ def __getattr__(self, name):
309
+ return getattr(self.runnable, name)
310
+
311
+ model = Model()
312
+ runner_model = CUDAGraphWrapper(model) if wrapped else model
313
+ worker = SimpleNamespace(model_runner=SimpleNamespace(model=runner_model, get_model=lambda: model))
314
+ with pytest.raises(RuntimeError, match="too short"):
315
+ runner_model.compute_logits([1, 2, 3])
316
+ namespace["monkey_patch_model"](worker, 10)
317
+ assert isinstance(model.logits_processor, LogitsProcessorWithLoRA)
318
+ namespace["monkey_patch_model"](worker, 10, crpd_base_scoring=True)
319
+ assert runner_model.compute_logits([1, 2, 3]) == [2, 4, 6]
320
+ assert model.transformer_adapter is adapter
321
+ assert model.lm_head is base_head
322
+ namespace["monkey_patch_model"](worker, 10, crpd_base_scoring=True)
323
+ assert model.logits_processor is base
snapshots/centered_startup_fix_20261012_172656/third_party/verl/verl/workers/rollout/vllm_rollout/vllm_async_server.py ADDED
@@ -0,0 +1,1108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import argparse
15
+ import asyncio
16
+ import inspect
17
+ import json
18
+ import logging
19
+ import os
20
+ from pprint import pprint
21
+ from typing import Any, Callable, Optional
22
+
23
+ import ray
24
+ import vllm.entrypoints.cli.serve
25
+ from packaging import version
26
+ from ray.actor import ActorHandle
27
+ from vllm import SamplingParams
28
+ from vllm.engine.arg_utils import AsyncEngineArgs
29
+ from vllm.entrypoints.cli.serve import run_headless
30
+ from vllm.entrypoints.openai.api_server import build_app, init_app_state
31
+ from vllm.inputs import TokensPrompt
32
+ from vllm.lora.request import LoRARequest
33
+ from vllm.outputs import RequestOutput
34
+ from vllm.sampling_params import RequestOutputKind
35
+ from vllm.usage.usage_lib import UsageContext
36
+ from vllm.v1.engine.async_llm import AsyncLLM
37
+
38
+ from verl.utils.config import omega_conf_to_dataclass
39
+ from verl.utils.device import get_resource_name, get_visible_devices_keyword, is_torch_npu_available
40
+ from verl.utils.net_utils import get_free_port, is_valid_ipv6_address
41
+ from verl.utils.profiler import DistProfiler, build_vllm_profiler_args
42
+ from verl.utils.tokenizer import normalize_token_ids
43
+ from verl.utils.vllm.vllm_fp8_utils import apply_vllm_fp8_patches
44
+ from verl.workers.config import HFModelConfig, RolloutConfig
45
+ from verl.workers.rollout.replica import RolloutMode, RolloutReplica, TokenOutput
46
+ from verl.workers.rollout.utils import get_max_position_embeddings, qwen2_5_vl_dedup_image_tokens, run_uvicorn
47
+ from verl.workers.rollout.vllm_rollout.utils import (
48
+ VLLM_LORA_INT_ID,
49
+ VLLM_LORA_NAME,
50
+ VLLM_LORA_PATH,
51
+ SuppressSignalInThread,
52
+ build_cli_args_from_config,
53
+ extract_prompt_logprobs,
54
+ get_vllm_max_lora_rank,
55
+ )
56
+
57
+ _VLLM_VERSION = version.parse(vllm.__version__)
58
+
59
+ if _VLLM_VERSION > version.parse("0.11.0"):
60
+ from vllm.utils.argparse_utils import FlexibleArgumentParser
61
+
62
+ if _VLLM_VERSION == version.parse("0.12.0"):
63
+ from vllm.entrypoints.harmony_utils import get_encoding
64
+
65
+ elif _VLLM_VERSION >= version.parse("0.13.0"):
66
+ from vllm.entrypoints.openai.parser.harmony_utils import get_encoding
67
+
68
+ else:
69
+ get_encoding = None
70
+
71
+ if get_encoding is not None and os.getenv("VERL_USE_GPT_OSS", "0") == "1":
72
+ get_encoding()
73
+ else:
74
+ from vllm.utils import FlexibleArgumentParser
75
+
76
+
77
+ logger = logging.getLogger(__file__)
78
+ logger.setLevel(logging.INFO)
79
+
80
+
81
+ class vLLMHttpServer:
82
+ """vLLM http server in single node, this is equivalent to launch server with command line:
83
+ ```
84
+ vllm serve --tensor-parallel-size=8 ...
85
+ ```
86
+ """
87
+
88
+ def __init__(
89
+ self,
90
+ config,
91
+ model_config,
92
+ rollout_mode: RolloutMode,
93
+ workers: list[ActorHandle],
94
+ replica_rank: int,
95
+ node_rank: int,
96
+ gpus_per_node: int,
97
+ nnodes: int,
98
+ cuda_visible_devices: str,
99
+ ):
100
+ """
101
+ Args:
102
+ config (RolloutConfig): full config.
103
+ model_config (HFModelConfig): model config.
104
+ rollout_mode (RolloutMode): rollout mode.
105
+ replica_rank (int): replica rank, a replica may contain multiple nodes.
106
+ node_rank (int): node rank.
107
+ gpus_per_node (int): number of gpus per node.
108
+ nnodes (int): number of nodes.
109
+ cuda_visible_devices (str): cuda visible devices.
110
+ """
111
+ os.environ[get_visible_devices_keyword()] = cuda_visible_devices
112
+
113
+ self.config = self._init_config(config)
114
+ self.model_config = self._init_model_config(model_config)
115
+ self._validate_configs()
116
+
117
+ self.rollout_mode = rollout_mode
118
+ self.workers = workers
119
+
120
+ self.replica_rank = replica_rank
121
+ self.node_rank = node_rank
122
+ self.gpus_per_node = gpus_per_node
123
+ self.nnodes = nnodes
124
+ # model weights version, set by ServerAdapter when update weights.
125
+ self.global_steps = None
126
+
127
+ if self.rollout_mode != RolloutMode.HYBRID and self.config.load_format == "dummy":
128
+ logger.warning(f"rollout mode is {self.rollout_mode}, load_format is dummy, set to auto")
129
+ self.config.load_format = "auto"
130
+
131
+ # used for http server
132
+ self._server_address = ray.util.get_node_ip_address().strip("[]")
133
+ self._server_port = None
134
+
135
+ # used for controlling vllm server profiler
136
+ profiler_config = self.config.profiler
137
+ tool_config = None
138
+ if profiler_config is not None:
139
+ if profiler_config.tool in ["torch", "npu"]:
140
+ tool_config = omega_conf_to_dataclass((profiler_config.tool_config or {}).get(profiler_config.tool))
141
+ else:
142
+ logger.warning(f"agent loop only support torch and npu profiler, got {profiler_config.tool}")
143
+ profiler_config = None
144
+ self.profiler_controller = DistProfiler(self.replica_rank, config=profiler_config, tool_config=tool_config)
145
+
146
+ # used for data parallel: --data-parallel-address, --data-parallel-rpc-port
147
+ if self.node_rank == 0:
148
+ self._master_address = self._server_address
149
+ # used for torch.distributed.init_process_group
150
+ self._master_port, self._master_sock = get_free_port(self._server_address, with_alive_sock=True)
151
+ # used for data parallel: --data-parallel-address, --data-parallel-rpc-port
152
+ self._dp_rpc_port, self._dp_rpc_sock = get_free_port(self._server_address, with_alive_sock=True)
153
+ self._dp_master_port, self._dp_master_sock = get_free_port(self._server_address, with_alive_sock=True)
154
+ else:
155
+ self._master_address = None
156
+ self._master_port = None
157
+ self._dp_rpc_port = None
158
+ self._dp_master_port = None
159
+
160
+ self._post_init(cuda_visible_devices)
161
+
162
+ def get_master_address(self):
163
+ """Get master address and port for data parallel.
164
+ Returns:
165
+ tuple: (master_address, master_port, dp_rpc_port)
166
+ """
167
+ return self._master_address, self._master_port, self._dp_rpc_port
168
+
169
+ def get_server_address(self):
170
+ """Get http server address and port."""
171
+ assert self._server_port is not None, "http server is not launched, port is None"
172
+ return self._server_address, self._server_port
173
+
174
+ @property
175
+ def lora_as_adapter(self) -> bool:
176
+ return (
177
+ self.model_config.lora_rank > 0 or self.model_config.lora.get("rank", 0) > 0
178
+ ) and not self.model_config.lora.get("merge", False)
179
+
180
+ async def collective_rpc(
181
+ self,
182
+ method: str | Callable,
183
+ timeout: float | None = None,
184
+ args: tuple = (),
185
+ kwargs: dict[str, Any] | None = None,
186
+ ):
187
+ await self.engine.collective_rpc(
188
+ method=method,
189
+ timeout=timeout,
190
+ args=args,
191
+ kwargs=kwargs,
192
+ )
193
+
194
+ async def launch_server(self, master_address: str = None, master_port: int = None, dp_rpc_port: int = None):
195
+ if self.node_rank != 0:
196
+ assert master_address and master_port and dp_rpc_port, (
197
+ "non-master node should provide master_address, master_port and dp_rpc_port"
198
+ )
199
+ self._master_address = master_address
200
+ self._master_port = master_port
201
+ self._dp_rpc_port = dp_rpc_port
202
+
203
+ # 1. setup vllm serve cli args
204
+ engine_kwargs = self.config.get("engine_kwargs", {}).get(self._get_engine_kwargs_key(), {}) or {}
205
+ engine_kwargs = {key: val for key, val in engine_kwargs.items() if val is not None}
206
+ if self.config.get("limit_images", None): # support for multi-image data
207
+ engine_kwargs["limit_mm_per_prompt"] = {"image": self.config.get("limit_images")}
208
+ if self.config.cudagraph_capture_sizes:
209
+ engine_kwargs["cuda_graph_sizes"] = self.config.cudagraph_capture_sizes
210
+
211
+ self._preprocess_engine_kwargs(engine_kwargs)
212
+
213
+ # Override default generation config from hugging face model config,
214
+ # user can still override them by passing kwargs in each request.
215
+ override_generation_config = self._get_override_generation_config()
216
+ logger.info(f"override_generation_config: {override_generation_config}")
217
+
218
+ logger.info(f"enable_sleep_mode: {self.config.enable_sleep_mode}")
219
+ if not self.config.enable_sleep_mode:
220
+ from verl.utils.device import set_expandable_segments
221
+
222
+ set_expandable_segments(True)
223
+
224
+ quantization, hf_overrides = self._apply_quantization()
225
+
226
+ compilation_config = engine_kwargs.pop("compilation_config", None) or {}
227
+ if isinstance(compilation_config, str):
228
+ compilation_config = json.loads(compilation_config)
229
+ compilation_config.setdefault("cudagraph_mode", "FULL_AND_PIECEWISE")
230
+
231
+ # FULL cuda graph is not yet supported with DCP, downgrade to PIECEWISE
232
+ dcp_size = engine_kwargs.get("decode_context_parallel_size", 1) or 1
233
+ if dcp_size > 1 and compilation_config["cudagraph_mode"] == "FULL_AND_PIECEWISE":
234
+ logger.warning(
235
+ "FULL cuda graph is not supported with DCP (decode_context_parallel_size=%d), "
236
+ "downgrading cudagraph_mode to PIECEWISE.",
237
+ dcp_size,
238
+ )
239
+ compilation_config["cudagraph_mode"] = "PIECEWISE"
240
+
241
+ compilation_config = json.dumps(compilation_config)
242
+ args = {
243
+ "dtype": self.config.dtype,
244
+ "load_format": self.config.load_format,
245
+ "skip_tokenizer_init": False,
246
+ "distributed_executor_backend": "mp",
247
+ "worker_extension_cls": self._get_worker_extension_cls(),
248
+ "trust_remote_code": self.model_config.trust_remote_code,
249
+ "max_model_len": self.config.max_model_len,
250
+ "max_num_seqs": self.config.max_num_seqs,
251
+ "enable_chunked_prefill": self.config.enable_chunked_prefill,
252
+ "max_num_batched_tokens": self.config.max_num_batched_tokens,
253
+ "enable_prefix_caching": self.config.enable_prefix_caching,
254
+ "enable_sleep_mode": self.config.enable_sleep_mode,
255
+ "logprobs_mode": self.config.logprobs_mode,
256
+ "enforce_eager": self.config.enforce_eager,
257
+ "gpu_memory_utilization": self.config.gpu_memory_utilization,
258
+ "disable_log_stats": self.config.disable_log_stats,
259
+ "tensor_parallel_size": self.config.tensor_model_parallel_size,
260
+ "seed": self.replica_rank + self.config.get("seed", 0),
261
+ "override_generation_config": json.dumps(override_generation_config),
262
+ "quantization": quantization,
263
+ "hf_overrides": hf_overrides,
264
+ "scheduling_policy": self.config.scheduling_policy,
265
+ "compilation_config": compilation_config,
266
+ **engine_kwargs,
267
+ }
268
+
269
+ # update profiler args
270
+ profiler_args = build_vllm_profiler_args(
271
+ self.profiler_controller.config, self.profiler_controller.tool_config, self.replica_rank
272
+ )
273
+ if _VLLM_VERSION >= version.parse("0.13.0"):
274
+ # vLLM >= 0.13.0 supports profiler config via CLI args; env vars still work but will be deprecated
275
+ args.update(profiler_args)
276
+
277
+ if self.config.prometheus.enable:
278
+ if self.config.prometheus.served_model_name:
279
+ # Extract model name from path if it's a full path
280
+ served_model_name = self.config.prometheus.served_model_name
281
+ if "/" in served_model_name:
282
+ # If it's a full path, extract the last part as model name
283
+ served_model_name = served_model_name.split("/")[-1]
284
+ args["served_model_name"] = served_model_name
285
+
286
+ # mtp (None for diffusion models; only LLM models use speculative decoding)
287
+ if self.config.mtp is not None and self.config.mtp.enable and self.config.mtp.enable_rollout:
288
+ speculative_config = {
289
+ "method": self.config.mtp.method,
290
+ "num_speculative_tokens": self.config.mtp.num_speculative_tokens,
291
+ }
292
+ args["speculative_config"] = speculative_config
293
+
294
+ if self.config.data_parallel_size > 1:
295
+ assert self.gpus_per_node % self.config.tensor_model_parallel_size == 0, (
296
+ "gpus_per_node should be divisible by tensor_model_parallel_size"
297
+ )
298
+ data_parallel_size_local = self.gpus_per_node // self.config.tensor_model_parallel_size
299
+ assert len(self.workers) == data_parallel_size_local * self.config.tensor_model_parallel_size, (
300
+ f"num workers ({len(self.workers)}) should be equal to "
301
+ f"dp_size_local ({data_parallel_size_local}) * tp_size ({self.config.tensor_model_parallel_size})"
302
+ )
303
+ dp_args = {
304
+ "data_parallel_size": self.config.data_parallel_size,
305
+ "data_parallel_size_local": data_parallel_size_local,
306
+ "data_parallel_start_rank": self.node_rank * data_parallel_size_local,
307
+ "data_parallel_address": self._master_address,
308
+ "data_parallel_rpc_port": self._dp_rpc_port,
309
+ }
310
+ args.update(dp_args)
311
+
312
+ args.update({"enable_expert_parallel": self.config.expert_parallel_size > 1})
313
+
314
+ # used for torch.distributed.init_process_group
315
+ if self.nnodes > 1:
316
+ args.update(
317
+ {
318
+ "master_addr": self._master_address,
319
+ "master_port": self._master_port,
320
+ "node_rank": self.node_rank,
321
+ "nnodes": self.nnodes,
322
+ "data_parallel_address": self._master_address,
323
+ "data_parallel_rpc_port": self._dp_rpc_port,
324
+ }
325
+ )
326
+
327
+ # update lora-related args
328
+ lora_rank = self.model_config.lora.get("rank", 0)
329
+ if lora_rank <= 0:
330
+ lora_rank = (
331
+ self.model_config.lora_rank
332
+ ) # FIXME: fallback to lora_rank for now, we should unify lora settings.
333
+
334
+ if self.model_config.lora.get("merge", False):
335
+ lora_rank = 0
336
+
337
+ if lora_rank > 0:
338
+ lora_args = {
339
+ "enable_lora": True,
340
+ "max_loras": 1,
341
+ "max_lora_rank": get_vllm_max_lora_rank(lora_rank),
342
+ }
343
+ if self.model_config.lora.get("fully_sharded_loras", False):
344
+ lora_args["fully_sharded_loras"] = True
345
+ args.update(lora_args)
346
+
347
+ if self.config.enable_rollout_routing_replay:
348
+ args.update({"enable_return_routed_experts": True})
349
+
350
+ server_args = ["serve", self.model_config.local_path] + build_cli_args_from_config(args)
351
+
352
+ if self.replica_rank == 0:
353
+ pprint(server_args)
354
+
355
+ CMD_MODULES = self._get_cli_modules()
356
+ parser = FlexibleArgumentParser(description=self._get_cli_description())
357
+ subparsers = parser.add_subparsers(required=False, dest="subparser")
358
+ cmds = {}
359
+ for cmd_module in CMD_MODULES:
360
+ new_cmds = cmd_module.cmd_init()
361
+ for cmd in new_cmds:
362
+ cmd.subparser_init(subparsers).set_defaults(dispatch_function=cmd.cmd)
363
+ cmds[cmd.name] = cmd
364
+ server_args = parser.parse_args(args=server_args)
365
+ server_args.model = server_args.model_tag
366
+ if server_args.subparser in cmds:
367
+ cmds[server_args.subparser].validate(server_args)
368
+
369
+ # 3. launch server
370
+ if self.node_rank == 0:
371
+ await self.run_server(server_args)
372
+ else:
373
+ await self.run_headless(server_args)
374
+
375
+ async def run_server(self, args: argparse.Namespace):
376
+ engine_args = AsyncEngineArgs.from_cli_args(args)
377
+ usage_context = UsageContext.OPENAI_API_SERVER
378
+ vllm_config = engine_args.create_engine_config(usage_context=usage_context)
379
+ vllm_config.parallel_config.data_parallel_master_port = self._dp_master_port
380
+
381
+ fn_args = set(dict(inspect.signature(AsyncLLM.from_vllm_config).parameters).keys())
382
+ kwargs = {}
383
+ if "enable_log_requests" in fn_args:
384
+ kwargs["enable_log_requests"] = engine_args.enable_log_requests
385
+ if "disable_log_stats" in fn_args:
386
+ kwargs["disable_log_stats"] = engine_args.disable_log_stats
387
+
388
+ engine_client = AsyncLLM.from_vllm_config(vllm_config=vllm_config, usage_context=usage_context, **kwargs)
389
+
390
+ # Don't keep the dummy data in memory
391
+ await engine_client.reset_mm_cache()
392
+ crpd_base_scoring = (self.config.custom or {}).get("objective") == "centered_power_student"
393
+ if crpd_base_scoring and self.model_config.target_modules != "all-linear":
394
+ raise ValueError("CRPD prompt scoring requires all-linear LoRA targets (excluding lm_head).")
395
+ patch_kwargs = {"vocab_size": len(self.model_config.tokenizer)}
396
+ if crpd_base_scoring:
397
+ patch_kwargs["crpd_base_scoring"] = True
398
+ await engine_client.collective_rpc(
399
+ method="monkey_patch_model", kwargs=patch_kwargs
400
+ )
401
+
402
+ build_app_sig = inspect.signature(build_app)
403
+ supported_tasks: tuple[Any, ...] = ()
404
+ if "supported_tasks" in build_app_sig.parameters:
405
+ supported_tasks = await engine_client.get_supported_tasks()
406
+ app = build_app(args, supported_tasks)
407
+ else:
408
+ app = build_app(args)
409
+
410
+ init_app_sig = inspect.signature(init_app_state)
411
+ if "vllm_config" in init_app_sig.parameters:
412
+ await init_app_state(engine_client, vllm_config, app.state, args)
413
+ elif "supported_tasks" in init_app_sig.parameters:
414
+ await init_app_state(engine_client, app.state, args, supported_tasks)
415
+ else:
416
+ await init_app_state(engine_client, app.state, args)
417
+ if self.replica_rank == 0 and self.node_rank == 0:
418
+ logger.info(f"Initializing a V1 LLM engine with config: {vllm_config}")
419
+
420
+ self.engine = engine_client
421
+ self._server_port, self._server_task = await run_uvicorn(app, args, self._server_address)
422
+
423
+ async def run_headless(self, args: argparse.Namespace):
424
+ """Run headless server in a separate thread."""
425
+ args.api_server_count = 0
426
+
427
+ def run_headless_wrapper():
428
+ with SuppressSignalInThread():
429
+ run_headless(args)
430
+
431
+ def on_run_headless_done(future: asyncio.Future):
432
+ try:
433
+ exc = future.exception()
434
+ if exc:
435
+ logger.exception(f"run_headless failed with exception: {exc}")
436
+ else:
437
+ logger.warning("run_headless completed successfully, but it's not expected.")
438
+ except Exception as e:
439
+ logger.exception(f"get result from run_headless failed: {e}")
440
+ finally:
441
+ os._exit(1)
442
+
443
+ self.task = asyncio.create_task(asyncio.to_thread(run_headless_wrapper))
444
+ self.task.add_done_callback(on_run_headless_done)
445
+
446
+ async def generate(
447
+ self,
448
+ prompt_ids: list[int],
449
+ sampling_params: dict[str, Any],
450
+ request_id: str,
451
+ image_data: Optional[list[Any]] = None,
452
+ video_data: Optional[list[Any]] = None,
453
+ priority: int = 0,
454
+ ) -> TokenOutput:
455
+ """Generate sequence with token-in-token-out."""
456
+ outputs = await self.generate_n(
457
+ prompt_ids=prompt_ids,
458
+ sampling_params=sampling_params,
459
+ request_id=request_id,
460
+ image_data=image_data,
461
+ video_data=video_data,
462
+ priority=priority,
463
+ )
464
+ if not outputs:
465
+ raise RuntimeError("vLLM generate returned no sequences.")
466
+ return outputs[0]
467
+
468
+ async def generate_n(
469
+ self,
470
+ prompt_ids: list[int],
471
+ sampling_params: dict[str, Any],
472
+ request_id: str,
473
+ image_data: Optional[list[Any]] = None,
474
+ video_data: Optional[list[Any]] = None,
475
+ priority: int = 0,
476
+ ) -> list[TokenOutput]:
477
+ """Generate one or more sequences from a shared prefix.
478
+
479
+ Passing SamplingParams.n>1 lets vLLM decode multiple future continuations after a
480
+ single prefill for CRPD candidate blocks or frozen-base futures.
481
+ """
482
+ sampling_params = dict(sampling_params)
483
+ prompt_ids = normalize_token_ids(prompt_ids)
484
+
485
+ # Calculate the maximum possible new tokens based on available context space
486
+ # This serves as a safety upper bound
487
+ max_possible_tokens = self.config.max_model_len - len(prompt_ids)
488
+ if max_possible_tokens < 0:
489
+ raise ValueError(
490
+ f"Prompt length ({len(prompt_ids)}) exceeds the model's maximum context length "
491
+ f"({self.config.max_model_len})."
492
+ )
493
+
494
+ # Student blocks use the active adapter; base scoring/futures disable it.
495
+ use_lora = bool(sampling_params.pop("use_lora", True))
496
+ strict_context = bool(sampling_params.pop("sps_strict_context", False))
497
+ require_adapter = bool(sampling_params.pop("crpd_require_adapter", False))
498
+ future_exponent = sampling_params.pop("power_future_exponent", None)
499
+ if future_exponent is not None:
500
+ if use_lora or self.config.logprobs_mode != "processed_logprobs":
501
+ raise ValueError("Power futures require frozen-base processed proposal log probabilities.")
502
+ if float(sampling_params.get("temperature", 1.0)) != 1.0 / future_exponent:
503
+ raise ValueError("Power future temperature must match its exponent.")
504
+ if not sampling_params.get("logprobs", False):
505
+ raise ValueError("Power futures require per-token importance weights.")
506
+ sampling_params["extra_args"] = {"power_future_exponent": float(future_exponent)}
507
+
508
+ # Determine max_tokens from sampling_params or use configured response_length as default
509
+ if "max_tokens" in sampling_params:
510
+ max_tokens = sampling_params.pop("max_tokens")
511
+ elif "max_new_tokens" in sampling_params:
512
+ # support sglang-style 'max_new_tokens' param
513
+ max_tokens = sampling_params.pop("max_new_tokens")
514
+ else:
515
+ # Default to a calculation that considers configured lengths
516
+ # Cap max_tokens by response_length to ensure tensor alignment,
517
+ # and by remaining budget to prevent OOM in multi-turn rollouts.
518
+ max_tokens = min(
519
+ self.config.response_length, self.config.prompt_length + self.config.response_length - len(prompt_ids)
520
+ )
521
+
522
+ if strict_context and max_tokens > max_possible_tokens:
523
+ raise ValueError(
524
+ f"SPS request needs {max_tokens} new tokens but only {max_possible_tokens} fit in "
525
+ f"the model context (prompt length {len(prompt_ids)}, max_model_len {self.config.max_model_len})."
526
+ )
527
+ # Non-SPS requests retain the existing context clamp. SPS uses a fixed horizon and
528
+ # must fail rather than silently changing the estimator's target.
529
+ max_tokens = max(0, min(max_tokens, max_possible_tokens))
530
+
531
+ assert max_tokens <= max_possible_tokens, (
532
+ f"max_tokens {max_tokens} exceeds available context space {max_possible_tokens}"
533
+ )
534
+ sampling_params["logprobs"] = 0 if sampling_params.pop("logprobs", False) else None
535
+ sampling_params.setdefault("repetition_penalty", self.config.get("repetition_penalty", 1.0))
536
+ # AsyncLLM streams CUMULATIVE n-sampling by child request; the last yield
537
+ # can drop completions. FINAL_ONLY plus index accumulation keeps all n.
538
+ sampling_params.setdefault("output_kind", RequestOutputKind.FINAL_ONLY)
539
+ sampling_params = SamplingParams(max_tokens=max_tokens, **sampling_params)
540
+ prompt_ids = qwen2_5_vl_dedup_image_tokens(prompt_ids, self.model_config.processor)
541
+ multi_modal_data = {}
542
+ if image_data is not None:
543
+ multi_modal_data["image"] = image_data
544
+ if video_data is not None:
545
+ multi_modal_data["video"] = video_data
546
+
547
+ prompt = TokensPrompt(prompt_token_ids=prompt_ids, multi_modal_data=multi_modal_data)
548
+
549
+ lora_request = None
550
+ if use_lora and require_adapter and not self.lora_as_adapter:
551
+ raise RuntimeError("CRPD student generation requires an unmerged LoRA adapter.")
552
+ if use_lora and self.lora_as_adapter:
553
+ # Make sure we also check that the lora is already loaded in the engine
554
+ lora_loaded = VLLM_LORA_INT_ID in await self.engine.list_loras()
555
+ if require_adapter and not lora_loaded:
556
+ raise RuntimeError("CRPD student adapter is not loaded in vLLM; refusing base fallback.")
557
+ if lora_loaded:
558
+ lora_request = LoRARequest(
559
+ lora_name=VLLM_LORA_NAME, lora_int_id=VLLM_LORA_INT_ID, lora_path=VLLM_LORA_PATH
560
+ )
561
+
562
+ generator = self.engine.generate(
563
+ prompt=prompt,
564
+ sampling_params=sampling_params,
565
+ request_id=request_id,
566
+ lora_request=lora_request,
567
+ priority=priority,
568
+ )
569
+
570
+ # Get final response. Accumulate by completion.index because AsyncLLM may
571
+ # emit a subset of the n sequences in any given RequestOutput.
572
+ final_res: Optional[RequestOutput] = None
573
+ completions: dict[int, Any] = {}
574
+ async for output in generator:
575
+ final_res = output
576
+ for completion in output.outputs:
577
+ completions[int(completion.index)] = completion
578
+ assert final_res is not None
579
+ if not completions:
580
+ raise RuntimeError("vLLM generate_n returned no sequences.")
581
+
582
+ extra_fields = {"global_steps": self.global_steps, "decode_logprobs_mode": self.config.logprobs_mode}
583
+ if future_exponent is not None:
584
+ extra_fields["decode_logprobs_mode"] = "power_log_weights"
585
+ if sampling_params.prompt_logprobs is not None:
586
+ extra_fields["prompt_logprobs_mode"] = "raw_logprobs"
587
+ extract_prompt_logprobs(
588
+ output=final_res,
589
+ num_prompt_logprobs=sampling_params.prompt_logprobs,
590
+ result_dict=extra_fields,
591
+ )
592
+ results = []
593
+ for completion in (completions[index] for index in sorted(completions)):
594
+ token_ids = completion.token_ids
595
+ log_probs = None
596
+ if sampling_params.logprobs is not None:
597
+ if completion.logprobs is None:
598
+ raise RuntimeError("vLLM generate_n did not return logprobs for a sampled sequence.")
599
+ log_probs = [logprobs[token_ids[i]].logprob for i, logprobs in enumerate(completion.logprobs)]
600
+
601
+ completion_extra_fields = dict(extra_fields)
602
+ if future_exponent is not None:
603
+ completion_extra_fields["future_log_power_weights"] = log_probs
604
+ log_probs = None
605
+
606
+ routed_experts = None
607
+ if self.config.enable_rollout_routing_replay:
608
+ routed_experts = completion.routed_experts
609
+
610
+ finish_reason = completion.finish_reason
611
+ if finish_reason == "abort":
612
+ stop_reason = "aborted"
613
+ elif finish_reason in ("stop", "length"):
614
+ stop_reason = "completed"
615
+ else:
616
+ stop_reason = finish_reason
617
+
618
+ num_preempted = completion.num_preempted if hasattr(completion, "num_preempted") else None
619
+ results.append(
620
+ TokenOutput(
621
+ token_ids=token_ids,
622
+ log_probs=log_probs,
623
+ routed_experts=routed_experts,
624
+ stop_reason=stop_reason,
625
+ num_preempted=num_preempted,
626
+ extra_fields=completion_extra_fields,
627
+ )
628
+ )
629
+ return results
630
+
631
+ async def wake_up(self):
632
+ if self.node_rank != 0:
633
+ return
634
+
635
+ if self.rollout_mode == RolloutMode.HYBRID:
636
+ # In hybrid mode, rollout is wake up in `update_weights`
637
+ raise ValueError(f"wake_up not support rollout_mode {self.rollout_mode}")
638
+ elif self.rollout_mode == RolloutMode.COLOCATED:
639
+ # Directly call engine to wake up without sync weights.
640
+ await self.engine.wake_up(tags=self._get_wake_up_tags())
641
+ await self.engine.reset_prefix_cache()
642
+ elif self.rollout_mode == RolloutMode.STANDALONE:
643
+ logger.info("skip wake_up in standalone mode")
644
+
645
+ async def sleep(self):
646
+ if self.node_rank != 0 or not self.config.free_cache_engine:
647
+ return
648
+
649
+ if self.rollout_mode == RolloutMode.HYBRID:
650
+ await self._sleep_hybrid()
651
+ elif self.rollout_mode == RolloutMode.COLOCATED:
652
+ await self.engine.sleep(level=1)
653
+ elif self.rollout_mode == RolloutMode.STANDALONE:
654
+ logger.info("skip sleep in standalone mode")
655
+
656
+ async def start_profile(self, **kwargs):
657
+ if (
658
+ self.profiler_controller.check_enable()
659
+ and self.profiler_controller.check_this_rank()
660
+ and self.profiler_controller.is_discrete_mode()
661
+ ):
662
+ await self.engine.start_profile(**kwargs)
663
+
664
+ async def stop_profile(self):
665
+ if (
666
+ self.profiler_controller.check_enable()
667
+ and self.profiler_controller.check_this_rank()
668
+ and self.profiler_controller.is_discrete_mode()
669
+ ):
670
+ await self.engine.stop_profile()
671
+
672
+ async def clear_kv_cache(self):
673
+ if self.node_rank == 0:
674
+ await self.engine.reset_prefix_cache()
675
+
676
+ async def set_global_steps(self, global_steps: int):
677
+ """Set the global steps of the model weights."""
678
+ self.global_steps = global_steps
679
+
680
+ async def wait_for_requests_to_drain(self):
681
+ await self.engine.wait_for_requests_to_drain()
682
+
683
+ async def abort_all_requests(self, reset_prefix_cache: bool = True) -> dict[str, Any]:
684
+ """Abort all ongoing generation requests.
685
+
686
+ On vLLM >= 0.12.0, uses AsyncLLM.pause_generation() to abort in-flight
687
+ requests, drain, and clear caches. The engine remains paused after this
688
+ call — use resume_generation() to accept new requests (e.g. before
689
+ validation).
690
+
691
+ On vLLM < 0.12.0, manually aborts each request and resets prefix cache.
692
+
693
+ Returns:
694
+ dict[str, Any]: Dictionary containing:
695
+ - aborted_count: Number of requests aborted
696
+ - request_ids: List of aborted request IDs
697
+ """
698
+ try:
699
+ if _VLLM_VERSION >= version.parse("0.12.0"):
700
+ # Snapshot request IDs before pausing for reporting
701
+ request_ids = list(self.engine.output_processor.request_states.keys())
702
+
703
+ # pause_generation with wait_for_inflight_requests=False will:
704
+ # 1. Set engine to paused state (blocks new generate calls)
705
+ # 2. Abort all in-flight requests
706
+ # 3. Wait for requests to drain
707
+ # 4. Clear prefix and mm caches if clear_cache=True
708
+ await self.engine.pause_generation(
709
+ wait_for_inflight_requests=False,
710
+ clear_cache=reset_prefix_cache,
711
+ )
712
+ else:
713
+ # Take an atomic snapshot to avoid race conditions with the vLLM engine thread
714
+ request_states_snapshot = list(self.engine.output_processor.request_states.items())
715
+ request_ids = [req_id for req_id, _ in request_states_snapshot]
716
+
717
+ if not request_ids:
718
+ return {"aborted_count": 0, "request_ids": []}
719
+
720
+ # For each request, create an abort output and put it to its queue
721
+ # This allows the generator to receive the aborted result
722
+ from vllm.v1.engine import FinishReason
723
+
724
+ for _, req_state in request_states_snapshot:
725
+ request_output = req_state.make_request_output(
726
+ [], pooling_output=None, finish_reason=FinishReason.ABORT, stop_reason=None
727
+ )
728
+ req_state.queue.put(request_output)
729
+
730
+ # Abort requests in the output processor and engine core
731
+ self.engine.output_processor.abort_requests(request_ids)
732
+ await self.engine.engine_core.abort_requests_async(request_ids)
733
+
734
+ # Try to reset prefix cache to ensure clean state
735
+ if reset_prefix_cache:
736
+ await self.clear_kv_cache()
737
+ logger.info("Prefix cache reset after abort")
738
+
739
+ logger.info(f"Aborted {len(request_ids)} requests: {request_ids}")
740
+ return {"aborted_count": len(request_ids), "request_ids": request_ids}
741
+
742
+ except Exception as e:
743
+ logger.error(f"Error aborting requests: {e}")
744
+ return {"aborted_count": 0, "request_ids": [], "error": str(e)}
745
+
746
+ async def resume_generation(self):
747
+ """Resume generation after abort_all_requests (pause_generation).
748
+
749
+ Only effective on vLLM >= 0.12.0 where pause_generation is used.
750
+ No-op on older versions.
751
+ """
752
+ if self.node_rank != 0:
753
+ return
754
+ if _VLLM_VERSION >= version.parse("0.12.0"):
755
+ await self.engine.resume_generation()
756
+
757
+ async def abort_request(self, request_id: str, reset_prefix_cache: bool = True) -> dict[str, Any]:
758
+ """Abort a specific generation request.
759
+
760
+ Args:
761
+ request_id: The ID of the request to abort.
762
+
763
+ Returns:
764
+ dict[str, Any]: Dictionary containing abort result.
765
+ """
766
+ try:
767
+ request_states = self.engine.output_processor.request_states
768
+ req_state = request_states.get(request_id)
769
+
770
+ if req_state is None:
771
+ return {"aborted": False, "error": f"Request {request_id} not found"}
772
+
773
+ # Create abort output and put it to the queue
774
+ from vllm.v1.engine import FinishReason
775
+
776
+ request_output = req_state.make_request_output(
777
+ [], pooling_output=None, finish_reason=FinishReason.ABORT, stop_reason=None
778
+ )
779
+ req_state.queue.put(request_output)
780
+
781
+ # Abort in output processor and engine core
782
+ self.engine.output_processor.abort_requests([request_id])
783
+ await self.engine.engine_core.abort_requests_async([request_id])
784
+
785
+ # Try to reset prefix cache to ensure clean state
786
+ if reset_prefix_cache:
787
+ await self.clear_kv_cache()
788
+ logger.info(f"Prefix cache reset after abort request {request_id}")
789
+
790
+ logger.info(f"Aborted request: {request_id}")
791
+ return {"aborted": True, "request_id": request_id}
792
+
793
+ except Exception as e:
794
+ logger.error(f"Error aborting request {request_id}: {e}")
795
+ return {"aborted": False, "request_id": request_id, "error": str(e)}
796
+
797
+ # -----------------------------------------------------------------------
798
+ # Hook methods for subclass overrides
799
+ # -----------------------------------------------------------------------
800
+
801
+ def _init_config(self, config):
802
+ """Initialise config. Override when a specific dataclass_type is needed."""
803
+ return omega_conf_to_dataclass(config)
804
+
805
+ def _init_model_config(self, model_config):
806
+ """Initialise model_config. Override when a specific dataclass_type is needed."""
807
+ return omega_conf_to_dataclass(model_config, dataclass_type=HFModelConfig)
808
+
809
+ def _validate_configs(self) -> None:
810
+ """Validate config/model_config after initialisation."""
811
+ max_position_embeddings = get_max_position_embeddings(self.model_config.hf_config)
812
+ if self.config.max_model_len is None:
813
+ self.config.max_model_len = max_position_embeddings
814
+ else:
815
+ if self.config.max_model_len > max_position_embeddings:
816
+ raise ValueError(
817
+ f"max_model_len ({self.config.max_model_len}) should be less than or equal to "
818
+ f"max_position_embeddings ({max_position_embeddings})"
819
+ )
820
+
821
+ def _post_init(self, cuda_visible_devices: str) -> None:
822
+ """Called at the end of __init__. Default logs server metadata."""
823
+ logger.info(
824
+ f"{self.__class__.__name__}, replica_rank: {self.replica_rank}, node_rank: {self.node_rank}, "
825
+ f"{get_visible_devices_keyword()}: {cuda_visible_devices}, "
826
+ f"master_address: {self._master_address}, master_port: {self._master_port}, "
827
+ f"data_parallel_rpc_port: {self._dp_rpc_port}, data_parallel_master_port: {self._dp_master_port}"
828
+ )
829
+
830
+ def _get_engine_kwargs_key(self) -> str:
831
+ """Return the key under config.engine_kwargs for this engine (e.g. 'vllm')."""
832
+ return "vllm"
833
+
834
+ def _preprocess_engine_kwargs(self, engine_kwargs: dict) -> None:
835
+ """Mutate engine_kwargs in-place before the CLI args dict is built. No-op by default."""
836
+ pass
837
+
838
+ def _get_override_generation_config(self) -> dict:
839
+ """Return the override_generation_config dict."""
840
+ # Override default generation config from hugging face model config,
841
+ # user can still override them by passing kwargs in each request.
842
+ return dict(
843
+ temperature=self.config.temperature,
844
+ top_k=self.config.top_k,
845
+ top_p=self.config.top_p,
846
+ repetition_penalty=1.0,
847
+ max_new_tokens=self.config.response_length,
848
+ )
849
+
850
+ def _apply_quantization(self) -> tuple[Optional[str], dict]:
851
+ """Process quantization config. Returns (quantization_str, hf_overrides)."""
852
+ quantization = self.config.quantization
853
+ hf_overrides = {}
854
+
855
+ if is_torch_npu_available(check_device=False):
856
+ from verl.utils.vllm.npu_vllm_patch import check_vllm_ascend_before_server_launch
857
+
858
+ check_vllm_ascend_before_server_launch()
859
+
860
+ # Handle QAT (Quantization-Aware Training) configuration
861
+ qat_config_dict = getattr(self.config, "qat", {}) or {}
862
+ if qat_config_dict.get("enable", False):
863
+ from verl.utils.qat import QATConfig, load_quantization_config
864
+
865
+ qat_config = QATConfig(**qat_config_dict)
866
+ quantization_config_dict = load_quantization_config(qat_config)
867
+ quant_method = quantization_config_dict.get("quant_method", None)
868
+
869
+ if quant_method == "modelopt":
870
+ from verl.utils.modelopt import apply_modelopt_nvfp4_patches
871
+
872
+ apply_modelopt_nvfp4_patches()
873
+ quantization = "modelopt"
874
+ elif quant_method == "compressed-tensors":
875
+ from verl.utils.qat import apply_qat_patches
876
+
877
+ apply_qat_patches()
878
+ quantization = "compressed-tensors"
879
+ else:
880
+ raise ValueError(f"Unsupported quant_method: {quant_method}")
881
+
882
+ logger.info(f"QAT quantization config injected (quant_method={quant_method})")
883
+ hf_overrides["quantization_config"] = quantization_config_dict
884
+ elif quantization is not None:
885
+ # Handle other quantization methods (fp8, torchao)
886
+ _SUPPORTED_QUANTIZATION = ["fp8", "torchao", "ascend"]
887
+ if quantization not in _SUPPORTED_QUANTIZATION:
888
+ raise ValueError(f"Currently only support {_SUPPORTED_QUANTIZATION} quantization, got: {quantization}")
889
+
890
+ if quantization == "fp8":
891
+ # Ignore MoE router layers for FP8 quantization
892
+ all_mlp_gate_layers = []
893
+ for layer in range(self.model_config.hf_config.num_hidden_layers):
894
+ all_mlp_gate_layers.append(f"model.layers.{layer}.mlp.gate")
895
+
896
+ FP8_BLOCK_QUANT_KWARGS = {
897
+ "activation_scheme": "dynamic",
898
+ "fmt": "e4m3",
899
+ "quant_method": "fp8",
900
+ "weight_block_size": [128, 128],
901
+ "ignored_layers": all_mlp_gate_layers,
902
+ }
903
+ hf_overrides["quantization_config"] = dict(FP8_BLOCK_QUANT_KWARGS)
904
+ # Apply vllm fp8 patches
905
+ # Will remove the patch after vllm support on-the-fly quant for rollout natively.
906
+ apply_vllm_fp8_patches()
907
+ # for subprocesses patching
908
+ os.environ["VERL_VLLM_FP8_QUANT_ENABLED"] = "1"
909
+
910
+ if quantization is not None and self.config.quantization_config_file is not None:
911
+ hf_overrides["quantization_config_file"] = self.config.quantization_config_file
912
+
913
+ return quantization, hf_overrides
914
+
915
+ def _get_worker_extension_cls(self) -> str:
916
+ """Return the fully-qualified colocate worker extension class name."""
917
+ return "verl.workers.rollout.vllm_rollout.utils.vLLMColocateWorkerExtension"
918
+
919
+ def _get_cli_modules(self) -> list:
920
+ """Return the list of CLI command modules used for argument parsing."""
921
+ return [vllm.entrypoints.cli.serve]
922
+
923
+ def _get_cli_description(self) -> str:
924
+ """Return the description string for the CLI argument parser."""
925
+ return "vLLM CLI"
926
+
927
+ def _get_wake_up_tags(self) -> list[str]:
928
+ """Return the tags passed to engine.wake_up(). Default includes kv_cache."""
929
+ return ["kv_cache", "weights"]
930
+
931
+ async def _sleep_hybrid(self):
932
+ """HYBRID sleep: lora adapters only need level=1; full weights need level=2."""
933
+ # Don't use engine.sleep(level=2) here
934
+ # lora only update adapter weights, so set sleep level to 1
935
+ if self.lora_as_adapter:
936
+ sleep_level = 1
937
+ else:
938
+ sleep_level = 2
939
+ await self.engine.collective_rpc("sleep", kwargs={"level": sleep_level})
940
+ if _VLLM_VERSION >= version.parse("0.17.0"):
941
+ await self.engine.reset_encoder_cache()
942
+
943
+
944
+ class vLLMReplica(RolloutReplica):
945
+ def __init__(
946
+ self,
947
+ replica_rank: int,
948
+ config: RolloutConfig,
949
+ model_config: HFModelConfig,
950
+ gpus_per_node: int = 8,
951
+ is_reward_model: bool = False,
952
+ is_teacher_model: bool = False,
953
+ ):
954
+ super().__init__(replica_rank, config, model_config, gpus_per_node, is_reward_model, is_teacher_model)
955
+ self.server_class = ray.remote(vLLMHttpServer)
956
+
957
+ async def launch_servers(self):
958
+ """Launch http server in each node."""
959
+ assert len(self.workers) == self.world_size, (
960
+ f"worker number {len(self.workers)} not equal to world size {self.world_size}"
961
+ )
962
+
963
+ self._validate_launch_requirements()
964
+
965
+ # get (node_id, CUDA_VISIBLE_DEVICES) of all workers
966
+ worker_infos = await asyncio.gather(
967
+ *[
968
+ worker.__ray_call__.remote(
969
+ lambda self: (
970
+ ray.get_runtime_context().get_node_id(),
971
+ ray.get_runtime_context().get_accelerator_ids()[get_resource_name()][0],
972
+ )
973
+ )
974
+ for worker in self.workers
975
+ ]
976
+ )
977
+ worker_cuda_visible_devices = [worker_info[1] for worker_info in worker_infos]
978
+ worker_node_ids = [worker_info[0] for worker_info in worker_infos]
979
+
980
+ # create server actor in each node with node affinity and cuda visible devices
981
+ nnodes, gpus_per_replica_node = self.nnodes, self.gpus_per_replica_node
982
+ for node_rank in range(nnodes):
983
+ workers = self.workers[node_rank * gpus_per_replica_node : (node_rank + 1) * gpus_per_replica_node]
984
+ node_cuda_visible_devices = ",".join(
985
+ worker_cuda_visible_devices[node_rank * gpus_per_replica_node : (node_rank + 1) * gpus_per_replica_node]
986
+ )
987
+ node_id = worker_node_ids[node_rank * gpus_per_replica_node]
988
+ prefix = self._get_server_name_prefix()
989
+ if self.is_reward_model:
990
+ name = f"{prefix}server_reward_{self.replica_rank}_{node_rank}"
991
+ elif self.is_teacher_model:
992
+ name = f"{prefix}server_teacher_{self.replica_rank}_{node_rank}"
993
+ else:
994
+ name = f"{prefix}server_{self.replica_rank}_{node_rank}"
995
+ server = self.server_class.options(
996
+ scheduling_strategy=ray.util.scheduling_strategies.NodeAffinitySchedulingStrategy(
997
+ node_id=node_id,
998
+ soft=False,
999
+ ),
1000
+ runtime_env={
1001
+ "env_vars": {
1002
+ "RAY_EXPERIMENTAL_NOSET_CUDA_VISIBLE_DEVICES": "1",
1003
+ "RAY_EXPERIMENTAL_NOSET_ASCEND_RT_VISIBLE_DEVICES": "1",
1004
+ # To prevent hanging or crash during synchronization of weights between actor and rollout
1005
+ # in disaggregated mode. See:
1006
+ # https://docs.vllm.ai/en/latest/usage/troubleshooting.html?h=nccl_cumem_enable#known-issues
1007
+ # https://github.com/vllm-project/vllm/blob/c6b0a7d3ba03ca414be1174e9bd86a97191b7090/vllm/worker/worker_base.py#L445
1008
+ "NCCL_CUMEM_ENABLE": "0",
1009
+ }
1010
+ },
1011
+ name=name,
1012
+ max_concurrency=self.max_concurrency,
1013
+ ).remote(
1014
+ config=self.config,
1015
+ model_config=self.model_config,
1016
+ rollout_mode=self.rollout_mode,
1017
+ workers=workers,
1018
+ replica_rank=self.replica_rank,
1019
+ node_rank=node_rank,
1020
+ gpus_per_node=gpus_per_replica_node,
1021
+ nnodes=nnodes,
1022
+ cuda_visible_devices=node_cuda_visible_devices,
1023
+ )
1024
+ self.servers.append(server)
1025
+
1026
+ # launch http server in each node
1027
+ master_address, master_port, dp_rpc_port = await self.servers[0].get_master_address.remote()
1028
+ await asyncio.gather(
1029
+ *[
1030
+ server.launch_server.remote(
1031
+ master_address=master_address, master_port=master_port, dp_rpc_port=dp_rpc_port
1032
+ )
1033
+ for server in self.servers
1034
+ ]
1035
+ )
1036
+
1037
+ # get http server address from first server
1038
+ server_address, server_port = await self.servers[0].get_server_address.remote()
1039
+ self._server_handle = self.servers[0]
1040
+ self._server_address = (
1041
+ f"[{server_address}]:{server_port}"
1042
+ if is_valid_ipv6_address(server_address)
1043
+ else f"{server_address}:{server_port}"
1044
+ )
1045
+
1046
+ async def sleep(self):
1047
+ """Sleep each rollout server."""
1048
+ # Drain DP engines for safe sleep.
1049
+ await self.servers[0].wait_for_requests_to_drain.remote()
1050
+ await asyncio.gather(*[server.sleep.remote() for server in self.servers])
1051
+
1052
+ async def abort_all_requests(self) -> dict[str, Any]:
1053
+ """Abort all ongoing generation requests across all servers.
1054
+
1055
+ Returns:
1056
+ dict[str, Any]: Combined abort results from all servers.
1057
+ """
1058
+ results = await asyncio.gather(*[server.abort_all_requests.remote() for server in self.servers])
1059
+
1060
+ total_aborted = sum(r.get("aborted_count", 0) for r in results)
1061
+ all_request_ids = []
1062
+ for r in results:
1063
+ all_request_ids.extend(r.get("request_ids", []))
1064
+
1065
+ return {
1066
+ "aborted_count": total_aborted,
1067
+ "request_ids": all_request_ids,
1068
+ "server_results": results,
1069
+ }
1070
+
1071
+ async def resume_generation(self):
1072
+ """Resume generation on all servers after abort_all_requests."""
1073
+ await asyncio.gather(*[server.resume_generation.remote() for server in self.servers])
1074
+
1075
+ async def abort_request(self, request_id: str) -> dict[str, Any]:
1076
+ """Abort a specific request. Tries all servers since we don't know which one has it.
1077
+
1078
+ Args:
1079
+ request_id: The ID of the request to abort.
1080
+
1081
+ Returns:
1082
+ dict[str, Any]: Abort result.
1083
+ """
1084
+ # TODO(petersh6): we should only abort on the server that has the request.
1085
+ results = await asyncio.gather(*[server.abort_request.remote(request_id) for server in self.servers])
1086
+
1087
+ for r in results:
1088
+ if r.get("aborted", False):
1089
+ return r
1090
+
1091
+ return {"aborted": False, "request_id": request_id, "error": "Request not found on any server"}
1092
+
1093
+ # -----------------------------------------------------------------------
1094
+ # Hook methods for subclass overrides
1095
+ # -----------------------------------------------------------------------
1096
+
1097
+ def _validate_launch_requirements(self) -> None:
1098
+ """Validate requirements before launching. Override in subclasses."""
1099
+ # NOTE: We always use MP Executor backend whether it's single-node or multi-node.
1100
+ # For multi-node without DP (e.g TP=16), need vllm>=0.11.1, https://github.com/vllm-project/vllm/pull/23691
1101
+ if self.config.data_parallel_size == 1 and self.nnodes > 1:
1102
+ assert _VLLM_VERSION >= version.parse("0.11.1"), (
1103
+ "For multi-node MP Executor, either (1) set data_parallel_size > 1 or (2) upgrade vLLM to >= 0.11.1"
1104
+ )
1105
+
1106
+ def _get_server_name_prefix(self) -> str:
1107
+ """Return the Ray actor name prefix (e.g. 'vllm_' or 'vllm_omni_')."""
1108
+ return "vllm_"