Skip to content

Commit 00a5645

Browse files
authored
Merge pull request #168 from CharlesR-W/feature/vllm-server-mode
feat: add --server-port option to connect to external vLLM server
2 parents d97c1e1 + f207027 commit 00a5645

8 files changed

Lines changed: 371 additions & 111 deletions

File tree

‎delphi/__main__.py‎

Lines changed: 122 additions & 106 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
)
2020

2121
from delphi import logger
22-
from delphi.clients import Offline, OpenRouter
22+
from delphi.clients import OpenRouter, ServerClient
2323
from delphi.config import RunConfig
2424
from delphi.explainers import ContrastiveExplainer, DefaultExplainer, NoOpExplainer
2525
from delphi.explainers.explainer import ExplainerResult
@@ -85,14 +85,12 @@ def create_neighbours(
8585
)
8686

8787
for hookpoint in hookpoints:
88-
8988
if constructor_cfg.neighbours_type == "co-occurrence":
9089
neighbour_calculator = NeighbourCalculator(
9190
cache_dir=latents_path / hookpoint, number_of_neighbours=250
9291
)
9392

9493
elif constructor_cfg.neighbours_type == "decoder_similarity":
95-
9694
neighbour_calculator = NeighbourCalculator(
9795
autoencoder=saes[hookpoint].to("cuda"), number_of_neighbours=250
9896
)
@@ -142,7 +140,21 @@ async def process_cache(
142140
tokenizer=tokenizer,
143141
)
144142

