outsider86 commited on
Commit
5d1aee5
·
verified ·
1 Parent(s): 14e702c

Package exact adaptive implementation: code/deployment/model_server/policy_wrapper.py

Browse files
models/piper-pick-white-block-25hz-qwenpi-v3-adaptive-left-exclude-gripper-native-controls13-gb32-50k-20260905/code/deployment/model_server/policy_wrapper.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 starVLA community. All rights reserved.
2
+ # Licensed under the MIT License.
3
+ """Policy server wrapper.
4
+
5
+ Encapsulates a `baseframework` instance plus a :class:`PolicyNormProcessor`
6
+ that reuses the *training-time* :class:`ComposedModalityTransform` for action
7
+ un-normalization (no hand-rolled math). The websocket server returns
8
+ already-unnormalized actions.
9
+
10
+ Client-side responsibilities that REMAIN on the client:
11
+ - environment-specific adapters (image_history, gripper sticky, action
12
+ ensembling)
13
+ - chunk-cache scheduling (`step % chunk_size == 0` triggers a new infer)
14
+
15
+ Exposed API:
16
+ - ``metadata`` (dict, sent at handshake): ``action_chunk_size``,
17
+ ``available_unnorm_keys``, ``action_keys``, ``state_keys``.
18
+ - ``predict_action(examples, unnorm_key=None, **kwargs)`` returns
19
+ ``{"actions": np.ndarray[B, T, action_dim]}``.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import logging
25
+ from typing import Any, Dict, List, Mapping, Optional, Sequence
26
+
27
+ import numpy as np
28
+ import torch
29
+
30
+ from starVLA.model.framework.base_framework import baseframework, merge_config_overrides
31
+ from starVLA.model.framework.share_tools import read_mode_config
32
+
33
+ from deployment.model_server.policy_norm_processor import PolicyNormProcessor
34
+ from deployment.model_server.action_constraints import GripperConstraint
35
+
36
+
37
+ def _training_obs_image_size(model_cfg: Dict[str, Any]) -> Optional[List[int]]:
38
+ """Return training image size metadata when it is explicitly configured.
39
+
40
+ This is only a consistency check for eval clients. It is not used to infer
41
+ camera order or to rewrite eval observations.
42
+ """
43
+ vla_data_cfg = model_cfg.get("datasets", {}).get("vla_data", {})
44
+ size = vla_data_cfg.get("obs_image_size") or vla_data_cfg.get("image_size")
45
+ if size is None and "default_image_resolution" in vla_data_cfg:
46
+ default_resolution = vla_data_cfg["default_image_resolution"]
47
+ if isinstance(default_resolution, (list, tuple)) and len(default_resolution) >= 2:
48
+ size = default_resolution[-2:]
49
+ if not isinstance(size, (list, tuple)) or len(size) != 2:
50
+ return None
51
+ return [int(size[0]), int(size[1])]
52
+
53
+
54
+ class PolicyServerWrapper:
55
+ """Wraps a `baseframework` for use as a websocket-server policy."""
56
+
57
+ def __init__(
58
+ self,
59
+ ckpt_path: str,
60
+ device: str = "cuda",
61
+ use_bf16: bool = False,
62
+ unnorm_key: Optional[str] = None,
63
+ config_overrides: Sequence[str] | None = None,
64
+ gripper_constraint: Mapping[str, Any] | None = None,
65
+ ) -> None:
66
+ self._ckpt_path = str(ckpt_path)
67
+
68
+ logging.info("PolicyServerWrapper: loading framework from %s", self._ckpt_path)
69
+ framework = baseframework.from_pretrained(self._ckpt_path, config_overrides=config_overrides)
70
+ if use_bf16:
71
+ framework = framework.to(torch.bfloat16)
72
+ framework = framework.to(device).eval()
73
+ self._framework = framework
74
+ self._supports_rtc = callable(getattr(framework, "predict_action_realtime", None))
75
+
76
+ # Co-located metadata.
77
+ model_cfg, norm_stats = read_mode_config(self._ckpt_path)
78
+ model_cfg = merge_config_overrides(model_cfg, config_overrides)
79
+ self._model_cfg = model_cfg
80
+ self._gripper_constraint = (
81
+ GripperConstraint.from_mapping(gripper_constraint)
82
+ if gripper_constraint is not None
83
+ else None
84
+ )
85
+
86
+ # The neural action horizon normally is the executable chunk length.
87
+ # Representations such as B-splines may predict fewer parameters and
88
+ # decode them to a longer executable chunk before returning here.
89
+ action_model_cfg = model_cfg["framework"]["action_model"]
90
+ representation_cfg = model_cfg["framework"].get("action_representation", {})
91
+
92
+ self._variable_action_horizon = (
93
+ representation_cfg.get("execution_horizon_mode")
94
+ == "predicted_duration_sum"
95
+ )
96
+ self._max_action_chunk_size = None
97
+ if self._variable_action_horizon:
98
+ self._action_chunk_size = None
99
+ self._max_action_chunk_size = int(
100
+ representation_cfg["max_native_horizon"]
101
+ )
102
+ if self._max_action_chunk_size < 1:
103
+ raise ValueError("Adaptive max_native_horizon must be positive")
104
+ elif "executable_horizon" in representation_cfg:
105
+ self._action_chunk_size = int(representation_cfg["executable_horizon"])
106
+ elif "action_horizon" in action_model_cfg:
107
+ self._action_chunk_size = int(action_model_cfg["action_horizon"])
108
+ elif "future_action_window_size" in action_model_cfg:
109
+ self._action_chunk_size = int(action_model_cfg["future_action_window_size"]) + 1
110
+ else:
111
+ raise ValueError(
112
+ f"PolicyServerWrapper: no action_horizon or future_action_window_size found in model config for {self._ckpt_path}"
113
+ )
114
+ # Cache of PolicyNormProcessor instances per unnorm_key.
115
+ # For single-dataset ckpts unnorm_key is auto-selected; for multi-dataset
116
+ # ckpts clients must pass unnorm_key per request.
117
+ self._default_unnorm_key = unnorm_key
118
+ self._norm_processors: Dict[str, PolicyNormProcessor] = {}
119
+
120
+ # Peek at available keys without building a full processor.
121
+ self._available_unnorm_keys: List[str] = list(norm_stats.keys())
122
+
123
+ # Eagerly build when unambiguous; defer for multi-key / no explicit key.
124
+ if unnorm_key is not None or len(self._available_unnorm_keys) == 1:
125
+ default_proc = self._get_processor(unnorm_key)
126
+ self._default_unnorm_key = default_proc.unnorm_key
127
+ logging.info(
128
+ "PolicyServerWrapper ready: action_chunk_size=%s, variable=%s, "
129
+ "default_unnorm_key=%s, available_unnorm_keys=%s, action_keys=%s, state_keys=%s",
130
+ self._action_chunk_size,
131
+ self._variable_action_horizon,
132
+ default_proc.unnorm_key,
133
+ default_proc.available_unnorm_keys,
134
+ default_proc.action_keys,
135
+ default_proc.state_keys,
136
+ )
137
+ else:
138
+ logging.info(
139
+ "PolicyServerWrapper ready (multi-key): action_chunk_size=%d, "
140
+ "available_unnorm_keys=%s — clients must pass unnorm_key per request.",
141
+ self._action_chunk_size,
142
+ self._available_unnorm_keys,
143
+ )
144
+
145
+ def _get_processor(self, unnorm_key: Optional[str]) -> PolicyNormProcessor:
146
+ cache_key = unnorm_key if unnorm_key is not None else "__default__"
147
+ if cache_key not in self._norm_processors:
148
+ self._norm_processors[cache_key] = PolicyNormProcessor(
149
+ self._ckpt_path, unnorm_key=unnorm_key
150
+ )
151
+ return self._norm_processors[cache_key]
152
+
153
+ def get_norm_processor(self, unnorm_key: Optional[str] = None) -> PolicyNormProcessor:
154
+ """Public accessor for the per-unnorm_key normalization processor.
155
+
156
+ Protocol adapters (e.g. the GR00T ZMQ compat server) use this to read
157
+ the training-time ``action_keys`` / ``state_keys`` and their per-key
158
+ dims so they can split the flat action chunk into named groups.
159
+ """
160
+ return self._get_processor(
161
+ unnorm_key if unnorm_key is not None else self._default_unnorm_key
162
+ )
163
+
164
+ @property
165
+ def metadata(self) -> Dict[str, Any]:
166
+ """Model-invariant metadata; sent to client at websocket handshake."""
167
+ base = {
168
+ "env": "starvla_policy_server",
169
+ "ckpt_path": self._ckpt_path,
170
+ "action_chunk_size": self._action_chunk_size,
171
+ "action_chunk_size_variable": self._variable_action_horizon,
172
+ "max_action_chunk_size": self._max_action_chunk_size,
173
+ "action_length_field": (
174
+ "action_lengths" if self._variable_action_horizon else None
175
+ ),
176
+ "available_unnorm_keys": self._available_unnorm_keys,
177
+ "default_unnorm_key": self._default_unnorm_key,
178
+ "training_data_mix": self._model_cfg.get("datasets", {}).get("vla_data", {}).get("data_mix"),
179
+ "training_obs_image_size": _training_obs_image_size(self._model_cfg),
180
+ "action_representation": self._model_cfg.get("framework", {}).get(
181
+ "action_representation", {"type": "direct"}
182
+ ),
183
+ "eval_image_contract": (
184
+ "Eval clients must explicitly choose image count and order. "
185
+ "The server does not infer or reorder camera views from training config."
186
+ ),
187
+ "supports_inference_time_rtc": self._supports_rtc,
188
+ "rtc_action_coordinates": "Client sends previous chunks in environment coordinates; server normalizes them.",
189
+ "gripper_constraint": (
190
+ self._gripper_constraint.as_dict()
191
+ if self._gripper_constraint is not None
192
+ else None
193
+ ),
194
+ }
195
+ # Enrich with per-embodiment keys when a default processor already exists.
196
+ if self._default_unnorm_key is not None:
197
+ proc = self._get_processor(self._default_unnorm_key)
198
+ base["action_keys"] = proc.action_keys
199
+ base["state_keys"] = proc.state_keys
200
+ return base
201
+
202
+ def predict_action(
203
+ self,
204
+ examples: List[dict],
205
+ unnorm_key: Optional[str] = None,
206
+ **kwargs,
207
+ ) -> Dict[str, np.ndarray]:
208
+ """Run the framework, then un-normalize via training-time transforms.
209
+
210
+ Args:
211
+ examples: list of dicts (each with ``image`` / ``lang`` / optional ``state``).
212
+ unnorm_key: dataset key for un-normalization stats. ``None`` -->
213
+ use the wrapper's default (auto-picked at startup).
214
+ **kwargs: forwarded to the framework's ``predict_action``
215
+ (``do_sample``, ``use_ddim``, ``num_ddim_steps``, ...).
216
+
217
+ Returns:
218
+ ``{"actions": np.ndarray[B, T, D]}`` -- un-normalized.
219
+ """
220
+ effective_key = unnorm_key if unnorm_key is not None else self._default_unnorm_key
221
+ if effective_key is None:
222
+ if len(self._available_unnorm_keys) == 1:
223
+ effective_key = self._available_unnorm_keys[0]
224
+ else:
225
+ raise ValueError(
226
+ f"predict_action: unnorm_key not specified and no default set. "
227
+ f"Pass one of {self._available_unnorm_keys}."
228
+ )
229
+ proc = self._get_processor(effective_key)
230
+
231
+ out = self._framework.predict_action(examples=examples, **kwargs)
232
+ normalized = np.asarray(out["normalized_actions"]) # (B, T, D)
233
+ action_lengths = out.get("action_lengths")
234
+ if self._variable_action_horizon:
235
+ if action_lengths is None:
236
+ raise ValueError("Adaptive framework omitted action_lengths")
237
+ action_lengths = np.asarray(action_lengths, dtype=np.int64)
238
+ if action_lengths.shape != (normalized.shape[0],):
239
+ raise ValueError(
240
+ f"Adaptive action_lengths must have shape {(normalized.shape[0],)}, "
241
+ f"got {action_lengths.shape}"
242
+ )
243
+ if np.any(action_lengths < 1) or np.any(action_lengths > normalized.shape[1]):
244
+ raise ValueError("Adaptive action_lengths exceed the returned padded action tensor")
245
+
246
+ unnorm = np.stack(
247
+ [proc.unapply_actions(normalized[b]) for b in range(normalized.shape[0])],
248
+ axis=0,
249
+ )
250
+ if self._gripper_constraint is not None:
251
+ unnorm = self._gripper_constraint.apply(unnorm)
252
+ result = {"actions": unnorm}
253
+ if action_lengths is not None:
254
+ result["action_lengths"] = action_lengths
255
+ if "action_lengths_uncapped" in out:
256
+ result["action_lengths_uncapped"] = np.asarray(
257
+ out["action_lengths_uncapped"], dtype=np.int64
258
+ )
259
+ return result
260
+
261
+ def predict_action_realtime(
262
+ self,
263
+ examples: List[dict],
264
+ prev_action_chunk: np.ndarray,
265
+ inference_delay: int,
266
+ unnorm_key: Optional[str] = None,
267
+ **kwargs,
268
+ ) -> Dict[str, np.ndarray]:
269
+ """Run inference-time RTC and return actions in robot coordinates.
270
+
271
+ ``prev_action_chunk`` is intentionally accepted in the same robot
272
+ coordinates returned by :meth:`predict_action`. It is normalized via
273
+ the checkpoint's training transform before ΠGDM-guided flow sampling.
274
+ No simulated-delay training objective is used by this path.
275
+ """
276
+ if not self._supports_rtc:
277
+ raise RuntimeError(
278
+ f"Framework {type(self._framework).__name__} does not expose "
279
+ "predict_action_realtime"
280
+ )
281
+ if inference_delay <= 0:
282
+ raise ValueError("inference_delay must be positive for RTC")
283
+
284
+ effective_key = unnorm_key if unnorm_key is not None else self._default_unnorm_key
285
+ if effective_key is None:
286
+ if len(self._available_unnorm_keys) == 1:
287
+ effective_key = self._available_unnorm_keys[0]
288
+ else:
289
+ raise ValueError(
290
+ "predict_action_realtime: unnorm_key not specified; "
291
+ f"pass one of {self._available_unnorm_keys}"
292
+ )
293
+ proc = self._get_processor(effective_key)
294
+
295
+ previous = np.asarray(prev_action_chunk, dtype=np.float32)
296
+ if previous.ndim == 2:
297
+ previous = previous[None, ...]
298
+ if previous.ndim != 3:
299
+ raise ValueError(
300
+ "prev_action_chunk must have shape (T, D) or (B, T, D); "
301
+ f"got {previous.shape}"
302
+ )
303
+ if previous.shape[0] != len(examples):
304
+ raise ValueError(
305
+ f"Previous chunk batch {previous.shape[0]} does not match "
306
+ f"examples batch {len(examples)}"
307
+ )
308
+
309
+ normalized_previous = np.stack(
310
+ [proc.apply_actions(previous[b]) for b in range(previous.shape[0])],
311
+ axis=0,
312
+ )
313
+ out = self._framework.predict_action_realtime(
314
+ examples=examples,
315
+ prev_action_chunk_normalized=normalized_previous,
316
+ inference_delay=int(inference_delay),
317
+ **kwargs,
318
+ )
319
+ normalized = np.asarray(out["normalized_actions"])
320
+ unnorm = np.stack(
321
+ [proc.unapply_actions(normalized[b]) for b in range(normalized.shape[0])],
322
+ axis=0,
323
+ )
324
+ if self._gripper_constraint is not None:
325
+ unnorm = self._gripper_constraint.apply(unnorm)
326
+ return {"actions": unnorm}