Download mlx_agent_tools/inference_window.py from ChengyiX/mlx-agent-tools: direct link, hf CLI and curl.
- Browser
- Download file 8.1 kB
-
https://huggingface.co/datasets/ChengyiX/mlx-agent-tools/resolve/main/mlx_agent_tools/inference_window.py
- Command line
-
hf download hf://datasets/ChengyiX/mlx-agent-tools/mlx_agent_tools/inference_window.py
-
curl -L -o inference_window.py https://huggingface.co/datasets/ChengyiX/mlx-agent-tools/resolve/main/mlx_agent_tools/inference_window.py
8.1 kB
| """Foreground owned engine window; controller lock held until prior restore.""" | |
| from pathlib import Path | |
| import argparse | |
| import json | |
| import os | |
| import signal | |
| import shlex | |
| import http.client | |
| import subprocess | |
| import sys | |
| import time | |
| ROOT = Path(__file__).resolve().parents[2] | |
| sys.path.insert(0, str(ROOT)) | |
| try: | |
| import stack_controller | |
| except ImportError: | |
| stack_controller = None | |
| def small_idle_llama(argv, *, query=None): | |
| """Permit only a verified <=2GiB, <=8k idle loopback native server. | |
| One-large-engine policy does not authorize stopping unrelated small apps. | |
| Any missing/unknown ownership, model or processing fact remains blocking. | |
| """ | |
| try: | |
| def option(*names): | |
| for name in names: | |
| if name in argv:return argv[argv.index(name)+1] | |
| return None | |
| weight = Path(option('-m', '--model')).resolve() | |
| host = option('--host') | |
| port = int(option('--port')) | |
| if host not in ('localhost', '127.0.0.1') or not 1 <= port <= 65535: | |
| return False | |
| if not weight.is_file() or weight.stat().st_size > 2 * 1024**3: | |
| return False | |
| def request(port, path): | |
| connection = http.client.HTTPConnection('127.0.0.1', port, timeout=2) | |
| try: | |
| connection.request('GET', path) | |
| response = connection.getresponse() | |
| if response.status != 200:return None | |
| return json.loads(response.read()) | |
| finally:connection.close() | |
| get = query or request | |
| props, slots = get(port, '/props'), get(port, '/slots') | |
| return bool(isinstance(props, dict) and Path(props.get('model_path', '')).resolve() == weight | |
| and isinstance(slots, list) and slots and all( | |
| isinstance(slot, dict) and slot.get('is_processing') is False | |
| and type(slot.get('n_ctx')) is int and 0 < slot['n_ctx'] <= 8192 | |
| for slot in slots)) | |
| except (OSError, ValueError, TypeError, IndexError, http.client.HTTPException): | |
| return False | |
| def external_accelerator_work(): | |
| """Conservative process-name guard; never reads/prints private task payloads.""" | |
| rows = subprocess.check_output(['ps', '-axo', 'pid=,command='], text=True) | |
| candidates = [] | |
| markers = {'encoder_experiment.py': 'encoder_training', | |
| 'image_tool.py --': 'image_generation', 'sd-server': 'image_backend', | |
| 'mlx_vlm server': 'mlx_server', 'mlx_dspark serve': 'mlx_server', | |
| 'llama-server': 'llama_server'} | |
| for row in rows.splitlines(): | |
| fields = row.strip().split(None, 1) | |
| if len(fields) != 2 or int(fields[0]) == os.getpid(): | |
| continue | |
| command = fields[1] | |
| # Parent shells can carry the worker command in their -c script; do not | |
| # mistake our own launch wrapper for an active GPU worker. | |
| if command.startswith(('/bin/bash ', '/bin/zsh ', '/usr/bin/bash ')): | |
| continue | |
| for marker, kind in markers.items(): | |
| if marker in command: | |
| if kind == 'llama_server' and small_idle_llama(shlex.split(command)): | |
| break | |
| candidates.append({'pid': int(fields[0]), 'kind': kind}) | |
| break | |
| return candidates | |
| def run_window(command, output, *, timeout=900, controller=stack_controller, | |
| external_work=None): | |
| output = Path(output) | |
| output.mkdir(parents=True, exist_ok=True) | |
| receipt = output / 'window.json' | |
| if receipt.exists(): | |
| raise ValueError('Window output already exists; preserve previous evidence') | |
| state = {'owner_pid': os.getpid(), 'started_at': time.time(), 'restored': False, | |
| 'authorization': 'operator resume after explicit temporary-pause notice', | |
| 'worker_returncode': None, 'timed_out': False} | |
| def save(): | |
| receipt.write_text(json.dumps(state, indent=2) + '\n') | |
| with controller.lock(): | |
| detector = external_work or (external_accelerator_work if controller is stack_controller else lambda: []) | |
| external = detector() | |
| state['external_accelerator_jobs'] = external | |
| if external: | |
| state['phase'] = 'blocked_before_unload' | |
| state['restored'] = True # No state was changed; prior service remains. | |
| save() | |
| raise RuntimeError('Another accelerator/GPU job is active; no backend unloaded') | |
| active = [profile for profile in controller.profiles().values() if controller.occupied(profile.port)] | |
| if len(active) > 1: | |
| raise RuntimeError('Multiple engines active; refusing ambiguous ownership') | |
| if controller.occupied(18800) or controller.occupied(18798): | |
| raise RuntimeError('Lab engine already active') | |
| previous = active[0] if active else None | |
| if previous: | |
| if previous.kind != 'text' or not controller.loaded(controller.label(previous)): | |
| raise RuntimeError('Current engine ownership is not verified') | |
| if not controller.text_snapshot_idle(controller.request_json(previous, '/status')): | |
| raise RuntimeError('Current engine busy or idle snapshot unknown') | |
| controller.validate_paths(previous) | |
| state['restore_profile'] = previous.key if previous else None | |
| save() | |
| process = None | |
| paused = False | |
| try: | |
| if previous: | |
| controller.stop_all() | |
| paused = True | |
| state['phase'] = 'worker' | |
| save() | |
| with (output / 'worker.log').open('wb') as log: | |
| process = subprocess.Popen(command, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, | |
| stdin=subprocess.DEVNULL, start_new_session=True) | |
| state['worker_pid'] = process.pid | |
| save() | |
| try: | |
| state['worker_returncode'] = process.wait(timeout=timeout) | |
| except subprocess.TimeoutExpired: | |
| state['timed_out'] = True | |
| os.killpg(process.pid, signal.SIGTERM) | |
| try: | |
| process.wait(timeout=20) | |
| except subprocess.TimeoutExpired: | |
| os.killpg(process.pid, signal.SIGKILL) | |
| process.wait() | |
| state['worker_returncode'] = process.returncode | |
| finally: | |
| if process is not None and process.poll() is None: | |
| os.killpg(process.pid, signal.SIGTERM) | |
| try: | |
| process.wait(timeout=20) | |
| except subprocess.TimeoutExpired: | |
| os.killpg(process.pid, signal.SIGKILL) | |
| process.wait() | |
| state['phase'] = 'restoring' | |
| try: | |
| save() | |
| finally: | |
| if paused: | |
| controller.start_locked(previous, quiet=True) | |
| state['restored'] = controller.status(previous)['api_ready'] | |
| else: | |
| state['restored'] = previous is None | |
| state['phase'] = 'finished' if state['restored'] else 'restore_failed' | |
| state['finished_at'] = time.time() | |
| save() | |
| if not state['restored']: | |
| raise RuntimeError('Prior service restoration failed; inspect window receipt') | |
| return state | |
| if __name__ == '__main__': | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('--output', type=Path, required=True) | |
| parser.add_argument('--timeout', type=float, default=900) | |
| parser.add_argument('command', nargs=argparse.REMAINDER) | |
| args = parser.parse_args() | |
| command = args.command[1:] if args.command[:1] == ['--'] else args.command | |
| if not command: | |
| parser.error('worker command required') | |
| result = run_window(command, args.output, timeout=args.timeout) | |
| print(json.dumps(result, indent=2)) | |
| raise SystemExit(0 if result['worker_returncode'] == 0 else 1) | |