145-
if run_cfg.explainer_provider == "offline":
143+
if run_cfg.server_url and run_cfg.server_port is not None:
144+
raise ValueError("Set only one of server_url and server_port")
145+
if run_cfg.server_url or run_cfg.server_port is not None:
146+
if run_cfg.explainer_provider != "offline":
147+
raise ValueError("Server options require explainer_provider=offline")
148+
if run_cfg.server_port is not None and not 1 <= run_cfg.server_port <= 65535:
149+
raise ValueError("server_port must be between 1 and 65535")
150+
llm_client = ServerClient(
151+
run_cfg.explainer_model,
152+
run_cfg.server_url or f"http://localhost:{run_cfg.server_port}/v1/",
153+
api_key=os.environ.get("SERVER_API_KEY"),
154+
)
155+
elif run_cfg.explainer_provider == "offline":
156+
from .clients.offline import Offline
157+
146158
llm_client = Offline(
147159
run_cfg.explainer_model,
148160
max_memory=run_cfg.max_memory,
@@ -171,124 +183,128 @@ async def process_cache(
171183
f"Explainer provider {run_cfg.explainer_provider} not supported"
172184
)
173185

174-
if not run_cfg.explainer == "none":
175-
176-
def explainer_postprocess(result):
177-
with open(explanations_path / f"{result.record.latent}.txt", "wb") as f:
178-
f.write(orjson.dumps(result.explanation))
186+
try:
187+
if not run_cfg.explainer == "none":
179188

180-
return result
181-
182-
if run_cfg.constructor_cfg.non_activating_source == "FAISS":
183-
explainer = ContrastiveExplainer(
184-
llm_client,
185-
threshold=0.3,
186-
verbose=run_cfg.verbose,
187-
)
188-
else:
189-
explainer = DefaultExplainer(
190-
llm_client,
191-
threshold=0.3,
192-
verbose=run_cfg.verbose,
193-
)
189+
def explainer_postprocess(result):
190+
with open(explanations_path / f"{result.record.latent}.txt", "wb") as f:
191+
f.write(orjson.dumps(result.explanation))
194192

195-
explainer_pipe = Pipe(
196-
process_wrapper(explainer, postprocess=explainer_postprocess)
197-
)
198-
else:
193+
return result
199194

200-
def none_postprocessor(result):
201-
# Load the explanation from disk
202-
explanation_path = explanations_path / f"{result.record.latent}.txt"
203-
if not explanation_path.exists():
204-
raise FileNotFoundError(
205-
f"Explanation file {explanation_path} does not exist. "
206-
"Make sure to run an explainer pipeline first."
195+
if run_cfg.constructor_cfg.non_activating_source == "FAISS":
196+
explainer = ContrastiveExplainer(
197+
llm_client,
198+
threshold=0.3,
199+
verbose=run_cfg.verbose,
207200
)
208-
209-
with open(explanation_path, "rb") as f:
210-
return ExplainerResult(
211-
record=result.record,
212-
explanation=orjson.loads(f.read()),
201+
else:
202+
explainer = DefaultExplainer(
203+
llm_client,
204+
threshold=0.3,
205+
verbose=run_cfg.verbose,
213206
)
214207

215-
explainer_pipe = Pipe(
216-
process_wrapper(
217-
NoOpExplainer(),
218-
postprocess=none_postprocessor,
208+
explainer_pipe = Pipe(
209+
process_wrapper(explainer, postprocess=explainer_postprocess)
219210
)
220-
)
221-
222-
# Builds the record from result returned by the pipeline
223-
def scorer_preprocess(result):
224-
if isinstance(result, list):
225-
result = result[0]
226-
227-
record = result.record
228-
record.explanation = result.explanation
229-
record.extra_examples = record.not_active
230-
return record
231-
232-
# Saves the score to a file
233-
def scorer_postprocess(result, score_dir):
234-
safe_latent_name = str(result.record.latent).replace("/", "--")
235-
236-
with open(score_dir / f"{safe_latent_name}.txt", "wb") as f:
237-
f.write(orjson.dumps(result.score))
211+
else:
238212

239-
scorers = []
240-
for scorer_name in run_cfg.scorers:
241-
scorer_path = scores_path / scorer_name
242-
scorer_path.mkdir(parents=True, exist_ok=True)
213+
def none_postprocessor(result):
214+
# Load the explanation from disk
215+
explanation_path = explanations_path / f"{result.record.latent}.txt"
216+
if not explanation_path.exists():
217+
raise FileNotFoundError(
218+
f"Explanation file {explanation_path} does not exist. "
219+
"Make sure to run an explainer pipeline first."
220+
)
221+
222+
with open(explanation_path, "rb") as f:
223+
return ExplainerResult(
224+
record=result.record,
225+
explanation=orjson.loads(f.read()),
226+
)
227+
228+
explainer_pipe = Pipe(
229+
process_wrapper(
230+
NoOpExplainer(),
231+
postprocess=none_postprocessor,
232+
)
233+
)
243234

244-
if scorer_name == "simulation":
245-
if isinstance(llm_client, Offline):
246-
scorer = OpenAISimulator(
247-
llm_client, tokenizer=tokenizer, all_at_once=True
235+
# Builds the record from result returned by the pipeline
236+
def scorer_preprocess(result):
237+
if isinstance(result, list):
238+
result = result[0]
239+
240+
record = result.record
241+
record.explanation = result.explanation
242+
record.extra_examples = record.not_active
243+
return record
244+
245+
# Saves the score to a file
246+
def scorer_postprocess(result, score_dir):
247+
safe_latent_name = str(result.record.latent).replace("/", "--")
248+
249+
with open(score_dir / f"{safe_latent_name}.txt", "wb") as f:
250+
f.write(orjson.dumps(result.score))
251+
252+
scorers = []
253+
for scorer_name in run_cfg.scorers:
254+
scorer_path = scores_path / scorer_name
255+
scorer_path.mkdir(parents=True, exist_ok=True)
256+
257+
if scorer_name == "simulation":
258+
if llm_client.supports_prompt_logprobs:
259+
scorer = OpenAISimulator(
260+
llm_client, tokenizer=tokenizer, all_at_once=True
261+
)
262+
else:
263+
scorer = OpenAISimulator(
264+
llm_client, tokenizer=tokenizer, all_at_once=False
265+
)
266+
elif scorer_name == "fuzz":
267+
scorer = FuzzingScorer(
268+
llm_client,
269+
n_examples_shown=run_cfg.num_examples_per_scorer_prompt,
270+
verbose=run_cfg.verbose,
271+
log_prob=run_cfg.log_probs,
272+
fuzz_type=run_cfg.fuzz_type,
248273
)
249-
else:
250-
scorer = OpenAISimulator(
251-
llm_client, tokenizer=tokenizer, all_at_once=False
274+
elif scorer_name == "detection":
275+
scorer = DetectionScorer(
276+
llm_client,
277+
n_examples_shown=run_cfg.num_examples_per_scorer_prompt,
278+
verbose=run_cfg.verbose,
279+
log_prob=run_cfg.log_probs,
252280
)
253-
elif scorer_name == "fuzz":
254-
scorer = FuzzingScorer(
255-
llm_client,
256-
n_examples_shown=run_cfg.num_examples_per_scorer_prompt,
257-
verbose=run_cfg.verbose,
258-
log_prob=run_cfg.log_probs,
259-
fuzz_type=run_cfg.fuzz_type,
260-
)
261-
elif scorer_name == "detection":
262-
scorer = DetectionScorer(
263-
llm_client,
264-
n_examples_shown=run_cfg.num_examples_per_scorer_prompt,
265-
verbose=run_cfg.verbose,
266-
log_prob=run_cfg.log_probs,
281+
else:
282+
raise ValueError(f"Scorer {scorer_name} not supported")
283+
284+
wrapped_scorer = process_wrapper(
285+
scorer,
286+
preprocess=scorer_preprocess,
287+
postprocess=partial(scorer_postprocess, score_dir=scorer_path),
267288
)
268-
else:
269-
raise ValueError(f"Scorer {scorer_name} not supported")
289+
scorers.append(wrapped_scorer)
270290

271-
wrapped_scorer = process_wrapper(
272-
scorer,
273-
preprocess=scorer_preprocess,
274-
postprocess=partial(scorer_postprocess, score_dir=scorer_path),
291+
pipeline = Pipeline(
292+
dataset,
293+
explainer_pipe,
294+
Pipe(*scorers),
275295
)
276-
scorers.append(wrapped_scorer)
277296

278-
pipeline = Pipeline(
279-
dataset,
280-
explainer_pipe,
281-
Pipe(*scorers),
282-
)
283-
284-
if run_cfg.pipeline_num_proc > 1 and run_cfg.explainer_provider == "openrouter":
285-
print(
286-
"OpenRouter does not support multiprocessing,"
287-
" setting pipeline_num_proc to 1"
288-
)
289-
run_cfg.pipeline_num_proc = 1
297+
if run_cfg.pipeline_num_proc > 1 and run_cfg.explainer_provider == "openrouter":
298+
print(
299+
"OpenRouter does not support multiprocessing,"
300+
" setting pipeline_num_proc to 1"
301+
)
302+
run_cfg.pipeline_num_proc = 1
290303

291-
await pipeline.run(run_cfg.pipeline_num_proc)
304+
await pipeline.run(run_cfg.pipeline_num_proc)
305+
finally:
306+
if isinstance(llm_client, ServerClient):
307+
await llm_client.close()
292308

293309

294310
def populate_cache(

‎delphi/clients/__init__.py‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
from .client import Client
2-
from .offline import Offline
32
from .openrouter import OpenRouter
3+
from .server import ServerClient
44

5-
__all__ = ["Client", "OpenRouter", "Offline"]
5+
__all__ = ["Client", "OpenRouter", "Offline", "ServerClient"]
6+
7+
8+
def __getattr__(name):
9+
if name == "Offline":
10+
from .offline import Offline
11+
12+
return Offline
13+
raise AttributeError(name)

‎delphi/clients/client.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
11
from abc import ABC, abstractmethod
22
from dataclasses import dataclass
3-
from typing import Union
3+
from typing import Any, Union
44

55

66
@dataclass
77
class Response:
88
text: str
9-
logprobs: list[float] | None = None
10-
prompt_logprobs: list[float] | None = None
9+
logprobs: list[Any] | None = None
10+
prompt_logprobs: list[Any] | None = None
1111

1212

1313
class Client(ABC):
14+
supports_prompt_logprobs = False
15+
1416
def __init__(self, model: str):
1517
self.model = model
1618

‎delphi/clients/offline.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ class Statistics:
3838

3939

4040
class Offline(Client):
41+
supports_prompt_logprobs = True
42+
4143
provider = "offline"
4244

4345
def __init__(

0 commit comments

Comments
 (0)