Coverage for transformer_lens/model_bridge/remote_bridge.py: 84%
100 statements
« prev ^ index » next coverage.py v7.10.1, created at 2026-11-25 00:28 +0000
« prev ^ index » next coverage.py v7.10.1, created at 2026-11-25 00:28 +0000
1"""Non-torch bridge: vLLM workers, Inspect remote providers."""
2from __future__ import annotations
4import warnings
5from typing import Any, Callable, List, Optional, Tuple, Union
7from transformer_lens.hook_points import HookIntrospectionMixin, HookPoint
8from transformer_lens.model_bridge.bridge_core import (
9 BridgeCore,
10 _validate_execution_kwargs,
11)
12from transformer_lens.model_bridge.driver_protocol import (
13 ForwardResult,
14 TensorLike,
15 to_torch,
16 validate_driver,
17)
20class RemoteBridge(BridgeCore, HookIntrospectionMixin):
21 """Bridge for backends with no local ``nn.Module`` (vLLM, Inspect).
23 No nn.Module parentage strips the torch-only surface; driver pre-declares
24 ``supported_hook_points`` (no model to walk).
25 """
27 def __init__(
28 self,
29 adapter: Any,
30 tokenizer: Any,
31 driver: Any,
32 ) -> None:
33 if not driver.supported_hook_points:
34 raise ValueError(
35 "RemoteBridge requires driver.supported_hook_points to be "
36 "non-empty: non-torch drivers own the hook namespace because "
37 "there is no local model for the bridge to walk."
38 )
39 BridgeCore.__init__(self, adapter, tokenizer, driver)
40 # No local device; tensor.to(None) is a no-op so downstream patterns degrade cleanly.
41 self.cfg.device = None
42 # HookPoint is nn.Module-backed but RemoteBridge isn't an nn.Module —
43 # named_modules() walks don't apply; only registry lookup matters.
44 for name in driver.supported_hook_points:
45 hp = HookPoint()
46 hp.name = name
47 self._hook_registry[name] = hp
48 self._hook_registry_initialized = True
49 validate_driver(self._driver, after_bridge_construction=True)
51 @staticmethod
52 def boot_vllm(*args: Any, **kwargs: Any) -> "RemoteBridge":
53 """Boot a model via vLLM. Returns a RemoteBridge wrapping a VLLMDriver.
55 Mirrors ``TransformerBridge.boot_transformers``. Lazy import so
56 ``remote_bridge`` itself stays vLLM-agnostic — only callers of this
57 method need vLLM installed. See :func:`sources.vllm.boot_vllm` for kwargs.
58 """
59 from .sources.vllm import boot_vllm as _boot_vllm
61 return _boot_vllm(*args, **kwargs)
63 @staticmethod
64 def boot_inspect(*args: Any, **kwargs: Any) -> "RemoteBridge":
65 """Boot a model via an inspect_ai provider. Returns a RemoteBridge wrapping
66 an InspectDriver. Lazy import keeps remote_bridge inspect-agnostic. See
67 :func:`sources.inspect.boot_inspect` for kwargs."""
68 from .sources.inspect import boot_inspect as _boot_inspect
70 return _boot_inspect(*args, **kwargs)
72 def _scan_existing_hooks(self, module: Any, prefix: str = "") -> None:
73 """No-op: registry built from driver declarations in __init__."""
75 def forward(
76 self,
77 input: Any = None,
78 *,
79 return_type: str | None = "logits",
80 loss_per_token: bool = False,
81 labels: Any = None,
82 **kwargs: Any,
83 ) -> Any:
84 """Tokenize → driver.forward → replay captures → finalize per return_type.
86 Explicit ``labels`` use shifted causal loss; remote encoder-decoder loss
87 is unsupported.
88 """
89 # Drivers drop unknown kwargs, so a misplaced hook/cache option would be a silent no-op.
90 _validate_execution_kwargs(kwargs, "forward")
91 # Early copy of _finalize_return's gate — fail before the wasted remote forward.
92 self._check_loss_supported(return_type)
93 self._reject_stop_at_layer(kwargs.pop("stop_at_layer", None))
94 if isinstance(input, str):
95 kwargs["input_ids"] = self.to_tokens(input) # BOS-aware, matches boot_transformers
96 elif isinstance(input, list) and any(isinstance(item, str) for item in input):
97 # Would otherwise be treated as raw input_ids and crash deep in numpy.
98 raise TypeError(
99 "RemoteBridge.forward received a list of strings; batched string "
100 "input is unsupported here. Pass a single str, or tokenize with "
101 "to_tokens() and pass token ids."
102 )
103 elif input is not None: 103 ↛ 108line 103 didn't jump to line 108 because the condition on line 103 was always true
104 kwargs["input_ids"] = input
106 # Only request hooks with a registered handler, so a plain forward(tokens)
107 # ships logits alone instead of the full residual decomposition every call.
108 if "capture" not in kwargs: 108 ↛ 113line 108 didn't jump to line 113 because the condition on line 108 was always true
109 kwargs["capture"] = tuple(
110 name for name, hp in self._hook_registry.items() if hp.fwd_hooks
111 )
113 result: ForwardResult = self._driver.forward(**kwargs)
114 if result.captured:
115 self._replay_captures(result.captured)
117 logits: Any = result.logits
118 if logits is not None and not isinstance(logits, TensorLike): 118 ↛ 119line 118 didn't jump to line 119 because the condition on line 118 was never true
119 return logits # weird shape — let caller handle
120 if logits is not None:
121 logits = to_torch(logits)
122 if labels is not None:
123 if not isinstance(labels, TensorLike): 123 ↛ 124line 123 didn't jump to line 124 because the condition on line 123 was never true
124 raise TypeError(f"labels must be tensor-like, got {type(labels).__name__}")
125 labels = to_torch(labels)
127 return self._finalize_return(
128 return_type,
129 logits,
130 kwargs.get("input_ids"),
131 attention_mask=kwargs.get("attention_mask"),
132 labels=labels,
133 is_audio_model=getattr(self.cfg, "is_audio_model", False),
134 is_visual_model=getattr(self.cfg, "is_visual_model", False),
135 loss_per_token=loss_per_token,
136 )
138 def run_with_hooks(
139 self,
140 input: Any,
141 fwd_hooks: List[Tuple[Union[str, Callable], Callable]] = [],
142 bwd_hooks: List[Tuple[Union[str, Callable], Callable]] = [],
143 reset_hooks_end: bool = True,
144 clear_contexts: bool = False,
145 return_type: Optional[str] = "logits",
146 stop_at_layer: Optional[int] = None,
147 start_at_layer: Optional[int] = None,
148 remove_batch_dim: bool = False,
149 **kwargs: Any,
150 ) -> Any:
151 """Run with hooks. Remote fwd_hooks fire post-forward on captured
152 activations (read-only) — they can't alter the computation, so warn; use
153 ``intervene=`` specs to mutate. bwd_hooks are unsupported (no backward)."""
154 if bwd_hooks:
155 raise NotImplementedError(
156 "RemoteBridge has no backward pass; bwd_hooks are unsupported."
157 )
158 self._reject_stop_at_layer(stop_at_layer)
159 self._reject_start_at_layer(start_at_layer)
160 if fwd_hooks:
161 warnings.warn(
162 "RemoteBridge fwd_hooks fire on already-captured activations (read-only): "
163 "a hook that returns a modified tensor does NOT change the forward "
164 "computation or logits — the return is discarded. To intervene on the "
165 "computation, pass intervene={hook_name: {'op': ...}} to "
166 "forward()/run_with_cache().",
167 UserWarning,
168 stacklevel=2,
169 )
170 return super().run_with_hooks(
171 input,
172 fwd_hooks=fwd_hooks,
173 bwd_hooks=bwd_hooks,
174 reset_hooks_end=reset_hooks_end,
175 clear_contexts=clear_contexts,
176 return_type=return_type,
177 remove_batch_dim=remove_batch_dim,
178 **kwargs,
179 )
181 @staticmethod
182 def _reject_stop_at_layer(stop_at_layer: Any) -> None:
183 # BridgeCore's stop hooks need a local `blocks` tree; silently ignoring
184 # the kwarg would lie about compute cost.
185 if stop_at_layer is not None:
186 raise NotImplementedError(
187 "RemoteBridge does not support stop_at_layer: the remote engine "
188 "always runs the full forward pass."
189 )
191 @staticmethod
192 def _reject_start_at_layer(start_at_layer: Any) -> None:
193 # Residual-stream injection needs a local `blocks` tree; the remote engine
194 # only runs a full forward from tokens.
195 if start_at_layer is not None: 195 ↛ 196line 195 didn't jump to line 196 because the condition on line 195 was never true
196 raise NotImplementedError(
197 "RemoteBridge does not support start_at_layer: the remote engine "
198 "always runs the full forward pass from tokens."
199 )
201 def run_with_cache(self, *args: Any, **kwargs: Any) -> Any:
202 """Cache via driver captures; stop/start_at_layer and incl_bwd rejected."""
203 self._reject_stop_at_layer(kwargs.get("stop_at_layer"))
204 self._reject_start_at_layer(kwargs.get("start_at_layer"))
205 if kwargs.get("incl_bwd"): 205 ↛ 208line 205 didn't jump to line 208 because the condition on line 205 was never true
206 # Captures come back as detached tensors from the remote engine, so there
207 # is no local graph for backward() to walk.
208 raise NotImplementedError(
209 "RemoteBridge has no backward pass; run_with_cache(incl_bwd=True) is "
210 "unsupported."
211 )
212 return super().run_with_cache(*args, **kwargs)
214 def to_tokens(self, input: Any, prepend_bos: bool | None = None, truncate: bool = True) -> Any:
215 """Tokenize a string with the same BOS handling as ``TransformerBridge``.
217 Mirrors ``cfg.default_prepend_bos`` / ``tokenizer_prepends_bos`` so
218 ``boot_inspect(m).run_with_cache("text")`` matches ``boot_transformers(m)``
219 on the same string — a bare ``encode`` (no BOS) would silently diverge.
220 """
221 from transformer_lens import utilities as utils
223 assert self.tokenizer is not None, "Tokenizer must be set."
224 if prepend_bos is None: 224 ↛ 226line 224 didn't jump to line 226 because the condition on line 224 was always true
225 prepend_bos = getattr(self.cfg, "default_prepend_bos", True)
226 tokenizer_prepends_bos = getattr(self.cfg, "tokenizer_prepends_bos", True)
227 if prepend_bos and not tokenizer_prepends_bos: 227 ↛ 228line 227 didn't jump to line 228 because the condition on line 227 was never true
228 bos = self.tokenizer.bos_token
229 encodes_atomically = (
230 bos is not None
231 and len(self.tokenizer(bos, add_special_tokens=False)["input_ids"]) == 1
232 )
233 if encodes_atomically:
234 input = utils.get_input_with_manually_prepended_bos(bos, input)
235 # else: the fallback BOS is not an atom in this vocab (e.g.
236 # '<|endoftext|>' installed on BERT); prepending the string would
237 # tokenize to subword garbage, so skip rather than pollute the input.
238 if isinstance(input, str): 238 ↛ 242line 238 didn't jump to line 242 because the condition on line 238 was always true
239 input = [input]
240 # A single sequence never needs padding; only pad when batching (which also
241 # avoids requiring a pad_token on tokenizers that lack one, e.g. raw gpt2).
242 tokens = self.tokenizer(
243 input,
244 return_tensors="pt",
245 padding=len(input) > 1,
246 truncation=truncate,
247 max_length=self.cfg.n_ctx if truncate else None,
248 )["input_ids"]
249 if not prepend_bos and tokenizer_prepends_bos: 249 ↛ 250line 249 didn't jump to line 250 because the condition on line 249 was never true
250 tokens = utils.get_tokens_with_bos_removed(self.tokenizer, tokens)
251 return tokens
253 def __enter__(self) -> "RemoteBridge":
254 """Use as a context manager so the engine is released on exit:
255 ``with RemoteBridge.boot_vllm(...) as bridge: ...``."""
256 return self
258 def __exit__(self, *exc: Any) -> None:
259 self.close()
261 def __del__(self) -> None:
262 # Best-effort safety net for notebooks that drop the bridge without
263 # close() — repeated boot_vllm would otherwise OOM. close() is idempotent.
264 try:
265 self.close()
266 except Exception:
267 pass