Download scripts/hybrid_concurrent_server.py from ar-mine/e5-c3-code: direct link, hf CLI and curl.
- Browser
- Download file 16.5 kB
-
https://huggingface.co/datasets/ar-mine/e5-c3-code/resolve/main/scripts/hybrid_concurrent_server.py
- Command line
-
hf download hf://datasets/ar-mine/e5-c3-code/scripts/hybrid_concurrent_server.py
-
curl -L -o hybrid_concurrent_server.py https://huggingface.co/datasets/ar-mine/e5-c3-code/resolve/main/scripts/hybrid_concurrent_server.py
16.5 kB
| """Isolated hybrid_v1 sessions sharing one serial, FIFO inference executor. | |
| The unchanged loader's instance-level controlled_infer closes over its original | |
| policy. We deliberately rebind the class method for each independent wrapper, | |
| then reproduce that control context. Merely shallow-copying the wrapper would | |
| silently execute every session on the original object. | |
| """ | |
| import asyncio | |
| from concurrent.futures import ThreadPoolExecutor | |
| import copy | |
| import hashlib | |
| import os | |
| from pathlib import Path | |
| import random | |
| import threading | |
| import time | |
| import uuid | |
| import numpy as np | |
| from hybrid_transport import (HybridPolicyServer, InfrastructureError, Packer, | |
| PROTOCOL, ProtocolSession, append_record, | |
| infer_with_noise, unpackb) | |
| CONCURRENCY_PROTOCOL = 'hybrid_concurrency_v1' | |
| GEOMETRY_FIELDS = ('pos_embeds', 'position_embeddings', 'cu_seqlens', | |
| 'visual_split_sizes', 'visual_max_seqlen') | |
| def infer_fixed_robotwin(policy, observation, noise): | |
| """Retain the frozen single-observation geometry used by offline warmup.""" | |
| if not observation.get('reset'): | |
| if 'batch' in observation: | |
| raise InfrastructureError('Concurrent service does not support dynamic batching') | |
| for name in ('cam_high', 'cam_left_wrist', 'cam_right_wrist'): | |
| value = observation.get('observation.images.' + name) | |
| if (not isinstance(value, np.ndarray) or value.dtype != np.uint8 or | |
| value.shape != (240, 320, 3)): | |
| raise InfrastructureError('Expected three raw uint8 240x320 RGB images') | |
| return infer_with_noise(policy, observation, noise) | |
| class SessionRNG: | |
| """Global generators are switched only by the dedicated inference thread.""" | |
| def __init__(self, torch_module=None): | |
| self.torch = torch_module | |
| def capture(self): | |
| state = {'python': random.getstate(), 'numpy': np.random.get_state(), | |
| 'hash_seed': os.environ.get('PYTHONHASHSEED')} | |
| if self.torch is not None: | |
| state['torch'] = self.torch.get_rng_state().clone() | |
| state['cuda'] = [x.clone() for x in self.torch.cuda.get_rng_state_all()] | |
| return state | |
| def restore(self, state): | |
| random.setstate(state['python']) | |
| np.random.set_state(state['numpy']) | |
| if state['hash_seed'] is None: | |
| os.environ.pop('PYTHONHASHSEED', None) | |
| else: | |
| os.environ['PYTHONHASHSEED'] = state['hash_seed'] | |
| if self.torch is not None: | |
| self.torch.set_rng_state(state['torch']) | |
| self.torch.cuda.set_rng_state_all(state['cuda']) | |
| def clone_official_policy(original, torch_module=None): | |
| """Independent wrapper/transform/tokenizer state, shared parameter tensors. | |
| This audited adapter supports the frozen RoboTwin policy, batch=1, chunk_ret | |
| and no compilation. All copies and inference execute on the same thread. | |
| The neural model is shared; its per-call KV cache is local in sample_actions. | |
| The small persistent visual-geometry cache is separately switched below. | |
| """ | |
| if torch_module is None: | |
| import torch as torch_module | |
| if not original.chunk_ret or original.use_compile: | |
| raise InfrastructureError('Concurrency requires chunk_ret=True and compile=False') | |
| replica = copy.copy(original) | |
| shared = {'vla', 'sample_actions_fn', 'infer'} | |
| cleared = {'last_action_chunk', 'last_normalized_action_chunk'} | |
| for name, value in vars(original).items(): | |
| if name in cleared: | |
| setattr(replica, name, None) | |
| elif name not in shared: | |
| setattr(replica, name, copy.deepcopy(value)) | |
| replica.global_step = 0 | |
| # nn.Module shallow copies otherwise share these registration containers. | |
| replica.vla = copy.copy(original.vla) | |
| for name in ('_modules', '_buffers', '_parameters'): | |
| if hasattr(original.vla, name): | |
| setattr(replica.vla, name, dict(getattr(original.vla, name))) | |
| if hasattr(replica.vla, '_modules'): | |
| replica.vla._modules.pop('feature_transform', None) | |
| replica.vla.__dict__.pop('feature_transform', None) | |
| replica.vla.feature_transform = None | |
| # Keep the copied processor and tokenizer coherent; both are CPU objects. | |
| if hasattr(replica, 'processor'): | |
| replica.language_tokenizer = replica.processor.tokenizer | |
| if hasattr(replica.vla, 'config'): | |
| replica.vla.config = replica.config | |
| raw_infer = type(original).infer.__get__(replica, type(replica)) | |
| def controlled_infer(observation): | |
| if observation.get('reset'): | |
| from deploy.lingbot_vla_v2_policy import set_seed_everywhere | |
| set_seed_everywhere(int(observation.get('policy_seed', 42))) | |
| with torch_module.inference_mode(), torch_module.autocast('cuda', enabled=False): | |
| return raw_infer(observation) | |
| replica.infer = controlled_infer | |
| return replica | |
| class IsolatedSession: | |
| def __init__(self, original, noise_shape, synchronize, policy_factory, | |
| infer_adapter, rng): | |
| self.original = original | |
| self.synchronize = synchronize | |
| self.policy_factory = policy_factory | |
| self.infer_adapter = infer_adapter | |
| self.rng = rng | |
| self.rng_state = None | |
| self.policy = None | |
| self.geometry = None | |
| self.protocol = ProtocolSession(self.infer, noise_shape, synchronize) | |
| self.closed = threading.Event() | |
| self.connection_id = uuid.uuid4().hex | |
| def infer(self, observation, noise): | |
| return self.infer_adapter(self.policy, observation, noise) | |
| def process(self, request, digest, enqueued_at, fifo_index, pending): | |
| started = time.perf_counter() | |
| if self.closed.is_set(): | |
| raise InfrastructureError('Connection closed before queued request execution') | |
| queue_ms = (started - enqueued_at) * 1000 | |
| init_ms = 0.0 | |
| if self.policy is None: | |
| init_started = time.perf_counter() | |
| self.policy = self.policy_factory(self.original) | |
| init_ms = (time.perf_counter() - init_started) * 1000 | |
| switch_started = time.perf_counter() | |
| ambient_rng = self.rng.capture() | |
| if self.rng_state is not None: | |
| self.rng.restore(self.rng_state) | |
| # Precompute geometry is not episode history. Still save/restore it so | |
| # a reset or later cache allocation cannot affect another connection. | |
| model = getattr(getattr(self.policy, 'vla', None), 'model', None) | |
| geometry_owner = getattr(model, 'qwenvl_with_expert', None) | |
| original_geometry = None | |
| if geometry_owner is not None: | |
| original_geometry = {key: getattr(geometry_owner, key) | |
| for key in GEOMETRY_FIELDS} | |
| if self.geometry is None: | |
| self.geometry = dict(original_geometry) | |
| for key, value in self.geometry.items(): | |
| setattr(geometry_owner, key, value) | |
| switch_ms = (time.perf_counter() - switch_started) * 1000 | |
| try: | |
| # ProtocolSession performs identity/noise validation and measures | |
| # CUDA-synchronized inference, excluding queue and state switching. | |
| response, duplicate = self.protocol.process(request, digest) | |
| finally: | |
| switch_started = time.perf_counter() | |
| self.rng_state = self.rng.capture() | |
| self.rng.restore(ambient_rng) | |
| if geometry_owner is not None: | |
| self.geometry = {key: getattr(geometry_owner, key) | |
| for key in GEOMETRY_FIELDS} | |
| for key, value in original_geometry.items(): | |
| setattr(geometry_owner, key, value) | |
| switch_ms += (time.perf_counter() - switch_started) * 1000 | |
| # Preserve cached actions, while reporting the actual cost of this | |
| # delivery. A duplicate never executes infer or advances RNG/state. | |
| response = dict(response) | |
| if duplicate: | |
| response['server_cached_infer_ms'] = response['server_infer_ms'] | |
| response['server_infer_ms'] = 0.0 | |
| response.update(concurrency_protocol=CONCURRENCY_PROTOCOL, | |
| server_queue_ms=queue_ms, | |
| server_state_switch_ms=switch_ms, | |
| server_session_init_ms=init_ms, | |
| server_fifo_index=fifo_index, | |
| server_pending_at_enqueue=pending, | |
| server_execution_thread_id=threading.get_ident(), | |
| duplicate=duplicate) | |
| return response, duplicate | |
| def release(self): | |
| self.closed.set() | |
| if self.policy is not None: | |
| # Break controlled_infer -> bound method -> replica cycles now, | |
| # without waiting for GC to reclaim large CPU tokenizer copies. | |
| self.policy.__dict__.pop('infer', None) | |
| self.policy.last_action_chunk = None | |
| self.policy.last_normalized_action_chunk = None | |
| self.policy.vla.feature_transform = None | |
| self.policy = self.geometry = self.rng_state = None | |
| self.protocol.cache.clear() | |
| self.protocol.seen_sessions.clear() | |
| self.protocol.infer = None | |
| class ConcurrentHybridPolicyServer(HybridPolicyServer): | |
| def __init__(self, *args, max_clients=4, policy_factory=None, | |
| infer_adapter=None, rng=None, **kwargs): | |
| if type(max_clients) is not int or not 1 <= max_clients <= 8: | |
| raise ValueError('max_clients must be an integer between 1 and 8') | |
| super().__init__(*args, **kwargs) | |
| if self.log_path is not None: | |
| self.log_path = Path(self.log_path).resolve() | |
| self.max_clients = max_clients | |
| self.policy_factory = policy_factory or clone_official_policy | |
| self.infer_adapter = infer_adapter or infer_fixed_robotwin | |
| if rng is None: | |
| import torch | |
| rng = SessionRNG(torch) | |
| self.rng = rng | |
| self.executor = ThreadPoolExecutor(max_workers=1, | |
| thread_name_prefix='hybrid-policy-fifo') | |
| self.connections = set() | |
| self._fifo = self._pending = 0 | |
| self.metadata.update( | |
| concurrency_protocol=CONCURRENCY_PROTOCOL, | |
| max_clients=max_clients, | |
| scheduler='FIFO_single_inference_thread_no_batching', | |
| session_isolation='independent_policy_vla_facade_processor_transform_chunks_and_RNG', | |
| shared_weights=True, model_replicas=1, | |
| geometry_cache='session_switched_fixed_3x240x320_RGB_batch1', | |
| queue_timing='from_decoded_request_enqueue_to_executor_entry', | |
| inference_timing='ProtocolSession_CUDA_synchronized_excludes_queue_and_state_switch', | |
| duplicate_timing='cached_result_no_execution_server_infer_ms_zero') | |
| async def run(self): | |
| try: | |
| await super().run() | |
| finally: | |
| self.executor.shutdown(wait=True, cancel_futures=True) | |
| async def submit(self, session, request, digest): | |
| if session.closed.is_set(): | |
| raise InfrastructureError('Connection is closed') | |
| self._fifo += 1 | |
| self._pending += 1 | |
| enqueued_at = time.perf_counter() | |
| future = asyncio.get_running_loop().run_in_executor( | |
| self.executor, session.process, request, digest, enqueued_at, | |
| self._fifo, self._pending) | |
| try: | |
| # Handler cancellation must not release session state while CUDA | |
| # still uses it. Shield preserves completion of in-flight work. | |
| return await asyncio.shield(future) | |
| except asyncio.CancelledError: | |
| session.closed.set() | |
| # Multiple shutdown/cancellation signals still must not let a | |
| # handler release its replica while the worker is using it. | |
| while not future.done(): | |
| try: | |
| await asyncio.shield(future) | |
| except asyncio.CancelledError: | |
| continue | |
| except Exception: | |
| break | |
| if not future.cancelled(): | |
| future.exception() # consume a discarded worker exception | |
| raise | |
| finally: | |
| self._pending -= 1 | |
| async def _handler(self, websocket): | |
| from websockets.exceptions import ConnectionClosed | |
| if len(self.connections) >= self.max_clients: | |
| append_record(self.log_path, {'timestamp': time.time(), | |
| 'event': 'client_limit_rejected', 'max_clients': self.max_clients}) | |
| await websocket.close(code=1013, reason='Concurrent policy client limit reached') | |
| return | |
| session = IsolatedSession(self.policy, self.noise_shape, self.synchronize, | |
| self.policy_factory, self.infer_adapter, self.rng) | |
| self.connections.add(session) | |
| packer = Packer() | |
| disconnected = asyncio.create_task(websocket.wait_closed()) | |
| # Flag queued work immediately on disconnect. In-flight GPU execution | |
| # completes in the same worker; its response is then discarded. | |
| disconnected.add_done_callback(lambda _: session.closed.set()) | |
| append_record(self.log_path, {'timestamp': time.time(), 'event': 'client_connected', | |
| 'connection_id': session.connection_id, | |
| 'active_clients': len(self.connections)}) | |
| try: | |
| await websocket.send(packer.pack(self.metadata)) | |
| while True: | |
| raw = await websocket.recv() | |
| if not isinstance(raw, bytes): | |
| raise InfrastructureError('Expected a binary request') | |
| started = time.perf_counter() | |
| request = unpackb(raw) | |
| unpack_ms = (time.perf_counter() - started) * 1000 | |
| digest = hashlib.sha256(raw).hexdigest() | |
| response, duplicate = await self.submit(session, request, digest) | |
| started = time.perf_counter() | |
| payload = packer.pack(response) | |
| pack_ms = (time.perf_counter() - started) * 1000 | |
| started = time.perf_counter() | |
| if not session.closed.is_set(): | |
| await websocket.send(payload) | |
| send_ms = (time.perf_counter() - started) * 1000 | |
| append_record(self.log_path, { | |
| 'timestamp': time.time(), 'connection_id': session.connection_id, | |
| 'active_clients': len(self.connections), | |
| 'session_id': response['session_id'], | |
| 'episode_id': response['episode_id'], 'sequence_id': response['sequence_id'], | |
| 'operation': request['operation'], 'duplicate': duplicate, | |
| 'request_sha256': digest, 'noise_sha256': response['noise_sha256'], | |
| 'request_bytes': len(raw), 'response_bytes': len(payload), | |
| 'server_unpack_ms': unpack_ms, 'server_pack_ms': pack_ms, | |
| 'server_send_ms': send_ms, | |
| **{key: value for key, value in response.items() | |
| if key.startswith('server_') or key == 'concurrency_protocol'}, | |
| 'response_discarded_after_disconnect': session.closed.is_set()}) | |
| if session.closed.is_set(): | |
| break | |
| except ConnectionClosed: | |
| pass | |
| except Exception as error: | |
| append_record(self.log_path, {'timestamp': time.time(), | |
| 'connection_id': session.connection_id, | |
| 'event': 'infrastructure_error', 'error': str(error)}) | |
| try: | |
| if not session.closed.is_set(): | |
| await websocket.send(packer.pack({'protocol': PROTOCOL, 'error': str(error)})) | |
| await websocket.close(code=1011, reason='Episode invalidated') | |
| except ConnectionClosed: | |
| pass | |
| finally: | |
| disconnected.cancel() | |
| session.release() | |
| self.connections.discard(session) | |
| append_record(self.log_path, {'timestamp': time.time(), 'event': 'client_disconnected', | |
| 'connection_id': session.connection_id, | |
| 'active_clients': len(self.connections)}) | |